Skip to content

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

Reduce inference GPU memory usage (#15)

Yudong Jine8243b74be34
diff --git a/README.md b/README.md
index e15437f..e266acf 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,10 @@
<p align="center">4DAnyone turns a casual monocular video into multi-view videos, enabling downstream 4DGS reconstruction.</p>
+## News
+
+- **2026-08-28**: Significantly reduced GPU memory usage while slightly improving speed. See [Inference performance](docs/inference_performance.md) for details.
+
## Installation
```bash
diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md
index 9106b38..983615c 100644
--- a/docs/THIRD_PARTY_NOTICES.md
+++ b/docs/THIRD_PARTY_NOTICES.md
@@ -51,10 +51,9 @@ The companion Hugging Face repository distributes eight modified 121-frame excer
`UPSTREAM.md`, `UPSTREAM.patch`, and `VENDORED_FILES.txt` in that directory record the exact provenance, research patch, and retained file set.
-Two retained DiffSynth files carry code-level upstream attribution:
+One retained DiffSynth file carries additional code-level upstream attribution:
- `models/wan_video_pose_encoder.py` derives its pose network from [Tencent/MimicMotion](https://github.com/Tencent/MimicMotion/tree/c053153a1d124abae8c08568925ae88debc63001), Copyright Tencent, under Apache-2.0.
-- `models/wan_video_camera_controller.py` contains camera-coordinate helpers from [hehao13/CameraCtrl](https://github.com/hehao13/CameraCtrl), under Apache-2.0. The exact retained bytes remain identified through the DiffSynth public-base revision above.
## Sapiens2-derived Goliath/MHR schema material
@@ -71,9 +70,9 @@ 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. The Wan VAE and UMT5-derived frozen prompt conditioning, 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`. The latter is used offline to produce the fixed prompt-conditioning tensor; its T5 weights and tokenizer are not part of reader downloads. 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.
diff --git a/docs/inference_performance.md b/docs/inference_performance.md
index 490ba9f..806b546 100644
--- a/docs/inference_performance.md
+++ b/docs/inference_performance.md
@@ -3,7 +3,6 @@
This page reports inference efficiency for the [6-view full-orbit](../README.md#6-view-full-orbit) example using:
```bash
-PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
python inference.py \
--video_path "data/source/pexels/2785536-uhd_2160_3840_25fps.mp4" \
--views_per_layer 6
@@ -22,10 +21,10 @@ This table compares denoising time across attention backends.
| GPU | SDPA (min) | FlashAttention-3 (min) | SageAttention (min) | Peak CUDA allocated (GiB) | GPU memory (GiB) |
| --- | ---: | ---: | ---: | ---: | ---: |
-| H200 | 9.17 | 7.84 | 7.86 | 43.34 | 140.40 |
-| H20-3E | 20.59 | 16.62 | 13.91 | 43.34 | 140.40 |
-| RTX 5880 Ada | 20.85 | — | 18.01 | 43.32 | 47.99 |
-| RTX A6000 | 22.93 | — | 22.75 | 43.32 | 47.99 |
+| H200 | 8.87 | 7.55 | 7.59 | 25.37 | 139.81 |
+| H20-3E | 19.55 | 15.63 | 12.89 | 25.37 | 139.81 |
+| RTX 5880 Ada | 20.28 | — | 17.51 | 24.21 | 47.37 |
+| RTX A6000 | 22.41 | — | 21.78 | 24.06 | 47.53 |
> [!NOTE]
> SageAttention results use the official `sageattn` entry point, which automatically dispatches an architecture-specific kernel for each GPU.
diff --git a/fdanyone/assets.py b/fdanyone/assets.py
index ef8a097..95be1ee 100644
--- a/fdanyone/assets.py
+++ b/fdanyone/assets.py
@@ -13,7 +13,7 @@ from pathlib import Path
from fdanyone.errors import AssetError
HF_REPO_ID = "AntResearch/4DAnyone"
-HF_REVISION = "7850985888b56aabf09e69480b73248f1a76bcbe"
+HF_REVISION = "ba4888adf7f1359b0d5133532df308cb58287351"
BIREFNET_REPO_ID = "ZhengPeng7/BiRefNet"
BIREFNET_REVISION = "e2bf8e4460fc8fa32bba5ea4d94b3233d367b0e4"
@@ -28,12 +28,7 @@ BIREFNET_FILES = (
CHECKPOINT = "4danyone/model.safetensors"
MHR70_REGRESSOR = "4danyone/smplx_to_goliath70.pt"
WAN_VAE = "4danyone/Wan2.2_VAE.pth"
-TEXT_ENCODER = "4danyone/models_t5_umt5-xxl-enc-bf16.pth"
-TOKENIZER_DIR = "4danyone/umt5-xxl"
-TOKENIZER_FILES = tuple(
- f"{TOKENIZER_DIR}/{name}"
- for name in ("special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json")
-)
+PROMPT_CONTEXT = "4danyone/prompt_context.safetensors"
GVHMR_CHECKPOINT = "gvhmr/gvhmr_siga24_release.ckpt"
HMR2_CHECKPOINT = "gvhmr/epoch=10-step=25000.ckpt"
@@ -47,8 +42,7 @@ MODEL_FILES = (
CHECKPOINT,
MHR70_REGRESSOR,
WAN_VAE,
- TEXT_ENCODER,
- *TOKENIZER_FILES,
+ PROMPT_CONTEXT,
GVHMR_CHECKPOINT,
HMR2_CHECKPOINT,
VITPOSE_CHECKPOINT,
@@ -81,8 +75,7 @@ GVHMR_LINKS = (
@dataclass(frozen=True)
class BaseAssets:
vae: Path
- text_encoder: Path
- tokenizer: Path
+ prompt_context: Path
def _require_file(path: Path, label: str, command: str) -> Path:
@@ -128,13 +121,10 @@ def resolve_perceptual_vgg19(model_dir: str | Path = "models") -> Path:
def resolve_base_assets(model_dir: str | Path = "models") -> BaseAssets:
- """Resolve the local VAE, T5 encoder, and tokenizer."""
+ """Resolve the local VAE and frozen prompt conditioning."""
root = Path(model_dir).expanduser()
- for relative in TOKENIZER_FILES:
- _require_file(root / relative, "Tokenizer file", "scripts/download_model.py")
return BaseAssets(
vae=_require_file(root / WAN_VAE, "VAE", "scripts/download_model.py"),
- text_encoder=_require_file(root / TEXT_ENCODER, "Text encoder", "scripts/download_model.py"),
- tokenizer=(root / TOKENIZER_DIR).expanduser().resolve(),
+ prompt_context=_require_file(root / PROMPT_CONTEXT, "Prompt conditioning", "scripts/download_model.py"),
)
diff --git a/fdanyone/config.py b/fdanyone/config.py
index 60a3414..355c543 100644
--- a/fdanyone/config.py
+++ b/fdanyone/config.py
@@ -31,17 +31,6 @@ class InferenceConfig:
num_inference_steps: int = 24
denoising_strength: float = 1.0
scheduler_shift: float = 5.0
- use_mvs_attention: bool = True
- mvs_attention_range: tuple[int | None, int | None, int | None] = (0, None, 1)
- disable_video_attention: bool = False
- use_4d_attention: bool = False
- use_source_self_attention: bool = False
- use_source_cross_attention: bool = False
- freqs_src_shift: int = 121
- use_pose_encoder: bool = True
- pose_encoder_type: str = "rgb"
- use_camera_encoder: bool = False
- use_lbm: bool = False
tiled_vae: bool = False
vae_tile_size: tuple[int, int] = (52, 30)
vae_tile_stride: tuple[int, int] = (26, 15)
diff --git a/fdanyone/device.py b/fdanyone/device.py
index 55e0b4c..1a83383 100644
--- a/fdanyone/device.py
+++ b/fdanyone/device.py
@@ -2,10 +2,26 @@
from __future__ import annotations
-from collections.abc import Sequence
+import os
+from collections.abc import MutableMapping, Sequence
from fdanyone.errors import ConfigurationError
+CUDA_ALLOCATOR_CONF = "PYTORCH_CUDA_ALLOC_CONF"
+CUDA_MAX_SPLIT_SIZE_MB = 4096
+
+
+def configure_inference_cuda_allocator(environment: MutableMapping[str, str] | None = None) -> None:
+ """Keep the DiT's reusable FFN allocation from being split into small blocks."""
+
+ environment = os.environ if environment is None else environment
+ current = environment.get(CUDA_ALLOCATOR_CONF, "").strip()
+ options = tuple(option.strip() for option in current.split(",") if option.strip())
+ if any(option.partition(":")[0] == "max_split_size_mb" for option in options):
+ return
+ required = f"max_split_size_mb:{CUDA_MAX_SPLIT_SIZE_MB}"
+ environment[CUDA_ALLOCATOR_CONF] = f"{current},{required}" if current else required
+
def select_cuda_device(device: str) -> tuple[str, int]:
"""Validate, select, and normalize one CUDA device."""
diff --git a/fdanyone/model/conditioning.py b/fdanyone/model/conditioning.py
new file mode 100644
index 0000000..2618d7a
--- /dev/null
+++ b/fdanyone/model/conditioning.py
@@ -0,0 +1,327 @@
+"""Frozen, timestep-independent conditioning used by the denoiser."""
+
+from __future__ import annotations
+
+import gc
+import logging
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from fdanyone.config import INFERENCE
+from fdanyone.errors import AssetError, FourDAnyoneError
+
+if TYPE_CHECKING:
+ from torch import Tensor
+
+ from fdanyone.skeleton.pipeline import Conditioning, SkeletonVideo
+
+LOGGER = logging.getLogger("fdanyone")
+
+PROMPT_CONTEXT_FORMAT = "fdanyone.prompt_context"
+PROMPT_CONTEXT_VERSION = "2"
+PROMPT_CONTEXT_KEY = "context"
+PROMPT_CONTEXT_SHAPE = (1, 512, 4096)
+PROMPT_CONTEXT_SOURCE_REPO = "Wan-AI/Wan2.1-T2V-1.3B"
+PROMPT_CONTEXT_SOURCE_REVISION = "3f40b6dc4ca5c02dd23c9db74d9d2ccb82903b86"
+POSE_FEATURE_SHAPE = (3072, 31, 40, 22)
+POSE_ENCODER_BATCH_LIMIT = 6
+
+
+def load_prompt_context(path: str | Path):
+ """Load and validate the frozen UMT5 output consumed by the DiT."""
+
+ import torch
+
+ try:
+ from safetensors import safe_open
+ except ImportError as exc:
+ raise AssetError("safetensors is required to load prompt conditioning.") from exc
+
+ resolved = Path(path).expanduser().resolve()
+ try:
+ with safe_open(str(resolved), framework="pt", device="cpu") as tensors:
+ keys = tuple(tensors.keys())
+ metadata = tensors.metadata() or {}
+ if keys != (PROMPT_CONTEXT_KEY,):
+ raise AssetError(f"Prompt conditioning must contain only {PROMPT_CONTEXT_KEY!r}, got {keys}.")
+ context = tensors.get_tensor(PROMPT_CONTEXT_KEY)
+ except AssetError:
+ raise
+ except Exception as exc:
+ raise AssetError(f"Could not load prompt conditioning from {resolved}: {exc}") from exc
+
+ expected_metadata = {
+ "format": PROMPT_CONTEXT_FORMAT,
+ "version": PROMPT_CONTEXT_VERSION,
+ "prompt": INFERENCE.prompt,
+ "source_repo": PROMPT_CONTEXT_SOURCE_REPO,
+ "source_revision": PROMPT_CONTEXT_SOURCE_REVISION,
+ }
+ mismatched = {
+ key: (metadata.get(key), expected)
+ for key, expected in expected_metadata.items()
+ if metadata.get(key) != expected
+ }
+ if mismatched:
+ raise AssetError(f"Prompt conditioning metadata does not match the released method: {mismatched}.")
+ for key in ("text_encoder_sha256", "tokenizer_manifest_sha256"):
+ value = metadata.get(key, "")
+ if len(value) != 64 or any(character not in "0123456789abcdef" for character in value):
+ raise AssetError(f"Prompt conditioning metadata has no valid {key} provenance hash.")
+ if tuple(context.shape) != PROMPT_CONTEXT_SHAPE or context.dtype != torch.bfloat16:
+ raise AssetError(
+ "Prompt conditioning must be BF16 with shape "
+ f"{PROMPT_CONTEXT_SHAPE}, got dtype={context.dtype}, shape={tuple(context.shape)}."
+ )
+ return context.contiguous()
+
+
+@dataclass(frozen=True)
+class PoseEncodingPlan:
+ """Fixed-shape PoseEncoder batches for one ordered camera layout."""
+
+ batch_size: int
+ packed_views: int
+ feature_groups: tuple[tuple[int, ...], ...]
+
+
+def plan_pose_encoding(*, num_features: int, group_size: int, packed_views: int) -> PoseEncodingPlan:
+ """Partition camera indices while reserving packed-view null inputs.
+
+ Every PoseEncoder call uses the same batch shape. This preserves the
+ released CUDA convolution path while bounding full-resolution inputs to six
+ videos. Camera indices remain the only identity used after decoding.
+ """
+
+ if num_features <= 0:
+ raise FourDAnyoneError(f"Pose conditioning requires at least one camera, got {num_features}.")
+ if group_size <= 0 or num_features % group_size:
+ raise FourDAnyoneError(
+ f"Pose camera count {num_features} must be divisible by positive group size {group_size}."
+ )
+ if packed_views <= 0:
+ raise FourDAnyoneError(f"Pose conditioning requires packed views, got {packed_views}.")
+
+ batch_size = min(POSE_ENCODER_BATCH_LIMIT, group_size + packed_views)
+ feature_capacity = batch_size - packed_views
+ if feature_capacity <= 0:
+ raise FourDAnyoneError(f"Pose batch limit {POSE_ENCODER_BATCH_LIMIT} cannot hold {packed_views} packed views.")
+ groups = tuple(
+ tuple(range(start, min(start + feature_capacity, num_features)))
+ for start in range(0, num_features, feature_capacity)
+ )
+ return PoseEncodingPlan(batch_size=batch_size, packed_views=packed_views, feature_groups=groups)
+
+
+@dataclass(frozen=True)
+class PoseFeatureBank:
+ """Owned CPU BF16 features in canonical camera-index order."""
+
+ features: Tensor
+ null_features: Tensor
+
+ def __post_init__(self) -> None:
+ import torch
+
+ feature_shape = tuple(self.features.shape)
+ null_shape = tuple(self.null_features.shape)
+ if self.features.ndim != 5 or feature_shape[1:] != POSE_FEATURE_SHAPE:
+ raise FourDAnyoneError(f"Pose features must have shape [views, {POSE_FEATURE_SHAPE}], got {feature_shape}.")
+ if self.null_features.ndim != 5 or null_shape[1:] != POSE_FEATURE_SHAPE or null_shape[0] <= 0:
+ raise FourDAnyoneError(
+ f"Null pose features must have shape [packed_views, {POSE_FEATURE_SHAPE}], got {null_shape}."
+ )
+ if self.features.dtype != torch.bfloat16 or self.null_features.dtype != torch.bfloat16:
+ raise FourDAnyoneError("Pose and null features must use BF16.")
+ if self.features.device.type != "cpu" or self.null_features.device.type != "cpu":
+ raise FourDAnyoneError("Pose feature banks must remain CPU-resident between denoising calls.")
+ for label, tensor in (("pose", self.features), ("null pose", self.null_features)):
+ exact_storage_bytes = tensor.numel() * tensor.element_size()
+ if (
+ not tensor.is_contiguous()
+ or tensor.storage_offset() != 0
+ or tensor.untyped_storage().nbytes() != exact_storage_bytes
+ ):
+ raise FourDAnyoneError(f"The {label} feature tensor must own one exact contiguous storage.")
+
+ @property
+ def num_features(self) -> int:
+ return int(self.features.shape[0])
+
+ @property
+ def num_packed_views(self) -> int:
+ return int(self.null_features.shape[0])
+
+ def allocate_group(self, size: int, device: str) -> Tensor:
+ """Allocate one reusable GPU group buffer."""
+
+ import torch
+
+ if size <= 0:
+ raise FourDAnyoneError(f"A pose feature group must be non-empty, got {size}.")
+ return torch.empty((size, *POSE_FEATURE_SHAPE), dtype=self.features.dtype, device=device)
+
+ def copy_group(self, indices: tuple[int, ...], destination: Tensor) -> None:
+ """Copy canonical camera features into a reusable device buffer."""
+
+ if not indices:
+ raise FourDAnyoneError("A pose feature group cannot be empty.")
+ expected = (len(indices), *POSE_FEATURE_SHAPE)
+ if tuple(destination.shape) != expected or destination.dtype != self.features.dtype:
+ raise FourDAnyoneError(
+ f"Pose destination must have dtype={self.features.dtype}, shape={expected}; "
+ f"got dtype={destination.dtype}, shape={tuple(destination.shape)}."
+ )
+ invalid = tuple(index for index in indices if index < 0 or index >= self.num_features)
+ if invalid:
+ raise FourDAnyoneError(
+ f"Pose feature indices {invalid} are outside camera range 0..{self.num_features - 1}."
+ )
+ for output_index, feature_index in enumerate(indices):
+ destination[output_index].copy_(self.features[feature_index])
+
+ def null_on(self, device: str) -> Tensor:
+ return self.null_features.to(device=device)
+
+
+@dataclass(frozen=True)
+class PoseFeatureCache:
+ """Pose features grouped by the RCP and target denoising layouts."""
+
+ rcp: PoseFeatureBank | None
+ target: PoseFeatureBank
+
+
+def _encode_pose_batch(pose_encoder, videos):
+ """Encode one bounded batch and return its CPU-resident BF16 features."""
+
+ import torch
+
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16):
+ encoded = pose_encoder(videos)
+ expected = (videos.shape[0], *POSE_FEATURE_SHAPE)
+ if tuple(encoded.shape) != expected or encoded.dtype != torch.bfloat16:
+ raise FourDAnyoneError(
+ f"PoseEncoder returned dtype={encoded.dtype}, shape={tuple(encoded.shape)}; expected BF16 {expected}."
+ )
+ return encoded.detach().to(device="cpu").contiguous()
+
+
+def _encode_pose_feature_set(
+ *,
+ 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
+
+ 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",
+ )
+ 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
+
+ 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
+
+ return PoseFeatureBank(features=features, null_features=null_features)
+
+
+def build_pose_feature_cache(
+ *,
+ conditioning: Conditioning,
+ checkpoint_path: str | Path,
+ device: str,
+) -> PoseFeatureCache:
+ """Encode every skeleton once before the full DiT is loaded.
+
+ 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.
+ """
+
+ import torch
+
+ from fdanyone.model.loader import load_pose_encoder
+
+ 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,
+ group_size=view_plan.views_per_group,
+ packed_views=2 if view_plan.enable_rcp else 1,
+ device=device,
+ channels_last=False,
+ )
+ finally:
+ del pose_encoder
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ return PoseFeatureCache(rcp=rcp, target=target)
diff --git a/fdanyone/model/denoise.py b/fdanyone/model/denoise.py
index 97af955..a138e40 100644
--- a/fdanyone/model/denoise.py
+++ b/fdanyone/model/denoise.py
@@ -2,21 +2,36 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
-def denoise_group(pipe, latents, source, context, skeletons, step_index: int):
+if TYPE_CHECKING:
+ from torch import Tensor
+
+ from fdanyone.model.loader import Denoiser
+
+
+def denoise_group(
+ denoiser: Denoiser,
+ latents: Tensor,
+ source: Tensor,
+ context: Tensor,
+ pose_features: Tensor,
+ null_pose_feature: Tensor,
+ step_index: int,
+) -> Tensor:
"""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)
+ timestep = denoiser.scheduler.timesteps[step_index]
+ batched_timestep = timestep.unsqueeze(0).to(dtype=denoiser.dtype, device=latents.device)
batched_timestep = torch.cat([batched_timestep] * latents.shape[0], dim=0)
- prediction = pipe.dit(
+ prediction = denoiser.model(
x=latents,
x_src=source,
timestep=batched_timestep,
- skeletons=skeletons,
+ pose_features=pose_features,
+ null_pose_feature=null_pose_feature,
context=context,
- **pipe.prepare_extra_input(latents),
)
- return pipe.scheduler.step(prediction, timestep, latents)
+ return denoiser.scheduler.step(prediction, timestep, latents)
diff --git a/fdanyone/model/distributed.py b/fdanyone/model/distributed.py
index 06b595a..2b753bf 100644
--- a/fdanyone/model/distributed.py
+++ b/fdanyone/model/distributed.py
@@ -14,20 +14,38 @@ import math
import os
import socket
import time
-from collections.abc import Callable, Iterable, Sequence
+from collections.abc import Sequence
from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path
-from typing import TypeVar
+from typing import TYPE_CHECKING, TypedDict
from fdanyone.errors import FourDAnyoneError
+if TYPE_CHECKING:
+ from torch import Tensor
+
+ from fdanyone.model.conditioning import PoseFeatureBank
+ from fdanyone.model.loader import Denoiser
+
LOGGER = logging.getLogger("fdanyone")
CameraGroup = tuple[int, ...]
StepGroups = tuple[CameraGroup, ...]
Routes = tuple[StepGroups, ...]
-ResultT = TypeVar("ResultT")
+
+
+class WorkerReport(TypedDict):
+ """Per-rank measurements published by a distributed denoising worker."""
+
+ rank: int
+ device: str
+ device_name: str
+ attention_backend: str
+ model_load_seconds: float
+ denoise_seconds: float
+ peak_vram_allocated_bytes: int
+ peak_vram_reserved_bytes: int
@dataclass(frozen=True)
@@ -38,7 +56,7 @@ class DistributedDenoiseRequest:
routes: Routes
denoising_strength: float
scheduler_shift: float
- skeleton_shape: tuple[int, ...]
+ pose_feature_shape: tuple[int, ...]
init_method: str
@@ -93,77 +111,199 @@ def validate_routes(routes: Routes, num_views: int) -> None:
)
-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."""
+def _resolve_empty_workspace(path: str | Path) -> Path:
+ """Validate the caller-owned transient directory used by spawned ranks."""
+
+ root = Path(path).expanduser().resolve()
+ if not root.is_dir():
+ raise ValueError(f"Distributed work_dir must be an existing directory: {root}")
+ if any(root.iterdir()):
+ raise ValueError(f"Distributed work_dir must be empty: {root}")
+ return root
- import torch
- items = tuple(skeletons)
- if not items:
- raise FourDAnyoneError("Distributed target denoising requires at least one skeleton video.")
+def _write_pose_feature_file(pose_features: PoseFeatureBank, path: Path) -> tuple[int, ...]:
+ """Write precomputed target pose features to a worker-shared BF16 tensor."""
+
+ import torch
- 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:]))
+ features = pose_features.features
+ if features.ndim != 5 or features.shape[0] <= 0:
+ raise FourDAnyoneError("Distributed target denoising requires at least one pose feature.")
+ shape = tuple(features.shape)
numel = math.prod(shape)
with path.open("xb") as handle:
- handle.truncate(numel * first.element_size())
+ handle.truncate(numel * features.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
+ mapped.copy_(features)
del mapped
return shape
+@dataclass
+class _WorkerState:
+ """CUDA tensors and collectives owned by one spawned NCCL rank."""
+
+ rank: int
+ request: DistributedDenoiseRequest
+ denoiser: Denoiser
+ device: str
+ device_index: int
+ source: Tensor
+ context: Tensor
+ null_pose_feature: Tensor
+ pose_features: Tensor
+ latents: Tensor | None
+ pose_feature_batch: Tensor
+ latent_tail: tuple[int, ...]
+
+ @property
+ def is_primary(self) -> bool:
+ return self.rank == 0
+
+ @property
+ def world_size(self) -> int:
+ return len(self.request.devices)
+
+ def _scatter_latents(self, wave: StepGroups) -> Tensor:
+ import torch
+ import torch.distributed as dist
+
+ local_input = torch.empty(
+ (self.pose_feature_batch.shape[0], *self.latent_tail),
+ dtype=self.denoiser.dtype,
+ device=self.device,
+ )
+ scatter_list = None
+ if self.is_primary:
+ if self.latents is None:
+ raise RuntimeError("The primary distributed rank does not own canonical latents.")
+ scatter_list = [torch.zeros_like(local_input) for _ in range(self.world_size)]
+ for worker_index, group in enumerate(wave):
+ index = torch.tensor(group, dtype=torch.long, device=self.device)
+ scatter_list[worker_index].copy_(torch.index_select(self.latents, 0, index))
+ dist.scatter(local_input, scatter_list=scatter_list, src=0)
+ return local_input
+
+ def _denoise_local_group(self, local_input: Tensor, wave: StepGroups, step_index: int) -> Tensor:
+ import torch
+
+ if self.rank >= len(wave):
+ return torch.zeros_like(local_input)
+
+ from fdanyone.model.denoise import denoise_group
+
+ group = wave[self.rank]
+ for output_index, camera_id in enumerate(group):
+ self.pose_feature_batch[output_index].copy_(self.pose_features[camera_id])
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16):
+ return denoise_group(
+ self.denoiser,
+ local_input,
+ self.source,
+ self.context,
+ self.pose_feature_batch,
+ self.null_pose_feature,
+ step_index,
+ )
+
+ def _gather_and_commit(self, local_result: Tensor, wave: StepGroups) -> None:
+ import torch
+ import torch.distributed as dist
+
+ gathered = [torch.empty_like(local_result) for _ in range(self.world_size)] if self.is_primary else None
+ dist.gather(local_result, gather_list=gathered, dst=0)
+ if not self.is_primary:
+ return
+ if self.latents is None or gathered is None:
+ raise RuntimeError("The primary distributed rank cannot commit gathered latents.")
+ for group, result in zip(wave, gathered[: len(wave)], strict=True):
+ index = torch.tensor(group, dtype=torch.long, device=self.device)
+ self.latents.index_copy_(0, index, result)
+
+ def denoise(self) -> None:
+ """Run every route step, committing a complete step before TCR moves on."""
+
+ import torch.distributed as dist
+
+ for step_index, groups in enumerate(self.request.routes):
+ for wave in group_waves(groups, self.world_size):
+ local_input = self._scatter_latents(wave)
+ local_result = self._denoise_local_group(local_input, wave, step_index)
+ self._gather_and_commit(local_result, wave)
+ del local_input, local_result
+ dist.barrier(device_ids=[self.device_index])
+ if self.is_primary:
+ LOGGER.info("Completed target denoising step %d/%d", step_index + 1, len(self.request.routes))
+
+
+def _load_worker_state(rank: int, request: DistributedDenoiseRequest, denoiser: Denoiser) -> _WorkerState:
+ import torch
+
+ device = request.devices[rank]
+ payload = torch.load(
+ Path(request.work_dir) / "inputs.pt",
+ map_location="cpu",
+ weights_only=True,
+ mmap=True,
+ )
+ group_size = len(request.routes[0][0])
+ pose_features = torch.from_file(
+ str(Path(request.work_dir) / "pose_features.bf16"),
+ shared=False,
+ size=math.prod(request.pose_feature_shape),
+ dtype=torch.bfloat16,
+ ).view(request.pose_feature_shape)
+ denoiser.scheduler.set_timesteps(
+ len(request.routes),
+ denoising_strength=request.denoising_strength,
+ shift=request.scheduler_shift,
+ )
+ return _WorkerState(
+ rank=rank,
+ request=request,
+ denoiser=denoiser,
+ device=device,
+ device_index=int(device.removeprefix("cuda:")),
+ source=payload["source"].to(dtype=denoiser.dtype, device=device),
+ context=payload["context"].to(dtype=denoiser.dtype, device=device),
+ null_pose_feature=payload["null_pose_feature"].to(dtype=denoiser.dtype, device=device),
+ pose_features=pose_features,
+ latents=payload["initial_latents"].to(dtype=denoiser.dtype, device=device) if rank == 0 else None,
+ pose_feature_batch=torch.empty(
+ (group_size, *request.pose_feature_shape[1:]),
+ dtype=denoiser.dtype,
+ device=device,
+ ),
+ latent_tail=tuple(payload["initial_latents"].shape[1:]),
+ )
+
+
+def _publish_worker_result(state: _WorkerState, report: WorkerReport) -> None:
+ import torch
+
+ root = Path(state.request.work_dir)
+ if state.is_primary:
+ if state.latents is None:
+ raise RuntimeError("The primary distributed rank has no target latents to publish.")
+ temporary = root / ".target_latents.pt.tmp"
+ torch.save(state.latents.detach().to("cpu"), temporary)
+ os.replace(temporary, root / "target_latents.pt")
+ (root / f"rank-{state.rank}.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
+
+
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
@@ -181,8 +321,9 @@ def _worker(rank: int, request: DistributedDenoiseRequest) -> None:
resolved_backend = get_attention_backend()
model_started = time.monotonic()
- pipe = load_denoiser(checkpoint_path=request.checkpoint_path, device=device)
- pipe.dit.to(device)
+ denoiser = load_denoiser(checkpoint_path=request.checkpoint_path)
+ denoiser.model.to(device)
+ torch.cuda.synchronize(device_index)
model_load_seconds = time.monotonic() - model_started
dist.init_process_group(
@@ -193,104 +334,14 @@ def _worker(rank: int, request: DistributedDenoiseRequest) -> None:
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,
- )
+ state = _load_worker_state(rank, request, denoiser)
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,
- )
+ state.denoise()
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 = {
+ report: WorkerReport = {
"rank": rank,
"device": device,
"device_name": torch.cuda.get_device_name(device_index),
@@ -300,8 +351,7 @@ def _worker(rank: int, request: DistributedDenoiseRequest) -> None:
"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")
+ _publish_worker_result(state, report)
dist.barrier(device_ids=[device_index])
finally:
if dist.is_initialized():
@@ -310,17 +360,17 @@ def _worker(rank: int, request: DistributedDenoiseRequest) -> None:
def denoise_targets_distributed(
*,
- src_latents,
- context,
- initial_latents,
- conditioning,
+ src_latents: Tensor,
+ context: Tensor,
+ initial_latents: Tensor,
+ pose_features: PoseFeatureBank,
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]]]:
+) -> tuple[Tensor, list[WorkerReport]]:
"""Prepare shared inputs, launch NCCL workers, and return canonical latents."""
import torch
@@ -334,20 +384,19 @@ def denoise_targets_distributed(
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)
+ root = _resolve_empty_workspace(work_dir)
torch.save(
{
"source": src_latents.detach().to("cpu").contiguous(),
"context": context.detach().to("cpu").contiguous(),
+ "null_pose_feature": pose_features.null_features,
"initial_latents": initial_latents.detach().to("cpu").contiguous(),
},
root / "inputs.pt",
)
- skeleton_shape = _write_skeleton_tensor_file(
- conditioning,
- conditioning.target_skeletons,
- root / "skeletons.bf16",
+ pose_feature_shape = _write_pose_feature_file(
+ pose_features,
+ root / "pose_features.bf16",
)
request = DistributedDenoiseRequest(
checkpoint_path=str(Path(checkpoint_path).expanduser().resolve()),
@@ -356,7 +405,7 @@ def denoise_targets_distributed(
routes=routes,
denoising_strength=denoising_strength,
scheduler_shift=scheduler_shift,
- skeleton_shape=skeleton_shape,
+ pose_feature_shape=pose_feature_shape,
init_method=f"tcp://127.0.0.1:{_free_local_port()}",
)
LOGGER.info(
@@ -374,7 +423,7 @@ def denoise_targets_distributed(
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 = []
+ reports: list[WorkerReport] = []
for rank in range(len(devices)):
report_path = root / f"rank-{rank}.json"
if not report_path.is_file():
diff --git a/fdanyone/model/inference.py b/fdanyone/model/inference.py
index a90d2e3..404bd7c 100644
--- a/fdanyone/model/inference.py
+++ b/fdanyone/model/inference.py
@@ -10,10 +10,12 @@ from __future__ import annotations
import gc
import logging
import math
-import time
-from collections.abc import Iterable
+from collections.abc import Iterable, 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
@@ -21,17 +23,35 @@ 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 denoise_targets_distributed, select_worker_devices
-from fdanyone.model.loader import load_pipeline
+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.metrics import GenerationMetrics
from fdanyone.model.routing import routing_steps
-from fdanyone.skeleton.pipeline import Conditioning, SkeletonVideo
+from fdanyone.skeleton.pipeline import Conditioning
from fdanyone.video import CanonicalClip, write_video
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")
+class ParallelismReport(TypedDict):
+ """The target-denoising topology and measurements written to metadata."""
+
+ backend: str
+ candidate_devices: list[str]
+ used_devices: list[str]
+ groups_per_step: int
+ waves_per_step: int
+ workers: list[WorkerReport]
+
+
@dataclass(frozen=True)
class GeneratedViews:
"""Paths and measurements produced by one resolved view plan."""
@@ -42,9 +62,26 @@ class GeneratedViews:
seed: int
device: str
elapsed_seconds: dict[str, float]
+ stage_peak_vram_bytes: dict[str, dict[str, int]]
peak_vram_allocated_bytes: int
peak_vram_reserved_bytes: int
- parallelism: dict[str, object] | None = None
+ parallelism: ParallelismReport | None = None
+
+
+@dataclass(frozen=True)
+class _GenerationPlan:
+ view_plan: ViewPlan
+ device: str
+ device_index: int
+ worker_devices: tuple[str, ...]
+
+ @property
+ def distributed(self) -> bool:
+ return len(self.worker_devices) > 1
+
+ @property
+ def needs_primary_denoiser(self) -> bool:
+ return self.view_plan.enable_rcp or not self.distributed
def _empty_cuda_cache() -> None:
@@ -55,17 +92,20 @@ def _empty_cuda_cache() -> None:
torch.cuda.empty_cache()
-def _move_model(model, device: str) -> None:
- model.to(device)
- _empty_cuda_cache()
-
+@contextmanager
+def _model_on_device(model: nn.Module, device: str) -> Iterator[nn.Module]:
+ """Keep one model resident for exactly one exception-safe stage."""
-def _offload_model(model) -> None:
- model.to("cpu")
+ model.to(device)
_empty_cuda_cache()
+ try:
+ yield model
+ finally:
+ model.to("cpu")
+ _empty_cuda_cache()
-def _tiler_kwargs() -> dict:
+def _tiler_kwargs() -> dict[str, bool | tuple[int, int]]:
return {
"tiled": INFERENCE.tiled_vae,
"tile_size": INFERENCE.vae_tile_size,
@@ -91,115 +131,67 @@ def _channels_last_source_layout(video):
return video.contiguous(memory_format=torch.channels_last_3d)
-def _encode_prompt(pipe, device: str):
+def _encode_videos(vae: WanVideoVAE38, videos: Tensor, device: str) -> Tensor:
import torch
- _move_model(pipe.text_encoder, device)
+ videos = videos.to(dtype=torch.bfloat16, device=device)
with torch.inference_mode(), _bf16_autocast():
- context = pipe.prompter.encode_prompt(INFERENCE.prompt, positive=True, device=device)
- context = context.detach().to("cpu")
- _offload_model(pipe.text_encoder)
- return context
-
-
-def _encode_videos(pipe, videos, device: str):
- import torch
-
- videos = videos.to(dtype=pipe.torch_dtype, device=device)
- with torch.inference_mode(), _bf16_autocast():
- latents = pipe.encode_video(videos, **_tiler_kwargs())
+ latents = vae.encode(videos, device=device, **_tiler_kwargs())
return latents.detach().to("cpu")
-def _noise(pipe, num_views: int, num_frames: int, seed: int, device: str):
+def _noise(vae: WanVideoVAE38, num_views: int, num_frames: int, seed: int, device: str) -> Tensor:
import torch
shape = (
num_views,
- pipe.vae.model.z_dim,
+ vae.model.z_dim,
(num_frames - 1) // 4 + 1,
- INFERENCE.height // pipe.vae.upsampling_factor,
- INFERENCE.width // pipe.vae.upsampling_factor,
+ INFERENCE.height // vae.upsampling_factor,
+ INFERENCE.width // vae.upsampling_factor,
)
generator = torch.Generator("cpu").manual_seed(seed)
return torch.randn(shape, generator=generator, device="cpu", dtype=torch.float32).to(
- dtype=pipe.torch_dtype, device=device
+ dtype=torch.bfloat16, device=device
)
-def _load_skeleton_cache(
- conditioning: Conditioning,
- skeletons: Iterable[SkeletonVideo],
- cache: dict[SkeletonVideo, object],
-) -> None:
- import torch
-
- for skeleton in skeletons:
- if skeleton in cache:
- continue
- LOGGER.info("Loading skeleton conditioning from %s", skeleton.path.name)
- tensor = conditioning.load_skeleton_tensor([skeleton]).to(dtype=torch.bfloat16, device="cpu")
- cache[skeleton] = tensor.contiguous()
-
-
-def _skeleton_group(
- cache: dict[SkeletonVideo, object],
- skeletons: Iterable[SkeletonVideo],
- device: str,
- *,
- channels_last: bool = False,
-):
- import torch
-
- items = tuple(skeletons)
- first = cache[items[0]]
- memory_format = torch.channels_last_3d if channels_last else torch.contiguous_format
- group = torch.empty(
- (len(items), *first.shape[1:]),
- dtype=first.dtype,
- device=device,
- memory_format=memory_format,
- )
- for output_index, skeleton in enumerate(items):
- group[output_index].copy_(cache[skeleton][0])
- return group
-
-
def _denoise_rcp(
- pipe,
- src_latents,
- context,
+ denoiser: Denoiser,
+ vae: WanVideoVAE38,
+ src_latents: Tensor,
+ context: Tensor,
camera_ids: tuple[int, ...],
- skeletons: tuple[SkeletonVideo, ...],
- skeleton_cache: dict[SkeletonVideo, object],
+ pose_features: PoseFeatureBank,
device: str,
seed: int,
-):
+) -> Tensor:
import torch
from tqdm.auto import tqdm
- if len(skeletons) != len(camera_ids):
- raise FourDAnyoneError(f"RCP requires {len(camera_ids)} skeleton views, got {len(skeletons)}.")
- pipe.scheduler.set_timesteps(
+ if pose_features.num_features != len(camera_ids):
+ raise FourDAnyoneError(f"RCP requires {len(camera_ids)} pose features, got {pose_features.num_features}.")
+ denoiser.scheduler.set_timesteps(
INFERENCE.num_inference_steps,
denoising_strength=INFERENCE.denoising_strength,
shift=INFERENCE.scheduler_shift,
)
- latents = _noise(pipe, len(skeletons), INFERENCE.num_frames, seed, device)
- source = src_latents.to(dtype=pipe.torch_dtype, device=device)
- 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)
+ latents = _noise(vae, len(camera_ids), INFERENCE.num_frames, seed, device)
+ source = src_latents.to(dtype=denoiser.dtype, device=device)
+ context = context.to(dtype=denoiser.dtype, device=device)
+ pose_feature_batch = pose_features.allocate_group(len(camera_ids), device)
+ pose_features.copy_group(tuple(range(len(camera_ids))), pose_feature_batch)
+ null_pose_feature = pose_features.null_on(device)
with torch.inference_mode(), _bf16_autocast():
- for step_index, _ in enumerate(tqdm(pipe.scheduler.timesteps, desc=f"RCP 1-to-{len(camera_ids)}")):
+ for step_index, _ in enumerate(tqdm(denoiser.scheduler.timesteps, desc=f"RCP 1-to-{len(camera_ids)}")):
latents = denoise_group(
- pipe,
+ denoiser,
latents,
source,
context,
- skeleton_tensor,
+ pose_feature_batch,
+ null_pose_feature,
step_index,
)
return latents.detach().to("cpu")
@@ -252,8 +244,8 @@ def _load_rcp_reference_videos(frame_dirs: Iterable[Path], num_frames: int):
def _decode_rcp(
- pipe,
- latents,
+ vae: WanVideoVAE38,
+ latents: Tensor,
camera_ids: tuple[int, ...],
output_dir: Path,
clip: CanonicalClip,
@@ -272,8 +264,9 @@ def _decode_rcp(
with torch.inference_mode(), _bf16_autocast():
for latent_index, camera_id in enumerate(camera_ids):
LOGGER.info("Decoding RCP camera %02d", camera_id)
- video = pipe.decode_video(
- latents[latent_index : latent_index + 1].to(dtype=pipe.torch_dtype, device=device),
+ 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))
@@ -292,54 +285,61 @@ def _decode_rcp(
def _denoise_targets_single(
- pipe,
- src_latents,
- context,
- skeletons: tuple[SkeletonVideo, ...],
- skeleton_cache: dict[SkeletonVideo, object],
- initial_latents,
- routes,
+ denoiser: Denoiser,
+ src_latents: Tensor,
+ context: Tensor,
+ pose_features: PoseFeatureBank,
+ initial_latents: Tensor,
+ routes: Routes,
device: str,
-):
+) -> Tensor:
import torch
from tqdm.auto import tqdm
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(
+ if pose_features.num_features != num_views:
+ raise FourDAnyoneError(
+ f"Target generation requires {num_views} pose features, got {pose_features.num_features}."
+ )
+ denoiser.scheduler.set_timesteps(
INFERENCE.num_inference_steps,
denoising_strength=INFERENCE.denoising_strength,
shift=INFERENCE.scheduler_shift,
)
latents = initial_latents
- source = src_latents.to(dtype=pipe.torch_dtype, device=device)
- context = context.to(dtype=pipe.torch_dtype, device=device)
+ source = src_latents.to(dtype=denoiser.dtype, device=device)
+ context = context.to(dtype=denoiser.dtype, device=device)
+ null_pose_feature = pose_features.null_on(device)
+ group_size = len(routes[0][0])
+ pose_feature_batch = pose_features.allocate_group(group_size, device)
with torch.inference_mode(), _bf16_autocast():
for step_index, groups in enumerate(tqdm(routes, desc=f"Generate {num_views} target views")):
for view_indices in groups:
index = torch.tensor(view_indices, dtype=torch.long, device=device)
local_latents = torch.index_select(latents, 0, index)
- local_skeletons = _skeleton_group(
- skeleton_cache,
- (skeletons[view_index] for view_index in view_indices),
- device,
- )
+ pose_features.copy_group(view_indices, pose_feature_batch)
local_latents = denoise_group(
- pipe,
+ denoiser,
local_latents,
source,
context,
- local_skeletons,
+ pose_feature_batch,
+ null_pose_feature,
step_index,
)
latents.index_copy_(0, index, local_latents)
- del local_latents, local_skeletons
+ del local_latents
return latents.detach().to("cpu")
-def _decode_targets(pipe, latents, output_dir: Path, clip: CanonicalClip, device: str) -> tuple[Path, ...]:
+def _decode_targets(
+ vae: WanVideoVAE38,
+ latents: Tensor,
+ output_dir: Path,
+ clip: CanonicalClip,
+ device: str,
+) -> tuple[Path, ...]:
import torch
video_root = output_dir / "videos"
@@ -348,8 +348,9 @@ def _decode_targets(pipe, latents, output_dir: Path, clip: CanonicalClip, device
with torch.inference_mode(), _bf16_autocast():
for camera_id in range(latents.shape[0]):
LOGGER.info("Decoding target camera %02d", camera_id)
- video = pipe.decode_video(
- latents[camera_id : camera_id + 1].to(dtype=pipe.torch_dtype, device=device),
+ video = vae.decode(
+ latents[camera_id : camera_id + 1].to(dtype=torch.bfloat16, device=device),
+ device=device,
**_tiler_kwargs(),
)[0]
path = write_video(
@@ -365,18 +366,12 @@ def _decode_targets(pipe, latents, output_dir: Path, clip: CanonicalClip, device
return tuple(outputs)
-def generate_views(
- *,
+def _resolve_generation_plan(
clip: CanonicalClip,
conditioning: Conditioning,
- checkpoint_path: str | Path,
- assets: BaseAssets,
- output_dir: str | Path,
devices: tuple[str, ...],
seed: int,
-) -> GeneratedViews:
- """Generate the proposal (when enabled) and the requested target views."""
-
+) -> _GenerationPlan:
import torch
if conditioning.num_frames != INFERENCE.num_frames or len(clip.frames) != INFERENCE.num_frames:
@@ -385,172 +380,249 @@ def generate_views(
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))
- root = Path(output_dir).expanduser().resolve()
- root.mkdir(parents=True, exist_ok=False)
view_plan = conditioning.view_plan
if len(conditioning.target_skeletons) != view_plan.num_target_views:
raise FourDAnyoneError("Target skeleton count does not match the resolved view plan.")
if len(conditioning.rcp_skeletons) != len(view_plan.rcp_camera_ids):
raise FourDAnyoneError("RCP skeleton count does not match the resolved view plan.")
- loaded = load_pipeline(checkpoint_path=checkpoint_path, assets=assets, device=device)
- pipe = loaded.pipe
- timings: dict[str, float] = {}
- skeleton_cache: dict[SkeletonVideo, object] = {}
- torch.cuda.reset_peak_memory_stats(device_index)
-
- started = time.monotonic()
- context = _encode_prompt(pipe, device)
- loaded.release_text_encoder()
- timings["prompt"] = time.monotonic() - started
-
- started = time.monotonic()
- _move_model(pipe.vae, device)
- source_video = _channels_last_source_layout(conditioning.load_source_tensor())
- source_latents = _encode_videos(pipe, source_video, device)
- del source_video
- _offload_model(pipe.vae)
- timings["source_encode"] = time.monotonic() - started
- rcp_videos: tuple[Path, ...] = ()
- target_sources = source_latents
- if view_plan.enable_rcp:
- started = time.monotonic()
- _load_skeleton_cache(conditioning, conditioning.rcp_skeletons, skeleton_cache)
- _move_model(pipe.dit, device)
+ 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):
+ LOGGER.info(
+ "Using %d of %d candidate GPUs for %d target groups",
+ len(worker_devices),
+ len(devices),
+ view_plan.num_groups,
+ )
+ return _GenerationPlan(
+ view_plan=view_plan,
+ device=device,
+ device_index=device_index,
+ worker_devices=worker_devices,
+ )
+
+
+def _generate_rcp_and_references(
+ *,
+ denoiser: Denoiser,
+ vae: WanVideoVAE38,
+ source_latents: Tensor,
+ context: Tensor,
+ pose_cache: PoseFeatureCache,
+ plan: _GenerationPlan,
+ root: Path,
+ clip: CanonicalClip,
+ seed: int,
+ metrics: GenerationMetrics,
+) -> tuple[Tensor, tuple[Path, ...]]:
+ import torch
+
+ 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):
rcp_latents = _denoise_rcp(
- pipe,
+ denoiser,
+ vae,
source_latents,
context,
- view_plan.rcp_camera_ids,
- conditioning.rcp_skeletons,
- skeleton_cache,
- device,
+ plan.view_plan.rcp_camera_ids,
+ rcp_pose_features,
+ plan.device,
seed,
)
- _offload_model(pipe.dit)
- timings["rcp_denoise"] = time.monotonic() - started
- started = time.monotonic()
+ with metrics.stage("rcp_decode_and_reference_encode"), _model_on_device(vae, plan.device):
rcp_root = root / "rcp"
rcp_root.mkdir()
- _move_model(pipe.vae, device)
frame_dirs, rcp_videos = _decode_rcp(
- pipe,
+ vae,
rcp_latents,
- view_plan.rcp_camera_ids,
+ plan.view_plan.rcp_camera_ids,
rcp_root,
clip,
- device,
+ plan.device,
)
- # Match the reference JPEG-backed RCP boundary before the second VAE
- # encode; backing layout changes can otherwise select different BF16
- # CUDA kernels even when tensor values are identical.
- rcp_reference_videos = _load_rcp_reference_videos(frame_dirs[:4], INFERENCE.num_frames)
- rcp_reference_latents = _encode_videos(pipe, rcp_reference_videos, device)
- # VAE38 encodes batch elements independently, so the existing source
- # encoding is identical to re-encoding source plus the RCP references.
- target_sources = torch.cat([source_latents, rcp_reference_latents], dim=0)
- del rcp_latents, rcp_reference_videos, rcp_reference_latents
- _offload_model(pipe.vae)
- timings["rcp_decode_and_reference_encode"] = time.monotonic() - started
-
- started = time.monotonic()
- routes = routing_steps(
+ # 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)
+ target_sources = torch.cat([source_latents, reference_latents], dim=0)
+ return target_sources, rcp_videos
+
+
+def _target_routes(view_plan: ViewPlan) -> Routes:
+ return 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,
)
- 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()
+
+def _denoise_targets_multi_gpu(
+ *,
+ target_sources: Tensor,
+ context: Tensor,
+ initial_latents: Tensor,
+ pose_features: PoseFeatureBank,
+ routes: Routes,
+ checkpoint_path: str | Path,
+ root: Path,
+ devices: tuple[str, ...],
+ candidate_devices: tuple[str, ...],
+ num_groups: int,
+) -> tuple[Tensor, ParallelismReport]:
+ with TemporaryDirectory(prefix=".distributed-", dir=root) as work_dir:
target_latents, workers = denoise_targets_distributed(
src_latents=target_sources,
context=context,
initial_latents=initial_latents,
- conditioning=conditioning,
+ pose_features=pose_features,
routes=routes,
checkpoint_path=checkpoint_path,
- work_dir=root / "distributed",
- devices=worker_devices,
+ work_dir=work_dir,
+ devices=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,
+ return target_latents, {
+ "backend": "nccl",
+ "candidate_devices": list(candidate_devices),
+ "used_devices": list(devices),
+ "groups_per_step": num_groups,
+ "waves_per_step": math.ceil(num_groups / len(devices)),
+ "workers": workers,
+ }
+
+
+def generate_views(
+ *,
+ clip: CanonicalClip,
+ conditioning: Conditioning,
+ checkpoint_path: str | Path,
+ assets: BaseAssets,
+ output_dir: str | Path,
+ devices: tuple[str, ...],
+ seed: int,
+) -> GeneratedViews:
+ """Generate the proposal (when enabled) and the requested target 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)
+
+ with metrics.stage("prompt"):
+ context = load_prompt_context(assets.prompt_context)
+
+ with metrics.stage("pose_conditioning"):
+ pose_cache = build_pose_feature_cache(
+ conditioning=conditioning,
+ checkpoint_path=checkpoint_path,
+ device=plan.device,
)
- _offload_model(pipe.dit)
- del initial_latents
- timings["target_denoise"] = time.monotonic() - started
-
- started = time.monotonic()
- target_root = root / "target"
- target_root.mkdir()
- _move_model(pipe.vae, device)
- target_videos = _decode_targets(pipe, target_latents, target_root, clip, device)
- _offload_model(pipe.vae)
- timings["target_decode"] = time.monotonic() - started
- peak_vram_allocated = int(torch.cuda.max_memory_allocated(device_index))
- peak_vram_reserved = int(torch.cuda.max_memory_reserved(device_index))
+
+ 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,
+ )
+
+ 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,
+ context=context,
+ initial_latents=initial_latents,
+ pose_features=pose_cache.target,
+ routes=routes,
+ checkpoint_path=checkpoint_path,
+ root=root,
+ devices=plan.worker_devices,
+ candidate_devices=devices,
+ num_groups=plan.view_plan.num_groups,
+ )
+ 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 denoiser
+ del initial_latents
+
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),
+ 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_latents, target_sources, source_latents, context, skeleton_cache, loaded, pipe
+ 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=view_plan,
+ view_plan=plan.view_plan,
seed=seed,
- device=device,
- elapsed_seconds=timings,
- peak_vram_allocated_bytes=peak_vram_allocated,
- peak_vram_reserved_bytes=peak_vram_reserved,
+ 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,
)
diff --git a/fdanyone/model/loader.py b/fdanyone/model/loader.py
index 004702e..3964297 100644
--- a/fdanyone/model/loader.py
+++ b/fdanyone/model/loader.py
@@ -2,55 +2,49 @@
from __future__ import annotations
-import gc
from dataclasses import dataclass
from pathlib import Path
+from typing import TYPE_CHECKING
-from fdanyone.assets import BaseAssets
-from fdanyone.config import INFERENCE
from fdanyone.errors import AssetError, ConfigurationError
-WAN22_TI2V_5B_CONFIG = {
- "has_image_input": False,
- "patch_size": (1, 2, 2),
- "in_dim": 48,
- "dim": 3072,
- "ffn_dim": 14336,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 48,
- "num_heads": 24,
- "num_layers": 30,
- "eps": 1e-6,
- "seperated_timestep": True,
- "require_clip_embedding": False,
- "require_vae_embedding": False,
- "fuse_vae_embedding_in_latents": True,
-}
-
-
-@dataclass
-class LoadedPipeline:
- pipe: object
-
- def release_text_encoder(self) -> None:
- """Release T5 after the single fixed prompt has been encoded."""
-
- import torch
-
- self.pipe.text_encoder = None
- self.pipe.prompter.text_encoder = None
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
-
-
-def _load_checkpoint(path: Path):
+if TYPE_CHECKING:
+ import torch
+ from torch import nn
+
+ from fdanyone.vendor.diffsynth.schedulers.flow_match import FlowMatchScheduler
+
+POSE_ENCODER_PREFIX = "pose_encoder."
+
+
+@dataclass(frozen=True)
+class Denoiser:
+ """The exact DiT, scheduler, and dtype used by one denoising process."""
+
+ model: nn.Module
+ scheduler: FlowMatchScheduler
+ dtype: torch.dtype
+
+
+def _load_checkpoint(
+ path: Path,
+ *,
+ include_prefix: str | None = None,
+ exclude_prefixes: tuple[str, ...] = (),
+):
try:
- from safetensors.torch import load_file
+ from safetensors import safe_open
except ImportError as exc:
raise AssetError("safetensors is required to load the 4DAnyone checkpoint.") from exc
- return load_file(str(path), device="cpu")
+ with safe_open(str(path), framework="pt", device="cpu") as checkpoint:
+ checkpoint_keys = checkpoint.keys()
+ keys = (
+ key
+ for key in checkpoint_keys
+ if (include_prefix is None or key.startswith(include_prefix))
+ and not any(key.startswith(prefix) for prefix in exclude_prefixes)
+ )
+ return {key: checkpoint.get_tensor(key) for key in keys}
def _strict_assign(module, state_dict: dict, label: str) -> None:
@@ -69,204 +63,81 @@ def _strict_assign(module, state_dict: dict, label: str) -> None:
)
-def _load_dit(checkpoint_path: Path, dtype):
+def _load_dit(checkpoint_path: Path):
import torch
- from fdanyone.vendor.diffsynth.models.wan_video_dit import WanModel, precompute_freqs_cis_3d
- from fdanyone.vendor.diffsynth.pipelines.wan_video_spatem import WanVideoSpaTemPipeline
+ from fdanyone.vendor.diffsynth.models.wan_video_dit import (
+ MODEL_DIM,
+ NUM_HEADS,
+ FourDAnyoneDiT,
+ precompute_freqs_cis_3d,
+ )
with torch.device("meta"):
- dit = WanModel(**WAN22_TI2V_5B_CONFIG)
- shell = WanVideoSpaTemPipeline(device="cpu", torch_dtype=dtype)
- shell.dit = dit
- shell.init_spatem_modules(
- disable_video_attn=INFERENCE.disable_video_attention,
- use_4d_attn=INFERENCE.use_4d_attention,
- use_mvs_attn=INFERENCE.use_mvs_attention,
- use_src_self_attn=INFERENCE.use_source_self_attention,
- use_src_cross_attn=INFERENCE.use_source_cross_attention,
- freqs_src_shift=INFERENCE.freqs_src_shift,
- range_mvs_attn=INFERENCE.mvs_attention_range,
- # ``ViewPack`` is the upstream module name for RCP references.
- use_viewpack=True,
- use_pose_encoder=INFERENCE.use_pose_encoder,
- pose_encoder_type=INFERENCE.pose_encoder_type,
- use_cam_encoder=INFERENCE.use_camera_encoder,
- use_lbm=INFERENCE.use_lbm,
- )
- state_dict = _load_checkpoint(checkpoint_path)
+ dit = FourDAnyoneDiT()
+ state_dict = _load_checkpoint(checkpoint_path, exclude_prefixes=(POSE_ENCODER_PREFIX,))
_strict_assign(dit, state_dict, "4DAnyone DiT checkpoint")
del state_dict
# ``freqs`` is a derived, non-persistent tensor and therefore is not in the
# state dict populated above.
- dit.freqs = precompute_freqs_cis_3d(WAN22_TI2V_5B_CONFIG["dim"] // WAN22_TI2V_5B_CONFIG["num_heads"])
+ dit.freqs = precompute_freqs_cis_3d(MODEL_DIM // NUM_HEADS)
return dit.eval().requires_grad_(False)
-def _load_vae(path: Path, dtype):
+def load_pose_encoder(checkpoint_path: str | Path, device: str):
+ """Load only the small pose encoder partition from the DiT checkpoint."""
+
import torch
- from fdanyone.vendor.diffsynth.models.wan_video_vae import WanVideoVAE38
+ from fdanyone.vendor.diffsynth.models.wan_video_dit import MODEL_DIM
+ from fdanyone.vendor.diffsynth.models.wan_video_pose_encoder import PoseEncoder
- state_dict = torch.load(path, map_location="cpu", weights_only=True)
- state_dict = WanVideoVAE38.state_dict_converter().from_civitai(state_dict)
+ state_dict = {
+ key.removeprefix(POSE_ENCODER_PREFIX): value
+ for key, value in _load_checkpoint(Path(checkpoint_path), include_prefix=POSE_ENCODER_PREFIX).items()
+ }
with torch.device("meta"):
- vae = WanVideoVAE38()
- _strict_assign(vae, state_dict, "Wan2.2 VAE")
+ pose_encoder = PoseEncoder(out_dim=MODEL_DIM, in_channels=3)
+ _strict_assign(pose_encoder, state_dict, "4DAnyone pose encoder checkpoint")
del state_dict
- # Wan's latent normalization tensors are plain attributes rather than
- # registered buffers, so materialize them after meta initialization.
- mean = (
- -0.2289,
- -0.0052,
- -0.1323,
- -0.2339,
- -0.2799,
- 0.0174,
- 0.1838,
- 0.1557,
- -0.1382,
- 0.0542,
- 0.2813,
- 0.0891,
- 0.1570,
- -0.0098,
- 0.0375,
- -0.1825,
- -0.2246,
- -0.1207,
- -0.0698,
- 0.5109,
- 0.2665,
- -0.2108,
- -0.2158,
- 0.2502,
- -0.2055,
- -0.0322,
- 0.1109,
- 0.1567,
- -0.0729,
- 0.0899,
- -0.2799,
- -0.1230,
- -0.0313,
- -0.1649,
- 0.0117,
- 0.0723,
- -0.2839,
- -0.2083,
- -0.0520,
- 0.3748,
- 0.0152,
- 0.1957,
- 0.1433,
- -0.2944,
- 0.3573,
- -0.0548,
- -0.1681,
- -0.0667,
- )
- std = (
- 0.4765,
- 1.0364,
- 0.4514,
- 1.1677,
- 0.5313,
- 0.4990,
- 0.4818,
- 0.5013,
- 0.8158,
- 1.0344,
- 0.5894,
- 1.0901,
- 0.6885,
- 0.6165,
- 0.8454,
- 0.4978,
- 0.5759,
- 0.3523,
- 0.7135,
- 0.6804,
- 0.5833,
- 1.4146,
- 0.8986,
- 0.5659,
- 0.7069,
- 0.5338,
- 0.4889,
- 0.4917,
- 0.4069,
- 0.4999,
- 0.6866,
- 0.4093,
- 0.5709,
- 0.6065,
- 0.6415,
- 0.4944,
- 0.5726,
- 1.2042,
- 0.5458,
- 1.6887,
- 0.3971,
- 1.0600,
- 0.3943,
- 0.5537,
- 0.5444,
- 0.4089,
- 0.7468,
- 0.7744,
- )
- vae.mean = torch.tensor(mean)
- vae.std = torch.tensor(std)
- vae.scale = [vae.mean, 1.0 / vae.std]
- return vae.to(dtype=dtype).eval().requires_grad_(False)
+ return pose_encoder.to(device=device, dtype=torch.bfloat16).eval().requires_grad_(False)
-def _load_text_encoder(path: Path, dtype):
+def _load_vae(path: Path, dtype):
import torch
- from fdanyone.vendor.diffsynth.models.wan_video_text_encoder import WanTextEncoder
+ from fdanyone.vendor.diffsynth.models.wan_video_vae import WanVideoVAE38
state_dict = torch.load(path, map_location="cpu", weights_only=True)
- state_dict = WanTextEncoder.state_dict_converter().from_civitai(state_dict)
+ state_dict = WanVideoVAE38.state_dict_converter().from_civitai(state_dict)
with torch.device("meta"):
- text_encoder = WanTextEncoder()
- _strict_assign(text_encoder, state_dict, "Wan T5 text encoder")
+ vae = WanVideoVAE38()
+ _strict_assign(vae, state_dict, "Wan2.2 VAE")
del state_dict
- return text_encoder.to(dtype=dtype).eval().requires_grad_(False)
+ # These tensors are derived attributes, not checkpoint entries. Recreate
+ # them after strict assignment because construction happened on ``meta``.
+ vae.materialize_normalization(device="cpu")
+ return vae.to(dtype=dtype).eval().requires_grad_(False)
-def load_pipeline(
- *,
- checkpoint_path: str | Path,
- assets: BaseAssets,
- device: str,
-) -> LoadedPipeline:
- """Load exactly the runtime models required by the released checkpoint."""
+def load_vae(path: str | Path):
+ """Load the frozen Wan VAE as an independent generation stage."""
import torch
- from fdanyone.vendor.diffsynth.pipelines.wan_video_spatem import WanVideoSpaTemPipeline
-
- dtype = torch.bfloat16
- pipe = WanVideoSpaTemPipeline(device=device, torch_dtype=dtype, tokenizer_path=str(assets.tokenizer))
- pipe.dit = _load_dit(Path(checkpoint_path), dtype)
- pipe.vae = _load_vae(assets.vae, dtype)
- pipe.text_encoder = _load_text_encoder(assets.text_encoder, dtype)
- pipe.prompter.fetch_models(pipe.text_encoder)
- pipe.height_division_factor = pipe.vae.upsampling_factor * 2
- pipe.width_division_factor = pipe.vae.upsampling_factor * 2
- return LoadedPipeline(pipe=pipe)
+ return _load_vae(Path(path), torch.bfloat16)
-def load_denoiser(*, checkpoint_path: str | Path, device: str):
+def load_denoiser(*, checkpoint_path: str | Path) -> Denoiser:
"""Load the DiT and scheduler required by one distributed worker."""
import torch
- from fdanyone.vendor.diffsynth.pipelines.wan_video_spatem import WanVideoSpaTemPipeline
+ from fdanyone.vendor.diffsynth.schedulers.flow_match import FlowMatchScheduler
dtype = torch.bfloat16
- pipe = WanVideoSpaTemPipeline(device=device, torch_dtype=dtype)
- pipe.dit = _load_dit(Path(checkpoint_path), dtype)
- return pipe
+ return Denoiser(
+ model=_load_dit(Path(checkpoint_path)),
+ scheduler=FlowMatchScheduler(shift=5, sigma_min=0.0, extra_one_step=True),
+ dtype=dtype,
+ )
diff --git a/fdanyone/model/metrics.py b/fdanyone/model/metrics.py
new file mode 100644
index 0000000..a945839
--- /dev/null
+++ b/fdanyone/model/metrics.py
@@ -0,0 +1,62 @@
+"""Stage-local wall-time and CUDA-memory measurements for generation."""
+
+from __future__ import annotations
+
+import time
+from contextlib import contextmanager
+
+
+class GenerationMetrics:
+ """Measure independent stages while preserving an end-to-end CUDA peak."""
+
+ def __init__(self, device_index: int) -> None:
+ self.device_index = device_index
+ self.elapsed_seconds: dict[str, float] = {}
+ self.stage_peak_vram_bytes: dict[str, dict[str, int]] = {}
+ self._active_stage: str | None = None
+
+ @contextmanager
+ def stage(self, name: str):
+ """Measure one non-overlapping stage."""
+
+ import torch
+
+ if self._active_stage is not None:
+ raise RuntimeError(f"Cannot start stage {name!r} while {self._active_stage!r} is active.")
+ if name in self.elapsed_seconds:
+ raise RuntimeError(f"Generation stage {name!r} was measured more than once.")
+
+ self._active_stage = name
+ torch.cuda.synchronize(self.device_index)
+ torch.cuda.reset_peak_memory_stats(self.device_index)
+ started = time.monotonic()
+ try:
+ yield
+ finally:
+ torch.cuda.synchronize(self.device_index)
+ self.elapsed_seconds[name] = time.monotonic() - started
+ self.merge_cuda_peak(
+ name,
+ allocated_bytes=int(torch.cuda.max_memory_allocated(self.device_index)),
+ reserved_bytes=int(torch.cuda.max_memory_reserved(self.device_index)),
+ )
+ self._active_stage = None
+
+ def merge_cuda_peak(self, name: str, *, allocated_bytes: int, reserved_bytes: int) -> None:
+ """Merge a child-process/device measurement into a named stage."""
+
+ if allocated_bytes < 0 or reserved_bytes < 0:
+ raise ValueError("CUDA memory measurements cannot be negative.")
+ previous = self.stage_peak_vram_bytes.get(name, {})
+ self.stage_peak_vram_bytes[name] = {
+ "allocated": max(allocated_bytes, previous.get("allocated", 0)),
+ "reserved": max(reserved_bytes, previous.get("reserved", 0)),
+ }
+
+ @property
+ def peak_vram_allocated_bytes(self) -> int:
+ return max((record["allocated"] for record in self.stage_peak_vram_bytes.values()), default=0)
+
+ @property
+ def peak_vram_reserved_bytes(self) -> int:
+ return max((record["reserved"] for record in self.stage_peak_vram_bytes.values()), default=0)
diff --git a/fdanyone/output.py b/fdanyone/output.py
index 3918bc8..591d2e2 100644
--- a/fdanyone/output.py
+++ b/fdanyone/output.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import os
import platform
import shutil
import sys
@@ -11,6 +12,7 @@ from pathlib import Path
from typing import TYPE_CHECKING
from fdanyone.config import INFERENCE
+from fdanyone.device import CUDA_ALLOCATOR_CONF
from fdanyone.errors import FourDAnyoneError
from fdanyone.io import write_json
@@ -34,6 +36,7 @@ def _runtime_metadata(device: str) -> dict:
"available": torch.cuda.is_available(),
"torch_cuda": torch.version.cuda,
"cudnn": torch.backends.cudnn.version(),
+ "allocator_config": os.environ.get(CUDA_ALLOCATOR_CONF),
}
if torch.cuda.is_available():
torch_device = torch.device(device)
@@ -164,6 +167,7 @@ def export_result(
"attention_backend": attention_backend,
"inference_steps": INFERENCE.num_inference_steps,
"elapsed_seconds": generated.elapsed_seconds,
+ "stage_peak_vram_bytes": generated.stage_peak_vram_bytes,
"total_elapsed_seconds": total_elapsed,
"peak_vram_allocated_bytes": generated.peak_vram_allocated_bytes,
"peak_vram_reserved_bytes": generated.peak_vram_reserved_bytes,
diff --git a/fdanyone/pipeline.py b/fdanyone/pipeline.py
index 7c1c718..9399a1a 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_devices
+from fdanyone.device import CUDA_ALLOCATOR_CONF, select_cuda_devices
from fdanyone.download import ensure_example_video, ensure_models, ensure_smplx
from fdanyone.errors import ConfigurationError
from fdanyone.io import AtomicResultDirectory, remove_tree, write_json
@@ -81,6 +81,9 @@ def _worker_environment() -> dict[str, str]:
}
)
environment.pop("PYTHONHOME", None)
+ # The 4 GiB split policy is specific to the long-lived DiT process. These
+ # short-lived preprocessing workers use unrelated allocation shapes.
+ environment.pop(CUDA_ALLOCATOR_CONF, None)
environment["PYTHONPATH"] = str(Path(__file__).resolve().parent.parent)
return environment
diff --git a/fdanyone/vendor/diffsynth/UPSTREAM.md b/fdanyone/vendor/diffsynth/UPSTREAM.md
index 2fa8f9b..02ffd09 100644
--- a/fdanyone/vendor/diffsynth/UPSTREAM.md
+++ b/fdanyone/vendor/diffsynth/UPSTREAM.md
@@ -7,9 +7,11 @@ This directory is a deliberately small inference-only extract from [modelscope/D
- `UPSTREAM.patch` SHA-256: `178e6035e451f94a2122fa4d2c876a488546964768b90275549cbf609f97daba`
- Extracted: 2026-07-16
-The research fork revision was not anonymously reachable when the release contract was audited. `UPSTREAM.patch` therefore records the exact binary-safe diff from the public base to the research revision for the retained Wan/SpaTem/scheduler source files. Unrelated research-fork changes are deliberately excluded. `VENDORED_FILES.txt` is the reviewable extraction manifest.
+The research fork revision was not anonymously reachable when the release contract was audited. `UPSTREAM.patch` therefore records the exact binary-safe diff from the public base to the research revision for the Wan/SpaTem/scheduler sources from which the reader graph was derived. Unrelated research-fork changes are deliberately excluded. `VENDORED_FILES.txt` is the reviewable final runtime manifest.
-4DAnyone subsequently removed registry, downloader, training, image-encoder, and unrelated pipeline surfaces; changed imports to the local vendored package; exposes direct, typed model construction in first-party code; and exposes the implementation selected by the retained automatic attention fallback chain for run metadata. These pruning and observability changes do not alter the retained Wan/SpaTem architecture or scheduler math.
+4DAnyone subsequently reduced the generic Wan implementation to the one checkpoint-key-compatible reader graph: video attention, MVS attention in every block, ViewPack source tokens, fixed prompt context, and precomputed RGB-pose features. Registry, downloader, text encoder/tokenizer, generic pipeline, training adapters, camera/control modules, VRAM wrappers, and alternate schedulers are not part of the reader closure. The retained automatic attention fallback remains observable in run metadata.
+
+The reader inference path bounds the temporary FP64 RoPE workspace and reuses PoseEncoder/FFN activation storage when gradients are disabled. These release-specific memory-lifetime changes preserve checkpoint parameter keys and the full-group attention and FFN matrix-multiplication shapes. The offline UMT5 conversion implementation used to generate the frozen prompt asset is development-only and not part of the reader distribution; it retains this license and provenance.
To reproduce the retained research sources before pruning:
diff --git a/fdanyone/vendor/diffsynth/VENDORED_FILES.txt b/fdanyone/vendor/diffsynth/VENDORED_FILES.txt
index 136e462..a8c4325 100644
--- a/fdanyone/vendor/diffsynth/VENDORED_FILES.txt
+++ b/fdanyone/vendor/diffsynth/VENDORED_FILES.txt
@@ -5,21 +5,8 @@ UPSTREAM.patch
VENDORED_FILES.txt
__init__.py
models/__init__.py
-models/utils.py
-models/wan_video_camera_controller.py
models/wan_video_dit.py
models/wan_video_pose_encoder.py
-models/wan_video_text_encoder.py
models/wan_video_vae.py
-pipelines/__init__.py
-pipelines/base.py
-pipelines/wan_video_spatem.py
-prompters/__init__.py
-prompters/base_prompter.py
-prompters/wan_prompter.py
schedulers/__init__.py
-schedulers/bride_match.py
schedulers/flow_match.py
-vram_management/__init__.py
-vram_management/gradient_checkpointing.py
-vram_management/layers.py
diff --git a/fdanyone/vendor/diffsynth/models/__init__.py b/fdanyone/vendor/diffsynth/models/__init__.py
index 125a76b..9bba884 100644
--- a/fdanyone/vendor/diffsynth/models/__init__.py
+++ b/fdanyone/vendor/diffsynth/models/__init__.py
@@ -1,7 +1 @@
-"""Vendored Wan model definitions."""
-
-from .wan_video_dit import WanModel
-from .wan_video_text_encoder import WanTextEncoder
-from .wan_video_vae import WanVideoVAE
-
-__all__ = ["WanModel", "WanTextEncoder", "WanVideoVAE"]
+"""Vendored model modules; reader code imports its exact modules directly."""
diff --git a/fdanyone/vendor/diffsynth/models/utils.py b/fdanyone/vendor/diffsynth/models/utils.py
deleted file mode 100644
index 86104d0..0000000
--- a/fdanyone/vendor/diffsynth/models/utils.py
+++ /dev/null
@@ -1,182 +0,0 @@
-import torch, os
-from safetensors import safe_open
-from contextlib import contextmanager
-import hashlib
-
-@contextmanager
-def init_weights_on_device(device = torch.device("meta"), include_buffers :bool = False):
-
- old_register_parameter = torch.nn.Module.register_parameter
- if include_buffers:
- old_register_buffer = torch.nn.Module.register_buffer
-
- def register_empty_parameter(module, name, param):
- old_register_parameter(module, name, param)
- if param is not None:
- param_cls = type(module._parameters[name])
- kwargs = module._parameters[name].__dict__
- kwargs["requires_grad"] = param.requires_grad
- module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
-
- def register_empty_buffer(module, name, buffer, persistent=True):
- old_register_buffer(module, name, buffer, persistent=persistent)
- if buffer is not None:
- module._buffers[name] = module._buffers[name].to(device)
-
- def patch_tensor_constructor(fn):
- def wrapper(*args, **kwargs):
- kwargs["device"] = device
- return fn(*args, **kwargs)
-
- return wrapper
-
- if include_buffers:
- tensor_constructors_to_patch = {
- torch_function_name: getattr(torch, torch_function_name)
- for torch_function_name in ["empty", "zeros", "ones", "full"]
- }
- else:
- tensor_constructors_to_patch = {}
-
- try:
- torch.nn.Module.register_parameter = register_empty_parameter
- if include_buffers:
- torch.nn.Module.register_buffer = register_empty_buffer
- for torch_function_name in tensor_constructors_to_patch.keys():
- setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
- yield
- finally:
- torch.nn.Module.register_parameter = old_register_parameter
- if include_buffers:
- torch.nn.Module.register_buffer = old_register_buffer
- for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
- setattr(torch, torch_function_name, old_torch_function)
-
-def load_state_dict_from_folder(file_path, torch_dtype=None):
- state_dict = {}
- for file_name in os.listdir(file_path):
- if "." in file_name and file_name.split(".")[-1] in [
- "safetensors", "bin", "ckpt", "pth", "pt"
- ]:
- state_dict.update(load_state_dict(os.path.join(file_path, file_name), torch_dtype=torch_dtype))
- return state_dict
-
-
-def load_state_dict(file_path, torch_dtype=None, device="cpu"):
- if file_path.endswith(".safetensors"):
- return load_state_dict_from_safetensors(file_path, torch_dtype=torch_dtype, device=device)
- else:
- return load_state_dict_from_bin(file_path, torch_dtype=torch_dtype, device=device)
-
-
-def load_state_dict_from_safetensors(file_path, torch_dtype=None, device="cpu"):
- state_dict = {}
- with safe_open(file_path, framework="pt", device=str(device)) as f:
- for k in f.keys():
- state_dict[k] = f.get_tensor(k)
- if torch_dtype is not None:
- state_dict[k] = state_dict[k].to(torch_dtype)
- return state_dict
-
-
-def load_state_dict_from_bin(file_path, torch_dtype=None, device="cpu"):
- state_dict = torch.load(file_path, map_location=device, weights_only=True)
- if torch_dtype is not None:
- for i in state_dict:
- if isinstance(state_dict[i], torch.Tensor):
- state_dict[i] = state_dict[i].to(torch_dtype)
- return state_dict
-
-
-def search_for_embeddings(state_dict):
- embeddings = []
- for k in state_dict:
- if isinstance(state_dict[k], torch.Tensor):
- embeddings.append(state_dict[k])
- elif isinstance(state_dict[k], dict):
- embeddings += search_for_embeddings(state_dict[k])
- return embeddings
-
-
-def search_parameter(param, state_dict):
- for name, param_ in state_dict.items():
- if param.numel() == param_.numel():
- if param.shape == param_.shape:
- if torch.dist(param, param_) < 1e-3:
- return name
- else:
- if torch.dist(param.flatten(), param_.flatten()) < 1e-3:
- return name
- return None
-
-
-def build_rename_dict(source_state_dict, target_state_dict, split_qkv=False):
- matched_keys = set()
- with torch.no_grad():
- for name in source_state_dict:
- rename = search_parameter(source_state_dict[name], target_state_dict)
- if rename is not None:
- print(f'"{name}": "{rename}",')
- matched_keys.add(rename)
- elif split_qkv and len(source_state_dict[name].shape)>=1 and source_state_dict[name].shape[0]%3==0:
- length = source_state_dict[name].shape[0] // 3
- rename = []
- for i in range(3):
- rename.append(search_parameter(source_state_dict[name][i*length: i*length+length], target_state_dict))
- if None not in rename:
- print(f'"{name}": {rename},')
- for rename_ in rename:
- matched_keys.add(rename_)
- for name in target_state_dict:
- if name not in matched_keys:
- print("Cannot find", name, target_state_dict[name].shape)
-
-
-def search_for_files(folder, extensions):
- files = []
- if os.path.isdir(folder):
- for file in sorted(os.listdir(folder)):
- files += search_for_files(os.path.join(folder, file), extensions)
- elif os.path.isfile(folder):
- for extension in extensions:
- if folder.endswith(extension):
- files.append(folder)
- break
- return files
-
-
-def convert_state_dict_keys_to_single_str(state_dict, with_shape=True):
- keys = []
- for key, value in state_dict.items():
- if isinstance(key, str):
- if isinstance(value, torch.Tensor):
- if with_shape:
- shape = "_".join(map(str, list(value.shape)))
- keys.append(key + ":" + shape)
- keys.append(key)
- elif isinstance(value, dict):
- keys.append(key + "|" + convert_state_dict_keys_to_single_str(value, with_shape=with_shape))
- keys.sort()
- keys_str = ",".join(keys)
- return keys_str
-
-
-def split_state_dict_with_prefix(state_dict):
- keys = sorted([key for key in state_dict if isinstance(key, str)])
- prefix_dict = {}
- for key in keys:
- prefix = key if "." not in key else key.split(".")[0]
- if prefix not in prefix_dict:
- prefix_dict[prefix] = []
- prefix_dict[prefix].append(key)
- state_dicts = []
- for prefix, keys in prefix_dict.items():
- sub_state_dict = {key: state_dict[key] for key in keys}
- state_dicts.append(sub_state_dict)
- return state_dicts
-
-
-def hash_state_dict_keys(state_dict, with_shape=True):
- keys_str = convert_state_dict_keys_to_single_str(state_dict, with_shape=with_shape)
- keys_str = keys_str.encode(encoding="UTF-8")
- return hashlib.md5(keys_str).hexdigest()
\ No newline at end of file
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_camera_controller.py b/fdanyone/vendor/diffsynth/models/wan_video_camera_controller.py
deleted file mode 100644
index 8655804..0000000
--- a/fdanyone/vendor/diffsynth/models/wan_video_camera_controller.py
+++ /dev/null
@@ -1,209 +0,0 @@
-import torch
-import torch.nn as nn
-import numpy as np
-from einops import rearrange
-import os
-from typing_extensions import Literal
-
-# Camera-coordinate helpers retained below are attributed to CameraCtrl
-# (https://github.com/hehao13/CameraCtrl), licensed under Apache-2.0.
-
-class SimpleAdapter(nn.Module):
- def __init__(self, in_dim, out_dim, kernel_size, stride, num_residual_blocks=1):
- super(SimpleAdapter, self).__init__()
-
- # Pixel Unshuffle: reduce spatial dimensions by a factor of 8
- self.pixel_unshuffle = nn.PixelUnshuffle(downscale_factor=8)
-
- # Convolution: reduce spatial dimensions by a factor
- # of 2 (without overlap)
- self.conv = nn.Conv2d(in_dim * 64, out_dim, kernel_size=kernel_size, stride=stride, padding=0)
-
- # Residual blocks for feature extraction
- self.residual_blocks = nn.Sequential(
- *[ResidualBlock(out_dim) for _ in range(num_residual_blocks)]
- )
-
- def forward(self, x):
- # Reshape to merge the frame dimension into batch
- bs, c, f, h, w = x.size()
- x = x.permute(0, 2, 1, 3, 4).contiguous().view(bs * f, c, h, w)
-
- # Pixel Unshuffle operation
- x_unshuffled = self.pixel_unshuffle(x)
-
- # Convolution operation
- x_conv = self.conv(x_unshuffled)
-
- # Feature extraction with residual blocks
- out = self.residual_blocks(x_conv)
-
- # Reshape to restore original bf dimension
- out = out.view(bs, f, out.size(1), out.size(2), out.size(3))
-
- # Permute dimensions to reorder (if needed), e.g., swap channels and feature frames
- out = out.permute(0, 2, 1, 3, 4)
-
- return out
-
- def process_camera_coordinates(
- self,
- direction: Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown"],
- length: int,
- height: int,
- width: int,
- speed: float = 1/54,
- origin=(0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
- ):
- if origin is None:
- origin = (0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
- coordinates = generate_camera_coordinates(direction, length, speed, origin)
- plucker_embedding = process_pose_file(coordinates, width, height)
- return plucker_embedding
-
-
-
-class ResidualBlock(nn.Module):
- def __init__(self, dim):
- super(ResidualBlock, self).__init__()
- self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
- self.relu = nn.ReLU(inplace=True)
- self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
-
- def forward(self, x):
- residual = x
- out = self.relu(self.conv1(x))
- out = self.conv2(out)
- out += residual
- return out
-
-class Camera(object):
- """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
- """
- def __init__(self, entry):
- fx, fy, cx, cy = entry[1:5]
- self.fx = fx
- self.fy = fy
- self.cx = cx
- self.cy = cy
- w2c_mat = np.array(entry[7:]).reshape(3, 4)
- w2c_mat_4x4 = np.eye(4)
- w2c_mat_4x4[:3, :] = w2c_mat
- self.w2c_mat = w2c_mat_4x4
- self.c2w_mat = np.linalg.inv(w2c_mat_4x4)
-
-def get_relative_pose(cam_params):
- """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
- """
- abs_w2cs = [cam_param.w2c_mat for cam_param in cam_params]
- abs_c2ws = [cam_param.c2w_mat for cam_param in cam_params]
- cam_to_origin = 0
- target_cam_c2w = np.array([
- [1, 0, 0, 0],
- [0, 1, 0, -cam_to_origin],
- [0, 0, 1, 0],
- [0, 0, 0, 1]
- ])
- abs2rel = target_cam_c2w @ abs_w2cs[0]
- ret_poses = [target_cam_c2w, ] + [abs2rel @ abs_c2w for abs_c2w in abs_c2ws[1:]]
- ret_poses = np.array(ret_poses, dtype=np.float32)
- return ret_poses
-
-def custom_meshgrid(*args):
- # torch>=2.0.0 only
- return torch.meshgrid(*args, indexing='ij')
-
-
-def ray_condition(K, c2w, H, W, device):
- """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
- """
- # c2w: B, V, 4, 4
- # K: B, V, 4
-
- B = K.shape[0]
-
- j, i = custom_meshgrid(
- torch.linspace(0, H - 1, H, device=device, dtype=c2w.dtype),
- torch.linspace(0, W - 1, W, device=device, dtype=c2w.dtype),
- )
- i = i.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]
- j = j.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]
-
- fx, fy, cx, cy = K.chunk(4, dim=-1) # B,V, 1
-
- zs = torch.ones_like(i) # [B, HxW]
- xs = (i - cx) / fx * zs
- ys = (j - cy) / fy * zs
- zs = zs.expand_as(ys)
-
- directions = torch.stack((xs, ys, zs), dim=-1) # B, V, HW, 3
- directions = directions / directions.norm(dim=-1, keepdim=True) # B, V, HW, 3
-
- rays_d = directions @ c2w[..., :3, :3].transpose(-1, -2) # B, V, 3, HW
- rays_o = c2w[..., :3, 3] # B, V, 3
- rays_o = rays_o[:, :, None].expand_as(rays_d) # B, V, 3, HW
- # c2w @ dirctions
- rays_dxo = torch.linalg.cross(rays_o, rays_d)
- plucker = torch.cat([rays_dxo, rays_d], dim=-1)
- plucker = plucker.reshape(B, c2w.shape[1], H, W, 6) # B, V, H, W, 6
- # plucker = plucker.permute(0, 1, 4, 2, 3)
- return plucker
-
-
-def process_pose_file(cam_params, width=672, height=384, original_pose_width=1280, original_pose_height=720, device='cpu', return_poses=False):
- if return_poses:
- return cam_params
- else:
- cam_params = [Camera(cam_param) for cam_param in cam_params]
-
- sample_wh_ratio = width / height
- pose_wh_ratio = original_pose_width / original_pose_height # Assuming placeholder ratios, change as needed
-
- if pose_wh_ratio > sample_wh_ratio:
- resized_ori_w = height * pose_wh_ratio
- for cam_param in cam_params:
- cam_param.fx = resized_ori_w * cam_param.fx / width
- else:
- resized_ori_h = width / pose_wh_ratio
- for cam_param in cam_params:
- cam_param.fy = resized_ori_h * cam_param.fy / height
-
- intrinsic = np.asarray([[cam_param.fx * width,
- cam_param.fy * height,
- cam_param.cx * width,
- cam_param.cy * height]
- for cam_param in cam_params], dtype=np.float32)
-
- K = torch.as_tensor(intrinsic)[None] # [1, 1, 4]
- c2ws = get_relative_pose(cam_params) # Assuming this function is defined elsewhere
- c2ws = torch.as_tensor(c2ws)[None] # [1, n_frame, 4, 4]
- plucker_embedding = ray_condition(K, c2ws, height, width, device=device)[0].permute(0, 3, 1, 2).contiguous() # V, 6, H, W
- plucker_embedding = plucker_embedding[None]
- plucker_embedding = rearrange(plucker_embedding, "b f c h w -> b f h w c")[0]
- return plucker_embedding
-
-
-
-def generate_camera_coordinates(
- direction: Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown", "In", "Out"],
- length: int,
- speed: float = 1/54,
- origin=(0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
-):
- coordinates = [list(origin)]
- while len(coordinates) < length:
- coor = coordinates[-1].copy()
- if "Left" in direction:
- coor[9] += speed
- if "Right" in direction:
- coor[9] -= speed
- if "Up" in direction:
- coor[13] += speed
- if "Down" in direction:
- coor[13] -= speed
- if "In" in direction:
- coor[18] -= speed
- if "Out" in direction:
- coor[18] += speed
- coordinates.append(coor)
- return coordinates
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_dit.py b/fdanyone/vendor/diffsynth/models/wan_video_dit.py
index f2cc2e7..e621487 100644
--- a/fdanyone/vendor/diffsynth/models/wan_video_dit.py
+++ b/fdanyone/vendor/diffsynth/models/wan_video_dit.py
@@ -1,38 +1,61 @@
+"""Wan/SpaTem DiT graph used by the released 4DAnyone checkpoint.
+
+This module intentionally contains one inference architecture. The public
+method always uses video self-attention, layer-local multiview attention,
+ViewPack source tokens, frozen text context, and precomputed RGB-pose features.
+Training-only adapters and alternate Wan model families are outside the reader
+runtime.
+"""
+
+from __future__ import annotations
+
+import math
+
import torch
import torch.nn as nn
import torch.nn.functional as F
-import math
-from typing import Tuple, Optional
from einops import rearrange, repeat
-from .utils import hash_state_dict_keys
-from .wan_video_camera_controller import SimpleAdapter
+
try:
import flash_attn_interface
+
FLASH_ATTN_3_AVAILABLE = True
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
+
SAGE_ATTN_AVAILABLE = True
except (ImportError, OSError, RuntimeError):
SAGE_ATTN_AVAILABLE = False
-try:
- from spas_sage_attn import spas_sage2_attn_meansim_topk_cuda
- SPARGE_ATTN_AVAILABLE = True
-except (ImportError, OSError, RuntimeError):
- SPARGE_ATTN_AVAILABLE = False
+
+LATENT_CHANNELS = 48
+MODEL_DIM = 3072
+FFN_DIM = 14336
+FREQUENCY_DIM = 256
+TEXT_DIM = 4096
+NUM_HEADS = 24
+NUM_LAYERS = 30
+PATCH_SIZE = (1, 2, 2)
+NORM_EPSILON = 1e-6
+
+# A converted FP64 chunk and its complex product coexist. Accounting for both
+# 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
def get_attention_backend() -> str:
- """Return the implementation selected by the vendored auto policy."""
+ """Return the implementation selected by the release auto policy."""
if FLASH_ATTN_3_AVAILABLE:
return "flash_attn_3"
@@ -43,980 +66,469 @@ def get_attention_backend() -> str:
return "sdpa"
-def flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_heads: int, compatibility_mode=False):
- if compatibility_mode:
- 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)
- x = F.scaled_dot_product_attention(q, k, v)
- x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
- elif FLASH_ATTN_3_AVAILABLE:
+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."""
+
+ if FLASH_ATTN_3_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)
- x = flash_attn_interface.flash_attn_func(q, k, v)
- if isinstance(x,tuple):
- x = x[0]
- x = rearrange(x, "b s n d -> b s (n d)", n=num_heads)
- elif FLASH_ATTN_2_AVAILABLE:
+ output = flash_attn_interface.flash_attn_func(q, k, v)
+ 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)
- x = flash_attn.flash_attn_func(q, k, v)
- x = rearrange(x, "b s n d -> b s (n d)", n=num_heads)
- # TODO: test spas_sage2_attn_meansim_topk_cuda
- # elif SPARGE_ATTN_AVAILABLE:
- # 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)
- # x = spas_sage2_attn_meansim_topk_cuda(q, k, v, simthreshd1=-0.1, topk=0.5, pvthreshd=15, is_causal=False)
- # x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
- elif SAGE_ATTN_AVAILABLE:
- 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)
- x = sageattn(q, k, v)
- x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
- else:
- 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)
- x = F.scaled_dot_product_attention(q, k, v)
- x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
- return x
-
-
-def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
- return (x * (1 + scale) + shift)
-
-
-def sinusoidal_embedding_1d(dim, position):
- sinusoid = torch.outer(position.type(torch.float64), torch.pow(
- 10000, -torch.arange(dim//2, dtype=torch.float64, device=position.device).div(dim//2)))
- x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
- return x.to(position.dtype)
-
-
-def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
- # 3d rope precompute
- f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
- h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
- w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
- return f_freqs_cis, h_freqs_cis, w_freqs_cis
-
-
-def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
- # 1d rope precompute
- freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)
- [: (dim // 2)].double() / dim))
- freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
- freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
- return freqs_cis
-
-
-def rope_apply(x, freqs, num_heads):
- x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
- x_out = torch.view_as_complex(x.to(torch.float64).reshape(
- x.shape[0], x.shape[1], x.shape[2], -1, 2))
- x_out = torch.view_as_real(x_out * freqs).flatten(2)
- return x_out.to(x.dtype)
+ 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)
+ return rearrange(output, "b n s d -> b s (n d)", n=num_heads)
+
+
+def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+ return x * (1 + scale) + shift
+
+
+def sinusoidal_embedding_1d(dim: int, position: torch.Tensor) -> torch.Tensor:
+ sinusoid = torch.outer(
+ position.to(torch.float64),
+ torch.pow(
+ 10000,
+ -torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(dim // 2),
+ ),
+ )
+ return torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1).to(position.dtype)
+
+
+def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0) -> torch.Tensor:
+ frequencies = 1.0 / (theta ** (torch.arange(0, dim, 2)[: dim // 2].double() / dim))
+ phases = torch.outer(torch.arange(end, device=frequencies.device), frequencies)
+ return torch.polar(torch.ones_like(phases), phases)
+
+
+def precompute_freqs_cis_3d(
+ dim: int,
+ end: int = 1024,
+ theta: float = 10000.0,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ return (
+ precompute_freqs_cis(dim - 2 * (dim // 3), end, theta),
+ precompute_freqs_cis(dim // 3, end, theta),
+ precompute_freqs_cis(dim // 3, end, theta),
+ )
+
+
+def gelu_tanh(x: torch.Tensor) -> torch.Tensor:
+ """Apply tanh-GELU while reusing its inference input buffer."""
+
+ if torch.is_grad_enabled():
+ return F.gelu(x, approximate="tanh")
+ return torch.ops.aten.gelu_.default(x, approximate="tanh")
+
+
+def _rotate_rope_chunk(chunk: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
+ complex_chunk = torch.view_as_complex(
+ chunk.to(torch.float64).reshape(chunk.shape[0], chunk.shape[1], chunk.shape[2], -1, 2)
+ )
+ return torch.view_as_real(complex_chunk * freqs).reshape_as(chunk)
+
+
+def rope_apply(x: torch.Tensor, freqs: torch.Tensor, num_heads: int) -> torch.Tensor:
+ """Apply the checkpoint's FP64 RoPE with bounded temporary storage."""
+
+ headed = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
+ fp64_bytes = headed[0].numel() * torch.empty((), dtype=torch.float64).element_size()
+ temporary_bytes_per_batch = 2 * fp64_bytes
+ batch_chunk = max(
+ 1,
+ min(headed.shape[0], ROPE_TEMPORARY_BUDGET_BYTES // temporary_bytes_per_batch),
+ )
+
+ if torch.is_grad_enabled():
+ chunks = []
+ for start in range(0, headed.shape[0], batch_chunk):
+ chunk = headed[start : start + batch_chunk]
+ chunks.append(_rotate_rope_chunk(chunk, freqs).flatten(2).to(headed.dtype))
+ return torch.cat(chunks, dim=0)
+
+ output = torch.empty_like(headed)
+ for start in range(0, headed.shape[0], batch_chunk):
+ chunk = headed[start : start + batch_chunk]
+ output[start : start + batch_chunk].copy_(_rotate_rope_chunk(chunk, freqs))
+ return output.flatten(2)
class RMSNorm(nn.Module):
- def __init__(self, dim, eps=1e-5):
+ def __init__(self, dim: int, eps: float = 1e-5) -> None:
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
- def norm(self, x):
+ def _normalize_float(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
- def forward(self, x):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
- return self.norm(x.float()).to(dtype) * self.weight
-
-
-class AttentionModule(nn.Module):
- def __init__(self, num_heads):
- super().__init__()
- self.num_heads = num_heads
-
- def forward(self, q, k, v):
- x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads)
- return x
+ return self._normalize_float(x.float()).to(dtype) * self.weight
class SelfAttention(nn.Module):
- def __init__(self, dim: int, num_heads: int, eps: float = 1e-6):
+ def __init__(self, dim: int, num_heads: int, eps: float = NORM_EPSILON) -> None:
super().__init__()
- self.dim = dim
self.num_heads = num_heads
- self.head_dim = dim // num_heads
-
self.q = nn.Linear(dim, dim)
self.k = nn.Linear(dim, dim)
self.v = nn.Linear(dim, dim)
self.o = nn.Linear(dim, dim)
self.norm_q = RMSNorm(dim, eps=eps)
self.norm_k = RMSNorm(dim, eps=eps)
-
- self.attn = AttentionModule(self.num_heads)
- def forward(self, x, freqs):
+ def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
q = self.norm_q(self.q(x))
k = self.norm_k(self.k(x))
v = self.v(x)
q = rope_apply(q, freqs, self.num_heads)
k = rope_apply(k, freqs, self.num_heads)
- x = self.attn(q, k, v)
- return self.o(x)
+ return self.o(flash_attention(q, k, v, self.num_heads))
class CrossAttention(nn.Module):
- def __init__(self, dim: int, num_heads: int, eps: float = 1e-6, has_image_input: bool = False):
+ def __init__(self, dim: int, num_heads: int, eps: float = NORM_EPSILON) -> None:
super().__init__()
- self.dim = dim
self.num_heads = num_heads
- self.head_dim = dim // num_heads
-
self.q = nn.Linear(dim, dim)
self.k = nn.Linear(dim, dim)
self.v = nn.Linear(dim, dim)
self.o = nn.Linear(dim, dim)
self.norm_q = RMSNorm(dim, eps=eps)
self.norm_k = RMSNorm(dim, eps=eps)
- self.has_image_input = has_image_input
- if has_image_input:
- self.k_img = nn.Linear(dim, dim)
- self.v_img = nn.Linear(dim, dim)
- self.norm_k_img = RMSNorm(dim, eps=eps)
-
- self.attn = AttentionModule(self.num_heads)
-
- def forward(self, x: torch.Tensor, y: torch.Tensor):
- if self.has_image_input:
- img = y[:, :257]
- ctx = y[:, 257:]
- else:
- ctx = y
- q = self.norm_q(self.q(x))
- k = self.norm_k(self.k(ctx))
- v = self.v(ctx)
- x = self.attn(q, k, v)
- if self.has_image_input:
- k_img = self.norm_k_img(self.k_img(img))
- v_img = self.v_img(img)
- y = flash_attention(q, k_img, v_img, num_heads=self.num_heads)
- x = x + y
- return self.o(x)
-
-
-class CrossAttentionSrcCam(nn.Module):
- def __init__(self, dim: int, num_heads: int, eps: float = 1e-6):
- super().__init__()
- self.dim = dim
- self.num_heads = num_heads
- self.head_dim = dim // num_heads
- self.q = nn.Linear(dim, dim)
- self.k = nn.Linear(dim, dim)
- self.v = nn.Linear(dim, dim)
- self.o = nn.Linear(dim, dim)
- self.norm_q = RMSNorm(dim, eps=eps)
- self.norm_k = RMSNorm(dim, eps=eps)
-
- self.attn = AttentionModule(self.num_heads)
-
- def forward(self, x, x_src, freqs, freqs_src):
+ def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor:
q = self.norm_q(self.q(x))
- k = self.norm_k(self.k(x_src))
- v = self.v(x_src)
- q = rope_apply(q, freqs, self.num_heads)
- k = rope_apply(k, freqs_src, self.num_heads)
- x = self.attn(q, k, v)
- return self.o(x)
+ k = self.norm_k(self.k(context))
+ v = self.v(context)
+ return self.o(flash_attention(q, k, v, self.num_heads))
-class GateModule(nn.Module):
- def __init__(self,):
+class DiTBlock(nn.Module):
+ """One frozen video + multiview + prompt + FFN transformer block."""
+
+ def __init__(self) -> None:
super().__init__()
+ self.self_attn = SelfAttention(MODEL_DIM, NUM_HEADS)
+ self.cross_attn = CrossAttention(MODEL_DIM, NUM_HEADS)
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=NORM_EPSILON, elementwise_affine=False)
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=NORM_EPSILON, elementwise_affine=False)
+ self.norm3 = nn.LayerNorm(MODEL_DIM, eps=NORM_EPSILON)
+ self.ffn = nn.Sequential(
+ nn.Linear(MODEL_DIM, FFN_DIM),
+ nn.GELU(approximate="tanh"),
+ nn.Linear(FFN_DIM, MODEL_DIM),
+ )
+ self.modulation = nn.Parameter(torch.randn(1, 6, MODEL_DIM) / MODEL_DIM**0.5)
- def forward(self, x, gate, residual):
- return x + gate * residual
+ self.modulation_mvs = nn.Parameter(torch.randn(1, 3, MODEL_DIM) / MODEL_DIM**0.5)
+ self.norm1_mvs = nn.LayerNorm(MODEL_DIM, eps=NORM_EPSILON, elementwise_affine=False)
+ self.self_attn_mvs = SelfAttention(MODEL_DIM, NUM_HEADS)
-class DiTBlock(nn.Module):
- def __init__(self, has_image_input: bool, dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6):
- super().__init__()
- self.dim = dim
- self.num_heads = num_heads
- self.ffn_dim = ffn_dim
-
- self.disable_video_attn = False
- self.use_4d_attn = False
- self.use_mvs_attn = False
- self.use_src_self_attn = False
- self.use_src_cross_attn = False
- self.use_cam_encoder = False
-
- self.self_attn = SelfAttention(dim, num_heads, eps)
- self.cross_attn = CrossAttention(
- dim, num_heads, eps, has_image_input=has_image_input)
- self.norm1 = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
- self.norm2 = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
- self.norm3 = nn.LayerNorm(dim, eps=eps)
- self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.GELU(
- approximate='tanh'), nn.Linear(ffn_dim, dim))
- self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
- self.gate = GateModule()
-
- def forward(self, x, x_src, context, t_mod, freqs, freqs_mvs, freqs_src, cam_emb, shape):
- v, f, h, w = shape
-
- has_seq = len(t_mod.shape) == 4
- chunk_dim = 2 if has_seq else 1
- # msa: multi-head self-attention mlp: multi-layer perceptron
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
- self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod).chunk(6, dim=chunk_dim)
- if has_seq:
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
- shift_msa.squeeze(2), scale_msa.squeeze(2), gate_msa.squeeze(2),
- shift_mlp.squeeze(2), scale_mlp.squeeze(2), gate_mlp.squeeze(2),
- )
+ def _feed_forward(self, x: torch.Tensor) -> torch.Tensor:
+ hidden = self.ffn[0](x)
+ hidden = gelu_tanh(hidden)
+ return self.ffn[2](hidden)
- # video self-attention
- if not self.disable_video_attn:
- input_x = modulate(self.norm1(x), shift_msa, scale_msa)
- if self.use_4d_attn:
- input_x = rearrange(input_x, "v fhw c -> (v fhw) c").unsqueeze(0)
- freqs = repeat(freqs, "fhw 1 c -> (v fhw) 1 c", v=v)
- input_x = self.self_attn(input_x, freqs)
- if self.use_4d_attn:
- input_x = rearrange(input_x.squeeze(0), "(v fhw) c -> v fhw c", v=v)
- x = self.gate(x, gate_msa, input_x)
-
- # source-view self-attention
- if self.use_src_self_attn:
- x_cat = torch.cat([x, x_src], dim=1)
- shift_src, scale_src, gate_src = (
- self.modulation_src.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod[:, :3, :]).chunk(3, dim=1)
- input_x_cat = modulate(self.norm1_src(x_cat), shift_src, scale_src)
-
- freqs_cat = torch.cat([freqs, freqs_src], dim=0)
- input_x_cat = self.self_attn_src(input_x_cat, freqs_cat)
- x_cat = self.gate(x_cat, gate_src, input_x_cat)
- len_src = x_src.shape[1]
- x, x_src = x_cat[:, :-len_src, ...], x_cat[:, -len_src:, ...]
-
- # source-view cross-attention
- if self.use_src_cross_attn:
- shift_src, scale_src, gate_src = (
- self.modulation_src.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod[:, :3, :]).chunk(3, dim=1)
- input_x = modulate(self.norm1_src(x), shift_src, scale_src)
- input_x_src = self.norm1_src(x_src)
-
- input_x = self.cross_attn_src(input_x, input_x_src, freqs, freqs_src)
- x = self.gate(x, gate_src, input_x)
-
- # multiview self-attention
- if self.use_mvs_attn:
- shift_mvs, scale_mvs, gate_mvs = (
- self.modulation_mvs.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod[:, :3, :]).chunk(3, dim=1)
- input_x = modulate(self.norm1_mvs(x), shift_mvs, scale_mvs)
-
- # add camera embedding before multiview attention
- if self.use_cam_encoder and cam_emb is not None:
- cam_proj = self.cam_encoder(cam_emb) # (v, 1, dim)
- cam_proj = cam_proj.unsqueeze(2).unsqueeze(3).expand(-1, f, h, w, -1) # (v, f, h, w, dim)
- cam_proj = rearrange(cam_proj, "v f h w d -> v (f h w) d")
- input_x = input_x + cam_proj
-
- input_x = rearrange(input_x, "v (f h w) c -> f (v h w) c", v=v, f=f, h=h, w=w)
- input_x = self.self_attn_mvs(input_x, freqs_mvs)
- input_x = rearrange(input_x, "f (v h w) c -> v (f h w) c", v=v, f=f, h=h, w=w)
-
- # projector wraps multiview attention output
- if self.use_cam_encoder:
- input_x = self.projector(input_x)
-
- x = self.gate(x, gate_mvs, input_x)
-
- # prompt cross-attention
- context = repeat(context, "1 l c -> v l c", v=x.shape[0])
- x = x + self.cross_attn(self.norm3(x), context)
-
- # feed-forward network
- input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
- x = self.gate(x, gate_mlp, self.ffn(input_x))
-
- if self.use_src_self_attn:
- # for src self-attention, the x_src is updated as well
- x_src = x_src + self.cross_attn(self.norm3(x_src), context)
-
- input_x_src = modulate(self.norm2(x_src), shift_mlp, scale_mlp)
- x_src = self.gate(x_src, gate_mlp, self.ffn(input_x_src))
-
- return x, x_src
-
-
-class MLP(torch.nn.Module):
- def __init__(self, in_dim, out_dim, has_pos_emb=False):
- super().__init__()
- self.proj = torch.nn.Sequential(
- nn.LayerNorm(in_dim),
- nn.Linear(in_dim, in_dim),
- nn.GELU(),
- nn.Linear(in_dim, out_dim),
- nn.LayerNorm(out_dim)
+ def _multiview_attention(
+ self,
+ x: torch.Tensor,
+ shift: torch.Tensor,
+ scale: torch.Tensor,
+ multiview_freqs: torch.Tensor,
+ shape: tuple[int, int, int, int],
+ ) -> torch.Tensor:
+ views, frames, height, width = shape
+ x = rearrange(
+ modulate(self.norm1_mvs(x), shift, scale),
+ "v (f h w) c -> f (v h w) c",
+ v=views,
+ f=frames,
+ h=height,
+ w=width,
+ )
+ x = self.self_attn_mvs(x, multiview_freqs)
+ return rearrange(
+ x,
+ "f (v h w) c -> v (f h w) c",
+ v=views,
+ f=frames,
+ h=height,
+ w=width,
)
- self.has_pos_emb = has_pos_emb
- if has_pos_emb:
- self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
- def forward(self, x):
- if self.has_pos_emb:
- x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
- return self.proj(x)
+ def forward(
+ self,
+ x: torch.Tensor,
+ context: torch.Tensor,
+ time_modulation: torch.Tensor,
+ spatial_freqs: torch.Tensor,
+ multiview_freqs: torch.Tensor,
+ shape: tuple[int, int, int, int],
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
+ self.modulation.to(dtype=time_modulation.dtype, device=time_modulation.device) + time_modulation
+ ).chunk(6, dim=1)
+
+ x = x + gate_msa * self.self_attn(modulate(self.norm1(x), shift_msa, scale_msa), spatial_freqs)
+
+ shift_mvs, scale_mvs, gate_mvs = (
+ self.modulation_mvs.to(dtype=time_modulation.dtype, device=time_modulation.device)
+ + time_modulation[:, :3, :]
+ ).chunk(3, dim=1)
+ x = x + gate_mvs * self._multiview_attention(
+ x,
+ shift_mvs,
+ scale_mvs,
+ multiview_freqs,
+ shape,
+ )
+
+ x = x + self.cross_attn(self.norm3(x), repeat(context, "1 l c -> v l c", v=x.shape[0]))
+
+ residual = self._feed_forward(modulate(self.norm2(x), shift_mlp, scale_mlp))
+ return x + gate_mlp * residual
class Head(nn.Module):
- def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
+ def __init__(self) -> None:
super().__init__()
- self.dim = dim
- self.patch_size = patch_size
- self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
- self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
- self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
-
- def forward(self, x, t_mod):
- if len(t_mod.shape) == 3:
- shift, scale = (self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device) + t_mod.unsqueeze(2)).chunk(2, dim=2)
- x = (self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2)))
- else:
- if t_mod.shape[0] != 1:
- t_mod = t_mod[:, None, :] # [b, d] -> [b, 1, d]
- shift, scale = (self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod).chunk(2, dim=1)
- x = (self.head(self.norm(x) * (1 + scale) + shift))
+ self.norm = nn.LayerNorm(MODEL_DIM, eps=NORM_EPSILON, elementwise_affine=False)
+ self.head = nn.Linear(MODEL_DIM, LATENT_CHANNELS * math.prod(PATCH_SIZE))
+ self.modulation = nn.Parameter(torch.randn(1, 2, MODEL_DIM) / MODEL_DIM**0.5)
+
+ def forward(self, x: torch.Tensor, time_embedding: torch.Tensor) -> torch.Tensor:
+ time_embedding = time_embedding[:, None, :]
+ shift, scale = (
+ self.modulation.to(dtype=time_embedding.dtype, device=time_embedding.device) + time_embedding
+ ).chunk(2, dim=1)
+ return self.head(self.norm(x) * (1 + scale) + shift)
+
+
+def pad_for_3d_conv(x: torch.Tensor, kernel_size: tuple[int, int, int]) -> torch.Tensor:
+ """Replicate-pad a video so every dimension is divisible by a kernel."""
+
+ _, _, frames, height, width = x.shape
+ temporal, vertical, horizontal = kernel_size
+ pad_frames = (temporal - frames % temporal) % temporal
+ pad_height = (vertical - height % vertical) % vertical
+ pad_width = (horizontal - width % horizontal) % horizontal
+ if pad_frames == pad_height == pad_width == 0:
return x
+ return F.pad(x, (0, pad_width, 0, pad_height, 0, pad_frames), mode="replicate")
-def pad_for_3d_conv(x, kernel_size):
- """Pad to be divisible by kernel_size. From FramePack."""
- _, _, t, h, w = x.shape
- pt, ph, pw = kernel_size
- pad_t = (pt - (t % pt)) % pt
- pad_h = (ph - (h % ph)) % ph
- pad_w = (pw - (w % pw)) % pw
- if pad_t == 0 and pad_h == 0 and pad_w == 0:
- return x
- return F.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode='replicate')
+class ViewPackEmbedding(nn.Module):
+ """Pack four half-resolution reference views into one token grid."""
+ def __init__(self) -> None:
+ super().__init__()
+ temporal, vertical, horizontal = PATCH_SIZE
+ self.proj_2x = nn.Conv3d(
+ LATENT_CHANNELS,
+ MODEL_DIM,
+ kernel_size=(temporal, vertical * 2, horizontal * 2),
+ stride=(temporal, vertical * 2, horizontal * 2),
+ )
+ # The released checkpoint contains this trained partition even though
+ # public inference uses exactly four 2x references.
+ self.proj_4x = nn.Conv3d(
+ LATENT_CHANNELS,
+ MODEL_DIM,
+ kernel_size=(temporal, vertical * 4, horizontal * 4),
+ stride=(temporal, vertical * 4, horizontal * 4),
+ )
-class ViewPackEmbedding(nn.Module):
- """Multi-resolution spatial patch embedding for clean source views.
- Spatial-only downsampling: temporal dim preserved.
- Ref: HunyuanVideoPatchEmbedForCleanLatents in FramePack.
- Supported configurations (all exactly fill 4 quadrants):
- - 4×2x views (each 2x view → 1 quadrant)
- - 3×2x + 4×4x (3 quadrants from 2x + 1 quadrant from 4×4x tile)
- """
+class FourDAnyoneDiT(nn.Module):
+ """Exact immutable inference graph for the released model checkpoint."""
- def __init__(self, in_dim, dim, patch_size):
+ def __init__(self) -> None:
super().__init__()
- pt, ph, pw = patch_size # (1, 2, 2) for Wan
- # 2x: spatial 2x downsample relative to 1x -> kernel (1, 4, 4)
- self.proj_2x = nn.Conv3d(in_dim, dim, kernel_size=(pt, ph*2, pw*2), stride=(pt, ph*2, pw*2))
- # 4x: spatial 4x downsample relative to 1x -> kernel (1, 8, 8)
- self.proj_4x = nn.Conv3d(in_dim, dim, kernel_size=(pt, ph*4, pw*4), stride=(pt, ph*4, pw*4))
-
- @torch.no_grad()
- def initialize_from_patch_embedding(self, patch_embedding: nn.Conv3d):
- """FramePack-style init: tile spatial dims and scale by 1/area_ratio."""
- weight = patch_embedding.weight.detach().clone() # (dim, in_dim, 1, 2, 2)
- bias = patch_embedding.bias.detach().clone()
- sd = {
- 'proj_2x.weight': repeat(weight, 'b c t h w -> b c t (h 2) (w 2)') / 4.0,
- 'proj_2x.bias': bias.clone(),
- 'proj_4x.weight': repeat(weight, 'b c t h w -> b c t (h 4) (w 4)') / 16.0,
- 'proj_4x.bias': bias.clone(),
- }
- self.load_state_dict(sd)
-
-
-class WanModel(torch.nn.Module):
- def __init__(
- self,
- dim: int,
- in_dim: int,
- ffn_dim: int,
- out_dim: int,
- text_dim: int,
- freq_dim: int,
- eps: float,
- patch_size: Tuple[int, int, int],
- num_heads: int,
- num_layers: int,
- has_image_input: bool,
- has_image_pos_emb: bool = False,
- has_ref_conv: bool = False,
- add_control_adapter: bool = False,
- in_dim_control_adapter: int = 24,
- seperated_timestep: bool = False,
- require_vae_embedding: bool = True,
- require_clip_embedding: bool = True,
- fuse_vae_embedding_in_latents: bool = False,
- ):
- super().__init__()
- self.dim = dim
- self.in_dim = in_dim
- self.freq_dim = freq_dim
- self.has_image_input = has_image_input
- self.patch_size = patch_size
- self.seperated_timestep = seperated_timestep
- self.require_vae_embedding = require_vae_embedding
- self.require_clip_embedding = require_clip_embedding
- self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
-
self.patch_embedding = nn.Conv3d(
- in_dim, dim, kernel_size=patch_size, stride=patch_size)
+ LATENT_CHANNELS,
+ MODEL_DIM,
+ kernel_size=PATCH_SIZE,
+ stride=PATCH_SIZE,
+ )
self.text_embedding = nn.Sequential(
- nn.Linear(text_dim, dim),
- nn.GELU(approximate='tanh'),
- nn.Linear(dim, dim)
+ nn.Linear(TEXT_DIM, MODEL_DIM),
+ nn.GELU(approximate="tanh"),
+ nn.Linear(MODEL_DIM, MODEL_DIM),
)
self.time_embedding = nn.Sequential(
- nn.Linear(freq_dim, dim),
+ nn.Linear(FREQUENCY_DIM, MODEL_DIM),
nn.SiLU(),
- nn.Linear(dim, dim)
+ nn.Linear(MODEL_DIM, MODEL_DIM),
)
- self.time_projection = nn.Sequential(
- nn.SiLU(), nn.Linear(dim, dim * 6))
- self.blocks = nn.ModuleList([
- DiTBlock(has_image_input, dim, num_heads, ffn_dim, eps)
- for _ in range(num_layers)
- ])
- self.head = Head(dim, out_dim, patch_size, eps)
- head_dim = dim // num_heads
- self.freqs = precompute_freqs_cis_3d(head_dim)
-
- if has_image_input:
- self.img_emb = MLP(1280, dim, has_pos_emb=has_image_pos_emb) # clip_feature_dim = 1280
- if has_ref_conv:
- self.ref_conv = nn.Conv2d(16, dim, kernel_size=(2, 2), stride=(2, 2))
- self.has_image_pos_emb = has_image_pos_emb
- self.has_ref_conv = has_ref_conv
- if add_control_adapter:
- self.control_adapter = SimpleAdapter(in_dim_control_adapter, dim, kernel_size=patch_size[1:], stride=patch_size[1:])
- else:
- self.control_adapter = None
-
- def patchify(self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None):
- x = self.patch_embedding(x)
- if self.control_adapter is not None and control_camera_latents_input is not None:
- y_camera = self.control_adapter(control_camera_latents_input)
- x = [u + v for u, v in zip(x, y_camera)]
- x = x[0].unsqueeze(0)
- grid_size = x.shape[2:]
- x = rearrange(x, 'b c f h w -> b (f h w) c').contiguous()
- return x, grid_size # x, grid_size: (f, h, w)
-
- def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(MODEL_DIM, MODEL_DIM * 6))
+ self.blocks = nn.ModuleList(DiTBlock() for _ in range(NUM_LAYERS))
+ self.head = Head()
+ self.viewpack_embedding = ViewPackEmbedding()
+ self.freqs: tuple[torch.Tensor, torch.Tensor, torch.Tensor] = ()
+
+ def _patchify(self, x: torch.Tensor) -> tuple[torch.Tensor, tuple[int, int, int]]:
+ embedded = self.patch_embedding(x)
+ grid_size = tuple(embedded.shape[2:])
+ tokens = rearrange(embedded, "b c f h w -> b (f h w) c").contiguous()
+ return tokens, grid_size
+
+ @staticmethod
+ def _unpatchify(x: torch.Tensor, grid_size: tuple[int, int, int]) -> torch.Tensor:
return rearrange(
- x, 'b (f h w) (x y z c) -> b c (f x) (h y) (w z)',
- f=grid_size[0], h=grid_size[1], w=grid_size[2],
- x=self.patch_size[0], y=self.patch_size[1], z=self.patch_size[2]
+ x,
+ "b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
+ f=grid_size[0],
+ h=grid_size[1],
+ w=grid_size[2],
+ x=PATCH_SIZE[0],
+ y=PATCH_SIZE[1],
+ z=PATCH_SIZE[2],
)
- def forward(self,
- x: torch.Tensor,
- x_src: torch.Tensor,
- timestep: torch.Tensor,
- context: torch.Tensor,
- skeletons: Optional[torch.Tensor] = None,
- cam_emb: Optional[torch.Tensor] = None,
- drop_viewpack_tokens: bool = False,
- clip_feature: Optional[torch.Tensor] = None,
- y: Optional[torch.Tensor] = None,
- use_gradient_checkpointing: bool = False,
- use_gradient_checkpointing_offload: bool = False,
- **kwargs,
- ):
- context = self.text_embedding(context)
+ def _spatial_frequencies(
+ self,
+ frames: int,
+ height: int,
+ width: int,
+ device: torch.device,
+ ) -> torch.Tensor:
+ return (
+ torch.cat(
+ [
+ self.freqs[0][:frames].view(frames, 1, 1, -1).expand(frames, height, width, -1),
+ self.freqs[1][:height].view(1, height, 1, -1).expand(frames, height, width, -1),
+ self.freqs[2][:width].view(1, 1, width, -1).expand(frames, height, width, -1),
+ ],
+ dim=-1,
+ )
+ .reshape(frames * height * width, 1, -1)
+ .to(device)
+ )
- if self.has_image_input:
- x = torch.cat([x, y], dim=1) # (b, c_x + c_y, f, h, w)
- clip_embdding = self.img_emb(clip_feature)
- context = torch.cat([clip_embdding, context], dim=1)
-
- x, (f, h, w) = self.patchify(x)
-
- freqs = torch.cat([
- self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
- self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
- self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
- ], dim=-1).reshape(f * h * w, 1, -1).to(x.device)
-
- # build packed views from 1x/2x/4x source views
- v_src = x_src.shape[0]
- if v_src == 1:
- # 1×1x: no 2x/4x sources
- x_src_2x, x_src_4x = None, None
- elif v_src == 5:
- # 1×1x + 4×2x
- x_src, x_src_2x, x_src_4x = x_src[:1], x_src[1:], None
- elif v_src == 8:
- # 1×1x + 3×2x + 4×4x
- x_src, x_src_2x, x_src_4x = x_src[:1], x_src[1:4], x_src[4:]
- else:
- raise ValueError(f"Unsupported number of source views: {v_src}")
-
- # 1x source: always packed as one extra view
- x_src, (f_src, h_src, w_src) = self.patchify(x_src)
- if not self.use_src_attn:
- # use viewpack for 1x source views
- x = torch.cat([x, x_src], dim=0)
- x_src = None
- freqs_src = None
- v_pack = 1
+ def _multiview_frequencies(
+ self,
+ views: int,
+ height: int,
+ width: int,
+ device: torch.device,
+ ) -> torch.Tensor:
+ return (
+ torch.cat(
+ [
+ self.freqs[0][:views].view(views, 1, 1, -1).expand(views, height, width, -1),
+ self.freqs[1][:height].view(1, height, 1, -1).expand(views, height, width, -1),
+ self.freqs[2][:width].view(1, 1, width, -1).expand(views, height, width, -1),
+ ],
+ dim=-1,
+ )
+ .reshape(views * height * width, 1, -1)
+ .to(device)
+ )
+
+ def _pack_sources(
+ self,
+ x: torch.Tensor,
+ sources: torch.Tensor,
+ grid_size: tuple[int, int, int],
+ ) -> tuple[torch.Tensor, int]:
+ source_views = int(sources.shape[0])
+ if source_views == 1:
+ primary_source = sources
+ reference_sources = None
+ elif source_views == 5:
+ primary_source = sources[:1]
+ reference_sources = sources[1:]
else:
- # use src self/cross-attention for 1x source views
- x_src = repeat(x_src, "1 fhw_src c -> v fhw_src c", v=x.shape[0])
- freqs_src = torch.cat([
- self.freqs[0][self.freqs_src_shift:f_src + self.freqs_src_shift].view(f_src, 1, 1, -1).expand(f_src, h_src, w_src, -1),
- self.freqs[1][:h_src].view(1, h_src, 1, -1).expand(f_src, h_src, w_src, -1),
- self.freqs[2][:w_src].view(1, 1, w_src, -1).expand(f_src, h_src, w_src, -1)
- ], dim=-1).reshape(f_src * h_src * w_src, 1, -1).to(x.device)
- v_pack = 0
-
- # 2x/4x source views: packed after 1x source views
- if self.use_viewpack:
- if x_src_2x is not None:
- x_src_2x = pad_for_3d_conv(x_src_2x, self.viewpack_embedding.proj_2x.kernel_size)
- x_src_2x = self.viewpack_embedding.proj_2x(x_src_2x) # (v_2x, dim, f, h//2, w//2)
-
- if x_src_4x is not None:
- # tile 4x source views into 2x source views
- x_src_4x = pad_for_3d_conv(x_src_4x, self.viewpack_embedding.proj_4x.kernel_size)
- x_src_4x = self.viewpack_embedding.proj_4x(x_src_4x) # (4, dim, f, h//4, w//4)
- x_src_4x = rearrange(x_src_4x, '(g1 g2) c f h w -> 1 c f (g1 h) (g2 w)', g1=2, g2=2) # (1, dim, f, h//2, w//2)
- f_2x, h_2x, w_2x = x_src_2x.shape[2:] # crop padding surplus to match 2x source views (f, h, w)
- x_src_4x = x_src_4x[:, :, :f_2x, :h_2x, :w_2x]
- x_src_2x = torch.cat([x_src_2x, x_src_4x], dim=0) # (4, dim, f, h//2, w//2)
-
- # tile 2x source views into 1x source views
- x_pack = rearrange(x_src_2x, '(g1 g2) c f h w -> 1 c f (g1 h) (g2 w)', g1=2, g2=2)
- x_pack = x_pack[:, :, :f, :h, :w] # crop padding surplus to match 1x source views (f, h, w)
- x_pack = rearrange(x_pack, '1 c f h w -> 1 (f h w) c')
- x_pack = x_pack.to(dtype=x.dtype)
- if drop_viewpack_tokens:
- # Keep viewpack parameters in the autograd graph across distributed ranks.
- zero_dependency = x_pack.float().mean().to(dtype=x.dtype) * 0.0
- x = x + zero_dependency
- else:
- x = torch.cat([x, x_pack], dim=0)
- v_pack += 1
-
- timestep = torch.cat([timestep, torch.zeros(v_pack, device=timestep.device, dtype=timestep.dtype)])
- if skeletons is not None:
- skeletons = torch.cat([skeletons, -torch.ones_like(skeletons[:1]).expand(v_pack, -1, -1, -1, -1)], dim=0)
-
- # Expand cam_emb for viewpack views (zero vectors for packed source views)
- if cam_emb is not None:
- cam_emb = torch.cat([cam_emb, torch.zeros(v_pack, cam_emb.shape[-1],
- device=cam_emb.device, dtype=cam_emb.dtype)], dim=0)
- cam_emb = cam_emb.unsqueeze(1) # (v, 1, 12)
-
- # Compute time embeddings (after concat since timestep may have been extended)
- t = self.time_embedding(
- sinusoidal_embedding_1d(self.freq_dim, timestep).to(x.dtype))
- t_mod = self.time_projection(t).unflatten(1, (6, self.dim))
-
- if self.use_pose_encoder:
- skeleton_latents = self.pose_encoder(skeletons)
- skeleton_tokens = rearrange(skeleton_latents, "v c f h w -> v (f h w) c")
- x = x + skeleton_tokens
-
- v = x.shape[0]
- freqs_mvs = torch.cat([
- self.freqs[0][:v].view(v, 1, 1, -1).expand(v, h, w, -1),
- self.freqs[1][:h].view(1, h, 1, -1).expand(v, h, w, -1),
- self.freqs[2][:w].view(1, 1, w, -1).expand(v, h, w, -1)
- ], dim=-1).reshape(v * h * w, 1, -1).to(x.device)
-
- def create_custom_forward(module):
- def custom_forward(*inputs):
- return module(*inputs)
- return custom_forward
+ raise ValueError(f"4DAnyone requires 1 or 5 source views, got {source_views}.")
+
+ primary_tokens, _ = self._patchify(primary_source)
+ x = torch.cat([x, primary_tokens], dim=0)
+ packed_views = 1
+
+ if reference_sources is not None:
+ projection = self.viewpack_embedding.proj_2x
+ reference_sources = pad_for_3d_conv(reference_sources, projection.kernel_size)
+ packed = projection(reference_sources)
+ packed = rearrange(packed, "(g1 g2) c f h w -> 1 c f (g1 h) (g2 w)", g1=2, g2=2)
+ frames, height, width = grid_size
+ packed = packed[:, :, :frames, :height, :width]
+ packed = rearrange(packed, "1 c f h w -> 1 (f h w) c").to(dtype=x.dtype)
+ x = torch.cat([x, packed], dim=0)
+ packed_views += 1
+ return x, packed_views
- for block in self.blocks:
- if self.training and use_gradient_checkpointing:
- if use_gradient_checkpointing_offload:
- with torch.autograd.graph.save_on_cpu():
- x, x_src = torch.utils.checkpoint.checkpoint(
- create_custom_forward(block),
- x, x_src, context, t_mod, freqs, freqs_mvs, freqs_src, cam_emb, (v, f, h, w),
- use_reentrant=False,
- )
- else:
- x, x_src = torch.utils.checkpoint.checkpoint(
- create_custom_forward(block),
- x, x_src, context, t_mod, freqs, freqs_mvs, freqs_src, cam_emb, (v, f, h, w),
- use_reentrant=False,
- )
- else:
- x, x_src = block(x, x_src, context, t_mod, freqs, freqs_mvs, freqs_src, cam_emb, (v, f, h, w))
-
- # Strip added views (viewpack)
- if v_pack > 0:
- x = x[:-v_pack, ...]
- t = t[:-v_pack, ...]
-
- x = self.head(x, t)
- x = self.unpatchify(x, (f, h, w))
+ @staticmethod
+ def _add_pose_features(
+ x: torch.Tensor,
+ pose_features: torch.Tensor,
+ null_pose_feature: torch.Tensor,
+ target_views: int,
+ packed_views: int,
+ grid_size: tuple[int, int, int],
+ ) -> torch.Tensor:
+ frames, height, width = grid_size
+ expected_pose = (target_views, MODEL_DIM, frames, height, width)
+ expected_null = (packed_views, MODEL_DIM, frames, height, width)
+ if tuple(pose_features.shape) != expected_pose:
+ raise ValueError(f"Expected pose features {expected_pose}, got {tuple(pose_features.shape)}.")
+ if tuple(null_pose_feature.shape) != expected_null:
+ raise ValueError(f"Expected null pose features {expected_null}, got {tuple(null_pose_feature.shape)}.")
+ pose_tokens = rearrange(pose_features, "v c f h w -> v (f h w) c")
+ null_tokens = rearrange(null_pose_feature, "v c f h w -> v (f h w) c")
+ if torch.is_grad_enabled():
+ return torch.cat([x[:target_views] + pose_tokens, x[target_views:] + null_tokens], dim=0)
+ x[:target_views].add_(pose_tokens)
+ x[target_views:].add_(null_tokens)
return x
- @staticmethod
- def state_dict_converter():
- return WanModelStateDictConverter()
-
-
-class WanModelStateDictConverter:
- def __init__(self):
- pass
-
- def from_diffusers(self, state_dict):
- rename_dict = {
- "blocks.0.attn1.norm_k.weight": "blocks.0.self_attn.norm_k.weight",
- "blocks.0.attn1.norm_q.weight": "blocks.0.self_attn.norm_q.weight",
- "blocks.0.attn1.to_k.bias": "blocks.0.self_attn.k.bias",
- "blocks.0.attn1.to_k.weight": "blocks.0.self_attn.k.weight",
- "blocks.0.attn1.to_out.0.bias": "blocks.0.self_attn.o.bias",
- "blocks.0.attn1.to_out.0.weight": "blocks.0.self_attn.o.weight",
- "blocks.0.attn1.to_q.bias": "blocks.0.self_attn.q.bias",
- "blocks.0.attn1.to_q.weight": "blocks.0.self_attn.q.weight",
- "blocks.0.attn1.to_v.bias": "blocks.0.self_attn.v.bias",
- "blocks.0.attn1.to_v.weight": "blocks.0.self_attn.v.weight",
- "blocks.0.attn2.norm_k.weight": "blocks.0.cross_attn.norm_k.weight",
- "blocks.0.attn2.norm_q.weight": "blocks.0.cross_attn.norm_q.weight",
- "blocks.0.attn2.to_k.bias": "blocks.0.cross_attn.k.bias",
- "blocks.0.attn2.to_k.weight": "blocks.0.cross_attn.k.weight",
- "blocks.0.attn2.to_out.0.bias": "blocks.0.cross_attn.o.bias",
- "blocks.0.attn2.to_out.0.weight": "blocks.0.cross_attn.o.weight",
- "blocks.0.attn2.to_q.bias": "blocks.0.cross_attn.q.bias",
- "blocks.0.attn2.to_q.weight": "blocks.0.cross_attn.q.weight",
- "blocks.0.attn2.to_v.bias": "blocks.0.cross_attn.v.bias",
- "blocks.0.attn2.to_v.weight": "blocks.0.cross_attn.v.weight",
- "blocks.0.ffn.net.0.proj.bias": "blocks.0.ffn.0.bias",
- "blocks.0.ffn.net.0.proj.weight": "blocks.0.ffn.0.weight",
- "blocks.0.ffn.net.2.bias": "blocks.0.ffn.2.bias",
- "blocks.0.ffn.net.2.weight": "blocks.0.ffn.2.weight",
- "blocks.0.norm2.bias": "blocks.0.norm3.bias",
- "blocks.0.norm2.weight": "blocks.0.norm3.weight",
- "blocks.0.scale_shift_table": "blocks.0.modulation",
- "condition_embedder.text_embedder.linear_1.bias": "text_embedding.0.bias",
- "condition_embedder.text_embedder.linear_1.weight": "text_embedding.0.weight",
- "condition_embedder.text_embedder.linear_2.bias": "text_embedding.2.bias",
- "condition_embedder.text_embedder.linear_2.weight": "text_embedding.2.weight",
- "condition_embedder.time_embedder.linear_1.bias": "time_embedding.0.bias",
- "condition_embedder.time_embedder.linear_1.weight": "time_embedding.0.weight",
- "condition_embedder.time_embedder.linear_2.bias": "time_embedding.2.bias",
- "condition_embedder.time_embedder.linear_2.weight": "time_embedding.2.weight",
- "condition_embedder.time_proj.bias": "time_projection.1.bias",
- "condition_embedder.time_proj.weight": "time_projection.1.weight",
- "patch_embedding.bias": "patch_embedding.bias",
- "patch_embedding.weight": "patch_embedding.weight",
- "scale_shift_table": "head.modulation",
- "proj_out.bias": "head.head.bias",
- "proj_out.weight": "head.head.weight",
- }
- state_dict_ = {}
- for name, param in state_dict.items():
- if name in rename_dict:
- state_dict_[rename_dict[name]] = param
- else:
- name_ = ".".join(name.split(".")[:1] + ["0"] + name.split(".")[2:])
- if name_ in rename_dict:
- name_ = rename_dict[name_]
- name_ = ".".join(name_.split(".")[:1] + [name.split(".")[1]] + name_.split(".")[2:])
- state_dict_[name_] = param
- if hash_state_dict_keys(state_dict) == "cb104773c6c2cb6df4f9529ad5c60d0b":
- config = {
- "model_type": "t2v",
- "patch_size": (1, 2, 2),
- "text_len": 512,
- "in_dim": 16,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "window_size": (-1, -1),
- "qk_norm": True,
- "cross_attn_norm": True,
- "eps": 1e-6,
- }
- else:
- config = {}
- return state_dict_, config
-
- def from_civitai(self, state_dict):
- state_dict = {name: param for name, param in state_dict.items() if not name.startswith("vace")}
- if hash_state_dict_keys(state_dict) == "9269f8db9040a9d860eaca435be61814":
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 16,
- "dim": 1536,
- "ffn_dim": 8960,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 12,
- "num_layers": 30,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "aafcfd9672c3a2456dc46e1cb6e52c70":
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 16,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "6bfcfb3b342cb286ce886889d519a77e":
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "6d6ccde6845b95ad9114ab993d917893":
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 1536,
- "ffn_dim": 8960,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 12,
- "num_layers": 30,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "6bfcfb3b342cb286ce886889d519a77e":
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "349723183fc063b2bfc10bb2835cf677":
- # 1.3B PAI control
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 48,
- "dim": 1536,
- "ffn_dim": 8960,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 12,
- "num_layers": 30,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "efa44cddf936c70abd0ea28b6cbe946c":
- # 14B PAI control
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 48,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6
- }
- elif hash_state_dict_keys(state_dict) == "3ef3b1f8e1dab83d5b71fd7b617f859f":
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "has_image_pos_emb": True
- }
- elif hash_state_dict_keys(state_dict) == "70ddad9d3a133785da5ea371aae09504":
- # 1.3B PAI control v1.1
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 48,
- "dim": 1536,
- "ffn_dim": 8960,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 12,
- "num_layers": 30,
- "eps": 1e-6,
- "has_ref_conv": True
- }
- elif hash_state_dict_keys(state_dict) == "26bde73488a92e64cc20b0a7485b9e5b":
- # 14B PAI control v1.1
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 48,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "has_ref_conv": True
- }
- elif hash_state_dict_keys(state_dict) == "ac6a5aa74f4a0aab6f64eb9a72f19901":
- # 1.3B PAI control-camera v1.1
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 32,
- "dim": 1536,
- "ffn_dim": 8960,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 12,
- "num_layers": 30,
- "eps": 1e-6,
- "has_ref_conv": False,
- "add_control_adapter": True,
- "in_dim_control_adapter": 24,
- }
- elif hash_state_dict_keys(state_dict) == "b61c605c2adbd23124d152ed28e049ae":
- # 14B PAI control-camera v1.1
- config = {
- "has_image_input": True,
- "patch_size": [1, 2, 2],
- "in_dim": 32,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "has_ref_conv": False,
- "add_control_adapter": True,
- "in_dim_control_adapter": 24,
- }
- elif hash_state_dict_keys(state_dict) == "1f5ab7703c6fc803fdded85ff040c316":
- # Wan-AI/Wan2.2-TI2V-5B
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 48,
- "dim": 3072,
- "ffn_dim": 14336,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 48,
- "num_heads": 24,
- "num_layers": 30,
- "eps": 1e-6,
- "seperated_timestep": True,
- "require_clip_embedding": False,
- "require_vae_embedding": False,
- "fuse_vae_embedding_in_latents": True,
- }
- elif hash_state_dict_keys(state_dict) == "5b013604280dd715f8457c6ed6d6a626":
- # Wan-AI/Wan2.2-I2V-A14B
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "require_clip_embedding": False,
- }
- elif hash_state_dict_keys(state_dict) == "2267d489f0ceb9f21836532952852ee5":
- # Wan2.2-Fun-A14B-Control
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 52,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "has_ref_conv": True,
- "require_clip_embedding": False,
- }
- elif hash_state_dict_keys(state_dict) == "47dbeab5e560db3180adf51dc0232fb1":
- # Wan2.2-Fun-A14B-Control-Camera
- config = {
- "has_image_input": False,
- "patch_size": [1, 2, 2],
- "in_dim": 36,
- "dim": 5120,
- "ffn_dim": 13824,
- "freq_dim": 256,
- "text_dim": 4096,
- "out_dim": 16,
- "num_heads": 40,
- "num_layers": 40,
- "eps": 1e-6,
- "has_ref_conv": False,
- "add_control_adapter": True,
- "in_dim_control_adapter": 24,
- "require_clip_embedding": False,
- }
- else:
- config = {}
- return state_dict, config
+ def forward(
+ self,
+ *,
+ x: torch.Tensor,
+ x_src: torch.Tensor,
+ timestep: torch.Tensor,
+ context: torch.Tensor,
+ pose_features: torch.Tensor,
+ null_pose_feature: torch.Tensor,
+ ) -> torch.Tensor:
+ context = self.text_embedding(context)
+ target_views = int(x.shape[0])
+ x, grid_size = self._patchify(x)
+ frames, height, width = grid_size
+ spatial_freqs = self._spatial_frequencies(frames, height, width, x.device)
+
+ x, packed_views = self._pack_sources(x, x_src, grid_size)
+ timestep = torch.cat([timestep, torch.zeros(packed_views, dtype=timestep.dtype, device=timestep.device)])
+ time_embedding = self.time_embedding(sinusoidal_embedding_1d(FREQUENCY_DIM, timestep).to(x.dtype))
+ time_modulation = self.time_projection(time_embedding).unflatten(1, (6, MODEL_DIM))
+
+ x = self._add_pose_features(
+ x,
+ pose_features,
+ null_pose_feature,
+ target_views,
+ packed_views,
+ grid_size,
+ )
+ total_views = target_views + packed_views
+ multiview_freqs = self._multiview_frequencies(total_views, height, width, x.device)
+ shape = (total_views, frames, height, width)
+ for block in self.blocks:
+ x = block(x, context, time_modulation, spatial_freqs, multiview_freqs, shape)
+
+ x = x[:target_views]
+ time_embedding = time_embedding[:target_views]
+ return self._unpatchify(self.head(x, time_embedding), grid_size)
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py b/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py
index 5fcfcb0..b2bb516 100644
--- a/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py
+++ b/fdanyone/vendor/diffsynth/models/wan_video_pose_encoder.py
@@ -29,25 +29,25 @@ class PoseEncoder(nn.Module):
self.conv_layers = nn.Sequential(
nn.Conv3d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(in_channels, 16, kernel_size=kernel_size, stride=strides[0], padding=(1, 1, 1)),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(16, 16, kernel_size=3, stride=1, padding=1),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(16, 32, kernel_size=kernel_size, stride=strides[1], padding=(1, 1, 1)),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(32, 32, kernel_size=3, stride=1, padding=1),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(32, 64, kernel_size=kernel_size, stride=strides[2], padding=(1, 1, 1)),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(64, 64, kernel_size=3, stride=1, padding=1),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(64, 128, kernel_size=kernel_size, stride=strides[3], padding=(1, 1, 1)),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(128, 128, kernel_size=3, stride=1, padding=1),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
nn.Conv3d(128, 256, kernel_size=kernel_size, stride=strides[4], padding=(1, 1, 1)),
- nn.SiLU(),
+ nn.SiLU(inplace=True),
)
self.final_proj = nn.Conv3d(256, out_dim, kernel_size=1)
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_text_encoder.py b/fdanyone/vendor/diffsynth/models/wan_video_text_encoder.py
deleted file mode 100644
index c288737..0000000
--- a/fdanyone/vendor/diffsynth/models/wan_video_text_encoder.py
+++ /dev/null
@@ -1,269 +0,0 @@
-import math
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-
-
-def fp16_clamp(x):
- if x.dtype == torch.float16 and torch.isinf(x).any():
- clamp = torch.finfo(x.dtype).max - 1000
- x = torch.clamp(x, min=-clamp, max=clamp)
- return x
-
-
-class GELU(nn.Module):
-
- def forward(self, x):
- return 0.5 * x * (1.0 + torch.tanh(
- math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
-
-
-class T5LayerNorm(nn.Module):
-
- def __init__(self, dim, eps=1e-6):
- super(T5LayerNorm, self).__init__()
- self.dim = dim
- self.eps = eps
- self.weight = nn.Parameter(torch.ones(dim))
-
- def forward(self, x):
- x = x * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) +
- self.eps)
- if self.weight.dtype in [torch.float16, torch.bfloat16]:
- x = x.type_as(self.weight)
- return self.weight * x
-
-
-class T5Attention(nn.Module):
-
- def __init__(self, dim, dim_attn, num_heads, dropout=0.1):
- assert dim_attn % num_heads == 0
- super(T5Attention, self).__init__()
- self.dim = dim
- self.dim_attn = dim_attn
- self.num_heads = num_heads
- self.head_dim = dim_attn // num_heads
-
- # layers
- self.q = nn.Linear(dim, dim_attn, bias=False)
- self.k = nn.Linear(dim, dim_attn, bias=False)
- self.v = nn.Linear(dim, dim_attn, bias=False)
- self.o = nn.Linear(dim_attn, dim, bias=False)
- self.dropout = nn.Dropout(dropout)
-
- def forward(self, x, context=None, mask=None, pos_bias=None):
- """
- x: [B, L1, C].
- context: [B, L2, C] or None.
- mask: [B, L2] or [B, L1, L2] or None.
- """
- # check inputs
- context = x if context is None else context
- b, n, c = x.size(0), self.num_heads, self.head_dim
-
- # compute query, key, value
- q = self.q(x).view(b, -1, n, c)
- k = self.k(context).view(b, -1, n, c)
- v = self.v(context).view(b, -1, n, c)
-
- # attention bias
- attn_bias = x.new_zeros(b, n, q.size(1), k.size(1))
- if pos_bias is not None:
- attn_bias += pos_bias
- if mask is not None:
- assert mask.ndim in [2, 3]
- mask = mask.view(b, 1, 1,
- -1) if mask.ndim == 2 else mask.unsqueeze(1)
- attn_bias.masked_fill_(mask == 0, torch.finfo(x.dtype).min)
-
- # compute attention (T5 does not use scaling)
- attn = torch.einsum('binc,bjnc->bnij', q, k) + attn_bias
- attn = F.softmax(attn.float(), dim=-1).type_as(attn)
- x = torch.einsum('bnij,bjnc->binc', attn, v)
-
- # output
- x = x.reshape(b, -1, n * c)
- x = self.o(x)
- x = self.dropout(x)
- return x
-
-
-class T5FeedForward(nn.Module):
-
- def __init__(self, dim, dim_ffn, dropout=0.1):
- super(T5FeedForward, self).__init__()
- self.dim = dim
- self.dim_ffn = dim_ffn
-
- # layers
- self.gate = nn.Sequential(nn.Linear(dim, dim_ffn, bias=False), GELU())
- self.fc1 = nn.Linear(dim, dim_ffn, bias=False)
- self.fc2 = nn.Linear(dim_ffn, dim, bias=False)
- self.dropout = nn.Dropout(dropout)
-
- def forward(self, x):
- x = self.fc1(x) * self.gate(x)
- x = self.dropout(x)
- x = self.fc2(x)
- x = self.dropout(x)
- return x
-
-
-class T5SelfAttention(nn.Module):
-
- def __init__(self,
- dim,
- dim_attn,
- dim_ffn,
- num_heads,
- num_buckets,
- shared_pos=True,
- dropout=0.1):
- super(T5SelfAttention, self).__init__()
- self.dim = dim
- self.dim_attn = dim_attn
- self.dim_ffn = dim_ffn
- self.num_heads = num_heads
- self.num_buckets = num_buckets
- self.shared_pos = shared_pos
-
- # layers
- self.norm1 = T5LayerNorm(dim)
- self.attn = T5Attention(dim, dim_attn, num_heads, dropout)
- self.norm2 = T5LayerNorm(dim)
- self.ffn = T5FeedForward(dim, dim_ffn, dropout)
- self.pos_embedding = None if shared_pos else T5RelativeEmbedding(
- num_buckets, num_heads, bidirectional=True)
-
- def forward(self, x, mask=None, pos_bias=None):
- e = pos_bias if self.shared_pos else self.pos_embedding(
- x.size(1), x.size(1))
- x = fp16_clamp(x + self.attn(self.norm1(x), mask=mask, pos_bias=e))
- x = fp16_clamp(x + self.ffn(self.norm2(x)))
- return x
-
-
-class T5RelativeEmbedding(nn.Module):
-
- def __init__(self, num_buckets, num_heads, bidirectional, max_dist=128):
- super(T5RelativeEmbedding, self).__init__()
- self.num_buckets = num_buckets
- self.num_heads = num_heads
- self.bidirectional = bidirectional
- self.max_dist = max_dist
-
- # layers
- self.embedding = nn.Embedding(num_buckets, num_heads)
-
- def forward(self, lq, lk):
- device = self.embedding.weight.device
- # rel_pos = torch.arange(lk).unsqueeze(0).to(device) - \
- # torch.arange(lq).unsqueeze(1).to(device)
- rel_pos = torch.arange(lk, device=device).unsqueeze(0) - \
- torch.arange(lq, device=device).unsqueeze(1)
- rel_pos = self._relative_position_bucket(rel_pos)
- rel_pos_embeds = self.embedding(rel_pos)
- rel_pos_embeds = rel_pos_embeds.permute(2, 0, 1).unsqueeze(
- 0) # [1, N, Lq, Lk]
- return rel_pos_embeds.contiguous()
-
- def _relative_position_bucket(self, rel_pos):
- # preprocess
- if self.bidirectional:
- num_buckets = self.num_buckets // 2
- rel_buckets = (rel_pos > 0).long() * num_buckets
- rel_pos = torch.abs(rel_pos)
- else:
- num_buckets = self.num_buckets
- rel_buckets = 0
- rel_pos = -torch.min(rel_pos, torch.zeros_like(rel_pos))
-
- # embeddings for small and large positions
- max_exact = num_buckets // 2
- rel_pos_large = max_exact + (torch.log(rel_pos.float() / max_exact) /
- math.log(self.max_dist / max_exact) *
- (num_buckets - max_exact)).long()
- rel_pos_large = torch.min(
- rel_pos_large, torch.full_like(rel_pos_large, num_buckets - 1))
- rel_buckets += torch.where(rel_pos < max_exact, rel_pos, rel_pos_large)
- return rel_buckets
-
-def init_weights(m):
- if isinstance(m, T5LayerNorm):
- nn.init.ones_(m.weight)
- elif isinstance(m, T5FeedForward):
- nn.init.normal_(m.gate[0].weight, std=m.dim**-0.5)
- nn.init.normal_(m.fc1.weight, std=m.dim**-0.5)
- nn.init.normal_(m.fc2.weight, std=m.dim_ffn**-0.5)
- elif isinstance(m, T5Attention):
- nn.init.normal_(m.q.weight, std=(m.dim * m.dim_attn)**-0.5)
- nn.init.normal_(m.k.weight, std=m.dim**-0.5)
- nn.init.normal_(m.v.weight, std=m.dim**-0.5)
- nn.init.normal_(m.o.weight, std=(m.num_heads * m.dim_attn)**-0.5)
- elif isinstance(m, T5RelativeEmbedding):
- nn.init.normal_(
- m.embedding.weight, std=(2 * m.num_buckets * m.num_heads)**-0.5)
-
-
-class WanTextEncoder(torch.nn.Module):
-
- def __init__(self,
- vocab=256384,
- dim=4096,
- dim_attn=4096,
- dim_ffn=10240,
- num_heads=64,
- num_layers=24,
- num_buckets=32,
- shared_pos=False,
- dropout=0.1):
- super(WanTextEncoder, self).__init__()
- self.dim = dim
- self.dim_attn = dim_attn
- self.dim_ffn = dim_ffn
- self.num_heads = num_heads
- self.num_layers = num_layers
- self.num_buckets = num_buckets
- self.shared_pos = shared_pos
-
- # layers
- self.token_embedding = vocab if isinstance(vocab, nn.Embedding) \
- else nn.Embedding(vocab, dim)
- self.pos_embedding = T5RelativeEmbedding(
- num_buckets, num_heads, bidirectional=True) if shared_pos else None
- self.dropout = nn.Dropout(dropout)
- self.blocks = nn.ModuleList([
- T5SelfAttention(dim, dim_attn, dim_ffn, num_heads, num_buckets,
- shared_pos, dropout) for _ in range(num_layers)
- ])
- self.norm = T5LayerNorm(dim)
-
- # initialize weights
- self.apply(init_weights)
-
- def forward(self, ids, mask=None):
- x = self.token_embedding(ids)
- x = self.dropout(x)
- e = self.pos_embedding(x.size(1),
- x.size(1)) if self.shared_pos else None
- for block in self.blocks:
- x = block(x, mask, pos_bias=e)
- x = self.norm(x)
- x = self.dropout(x)
- return x
-
- @staticmethod
- def state_dict_converter():
- return WanTextEncoderStateDictConverter()
-
-
-class WanTextEncoderStateDictConverter:
- def __init__(self):
- pass
-
- def from_diffusers(self, state_dict):
- return state_dict
-
- def from_civitai(self, state_dict):
- return state_dict
diff --git a/fdanyone/vendor/diffsynth/models/wan_video_vae.py b/fdanyone/vendor/diffsynth/models/wan_video_vae.py
index 43057ff..48aa72b 100644
--- a/fdanyone/vendor/diffsynth/models/wan_video_vae.py
+++ b/fdanyone/vendor/diffsynth/models/wan_video_vae.py
@@ -1353,30 +1353,35 @@ class VideoVAE38_(VideoVAE_):
class WanVideoVAE38(WanVideoVAE):
+ NORMALIZATION_MEAN = (
+ -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
+ -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
+ -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
+ -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
+ -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
+ 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667,
+ )
+ NORMALIZATION_STD = (
+ 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
+ 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
+ 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
+ 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
+ 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
+ 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744,
+ )
+
def __init__(self, z_dim=48, dim=160):
super(WanVideoVAE, self).__init__()
-
- mean = [
- -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
- -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
- -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
- -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
- -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
- 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667
- ]
- std = [
- 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
- 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
- 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
- 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
- 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
- 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744
- ]
- self.mean = torch.tensor(mean)
- self.std = torch.tensor(std)
- self.scale = [self.mean, 1.0 / self.std]
+ self.materialize_normalization()
# init model
self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False)
self.upsampling_factor = 16
self.z_dim = z_dim
+
+ def materialize_normalization(self, device=None):
+ """Create the derived normalization tensors on a real or meta device."""
+
+ self.mean = torch.tensor(self.NORMALIZATION_MEAN, device=device)
+ self.std = torch.tensor(self.NORMALIZATION_STD, device=device)
+ self.scale = [self.mean, 1.0 / self.std]
diff --git a/fdanyone/vendor/diffsynth/pipelines/__init__.py b/fdanyone/vendor/diffsynth/pipelines/__init__.py
deleted file mode 100644
index 3117b0d..0000000
--- a/fdanyone/vendor/diffsynth/pipelines/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Vendored inference pipelines."""
-
-from .wan_video_spatem import WanVideoSpaTemPipeline
-
-__all__ = ["WanVideoSpaTemPipeline"]
diff --git a/fdanyone/vendor/diffsynth/pipelines/base.py b/fdanyone/vendor/diffsynth/pipelines/base.py
deleted file mode 100644
index 2a4f01c..0000000
--- a/fdanyone/vendor/diffsynth/pipelines/base.py
+++ /dev/null
@@ -1,127 +0,0 @@
-import torch
-import numpy as np
-from PIL import Image
-from torchvision.transforms import GaussianBlur
-
-
-
-class BasePipeline(torch.nn.Module):
-
- def __init__(self, device="cuda", torch_dtype=torch.float16, height_division_factor=64, width_division_factor=64):
- super().__init__()
- self.device = device
- self.torch_dtype = torch_dtype
- self.height_division_factor = height_division_factor
- self.width_division_factor = width_division_factor
- self.cpu_offload = False
- self.model_names = []
-
-
- def check_resize_height_width(self, height, width):
- if height % self.height_division_factor != 0:
- height = (height + self.height_division_factor - 1) // self.height_division_factor * self.height_division_factor
- print(f"The height cannot be evenly divided by {self.height_division_factor}. We round it up to {height}.")
- if width % self.width_division_factor != 0:
- width = (width + self.width_division_factor - 1) // self.width_division_factor * self.width_division_factor
- print(f"The width cannot be evenly divided by {self.width_division_factor}. We round it up to {width}.")
- return height, width
-
-
- def preprocess_image(self, image):
- image = torch.Tensor(np.array(image, dtype=np.float32) * (2 / 255) - 1).permute(2, 0, 1).unsqueeze(0)
- return image
-
-
- def preprocess_images(self, images):
- return [self.preprocess_image(image) for image in images]
-
-
- def vae_output_to_image(self, vae_output):
- image = vae_output[0].cpu().float().permute(1, 2, 0).numpy()
- image = Image.fromarray(((image / 2 + 0.5).clip(0, 1) * 255).astype("uint8"))
- return image
-
-
- def vae_output_to_video(self, vae_output):
- video = vae_output.cpu().permute(1, 2, 0).numpy()
- video = [Image.fromarray(((image / 2 + 0.5).clip(0, 1) * 255).astype("uint8")) for image in video]
- return video
-
-
- def merge_latents(self, value, latents, masks, scales, blur_kernel_size=33, blur_sigma=10.0):
- if len(latents) > 0:
- blur = GaussianBlur(kernel_size=blur_kernel_size, sigma=blur_sigma)
- height, width = value.shape[-2:]
- weight = torch.ones_like(value)
- for latent, mask, scale in zip(latents, masks, scales):
- mask = self.preprocess_image(mask.resize((width, height))).mean(dim=1, keepdim=True) > 0
- mask = mask.repeat(1, latent.shape[1], 1, 1).to(dtype=latent.dtype, device=latent.device)
- mask = blur(mask)
- value += latent * mask * scale
- weight += mask * scale
- value /= weight
- return value
-
-
- def control_noise_via_local_prompts(self, prompt_emb_global, prompt_emb_locals, masks, mask_scales, inference_callback, special_kwargs=None, special_local_kwargs_list=None):
- if special_kwargs is None:
- noise_pred_global = inference_callback(prompt_emb_global)
- else:
- noise_pred_global = inference_callback(prompt_emb_global, special_kwargs)
- if special_local_kwargs_list is None:
- noise_pred_locals = [inference_callback(prompt_emb_local) for prompt_emb_local in prompt_emb_locals]
- else:
- noise_pred_locals = [inference_callback(prompt_emb_local, special_kwargs) for prompt_emb_local, special_kwargs in zip(prompt_emb_locals, special_local_kwargs_list)]
- noise_pred = self.merge_latents(noise_pred_global, noise_pred_locals, masks, mask_scales)
- return noise_pred
-
-
- def extend_prompt(self, prompt, local_prompts, masks, mask_scales):
- local_prompts = local_prompts or []
- masks = masks or []
- mask_scales = mask_scales or []
- extended_prompt_dict = self.prompter.extend_prompt(prompt)
- prompt = extended_prompt_dict.get("prompt", prompt)
- local_prompts += extended_prompt_dict.get("prompts", [])
- masks += extended_prompt_dict.get("masks", [])
- mask_scales += [100.0] * len(extended_prompt_dict.get("masks", []))
- return prompt, local_prompts, masks, mask_scales
-
-
- def enable_cpu_offload(self):
- self.cpu_offload = True
-
-
- def load_models_to_device(self, loadmodel_names=[]):
- # only load models to device if cpu_offload is enabled
- if not self.cpu_offload:
- return
- # offload the unneeded models to cpu
- for model_name in self.model_names:
- if model_name not in loadmodel_names:
- model = getattr(self, model_name)
- if model is not None:
- if hasattr(model, "vram_management_enabled") and model.vram_management_enabled:
- for module in model.modules():
- if hasattr(module, "offload"):
- module.offload()
- else:
- model.cpu()
- # load the needed models to device
- for model_name in loadmodel_names:
- model = getattr(self, model_name)
- if model is not None:
- if hasattr(model, "vram_management_enabled") and model.vram_management_enabled:
- for module in model.modules():
- if hasattr(module, "onload"):
- module.onload()
- else:
- model.to(self.device)
- # fresh the cuda cache
- torch.cuda.empty_cache()
-
-
- def generate_noise(self, shape, seed=None, device="cpu", dtype=torch.float16):
- generator = None if seed is None else torch.Generator(device).manual_seed(seed)
- noise = torch.randn(shape, generator=generator, device=device, dtype=dtype)
- return noise
diff --git a/fdanyone/vendor/diffsynth/pipelines/wan_video_spatem.py b/fdanyone/vendor/diffsynth/pipelines/wan_video_spatem.py
deleted file mode 100644
index 53ad33c..0000000
--- a/fdanyone/vendor/diffsynth/pipelines/wan_video_spatem.py
+++ /dev/null
@@ -1,518 +0,0 @@
-from ..models.wan_video_dit import WanModel
-from ..models.wan_video_pose_encoder import PoseEncoder
-from ..models.wan_video_text_encoder import WanTextEncoder
-from ..models.wan_video_vae import WanVideoVAE
-from ..schedulers.flow_match import FlowMatchScheduler
-from ..schedulers.bride_match import BridgeMatchScheduler
-from ..pipelines.base import BasePipeline
-from ..prompters.wan_prompter import WanPrompter
-import torch
-import torch.nn as nn
-import numpy as np
-import torch.nn.functional as F
-from PIL import Image
-from tqdm import tqdm
-from typing import Optional
-from functools import partial
-from einops import rearrange
-
-from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear
-from ..models.wan_video_text_encoder import T5RelativeEmbedding, T5LayerNorm
-from ..models.wan_video_dit import RMSNorm, SelfAttention, CrossAttentionSrcCam, ViewPackEmbedding
-from ..models.wan_video_vae import RMS_norm, CausalConv3d, Upsample
-
-
-class WanVideoSpaTemPipeline(BasePipeline):
-
- def __init__(self, device="cuda", torch_dtype=torch.float16, tokenizer_path=None):
- super().__init__(device=device, torch_dtype=torch_dtype)
- self.scheduler = FlowMatchScheduler(shift=5, sigma_min=0.0, extra_one_step=True)
- self.prompter = WanPrompter(tokenizer_path=tokenizer_path)
- self.text_encoder: WanTextEncoder = None
- self.dit: WanModel = None
- self.vae: WanVideoVAE = None
- self.model_names = ["text_encoder", "dit", "vae"]
- self.height_division_factor = 16
- self.width_division_factor = 16
-
- def enable_vram_management(self, num_persistent_param_in_dit=None):
- dtype = next(iter(self.text_encoder.parameters())).dtype
- enable_vram_management(
- self.text_encoder,
- module_map={
- torch.nn.Linear: AutoWrappedLinear,
- torch.nn.Embedding: AutoWrappedModule,
- T5RelativeEmbedding: AutoWrappedModule,
- T5LayerNorm: AutoWrappedModule,
- },
- module_config=dict(
- offload_dtype=dtype,
- offload_device="cpu",
- onload_dtype=dtype,
- onload_device="cpu",
- computation_dtype=self.torch_dtype,
- computation_device=self.device,
- ),
- )
- dtype = next(iter(self.dit.parameters())).dtype
- enable_vram_management(
- self.dit,
- module_map={
- torch.nn.Linear: AutoWrappedLinear,
- torch.nn.Conv3d: AutoWrappedModule,
- torch.nn.LayerNorm: AutoWrappedModule,
- RMSNorm: AutoWrappedModule,
- },
- module_config=dict(
- offload_dtype=dtype,
- offload_device="cpu",
- onload_dtype=dtype,
- onload_device=self.device,
- computation_dtype=self.torch_dtype,
- computation_device=self.device,
- ),
- max_num_param=num_persistent_param_in_dit,
- overflow_module_config=dict(
- offload_dtype=dtype,
- offload_device="cpu",
- onload_dtype=dtype,
- onload_device="cpu",
- computation_dtype=self.torch_dtype,
- computation_device=self.device,
- ),
- )
- dtype = next(iter(self.vae.parameters())).dtype
- enable_vram_management(
- self.vae,
- module_map={
- torch.nn.Linear: AutoWrappedLinear,
- torch.nn.Conv2d: AutoWrappedModule,
- RMS_norm: AutoWrappedModule,
- CausalConv3d: AutoWrappedModule,
- Upsample: AutoWrappedModule,
- torch.nn.SiLU: AutoWrappedModule,
- torch.nn.Dropout: AutoWrappedModule,
- },
- module_config=dict(
- offload_dtype=dtype,
- offload_device="cpu",
- onload_dtype=dtype,
- onload_device=self.device,
- computation_dtype=self.torch_dtype,
- computation_device=self.device,
- ),
- )
- self.enable_cpu_offload()
-
- def init_spatem_modules(
- self,
- disable_video_attn: bool = False,
- use_4d_attn: bool = False,
- use_mvs_attn: bool = False,
- use_src_self_attn: bool = False,
- use_src_cross_attn: bool = False,
- freqs_src_shift: int = 121,
- use_viewpack: bool = True,
- viewpack_dropout_prob: float = 0.0,
- use_pose_encoder: bool = True,
- pose_encoder_type: str = "rgb",
- use_cam_encoder: bool = False,
- range_4d_attn: tuple[int, int, int] = (0, None, 2),
- range_mvs_attn: tuple[int, int, int] = (1, None, 2),
- range_src_self_attn: tuple[int, int, int] = (0, None, 2),
- range_src_cross_attn: tuple[int, int, int] = (0, None, 2),
- use_lbm: bool = False,
- fill_wpmask_with_noise: bool = False,
- ):
- device, dtype = self.dit.patch_embedding.weight.device, self.dit.patch_embedding.weight.dtype
-
- if disable_video_attn:
- # todo: delete self_attn layers from the model
- if use_4d_attn:
- raise ValueError("Cannot use 4D attention when video attention is disabled")
- for block in self.dit.blocks:
- block.disable_video_attn = True
-
- if use_4d_attn:
- b, e, s = range_4d_attn
- for block in self.dit.blocks[b:e:s]:
- block.use_4d_attn = True
-
- if use_mvs_attn:
- b, e, s = range_mvs_attn
- for block in self.dit.blocks[b:e:s]:
- block.use_mvs_attn = True
-
- dim = block.self_attn.q.weight.shape[0]
- block.modulation_mvs = nn.Parameter(block.modulation[:, :3, :].detach().clone())
- block.norm1_mvs = nn.LayerNorm(dim, eps=block.norm1.eps, elementwise_affine=False).to(
- device=device, dtype=dtype
- )
- block.self_attn_mvs = SelfAttention(dim, block.self_attn.num_heads, block.self_attn.norm_q.eps).to(
- device=device, dtype=dtype
- )
- block.self_attn_mvs.load_state_dict(block.self_attn.state_dict(), strict=True)
-
- if not 0.0 <= viewpack_dropout_prob <= 1.0:
- raise ValueError("viewpack_dropout_prob should be between 0 and 1")
- if viewpack_dropout_prob > 0.0 and not use_viewpack:
- raise ValueError("viewpack_dropout_prob requires use_viewpack=True")
-
- if use_viewpack:
- viewpack_emb = ViewPackEmbedding(
- in_dim=self.dit.patch_embedding.weight.shape[1],
- dim=self.dit.patch_embedding.weight.shape[0],
- patch_size=list(self.dit.patch_embedding.kernel_size),
- )
- viewpack_emb.initialize_from_patch_embedding(self.dit.patch_embedding)
- self.dit.viewpack_embedding = viewpack_emb.to(device=device, dtype=dtype)
- elif use_src_self_attn:
- if use_src_cross_attn:
- raise ValueError("Cannot use both src self-attention and src cross-attention")
-
- b, e, s = range_src_self_attn
- for block in self.dit.blocks[b:e:s]:
- block.use_src_self_attn = True
-
- dim = block.self_attn.q.weight.shape[0]
- block.modulation_src = nn.Parameter(block.modulation[:, :3, :].detach().clone())
- block.norm1_src = nn.LayerNorm(dim, eps=block.norm1.eps, elementwise_affine=False).to(
- device=device, dtype=dtype
- )
- block.self_attn_src = SelfAttention(dim, block.self_attn.num_heads, block.self_attn.norm_q.eps).to(
- device=device, dtype=dtype
- )
- block.self_attn_src.load_state_dict(block.self_attn.state_dict(), strict=True)
- elif use_src_cross_attn:
- b, e, s = range_src_cross_attn
- for block in self.dit.blocks[b:e:s]:
- block.use_src_cross_attn = True
-
- dim = block.self_attn.q.weight.shape[0]
- block.modulation_src = nn.Parameter(block.modulation[:, :3, :].detach().clone())
- block.norm1_src = nn.LayerNorm(dim, eps=block.norm1.eps, elementwise_affine=False).to(
- device=device, dtype=dtype
- )
- block.cross_attn_src = CrossAttentionSrcCam(
- dim, block.self_attn.num_heads, block.self_attn.norm_q.eps
- ).to(device=device, dtype=dtype)
- block.cross_attn_src.load_state_dict(block.self_attn.state_dict(), strict=True)
-
- if use_pose_encoder:
- if pose_encoder_type == "rgb":
- in_channels = 3
- elif pose_encoder_type == "rgbd":
- in_channels = 4
- else:
- raise ValueError(f"Invalid pose_encoder_type: {pose_encoder_type}")
- pose_encoder = PoseEncoder(out_dim=self.dit.patch_embedding.out_channels, in_channels=in_channels)
- self.dit.pose_encoder = pose_encoder.to(device=device, dtype=dtype)
-
- if use_cam_encoder:
- dim = self.dit.blocks[0].self_attn.q.weight.shape[0]
- for block in self.dit.blocks:
- block.use_cam_encoder = True
- block.cam_encoder = nn.Linear(12, dim).to(device=device, dtype=dtype)
- block.projector = nn.Linear(dim, dim).to(device=device, dtype=dtype)
- block.cam_encoder.weight.data.zero_()
- block.cam_encoder.bias.data.zero_()
- block.projector.weight = nn.Parameter(torch.eye(dim, device=device, dtype=dtype))
- block.projector.bias = nn.Parameter(torch.zeros(dim, device=device, dtype=dtype))
-
- if use_lbm:
- # TODO: hard-code for now
- self.scheduler = BridgeMatchScheduler()
- self.dit.fill_wpmask_with_noise = fill_wpmask_with_noise
-
- self.dit.use_pose_encoder = use_pose_encoder
- self.dit.use_cam_encoder = use_cam_encoder
- self.dit.use_viewpack = use_viewpack
- self.dit.viewpack_dropout_prob = viewpack_dropout_prob
- self.dit.use_src_attn = use_src_self_attn or use_src_cross_attn
- self.dit.use_lbm = use_lbm
- self.dit.freqs_src_shift = freqs_src_shift
-
- def denoising_model(self):
- return self.dit
-
- def encode_prompt(self, prompt, positive=True):
- prompt_emb = self.prompter.encode_prompt(prompt, positive=positive)
- return {"context": prompt_emb}
-
- def tensor2video(self, frames):
- frames = rearrange(frames, "c f h w -> f h w c")
- frames = ((frames.float() + 1) * 127.5).clip(0, 255).cpu().numpy().astype(np.uint8)
- frames = [Image.fromarray(frame) for frame in frames]
- return frames
-
- def prepare_extra_input(self, latents=None):
- return {}
-
- def encode_video(self, input_video, tiled=True, tile_size=(34, 34), tile_stride=(18, 16)):
- latents = self.vae.encode(
- input_video, device=self.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride
- )
- return latents
-
- def decode_video(self, latents, tiled=True, tile_size=(34, 34), tile_stride=(18, 16)):
- frames = self.vae.decode(latents, device=self.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
- return frames
-
- def encode_fmask(self, mask, size):
- f_, h_, w_ = size
- g_ = (mask.shape[2] - 1) // (f_ - 1)
-
- # union of the frames in each latent (the first frame is encoded independently)
- mask = torch.cat([mask[:, :, :1].repeat(1, 1, g_ - 1, 1, 1), mask], dim=2)
- mask = rearrange(mask, "v c (f g) h w -> v c f g h w", f=f_, g=g_)
- mask = mask.max(dim=3).values
-
- # interpolate along the spatial dimensions
- mask = rearrange(mask, "v c f h w -> (v f) c h w")
- mask = F.interpolate(mask, size=(h_, w_), mode="area")
- mask = rearrange(mask, "(v f) c h w -> v c f h w", f=f_)
- return mask
-
- def encode_wpmask(self, mask, size):
- f_, h_, w_ = size
- g_ = (mask.shape[2] - 1) // (f_ - 1)
-
- # intersection of the frames in each latent (the first frame is encoded independently)
- mask = torch.cat([mask[:, :, :1].repeat(1, 1, g_ - 1, 1, 1), mask], dim=2)
- mask = rearrange(mask, "v c (f g) h w -> v c f g h w", f=f_, g=g_)
- mask = mask.min(dim=3).values
-
- # interpolate along the spatial dimensions
- mask = rearrange(mask, "v c f h w -> (v f) c h w")
- mask = F.interpolate(mask, size=(h_, w_), mode="area")
- mask = rearrange(mask, "(v f) c h w -> v c f h w", f=f_)
- return mask
-
- @torch.no_grad()
- def __call__(
- self,
- prompt,
- negative_prompt="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
- src_videos: torch.Tensor = None,
- skeletons: torch.Tensor = None,
- wpvideos: torch.Tensor = None,
- wpmasks: torch.Tensor = None,
- cam_emb: torch.Tensor = None,
- input_image: Image.Image = None,
- input_video: torch.Tensor = None,
- denoising_strength: float = 1.0,
- seed: int = None,
- rand_device: str = "cpu",
- height: int = 832,
- width: int = 480,
- num_frames: int = None,
- cfg_scale: float = 5.0,
- num_inference_steps: int = 50,
- sigma_shift: float = 5.0,
- tiled: bool = True,
- tile_size: tuple[int, int] = (52, 30),
- tile_stride: tuple[int, int] = (26, 15),
- tea_cache_l1_thresh: float = None,
- tea_cache_model_id: str = "",
- progress_bar_cmd=partial(tqdm, desc="Denoising"),
- progress_bar_st=None,
- return_tensor=False,
- ):
- assert num_frames is None, "num_frames is not supported for WanVideoSpaTemPipeline"
- assert input_image is None, "input_image is not supported for WanVideoSpaTemPipeline"
- assert input_video is None, "input_video is not supported for WanVideoSpaTemPipeline"
- assert tea_cache_l1_thresh is None, "tea_cache_l1_thresh is not supported for WanVideoSpaTemPipeline"
-
- # Parameter check
- height, width = self.check_resize_height_width(height, width)
-
- # Tiler parameters
- tiler_kwargs = {"tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride}
-
- # Scheduler
- if self.dit.use_lbm:
- # bridge matching scheduler
- self.scheduler.set_timesteps(num_inference_steps)
- else:
- # flow matching scheduler
- self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength, shift=sigma_shift)
-
- src_videos = src_videos.to(dtype=self.torch_dtype, device=self.device)
- if skeletons is not None:
- skeletons = skeletons.to(dtype=self.torch_dtype, device=self.device)
- if wpvideos is not None:
- wpvideos = wpvideos.to(dtype=self.torch_dtype, device=self.device)
- if wpmasks is not None:
- wpmasks = wpmasks.to(dtype=self.torch_dtype, device=self.device)
- if cam_emb is not None:
- cam_emb = cam_emb.to(dtype=self.torch_dtype, device=self.device)
-
- if skeletons is not None:
- num_cameras = skeletons.shape[0]
- num_frames = skeletons.shape[2]
- elif wpvideos is not None:
- num_cameras = wpvideos.shape[0]
- num_frames = wpvideos.shape[2]
- else:
- raise ValueError("Either skeletons or wpvideos must be provided")
-
- # Initialize noise
- noise_shape = (
- num_cameras,
- self.vae.model.z_dim,
- (num_frames - 1) // 4 + 1,
- height // self.vae.upsampling_factor,
- width // self.vae.upsampling_factor,
- )
- noise = self.generate_noise(noise_shape, seed=seed, device=rand_device, dtype=torch.float32)
- noise = noise.to(dtype=self.torch_dtype, device=self.device)
-
- if input_video is not None:
- self.load_models_to_device(["vae"])
- input_video = self.preprocess_images(input_video)
- input_video = torch.stack(input_video, dim=2).to(dtype=self.torch_dtype, device=self.device)
- latents = self.encode_video(input_video, **tiler_kwargs).to(dtype=self.torch_dtype, device=self.device)
- latents = self.scheduler.add_noise(latents, noise, timestep=self.scheduler.timesteps[0])
- else:
- latents = noise
-
- # Encode source video
- self.load_models_to_device(["vae"])
- src_latents = self.encode_video(src_videos, **tiler_kwargs)
- src_latents = src_latents.to(dtype=self.torch_dtype, device=self.device)
- src_latents_nega = torch.zeros_like(src_latents)
-
- # Latent bridge matching
- if self.dit.use_lbm:
- if skeletons is not None:
- # skeleton-based: use primary src_latents as bridge source
- lbm_src_latents = src_latents[:1].expand_as(latents)
- elif wpvideos is not None:
- lbm_src_latents = self.encode_video(wpvideos, **tiler_kwargs).to(
- dtype=self.torch_dtype, device=self.device
- )
- if self.dit.fill_wpmask_with_noise:
- wpmask_latents = self.encode_wpmask(wpmasks, size=lbm_src_latents.shape[-3:])
- lbm_src_latents = lbm_src_latents * wpmask_latents + noise * (1 - wpmask_latents)
-
- latents = lbm_src_latents
-
- # Encode prompts
- self.load_models_to_device(["text_encoder"])
- prompt_emb_posi = self.encode_prompt(prompt, positive=True)
- if cfg_scale != 1.0:
- prompt_emb_nega = self.encode_prompt(negative_prompt, positive=False)
-
- image_emb = {}
-
- # Extra input
- extra_input = self.prepare_extra_input(latents)
-
- # Denoise
- self.load_models_to_device(["dit"])
- for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
- timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device)
- timestep = torch.cat([timestep] * num_cameras, dim=0)
-
- # Inference
- noise_pred_posi = self.denoising_model()(
- x=latents,
- x_src=src_latents,
- timestep=timestep,
- skeletons=skeletons,
- cam_emb=cam_emb,
- **prompt_emb_posi,
- **image_emb,
- **extra_input,
- )
- if cfg_scale != 1.0:
- noise_pred_nega = self.denoising_model()(
- x=latents,
- x_src=src_latents_nega,
- timestep=timestep,
- skeletons=skeletons,
- cam_emb=cam_emb,
- **prompt_emb_nega,
- **image_emb,
- **extra_input,
- )
- noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
- else:
- noise_pred = noise_pred_posi
-
- # Scheduler
- latents = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], latents)
-
- # Decode
- self.load_models_to_device(["vae"])
- pred_videos = self.decode_video(latents, **tiler_kwargs)
-
- if return_tensor:
- return pred_videos
-
- self.load_models_to_device([])
- pred_video_list = []
- for pred_video in pred_videos:
- pred_video_list.append(self.tensor2video(pred_video))
- return pred_video_list
-
-
-class TeaCache:
- def __init__(self, num_inference_steps, rel_l1_thresh, model_id):
- self.num_inference_steps = num_inference_steps
- self.step = 0
- self.accumulated_rel_l1_distance = 0
- self.previous_modulated_input = None
- self.rel_l1_thresh = rel_l1_thresh
- self.previous_residual = None
- self.previous_hidden_states = None
-
- self.coefficients_dict = {
- "Wan2.1-T2V-1.3B": [-5.21862437e04, 9.23041404e03, -5.28275948e02, 1.36987616e01, -4.99875664e-02],
- "Wan2.1-T2V-14B": [-3.03318725e05, 4.90537029e04, -2.65530556e03, 5.87365115e01, -3.15583525e-01],
- "Wan2.1-I2V-14B-480P": [2.57151496e05, -3.54229917e04, 1.40286849e03, -1.35890334e01, 1.32517977e-01],
- "Wan2.1-I2V-14B-720P": [8.10705460e03, 2.13393892e03, -3.72934672e02, 1.66203073e01, -4.17769401e-02],
- }
- if model_id not in self.coefficients_dict:
- supported_model_ids = ", ".join([i for i in self.coefficients_dict])
- raise ValueError(
- f"{model_id} is not a supported TeaCache model id. Please choose a valid model id in ({supported_model_ids})."
- )
- self.coefficients = self.coefficients_dict[model_id]
-
- def check(self, dit: WanModel, x, t_mod):
- modulated_inp = t_mod.clone()
- if self.step == 0 or self.step == self.num_inference_steps - 1:
- should_calc = True
- self.accumulated_rel_l1_distance = 0
- else:
- coefficients = self.coefficients
- rescale_func = np.poly1d(coefficients)
- self.accumulated_rel_l1_distance += rescale_func(
- (
- (modulated_inp - self.previous_modulated_input).abs().mean()
- / self.previous_modulated_input.abs().mean()
- )
- .cpu()
- .item()
- )
- if self.accumulated_rel_l1_distance < self.rel_l1_thresh:
- should_calc = False
- else:
- should_calc = True
- self.accumulated_rel_l1_distance = 0
- self.previous_modulated_input = modulated_inp
- self.step += 1
- if self.step == self.num_inference_steps:
- self.step = 0
- if should_calc:
- self.previous_hidden_states = x.clone()
- return not should_calc
-
- def store(self, hidden_states):
- self.previous_residual = hidden_states - self.previous_hidden_states
- self.previous_hidden_states = None
-
- def update(self, hidden_states):
- hidden_states = hidden_states + self.previous_residual
- return hidden_states
diff --git a/fdanyone/vendor/diffsynth/prompters/__init__.py b/fdanyone/vendor/diffsynth/prompters/__init__.py
deleted file mode 100644
index d986931..0000000
--- a/fdanyone/vendor/diffsynth/prompters/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Vendored Wan prompt helpers."""
-
-from .wan_prompter import WanPrompter
-
-__all__ = ["WanPrompter"]
diff --git a/fdanyone/vendor/diffsynth/prompters/base_prompter.py b/fdanyone/vendor/diffsynth/prompters/base_prompter.py
deleted file mode 100644
index 749fc3f..0000000
--- a/fdanyone/vendor/diffsynth/prompters/base_prompter.py
+++ /dev/null
@@ -1,69 +0,0 @@
-import torch
-
-
-
-def tokenize_long_prompt(tokenizer, prompt, max_length=None):
- # Get model_max_length from self.tokenizer
- length = tokenizer.model_max_length if max_length is None else max_length
-
- # To avoid the warning. set self.tokenizer.model_max_length to +oo.
- tokenizer.model_max_length = 99999999
-
- # Tokenize it!
- input_ids = tokenizer(prompt, return_tensors="pt").input_ids
-
- # Determine the real length.
- max_length = (input_ids.shape[1] + length - 1) // length * length
-
- # Restore tokenizer.model_max_length
- tokenizer.model_max_length = length
-
- # Tokenize it again with fixed length.
- input_ids = tokenizer(
- prompt,
- return_tensors="pt",
- padding="max_length",
- max_length=max_length,
- truncation=True
- ).input_ids
-
- # Reshape input_ids to fit the text encoder.
- num_sentence = input_ids.shape[1] // length
- input_ids = input_ids.reshape((num_sentence, length))
-
- return input_ids
-
-
-
-class BasePrompter:
- def __init__(self):
- self.refiners = []
- self.extenders = []
-
-
- def load_prompt_refiners(self, model_manager, refiner_classes=[]):
- for refiner_class in refiner_classes:
- refiner = refiner_class.from_model_manager(model_manager)
- self.refiners.append(refiner)
-
- def load_prompt_extenders(self, model_manager, extender_classes=[]):
- for extender_class in extender_classes:
- extender = extender_class.from_model_manager(model_manager)
- self.extenders.append(extender)
-
-
- @torch.no_grad()
- def process_prompt(self, prompt, positive=True):
- if isinstance(prompt, list):
- prompt = [self.process_prompt(prompt_, positive=positive) for prompt_ in prompt]
- else:
- for refiner in self.refiners:
- prompt = refiner(prompt, positive=positive)
- return prompt
-
- @torch.no_grad()
- def extend_prompt(self, prompt:str, positive=True):
- extended_prompt = dict(prompt=prompt)
- for extender in self.extenders:
- extended_prompt = extender(extended_prompt)
- return extended_prompt
diff --git a/fdanyone/vendor/diffsynth/prompters/wan_prompter.py b/fdanyone/vendor/diffsynth/prompters/wan_prompter.py
deleted file mode 100644
index 01a765d..0000000
--- a/fdanyone/vendor/diffsynth/prompters/wan_prompter.py
+++ /dev/null
@@ -1,109 +0,0 @@
-from .base_prompter import BasePrompter
-from ..models.wan_video_text_encoder import WanTextEncoder
-from transformers import AutoTokenizer
-import os, torch
-import ftfy
-import html
-import string
-import regex as re
-
-
-def basic_clean(text):
- text = ftfy.fix_text(text)
- text = html.unescape(html.unescape(text))
- return text.strip()
-
-
-def whitespace_clean(text):
- text = re.sub(r'\s+', ' ', text)
- text = text.strip()
- return text
-
-
-def canonicalize(text, keep_punctuation_exact_string=None):
- text = text.replace('_', ' ')
- if keep_punctuation_exact_string:
- text = keep_punctuation_exact_string.join(
- part.translate(str.maketrans('', '', string.punctuation))
- for part in text.split(keep_punctuation_exact_string))
- else:
- text = text.translate(str.maketrans('', '', string.punctuation))
- text = text.lower()
- text = re.sub(r'\s+', ' ', text)
- return text.strip()
-
-
-class HuggingfaceTokenizer:
-
- def __init__(self, name, seq_len=None, clean=None, **kwargs):
- assert clean in (None, 'whitespace', 'lower', 'canonicalize')
- self.name = name
- self.seq_len = seq_len
- self.clean = clean
-
- # init tokenizer
- self.tokenizer = AutoTokenizer.from_pretrained(name, **kwargs)
- self.vocab_size = self.tokenizer.vocab_size
-
- def __call__(self, sequence, **kwargs):
- return_mask = kwargs.pop('return_mask', False)
-
- # arguments
- _kwargs = {'return_tensors': 'pt'}
- if self.seq_len is not None:
- _kwargs.update({
- 'padding': 'max_length',
- 'truncation': True,
- 'max_length': self.seq_len
- })
- _kwargs.update(**kwargs)
-
- # tokenization
- if isinstance(sequence, str):
- sequence = [sequence]
- if self.clean:
- sequence = [self._clean(u) for u in sequence]
- ids = self.tokenizer(sequence, **_kwargs)
-
- # output
- if return_mask:
- return ids.input_ids, ids.attention_mask
- else:
- return ids.input_ids
-
- def _clean(self, text):
- if self.clean == 'whitespace':
- text = whitespace_clean(basic_clean(text))
- elif self.clean == 'lower':
- text = whitespace_clean(basic_clean(text)).lower()
- elif self.clean == 'canonicalize':
- text = canonicalize(basic_clean(text))
- return text
-
-
-class WanPrompter(BasePrompter):
-
- def __init__(self, tokenizer_path=None, text_len=512):
- super().__init__()
- self.text_len = text_len
- self.text_encoder = None
- self.fetch_tokenizer(tokenizer_path)
-
- def fetch_tokenizer(self, tokenizer_path=None):
- if tokenizer_path is not None:
- self.tokenizer = HuggingfaceTokenizer(name=tokenizer_path, seq_len=self.text_len, clean='whitespace')
-
- def fetch_models(self, text_encoder: WanTextEncoder = None):
- self.text_encoder = text_encoder
-
- def encode_prompt(self, prompt, positive=True, device="cuda"):
- prompt = self.process_prompt(prompt, positive=positive)
-
- ids, mask = self.tokenizer(prompt, return_mask=True, add_special_tokens=True)
- ids = ids.to(device)
- mask = mask.to(device)
- seq_lens = mask.gt(0).sum(dim=1).long()
- prompt_emb = self.text_encoder(ids, mask)
- for i, v in enumerate(seq_lens):
- prompt_emb[:, v:] = 0
- return prompt_emb
diff --git a/fdanyone/vendor/diffsynth/schedulers/bride_match.py b/fdanyone/vendor/diffsynth/schedulers/bride_match.py
deleted file mode 100644
index c157702..0000000
--- a/fdanyone/vendor/diffsynth/schedulers/bride_match.py
+++ /dev/null
@@ -1,71 +0,0 @@
-import torch, math
-
-
-class BridgeMatchScheduler:
-
- def __init__(
- self,
- num_train_timesteps=1000,
- num_inference_steps=8,
- sigma_max=1.0,
- bridge_noise_sigma=0.005,
- ):
- self.sigma_max = sigma_max
- self.sigma_min = sigma_max / num_train_timesteps
- self.num_train_timesteps = num_train_timesteps # train timesteps for base model
- self.num_inference_steps = num_inference_steps # inference steps for bridge matching
- self.bridge_noise_sigma = bridge_noise_sigma
-
- self.set_timesteps(self.num_inference_steps)
-
- def set_timesteps(self, num_inference_steps=8, training=False):
- sigma_start = self.sigma_max
- sigma_end = self.sigma_max / num_inference_steps
- self.sigmas = torch.linspace(sigma_start, sigma_end, num_inference_steps)
- self.timesteps = self.sigmas * self.num_train_timesteps
-
- self.training = training
-
- def retrieve_sigma(self, timestep):
- if isinstance(timestep, torch.Tensor):
- timestep = timestep.cpu()
- timestep_id = torch.argmin((self.timesteps - timestep).abs())
- sigma = self.sigmas[timestep_id]
- return sigma
-
- def get_noise_term(self, sigma, sample):
- # bridge noise term == 0 when sigma == 1 or 0
- return self.bridge_noise_sigma * (sigma * (1.0 - sigma)) ** 0.5 * torch.randn_like(sample)
-
- def step(self, model_output, timestep, sample, to_final=False, **kwargs):
- if isinstance(timestep, torch.Tensor):
- timestep = timestep.cpu()
- timestep_id = torch.argmin((self.timesteps - timestep).abs())
- sigma = self.sigmas[timestep_id]
- if to_final or timestep_id + 1 >= len(self.timesteps):
- sigma_ = 0
- else:
- sigma_ = self.sigmas[timestep_id + 1]
-
- prev_sample = sample + model_output * (sigma_ - sigma) + self.get_noise_term(sigma_, sample)
- return prev_sample
-
- def add_noise(self, tgt_sample, src_sample, timestep):
- sigma = self.retrieve_sigma(timestep)
- noisy_sample = sigma * src_sample + (1 - sigma) * tgt_sample + self.get_noise_term(sigma, tgt_sample)
- return noisy_sample
-
- def training_target(self, tgt_sample, noisy_sample, timestep):
- sigma = self.retrieve_sigma(timestep)
-
- target = (noisy_sample - tgt_sample) / sigma
- return target
-
- def denoised_sample(self, prediction, noisy_sample, timestep):
- sigma = self.retrieve_sigma(timestep)
-
- sample = noisy_sample - prediction * sigma
- return sample
-
- def training_weight(self, timestep):
- return 1.0
diff --git a/fdanyone/vendor/diffsynth/vram_management/__init__.py b/fdanyone/vendor/diffsynth/vram_management/__init__.py
deleted file mode 100644
index 5b07580..0000000
--- a/fdanyone/vendor/diffsynth/vram_management/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from .layers import *
-from .gradient_checkpointing import *
diff --git a/fdanyone/vendor/diffsynth/vram_management/gradient_checkpointing.py b/fdanyone/vendor/diffsynth/vram_management/gradient_checkpointing.py
deleted file mode 100644
index b356415..0000000
--- a/fdanyone/vendor/diffsynth/vram_management/gradient_checkpointing.py
+++ /dev/null
@@ -1,34 +0,0 @@
-import torch
-
-
-def create_custom_forward(module):
- def custom_forward(*inputs, **kwargs):
- return module(*inputs, **kwargs)
- return custom_forward
-
-
-def gradient_checkpoint_forward(
- model,
- use_gradient_checkpointing,
- use_gradient_checkpointing_offload,
- *args,
- **kwargs,
-):
- if use_gradient_checkpointing_offload:
- with torch.autograd.graph.save_on_cpu():
- model_output = torch.utils.checkpoint.checkpoint(
- create_custom_forward(model),
- *args,
- **kwargs,
- use_reentrant=False,
- )
- elif use_gradient_checkpointing:
- model_output = torch.utils.checkpoint.checkpoint(
- create_custom_forward(model),
- *args,
- **kwargs,
- use_reentrant=False,
- )
- else:
- model_output = model(*args, **kwargs)
- return model_output
diff --git a/fdanyone/vendor/diffsynth/vram_management/layers.py b/fdanyone/vendor/diffsynth/vram_management/layers.py
deleted file mode 100644
index c6f1ec6..0000000
--- a/fdanyone/vendor/diffsynth/vram_management/layers.py
+++ /dev/null
@@ -1,213 +0,0 @@
-import torch, copy
-from ..models.utils import init_weights_on_device
-
-
-def cast_to(weight, dtype, device):
- r = torch.empty_like(weight, dtype=dtype, device=device)
- r.copy_(weight)
- return r
-
-
-class AutoTorchModule(torch.nn.Module):
- def __init__(self):
- super().__init__()
-
- def check_free_vram(self):
- gpu_mem_state = torch.cuda.mem_get_info(self.computation_device)
- used_memory = (gpu_mem_state[1] - gpu_mem_state[0]) / (1024 ** 3)
- return used_memory < self.vram_limit
-
- def offload(self):
- if self.state != 0:
- self.to(dtype=self.offload_dtype, device=self.offload_device)
- self.state = 0
-
- def onload(self):
- if self.state != 1:
- self.to(dtype=self.onload_dtype, device=self.onload_device)
- self.state = 1
-
- def keep(self):
- if self.state != 2:
- self.to(dtype=self.computation_dtype, device=self.computation_device)
- self.state = 2
-
-
-class AutoWrappedModule(AutoTorchModule):
- def __init__(self, module: torch.nn.Module, offload_dtype, offload_device, onload_dtype, onload_device, computation_dtype, computation_device, vram_limit, **kwargs):
- super().__init__()
- self.module = module.to(dtype=offload_dtype, device=offload_device)
- self.offload_dtype = offload_dtype
- self.offload_device = offload_device
- self.onload_dtype = onload_dtype
- self.onload_device = onload_device
- self.computation_dtype = computation_dtype
- self.computation_device = computation_device
- self.vram_limit = vram_limit
- self.state = 0
-
- def forward(self, *args, **kwargs):
- if self.state == 2:
- module = self.module
- else:
- if self.onload_dtype == self.computation_dtype and self.onload_device == self.computation_device:
- module = self.module
- elif self.vram_limit is not None and self.check_free_vram():
- self.keep()
- module = self.module
- else:
- module = copy.deepcopy(self.module).to(dtype=self.computation_dtype, device=self.computation_device)
- return module(*args, **kwargs)
-
-
-class WanAutoCastLayerNorm(torch.nn.LayerNorm, AutoTorchModule):
- def __init__(self, module: torch.nn.LayerNorm, offload_dtype, offload_device, onload_dtype, onload_device, computation_dtype, computation_device, vram_limit, **kwargs):
- with init_weights_on_device(device=torch.device("meta")):
- super().__init__(module.normalized_shape, eps=module.eps, elementwise_affine=module.elementwise_affine, bias=module.bias is not None, dtype=offload_dtype, device=offload_device)
- self.weight = module.weight
- self.bias = module.bias
- self.offload_dtype = offload_dtype
- self.offload_device = offload_device
- self.onload_dtype = onload_dtype
- self.onload_device = onload_device
- self.computation_dtype = computation_dtype
- self.computation_device = computation_device
- self.vram_limit = vram_limit
- self.state = 0
-
- def forward(self, x, *args, **kwargs):
- if self.state == 2:
- weight, bias = self.weight, self.bias
- else:
- if self.onload_dtype == self.computation_dtype and self.onload_device == self.computation_device:
- weight, bias = self.weight, self.bias
- elif self.vram_limit is not None and self.check_free_vram():
- self.keep()
- weight, bias = self.weight, self.bias
- else:
- weight = None if self.weight is None else cast_to(self.weight, self.computation_dtype, self.computation_device)
- bias = None if self.bias is None else cast_to(self.bias, self.computation_dtype, self.computation_device)
- with torch.amp.autocast(device_type=x.device.type):
- x = torch.nn.functional.layer_norm(x.float(), self.normalized_shape, weight, bias, self.eps).type_as(x)
- return x
-
-
-class AutoWrappedLinear(torch.nn.Linear, AutoTorchModule):
- def __init__(self, module: torch.nn.Linear, offload_dtype, offload_device, onload_dtype, onload_device, computation_dtype, computation_device, vram_limit, name="", **kwargs):
- with init_weights_on_device(device=torch.device("meta")):
- super().__init__(in_features=module.in_features, out_features=module.out_features, bias=module.bias is not None, dtype=offload_dtype, device=offload_device)
- self.weight = module.weight
- self.bias = module.bias
- self.offload_dtype = offload_dtype
- self.offload_device = offload_device
- self.onload_dtype = onload_dtype
- self.onload_device = onload_device
- self.computation_dtype = computation_dtype
- self.computation_device = computation_device
- self.vram_limit = vram_limit
- self.state = 0
- self.name = name
- self.lora_A_weights = []
- self.lora_B_weights = []
- self.lora_merger = None
- self.enable_fp8 = computation_dtype in [torch.float8_e4m3fn, torch.float8_e4m3fnuz]
-
- def fp8_linear(
- self,
- input: torch.Tensor,
- weight: torch.Tensor,
- bias: torch.Tensor | None = None,
- ) -> torch.Tensor:
- device = input.device
- origin_dtype = input.dtype
- origin_shape = input.shape
- input = input.reshape(-1, origin_shape[-1])
-
- x_max = torch.max(torch.abs(input), dim=-1, keepdim=True).values
- fp8_max = 448.0
- # For float8_e4m3fnuz, the maximum representable value is half of that of e4m3fn.
- # To avoid overflow and ensure numerical compatibility during FP8 computation,
- # we scale down the input by 2.0 in advance.
- # This scaling will be compensated later during the final result scaling.
- if self.computation_dtype == torch.float8_e4m3fnuz:
- fp8_max = fp8_max / 2.0
- scale_a = torch.clamp(x_max / fp8_max, min=1.0).float().to(device=device)
- scale_b = torch.ones((weight.shape[0], 1)).to(device=device)
- input = input / (scale_a + 1e-8)
- input = input.to(self.computation_dtype)
- weight = weight.to(self.computation_dtype)
- bias = bias.to(torch.bfloat16)
-
- result = torch._scaled_mm(
- input,
- weight.T,
- scale_a=scale_a,
- scale_b=scale_b.T,
- bias=bias,
- out_dtype=origin_dtype,
- )
- new_shape = origin_shape[:-1] + result.shape[-1:]
- result = result.reshape(new_shape)
- return result
-
- def forward(self, x, *args, **kwargs):
- # VRAM management
- if self.state == 2:
- weight, bias = self.weight, self.bias
- else:
- if self.onload_dtype == self.computation_dtype and self.onload_device == self.computation_device:
- weight, bias = self.weight, self.bias
- elif self.vram_limit is not None and self.check_free_vram():
- self.keep()
- weight, bias = self.weight, self.bias
- else:
- weight = cast_to(self.weight, self.computation_dtype, self.computation_device)
- bias = None if self.bias is None else cast_to(self.bias, self.computation_dtype, self.computation_device)
-
- # Linear forward
- if self.enable_fp8:
- out = self.fp8_linear(x, weight, bias)
- else:
- out = torch.nn.functional.linear(x, weight, bias)
-
- # LoRA
- if len(self.lora_A_weights) == 0:
- # No LoRA
- return out
- elif self.lora_merger is None:
- # Native LoRA inference
- for lora_A, lora_B in zip(self.lora_A_weights, self.lora_B_weights):
- out = out + x @ lora_A.T @ lora_B.T
- else:
- # LoRA fusion
- lora_output = []
- for lora_A, lora_B in zip(self.lora_A_weights, self.lora_B_weights):
- lora_output.append(x @ lora_A.T @ lora_B.T)
- lora_output = torch.stack(lora_output)
- out = self.lora_merger(out, lora_output)
- return out
-
-
-def enable_vram_management_recursively(model: torch.nn.Module, module_map: dict, module_config: dict, max_num_param=None, overflow_module_config: dict = None, total_num_param=0, vram_limit=None, name_prefix=""):
- for name, module in model.named_children():
- layer_name = name if name_prefix == "" else name_prefix + "." + name
- for source_module, target_module in module_map.items():
- if isinstance(module, source_module):
- num_param = sum(p.numel() for p in module.parameters())
- if max_num_param is not None and total_num_param + num_param > max_num_param:
- module_config_ = overflow_module_config
- else:
- module_config_ = module_config
- module_ = target_module(module, **module_config_, vram_limit=vram_limit, name=layer_name)
- setattr(model, name, module_)
- total_num_param += num_param
- break
- else:
- total_num_param = enable_vram_management_recursively(module, module_map, module_config, max_num_param, overflow_module_config, total_num_param, vram_limit=vram_limit, name_prefix=layer_name)
- return total_num_param
-
-
-def enable_vram_management(model: torch.nn.Module, module_map: dict, module_config: dict, max_num_param=None, overflow_module_config: dict = None, vram_limit=None):
- enable_vram_management_recursively(model, module_map, module_config, max_num_param, overflow_module_config, total_num_param=0, vram_limit=vram_limit)
- model.vram_management_enabled = True
-
diff --git a/inference.py b/inference.py
index 23c0021..a70ffb2 100644
--- a/inference.py
+++ b/inference.py
@@ -4,8 +4,7 @@ from __future__ import annotations
import sys
-from fire import Fire
-
+from fdanyone.device import configure_inference_cuda_allocator
from fdanyone.errors import FourDAnyoneError
@@ -59,6 +58,9 @@ def inference(
seed: Random seed shared by proposal and target generation.
"""
+ # This must run before the first model/PyTorch import. It protects the
+ # reusable 5--6 GiB DiT FFN allocation from allocator fragmentation.
+ configure_inference_cuda_allocator()
# Keep model imports out of module scope so ``--help`` stays lightweight.
from fdanyone.pipeline import run_pipeline
@@ -83,10 +85,19 @@ def inference(
)
-if __name__ == "__main__":
+def main() -> None:
+ """Bootstrap the CLI without importing Fire or PyTorch at module import."""
+
+ configure_inference_cuda_allocator()
+ from fire import Fire
+
try:
Fire(inference)
except FourDAnyoneError as exc:
message = " ".join(line.strip() for line in str(exc).splitlines())
print(f"error: {message}", file=sys.stderr)
raise SystemExit(1) from None
+
+
+if __name__ == "__main__":
+ main()
diff --git a/requirements.txt b/requirements.txt
index 32a6c5e..65b1733 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,7 +3,6 @@ colorlog>=6,<7
einops>=0.8,<1
ffmpeg-python>=0.2,<1
fire>=0.7,<1
-ftfy>=6,<7
huggingface-hub>=0.36,<1
hydra-core>=1.3,<2
hydra-zen>=0.16,<1
@@ -14,10 +13,8 @@ numpy>=1.26,<2
opencv-python>=4.10,<5
pillow>=10,<13
pytorch-lightning>=2.3,<3
-regex>=2024.11
safetensors>=0.5,<1
scipy>=1.10,<2
-sentencepiece>=0.2,<1
smplx==0.1.28
timm==0.9.12
torch>=2.8,<2.9