Skip to content

[SIGGRAPH Asia 2026] 4DAnyone: Create Anyone in 4D from a Casual Monocular Video

Accelerate multi-GPU inference view stages (#18)

Yudong Jinf4ae8ae9aa07
diff --git a/README.md b/README.md
index 4f630a5..2edc3d8 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,8 @@
## News
-- **2026-08-28**: Significantly reduced GPU memory usage while slightly improving speed. See [Inference performance](docs/inference_performance.md) for details.
+- **2026-08-28**: Achieved a **1.42×** end-to-end speedup for the complete 24-view generation pipeline.
+- **2026-08-28**: Reduced peak GPU memory to **25.4 GiB** while slightly improving speed. See [Inference performance](docs/inference_performance.md) for details.
## Installation
@@ -92,7 +93,7 @@ Run `python inference.py --help` for the full list. Key arguments are:
- `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.
+- `gpu_ids`: GPU IDs used for parallel pose/VAE view stages and target denoising. Defaults to all visible GPUs.
### Output
@@ -112,7 +113,7 @@ data/
### Inference Efficiency
-For faster inference on supported GPUs, optionally install [FlashAttention-3](https://github.com/Dao-AILab/flash-attention/tree/main/hopper) or [SageAttention](https://github.com/thu-ml/SageAttention). Our implementation automatically detects installed backends at runtime.
+For faster inference on supported GPUs, optionally install [FlashAttention-3](https://github.com/Dao-AILab/flash-attention/tree/main/hopper) or [SageAttention](https://github.com/thu-ml/SageAttention). Runtime selection follows one fixed order: FlashAttention-3, SageAttention, then PyTorch SDPA.
See [Inference performance](docs/inference_performance.md) for measured 6-view runtimes and peak GPU memory usage on H20-3E, H200, RTX 5880 Ada, and RTX A6000 GPUs.
@@ -130,11 +131,22 @@ Use an input video that:
See the [nerfstudio guide](docs/nerfstudio.md) for details.
-## Todos
+## Roadmap
-- [x] Reduce peak GPU memory usage below 32 GB
-- [ ] Accelerate inference, targeting a 5× speedup
-- [ ] Support 4DGS reconstruction with an open-source method
+### Peak Memory Optimization
+
+- [x] Reduce peak GPU memory below 32 GB through pose precomputation and memory-efficient operators.
+
+### Inference Acceleration
+
+- [x] Achieve up to 1.42× end-to-end speedup by parallelizing pose encoding and VAE processing across GPUs.
+- [ ] Integrate [Sol-Engine](https://nvlabs.github.io/Sana/Sol-Engine/) (expected 2× speedup).
+- [ ] Distill the model for few-step inference (expected 5× speedup).
+
+### Reconstruction
+
+- [x] Support 3DGS reconstruction with nerfstudio.
+- [ ] Support 4DGS reconstruction with an open-source method.
## Citation
diff --git a/fdanyone/model/conditioning.py b/fdanyone/model/conditioning.py
index 2618d7a..0eb2cfa 100644
--- a/fdanyone/model/conditioning.py
+++ b/fdanyone/model/conditioning.py
@@ -4,8 +4,11 @@ from __future__ import annotations
import gc
import logging
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
+from threading import Event
from typing import TYPE_CHECKING
from fdanyone.config import INFERENCE
@@ -193,6 +196,45 @@ class PoseFeatureCache:
target: PoseFeatureBank
+@dataclass(frozen=True)
+class _PoseEncodingJob:
+ """One complete fixed-shape PoseEncoder call."""
+
+ feature_indices: tuple[int, ...]
+ skeletons: tuple[SkeletonVideo, ...]
+ batch_size: int
+ packed_views: int
+ channels_last: bool
+ builder: _PoseFeatureBuilder
+
+
+@dataclass
+class _PoseFeatureBuilder:
+ """Gather independently computed batches into canonical camera order."""
+
+ features: Tensor
+ null_features: Tensor
+
+ @classmethod
+ def create(cls, num_features: int, packed_views: int) -> _PoseFeatureBuilder:
+ import torch
+
+ return cls(
+ features=torch.empty((num_features, *POSE_FEATURE_SHAPE), dtype=torch.bfloat16, device="cpu"),
+ null_features=torch.empty((packed_views, *POSE_FEATURE_SHAPE), dtype=torch.bfloat16, device="cpu"),
+ )
+
+ def store(self, job: _PoseEncodingJob, encoded: Tensor) -> None:
+ for batch_index, feature_index in enumerate(job.feature_indices):
+ self.features[feature_index].copy_(encoded[batch_index])
+ if job.feature_indices[0] == 0:
+ null_start = len(job.feature_indices)
+ self.null_features.copy_(encoded[null_start : null_start + job.packed_views])
+
+ def build(self) -> PoseFeatureBank:
+ return PoseFeatureBank(features=self.features, null_features=self.null_features)
+
+
def _encode_pose_batch(pose_encoder, videos):
"""Encode one bounded batch and return its CPU-resident BF16 features."""
@@ -208,85 +250,86 @@ def _encode_pose_batch(pose_encoder, videos):
return encoded.detach().to(device="cpu").contiguous()
-def _encode_pose_feature_set(
+def _pose_jobs(
*,
- pose_encoder,
- conditioning: Conditioning,
skeletons: tuple[SkeletonVideo, ...],
group_size: int,
packed_views: int,
- device: str,
channels_last: bool,
-) -> PoseFeatureBank:
- """Encode poses in fixed-shape batches capped below the denoising group."""
-
- import torch
+) -> tuple[tuple[_PoseEncodingJob, ...], _PoseFeatureBuilder]:
+ """Plan complete fixed-shape calls and their canonical output owner."""
plan = plan_pose_encoding(
num_features=len(skeletons),
group_size=group_size,
packed_views=packed_views,
)
- features = torch.empty(
- (len(skeletons), *POSE_FEATURE_SHAPE),
- dtype=torch.bfloat16,
- device="cpu",
- )
- null_features = torch.empty(
- (packed_views, *POSE_FEATURE_SHAPE),
- dtype=torch.bfloat16,
- device="cpu",
+ builder = _PoseFeatureBuilder.create(len(skeletons), packed_views)
+ jobs = tuple(
+ _PoseEncodingJob(
+ feature_indices=indices,
+ skeletons=tuple(skeletons[index] for index in indices),
+ batch_size=plan.batch_size,
+ packed_views=packed_views,
+ channels_last=channels_last,
+ builder=builder,
+ )
+ for indices in plan.feature_groups
)
- video_shape = None
- memory_format = torch.channels_last_3d if channels_last else torch.contiguous_format
- for group_index, feature_indices in enumerate(plan.feature_groups):
- batch = None
- for batch_index, feature_index in enumerate(feature_indices):
- skeleton = skeletons[feature_index]
- LOGGER.info("Loading skeleton conditioning from %s", skeleton.path.name)
- decoded = conditioning.load_skeleton_tensor([skeleton]).to(dtype=torch.bfloat16, device="cpu").contiguous()
- if decoded.ndim != 5 or decoded.shape[0] != 1:
- raise FourDAnyoneError(f"Expected one 5D skeleton tensor, got shape {tuple(decoded.shape)}.")
- current_shape = tuple(decoded.shape[1:])
- if video_shape is None:
- video_shape = current_shape
- elif current_shape != video_shape:
- raise FourDAnyoneError(
- f"Skeleton {skeleton.path} has shape {tuple(decoded.shape)}, expected {(1, *video_shape)}."
- )
- if batch is None:
- batch = torch.empty(
- (plan.batch_size, *video_shape),
- dtype=torch.bfloat16,
- device=device,
- memory_format=memory_format,
- ).fill_(-1)
- batch[batch_index].copy_(decoded[0])
- del decoded
+ return jobs, builder
+
+
+def _execute_pose_job(
+ *,
+ job: _PoseEncodingJob,
+ pose_encoder,
+ conditioning: Conditioning,
+ device: str,
+) -> None:
+ """Decode, encode, and gather one bounded pose batch."""
+
+ import torch
- encoded = _encode_pose_batch(pose_encoder, batch)
- for batch_index, feature_index in enumerate(feature_indices):
- features[feature_index].copy_(encoded[batch_index])
- if group_index == 0:
- null_start = len(feature_indices)
- null_features.copy_(encoded[null_start : null_start + packed_views])
- del batch, encoded
+ video_shape = None
+ batch = None
+ memory_format = torch.channels_last_3d if job.channels_last else torch.contiguous_format
+ for batch_index, skeleton in enumerate(job.skeletons):
+ LOGGER.info("Loading skeleton conditioning from %s", skeleton.path.name)
+ decoded = conditioning.load_skeleton_tensor([skeleton]).to(dtype=torch.bfloat16, device="cpu").contiguous()
+ if decoded.ndim != 5 or decoded.shape[0] != 1:
+ raise FourDAnyoneError(f"Expected one 5D skeleton tensor, got shape {tuple(decoded.shape)}.")
+ current_shape = tuple(decoded.shape[1:])
+ if video_shape is None:
+ video_shape = current_shape
+ batch = torch.empty(
+ (job.batch_size, *video_shape),
+ dtype=torch.bfloat16,
+ device=device,
+ memory_format=memory_format,
+ ).fill_(-1)
+ elif current_shape != video_shape:
+ raise FourDAnyoneError(
+ f"Skeleton {skeleton.path} has shape {tuple(decoded.shape)}, expected {(1, *video_shape)}."
+ )
+ batch[batch_index].copy_(decoded[0])
+ del decoded
- return PoseFeatureBank(features=features, null_features=null_features)
+ encoded = _encode_pose_batch(pose_encoder, batch)
+ job.builder.store(job, encoded)
+ del batch, encoded
def build_pose_feature_cache(
*,
conditioning: Conditioning,
checkpoint_path: str | Path,
- device: str,
+ devices: tuple[str, ...],
) -> PoseFeatureCache:
- """Encode every skeleton once before the full DiT is loaded.
+ """Encode all fixed-shape pose jobs on an ordered CUDA device pool.
- PoseEncoder has no cross-view operations. Inputs are therefore split into
- fixed-shape batches of at most six videos, keeping the full-resolution peak
- bounded while preserving a stable CUDA convolution path. Only compact
- output features are retained.
+ One worker owns one PoseEncoder and one full-resolution batch at a time.
+ This bounds host/device memory while independent jobs execute concurrently;
+ builders restore canonical camera order regardless of completion order.
"""
import torch
@@ -296,32 +339,68 @@ def build_pose_feature_cache(
view_plan = conditioning.view_plan
if not conditioning.target_skeletons:
raise FourDAnyoneError("Pose conditioning requires at least one skeleton video.")
-
- pose_encoder = load_pose_encoder(checkpoint_path, device)
- try:
- rcp = None
- if view_plan.enable_rcp:
- rcp = _encode_pose_feature_set(
- pose_encoder=pose_encoder,
- conditioning=conditioning,
- skeletons=conditioning.rcp_skeletons,
- group_size=view_plan.views_per_group,
- packed_views=1,
- device=device,
- channels_last=True,
- )
- target = _encode_pose_feature_set(
- pose_encoder=pose_encoder,
- conditioning=conditioning,
- skeletons=conditioning.target_skeletons,
+ if not devices:
+ raise FourDAnyoneError("Pose conditioning requires at least one CUDA device.")
+
+ rcp_jobs: tuple[_PoseEncodingJob, ...] = ()
+ rcp_builder = None
+ if view_plan.enable_rcp:
+ rcp_jobs, rcp_builder = _pose_jobs(
+ skeletons=conditioning.rcp_skeletons,
group_size=view_plan.views_per_group,
- packed_views=2 if view_plan.enable_rcp else 1,
- device=device,
- channels_last=False,
+ packed_views=1,
+ channels_last=True,
)
- finally:
- del pose_encoder
- gc.collect()
- torch.cuda.empty_cache()
-
- return PoseFeatureCache(rcp=rcp, target=target)
+ target_jobs, target_builder = _pose_jobs(
+ skeletons=conditioning.target_skeletons,
+ group_size=view_plan.views_per_group,
+ packed_views=2 if view_plan.enable_rcp else 1,
+ channels_last=False,
+ )
+ jobs = (*rcp_jobs, *target_jobs)
+ worker_count = min(len(jobs), len(devices))
+ stopped = Event()
+ prototype = load_pose_encoder(checkpoint_path, "cpu")
+ pose_encoders = [prototype]
+ pose_encoders.extend(deepcopy(prototype) for _ in range(worker_count - 1))
+
+ def run(worker_index: int) -> None:
+ device = devices[worker_index]
+ device_index = int(device.removeprefix("cuda:"))
+ torch.cuda.set_device(device_index)
+ pose_encoder = pose_encoders[worker_index]
+ try:
+ pose_encoder.to(device)
+ for job in jobs[worker_index::worker_count]:
+ if stopped.is_set():
+ return
+ _execute_pose_job(
+ job=job,
+ pose_encoder=pose_encoder,
+ conditioning=conditioning,
+ device=device,
+ )
+ except BaseException:
+ stopped.set()
+ raise
+ finally:
+ pose_encoder.to("cpu")
+ torch.cuda.empty_cache()
+
+ with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix="pose") as pool:
+ futures = [pool.submit(run, worker_index) for worker_index in range(worker_count)]
+ try:
+ for future in as_completed(futures):
+ future.result()
+ except BaseException:
+ stopped.set()
+ for future in futures:
+ future.cancel()
+ raise
+
+ pose_encoders.clear()
+ gc.collect()
+ return PoseFeatureCache(
+ rcp=None if rcp_builder is None else rcp_builder.build(),
+ target=target_builder.build(),
+ )
diff --git a/fdanyone/model/inference.py b/fdanyone/model/inference.py
index 404bd7c..9c74cf8 100644
--- a/fdanyone/model/inference.py
+++ b/fdanyone/model/inference.py
@@ -10,34 +10,30 @@ from __future__ import annotations
import gc
import logging
import math
-from collections.abc import Iterable, Iterator
+from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING, TypedDict
-import numpy as np
-from PIL import Image
-
from fdanyone.assets import BaseAssets
from fdanyone.config import INFERENCE
from fdanyone.errors import FourDAnyoneError
from fdanyone.model.conditioning import PoseFeatureBank, PoseFeatureCache, build_pose_feature_cache, load_prompt_context
from fdanyone.model.denoise import denoise_group
from fdanyone.model.distributed import Routes, WorkerReport, denoise_targets_distributed, select_worker_devices
-from fdanyone.model.loader import Denoiser, load_denoiser, load_vae
+from fdanyone.model.loader import Denoiser, load_denoiser
from fdanyone.model.metrics import GenerationMetrics
from fdanyone.model.routing import routing_steps
+from fdanyone.model.vae import VaeExecutor, load_reference_videos
from fdanyone.skeleton.pipeline import Conditioning
-from fdanyone.video import CanonicalClip, write_video
+from fdanyone.video import CanonicalClip
from fdanyone.views import ViewPlan
if TYPE_CHECKING:
from torch import Tensor, nn
- from fdanyone.vendor.diffsynth.models.wan_video_vae import WanVideoVAE38
-
LOGGER = logging.getLogger("fdanyone")
@@ -71,13 +67,18 @@ class GeneratedViews:
@dataclass(frozen=True)
class _GenerationPlan:
view_plan: ViewPlan
- device: str
- device_index: int
- worker_devices: tuple[str, ...]
+ candidate_devices: tuple[str, ...]
+ primary_device: str
+ primary_device_index: int
+ dit_devices: tuple[str, ...]
+
+ @property
+ def view_devices(self) -> tuple[str, ...]:
+ return self.candidate_devices
@property
def distributed(self) -> bool:
- return len(self.worker_devices) > 1
+ return len(self.dit_devices) > 1
@property
def needs_primary_denoiser(self) -> bool:
@@ -105,14 +106,6 @@ def _model_on_device(model: nn.Module, device: str) -> Iterator[nn.Module]:
_empty_cuda_cache()
-def _tiler_kwargs() -> dict[str, bool | tuple[int, int]]:
- return {
- "tiled": INFERENCE.tiled_vae,
- "tile_size": INFERENCE.vae_tile_size,
- "tile_stride": INFERENCE.vae_tile_stride,
- }
-
-
def _bf16_autocast():
"""Match Lightning's ``bf16-mixed`` inference context without Lightning."""
@@ -131,21 +124,12 @@ def _channels_last_source_layout(video):
return video.contiguous(memory_format=torch.channels_last_3d)
-def _encode_videos(vae: WanVideoVAE38, videos: Tensor, device: str) -> Tensor:
- import torch
-
- videos = videos.to(dtype=torch.bfloat16, device=device)
- with torch.inference_mode(), _bf16_autocast():
- latents = vae.encode(videos, device=device, **_tiler_kwargs())
- return latents.detach().to("cpu")
-
-
-def _noise(vae: WanVideoVAE38, num_views: int, num_frames: int, seed: int, device: str) -> Tensor:
+def _noise(vae: VaeExecutor, num_views: int, num_frames: int, seed: int, device: str) -> Tensor:
import torch
shape = (
num_views,
- vae.model.z_dim,
+ vae.latent_channels,
(num_frames - 1) // 4 + 1,
INFERENCE.height // vae.upsampling_factor,
INFERENCE.width // vae.upsampling_factor,
@@ -158,7 +142,7 @@ def _noise(vae: WanVideoVAE38, num_views: int, num_frames: int, seed: int, devic
def _denoise_rcp(
denoiser: Denoiser,
- vae: WanVideoVAE38,
+ vae: VaeExecutor,
src_latents: Tensor,
context: Tensor,
camera_ids: tuple[int, ...],
@@ -197,93 +181,6 @@ def _denoise_rcp(
return latents.detach().to("cpu")
-def _tensor_frames(video) -> Iterable[np.ndarray]:
- """Match DiffSynth's float-to-uint8 truncation exactly."""
-
- frames = video.detach().float().add_(1.0).mul_(127.5).clamp_(0.0, 255.0).to("cpu")
- for frame_index in range(frames.shape[1]):
- yield frames[:, frame_index].permute(1, 2, 0).numpy().astype(np.uint8)
-
-
-def _save_rcp_jpegs(video, camera_id: int, root: Path) -> Path:
- import torchvision.transforms.functional as transform
-
- frame_dir = root / f"{camera_id:06d}"
- frame_dir.mkdir(parents=True, exist_ok=False)
- normalized = video.detach().float().mul(0.5).add_(0.5).clamp_(0.0, 1.0).to("cpu")
- for frame_index in range(normalized.shape[1]):
- image = transform.to_pil_image(normalized[:, frame_index])
- image.save(frame_dir / f"{frame_index:06d}.jpg", quality=INFERENCE.rcp_jpeg_quality)
- return frame_dir
-
-
-def _rcp_reference_video_layout(frame_first_video):
- """Match ``prepare_batch`` for JPEG-backed ``[V,F,C,H,W]`` data."""
-
- if frame_first_video.ndim != 5:
- raise FourDAnyoneError(f"Expected a 5D frame-first video tensor, got shape {tuple(frame_first_video.shape)}.")
- return frame_first_video.permute(0, 2, 1, 3, 4)
-
-
-def _load_rcp_reference_videos(frame_dirs: Iterable[Path], num_frames: int):
- """Decode RCP references exactly like the frozen JPEG-backed input path."""
-
- import torch
- import torchvision.transforms.functional as transform
-
- videos = []
- for frame_dir in frame_dirs:
- frames = []
- for frame_index in range(num_frames):
- path = frame_dir / f"{frame_index:06d}.jpg"
- with Image.open(path) as image:
- frames.append(transform.to_tensor(image.convert("RGB")))
- videos.append(torch.stack(frames, dim=0))
- frame_first_video = torch.stack(videos, dim=0).mul_(2.0).sub_(1.0)
- return _rcp_reference_video_layout(frame_first_video)
-
-
-def _decode_rcp(
- vae: WanVideoVAE38,
- latents: Tensor,
- camera_ids: tuple[int, ...],
- output_dir: Path,
- clip: CanonicalClip,
- device: str,
-) -> tuple[tuple[Path, ...], tuple[Path, ...]]:
- import torch
-
- if latents.shape[0] != len(camera_ids):
- raise FourDAnyoneError(f"RCP decode expected {len(camera_ids)} latent views, got {latents.shape[0]}.")
- frame_root = output_dir / "frames"
- video_root = output_dir / "videos"
- frame_root.mkdir(parents=True, exist_ok=False)
- video_root.mkdir(parents=True, exist_ok=False)
- frame_outputs: list[Path] = []
- video_outputs: list[Path] = []
- with torch.inference_mode(), _bf16_autocast():
- for latent_index, camera_id in enumerate(camera_ids):
- LOGGER.info("Decoding RCP camera %02d", camera_id)
- video = vae.decode(
- latents[latent_index : latent_index + 1].to(dtype=torch.bfloat16, device=device),
- device=device,
- **_tiler_kwargs(),
- )[0]
- frame_outputs.append(_save_rcp_jpegs(video, camera_id, frame_root))
- video_outputs.append(
- write_video(
- _tensor_frames(video),
- video_root / f"{camera_id:02d}.mp4",
- clip.fps,
- crf=INFERENCE.target_h264_crf,
- preset=INFERENCE.h264_preset,
- )
- )
- del video
- torch.cuda.empty_cache()
- return tuple(frame_outputs), tuple(video_outputs)
-
-
def _denoise_targets_single(
denoiser: Denoiser,
src_latents: Tensor,
@@ -333,39 +230,6 @@ def _denoise_targets_single(
return latents.detach().to("cpu")
-def _decode_targets(
- vae: WanVideoVAE38,
- latents: Tensor,
- output_dir: Path,
- clip: CanonicalClip,
- device: str,
-) -> tuple[Path, ...]:
- import torch
-
- video_root = output_dir / "videos"
- video_root.mkdir(parents=True, exist_ok=False)
- outputs: list[Path] = []
- with torch.inference_mode(), _bf16_autocast():
- for camera_id in range(latents.shape[0]):
- LOGGER.info("Decoding target camera %02d", camera_id)
- video = vae.decode(
- latents[camera_id : camera_id + 1].to(dtype=torch.bfloat16, device=device),
- device=device,
- **_tiler_kwargs(),
- )[0]
- path = write_video(
- _tensor_frames(video),
- video_root / f"{camera_id:02d}.mp4",
- clip.fps,
- crf=INFERENCE.target_h264_crf,
- preset=INFERENCE.h264_preset,
- )
- outputs.append(path)
- del video
- torch.cuda.empty_cache()
- return tuple(outputs)
-
-
def _resolve_generation_plan(
clip: CanonicalClip,
conditioning: Conditioning,
@@ -387,29 +251,30 @@ def _resolve_generation_plan(
if len(conditioning.rcp_skeletons) != len(view_plan.rcp_camera_ids):
raise FourDAnyoneError("RCP skeleton count does not match the resolved view plan.")
- device = devices[0]
- device_index = int(device.removeprefix("cuda:"))
- worker_devices = select_worker_devices(devices, view_plan.num_groups)
- LOGGER.info("Using %s (%s)", device, torch.cuda.get_device_name(device_index))
- if len(worker_devices) < len(devices):
+ primary_device = devices[0]
+ primary_device_index = int(primary_device.removeprefix("cuda:"))
+ dit_devices = select_worker_devices(devices, view_plan.num_groups)
+ LOGGER.info("Using %s (%s)", primary_device, torch.cuda.get_device_name(primary_device_index))
+ if len(dit_devices) < len(devices):
LOGGER.info(
- "Using %d of %d candidate GPUs for %d target groups",
- len(worker_devices),
+ "Using %d of %d candidate GPUs for DiT and all %d for independent view stages",
+ len(dit_devices),
+ len(devices),
len(devices),
- view_plan.num_groups,
)
return _GenerationPlan(
view_plan=view_plan,
- device=device,
- device_index=device_index,
- worker_devices=worker_devices,
+ candidate_devices=devices,
+ primary_device=primary_device,
+ primary_device_index=primary_device_index,
+ dit_devices=dit_devices,
)
def _generate_rcp_and_references(
*,
denoiser: Denoiser,
- vae: WanVideoVAE38,
+ vae: VaeExecutor,
source_latents: Tensor,
context: Tensor,
pose_cache: PoseFeatureCache,
@@ -424,7 +289,7 @@ def _generate_rcp_and_references(
rcp_pose_features = pose_cache.rcp
if rcp_pose_features is None:
raise FourDAnyoneError("RCP was enabled without precomputed proposal pose features.")
- with metrics.stage("rcp_denoise"), _model_on_device(denoiser.model, plan.device):
+ with metrics.stage("rcp_denoise"), _model_on_device(denoiser.model, plan.primary_device):
rcp_latents = _denoise_rcp(
denoiser,
vae,
@@ -432,27 +297,41 @@ def _generate_rcp_and_references(
context,
plan.view_plan.rcp_camera_ids,
rcp_pose_features,
- plan.device,
+ plan.primary_device,
seed,
)
- with metrics.stage("rcp_decode_and_reference_encode"), _model_on_device(vae, plan.device):
+ with metrics.stage("rcp_decode_and_publish"):
rcp_root = root / "rcp"
rcp_root.mkdir()
- frame_dirs, rcp_videos = _decode_rcp(
- vae,
+ published = vae.publish_rcp(
rcp_latents,
plan.view_plan.rcp_camera_ids,
rcp_root,
clip,
- plan.device,
)
+ _merge_view_stage_peak(metrics, "rcp_decode_and_publish", vae)
+
+ with metrics.stage("rcp_reference_load"):
# The released model consumes four JPEG-decoded proposal views. Keep
# that numerical boundary even though the decoded tensors are local.
- reference_videos = _load_rcp_reference_videos(frame_dirs[:4], INFERENCE.num_frames)
- reference_latents = _encode_videos(vae, reference_videos, plan.device)
+ reference_videos = load_reference_videos(published.frame_directories[:4], INFERENCE.num_frames)
+
+ with metrics.stage("reference_encode"):
+ reference_latents = vae.encode(reference_videos)
target_sources = torch.cat([source_latents, reference_latents], dim=0)
- return target_sources, rcp_videos
+ _merge_view_stage_peak(metrics, "reference_encode", vae)
+ return target_sources, published.videos
+
+
+def _merge_view_stage_peak(metrics: GenerationMetrics, stage: str, vae: VaeExecutor) -> None:
+ if not vae.last_peak_vram_bytes:
+ return
+ metrics.merge_cuda_peak(
+ stage,
+ allocated_bytes=max(peak["allocated"] for peak in vae.last_peak_vram_bytes.values()),
+ reserved_bytes=max(peak["reserved"] for peak in vae.last_peak_vram_bytes.values()),
+ )
def _target_routes(view_plan: ViewPlan) -> Routes:
@@ -516,7 +395,7 @@ def generate_views(
plan = _resolve_generation_plan(clip, conditioning, devices, seed)
root = Path(output_dir).expanduser().resolve()
root.mkdir(parents=True, exist_ok=False)
- metrics = GenerationMetrics(plan.device_index)
+ metrics = GenerationMetrics(plan.primary_device_index)
with metrics.stage("prompt"):
context = load_prompt_context(assets.prompt_context)
@@ -525,104 +404,115 @@ def generate_views(
pose_cache = build_pose_feature_cache(
conditioning=conditioning,
checkpoint_path=checkpoint_path,
- device=plan.device,
+ devices=plan.view_devices,
)
with metrics.stage("model_load"):
denoiser = load_denoiser(checkpoint_path=checkpoint_path) if plan.needs_primary_denoiser else None
- vae = load_vae(assets.vae)
-
- with metrics.stage("source_encode"), _model_on_device(vae, plan.device):
- source_video = _channels_last_source_layout(conditioning.load_source_tensor())
- source_latents = _encode_videos(vae, source_video, plan.device)
- del source_video
-
- rcp_videos: tuple[Path, ...] = ()
- target_sources = source_latents
- if plan.view_plan.enable_rcp:
- if denoiser is None:
- raise RuntimeError("RCP requires a primary-process denoiser.")
- target_sources, rcp_videos = _generate_rcp_and_references(
- denoiser=denoiser,
- vae=vae,
- source_latents=source_latents,
- context=context,
- pose_cache=pose_cache,
- plan=plan,
- root=root,
- clip=clip,
- seed=seed,
- metrics=metrics,
- )
+ vae = VaeExecutor.load(assets.vae, plan.view_devices)
- parallelism = None
- with metrics.stage("target_denoise"):
- routes = _target_routes(plan.view_plan)
- initial_latents = _noise(
- vae,
- plan.view_plan.num_target_views,
- INFERENCE.num_frames,
- seed,
- plan.device,
- )
- if plan.distributed:
- if denoiser is not None:
- del denoiser
- initial_latents = initial_latents.to("cpu")
- _empty_cuda_cache()
- target_latents, parallelism = _denoise_targets_multi_gpu(
- target_sources=target_sources,
+ try:
+ with metrics.stage("source_encode"):
+ source_video = _channels_last_source_layout(conditioning.load_source_tensor())
+ source_latents = vae.encode(source_video)
+ del source_video
+ _merge_view_stage_peak(metrics, "source_encode", vae)
+
+ rcp_videos: tuple[Path, ...] = ()
+ target_sources = source_latents
+ if plan.view_plan.enable_rcp:
+ if denoiser is None:
+ raise RuntimeError("RCP requires a primary-process denoiser.")
+ target_sources, rcp_videos = _generate_rcp_and_references(
+ denoiser=denoiser,
+ vae=vae,
+ source_latents=source_latents,
context=context,
- initial_latents=initial_latents,
- pose_features=pose_cache.target,
- routes=routes,
- checkpoint_path=checkpoint_path,
+ pose_cache=pose_cache,
+ plan=plan,
root=root,
- devices=plan.worker_devices,
- candidate_devices=devices,
- num_groups=plan.view_plan.num_groups,
+ clip=clip,
+ seed=seed,
+ metrics=metrics,
)
- else:
- if denoiser is None:
- raise RuntimeError("Single-GPU target generation requires a primary-process denoiser.")
- with _model_on_device(denoiser.model, plan.device):
- target_latents = _denoise_targets_single(
- denoiser,
- target_sources,
- context,
- pose_cache.target,
- initial_latents,
- routes,
- plan.device,
+ del source_latents
+ # Parallel VAE replicas are stage-local. Retaining only the prototype
+ # bounds parent host memory while distributed DiT workers load.
+ vae.release_replicas()
+ target_pose_features = pose_cache.target
+ del pose_cache
+
+ parallelism = None
+ with metrics.stage("target_denoise"):
+ routes = _target_routes(plan.view_plan)
+ initial_latents = _noise(
+ vae,
+ plan.view_plan.num_target_views,
+ INFERENCE.num_frames,
+ seed,
+ plan.primary_device,
+ )
+ if plan.distributed:
+ denoiser = None
+ initial_latents = initial_latents.to("cpu")
+ _empty_cuda_cache()
+ target_latents, parallelism = _denoise_targets_multi_gpu(
+ target_sources=target_sources,
+ context=context,
+ initial_latents=initial_latents,
+ pose_features=target_pose_features,
+ routes=routes,
+ checkpoint_path=checkpoint_path,
+ root=root,
+ devices=plan.dit_devices,
+ candidate_devices=plan.candidate_devices,
+ num_groups=plan.view_plan.num_groups,
)
- del denoiser
- del initial_latents
-
- if parallelism is not None:
- workers = parallelism["workers"]
- metrics.merge_cuda_peak(
- "target_denoise",
- allocated_bytes=max(int(worker["peak_vram_allocated_bytes"]) for worker in workers),
- reserved_bytes=max(int(worker["peak_vram_reserved_bytes"]) for worker in workers),
+ else:
+ if denoiser is None:
+ raise RuntimeError("Single-GPU target generation requires a primary-process denoiser.")
+ with _model_on_device(denoiser.model, plan.primary_device):
+ target_latents = _denoise_targets_single(
+ denoiser,
+ target_sources,
+ context,
+ target_pose_features,
+ initial_latents,
+ routes,
+ plan.primary_device,
+ )
+ denoiser = None
+ del initial_latents
+
+ if parallelism is not None:
+ workers = parallelism["workers"]
+ metrics.merge_cuda_peak(
+ "target_denoise",
+ allocated_bytes=max(int(worker["peak_vram_allocated_bytes"]) for worker in workers),
+ reserved_bytes=max(int(worker["peak_vram_reserved_bytes"]) for worker in workers),
+ )
+ del target_pose_features, target_sources, context
+
+ with metrics.stage("target_decode_and_publish"):
+ target_root = root / "target"
+ target_root.mkdir()
+ target_videos = vae.publish_targets(target_latents, target_root, clip)
+ _merge_view_stage_peak(metrics, "target_decode_and_publish", vae)
+
+ result = GeneratedViews(
+ rcp_videos=rcp_videos,
+ target_videos=target_videos,
+ view_plan=plan.view_plan,
+ seed=seed,
+ device=plan.primary_device,
+ elapsed_seconds=metrics.elapsed_seconds,
+ stage_peak_vram_bytes=metrics.stage_peak_vram_bytes,
+ peak_vram_allocated_bytes=metrics.peak_vram_allocated_bytes,
+ peak_vram_reserved_bytes=metrics.peak_vram_reserved_bytes,
+ parallelism=parallelism,
)
+ finally:
+ vae.close()
+ _empty_cuda_cache()
- with metrics.stage("target_decode"):
- target_root = root / "target"
- target_root.mkdir()
- with _model_on_device(vae, plan.device):
- target_videos = _decode_targets(vae, target_latents, target_root, clip, plan.device)
-
- del target_latents, target_sources, source_latents, context, pose_cache, vae
- _empty_cuda_cache()
- return GeneratedViews(
- rcp_videos=rcp_videos,
- target_videos=target_videos,
- view_plan=plan.view_plan,
- seed=seed,
- device=plan.device,
- elapsed_seconds=metrics.elapsed_seconds,
- stage_peak_vram_bytes=metrics.stage_peak_vram_bytes,
- peak_vram_allocated_bytes=metrics.peak_vram_allocated_bytes,
- peak_vram_reserved_bytes=metrics.peak_vram_reserved_bytes,
- parallelism=parallelism,
- )
+ return result
diff --git a/fdanyone/model/vae.py b/fdanyone/model/vae.py
new file mode 100644
index 0000000..a6e6ba3
--- /dev/null
+++ b/fdanyone/model/vae.py
@@ -0,0 +1,358 @@
+"""Per-view VAE execution and publication for generation stages."""
+
+from __future__ import annotations
+
+import gc
+import logging
+from collections.abc import Callable, Iterable
+from concurrent.futures import Future, ThreadPoolExecutor, as_completed
+from copy import deepcopy
+from dataclasses import dataclass
+from pathlib import Path
+from threading import BoundedSemaphore, Event
+from typing import TYPE_CHECKING, TypeVar
+
+import numpy as np
+from PIL import Image
+
+from fdanyone.config import INFERENCE
+from fdanyone.errors import FourDAnyoneError
+from fdanyone.video import CanonicalClip, write_video
+
+if TYPE_CHECKING:
+ from torch import Tensor
+
+ from fdanyone.vendor.diffsynth.models.wan_video_vae import WanVideoVAE38
+
+LOGGER = logging.getLogger("fdanyone")
+
+Output = TypeVar("Output")
+
+
+@dataclass(frozen=True)
+class PublishedRcp:
+ """Canonical RCP frame directories and videos."""
+
+ frame_directories: tuple[Path, ...]
+ videos: tuple[Path, ...]
+
+
+@dataclass(frozen=True)
+class _DecodedView:
+ """Host-owned values consumed by publication sinks."""
+
+ video: Tensor | None
+ rgb_frames: tuple[np.ndarray, ...]
+
+
+def _bf16_autocast():
+ import torch
+
+ return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
+
+
+def _rgb_frames(video: Tensor) -> tuple[np.ndarray, ...]:
+ """Freeze the released CUDA scaling boundary before CPU publication."""
+
+ scaled = video.detach().float().add_(1.0).mul_(127.5).clamp_(0.0, 255.0).to(device="cpu")
+ return tuple(
+ scaled[:, frame_index].permute(1, 2, 0).numpy().astype(np.uint8) for frame_index in range(scaled.shape[1])
+ )
+
+
+def _save_jpegs(video: Tensor, camera_id: int, root: Path) -> Path:
+ import torchvision.transforms.functional as transform
+
+ frame_dir = root / f"{camera_id:06d}"
+ frame_dir.mkdir(parents=True, exist_ok=False)
+ for frame_index in range(video.shape[1]):
+ normalized = video[:, frame_index].float().mul_(0.5).add_(0.5).clamp_(0.0, 1.0)
+ image = transform.to_pil_image(normalized)
+ image.save(frame_dir / f"{frame_index:06d}.jpg", quality=INFERENCE.rcp_jpeg_quality)
+ return frame_dir
+
+
+def load_reference_videos(frame_dirs: Iterable[Path], num_frames: int) -> Tensor:
+ """Load the frozen JPEG reference boundary as ``[V,C,F,H,W]``."""
+
+ import torch
+ import torchvision.transforms.functional as transform
+
+ videos = []
+ for frame_dir in frame_dirs:
+ frames = []
+ for frame_index in range(num_frames):
+ path = frame_dir / f"{frame_index:06d}.jpg"
+ with Image.open(path) as image:
+ frames.append(transform.to_tensor(image.convert("RGB")))
+ videos.append(torch.stack(frames, dim=0))
+ frame_first = torch.stack(videos, dim=0).mul_(2.0).sub_(1.0)
+ return frame_first.permute(0, 2, 1, 3, 4)
+
+
+class VaeExecutor:
+ """Run independent views on an ordered CUDA device pool.
+
+ Each worker owns one model replica and processes a deterministic strided
+ subset of camera indices. Models return to CPU between stages so the same
+ replicas can be reused without competing with the DiT for device memory.
+ """
+
+ def __init__(self, model: WanVideoVAE38, devices: tuple[str, ...]) -> None:
+ if not devices:
+ raise FourDAnyoneError("VAE execution requires at least one CUDA device.")
+ self.devices = devices
+ self._models = [model]
+ self.last_peak_vram_bytes: dict[str, dict[str, int]] = {}
+
+ @classmethod
+ def load(cls, path: str | Path, devices: tuple[str, ...]) -> VaeExecutor:
+ from fdanyone.model.loader import load_vae
+
+ return cls(load_vae(path), devices)
+
+ @property
+ def latent_channels(self) -> int:
+ return int(self._models[0].model.z_dim)
+
+ @property
+ def upsampling_factor(self) -> int:
+ return int(self._models[0].upsampling_factor)
+
+ def _ensure_models(self, count: int) -> None:
+ while len(self._models) < count:
+ self._models.append(deepcopy(self._models[0]))
+
+ @staticmethod
+ def _worker_count(num_views: int, num_devices: int) -> int:
+ if num_views <= 0:
+ raise FourDAnyoneError("VAE execution requires at least one view.")
+ return min(num_views, num_devices)
+
+ @staticmethod
+ def _worker_indices(num_views: int, worker_index: int, worker_count: int) -> tuple[int, ...]:
+ return tuple(range(worker_index, num_views, worker_count))
+
+ def _run_workers(
+ self,
+ *,
+ num_views: int,
+ operation: Callable[[WanVideoVAE38, str, tuple[int, ...], Event], None],
+ stopped: Event | None = None,
+ ) -> None:
+ import torch
+
+ worker_count = self._worker_count(num_views, len(self.devices))
+ self._ensure_models(worker_count)
+ stopped = Event() if stopped is None else stopped
+ peaks: dict[str, dict[str, int]] = {}
+
+ def run(worker_index: int) -> None:
+ device = self.devices[worker_index]
+ device_index = int(device.removeprefix("cuda:"))
+ model = self._models[worker_index]
+ indices = self._worker_indices(num_views, worker_index, worker_count)
+ torch.cuda.set_device(device_index)
+ torch.cuda.reset_peak_memory_stats(device_index)
+ try:
+ model.to(device)
+ operation(model, device, indices, stopped)
+ torch.cuda.synchronize(device_index)
+ peaks[device] = {
+ "allocated": int(torch.cuda.max_memory_allocated(device_index)),
+ "reserved": int(torch.cuda.max_memory_reserved(device_index)),
+ }
+ except BaseException:
+ stopped.set()
+ raise
+ finally:
+ model.to("cpu")
+ torch.cuda.empty_cache()
+
+ with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix="vae") as pool:
+ futures = [pool.submit(run, worker_index) for worker_index in range(worker_count)]
+ try:
+ for future in as_completed(futures):
+ future.result()
+ except BaseException:
+ stopped.set()
+ for future in futures:
+ future.cancel()
+ raise
+ self.last_peak_vram_bytes = peaks
+
+ @staticmethod
+ def _encode_view(model: WanVideoVAE38, video: Tensor, device: str) -> Tensor:
+ import torch
+
+ if INFERENCE.tiled_vae:
+ tile_size = tuple(size * model.upsampling_factor for size in INFERENCE.vae_tile_size)
+ tile_stride = tuple(stride * model.upsampling_factor for stride in INFERENCE.vae_tile_stride)
+ batched = video.unsqueeze(0).to(dtype=torch.bfloat16, device="cpu")
+ return model.tiled_encode(batched, device, tile_size, tile_stride)
+ batched = video.unsqueeze(0).to(dtype=torch.bfloat16, device=device)
+ return model.encode_view(batched)
+
+ @staticmethod
+ def _decode_view(model: WanVideoVAE38, latent: Tensor, device: str) -> Tensor:
+ import torch
+
+ if INFERENCE.tiled_vae:
+ batched = latent.unsqueeze(0).to(dtype=torch.bfloat16, device="cpu")
+ return model.tiled_decode(
+ batched,
+ device,
+ INFERENCE.vae_tile_size,
+ INFERENCE.vae_tile_stride,
+ )
+ batched = latent.unsqueeze(0).to(dtype=torch.bfloat16, device=device)
+ return model.decode_view(batched)
+
+ def encode(self, videos: Tensor) -> Tensor:
+ """Encode CPU-resident views and gather latents by input index."""
+
+ import torch
+
+ if videos.ndim != 5 or videos.device.type != "cpu":
+ raise FourDAnyoneError(f"VAE input must be CPU [V,C,F,H,W], got {tuple(videos.shape)} on {videos.device}.")
+ outputs: list[Tensor | None] = [None] * videos.shape[0]
+
+ def operation(model: WanVideoVAE38, device: str, indices: tuple[int, ...], stopped: Event) -> None:
+ with torch.inference_mode(), _bf16_autocast():
+ for index in indices:
+ if stopped.is_set():
+ return
+ encoded = self._encode_view(model, videos[index], device)
+ outputs[index] = encoded[0].detach().to(device="cpu").contiguous()
+ del encoded
+
+ self._run_workers(num_views=videos.shape[0], operation=operation)
+ if any(output is None for output in outputs):
+ raise RuntimeError("VAE encode completed without every canonical view.")
+ return torch.stack(outputs) # type: ignore[arg-type]
+
+ def _decode_and_publish(
+ self,
+ latents: Tensor,
+ sink: Callable[[int, _DecodedView], Output],
+ *,
+ retain_video: bool,
+ ) -> tuple[Output, ...]:
+ import torch
+
+ if latents.ndim != 5 or latents.device.type != "cpu":
+ raise FourDAnyoneError(
+ f"VAE latents must be CPU [V,C,F,H,W], got {tuple(latents.shape)} on {latents.device}."
+ )
+ num_views = int(latents.shape[0])
+ worker_count = self._worker_count(num_views, len(self.devices))
+ slots = BoundedSemaphore(worker_count)
+ sink_futures: list[Future[Output] | None] = [None] * num_views
+ stopped = Event()
+
+ with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix="video-codec") as codec_pool:
+
+ def release_slot(future: Future[Output]) -> None:
+ if future.exception() is not None:
+ stopped.set()
+ slots.release()
+
+ def operation(
+ model: WanVideoVAE38,
+ device: str,
+ indices: tuple[int, ...],
+ worker_stop: Event,
+ ) -> None:
+ with torch.inference_mode(), _bf16_autocast():
+ for index in indices:
+ if worker_stop.is_set():
+ return
+ slots.acquire()
+ try:
+ decoded = self._decode_view(model, latents[index], device)
+ device_video = decoded[0].detach()
+ rgb_frames = _rgb_frames(device_video)
+ video = device_video.to(device="cpu").contiguous() if retain_video else None
+ del decoded, device_video
+ future = codec_pool.submit(
+ sink,
+ index,
+ _DecodedView(video=video, rgb_frames=rgb_frames),
+ )
+ future.add_done_callback(release_slot)
+ sink_futures[index] = future
+ except BaseException:
+ slots.release()
+ stopped.set()
+ raise
+
+ self._run_workers(num_views=num_views, operation=operation, stopped=stopped)
+ for future in sink_futures:
+ if future is not None and future.done() and future.exception() is not None:
+ future.result()
+ if any(future is None for future in sink_futures):
+ raise RuntimeError("VAE decode completed without every canonical view.")
+ return tuple(future.result() for future in sink_futures if future is not None)
+
+ def publish_rcp(
+ self,
+ latents: Tensor,
+ camera_ids: tuple[int, ...],
+ output_dir: Path,
+ clip: CanonicalClip,
+ ) -> PublishedRcp:
+ if latents.shape[0] != len(camera_ids):
+ raise FourDAnyoneError(f"RCP decode expected {len(camera_ids)} latent views, got {latents.shape[0]}.")
+ frame_root = output_dir / "frames"
+ video_root = output_dir / "videos"
+ frame_root.mkdir(parents=True, exist_ok=False)
+ video_root.mkdir(parents=True, exist_ok=False)
+
+ def publish(index: int, decoded: _DecodedView) -> tuple[Path, Path]:
+ camera_id = camera_ids[index]
+ LOGGER.info("Publishing RCP camera %02d", camera_id)
+ if decoded.video is None:
+ raise RuntimeError("RCP publication requires the decoded BF16 video.")
+ frame_dir = _save_jpegs(decoded.video, camera_id, frame_root)
+ video_path = write_video(
+ iter(decoded.rgb_frames),
+ video_root / f"{camera_id:02d}.mp4",
+ clip.fps,
+ crf=INFERENCE.target_h264_crf,
+ preset=INFERENCE.h264_preset,
+ )
+ return frame_dir, video_path
+
+ published = self._decode_and_publish(latents, publish, retain_video=True)
+ return PublishedRcp(
+ frame_directories=tuple(item[0] for item in published),
+ videos=tuple(item[1] for item in published),
+ )
+
+ def publish_targets(self, latents: Tensor, output_dir: Path, clip: CanonicalClip) -> tuple[Path, ...]:
+ video_root = output_dir / "videos"
+ video_root.mkdir(parents=True, exist_ok=False)
+
+ def publish(camera_id: int, decoded: _DecodedView) -> Path:
+ LOGGER.info("Publishing target camera %02d", camera_id)
+ return write_video(
+ iter(decoded.rgb_frames),
+ video_root / f"{camera_id:02d}.mp4",
+ clip.fps,
+ crf=INFERENCE.target_h264_crf,
+ preset=INFERENCE.h264_preset,
+ )
+
+ return self._decode_and_publish(latents, publish, retain_video=False)
+
+ def release_replicas(self) -> None:
+ """Keep one CPU model while releasing stage-local parallel replicas."""
+
+ del self._models[1:]
+ gc.collect()
+
+ def close(self) -> None:
+ """Release all CPU replicas after the final VAE stage."""
+
+ self._models.clear()
+ gc.collect()
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_dit.py b/fdanyone/vendor/diffsynth/models/wan_video_dit.py
index e621487..6b29440 100644
--- a/fdanyone/vendor/diffsynth/models/wan_video_dit.py
+++ b/fdanyone/vendor/diffsynth/models/wan_video_dit.py
@@ -23,13 +23,6 @@ try:
except (ImportError, OSError, RuntimeError):
FLASH_ATTN_3_AVAILABLE = False
-try:
- import flash_attn
-
- FLASH_ATTN_2_AVAILABLE = True
-except (ImportError, OSError, RuntimeError):
- FLASH_ATTN_2_AVAILABLE = False
-
try:
from sageattention import sageattn
@@ -52,24 +45,25 @@ NORM_EPSILON = 1e-6
# gives the same one-view production chunk as the original 768 MiB
# single-allocation limit, while naming the actual temporary budget.
ROPE_TEMPORARY_BUDGET_BYTES = 1536 * 1024**2
+ATTENTION_BACKEND_PRIORITY = ("flash_attn_3", "sageattention", "sdpa")
def get_attention_backend() -> str:
"""Return the implementation selected by the release auto policy."""
- if FLASH_ATTN_3_AVAILABLE:
- return "flash_attn_3"
- if FLASH_ATTN_2_AVAILABLE:
- return "flash_attn_2"
- if SAGE_ATTN_AVAILABLE:
- return "sageattention"
- return "sdpa"
+ availability = {
+ "flash_attn_3": FLASH_ATTN_3_AVAILABLE,
+ "sageattention": SAGE_ATTN_AVAILABLE,
+ "sdpa": True,
+ }
+ return next(backend for backend in ATTENTION_BACKEND_PRIORITY if availability[backend])
-def flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_heads: int) -> torch.Tensor:
- """Evaluate attention with the fastest installed release backend."""
+def attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_heads: int) -> torch.Tensor:
+ """Evaluate attention with the backend selected by the release policy."""
- if FLASH_ATTN_3_AVAILABLE:
+ backend = get_attention_backend()
+ if backend == "flash_attn_3":
q = rearrange(q, "b s (n d) -> b s n d", n=num_heads)
k = rearrange(k, "b s (n d) -> b s n d", n=num_heads)
v = rearrange(v, "b s (n d) -> b s n d", n=num_heads)
@@ -77,17 +71,10 @@ def flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_heads
if isinstance(output, tuple):
output = output[0]
return rearrange(output, "b s n d -> b s (n d)", n=num_heads)
- if FLASH_ATTN_2_AVAILABLE:
- q = rearrange(q, "b s (n d) -> b s n d", n=num_heads)
- k = rearrange(k, "b s (n d) -> b s n d", n=num_heads)
- v = rearrange(v, "b s (n d) -> b s n d", n=num_heads)
- output = flash_attn.flash_attn_func(q, k, v)
- return rearrange(output, "b s n d -> b s (n d)", n=num_heads)
-
q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
- output = sageattn(q, k, v) if SAGE_ATTN_AVAILABLE else F.scaled_dot_product_attention(q, k, v)
+ output = sageattn(q, k, v) if backend == "sageattention" else F.scaled_dot_product_attention(q, k, v)
return rearrange(output, "b n s d -> b s (n d)", n=num_heads)
@@ -195,7 +182,7 @@ class SelfAttention(nn.Module):
v = self.v(x)
q = rope_apply(q, freqs, self.num_heads)
k = rope_apply(k, freqs, self.num_heads)
- return self.o(flash_attention(q, k, v, self.num_heads))
+ return self.o(attention(q, k, v, self.num_heads))
class CrossAttention(nn.Module):
@@ -213,7 +200,7 @@ class CrossAttention(nn.Module):
q = self.norm_q(self.q(x))
k = self.norm_k(self.k(context))
v = self.v(context)
- return self.o(flash_attention(q, k, v, self.num_heads))
+ return self.o(attention(q, k, v, self.num_heads))
class DiTBlock(nn.Module):
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_vae.py b/fdanyone/vendor/diffsynth/models/wan_video_vae.py
index 48aa72b..9569c2d 100644
--- a/fdanyone/vendor/diffsynth/models/wan_video_vae.py
+++ b/fdanyone/vendor/diffsynth/models/wan_video_vae.py
@@ -3,7 +3,6 @@ from einops import rearrange, repeat
import torch
import torch.nn as nn
import torch.nn.functional as F
-from tqdm import tqdm
CACHE_T = 2
@@ -987,17 +986,19 @@ class VideoVAE_(nn.Module):
t = x.shape[2]
iter_ = 1 + (t - 1) // 4
+ chunks = []
for i in range(iter_):
self._enc_conv_idx = [0]
if i == 0:
- out = self.encoder(x[:, :, :1, :, :],
- feat_cache=self._enc_feat_map,
- feat_idx=self._enc_conv_idx)
+ chunk = self.encoder(x[:, :, :1, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
else:
- out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
- feat_cache=self._enc_feat_map,
- feat_idx=self._enc_conv_idx)
- out = torch.cat([out, out_], 2)
+ chunk = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
+ chunks.append(chunk)
+ out = chunks[0] if len(chunks) == 1 else torch.cat(chunks, dim=2)
mu, log_var = self.conv1(out).chunk(2, dim=1)
if isinstance(scale[0], torch.Tensor):
scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
@@ -1020,17 +1021,19 @@ class VideoVAE_(nn.Module):
z = z / scale[1] + scale[0]
iter_ = z.shape[2]
x = self.conv2(z)
+ chunks = []
for i in range(iter_):
self._conv_idx = [0]
if i == 0:
- out = self.decoder(x[:, :, i:i + 1, :, :],
- feat_cache=self._feat_map,
- feat_idx=self._conv_idx)
+ chunk = self.decoder(x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx)
else:
- out_ = self.decoder(x[:, :, i:i + 1, :, :],
- feat_cache=self._feat_map,
- feat_idx=self._conv_idx)
- out = torch.cat([out, out_], 2) # may add tensor offload
+ chunk = self.decoder(x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx)
+ chunks.append(chunk)
+ out = chunks[0] if len(chunks) == 1 else torch.cat(chunks, dim=2)
return out
def reparameterize(self, mu, log_var):
@@ -1203,48 +1206,20 @@ class WanVideoVAE(nn.Module):
return values
- def single_encode(self, video, device):
- video = video.to(device)
- x = self.model.encode(video, self.scale)
- return x
+ def encode_view(self, video):
+ """Encode one device-resident ``[1,C,F,H,W]`` view."""
+ if video.ndim != 5 or video.shape[0] != 1:
+ raise ValueError(f"VAE encode expects one batched view, got {tuple(video.shape)}.")
+ return self.model.encode(video, self.scale)
- def single_decode(self, hidden_state, device):
- hidden_state = hidden_state.to(device)
- video = self.model.decode(hidden_state, self.scale)
- return video.clamp_(-1, 1)
+ def decode_view(self, hidden_state):
+ """Decode one device-resident ``[1,C,F,H,W]`` latent view."""
- def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
- videos = [video.to("cpu") for video in videos]
- hidden_states = []
- for video in tqdm(videos, desc="VAE encoding", disable=not tiled):
- video = video.unsqueeze(0)
- if tiled:
- tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor)
- tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor)
- hidden_state = self.tiled_encode(video, device, tile_size, tile_stride)
- else:
- hidden_state = self.single_encode(video, device)
- hidden_state = hidden_state.squeeze(0)
- hidden_states.append(hidden_state)
- hidden_states = torch.stack(hidden_states)
- return hidden_states
-
-
- def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
- hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states]
- videos = []
- for hidden_state in tqdm(hidden_states, desc="VAE decoding", disable=not tiled):
- hidden_state = hidden_state.unsqueeze(0)
- if tiled:
- video = self.tiled_decode(hidden_state, device, tile_size, tile_stride)
- else:
- video = self.single_decode(hidden_state, device)
- video = video.squeeze(0)
- videos.append(video)
- videos = torch.stack(videos)
- return videos
+ if hidden_state.ndim != 5 or hidden_state.shape[0] != 1:
+ raise ValueError(f"VAE decode expects one batched view, got {tuple(hidden_state.shape)}.")
+ return self.model.decode(hidden_state, self.scale).clamp_(-1, 1)
@staticmethod
@@ -1300,17 +1275,19 @@ class VideoVAE38_(VideoVAE_):
x = patchify(x, patch_size=2)
t = x.shape[2]
iter_ = 1 + (t - 1) // 4
+ chunks = []
for i in range(iter_):
self._enc_conv_idx = [0]
if i == 0:
- out = self.encoder(x[:, :, :1, :, :],
- feat_cache=self._enc_feat_map,
- feat_idx=self._enc_conv_idx)
+ chunk = self.encoder(x[:, :, :1, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
else:
- out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
- feat_cache=self._enc_feat_map,
- feat_idx=self._enc_conv_idx)
- out = torch.cat([out, out_], 2)
+ chunk = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
+ chunks.append(chunk)
+ out = chunks[0] if len(chunks) == 1 else torch.cat(chunks, dim=2)
mu, log_var = self.conv1(out).chunk(2, dim=1)
if isinstance(scale[0], torch.Tensor):
scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
@@ -1334,18 +1311,20 @@ class VideoVAE38_(VideoVAE_):
z = z / scale[1] + scale[0]
iter_ = z.shape[2]
x = self.conv2(z)
+ chunks = []
for i in range(iter_):
self._conv_idx = [0]
if i == 0:
- out = self.decoder(x[:, :, i:i + 1, :, :],
- feat_cache=self._feat_map,
- feat_idx=self._conv_idx,
- first_chunk=True)
+ chunk = self.decoder(x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx,
+ first_chunk=True)
else:
- out_ = self.decoder(x[:, :, i:i + 1, :, :],
- feat_cache=self._feat_map,
- feat_idx=self._conv_idx)
- out = torch.cat([out, out_], 2)
+ chunk = self.decoder(x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx)
+ chunks.append(chunk)
+ out = chunks[0] if len(chunks) == 1 else torch.cat(chunks, dim=2)
out = unpatchify(out, patch_size=2)
self.clear_cache()
return out
diff --git a/inference.py b/inference.py
index a70ffb2..16a34f4 100644
--- a/inference.py
+++ b/inference.py
@@ -50,8 +50,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.
- gpu_ids: GPU IDs to use for parallel denoising. Omit to use all
- visible GPUs.
+ gpu_ids: GPU IDs used for parallel pose/VAE view stages and target
+ denoising. Omit to use all visible GPUs.
target_fps: auto preserves the input clock unless it divides evenly
to 24, 25, or 30 FPS; a positive number requests an explicit FPS.
start_time: Clip start time on the input timeline, in seconds.