Spaces:
Running on Zero

4danything / app.py
multimodalart's picture
multimodalart HF Staff
Duration headroom for larger objects
61b5856 verified
Raw History Blame Contribute Delete
22.4 kB
import os
import subprocess
import sys
os.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: F401
except Exception:
_pip_no_deps("git+https://github.com/EasternJournalist/utils3d.git@3913c65d81e05e47b9f367250cf8c0f7462a0900")
try:
import moge # noqa: F401
except Exception:
_pip_no_deps("git+https://github.com/microsoft/MoGe.git@a8c37341bc0325ca99b9d57981cc3bb2bd3e255b")
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: E402
APP_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: E402
import json # noqa: E402
import shutil # noqa: E402
import tempfile # noqa: E402
import time # noqa: E402
import gradio as gr # noqa: E402
import numpy as np # noqa: E402
from huggingface_hub import hf_hub_download, snapshot_download # noqa: E402
from PIL import Image # noqa: E402
import 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: E402
from xformers.ops.fmha.attn_bias import BlockDiagonalMask as _BDM # noqa: E402
_xops_mea = _xops.memory_efficient_attention
def _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_py
q, 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.device
for (ql, kl), starts in groups.items():
if ql == 0:
continue
st = 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.contextmanager
def _no_cuda_queries():
"""SAM 3D only *logs* the GPU name / current device while importing and constructing; answer those
without touching CUDA in the ZeroGPU main process."""
gdn, cd = torch.cuda.get_device_name, torch.cuda.current_device
torch.cuda.get_device_name = lambda *a, **k: "ZeroGPU"
torch.cuda.current_device = lambda *a, **k: 0
try:
yield
finally:
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 instantiate
from omegaconf import OmegaConf
from anything4d.model.build import build_model, partial_warm_start
from anything4d.model.decoder4d import build_decoder
from anything4d.pipeline import precompute as a4d_pre
from anything4d.pipeline import reconstruct as a4d_rec
from anything4d.pipeline.video_to_4d import _overlay_ckpt, _share_noise_across_frames
from anything4d.pipeline.visualize import visualize
from anything4d.preprocessing import pointmaps as a4d_pointmaps
from anything4d.preprocessing import segmentation as a4d_seg
import sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.full_attn # noqa: F401
from sam3d_objects.model.backbone.tdfy_dit.modules import sparse as sp
# "object-scale" workspace of the reference (scripts/download_checkpoints.sh): use_scene_scale false
cfg = OmegaConf.load(os.path.join(WS, "pipeline.yaml"))
cfg.ss_preprocessor.pointmap_normalizer.use_scene_scale = False
cfg.workspace_dir = WS
cfg.compile_model = False
cfg._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 = None
cfg.slat_decoder_gs_4_ckpt_path = None
cfg.pop("depth_model", None)
cfg.pop("clip_pointmap_beyond_scale", None)
PIPE = instantiate(cfg, _recursive_=True)
PIPE.use_pointmap = True
PIPE.decode_formats = [] # per-frame backbone Gaussians are not used by the 4D decoder
def _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 c
for 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 deformation
dcfg = 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 _st
PIPE.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: E402
Sam2VideoModel, Sam2VideoProcessor)
# MoGe pointmaps through SAM 3D Objects' released compute_pointmap (the repo's `--pointmap-model moge` path).
a4d_pointmaps._alias_utils3d_pt()
from moge.model.v1 import MoGeModel # noqa: E402
from sam3d_objects.pipeline.depth_models.moge import MoGe # noqa: E402
PIPE.depth_model = MoGe(MoGeModel.from_pretrained("Ruicheng/moge-vitl").eval(), device="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: E402
BIREFNET = 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 ndi
sal = np.asarray(remove(im, session=BIREFNET, only_mask=True).convert("L")) >= 128
lab, 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].size
f0 = len(frames) // 2 if prompt_frame is None else prompt_frame
info = {"frame": f0}
if box is None and not points:
if prompt:
box, info["score"] = detect_box(frames[f0], prompt)
info["prompt"] = prompt
else:
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)
logits = {}
with torch.no_grad():
SAM2(inference_session=sess, frame_idx=f0)
for rev in (False, True):
for o in SAM2.propagate_in_video_iterator(inference_session=sess, start_frame_idx=f0, reverse=rev):
m = SAM2_PROC.post_process_masks([o.pred_masks], original_sizes=[[H, W]], binarize=False)[0]
logits[o.frame_idx] = m[0, 0].float().cpu().numpy()
del sess
return [logits[t] > 0 if t in logits else np.zeros((H, W), bool) for t in range(len(frames))], info
def moge_pointmaps(workspace, imgs, msks):
"""anything4d.preprocessing.pointmaps.moge_pointmaps, using the preloaded pipeline's MoGe depth model."""
from sam3d_objects.pipeline.inference_pipeline_pointmap import InferencePipelinePointMap
if not hasattr(PIPE, "clip_pointmap_beyond_scale"):
PIPE.clip_pointmap_beyond_scale = None # pipeline.yaml sets none
if not hasattr(PIPE, "_clip_pointmap"):
PIPE._clip_pointmap = types.MethodType(InferencePipelinePointMap._clip_pointmap, PIPE)
pms, Ks = [], []
for im, mk in zip(imgs, msks):
rgba = np.asarray(PIPE.merge_image_and_mask(np.asarray(im), mk.astype(np.uint8) * 255), dtype=np.uint8)
d = InferencePipelinePointMap.compute_pointmap(PIPE, rgba, pointmap=None)
pms.append(d["pointmap"].detach().float().cpu().numpy())
Ks.append(d["intrinsics"].detach().float().cpu().numpy().reshape(3, 3))
torch.cuda.empty_cache()
return pms, Ks
def 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 out
torch.cuda.empty_cache()
return res
def run_decoder(coords, feats, F, workspace, decoder_ckpt, canonical_frame):
model = DECODER
def pack(ts):
cs, fs = [], []
for b, t in enumerate(ts):
m = coords[:, 0] == t
c = coords[m].copy(); c[:, 0] = b; cs.append(c); fs.append(feats[m])
return sp.SparseTensor(feats=torch.as_tensor(np.concatenate(fs), dtype=torch.float32).cuda(),
coords=torch.as_tensor(np.concatenate(cs), dtype=torch.int32).cuda())
with torch.no_grad():
torch.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, fields
a4d_pre.predict_masks = predict_masks
a4d_pre.moge_pointmaps = moge_pointmaps
a4d_rec.run_backbone = run_backbone
a4d_rec.run_decoder = run_decoder
# ----------------------------------------------------------------------------------------------
# GPU stages
# ----------------------------------------------------------------------------------------------
def _pre_duration(video, clip_dir, prompt, box, points, num_frames, stride, *a, **k):
return int(15 + 0.5 * int(num_frames)) # measured 8.5 s @16 frames (+ cold-start weight streaming)
@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="moge")
return time.perf_counter() - t0
def _rec_duration(clip_dir, seed, fps, num_frames, *a, **k):
F = int(num_frames)
return int(1.25 * (6.9 * F + 0.104 * F * F) + 15) # measured 138-162 s @16 frames (kangaroo, horse)
@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"), fps=fps, tile=384)
return t1 - t0, time.perf_counter() - t1
def _video_fps(path):
try:
import imageio.v2 as imageio
return float(imageio.get_reader(path, "ffmpeg").get_meta_data().get("fps") or 24.0)
except Exception:
return 24.0
def 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, 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 = None
if 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 (MoGe)")
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_stride
t_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")) > 127
fr[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, "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)
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, 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)