Bobby commited on
Commit
df7e8d2
·
1 Parent(s): c0a4a6e

Support Blackwell ZeroGPU runtime

Browse files
Files changed (2) hide show
  1. app.py +125 -7
  2. requirements.txt +1 -2
app.py CHANGED
@@ -7,15 +7,21 @@ import inspect
7
  import importlib.util
8
  import json
9
  import os
 
10
  import sys
 
11
  import time
 
12
  from datetime import datetime
13
  from uuid import uuid4
14
  from typing import Any, Dict, Generator, List, Optional, Tuple
15
 
16
  os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
17
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
18
- if os.getenv("SPACE_ID"):
 
 
 
19
  _attn_backend = "sdpa"
20
  elif importlib.util.find_spec("flash_attn") is not None:
21
  _attn_backend = "flash_attn"
@@ -25,6 +31,7 @@ else:
25
  _attn_backend = "sdpa"
26
  os.environ.setdefault("ATTN_BACKEND", _attn_backend)
27
  os.environ.setdefault("SPARSE_ATTN_BACKEND", _attn_backend)
 
28
  os.environ.setdefault("SPCONV_ALGO", "native")
29
  os.environ["FLEX_GEMM_AUTOTUNE_CACHE_PATH"] = os.path.join(
30
  os.path.dirname(os.path.abspath(__file__)), "autotune_cache.json"
@@ -37,6 +44,123 @@ import gradio as gr
37
  import imageio
38
  import numpy as np
39
  import spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  import torch
41
  import trimesh
42
  from PIL import Image
@@ -51,11 +175,6 @@ from trellis.representations import Gaussian, MeshExtractResult
51
  from trellis.utils import postprocessing_utils as trellis_postprocessing_utils
52
  from trellis.utils import render_utils as trellis_render_utils
53
 
54
- import logging
55
-
56
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
57
- logger = logging.getLogger(__name__)
58
-
59
 
60
  def patch_starlette_template_response() -> None:
61
  """Support Gradio's older TemplateResponse call style on newer Starlette."""
@@ -110,7 +229,6 @@ cmd_args, _unknown_args = parser.parse_known_args()
110
  prod = cmd_args.prod
111
  port = cmd_args.port if cmd_args.port else (8081 if prod else 8080)
112
  show_options = not prod
113
- RUNNING_ON_SPACES = bool(os.getenv("SPACE_ID"))
114
  PUBLIC_BASE_URL = os.getenv("PUBLIC_BASE_URL", "").strip()
115
  if PUBLIC_BASE_URL and not PUBLIC_BASE_URL.startswith(("http://", "https://")):
116
  PUBLIC_BASE_URL = f"https://{PUBLIC_BASE_URL}"
 
7
  import importlib.util
8
  import json
9
  import os
10
+ import subprocess
11
  import sys
12
+ import tempfile
13
  import time
14
+ import ctypes
15
  from datetime import datetime
16
  from uuid import uuid4
17
  from typing import Any, Dict, Generator, List, Optional, Tuple
18
 
19
  os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
20
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
21
+ RUNNING_ON_SPACES = bool(os.getenv("SPACE_ID"))
22
+ if RUNNING_ON_SPACES and importlib.util.find_spec("xformers") is not None:
23
+ _attn_backend = "xformers"
24
+ elif os.getenv("SPACE_ID"):
25
  _attn_backend = "sdpa"
26
  elif importlib.util.find_spec("flash_attn") is not None:
27
  _attn_backend = "flash_attn"
 
31
  _attn_backend = "sdpa"
32
  os.environ.setdefault("ATTN_BACKEND", _attn_backend)
33
  os.environ.setdefault("SPARSE_ATTN_BACKEND", _attn_backend)
34
+ os.environ.setdefault("SPARSE_ATTN", _attn_backend)
35
  os.environ.setdefault("SPCONV_ALGO", "native")
36
  os.environ["FLEX_GEMM_AUTOTUNE_CACHE_PATH"] = os.path.join(
37
  os.path.dirname(os.path.abspath(__file__)), "autotune_cache.json"
 
44
  import imageio
45
  import numpy as np
46
  import spaces
47
+
48
+ import logging
49
+
50
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ CUDA_HOME = "/cuda-image/usr/local/cuda-13.0"
55
+ CUDA_LIBDIR = os.path.join(CUDA_HOME, "lib64")
56
+
57
+
58
+ @spaces.GPU(duration=600)
59
+ def prepare_blackwell_extensions() -> None:
60
+ missing_nvdiffrast = False
61
+ missing_diff_gaussian = False
62
+ try:
63
+ import nvdiffrast.torch # noqa: F401
64
+ except ImportError:
65
+ missing_nvdiffrast = True
66
+ try:
67
+ import diff_gaussian_rasterization # noqa: F401
68
+ except ImportError:
69
+ missing_diff_gaussian = True
70
+
71
+ if not (missing_nvdiffrast or missing_diff_gaussian):
72
+ return
73
+
74
+ if not os.path.exists(os.path.join(CUDA_HOME, "bin", "nvcc")):
75
+ raise RuntimeError(f"nvcc not found at {CUDA_HOME}/bin/nvcc on the ZeroGPU worker.")
76
+
77
+ patch_dir = tempfile.mkdtemp(prefix="torch_cuda_patch_")
78
+ patch_file = os.path.join(patch_dir, "sitecustomize.py")
79
+ with open(patch_file, "w") as file:
80
+ file.write(
81
+ "try:\n"
82
+ " import torch.utils.cpp_extension as _c\n"
83
+ " _c._check_cuda_version = lambda *a, **k: None\n"
84
+ "except Exception:\n"
85
+ " pass\n"
86
+ )
87
+
88
+ build_env = os.environ.copy()
89
+ build_env["CUDA_HOME"] = CUDA_HOME
90
+ build_env["CUDA_PATH"] = CUDA_HOME
91
+ build_env["PATH"] = os.path.join(CUDA_HOME, "bin") + os.pathsep + build_env.get("PATH", "")
92
+ build_env["PYTHONPATH"] = patch_dir + os.pathsep + build_env.get("PYTHONPATH", "")
93
+ build_env["TORCH_CUDA_ARCH_LIST"] = "12.0"
94
+
95
+ subprocess.check_call(
96
+ [sys.executable, "-m", "pip", "install", "--no-deps", "setuptools", "wheel", "ninja"]
97
+ )
98
+
99
+ if missing_nvdiffrast:
100
+ nvdiffrast_dir = tempfile.mkdtemp(prefix="nvdiffrast_")
101
+ subprocess.check_call(
102
+ [
103
+ "git",
104
+ "clone",
105
+ "--branch",
106
+ "v0.3.3",
107
+ "--depth=1",
108
+ "https://github.com/NVlabs/nvdiffrast.git",
109
+ nvdiffrast_dir,
110
+ ]
111
+ )
112
+ subprocess.check_call(
113
+ [sys.executable, "-m", "pip", "install", "--no-build-isolation", nvdiffrast_dir],
114
+ env=build_env,
115
+ )
116
+
117
+ if missing_diff_gaussian:
118
+ mip_splatting_dir = tempfile.mkdtemp(prefix="mip_splatting_")
119
+ subprocess.check_call(
120
+ [
121
+ "git",
122
+ "clone",
123
+ "--recursive",
124
+ "--depth=1",
125
+ "https://github.com/autonomousvision/mip-splatting.git",
126
+ mip_splatting_dir,
127
+ ]
128
+ )
129
+ subprocess.check_call(
130
+ [
131
+ sys.executable,
132
+ "-m",
133
+ "pip",
134
+ "install",
135
+ "--no-build-isolation",
136
+ os.path.join(mip_splatting_dir, "submodules", "diff-gaussian-rasterization"),
137
+ ],
138
+ env=build_env,
139
+ )
140
+
141
+
142
+ if RUNNING_ON_SPACES:
143
+ prepare_blackwell_extensions()
144
+ ctypes.CDLL(os.path.join(CUDA_LIBDIR, "libcudart.so.13"), mode=ctypes.RTLD_GLOBAL)
145
+ os.environ["LD_LIBRARY_PATH"] = CUDA_LIBDIR + os.pathsep + os.environ.get("LD_LIBRARY_PATH", "")
146
+
147
+
148
+ if RUNNING_ON_SPACES and _attn_backend == "xformers":
149
+ import xformers.ops as _xformers_ops
150
+
151
+ _original_memory_efficient_attention = _xformers_ops.memory_efficient_attention
152
+ _cutlass_attention_ops = (
153
+ _xformers_ops.fmha.cutlass.FwOp,
154
+ _xformers_ops.fmha.cutlass.BwOp,
155
+ )
156
+
157
+ def memory_efficient_attention_with_cutlass(*args, **kwargs):
158
+ kwargs.setdefault("op", _cutlass_attention_ops)
159
+ return _original_memory_efficient_attention(*args, **kwargs)
160
+
161
+ _xformers_ops.memory_efficient_attention = memory_efficient_attention_with_cutlass
162
+
163
+
164
  import torch
165
  import trimesh
166
  from PIL import Image
 
175
  from trellis.utils import postprocessing_utils as trellis_postprocessing_utils
176
  from trellis.utils import render_utils as trellis_render_utils
177
 
 
 
 
 
 
178
 
179
  def patch_starlette_template_response() -> None:
180
  """Support Gradio's older TemplateResponse call style on newer Starlette."""
 
229
  prod = cmd_args.prod
230
  port = cmd_args.port if cmd_args.port else (8081 if prod else 8080)
231
  show_options = not prod
 
232
  PUBLIC_BASE_URL = os.getenv("PUBLIC_BASE_URL", "").strip()
233
  if PUBLIC_BASE_URL and not PUBLIC_BASE_URL.startswith(("http://", "https://")):
234
  PUBLIC_BASE_URL = f"https://{PUBLIC_BASE_URL}"
requirements.txt CHANGED
@@ -17,15 +17,14 @@ zstandard==0.25.0
17
  kornia==0.8.2
18
  timm==1.0.22
19
  pydantic==2.10.6
 
20
 
21
  gradio_litmodel3d==0.0.1
22
  git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
23
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/cumesh-latest/cumesh-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_35_x86_64.whl
24
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/flex_gemm-latest/flex_gemm-1.0.0%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
25
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/o_voxel-latest/o_voxel-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
26
- https://github.com/PozzettiAndrea/cuda-wheels/releases/download/nvdiffrast-latest/nvdiffrast-0.4.0%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
27
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/nvdiffrec_render-latest/nvdiffrec_render-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
28
- https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt28-cu128-cp310/diff_gaussian_rasterization-0.0.0-cp310-cp310-linux_x86_64.whl
29
 
30
  spconv-cu120==2.3.6
31
  xatlas==0.0.9
 
17
  kornia==0.8.2
18
  timm==1.0.22
19
  pydantic==2.10.6
20
+ xformers
21
 
22
  gradio_litmodel3d==0.0.1
23
  git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8
24
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/cumesh-latest/cumesh-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_35_x86_64.whl
25
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/flex_gemm-latest/flex_gemm-1.0.0%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
26
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/o_voxel-latest/o_voxel-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
 
27
  https://github.com/PozzettiAndrea/cuda-wheels/releases/download/nvdiffrec_render-latest/nvdiffrec_render-0.0.1%2Bcu128torch2.8-cp310-cp310-manylinux_2_34_x86_64.manylinux_2_35_x86_64.whl
 
28
 
29
  spconv-cu120==2.3.6
30
  xatlas==0.0.9