import os import sys import subprocess # --------------------------------------------------------------------------- # Blackwell ZeroGPU shim — env + heavy CUDA-extension build # --------------------------------------------------------------------------- # pytorch3d publishes prebuilt wheels only for torch <= 2.4. On the new # Blackwell ZeroGPU stack (torch 2.10/2.11, CUDA 13) the old offline-install # block in this file simply fails. Build pytorch3d from source the first time # we get a GPU, the same way the Blackwell playbook recommends for # nvdiffrast / diff_gaussian_rasterization. import spaces # MUST come before torch / CUDA-touching imports import torch # torch.load weights_only flipped in 2.6 — old ckpts (DUSt3R/dynamicrafter) use # argparse Namespaces / numpy scalars that the new default refuses to unpickle. _orig_torch_load = torch.load def _patched_torch_load(*args, **kwargs): kwargs.setdefault("weights_only", False) return _orig_torch_load(*args, **kwargs) torch.load = _patched_torch_load # xformers on the Blackwell ZeroGPU wheel ships without CUDA-built ops for # sm_120: FA3 needs cap <= 9.0, Cutlass needs cap <= 9.0 too. Every op raises # `NotImplementedError`. Replace `xformers.ops.memory_efficient_attention` with # a torch-native SDPA equivalent so existing call-sites keep working. def _mea_sdpa(q, k, v, attn_bias=None, p=0.0, scale=None, op=None): # xformers convention: q/k/v shaped (B, M, H, K) or (B*H, M, K). # The lvdm code path passes 3D (B*H, M, K). Convert to (B*H, 1, M, K) # for F.scaled_dot_product_attention. import torch.nn.functional as F is_3d = (q.ndim == 3) if is_3d: q = q.unsqueeze(1); k = k.unsqueeze(1); v = v.unsqueeze(1) elif q.ndim == 4: # (B, M, H, K) -> (B, H, M, K) q = q.transpose(1, 2); k = k.transpose(1, 2); v = v.transpose(1, 2) mask = None if attn_bias is not None and hasattr(attn_bias, "to_tensor"): mask = attn_bias.to_tensor() elif attn_bias is not None and torch.is_tensor(attn_bias): mask = attn_bias out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=p, scale=scale) if is_3d: out = out.squeeze(1) else: out = out.transpose(1, 2) return out try: import xformers.ops as _xops # noqa: E402 _xops.memory_efficient_attention = _mea_sdpa except Exception as _e: print(f"[xformers shim] could not patch xformers.ops: {_e}") CUDA_HOME = "/cuda-image/usr/local/cuda-13.0" @spaces.GPU(duration=600) def _first_gpu_setup(): """Build pytorch3d from source against the live torch on first GPU acquire.""" try: import pytorch3d # noqa: F401 return except ImportError: pass import tempfile patch_dir = tempfile.mkdtemp(prefix="torch_cuda_patch_") with open(os.path.join(patch_dir, "sitecustomize.py"), "w") as f: f.write( "try:\n" " import torch.utils.cpp_extension as _c\n" " _c._check_cuda_version = lambda *a, **k: None\n" "except Exception:\n" " pass\n" ) env = os.environ.copy() env["CUDA_HOME"] = CUDA_HOME env["CUDA_PATH"] = CUDA_HOME env["PATH"] = os.path.join(CUDA_HOME, "bin") + os.pathsep + env.get("PATH", "") env["PYTHONPATH"] = patch_dir + os.pathsep + env.get("PYTHONPATH", "") env["TORCH_CUDA_ARCH_LIST"] = "12.0" env["FORCE_CUDA"] = "1" # CUDA 13 changed default symbol visibility; pytorch3d's pulsar renderer # needs the old behaviour or it fails to link with "undefined reference". # https://github.com/facebookresearch/pytorch3d/issues/2011 env["NVCC_FLAGS"] = "-static-global-template-stub=false" subprocess.check_call( [sys.executable, "-m", "pip", "install", "--no-deps", "setuptools", "wheel", "ninja", "packaging"], ) subprocess.check_call( [sys.executable, "-m", "pip", "install", "--no-build-isolation", "--no-deps", "git+https://github.com/facebookresearch/pytorch3d.git@stable"], env=env, ) # Pre-download the DUSt3R checkpoint at module scope (CPU-only). Using # hf_hub_download lets us avoid a fresh wget every boot. from huggingface_hub import hf_hub_download os.makedirs("./checkpoints/", exist_ok=True) if not os.path.exists("./checkpoints/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth"): try: hf_hub_download( repo_id="naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt", filename="DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth", local_dir="./checkpoints/", ) except Exception as _e: print(f"[dust3r hf_hub_download fallback to wget] {_e}") subprocess.check_call([ "wget", "-q", "-c", "https://download.europe.naverlabs.com/ComputerVision/DUSt3R/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth", "-P", "checkpoints/", ]) # --------------------------------------------------------------------------- # Original app # --------------------------------------------------------------------------- import random import gradio as gr from configs.infer_config import get_parser # Build pytorch3d before any module-scope code tries to import it. We need a # GPU here because pytorch3d's CUDA kernels link against the CUDA runtime # headers — run inside @spaces.GPU. _first_gpu_setup() traj_examples = [ ['0 -35; 0 0; 0 -0.1'], ['0 -3 -15 -20 -17 -5 0; 0 -2 -5 -10 -8 -5 0 2 5 3 0; 0 0'], ['0 3 10 20 17 10 0; 0 -2 -8 -6 0 2 5 3 0; 0 -0.02 -0.09 -0.16 -0.09 0'], ['0 30; 0 -1 -5 -4 0 1 5 4 0; 0 -0.2'], ] img_examples = [ ['test/images/boy.png',0,1], ['test/images/car.jpeg',5,1], ['test/images/fruit.jpg',5,1], ['test/images/room.png',10,1], ['test/images/castle.png',-4,1], ] max_seed = 2 ** 31 def download_model(): REPO_ID = 'Drexubery/ViewCrafter_25' filename_list = ['model.ckpt'] for filename in filename_list: local_file = os.path.join('./checkpoints/', filename) if not os.path.exists(local_file): hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/', force_download=True) download_model() parser = get_parser() opts = parser.parse_args() tmp = str(random.randint(10**(5-1), 10**5 - 1)) opts.save_dir = f'./{tmp}' os.makedirs(opts.save_dir, exist_ok=True) opts.device = "cuda" if torch.cuda.is_available() else "cpu" opts.config = './configs/inference_pvd_1024_gradio.yaml' from viewcrafter import ViewCrafter CAMERA_MOTION_MODE = ["Basic Camera Trajectory", "Custom Camera Trajectory"] def show_traj(mode): if mode == 'Left': return gr.update(value='0 -35; 0 0; 0 0',visible=True),gr.update(visible=False) elif mode == 'Right': return gr.update(value='0 35; 0 0; 0 0',visible=True),gr.update(visible=False) elif mode == 'Up': return gr.update(value='0 0; 0 -30; 0 0',visible=True),gr.update(visible=False) elif mode == 'Down': return gr.update(value='0 0; 0 20; 0 0',visible=True), gr.update(visible=False) elif mode == 'Zoom in': return gr.update(value='0 0; 0 0; 0 -0.4',visible=True), gr.update(visible=False) elif mode == 'Zoom out': return gr.update(value='0 0; 0 0; 0 0.4',visible=True), gr.update(visible=False) elif mode == 'Customize': return gr.update(value='0 0; 0 0; 0 0',visible=True), gr.update(visible=True) elif mode == 'Reset': return gr.update(value='0 0; 0 0; 0 0',visible=False), gr.update(visible=False) def viewcrafter_demo(opts): css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height:576px} #random_button {max-width: 100px !important}""" image2video = ViewCrafter(opts, gradio = True) image2video.run_both = spaces.GPU(image2video.run_both, duration=290) with gr.Blocks(analytics_enabled=False, css=css) as viewcrafter_iface: gr.Markdown("