Spaces:
Running on Zero
Running on Zero
Restore working pipeline; VGGT-Omega pointmaps (reference default) + in-scene orbit video
Browse filesFiles changed (8)
- .gitattributes-1
- LICENSE_4DAnythingDeleted-21
- README.md+22-34
- anything4d/render/gaussians.py+8-47
- app.py+322-341
- examples/dog.mp4Deleted-3
- examples/horse.mp4+2-2
- requirements.txt+29-25
35 unmodified lines3637383935 unmodified linesexamples/cat.mp4 filter=lfs diff=lfs merge=lfs -textexamples/horse.mp4 filter=lfs diff=lfs merge=lfs -textexamples/kangaroo.mp4 filter=lfs diff=lfs merge=lfs -textexamples/dog.mp4 filter=lfs diff=lfs merge=lfs -text35 unmodified lines36373835 unmodified linesexamples/cat.mp4 filter=lfs diff=lfs merge=lfs -textexamples/horse.mp4 filter=lfs diff=lfs merge=lfs -textexamples/kangaroo.mp4 filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021MIT License
Copyright (c) 2026 The 4DAnything Authors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354554 unmodified linescolorTo: indigosdk: gradiosdk_version: 6.33.0python_version: "3.12"app_file: app.pypinned: falselicense: othershort_description: Feed-forward 4D Gaussian reconstruction from a videostartup_duration_timeout: 1hmodels:- ncc2/4DAnything- facebook/sam-3d-objects- facebook/VGGT-Omega- facebook/sam2.1-hiera-large- IDEA-Research/grounding-dino-basetags:- 4d-reconstruction- gaussian-splatting- video-to-4d---# 4DAnythingGradio demo of [4DAnything: Generalizable Feed-Forward 4D Reconstruction In-The-Wild](https://4danything.github.io/)([code](https://github.com/nathalie000/4DAnything), [weights](https://huggingface.co/ncc2/4DAnything)).Upload a video of a moving object; the Space runs the authors' three stages in one call:1. **precompute**: the object is picked by BiRefNet (most salient object on the middle frame) or by aGrounding-DINO text prompt, tracked through the clip with SAM 2.1, and VGGT-Omega predicts pointmapsand cameras for the whole clip;2. **4DAnything**: the video backbone (fine-tuned from SAM 3D Objects) predicts shape, per-frame layout andstructured latents for the whole clip in one pass, and the 4D decoder turns them into canonical GaussiansG* plus a deformation per frame;3. **visualize**: renders of the result from the input camera, from four views, and placed in the scene.## Differences from the reference implementation* Rendering uses the Inria `diff_gaussian_rasterization` rasterizer instead of `gsplat`, which has noBlackwell (sm_120) build. Same pinhole cameras and the same videos; expected depth for occlusion culling iscomputed as a depth-weighted render divided by alpha.* Clips are capped at 32 frames (default: 24 frames, stride 2) to fit a ZeroGPU call.* The multi-view video uses 384 px tiles (upstream default) and all models are cached between calls.## Licenses and creditsThe 4DAnything weights derive from SAM 3D Objects and are under the SAM License; VGGT-Omega is under theFAIR Noncommercial Research License. The 4DAnything code is MIT (`LICENSE_4DAnything`), and`third_party/sam-3d-objects` is vendored from facebookresearch/sam-3d-objects at the commit pinned by 4DAnything.The kangaroo example is from the 4DAnything repository; the horse and dog clips are from[linoyts/repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434 unmodified linescolorTo: indigosdk: gradiosdk_version: 6.33.0app_file: app.pyshort_description: Feed-forward 4D Gaussian reconstruction from a videopython_version: "3.12"startup_duration_timeout: 1hlicense: othermodels:- ncc2/4DAnything- facebook/sam-3d-objects- facebook/sam2.1-hiera-large- IDEA-Research/grounding-dino-base- facebook/VGGT-Omega---# 4DAnythingDemo of **4DAnything: Generalizable Feed-Forward 4D Reconstruction In-The-Wild**([project page](https://4danything.github.io/), [code](https://github.com/nathalie000/4DAnything),[weights](https://huggingface.co/ncc2/4DAnything)).Pipeline (as in the official `inference/precompute.py → infer.py → visualize.py`):SAM 2.1 video masks (object picked by BiRefNet saliency or Grounding-DINO text) → VGGT-Omega pointmaps and camerasfor the whole clip (the reference default) →4DAnything video backbone (fine-tuned SAM 3D Objects) → 4D decoder (canonical Gaussians + per-frame deformation) → renders.Defaults: 16 frames at stride 3 (≈2.5–3 min of ZeroGPU time); up to 24 frames in Advanced settings.Outputs: the input-camera render/overlay, the orbit of the object placed in the VGGT-Omega scene, the multi-viewvideo (canonical G* and deformed object per frame) and the canonical Gaussians (.ply).Rendering uses the Inria `diff_gaussian_rasterization` kernels through a small `gsplat.rasterization` shim(`gsplat/`), since gsplat has no prebuilt wheel for the ZeroGPU torch/Blackwell stack.Licenses: 4DAnything code MIT; 4DAnything and SAM 3D Objects weights under the SAM License; VGGT-Omega weights under theFAIR Noncommercial Research License.Examples: `kangaroo.mp4` from the 4DAnything repository (MIT); `horse.mp4` and `cat.mp4` are trimmed from CC0 clips in[linoyts/repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).
42 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979842 unmodified linesreturn M# World units are scaled by this factor before rasterizing: the Inria rasterizer culls splats closer than# z=0.2, gsplat (used upstream) uses 0.01. A uniform scale of scene + camera leaves the image unchanged._UNIT = 20.0def _rasterize(xyz, quat, scale, opacity, colors, w2c, K, W, H, bg):"""Inria 3DGS rasterizer with a pinhole K (principal point anywhere) and OpenCV w2c; returns (3,H,W)."""import mathfrom diff_gaussian_rasterization import GaussianRasterizationSettings, GaussianRasterizerdev = xyz.devicefx, fy, cx, cy = float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2])znear, zfar = 0.01, 1000.0P = torch.zeros(4, 4, dtype=torch.float32, device=dev)P[0, 0] = 2 * fx / W; P[0, 2] = 2 * cx / W - 1P[1, 1] = 2 * fy / H; P[1, 2] = 2 * cy / H - 1P[2, 2] = zfar / (zfar - znear); P[2, 3] = -zfar * znear / (zfar - znear); P[3, 2] = 1.0V = w2c.clone(); V[:3, 3] *= _UNITfull = P @ Vsettings = GaussianRasterizationSettings(image_height=int(H), image_width=int(W), tanfovx=W / (2 * fx), tanfovy=H / (2 * fy),bg=bg, scale_modifier=1.0, viewmatrix=V.transpose(0, 1).contiguous(),projmatrix=full.transpose(0, 1).contiguous(), sh_degree=0,campos=torch.linalg.inv(V)[:3, 3].contiguous(), prefiltered=False, debug=False)means = (xyz * _UNIT).contiguous()img, _ = GaussianRasterizer(raster_settings=settings)(means3D=means, means2D=torch.zeros_like(means), shs=None, colors_precomp=colors.contiguous(),opacities=opacity.reshape(-1, 1).contiguous(), scales=(scale * _UNIT).contiguous(),rotations=quat.contiguous(), cov3D_precomp=None)return imgdef render(g, w2c, K, W, H, bg=(1.0, 1.0, 1.0), mode="RGB", with_alpha=False):"""Render one Gaussian set: uint8 HxWx3 (plus float HxW alpha if with_alpha), or (depth, alpha) tensors for ED.Same interface as the upstream gsplat version; implemented with the Inria rasterizer (gsplat has no sm_120 build)."""T = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float32, device="cuda")xyz, quat, scale, opa = T(g["xyz"]), T(g["quat"]), T(g["scale"]), T(g["opacity"])quat = quat / quat.norm(dim=-1, keepdim=True).clamp_min(1e-12)V, Kt = T(w2c), T(K)zero = torch.zeros(3, dtype=torch.float32, device="cuda")need_alpha = with_alpha or mode != "RGB"alpha = Noneif need_alpha:alpha = _rasterize(xyz, quat, scale, opa, torch.ones_like(xyz), V, Kt, W, H, zero)[0].clamp(0, 1)if mode != "RGB":z = xyz @ V[2, :3] + V[2, 3]acc = _rasterize(xyz, quat, scale, opa, z[:, None].expand(-1, 3).contiguous(), V, Kt, W, H, zero)[0]return acc / alpha.clamp_min(1e-6), alphaout = _rasterize(xyz, quat, scale, opa, T(g["rgb"]), V, Kt, W, H, T(bg))img = (out.permute(1, 2, 0).clamp(0, 1).cpu().numpy() * 255).astype(np.uint8)return (img, alpha.cpu().numpy()) if with_alpha else imgdef intrinsics(W, H, fov_deg=40.0):42 unmodified lines434445464748495051525354555657585942 unmodified linesreturn Mdef render(g, w2c, K, W, H, bg=(1.0, 1.0, 1.0), mode="RGB", with_alpha=False):"""gsplat render of one Gaussian set: uint8 HxWx3 (plus float HxW alpha if with_alpha), or (depth, alpha) tensors for ED."""from gsplat import rasterizationT = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float32, device="cuda")out, alpha, _ = rasterization(T(g["xyz"]), T(g["quat"]), T(g["scale"]), T(g["opacity"]), T(g["rgb"]),T(w2c)[None], T(K)[None], W, H, backgrounds=T(bg)[None] if mode == "RGB" else None,render_mode=mode, packed=False)if mode != "RGB":return out[0, ..., 0], alpha[0, ..., 0]img = (out[0].clamp(0, 1).cpu().numpy() * 255).astype(np.uint8)return (img, alpha[0, ..., 0].cpu().numpy()) if with_alpha else imgdef intrinsics(W, H, fov_deg=40.0):
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921939 unmodified lines2032042052062072082092102112122132147 unmodified lines22222322422522622712 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862877 unmodified lines295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""4DAnything: feed-forward 4D reconstruction of an object from a casual monocular video.Runs the reference pipeline of https://github.com/nathalie000/4DAnything end to end:1. precompute -- object masks (BiRefNet salient box or Grounding-DINO prompt -> SAM 2.1 video tracking),pointmaps + cameras (VGGT-Omega over the whole clip)2. infer -- 4DAnything video backbone (SS + SLat flow, fine-tuned from SAM 3D Objects) over the wholeclip in one pass, then the 4D decoder: canonical Gaussians G* + per-frame deformation3. visualize -- input-camera view, multi-view turntable, and the object placed in the reconstructed scene"""import osimport subprocessimport sysos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")os.environ["LIDRA_SKIP_INIT"] = "1"os.environ["ATTN_BACKEND"] = "xformers" # upstream default (anything4d/external/sam3d.py)os.environ["SPARSE_ATTN_BACKEND"] = "xformers"os.environ["SPARSE_BACKEND"] = "spconv"os.environ["SPCONV_ALGO"] = "native"os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")import spaces # noqa: E402 (must precede torch)def _pip(*args):r = subprocess.run([sys.executable, "-m", "pip", "install", "--no-cache-dir", *args],capture_output=True, text=True, timeout=1800)print(f" pip {'OK' if r.returncode == 0 else 'FAIL'}: {args[-1][:90]}", flush=True)if r.returncode != 0:print(r.stderr[-1500:], flush=True)print("=== runtime installs (--no-deps, so they cannot touch the torch stack) ===", flush=True)# utils3d / MoGe: geometry helpers imported by sam3d_objects.pipeline.utils.pointmap_pip("--no-deps", "git+https://github.com/EasternJournalist/utils3d.git@3913c65d81e05e47b9f367250cf8c0f7462a0900")_pip("--no-deps", "git+https://github.com/microsoft/MoGe.git@a8c37341bc0325ca99b9d57981cc3bb2bd3e255b")# gsplat: only imported (module scope) by sam3d's gaussian_render; rendering here uses the Inria rasterizer_pip("--no-deps", "gsplat==1.5.3")# VGGT-Omega at the commit pinned by 4DAnything (its numpy<2 pin would otherwise downgrade numpy)_pip("--no-deps", "git+https://github.com/facebookresearch/vggt-omega.git@48b23c8ce72c9a8fcf987f0d7f43d8e4870759f6")import json # noqa: E402import shutil # noqa: E402import tempfile # noqa: E402import time # noqa: E402import uuid # noqa: E402import zipfile # noqa: E402from pathlib import Path # noqa: E402import gradio as gr # noqa: E402import numpy as np # noqa: E402import torch # noqa: E402from huggingface_hub import hf_hub_download, snapshot_download # noqa: E402from PIL import Image # noqa: E402APP = Path(__file__).parent.resolve()sys.path.insert(0, str(APP))import anything4d # noqa: E402,F401 (puts third_party/sam-3d-objects on sys.path, kaolin stand-in)from anything4d.io.video_input import load_frames # noqa: E402TOKEN = os.environ.get("HF_TOKEN")# ----------------------------------------------------------------------------------------------# weights (downloaded at startup, never inside a GPU call)# ----------------------------------------------------------------------------------------------print("=== downloading weights ===", flush=True)SAM3D = Path(snapshot_download("facebook/sam-3d-objects", token=TOKEN, allow_patterns=["checkpoints/*.yaml", "checkpoints/ss_generator.ckpt", "checkpoints/slat_generator.ckpt","checkpoints/ss_decoder.ckpt", "checkpoints/slat_decoder_gs.ckpt", "checkpoints/slat_decoder_gs_4.ckpt","checkpoints/slat_decoder_mesh.ckpt"])) / "checkpoints"A4D = Path(snapshot_download("ncc2/4DAnything", allow_patterns=["ss.pt", "slat.pt", "decoder.pt"]))OMEGA_CKPT = hf_hub_download("facebook/VGGT-Omega", "vggt_omega_1b_512.pt", token=TOKEN)# object-scale workspace (scripts/download_checkpoints.sh): same weights, `use_scene_scale: false`WS = Path("/tmp/a4d_ckpt/sam3d_objscale")if not (WS / "pipeline.yaml").exists():WS.mkdir(parents=True, exist_ok=True)for f in SAM3D.iterdir():if f.name != "pipeline.yaml" and not (WS / f.name).exists():os.symlink(f.resolve(), WS / f.name)txt = (SAM3D / "pipeline.yaml").read_text().replace("use_scene_scale: true", "use_scene_scale: false")assert "use_scene_scale: false" in txt(WS / "pipeline.yaml").write_text(txt)# DINOv2 (SAM 3D condition embedders load it through torch.hub): cache code + weights nowtorch.hub.load("facebookresearch/dinov2", "dinov2_vitl14_reg", verbose=False)# ----------------------------------------------------------------------------------------------# precompute models (plain nn.Modules -> module scope, on cuda)# ----------------------------------------------------------------------------------------------from transformers import (AutoModelForZeroShotObjectDetection, AutoProcessor, # noqa: E402Sam2VideoModel, Sam2VideoProcessor)from vggt_omega.models import VGGTOmega # noqa: E402DINO_ID = "IDEA-Research/grounding-dino-base"SAM2_ID = "facebook/sam2.1-hiera-large"print("=== loading precompute models ===", flush=True)OMEGA = VGGTOmega()OMEGA.load_state_dict(torch.load(OMEGA_CKPT, map_location="cpu"))OMEGA = OMEGA.to("cuda").eval()SAM2 = Sam2VideoModel.from_pretrained(SAM2_ID).to("cuda", dtype=torch.bfloat16).eval()SAM2_PROC = Sam2VideoProcessor.from_pretrained(SAM2_ID)GDINO = AutoModelForZeroShotObjectDetection.from_pretrained(DINO_ID).to("cuda").eval()GDINO_PROC = AutoProcessor.from_pretrained(DINO_ID)# BiRefNet (rembg "birefnet-general", as upstream) runs on CPU before the GPU callfrom rembg import new_session, remove # noqa: E402REMBG = new_session("birefnet-general")# The SAM 3D-based 4DAnything pipeline must be built with a real GPU attached (its constructors mix devices),# so it is built on the first call inside the GPU worker and cached there._PIPE = None_DECODER = Nonedef _backbone_cfg(name):c = json.load(open(APP / "anything4d" / "configs" / f"backbone_{name}.json"))gen = "ss_generator" if name == "ss" else "slat_generator"c["model"]["base_yaml"] = str(SAM3D / f"{gen}.yaml")c["model"]["warm_start_ckpt"] = str(SAM3D / f"{gen}.ckpt")return c["model"]def _get_pipeline():"""anything4d.pipeline.reconstruct.run_backbone / run_decoder, built once per GPU worker."""global _PIPE, _DECODERif _PIPE is None:import sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.full_attn # noqa: F401from anything4d.pipeline.video_to_4d import VideoTo4DPipeline_PIPE = VideoTo4DPipeline.from_pretrained(workspace_dir=str(WS), ss_model_cfg=_backbone_cfg("ss"), slat_model_cfg=_backbone_cfg("slat"),ss_ckpt=str(A4D / "ss.pt"), slat_ckpt=str(A4D / "slat.pt"), use_pointmap=True, device="cuda",shared_noise="all")if _DECODER is None:from hydra.utils import instantiatefrom omegaconf import OmegaConffrom anything4d.model.decoder4d import build_decoderstem = str(WS / "slat_decoder_gs")cfg = OmegaConf.load(f"{stem}.yaml"); cfg.pop("pretrained_ckpt_path", None)base = instantiate(cfg)base.load_state_dict(torch.load(f"{stem}.ckpt", map_location="cpu", weights_only=True), strict=True)st = torch.load(str(A4D / "decoder.pt"), map_location="cpu", weights_only=False)model = build_decoder(base, st.get("args")).cuda().float().eval()model.load_state_dict({k: v for k, v in st["model"].items() if not k.startswith("frozen.")}, strict=True)_DECODER = modelreturn _PIPE, _DECODER# ----------------------------------------------------------------------------------------------# stage 1: precompute (anything4d/pipeline/precompute.py with cached models)# ----------------------------------------------------------------------------------------------def salient_box(im):"""anything4d.preprocessing.segmentation.salient_box (BiRefNet via rembg), CPU."""from scipy import ndimage as ndisal = np.asarray(remove(im, session=REMBG, only_mask=True).convert("L")) >= 128lab, n = ndi.label(sal)if not n:raise gr.Error("No salient object found in the middle frame; name the object in the prompt box.")big = lab == (1 + int(np.argmax(ndi.sum(sal, lab, range(1, n + 1)))))ys, xs = np.nonzero(big)py, px = np.unravel_index(np.argmax(ndi.distance_transform_edt(big)), big.shape)return [float(xs.min()), float(ys.min()), float(xs.max()), float(ys.max())], [float(px), float(py)]def detect_box(im, prompt):inp = GDINO_PROC(images=im, text=f"a {prompt}.", return_tensors="pt").to("cuda")with torch.no_grad():out = GDINO(**inp)r = GDINO_PROC.post_process_grounded_object_detection(out, inp.input_ids, threshold=0.25, text_threshold=0.2,target_sizes=[im.size[::-1]])[0]if not len(r["scores"]):raise gr.Error(f"Grounding-DINO found no '{prompt}'. Try another prompt, or leave it empty.")k = int(r["scores"].argmax())return [float(v) for v in r["boxes"][k].tolist()], float(r["scores"][k])def predict_masks(frames, prompt=None, box=None, points=None):"""anything4d.preprocessing.segmentation.predict_masks with the cached SAM 2.1 / Grounding-DINO."""W, H = frames[0].sizef0 = len(frames) // 2info = {"frame": f0}if box is None and not points:box, info["score"] = detect_box(frames[f0], prompt)info["prompt"] = promptelif not prompt:info["prompt"] = "auto (salient object)"info.update(box=box, points=points)sess = SAM2_PROC.init_video_session(video=frames, inference_device="cuda", dtype=torch.bfloat16)kw = {"input_boxes": [[list(map(float, box))]]}if points:kw.update(input_points=[[[list(map(float, p)) for p in points]]], input_labels=[[[1] * len(points)]])SAM2_PROC.add_inputs_to_inference_session(inference_session=sess, frame_idx=f0, obj_ids=[1], **kw)9 unmodified linesdef vggt_omega_pointmaps(frames, res=512):"""anything4d.preprocessing.pointmaps.vggt_omega_pointmaps with the cached model."""from vggt_omega.utils.load_fn import load_and_preprocess_imagesfrom vggt_omega.utils.pose_enc import encoding_to_cameraw0, h0 = frames[0].sizeif not 0.5 <= h0 / w0 <= 2.0:raise gr.Error("Video aspect ratio must be between 1:2 and 2:1.")tmp = tempfile.mkdtemp(prefix="a4d_omega_")paths = []for t, im in enumerate(frames):7 unmodified linesconf = pred["depth_conf"][0].float().cpu().numpy().reshape(depth.shape)colors = images.permute(0, 2, 3, 1).float().cpu().numpy()del pred, imagesshutil.rmtree(tmp, ignore_errors=True)S, H, W = depth.shapeu = np.tile(np.arange(W, dtype=np.float32)[None, :], (H, 1)); v = np.tile(np.arange(H, dtype=np.float32)[:, None], (1, W))12 unmodified linesreturn list(pms), list(scene["intrinsics"]), scenedef precompute(ims, P, prompt=None, box=None, points=None):"""anything4d.pipeline.precompute.precompute (VGGT-Omega pointmaps), writing <clip>/precompute/."""os.makedirs(os.path.join(P, "frames"), exist_ok=True)names = [f"{t:04d}.png" for t in range(len(ims))]for n, im in zip(names, ims):im.save(os.path.join(P, "frames", n))msks, info = predict_masks(ims, prompt, box, points)if sum(int(m.any()) for m in msks) < len(msks):raise gr.Error("The object was lost in some frames. Try naming it in the prompt box, or a shorter clip.")os.makedirs(os.path.join(P, "masks"), exist_ok=True)for n, m in zip(names, msks):Image.fromarray(m.astype(np.uint8) * 255).save(os.path.join(P, "masks", n))H, W = ims[0].size[1], ims[0].size[0]pms, Ks, scene = vggt_omega_pointmaps(ims)np.savez_compressed(os.path.join(P, "scene.npz"), object_mask=np.stack([np.asarray(Image.fromarray(m.astype(np.uint8) * 255).resize(tuple(scene["proc_hw"][::-1]), Image.NEAREST)) > 127for m in msks]), **scene)pms, Ks, c2w = np.stack(pms), np.stack(Ks), scene["cam_c2w"].astype(np.float32)if pms.shape[-2:] != (H, W):pms = torch.nn.functional.interpolate(torch.from_numpy(np.ascontiguousarray(pms)), size=(H, W), mode="nearest").numpy()Kpx = np.asarray(Ks, np.float32).copy(); Kpx[:, 0] *= W; Kpx[:, 1] *= Hnp.savez_compressed(os.path.join(P, "cameras.npz"), intrinsics=Kpx, cam_c2w=c2w, image_size=np.array([W, H]))return msks, list(pms.astype(np.float32)), info# ----------------------------------------------------------------------------------------------# stage 2: 4DAnything (anything4d/pipeline/reconstruct.py)# ----------------------------------------------------------------------------------------------def reconstruct_4d(imgs, msks, pms, R, canonical_frame=0, pose_smooth_window=5, seed=42):from sam3d_objects.model.backbone.tdfy_dit.modules import sparse as spfrom anything4d.io.gaussians import layout_to_json, save_gaussiansfrom anything4d.pipeline.video_to_4d import VideoTo4DPipelinepipe, model = _get_pipeline()F = len(imgs)os.makedirs(R, exist_ok=True)out = pipe.run_video(imgs, [m.astype(np.uint8) * 255 for m in msks], pointmaps=pms, seed=seed,decode_formats=["gaussian"], pose_smooth_window=pose_smooth_window)slat = out["slat"]coords, feats, layout = slat.coords.detach().cpu().numpy(), slat.feats.detach().float().cpu().numpy(), out["layout"]del out, slatnames = [f"{t:04d}.png" for t in range(F)]json.dump({"frames": names, "layout": layout_to_json(layout)}, open(os.path.join(R, "layout.json"), "w"), indent=1)def pack(ts):cs, fs = [], []7 unmodified linestorch.manual_seed(0)canonical, fields = model(pack([canonical_frame]), pack(list(range(F))))frames = [model.gaussians_at_frame(canonical, fields[t]) for t in range(F)]save_gaussians(canonical, os.path.join(R, "canonical"))for d in ("object", "camera"):os.makedirs(os.path.join(R, d), exist_ok=True)for t, g in enumerate(frames):save_gaussians(g, os.path.join(R, "object", f"{t:04d}"))g_cam = VideoTo4DPipeline.place_in_camera_space(g, layout[t]["rotation"][None], layout[t]["translation"][None], layout[t]["scale"], "cuda")save_gaussians(g_cam, os.path.join(R, "camera", f"{t:04d}"))del canonical, fields, frames# ----------------------------------------------------------------------------------------------# viewer export: per-frame 3DGS .ply in a y-up frame for gr.Model3D# ----------------------------------------------------------------------------------------------SH_C0 = 0.28209479177387814def write_viewer_ply(path, g, center):from anything4d.render.gaussians import qmulflip = np.diag([1.0, -1.0, -1.0]) # OpenCV camera (y down, z fwd) -> viewer (y up)xyz = (g["xyz"] - center) @ flip.Tquat = qmul(np.array([0.0, 1.0, 0.0, 0.0])[None], g["quat"])eps = 1e-6o = np.clip(g["opacity"], eps, 1 - eps)data = np.concatenate([xyz, np.zeros_like(xyz), (g["rgb"] - 0.5) / SH_C0, np.log(o / (1 - o))[:, None],np.log(np.clip(g["scale"], eps, None)), quat], 1).astype(np.float32)props = ["x", "y", "z", "nx", "ny", "nz", "f_dc_0", "f_dc_1", "f_dc_2", "opacity","scale_0", "scale_1", "scale_2", "rot_0", "rot_1", "rot_2", "rot_3"]header = ("ply\nformat binary_little_endian 1.0\n" f"element vertex {len(data)}\n"+ "".join(f"property float {p}\n" for p in props) + "end_header\n")with open(path, "wb") as fh:fh.write(header.encode("ascii")); fh.write(data.tobytes())def export_viewer(R, lay, V):from anything4d.io.gaussians import load_gaussiansfrom anything4d.render.gaussians import layout_matrix, transformos.makedirs(V, exist_ok=True)gs = []for t in range(len(lay)):A, b, s = layout_matrix(lay[t])gs.append(transform(load_gaussians(os.path.join(R, "object", f"{t:04d}.npz")), A, b, s))center = np.median(gs[0]["xyz"], 0)paths = []for t, g in enumerate(gs):p = os.path.join(V, f"frame_{t:04d}.ply"); write_viewer_ply(p, g, center); paths.append(p)return paths# ----------------------------------------------------------------------------------------------# GPU entry point# ----------------------------------------------------------------------------------------------def _duration(frames, *args, **kwargs):n = len(frames) if frames else 24return int(min(600, 200 + 9 * n))@spaces.GPU(duration=_duration)def run_gpu(frames, clip_dir, prompt="", box=None, points=None, seed=42, pose_smooth_window=5, canonical_frame=0):from anything4d.render.videos import camera_view, multiview, scene_videost0 = time.time()P, R, V = (os.path.join(clip_dir, d) for d in ("precompute", "recon", "videos"))msks, pms, info = precompute(frames, P, prompt=prompt or None, box=box, points=points)torch.cuda.empty_cache()t1 = time.time()imgs = [np.asarray(im) for im in frames]reconstruct_4d(imgs, msks, pms, R, canonical_frame=canonical_frame, pose_smooth_window=pose_smooth_window, seed=seed)torch.cuda.empty_cache()t2 = time.time()# stage 3: anything4d/pipeline/visualize.pyos.makedirs(V, exist_ok=True)lay = json.load(open(os.path.join(R, "layout.json")))["layout"]Kpx = np.load(os.path.join(P, "cameras.npz"))["intrinsics"].astype(np.float64)fps = 12.0camera_view(R, imgs, lay, Kpx, os.path.join(V, "camera.mp4"), fps)multiview(R, imgs, lay, os.path.join(V, "multiview.mp4"), fps, 384)scene_videos(R, P, imgs, lay, os.path.join(V, "scene"), fps)t3 = time.time()timings = {"precompute": t1 - t0, "4danything": t2 - t1, "render": t3 - t2, "total": t3 - t0}print(f"[timing] {len(frames)} frames: {timings}", flush=True)return info, timingsMAX_FRAMES = 32def reconstruct(video: str, prompt: str = "", num_frames: int = 24, stride: int = 2, seed: int = 42,pose_smooth_window: int = 5, canonical_frame: int = 0, progress=gr.Progress(track_tqdm=True)):"""Reconstruct a moving object from a monocular video as 4D Gaussians with 4DAnything.Args:video: input video file (one moving object in view).prompt: name of the object to reconstruct (e.g. "dog"); empty picks the most salient object.num_frames: number of frames to reconstruct (taken from the start of the clip, after striding).stride: keep every N-th video frame.seed: random seed of the flow sampler.pose_smooth_window: moving-average window for the per-frame poses (1 disables smoothing).canonical_frame: frame whose latent seeds the canonical Gaussians G*.Returns:Input-camera video, multi-view video, in-scene orbit video, per-frame Gaussian splat (.ply) of frame 0,a zip with all Gaussians and poses, a status message, and the folder of per-frame splats."""if not video:raise gr.Error("Please upload a video.")num_frames, stride = int(min(max(num_frames, 2), MAX_FRAMES)), int(max(stride, 1))frames, _ = load_frames(video, num_frames, stride, 854)if len(frames) < 2:raise gr.Error("Could not read at least two frames from the video.")canonical_frame = int(min(max(canonical_frame, 0), len(frames) - 1))prompt = (prompt or "").strip()box = points = Noneif not prompt:progress(0.02, desc="Finding the salient object (BiRefNet)")box, pt = salient_box(frames[len(frames) // 2])points = [pt]clip_dir = os.path.join(tempfile.gettempdir(), "a4d_runs", uuid.uuid4().hex[:10])progress(0.05, desc=f"Reconstructing {len(frames)} frames")info, timings = run_gpu(frames, clip_dir, prompt, box, points, int(seed), int(pose_smooth_window), canonical_frame)R, V = os.path.join(clip_dir, "recon"), os.path.join(clip_dir, "videos")lay = json.load(open(os.path.join(R, "layout.json")))["layout"]plys = export_viewer(R, lay, os.path.join(clip_dir, "viewer"))zpath = os.path.join(clip_dir, "4danything_result.zip")with zipfile.ZipFile(zpath, "w", zipfile.ZIP_DEFLATED) as z:z.write(os.path.join(R, "layout.json"), "layout.json")z.write(os.path.join(R, "canonical.ply"), "canonical.ply")for t in range(len(lay)):z.write(os.path.join(R, "object", f"{t:04d}.ply"), f"object/{t:04d}.ply")z.write(os.path.join(R, "camera", f"{t:04d}.ply"), f"camera/{t:04d}.ply")who = f"'{info.get('prompt')}'"status = (f"Reconstructed **{len(frames)} frames** of {who} in {timings['total']:.0f}s on GPU "f"(masks + pointmaps {timings['precompute']:.0f}s, 4DAnything {timings['4danything']:.0f}s, "f"rendering {timings['render']:.0f}s).")return (os.path.join(V, "camera.mp4"), os.path.join(V, "multiview.mp4"), os.path.join(V, "scene_orbit.mp4"),plys[0], zpath, status, os.path.dirname(plys[0]))def show_frame(viewer_dir: str, idx: int):"""Show the Gaussian splat of another reconstructed frame."""if not viewer_dir or not os.path.isdir(viewer_dir):return gr.update()plys = sorted(Path(viewer_dir).glob("frame_*.ply"))if not plys:return gr.update()return str(plys[max(0, min(int(idx), len(plys) - 1))])CSS = """#col-container { max-width: 1280px; margin: 0 auto; }.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks(title="4DAnything") as demo:with gr.Column(elem_id="col-container"):gr.Markdown("# 4DAnything: feed-forward 4D reconstruction in the wild\n""Upload a casual video of a moving object. 4DAnything reconstructs it in a single forward pass as ""canonical 3D Gaussians plus a per-frame deformation, posed in the camera of every frame. \n""[Project page](https://4danything.github.io/) · [Code](https://github.com/nathalie000/4DAnything) · ""[Weights](https://huggingface.co/ncc2/4DAnything)")with gr.Row():with gr.Column(scale=2):video = gr.Video(label="Input video", height=300)prompt = gr.Textbox(label="Object (optional)", placeholder="e.g. dog. Leave empty for the most salient object")run = gr.Button("Reconstruct 4D", variant="primary")with gr.Accordion("Advanced settings", open=False):num_frames = gr.Slider(2, MAX_FRAMES, value=24, step=1, label="Frames",info="Frames taken from the start of the clip (after the stride). More = longer run.")stride = gr.Slider(1, 6, value=2, step=1, label="Frame stride", info="Keep every N-th video frame.")seed = gr.Number(value=42, precision=0, label="Seed")pose_smooth_window = gr.Slider(1, 9, value=5, step=2, label="Pose smoothing window",info="1 disables pose smoothing.")canonical_frame = gr.Number(value=0, precision=0, label="Canonical frame",info="Frame whose latent seeds the canonical Gaussians G*.")status = gr.Markdown()with gr.Column(scale=3):with gr.Tabs():with gr.Tab("Input camera"):cam_vid = gr.Video(label="Input | reconstruction | overlay", autoplay=True, loop=True)with gr.Tab("Object in the scene"):scene_vid = gr.Video(label="Orbit around the object placed in the reconstructed scene",autoplay=True, loop=True)with gr.Tab("Multi-view"):mv_vid = gr.Video(label="Top: canonical G*. Bottom: deformed object per frame",autoplay=True, loop=True)splat = gr.Model3D(label="Gaussian splat (drag to orbit)", height=380,clear_color=[1.0, 1.0, 1.0, 1.0])frame_idx = gr.Slider(0, MAX_FRAMES - 1, value=0, step=1, label="Splat viewer frame")result_zip = gr.File(label="Download Gaussians (.ply per frame) and poses")viewer_dir = gr.Textbox(visible=False)outputs = [cam_vid, mv_vid, scene_vid, splat, result_zip, status, viewer_dir]run.click(reconstruct, inputs=[video, prompt, num_frames, stride, seed, pose_smooth_window, canonical_frame],outputs=outputs, api_name="reconstruct", concurrency_limit=1)frame_idx.change(show_frame, inputs=[viewer_dir, frame_idx], outputs=[splat], api_name="show_frame")gr.Examples(examples=[["examples/kangaroo.mp4", ""], ["examples/horse.mp4", "horse"], ["examples/dog.mp4", "dog"]],inputs=[video, prompt], outputs=outputs, fn=reconstruct, cache_examples=True, cache_mode="lazy",)demo.queue(max_size=8).launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True, show_error=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632649 unmodified lines2742752762772782792802812822832842857 unmodified lines29329429529629729829912 unmodified lines3123133143153163173183193203213223233243253263273283293307 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482import osimport subprocessimport sysos.environ.setdefault("NUMBA_DISABLE_CUDA", "1")os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")os.environ["LIDRA_SKIP_INIT"] = "1"os.environ["ATTN_BACKEND"] = "xformers"os.environ["SPARSE_ATTN_BACKEND"] = "xformers"os.environ["SPCONV_ALGO"] = "native"def _pip_no_deps(spec):r = subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps", "--no-cache-dir", spec],capture_output=True, text=True)print(f"pip install --no-deps {spec}: {'OK' if r.returncode == 0 else 'FAILED'}\n{r.stderr[-800:] if r.returncode else ''}",flush=True)# Pure-python deps whose metadata would drag numpy<2 / old pins into the resolver: install without deps.try:import utils3d # noqa: F401except Exception:_pip_no_deps("git+https://github.com/EasternJournalist/utils3d.git@3913c65d81e05e47b9f367250cf8c0f7462a0900")try:import moge # noqa: F401except Exception:_pip_no_deps("git+https://github.com/microsoft/MoGe.git@a8c37341bc0325ca99b9d57981cc3bb2bd3e255b")try:import vggt_omega # noqa: F401except Exception: # commit pinned by 4DAnything's requirements.txt (its numpy<2 pin is not needed at runtime)_pip_no_deps("git+https://github.com/facebookresearch/vggt-omega.git@48b23c8ce72c9a8fcf987f0d7f43d8e4870759f6")import types # noqa: E402# open3d's Linux wheels are CUDA builds; SAM 3D imports it only for plane estimation (unused here).sys.modules.setdefault("open3d", types.ModuleType("open3d"))import spaces # noqa: E402 (must come before torch)import torch # noqa: E402APP_DIR = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, APP_DIR)sys.path.insert(0, os.path.join(APP_DIR, "third_party", "sam-3d-objects"))import contextlib # noqa: E402import json # noqa: E402import shutil # noqa: E402import tempfile # noqa: E402import time # noqa: E402import gradio as gr # noqa: E402import numpy as np # noqa: E402from huggingface_hub import hf_hub_download, snapshot_download # noqa: E402from PIL import Image # noqa: E402import anything4d # noqa: E402,F401 (sets SAM 3D env defaults + kaolin stand-in)# ----------------------------------------------------------------------------------------------# xformers on Blackwell (sm_120) only ships FA2 kernels (fp16/bf16). The 4D decoder runs in fp32 like the reference# (which used xformers' fp32 cutlass kernel), so fp32 calls fall back to an exact torch-SDPA implementation of# block-diagonal attention, batching segments of equal length.# ----------------------------------------------------------------------------------------------import xformers.ops as _xops # noqa: E402from xformers.ops.fmha.attn_bias import BlockDiagonalMask as _BDM # noqa: E402_xops_mea = _xops.memory_efficient_attentiondef _sdpa_bshd(q, k, v, scale=None):o = torch.nn.functional.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2),scale=scale)return o.transpose(1, 2)def _mea_with_fp32_fallback(query, key, value, attn_bias=None, p=0.0, scale=None, **kwargs):if query.dtype in (torch.float16, torch.bfloat16) or p:return _xops_mea(query, key, value, attn_bias, p, scale, **kwargs)if attn_bias is None:return _sdpa_bshd(query, key, value, scale)if not isinstance(attn_bias, _BDM):return _xops_mea(query, key, value, attn_bias, p, scale, **kwargs)qs, ks = attn_bias.q_seqinfo.seqstart_py, attn_bias.k_seqinfo.seqstart_pyq, k, v = query[0], key[0], value[0] # (M, H, C)out = q.new_empty(q.shape[:-1] + (v.shape[-1],))groups = {}for i in range(len(qs) - 1):groups.setdefault((qs[i + 1] - qs[i], ks[i + 1] - ks[i]), []).append((qs[i], ks[i]))dev = q.devicefor (ql, kl), starts in groups.items():if ql == 0:continuest = torch.tensor(starts, device=dev, dtype=torch.long)iq = st[:, :1] + torch.arange(ql, device=dev)[None]ik = st[:, 1:] + torch.arange(kl, device=dev)[None]for c in range(0, len(starts), 4096):a, b = iq[c:c + 4096], ik[c:c + 4096]out[a.reshape(-1)] = _sdpa_bshd(q[a], k[b], v[b], scale).reshape(-1, *out.shape[1:])return out[None]_xops.memory_efficient_attention = _mea_with_fp32_fallback# ----------------------------------------------------------------------------------------------# Weights# ----------------------------------------------------------------------------------------------TOKEN = os.environ.get("HF_TOKEN")SAM3D_ROOT = snapshot_download("facebook/sam-3d-objects", token=TOKEN,allow_patterns=["checkpoints/pipeline.yaml", "checkpoints/ss_generator.*", "checkpoints/slat_generator.*","checkpoints/ss_decoder.*", "checkpoints/slat_decoder_gs.*"])WS = os.path.join(SAM3D_ROOT, "checkpoints")A4D = {n: hf_hub_download("ncc2/4DAnything", n, token=TOKEN) for n in ("ss.pt", "slat.pt", "decoder.pt")}@contextlib.contextmanagerdef _no_cuda_queries():"""SAM 3D only *logs* the GPU name / current device while importing and constructing; answer thosewithout touching CUDA in the ZeroGPU main process."""gdn, cd = torch.cuda.get_device_name, torch.cuda.current_devicetorch.cuda.get_device_name = lambda *a, **k: "ZeroGPU"torch.cuda.current_device = lambda *a, **k: 0try:yieldfinally:torch.cuda.get_device_name, torch.cuda.current_device = gdn, cd# ----------------------------------------------------------------------------------------------# 4DAnything video backbone (SAM 3D Objects pipeline with the video SS / SLat flow models swapped in)# ----------------------------------------------------------------------------------------------with _no_cuda_queries():from hydra.utils import instantiatefrom omegaconf import OmegaConffrom anything4d.model.build import build_model, partial_warm_startfrom anything4d.model.decoder4d import build_decoderfrom anything4d.pipeline import precompute as a4d_prefrom anything4d.pipeline import reconstruct as a4d_recfrom anything4d.pipeline.video_to_4d import _overlay_ckpt, _share_noise_across_framesfrom anything4d.pipeline.visualize import visualizefrom anything4d.preprocessing import pointmaps as a4d_pointmapsfrom anything4d.preprocessing import segmentation as a4d_segimport sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.full_attn # noqa: F401from sam3d_objects.model.backbone.tdfy_dit.modules import sparse as sp# "object-scale" workspace of the reference (scripts/download_checkpoints.sh): use_scene_scale falsecfg = OmegaConf.load(os.path.join(WS, "pipeline.yaml"))cfg.ss_preprocessor.pointmap_normalizer.use_scene_scale = Falsecfg.workspace_dir = WScfg.compile_model = Falsecfg._target_ = "demo_pipeline.DemoPipeline"cfg.device = "cpu" # build on CPU, then move to CUDA (ZeroGPU packs module-level weights)cfg.slat_decoder_gs_4_config_path = Nonecfg.slat_decoder_gs_4_ckpt_path = Nonecfg.pop("depth_model", None)cfg.pop("clip_pointmap_beyond_scale", None)PIPE = instantiate(cfg, _recursive_=True)PIPE.use_pointmap = TruePIPE.decode_formats = [] # per-frame backbone Gaussians are not used by the 4D decoderdef _backbone_cfg(name):c = json.load(open(os.path.join(APP_DIR, "anything4d", "configs", f"backbone_{name}.json")))["model"]c["base_yaml"] = os.path.join(WS, f"{name}_generator.yaml")return cfor name, key in (("ss", "ss_generator"), ("slat", "slat_generator")):video_bb = build_model(_backbone_cfg(name)).eval()# warm start == the released SAM 3D Objects *_generator.ckpt backbone (already loaded strictly above)partial_warm_start(video_bb, None, raw_checkpoint=PIPE.models[key].reverse_fn.backbone.state_dict())_overlay_ckpt(video_bb, A4D[f"{name}.pt"], tag=f"{name}_flow")PIPE.models[key].reverse_fn.backbone = video_bb_share_noise_across_frames(PIPE.models["ss_generator"], {"shape": True, "layout": True})_share_noise_across_frames(PIPE.models["slat_generator"], {"shape": True, "layout": True})# 4D decoder: canonical Gaussians G* + per-frame deformationdcfg = OmegaConf.load(os.path.join(WS, "slat_decoder_gs.yaml"))dcfg.pop("pretrained_ckpt_path", None)_base = instantiate(dcfg)_base.load_state_dict(torch.load(os.path.join(WS, "slat_decoder_gs.ckpt"), map_location="cpu", weights_only=True),strict=True)_st = torch.load(A4D["decoder.pt"], map_location="cpu", weights_only=False)DECODER = build_decoder(_base, _st.get("args")).float().eval()DECODER.load_state_dict({k: v for k, v in _st["model"].items() if not k.startswith("frozen.")}, strict=True)del _stPIPE.models.to("cuda")for _emb in PIPE.condition_embedders.values():if _emb is not None:_emb.to("cuda")PIPE.device = torch.device("cuda")DECODER.to("cuda")# ----------------------------------------------------------------------------------------------# Preprocessing models: VGGT-Omega (pointmaps + cameras), SAM 2.1 (video masks), Grounding-DINO, BiRefNet# ----------------------------------------------------------------------------------------------from transformers import (AutoModelForZeroShotObjectDetection, AutoProcessor, # noqa: E402Sam2VideoModel, Sam2VideoProcessor)# VGGT-Omega over the whole clip: pointmaps + cameras (the reference default `--pointmap-model vggt_omega`)from vggt_omega.models import VGGTOmega # noqa: E402OMEGA = VGGTOmega()OMEGA.load_state_dict(torch.load(hf_hub_download(a4d_pointmaps.OMEGA_REPO, a4d_pointmaps.OMEGA_CKPT, token=TOKEN),map_location="cpu"))OMEGA = OMEGA.eval().to("cuda")SAM2 = Sam2VideoModel.from_pretrained(a4d_seg.SAM2_ID).to("cuda", dtype=torch.bfloat16)SAM2_PROC = Sam2VideoProcessor.from_pretrained(a4d_seg.SAM2_ID)DINO = AutoModelForZeroShotObjectDetection.from_pretrained(a4d_seg.DINO_ID).eval().to("cuda")DINO_PROC = AutoProcessor.from_pretrained(a4d_seg.DINO_ID)from rembg import new_session, remove # noqa: E402BIREFNET = new_session("birefnet-general", providers=["CPUExecutionProvider"])# ---- reference functions, rewired to the preloaded models (logic copied 1:1) ----def salient_box(im):"""anything4d.preprocessing.segmentation.salient_box with a cached BiRefNet session (runs on CPU)."""from scipy import ndimage as ndisal = np.asarray(remove(im, session=BIREFNET, only_mask=True).convert("L")) >= 128lab, n = ndi.label(sal)if not n:raise gr.Error("No salient object found; name the object in the 'Object' box.")big = lab == (1 + int(np.argmax(ndi.sum(sal, lab, range(1, n + 1)))))ys, xs = np.nonzero(big)py, px = np.unravel_index(np.argmax(ndi.distance_transform_edt(big)), big.shape)return [float(xs.min()), float(ys.min()), float(xs.max()), float(ys.max())], [float(px), float(py)]def detect_box(im, prompt, dev="cuda"):inp = DINO_PROC(images=im, text=f"a {prompt}.", return_tensors="pt").to(dev)with torch.no_grad():out = DINO(**inp)r = DINO_PROC.post_process_grounded_object_detection(out, inp.input_ids, threshold=0.25, text_threshold=0.2,target_sizes=[im.size[::-1]])[0]if not len(r["scores"]):raise gr.Error(f"Grounding-DINO found no '{prompt}'. Try another object name, or leave it empty.")k = int(r["scores"].argmax())return [float(v) for v in r["boxes"][k].tolist()], float(r["scores"][k])def predict_masks(frames, prompt=None, box=None, points=None, prompt_frame=None):W, H = frames[0].sizef0 = len(frames) // 2 if prompt_frame is None else prompt_frameinfo = {"frame": f0}if box is None and not points:if prompt:box, info["score"] = detect_box(frames[f0], prompt)info["prompt"] = promptelse:box, pt = salient_box(frames[f0])points = [pt]info["prompt"] = "auto (salient object)"info.update(box=box, points=points)dev = "cuda"sess = SAM2_PROC.init_video_session(video=frames, inference_device=dev, dtype=torch.bfloat16)kw = {}if box is not None:kw["input_boxes"] = [[list(map(float, box))]]if points:kw.update(input_points=[[[list(map(float, p)) for p in points]]], input_labels=[[[1] * len(points)]])SAM2_PROC.add_inputs_to_inference_session(inference_session=sess, frame_idx=f0, obj_ids=[1], **kw)9 unmodified linesdef vggt_omega_pointmaps(frames, res=512):"""anything4d.preprocessing.pointmaps.vggt_omega_pointmaps with the preloaded VGGT-Omega (logic copied 1:1)."""from vggt_omega.utils.load_fn import load_and_preprocess_imagesfrom vggt_omega.utils.pose_enc import encoding_to_cameraw0, h0 = frames[0].sizeif not 0.5 <= h0 / w0 <= 2.0:raise gr.Error("The video aspect ratio must be between 1:2 and 2:1.")tmp = tempfile.mkdtemp(prefix="a4d_omega_")paths = []for t, im in enumerate(frames):7 unmodified linesconf = pred["depth_conf"][0].float().cpu().numpy().reshape(depth.shape)colors = images.permute(0, 2, 3, 1).float().cpu().numpy()del pred, imagestorch.cuda.empty_cache()shutil.rmtree(tmp, ignore_errors=True)S, H, W = depth.shapeu = np.tile(np.arange(W, dtype=np.float32)[None, :], (H, 1)); v = np.tile(np.arange(H, dtype=np.float32)[:, None], (1, W))12 unmodified linesreturn list(pms), list(scene["intrinsics"]), scenedef run_backbone(imgs, msks, pms, workspace, ss_config, slat_config, ss_ckpt, slat_ckpt, seed, pose_smooth_window):out = PIPE.run_video(imgs, [m.astype(np.uint8) * 255 for m in msks], pointmaps=pms, seed=seed,decode_formats=[], pose_smooth_window=pose_smooth_window)slat = out["slat"]res = {"coords": slat.coords.detach().cpu().numpy(), "feats": slat.feats.detach().float().cpu().numpy(),"layout": out["layout"], "gaussian": []}del outtorch.cuda.empty_cache()return resdef run_decoder(coords, feats, F, workspace, decoder_ckpt, canonical_frame):model = DECODERdef pack(ts):cs, fs = [], []7 unmodified linestorch.manual_seed(0)canonical, fields = model(pack([canonical_frame]), pack(list(range(F))))frames = [model.gaussians_at_frame(canonical, fields[t]) for t in range(F)]return model, canonical, frames, fieldsa4d_pre.predict_masks = predict_masksa4d_pre.vggt_omega_pointmaps = vggt_omega_pointmapsa4d_rec.run_backbone = run_backbonea4d_rec.run_decoder = run_decoder# ----------------------------------------------------------------------------------------------# GPU stages# ----------------------------------------------------------------------------------------------def _pre_duration(video, clip_dir, prompt, box, points, num_frames, stride, *a, **k):return int(25 + 0.8 * int(num_frames))@spaces.GPU(duration=_pre_duration)def gpu_precompute(video, clip_dir, prompt, box, points, num_frames, stride):t0 = time.perf_counter()a4d_pre.precompute(video, clip_dir, prompt=prompt or None, box=box, points=points,num_frames=num_frames, stride=stride, long_side=854,pointmap_model="vggt_omega")return time.perf_counter() - t0def _rec_duration(clip_dir, seed, fps, num_frames, *a, **k):F = int(num_frames)return int(1.3 * (6.9 * F + 0.104 * F * F) + 15 + 10 + 1.2 * F) # + scene videos (to be measured)@spaces.GPU(duration=_rec_duration)def gpu_reconstruct(clip_dir, seed, fps, num_frames):t0 = time.perf_counter()a4d_rec.reconstruct(clip_dir, WS, None, None, None, None, None, canonical_frame=0, pose_smooth_window=5,seed=int(seed))t1 = time.perf_counter()visualize(clip_dir, ("multiview", "camera", "scene"), fps=fps, tile=384)return t1 - t0, time.perf_counter() - t1def _video_fps(path):try:import imageio.v2 as imageioreturn float(imageio.get_reader(path, "ffmpeg").get_meta_data().get("fps") or 24.0)except Exception:return 24.0def reconstruct_4d(video: str, object_name: str = "", num_frames: int = 16, frame_stride: int = 3, seed: int = 42,progress=gr.Progress(track_tqdm=True)):"""Reconstruct one dynamic object from a monocular video as a complete 4D Gaussian asset.Args:video: Path to an input video (one dynamic object; casually captured footage works).object_name: Optional name of the object to reconstruct (Grounding-DINO). Empty = most salient object.num_frames: Number of frames to use (after striding).frame_stride: Keep every N-th frame of the video.seed: Random seed for the generative backbone.Returns:Input/render/overlay video, orbit video of the object placed in the VGGT-Omega scene, multi-view video (canonical G* and deformed object per frame),canonical Gaussians (.ply) and a mask preview of the tracked object."""if not video:raise gr.Error("Please upload a video.")num_frames, frame_stride = int(num_frames), int(frame_stride)clip_dir = tempfile.mkdtemp(prefix="a4d_")object_name = (object_name or "").strip()box = points = Noneif not object_name: # default object pick: BiRefNet salient box + centre click on the middle frame (CPU)progress(0.02, desc="Finding the salient object")frames, _ = a4d_pre.load_frames(video, num_frames, frame_stride, 854)if len(frames) < 3:raise gr.Error("The video is too short; it needs at least 3 frames after striding.")box, pt = salient_box(frames[len(frames) // 2])points = [pt]progress(0.05, desc="Masks (SAM 2.1) + pointmaps and cameras (VGGT-Omega)")t_pre = gpu_precompute(video, clip_dir, object_name, box, points, num_frames, frame_stride)progress(0.3, desc="4DAnything reconstruction + rendering")fps = _video_fps(video) / frame_stridet_rec, t_vis = gpu_reconstruct(clip_dir, seed, fps, num_frames)print(f"[timing] precompute {t_pre:.1f}s, reconstruct {t_rec:.1f}s, render {t_vis:.1f}s", flush=True)P, R, V = (os.path.join(clip_dir, d) for d in ("precompute", "recon", "videos"))names = sorted(os.listdir(os.path.join(P, "masks")))mid = names[len(names) // 2]fr = np.asarray(Image.open(os.path.join(P, "frames", mid)).convert("RGB")).astype(np.float32)mk = np.asarray(Image.open(os.path.join(P, "masks", mid)).convert("L")) > 127fr[mk] = 0.45 * fr[mk] + 0.55 * np.array([255, 140, 0], np.float32)preview = Image.fromarray(fr.astype(np.uint8))return (os.path.join(V, "camera.mp4"), os.path.join(V, "scene_orbit.mp4"), os.path.join(V, "multiview.mp4"),os.path.join(R, "canonical.ply"), preview)# ----------------------------------------------------------------------------------------------# UI# ----------------------------------------------------------------------------------------------CSS = """#col-container { max-width: 1200px; margin: 0 auto; }.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks(title="4DAnything") as demo:with gr.Column(elem_id="col-container"):gr.Markdown("# 4DAnything\n""Feed-forward **video → 4D** reconstruction: from a casual monocular video, recover a complete 4D Gaussian ""object (geometry, appearance, deformation and camera-space motion) in one pass. \n""[Project page](https://4danything.github.io/) · [Paper](https://arxiv.org/abs/2612.02443) · ""[Code](https://github.com/nathalie000/4DAnything) · [Weights](https://huggingface.co/ncc2/4DAnything)")with gr.Row():with gr.Column(scale=1):video_in = gr.Video(label="Input video (one dynamic object)", sources=["upload"])object_in = gr.Textbox(label="Object (optional)", placeholder="e.g. kangaroo — empty picks the most salient object")run_btn = gr.Button("Reconstruct 4D", variant="primary")with gr.Accordion("Advanced settings", open=False):frames_in = gr.Slider(8, 24, value=16, step=1, label="Frames")stride_in = gr.Slider(1, 4, value=3, step=1, label="Frame stride")seed_in = gr.Number(value=42, precision=0, label="Seed")mask_out = gr.Image(label="Tracked object (middle frame)", interactive=False)with gr.Column(scale=2):camera_out = gr.Video(label="Input | 4D reconstruction from the input camera | overlay",autoplay=True, loop=True)scene_out = gr.Video(label="Orbit: the reconstructed object placed in the scene (VGGT-Omega)",autoplay=True, loop=True)multiview_out = gr.Video(label="Canonical G* (top) and deformed object per frame (bottom)",autoplay=True, loop=True)ply_out = gr.Model3D(label="Canonical Gaussians G* (.ply)", height=380)outputs = [camera_out, scene_out, multiview_out, ply_out, mask_out]run_btn.click(reconstruct_4d, inputs=[video_in, object_in, frames_in, stride_in, seed_in], outputs=outputs,api_name="reconstruct")gr.Examples(examples=[["examples/kangaroo.mp4", ""], ["examples/horse.mp4", "horse"], ["examples/cat.mp4", "cat"]],inputs=[video_in, object_in], outputs=outputs, fn=reconstruct_4d,cache_examples=True, cache_mode="lazy")if __name__ == "__main__":demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
123version https://git-lfs.github.com/spec/v1oid sha256:3b9b69bef60dfb891fe38f94c4ad100e08494285175372a47893d39a01bac59esize 3445757123version https://git-lfs.github.com/spec/v1oid sha256:693abc1e2fb5ca148e0eaf238d3bf066151d39bb4012b96d0e85928879c3ac79size 3178895123version https://git-lfs.github.com/spec/v1oid sha256:e77670fa0d48a7ad2293272705b3e8bb550cb232b86f71bd050d175d6fa7de02size 970507
12345678910111213141516171819202122232425262728293031323334353637383940torchvision# prebuilt sm_120 (Blackwell) CUDA wheels, cell pt211-cu130-cp312https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/pytorch3d-0.7.9-cp312-cp312-linux_x86_64.whlhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/diff_gaussian_rasterization-0.0.0-cp312-cp312-linux_x86_64.whlhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/xformers-0.0.34+3da0fc92.d20260528-cp39-abi3-linux_x86_64.whliopathfvcore# sparse convolutions for SAM 3D Objects / TRELLIS latentsspconv-cu124==2.3.8hydra-core==1.3.2omegaconf==2.3.0logurutqdmeinopseasydictoptreeastorlightningsafetensorstimmtransformersacceleratePillowopencv-python-headlessscipymatplotlibseaborntrimeshplyfilexatlasigraphopen3dpyvistapymeshfiximageio[ffmpeg]imageio-ffmpegrembg[cpu]==2.0.671234567891011121314151617181920212223242526272829303132333435363738394041424344torch==2.11.0torchvision==0.26.0https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/xformers-0.0.34+3da0fc92.d20260528-cp39-abi3-linux_x86_64.whlhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/flash_attn-2.8.3-cp312-cp312-linux_x86_64.whlhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/pytorch3d-0.7.9-cp312-cp312-linux_x86_64.whlhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/diff_gaussian_rasterization-0.0.0-cp312-cp312-linux_x86_64.whlhttps://github.com/fafraob/spconv-wheels/releases/download/v2.3.8/cumm_cu130-0.8.2-cp312-cp312-linux_x86_64.whlhttps://github.com/fafraob/spconv-wheels/releases/download/v2.3.8/spconv_cu130-2.3.8-cp312-cp312-linux_x86_64.whlpccmccimportpybind11fireiopathfvcorenumpyeinopseasydictloguruhydra-core==1.3.2omegaconf==2.3.0timm==0.9.16opencv-python-headlesspillowscipymatplotlibseabornplotlytrimeshplyfileopen3dsafetensorstransformers>=5accelerateimageio[ffmpeg]imageio-ffmpegoptreeastorlightningxatlaspyvistapymeshfixigraphrembg==2.0.67onnxruntime
.gitattributes-1
LICENSE_4DAnythingDeleted-21
README.md+22-34
anything4d/render/gaussians.py+8-47
app.py+322-341
examples/dog.mp4Deleted-3
examples/horse.mp4+2-2
requirements.txt+29-25