[SIGGRAPH Asia 2026] 4DAnyone: Create Anyone in 4D from a Casual Monocular Video
Add single-node multi-GPU inference (#13)
Yudong Jin5ad3c5f1c938
diff --git a/README.md b/README.mdindex f8271d4..06c1b16 100644--- a/README.md+++ b/README.md@@ -84,12 +84,13 @@ python inference.py \### Arguments-Run `python inference.py --help` for the full list. Key camera-layout arguments are:+Run `python inference.py --help` for the full list. Key arguments are:-- `views_per_layer`: number of evenly spaced views per pitch layer; must be divisible by 4 or 6.-- `layer_pitches`: pitch angles in degrees, one per layer; positive values place cameras above the subject. Total views are `views_per_layer × len(layer_pitches)`.-- `start_yaw`: horizontal angle of the first view, in degrees; yaw `0` is the front view.+- `views_per_layer`: number of evenly spaced views per pitch layer. It must be divisible by 4 or 6.+- `layer_pitches`: pitch angles in degrees, one per layer. Positive values place cameras above the subject. Total views are `views_per_layer × len(layer_pitches)`.+- `start_yaw`: horizontal angle of the first view, in degrees. Yaw `0` is the front view.- `yaw_span`: horizontal range covered by each camera layer, in degrees.+- `gpu_ids`: GPU IDs to use for parallel denoising. Defaults to all visible GPUs.### Output@@ -111,10 +112,10 @@ data/Use an input video that:-- is 720p or higher, with 1080p recommended;-- uses a 9:16 portrait aspect ratio;-- shows one person in a full-body or upper-body shot;-- has at least 121 frames;+- is 720p or higher, with 1080p recommended.+- uses a 9:16 portrait aspect ratio.+- shows one person in a full-body or upper-body shot.+- has at least 121 frames.- contains only mild camera motion.### Inference Efficiencydiff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.mdindex 1b8d0f2..9106b38 100644--- a/docs/THIRD_PARTY_NOTICES.md+++ b/docs/THIRD_PARTY_NOTICES.md@@ -11,7 +11,7 @@ The root Apache-2.0 license applies only to first-party 4DAnyone code. The follo4DAnyone uses the official upstream source without a GVHMR source patch. The pinned revision is immutable and can be fetched anonymously from the upstream repository.-GVHMR, HMR2, ViTPose, YOLO, SMPL, and SMPL-X model files are not bundled in 4DAnyone. The complete public inference closure is anchored by the immutable Hugging Face revision frozen in `fdanyone/assets.py`; users obtain those files through the applicable upstream or licensed setup flows.+GVHMR, HMR2, ViTPose, YOLO, SMPL, and SMPL-X model files are not bundled in 4DAnyone. The complete public inference closure is anchored by the immutable Hugging Face revision frozen in `fdanyone/assets.py`. Users obtain those files through the applicable upstream or licensed setup flows.GVHMR permits use, copying, modification, and distribution for educational, research, and non-profit purposes only. It requires modifications based on the work to be open source and prohibits commercial use. Its checkpoints and transitive model assets may have additional terms.@@ -22,7 +22,7 @@ GVHMR permits use, copying, modification, and distribution for educational, rese- Upstream code: <https://github.com/ZhengPeng7/BiRefNet>- License: MIT, copied at `third_party/licenses/BIREFNET_LICENSE`-The adaptive preprocessing path downloads the pinned BiRefNet configuration, inference source, and weights on demand. It uses the resulting foreground masks for source cropping and source-framing analysis; those downloaded files retain their upstream terms.+The adaptive preprocessing path downloads the pinned BiRefNet configuration, inference source, and weights on demand. It uses the resulting foreground masks for source cropping and source-framing analysis. Those downloaded files retain their upstream terms.## PyTorch3D compatibility subset@@ -39,7 +39,7 @@ Classic GVHMR imports PyTorch3D rotation conversions through a broader training-- Location: `data/source/pexels`- Terms: <https://www.pexels.com/license/>-The companion Hugging Face repository distributes eight modified 121-frame excerpts for running the public demo; they are installed under the location above on demand. The excerpts derive from Pexels videos [10331522](https://www.pexels.com/video/10331522/), [2785536](https://www.pexels.com/video/2785536/), [5435720](https://www.pexels.com/video/5435720/), [5885633](https://www.pexels.com/video/5885633/), [5999210](https://www.pexels.com/video/5999210/), [6980035](https://www.pexels.com/video/6980035/), [7080903](https://www.pexels.com/video/7080903/), and [7480858](https://www.pexels.com/video/7480858/). Pexels permits its media to be used and modified for free and does not require attribution; the source links are retained for provenance and creator credit.+The companion Hugging Face repository distributes eight modified 121-frame excerpts for running the public demo. They are installed under the location above on demand. The excerpts derive from Pexels videos [10331522](https://www.pexels.com/video/10331522/), [2785536](https://www.pexels.com/video/2785536/), [5435720](https://www.pexels.com/video/5435720/), [5885633](https://www.pexels.com/video/5885633/), [5999210](https://www.pexels.com/video/5999210/), [6980035](https://www.pexels.com/video/6980035/), [7080903](https://www.pexels.com/video/7080903/), and [7480858](https://www.pexels.com/video/7480858/). Pexels permits its media to be used and modified for free and does not require attribution. The source links are retained for provenance and creator credit.## DiffSynth-Studio inference runtime@@ -71,13 +71,13 @@ The retained schema material is conservatively treated as Sapiens2-derived and t## Model and body assets-The 4DAnyone checkpoint and sanitized MHR70 sparse regression tensors are first-party release artifacts licensed under Apache-2.0, published at the Hugging Face revision frozen in `fdanyone/assets.py`. The regressor file also embeds the exact keypoint-name order required to interpret those tensors; that schema material retains the Sapiens2 notice above and is not relicensed by the tensor license. Wan VAE/T5/tokenizer, GVHMR checkpoints, HMR2, ViTPose, detector weights, and SMPL-X body models remain third-party assets. The redistributable files are mirrored by the companion Hugging Face repository; users obtain SMPL-X from its official site and remain responsible for every applicable license.+The 4DAnyone checkpoint and sanitized MHR70 sparse regression tensors are first-party release artifacts licensed under Apache-2.0, published at the Hugging Face revision frozen in `fdanyone/assets.py`. The regressor file also embeds the exact keypoint-name order required to interpret those tensors. That schema material retains the Sapiens2 notice above and is not relicensed by the tensor license. Wan VAE/T5/tokenizer, GVHMR checkpoints, HMR2, ViTPose, detector weights, and SMPL-X body models remain third-party assets. The redistributable files are mirrored by the companion Hugging Face repository. Users obtain SMPL-X from its official site and remain responsible for every applicable license.-The frozen base-model assets come from the official [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B) repository at revision `37685f96025fc1425edccdd4b2bca3836ae917ff` and the official [Wan2.1-T2V-1.3B](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) repository at revision `3f40b6dc4ca5c02dd23c9db74d9d2ccb82903b86`. Their official model cards license those model assets under Apache-2.0; the redistributed copies are pinned by the frozen Hugging Face revision.+The frozen base-model assets come from the official [Wan2.2-TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B) repository at revision `37685f96025fc1425edccdd4b2bca3836ae917ff` and the official [Wan2.1-T2V-1.3B](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) repository at revision `3f40b6dc4ca5c02dd23c9db74d9d2ccb82903b86`. Their official model cards license those model assets under Apache-2.0. The redistributed copies are pinned by the frozen Hugging Face revision.-The MHR70 asset is a sanitized inference artifact containing only the sparse support/weight tensors, keypoint names, and a path-free structural schema. The first-party regression tensors are redistributed under Apache-2.0; the embedded name/order metadata remains covered by the schema notice above.+The MHR70 asset is a sanitized inference artifact containing only the sparse support/weight tensors, keypoint names, and a path-free structural schema. The first-party regression tensors are redistributed under Apache-2.0. The embedded name/order metadata remains covered by the schema notice above.-That regressor was trained by the 4DAnyone project on DNA-Rendering frames, using outputs from [SAM 3D Body](https://github.com/facebookresearch/sam-3d-body) and the [Momentum Human Rig](https://github.com/facebookresearch/MHR) conversion tools. SAM 3D Body is governed by the SAM License, MHR source is Apache-2.0, and DNA-Rendering access requires a separate signed dataset agreement. The regressor is not bundled in the source repository; its Hugging Face model card must retain these source-model and dataset citations alongside the split tensor/schema license declaration in this notice.+That regressor was trained by the 4DAnyone project on DNA-Rendering frames, using outputs from [SAM 3D Body](https://github.com/facebookresearch/sam-3d-body) and the [Momentum Human Rig](https://github.com/facebookresearch/MHR) conversion tools. SAM 3D Body is governed by the SAM License, MHR source is Apache-2.0, and DNA-Rendering access requires a separate signed dataset agreement. The regressor is not bundled in the source repository. Its Hugging Face model card must retain these source-model and dataset citations alongside the split tensor/schema license declaration in this notice.## VGG-19 perceptual reconstruction@@ -86,4 +86,4 @@ That regressor was trained by the 4DAnyone project on DNA-Rendering frames, usin- MatConvNet distribution: [imagenet-vgg-verydeep-19](https://www.vlfeat.org/matconvnet/pretrained/), source MD5 `106118b7cf60435e6d8e04f6a6dc3657`- Model license: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/)-The optional `splatfacto-perceptual` method uses a custom pixel-plus-feature objective rather than standard LPIPS. The companion Hugging Face repository contains a modified copy of the VGG-19 model: MatConvNet filters are transposed into PyTorch layout and serialized as safetensors, while the unused classifier and final two convolution layers are omitted. The retained tensor values are otherwise unchanged. Credit remains with Karen Simonyan and Andrew Zisserman; users must preserve that attribution and the CC BY 4.0 license when redistributing the converted weights.+The optional `splatfacto-perceptual` method uses a custom pixel-plus-feature objective rather than standard LPIPS. The companion Hugging Face repository contains a modified copy of the VGG-19 model: MatConvNet filters are transposed into PyTorch layout and serialized as safetensors, while the unused classifier and final two convolution layers are omitted. The retained tensor values are otherwise unchanged. Credit remains with Karen Simonyan and Andrew Zisserman. Users must preserve that attribution and the CC BY 4.0 license when redistributing the converted weights.diff --git a/docs/output.md b/docs/output.mdindex 89ead1a..3f01789 100644--- a/docs/output.md+++ b/docs/output.md@@ -24,7 +24,7 @@ data/- `videos/sparse/` contains intermediate proposal views for larger camera layouts.- `skeletons/` contains pose-conditioning videos aligned with the target views.- `cameras.json` contains camera intrinsics and poses for every target view.-- `metadata.json` records the input, generation settings, model versions, and timings.+- `metadata.json` records the input, generation settings, model versions, timings, and worker metrics when target denoising uses multiple GPUs.- `gvhmr/results/` caches the recovered input motion for reuse.All output videos contain 121 frames at 704×1280, use the selected output FPS, and contain no audio.diff --git a/fdanyone/device.py b/fdanyone/device.pyindex 73bd828..55e0b4c 100644--- a/fdanyone/device.py+++ b/fdanyone/device.py@@ -2,6 +2,8 @@from __future__ import annotations+from collections.abc import Sequence+from fdanyone.errors import ConfigurationError@@ -23,3 +25,33 @@ def select_cuda_device(device: str) -> tuple[str, int]:)torch.cuda.set_device(index)return f"cuda:{index}", index+++def select_cuda_devices(gpu_ids: Sequence[int] | None = None) -> tuple[str, ...]:+ """Select an ordered set of CUDA-visible devices for one inference run."""++ import torch++ if not torch.cuda.is_available() or torch.cuda.device_count() <= 0:+ raise ConfigurationError("4DAnyone requires at least one available CUDA device.")++ if gpu_ids is None:+ selected = tuple(range(torch.cuda.device_count()))+ else:+ if isinstance(gpu_ids, (str, bytes)) or not isinstance(gpu_ids, Sequence) or not gpu_ids:+ raise ConfigurationError("gpu_ids must be a non-empty list of CUDA-visible device IDs.")+ selected = tuple(gpu_ids)+ invalid = [gpu_id for gpu_id in selected if isinstance(gpu_id, bool) or not isinstance(gpu_id, int)]+ if invalid:+ raise ConfigurationError(f"gpu_ids must contain only integers, got {invalid!r}.")+ if len(set(selected)) != len(selected):+ raise ConfigurationError(f"gpu_ids must not contain duplicates, got {list(selected)!r}.")++ available = torch.cuda.device_count()+ unavailable = [gpu_id for gpu_id in selected if gpu_id < 0 or gpu_id >= available]+ if unavailable:+ raise ConfigurationError(+ f"gpu_ids contains unavailable CUDA-visible device IDs {unavailable}; visible device count is {available}."+ )+ torch.cuda.set_device(selected[0])+ return tuple(f"cuda:{gpu_id}" for gpu_id in selected)diff --git a/fdanyone/model/denoise.py b/fdanyone/model/denoise.pynew file mode 100644index 0000000..97af955--- /dev/null+++ b/fdanyone/model/denoise.py@@ -0,0 +1,22 @@+"""Shared denoising math for RCP, single-GPU, and multi-GPU execution."""++from __future__ import annotations+++def denoise_group(pipe, latents, source, context, skeletons, step_index: int):+ """Advance one camera group by one scheduler step."""++ import torch++ timestep = pipe.scheduler.timesteps[step_index]+ batched_timestep = timestep.unsqueeze(0).to(dtype=pipe.torch_dtype, device=latents.device)+ batched_timestep = torch.cat([batched_timestep] * latents.shape[0], dim=0)+ prediction = pipe.dit(+ x=latents,+ x_src=source,+ timestep=batched_timestep,+ skeletons=skeletons,+ context=context,+ **pipe.prepare_extra_input(latents),+ )+ return pipe.scheduler.step(prediction, timestep, latents)diff --git a/fdanyone/model/distributed.py b/fdanyone/model/distributed.pynew file mode 100644index 0000000..06b595a--- /dev/null+++ b/fdanyone/model/distributed.py@@ -0,0 +1,383 @@+"""Single-node distributed target denoising.++The public pipeline keeps preprocessing, RCP, and result publication in the+primary process. This module gives each CUDA worker one DiT replica and uses+NCCL collectives to evaluate independent camera groups in parallel. Every+TCR step is fully gathered before the next routing step begins.+"""++from __future__ import annotations++import json+import logging+import math+import os+import socket+import time+from collections.abc import Callable, Iterable, Sequence+from dataclasses import dataclass+from datetime import timedelta+from pathlib import Path+from typing import TypeVar++from fdanyone.errors import FourDAnyoneError++LOGGER = logging.getLogger("fdanyone")++CameraGroup = tuple[int, ...]+StepGroups = tuple[CameraGroup, ...]+Routes = tuple[StepGroups, ...]+ResultT = TypeVar("ResultT")+++@dataclass(frozen=True)+class DistributedDenoiseRequest:+ checkpoint_path: str+ work_dir: str+ devices: tuple[str, ...]+ routes: Routes+ denoising_strength: float+ scheduler_shift: float+ skeleton_shape: tuple[int, ...]+ init_method: str+++def worker_count_for_groups(num_groups: int, max_workers: int) -> int:+ """Use fewer workers when that balances groups without adding waves."""++ if num_groups <= 0 or max_workers <= 0:+ raise ValueError(f"num_groups and max_workers must be positive, got {num_groups} and {max_workers}.")+ workers = min(num_groups, max_workers)+ waves = math.ceil(num_groups / workers)+ for candidate in range(workers, 0, -1):+ if num_groups % candidate == 0 and num_groups // candidate == waves:+ return candidate+ return workers+++def select_worker_devices(devices: Sequence[str], num_groups: int) -> tuple[str, ...]:+ """Choose the largest balanced GPU prefix that does not add a wave."""++ if not devices:+ raise ValueError("At least one candidate GPU is required.")+ return tuple(devices[: worker_count_for_groups(num_groups, len(devices))])+++def group_waves(groups: Sequence[CameraGroup], num_workers: int) -> tuple[StepGroups, ...]:+ """Split one routing step into waves that fit the available workers."""++ if num_workers <= 0:+ raise ValueError(f"num_workers must be positive, got {num_workers}.")+ return tuple(tuple(groups[start : start + num_workers]) for start in range(0, len(groups), num_workers))+++def validate_routes(routes: Routes, num_views: int) -> None:+ """Require every routing step to be a disjoint canonical camera partition."""++ expected = list(range(num_views))+ if not routes:+ raise ValueError("Distributed denoising requires at least one routing step.")+ if not routes[0] or not routes[0][0]:+ raise ValueError("Distributed denoising requires non-empty camera groups.")+ num_groups = len(routes[0])+ group_size = len(routes[0][0])+ for step_index, groups in enumerate(routes):+ if len(groups) != num_groups:+ raise ValueError(f"Routing step {step_index} has {len(groups)} groups; every step must have {num_groups}.")+ if any(len(group) != group_size for group in groups):+ raise ValueError(f"Routing step {step_index} contains camera groups with inconsistent sizes.")+ flattened = sorted(camera for group in groups for camera in group)+ if flattened != expected:+ raise ValueError(+ f"Routing step {step_index} is not a disjoint partition of cameras 0..{num_views - 1}: {groups}."+ )+++def run_group_schedule(+ routes: Routes,+ num_workers: int,+ *,+ execute_wave: Callable[[int, StepGroups], Sequence[ResultT]],+ apply_result: Callable[[CameraGroup, ResultT], None],+ finish_step: Callable[[int], None],+) -> None:+ """Execute group waves in route order and finish each step with a barrier."""++ for step_index, groups in enumerate(routes):+ for wave in group_waves(groups, num_workers):+ results = tuple(execute_wave(step_index, wave))+ if len(results) != len(wave):+ raise RuntimeError(f"Distributed wave returned {len(results)} results for {len(wave)} camera groups.")+ for group, result in zip(wave, results, strict=True):+ apply_result(group, result)+ finish_step(step_index)+++def _free_local_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _write_skeleton_tensor_file(conditioning, skeletons: Iterable, path: Path) -> tuple[int, ...]:+ """Decode target skeletons once into a file-backed BF16 tensor."""++ import torch++ items = tuple(skeletons)+ if not items:+ raise FourDAnyoneError("Distributed target denoising requires at least one skeleton video.")++ LOGGER.info("Preparing shared target skeleton 1/%d from %s", len(items), items[0].path.name)+ first = conditioning.load_skeleton_tensor([items[0]]).to(dtype=torch.bfloat16, device="cpu").contiguous()+ if first.ndim != 5 or first.shape[0] != 1:+ raise FourDAnyoneError(f"Expected one 5D skeleton tensor, got shape {tuple(first.shape)}.")+ shape = (len(items), *tuple(first.shape[1:]))+ numel = math.prod(shape)+ with path.open("xb") as handle:+ handle.truncate(numel * first.element_size())+ mapped = torch.from_file(str(path), shared=True, size=numel, dtype=torch.bfloat16).view(shape)+ mapped[0].copy_(first[0])+ del first+ for camera_id, skeleton in enumerate(items[1:], start=1):+ LOGGER.info(+ "Preparing shared target skeleton %d/%d from %s",+ camera_id + 1,+ len(items),+ skeleton.path.name,+ )+ tensor = conditioning.load_skeleton_tensor([skeleton]).to(dtype=torch.bfloat16, device="cpu").contiguous()+ if tuple(tensor.shape[1:]) != shape[1:] or tensor.shape[0] != 1:+ raise FourDAnyoneError(+ f"Skeleton camera {camera_id} has shape {tuple(tensor.shape)}, expected {(1, *shape[1:])}."+ )+ mapped[camera_id].copy_(tensor[0])+ del tensor+ del mapped+ return shape+++def _worker(rank: int, request: DistributedDenoiseRequest) -> None:+ """Run one NCCL rank. Rank zero owns and publishes the canonical latents."""++ import torch+ import torch.distributed as dist++ from fdanyone.model.denoise import denoise_group+ from fdanyone.model.loader import load_denoiser+ from fdanyone.vendor.diffsynth.models.wan_video_dit import get_attention_backend++ logging.basicConfig(+ level=logging.INFO,+ format=f"%(asctime)s | %(levelname)s | GPU rank {rank} | %(message)s",+ )+ os.environ.setdefault("TORCH_NCCL_ASYNC_ERROR_HANDLING", "1")+ os.environ.setdefault("CUDA_DEVICE_MAX_CONNECTIONS", "1")++ device = request.devices[rank]+ device_index = int(device.removeprefix("cuda:"))+ torch.cuda.set_device(device_index)+ torch.cuda.reset_peak_memory_stats(device_index)+ resolved_backend = get_attention_backend()++ model_started = time.monotonic()+ pipe = load_denoiser(checkpoint_path=request.checkpoint_path, device=device)+ pipe.dit.to(device)+ model_load_seconds = time.monotonic() - model_started++ dist.init_process_group(+ backend="nccl",+ init_method=request.init_method,+ rank=rank,+ world_size=len(request.devices),+ timeout=timedelta(minutes=30),+ )+ try:+ payload = torch.load(+ Path(request.work_dir) / "inputs.pt",+ map_location="cpu",+ weights_only=True,+ mmap=True,+ )+ source = payload["source"].to(dtype=pipe.torch_dtype, device=device)+ context = payload["context"].to(dtype=pipe.torch_dtype, device=device)+ skeletons = torch.from_file(+ str(Path(request.work_dir) / "skeletons.bf16"),+ shared=False,+ size=math.prod(request.skeleton_shape),+ dtype=torch.bfloat16,+ ).view(request.skeleton_shape)+ routes = request.routes+ group_size = len(routes[0][0])+ latent_shape = tuple(payload["initial_latents"].shape)+ latent_tail = latent_shape[1:]+ latents = payload["initial_latents"].to(dtype=pipe.torch_dtype, device=device) if rank == 0 else None++ pipe.scheduler.set_timesteps(+ len(routes),+ denoising_strength=request.denoising_strength,+ shift=request.scheduler_shift,+ )+ dist.barrier(device_ids=[device_index])+ denoise_started = time.monotonic()++ def execute_wave(step_index: int, wave: StepGroups):+ local_input = torch.empty((group_size, *latent_tail), dtype=pipe.torch_dtype, device=device)+ if rank == 0:+ scatter_list = []+ for worker_index in range(len(request.devices)):+ padded = torch.zeros_like(local_input)+ if worker_index < len(wave):+ group = wave[worker_index]+ index = torch.tensor(group, dtype=torch.long, device=device)+ padded[: len(group)].copy_(torch.index_select(latents, 0, index))+ scatter_list.append(padded)+ else:+ scatter_list = None+ dist.scatter(local_input, scatter_list=scatter_list, src=0)+ if scatter_list is not None:+ del scatter_list++ local_result = torch.zeros_like(local_input)+ if rank < len(wave):+ group = wave[rank]+ valid = len(group)+ local_latents = local_input[:valid]+ cpu_index = torch.tensor(group, dtype=torch.long, device="cpu")+ local_skeletons = torch.index_select(skeletons, 0, cpu_index).to(device=device)+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16):+ updated = denoise_group(+ pipe,+ local_latents,+ source,+ context,+ local_skeletons,+ step_index,+ )+ local_result[:valid].copy_(updated)+ del local_latents, local_skeletons, updated++ gather_list = [torch.empty_like(local_result) for _ in request.devices] if rank == 0 else None+ dist.gather(local_result, gather_list=gather_list, dst=0)+ del local_input, local_result+ if rank == 0:+ return tuple(gather_list[: len(wave)])+ return (None,) * len(wave)++ def apply_result(group: CameraGroup, result) -> None:+ if rank != 0:+ return+ index = torch.tensor(group, dtype=torch.long, device=device)+ latents.index_copy_(0, index, result[: len(group)])++ def finish_step(step_index: int) -> None:+ dist.barrier(device_ids=[device_index])+ if rank == 0:+ LOGGER.info("Completed target denoising step %d/%d", step_index + 1, len(routes))++ run_group_schedule(+ routes,+ len(request.devices),+ execute_wave=execute_wave,+ apply_result=apply_result,+ finish_step=finish_step,+ )+ torch.cuda.synchronize(device_index)+ denoise_seconds = time.monotonic() - denoise_started++ if rank == 0:+ temporary = Path(request.work_dir) / ".target_latents.pt.tmp"+ torch.save(latents.detach().to("cpu"), temporary)+ os.replace(temporary, Path(request.work_dir) / "target_latents.pt")++ report = {+ "rank": rank,+ "device": device,+ "device_name": torch.cuda.get_device_name(device_index),+ "attention_backend": resolved_backend,+ "model_load_seconds": model_load_seconds,+ "denoise_seconds": denoise_seconds,+ "peak_vram_allocated_bytes": int(torch.cuda.max_memory_allocated(device_index)),+ "peak_vram_reserved_bytes": int(torch.cuda.max_memory_reserved(device_index)),+ }+ report_path = Path(request.work_dir) / f"rank-{rank}.json"+ report_path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")+ dist.barrier(device_ids=[device_index])+ finally:+ if dist.is_initialized():+ dist.destroy_process_group()+++def denoise_targets_distributed(+ *,+ src_latents,+ context,+ initial_latents,+ conditioning,+ routes: Routes,+ checkpoint_path: str | Path,+ work_dir: str | Path,+ devices: Sequence[str],+ denoising_strength: float,+ scheduler_shift: float,+) -> tuple[object, list[dict[str, object]]]:+ """Prepare shared inputs, launch NCCL workers, and return canonical latents."""++ import torch+ import torch.multiprocessing as mp++ devices = tuple(devices)+ if len(devices) < 2:+ raise ValueError("Distributed denoising requires at least two GPUs.")+ if not torch.distributed.is_available() or not torch.distributed.is_nccl_available():+ raise FourDAnyoneError("Multi-GPU inference requires a PyTorch build with NCCL support.")+ validate_routes(routes, int(initial_latents.shape[0]))+ num_groups = len(routes[0])++ root = Path(work_dir).expanduser().resolve()+ root.mkdir(parents=True, exist_ok=False)+ torch.save(+ {+ "source": src_latents.detach().to("cpu").contiguous(),+ "context": context.detach().to("cpu").contiguous(),+ "initial_latents": initial_latents.detach().to("cpu").contiguous(),+ },+ root / "inputs.pt",+ )+ skeleton_shape = _write_skeleton_tensor_file(+ conditioning,+ conditioning.target_skeletons,+ root / "skeletons.bf16",+ )+ request = DistributedDenoiseRequest(+ checkpoint_path=str(Path(checkpoint_path).expanduser().resolve()),+ work_dir=str(root),+ devices=devices,+ routes=routes,+ denoising_strength=denoising_strength,+ scheduler_shift=scheduler_shift,+ skeleton_shape=skeleton_shape,+ init_method=f"tcp://127.0.0.1:{_free_local_port()}",+ )+ LOGGER.info(+ "Starting distributed target denoising on %d GPUs (%d groups, up to %d waves per step)",+ len(devices),+ num_groups,+ math.ceil(num_groups / len(devices)),+ )+ try:+ mp.spawn(_worker, args=(request,), nprocs=len(devices), join=True)+ except Exception as exc:+ raise FourDAnyoneError(f"Multi-GPU target denoising failed: {exc}") from exc++ output_path = root / "target_latents.pt"+ if not output_path.is_file():+ raise FourDAnyoneError("Multi-GPU target denoising finished without publishing target latents.")+ latents = torch.load(output_path, map_location="cpu", weights_only=True)+ reports = []+ for rank in range(len(devices)):+ report_path = root / f"rank-{rank}.json"+ if not report_path.is_file():+ raise FourDAnyoneError(f"Multi-GPU worker {rank} did not publish its runtime report.")+ reports.append(json.loads(report_path.read_text()))+ return latents, reportsdiff --git a/fdanyone/model/inference.py b/fdanyone/model/inference.pyindex 0b04aa9..a90d2e3 100644--- a/fdanyone/model/inference.py+++ b/fdanyone/model/inference.py@@ -1,14 +1,15 @@"""Hydra/Lightning-free multi-view generation.RCP and final target generation share one source encoding and prompt embedding.-Target groups execute sequentially on one GPU; TCR optionally shifts their-membership between denoising steps.+Target groups execute sequentially on one GPU or concurrently across multiple+GPUs; TCR optionally shifts their membership between denoising steps."""from __future__ import annotationsimport gcimport logging+import mathimport timefrom collections.abc import Iterablefrom dataclasses import dataclass@@ -20,6 +21,8 @@ from PIL import Imagefrom fdanyone.assets import BaseAssetsfrom fdanyone.config import INFERENCEfrom fdanyone.errors import FourDAnyoneError+from fdanyone.model.denoise import denoise_group+from fdanyone.model.distributed import denoise_targets_distributed, select_worker_devicesfrom fdanyone.model.loader import load_pipelinefrom fdanyone.model.routing import routing_stepsfrom fdanyone.skeleton.pipeline import Conditioning, SkeletonVideo@@ -41,6 +44,7 @@ class GeneratedViews:elapsed_seconds: dict[str, float]peak_vram_allocated_bytes: intpeak_vram_reserved_bytes: int+ parallelism: dict[str, object] | None = Nonedef _empty_cuda_cache() -> None:@@ -87,15 +91,15 @@ def _channels_last_source_layout(video):return video.contiguous(memory_format=torch.channels_last_3d)-def _encode_prompt(pipe, device: str) -> dict[str, object]:+def _encode_prompt(pipe, device: str):import torch_move_model(pipe.text_encoder, device)with torch.inference_mode(), _bf16_autocast():context = pipe.prompter.encode_prompt(INFERENCE.prompt, positive=True, device=device)- prompt = {"context": context.detach().to("cpu")}+ context = context.detach().to("cpu")_offload_model(pipe.text_encoder)- return prompt+ return contextdef _encode_videos(pipe, videos, device: str):@@ -164,7 +168,7 @@ def _skeleton_group(def _denoise_rcp(pipe,src_latents,- prompt,+ context,camera_ids: tuple[int, ...],skeletons: tuple[SkeletonVideo, ...],skeleton_cache: dict[SkeletonVideo, object],@@ -183,24 +187,21 @@ def _denoise_rcp()latents = _noise(pipe, len(skeletons), INFERENCE.num_frames, seed, device)source = src_latents.to(dtype=pipe.torch_dtype, device=device)- context = {name: value.to(dtype=pipe.torch_dtype, device=device) for name, value in prompt.items()}+ context = context.to(dtype=pipe.torch_dtype, device=device)# Preserve the reviewed RCP tensor layout: it changes CUDA kernel selection.# Target generation below materializes each sequential group contiguously.skeleton_tensor = _skeleton_group(skeleton_cache, skeletons, device, channels_last=True)with torch.inference_mode(), _bf16_autocast():- for timestep in tqdm(pipe.scheduler.timesteps, desc=f"RCP 1-to-{len(camera_ids)}"):- batched_timestep = timestep.unsqueeze(0).to(dtype=pipe.torch_dtype, device=device)- batched_timestep = torch.cat([batched_timestep] * len(skeletons), dim=0)- prediction = pipe.dit(- x=latents,- x_src=source,- timestep=batched_timestep,- skeletons=skeleton_tensor,- **context,- **pipe.prepare_extra_input(latents),+ for step_index, _ in enumerate(tqdm(pipe.scheduler.timesteps, desc=f"RCP 1-to-{len(camera_ids)}")):+ latents = denoise_group(+ pipe,+ latents,+ source,+ context,+ skeleton_tensor,+ step_index,)- latents = pipe.scheduler.step(prediction, timestep, latents)return latents.detach().to("cpu")@@ -290,39 +291,30 @@ def _decode_rcp(return tuple(frame_outputs), tuple(video_outputs)-def _denoise_targets(+def _denoise_targets_single(pipe,src_latents,- prompt,+ context,skeletons: tuple[SkeletonVideo, ...],skeleton_cache: dict[SkeletonVideo, object],- view_plan: ViewPlan,+ initial_latents,+ routes,device: str,- seed: int,):import torchfrom tqdm.auto import tqdm- num_views = len(skeletons)- if num_views != view_plan.num_target_views:- raise FourDAnyoneError(- f"Target generation requires {view_plan.num_target_views} skeleton views, got {num_views}."- )+ num_views = initial_latents.shape[0]+ if len(skeletons) != num_views:+ raise FourDAnyoneError(f"Target generation requires {num_views} skeleton views, got {len(skeletons)}.")pipe.scheduler.set_timesteps(INFERENCE.num_inference_steps,denoising_strength=INFERENCE.denoising_strength,shift=INFERENCE.scheduler_shift,)- latents = _noise(pipe, num_views, INFERENCE.num_frames, seed, device)+ latents = initial_latentssource = src_latents.to(dtype=pipe.torch_dtype, device=device)- context = {name: value.to(dtype=pipe.torch_dtype, device=device) for name, value in prompt.items()}- routes = routing_steps(- views_per_layer=view_plan.views_per_layer,- num_layers=view_plan.num_layers,- group_size=view_plan.views_per_group,- num_steps=INFERENCE.num_inference_steps,- enable_tcr=view_plan.enable_tcr,- )+ context = context.to(dtype=pipe.torch_dtype, device=device)with torch.inference_mode(), _bf16_autocast():for step_index, groups in enumerate(tqdm(routes, desc=f"Generate {num_views} target views")):@@ -334,20 +326,16 @@ def _denoise_targets((skeletons[view_index] for view_index in view_indices),device,)- timestep = pipe.scheduler.timesteps[step_index]- batched_timestep = timestep.unsqueeze(0).to(dtype=pipe.torch_dtype, device=device)- batched_timestep = torch.cat([batched_timestep] * len(view_indices), dim=0)- prediction = pipe.dit(- x=local_latents,- x_src=source,- timestep=batched_timestep,- skeletons=local_skeletons,- **context,- **pipe.prepare_extra_input(local_latents),+ local_latents = denoise_group(+ pipe,+ local_latents,+ source,+ context,+ local_skeletons,+ step_index,)- local_latents = pipe.scheduler.step(prediction, timestep, local_latents)latents.index_copy_(0, index, local_latents)- del local_latents, local_skeletons, prediction+ del local_latents, local_skeletonsreturn latents.detach().to("cpu")@@ -384,7 +372,7 @@ def generate_views(checkpoint_path: str | Path,assets: BaseAssets,output_dir: str | Path,- device: str,+ devices: tuple[str, ...],seed: int,) -> GeneratedViews:"""Generate the proposal (when enabled) and the requested target views."""@@ -395,6 +383,9 @@ def generate_views(raise FourDAnyoneError("Generation requires the frozen 121-frame contract.")if seed < 0:raise FourDAnyoneError(f"seed must be non-negative, got {seed}.")+ if not devices:+ raise FourDAnyoneError("Generation requires at least one CUDA device.")+ device = devices[0]device_index = int(device.removeprefix("cuda:"))LOGGER.info("Using %s (%s)", device, torch.cuda.get_device_name(device_index))@@ -412,7 +403,7 @@ def generate_views(torch.cuda.reset_peak_memory_stats(device_index)started = time.monotonic()- prompt = _encode_prompt(pipe, device)+ context = _encode_prompt(pipe, device)loaded.release_text_encoder()timings["prompt"] = time.monotonic() - started@@ -433,7 +424,7 @@ def generate_views(rcp_latents = _denoise_rcp(pipe,source_latents,- prompt,+ context,view_plan.rcp_camera_ids,conditioning.rcp_skeletons,skeleton_cache,@@ -468,19 +459,66 @@ def generate_views(timings["rcp_decode_and_reference_encode"] = time.monotonic() - startedstarted = time.monotonic()- _load_skeleton_cache(conditioning, conditioning.target_skeletons, skeleton_cache)- _move_model(pipe.dit, device)- target_latents = _denoise_targets(- pipe,- target_sources,- prompt,- conditioning.target_skeletons,- skeleton_cache,- view_plan,- device,- seed,+ routes = routing_steps(+ views_per_layer=view_plan.views_per_layer,+ num_layers=view_plan.num_layers,+ group_size=view_plan.views_per_group,+ num_steps=INFERENCE.num_inference_steps,+ enable_tcr=view_plan.enable_tcr,)- _offload_model(pipe.dit)+ initial_latents = _noise(pipe, view_plan.num_target_views, INFERENCE.num_frames, seed, device)+ worker_devices = select_worker_devices(devices, view_plan.num_groups)+ if len(worker_devices) < len(devices):+ LOGGER.info(+ "Using %d of %d candidate GPUs for %d target groups",+ len(worker_devices),+ len(devices),+ view_plan.num_groups,+ )++ parallelism = None+ if len(worker_devices) > 1:+ # RCP has finished, so the parent no longer needs a DiT replica. Each+ # spawned NCCL rank loads its own copy directly onto its assigned GPU.+ pipe.dit = None+ initial_latents = initial_latents.to("cpu")+ skeleton_cache.clear()+ _empty_cuda_cache()+ target_latents, workers = denoise_targets_distributed(+ src_latents=target_sources,+ context=context,+ initial_latents=initial_latents,+ conditioning=conditioning,+ routes=routes,+ checkpoint_path=checkpoint_path,+ work_dir=root / "distributed",+ devices=worker_devices,+ denoising_strength=INFERENCE.denoising_strength,+ scheduler_shift=INFERENCE.scheduler_shift,+ )+ parallelism = {+ "backend": "nccl",+ "candidate_devices": list(devices),+ "used_devices": list(worker_devices),+ "groups_per_step": view_plan.num_groups,+ "waves_per_step": math.ceil(view_plan.num_groups / len(worker_devices)),+ "workers": workers,+ }+ else:+ _load_skeleton_cache(conditioning, conditioning.target_skeletons, skeleton_cache)+ _move_model(pipe.dit, device)+ target_latents = _denoise_targets_single(+ pipe,+ target_sources,+ context,+ conditioning.target_skeletons,+ skeleton_cache,+ initial_latents,+ routes,+ device,+ )+ _offload_model(pipe.dit)+ del initial_latentstimings["target_denoise"] = time.monotonic() - startedstarted = time.monotonic()@@ -492,8 +530,18 @@ def generate_views(timings["target_decode"] = time.monotonic() - startedpeak_vram_allocated = int(torch.cuda.max_memory_allocated(device_index))peak_vram_reserved = int(torch.cuda.max_memory_reserved(device_index))+ if parallelism is not None:+ workers = parallelism["workers"]+ peak_vram_allocated = max(+ peak_vram_allocated,+ *(int(worker["peak_vram_allocated_bytes"]) for worker in workers),+ )+ peak_vram_reserved = max(+ peak_vram_reserved,+ *(int(worker["peak_vram_reserved_bytes"]) for worker in workers),+ )- del target_latents, target_sources, source_latents, prompt, skeleton_cache, loaded, pipe+ del target_latents, target_sources, source_latents, context, skeleton_cache, loaded, pipe_empty_cuda_cache()return GeneratedViews(rcp_videos=rcp_videos,@@ -504,4 +552,5 @@ def generate_views(elapsed_seconds=timings,peak_vram_allocated_bytes=peak_vram_allocated,peak_vram_reserved_bytes=peak_vram_reserved,+ parallelism=parallelism,)diff --git a/fdanyone/model/loader.py b/fdanyone/model/loader.pyindex d2c021e..004702e 100644--- a/fdanyone/model/loader.py+++ b/fdanyone/model/loader.py@@ -257,3 +257,16 @@ def load_pipeline(pipe.height_division_factor = pipe.vae.upsampling_factor * 2pipe.width_division_factor = pipe.vae.upsampling_factor * 2return LoadedPipeline(pipe=pipe)+++def load_denoiser(*, checkpoint_path: str | Path, device: str):+ """Load the DiT and scheduler required by one distributed worker."""++ import torch++ from fdanyone.vendor.diffsynth.pipelines.wan_video_spatem import WanVideoSpaTemPipeline++ dtype = torch.bfloat16+ pipe = WanVideoSpaTemPipeline(device=device, torch_dtype=dtype)+ pipe.dit = _load_dit(Path(checkpoint_path), dtype)+ return pipediff --git a/fdanyone/output.py b/fdanyone/output.pyindex 3ff9867..3918bc8 100644--- a/fdanyone/output.py+++ b/fdanyone/output.py@@ -153,6 +153,23 @@ def export_result(conditioning_metadata = json.loads((conditioning.root / "metadata.json").read_text())camera_records = _target_cameras(camera_payload, view_plan.num_target_views)total_elapsed = time.monotonic() - pipeline_started+ generation_metadata = {+ "seed": generated.seed,+ "view_plan": {+ **view_plan.to_dict(),+ "num_layers": view_plan.num_layers,+ "num_target_views": view_plan.num_target_views,+ "groups_per_layer": view_plan.groups_per_layer,+ },+ "attention_backend": attention_backend,+ "inference_steps": INFERENCE.num_inference_steps,+ "elapsed_seconds": generated.elapsed_seconds,+ "total_elapsed_seconds": total_elapsed,+ "peak_vram_allocated_bytes": generated.peak_vram_allocated_bytes,+ "peak_vram_reserved_bytes": generated.peak_vram_reserved_bytes,+ }+ if generated.parallelism is not None:+ generation_metadata["parallelism"] = generated.parallelismmetadata = {"input": {@@ -174,21 +191,7 @@ def export_result("skeleton_draw_scale": conditioning_metadata["skeleton_draw_scale"],},"model": dict(model_identity),- "generation": {- "seed": generated.seed,- "view_plan": {- **view_plan.to_dict(),- "num_layers": view_plan.num_layers,- "num_target_views": view_plan.num_target_views,- "groups_per_layer": view_plan.groups_per_layer,- },- "attention_backend": attention_backend,- "inference_steps": INFERENCE.num_inference_steps,- "elapsed_seconds": generated.elapsed_seconds,- "total_elapsed_seconds": total_elapsed,- "peak_vram_allocated_bytes": generated.peak_vram_allocated_bytes,- "peak_vram_reserved_bytes": generated.peak_vram_reserved_bytes,- },+ "generation": generation_metadata,"output": {"rcp_views": len(output_sparse),"target_views": len(output_dense),diff --git a/fdanyone/pipeline.py b/fdanyone/pipeline.pyindex 7fa0abe..7c1c718 100644--- a/fdanyone/pipeline.py+++ b/fdanyone/pipeline.py@@ -20,7 +20,7 @@ from fdanyone.assets import (resolve_regressor,)from fdanyone.config import INFERENCE-from fdanyone.device import select_cuda_device+from fdanyone.device import select_cuda_devicesfrom fdanyone.download import ensure_example_video, ensure_models, ensure_smplxfrom fdanyone.errors import ConfigurationErrorfrom fdanyone.io import AtomicResultDirectory, remove_tree, write_json@@ -173,7 +173,7 @@ def run_pipeline(checkpoint_path: str | None,mhr70_regressor_path: str | None,gvhmr_root: str,- device: str,+ gpu_ids: list[int] | None,start_time: float,target_fps: str | int | float,seed: int,@@ -210,7 +210,8 @@ def run_pipeline(f"4DAnyone result already exists: {atomic.destination}. Choose a new --data_dir or input filename.")validate_required_video_codecs()- device, _ = select_cuda_device(device)+ devices = select_cuda_devices(gpu_ids)+ device = devices[0]ensure_example_video(video_path)# Resolve the licensed body model before starting the much larger public@@ -304,7 +305,7 @@ def run_pipeline(checkpoint_path=checkpoint,assets=base_assets,output_dir=scratch / "generation",- device=device,+ devices=devices,seed=seed,)summary = export_result(diff --git a/inference.py b/inference.pyindex 9785f41..23c0021 100644--- a/inference.py+++ b/inference.py@@ -23,7 +23,7 @@ def inference(checkpoint_path: str | None = None,mhr70_regressor_path: str | None = None,gvhmr_root: str = "third_party/GVHMR",- device: str = "cuda:0",+ gpu_ids: list[int] | None = None,target_fps: str | int | float = "auto",start_time: float = 0.0,seed: int = 42,@@ -51,7 +51,8 @@ def inference(checkpoint_path: Local 4DAnyone checkpoint override.mhr70_regressor_path: Local SMPL-X-to-MHR70 regressor override.gvhmr_root: Path to the GVHMR source checkout.- device: CUDA device, for example cuda:0.+ gpu_ids: GPU IDs to use for parallel denoising. Omit to use all+ visible GPUs.target_fps: auto preserves the input clock unless it divides evenlyto 24, 25, or 30 FPS; a positive number requests an explicit FPS.start_time: Clip start time on the input timeline, in seconds.@@ -75,7 +76,7 @@ def inference(checkpoint_path=checkpoint_path,mhr70_regressor_path=mhr70_regressor_path,gvhmr_root=gvhmr_root,- device=device,+ gpu_ids=gpu_ids,target_fps=target_fps,start_time=start_time,seed=seed,