diff --git a/releases/2026-10-20-code/diffsynth/__init__.py b/releases/2026-10-20-code/diffsynth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d629b194077b4048283a866057b062b62b4610 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/__init__.py @@ -0,0 +1 @@ +from .data.video import VideoData, save_video, save_video_with_audio diff --git a/releases/2026-10-20-code/diffsynth/bridge/__init__.py b/releases/2026-10-20-code/diffsynth/bridge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/bridge/wan_bridge_pipeline.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/bridge/wan_bridge_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..49146c4cbf9413ba47a0ca67d131bf2a805b2e56 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/bridge/wan_bridge_pipeline.py @@ -0,0 +1,413 @@ +import torch, warnings, glob, os, types +import numpy as np +from PIL import Image +from einops import repeat, reduce +from typing import Optional, Union +from dataclasses import dataclass +try: + from modelscope import snapshot_download +except ModuleNotFoundError: + snapshot_download = None +from einops import rearrange +import numpy as np +from PIL import Image +from tqdm import tqdm +from typing import Optional +from typing_extensions import Literal + +from diffsynth.utils import PipelineUnitRunner +from diffsynth.models.wan_video_dit import WanModel +from diffsynth.models.wan_video_text_encoder import WanTextEncoder +from diffsynth.models.wan_video_vae import WanVideoVAE +from diffsynth.models.wan_video_image_encoder import WanImageEncoder +from diffsynth.models.wan_video_vace import VaceWanModel +from diffsynth.models.wan_video_motion_controller import WanMotionControllerModel +from diffsynth.schedulers.flow_match import FlowMatchScheduler +from diffsynth.prompters.wan_prompter import WanPrompter + +from diffsynth.pipelines.wan_video_new import * + + +import torch, math + + +def clip_bf16(x: torch.FloatTensor) -> torch.FloatTensor: + if x.dtype == torch.float16: + x = x.clip(-65504, 65504) + return x + + +class BridgeScheduler(FlowMatchScheduler): + def __init__(self, noise_scale=0.05, *args, **kwargs): + super().__init__(*args, **kwargs) + self.noise_scale = noise_scale + self.bridge_type = "brownian" + self.training_weight_type = "uniform" + + def get_sigma(self, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + return self.sigmas[timestep_id] + + def step(self, model_output, timestep, sample, source_sample, noise=None, **kwargs): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + if timestep_id + 1 >= len(self.timesteps): + sigma_ = 1 if (self.inverse_timesteps or self.reverse_sigmas) else 0 + else: + sigma_ = self.sigmas[timestep_id + 1] + noise = noise if noise is not None else torch.randn_like(sample) + + dt = sigma_ - sigma + if self.target == "x0": + drift = (sample - model_output) / (sigma + 1e-5) + elif self.target == "drift": + drift = model_output + elif self.target == "stabilized_drift": + factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5 + drift = model_output * factor + else: + raise ValueError(f"Unknown target {self.target}") + result = sample + drift * dt + correction_term = (sigma_) / (sigma) + noise_scale_t = self.noise_scale * (-dt * correction_term).sqrt() + result += noise_scale_t * noise + + return result + + def get_noise_coeff(self, sigma): + if self.bridge_type == "brownian": + return (sigma * (1 - sigma)) ** 0.5 * self.noise_scale + elif self.bridge_type == "brownian2": + return (sigma * (1 - sigma)) * self.noise_scale + + def add_noise(self, z0, z1, noise, timestep): + sigma = self.get_sigma(timestep) + + zt = (1 - sigma) * z0 + sigma * z1 + noise_scale_t = self.get_noise_coeff(sigma) + + return zt + noise_scale_t * noise + + def training_target(self, z0, zt, timestep, epsilon=1e-5): + sigma = self.get_sigma(timestep) + target = (zt - z0) / (sigma + epsilon) + return target + + def training_weight(self, timestep, **kwargs): + sigma = self.get_sigma(timestep) + if self.training_weight_type == "uniform": + return 1.0 + elif self.training_weight_type == "time": + return sigma**0.5 + elif self.training_weight_type == "time_linear": + return sigma + elif self.training_weight_type == "displacement": + return sigma**2 + elif self.training_weight_type == "flow_matching": + return super().training_weight(timestep) + elif self.training_weight_type == "snr": + raise NotImplementedError("SNR training weight type is not implemented") + elif self.training_weight_type == "stablized": + drift_10 = kwargs.get("drift_10", None) + assert ( + drift_10 is not None + ), "drift is required for stablized training weight" + drift_norm_sq = reduce(drift_10**2, "b ... -> b", "mean") + weight = ( + sigma * drift_norm_sq / (sigma * drift_norm_sq + (1 - sigma)) + ).item() + return weight + else: + raise ValueError( + f"Unknown training_weight_type {self.training_weight_type}" + ) + + +class WanVideoBridgeUnit_InputVideoEmbedder_FSR(PipelineUnit): + def __init__(self, target_frames=321, fsr_factor=4): + super().__init__( + input_params=( + "source_video", + "tiled", + "tile_size", + "tile_stride", + ), + onload_model_names=("vae",), + ) + self.target_frames = target_frames + self.fsr_factor = fsr_factor + + def process( + self, + pipe: WanVideoPipeline, + source_video, + tiled, + tile_size, + tile_stride, + ): + pipe.load_models_to_device(["vae"]) + source_video = pipe.preprocess_video(source_video) + frames_count = source_video.shape[2] + if frames_count == self.target_frames: + source_video = source_video[:, :, :: self.fsr_factor] + elif frames_count - 1 == (self.target_frames - 1) // self.fsr_factor: + # do_nothing + pass + else: + raise ValueError( + f"Source video frames {frames_count} not match target frames {self.target_frames} or {(self.target_frames - 1) // self.fsr_factor + 1}" + ) + + def repeat_frames(source_video: torch.Tensor, n: int) -> torch.Tensor: + b, c, t, h, w = source_video.shape + first = source_video[:, :, :1] + rest = source_video[:, :, 1:] + rest_repeated = rest.repeat_interleave(n, dim=2) + out = torch.cat([first, rest_repeated], dim=2) + return out + + source_video = repeat_frames(source_video, self.fsr_factor) + source_latents = pipe.vae.encode( + source_video, + device=pipe.device, + tiled=tiled, + tile_size=tile_size, + tile_stride=tile_stride, + ).to(dtype=pipe.torch_dtype, device=pipe.device) + return {"source_latents": source_latents} + + +class WanVideoBridgeUnit_InputVideoEmbedder(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("source_video", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",), + ) + + def process( + self, pipe: WanVideoPipeline, source_video, tiled, tile_size, tile_stride + ): + pipe.load_models_to_device(["vae"]) + source_video = pipe.preprocess_video(source_video) + source_latents = pipe.vae.encode( + source_video, + device=pipe.device, + tiled=tiled, + tile_size=tile_size, + tile_stride=tile_stride, + ).to(dtype=pipe.torch_dtype, device=pipe.device) + + return {"source_latents": source_latents} + + +class WanVideoBridgePipeline(WanVideoPipeline): + def __init__(self, device="npu", torch_dtype=torch.float16, tokenizer_path=None): + super().__init__( + device=device, torch_dtype=torch_dtype, tokenizer_path=tokenizer_path + ) + + self.units = [ + WanVideoUnit_ShapeChecker(), + WanVideoUnit_NoiseInitializer(), + WanVideoUnit_PromptEmbedder(), + WanVideoUnit_InputVideoEmbedder(), + WanVideoUnit_UnifiedSequenceParallel(), + WanVideoBridgeUnit_InputVideoEmbedder(), + ] + + self.scheduler = BridgeScheduler(shift=1.0, sigma_min=0.0, extra_one_step=True) + # self.scheduler = FlowMatchScheduler(shift=1.0, sigma_min=0.0, extra_one_step=True) + self.model_fn = model_fn_wan_video + + def training_loss(self, **inputs): + """Single-head ViBT training objective. + + x0: target/style video latent + x1: source/content video latent + xt: Brownian-bridge sample between x0 and x1 + The DiT predicts the bridge drift from xt toward x0. + """ + max_timestep_boundary = int( + inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps + ) + min_timestep_boundary = int( + inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps + ) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to( + dtype=self.torch_dtype, device=self.device + ) + + x0 = inputs["input_latents"] + x1 = inputs["source_latents"] + noise = inputs["noise"] + + xt = self.scheduler.add_noise(x0, x1, noise, timestep) + inputs["latents"] = xt + + target = self.scheduler.training_target(x0, xt, timestep) + drift_10 = x1 - x0 + model_output = self.model_fn(**inputs, timestep=timestep) + + if self.scheduler.target == "drift": + loss = torch.nn.functional.mse_loss( + model_output.float(), target.float() + ) + loss *= self.scheduler.training_weight(timestep, drift_10=drift_10) + elif self.scheduler.target == "x0": + sigma = self.scheduler.get_sigma(timestep) + drift = (xt - model_output) / (sigma + 1e-5) + loss = torch.nn.functional.mse_loss(drift.float(), target.float()) + loss *= self.scheduler.training_weight(timestep, drift_10=drift_10) + elif self.scheduler.target == "stabilized_drift": + sigma = self.scheduler.get_sigma(timestep) + factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5 + stabilized_target = target / factor + loss = torch.nn.functional.mse_loss( + model_output.float(), stabilized_target.float() + ) + else: + raise ValueError(f"Unknown target {self.scheduler.target}") + + return loss + + @torch.no_grad() + def __call__( + self, + # Prompt + prompt: str, + negative_prompt: Optional[str] = "", + # Video-to-video + input_video: Optional[list[Image.Image]] = None, + seed: Optional[int] = None, + rand_device: Optional[str] = "cpu", + # Shape + height: Optional[int] = 480, + width: Optional[int] = 832, + num_frames=81, + # Classifier-free guidance + cfg_scale: Optional[float] = 5.0, + cfg_merge: Optional[bool] = False, + # Boundary + switch_DiT_boundary: Optional[float] = 0.875, + # Scheduler + num_inference_steps: Optional[int] = 50, + sigma_shift: Optional[float] = 1.0, + # VAE tiling + tiled: Optional[bool] = True, + tile_size: Optional[tuple[int, int]] = (30, 52), + tile_stride: Optional[tuple[int, int]] = (15, 26), + # progress_bar + progress_bar_cmd=tqdm, + # bridge + source_video: Optional[Image.Image] = None, + ): + # Scheduler + self.scheduler.set_timesteps(num_inference_steps, shift=sigma_shift) + + # Inputs + inputs_posi = { + "prompt": prompt, + "num_inference_steps": num_inference_steps, + } + inputs_nega = { + "negative_prompt": negative_prompt, + "num_inference_steps": num_inference_steps, + } + inputs_shared = { + "input_video": input_video, + "source_video": source_video, + "seed": seed, + "rand_device": rand_device, + "height": height, + "width": width, + "num_frames": num_frames, + "cfg_scale": cfg_scale, + "cfg_merge": cfg_merge, + "sigma_shift": sigma_shift, + "tiled": tiled, + "tile_size": tile_size, + "tile_stride": tile_stride, + } + + for unit in self.units: + inputs_shared, inputs_posi, inputs_nega = self.unit_runner( + unit, self, inputs_shared, inputs_posi, inputs_nega + ) + + inputs_shared["latents"] = inputs_shared["source_latents"].clone() + + # Denoise + self.load_models_to_device(self.in_iteration_models) + models = {name: getattr(self, name) for name in self.in_iteration_models} + for progress_id, timestep in enumerate( + progress_bar_cmd(self.scheduler.timesteps) + ): + # Switch DiT if necessary + if ( + timestep.item() + < switch_DiT_boundary * self.scheduler.num_train_timesteps + and self.dit2 is not None + and not models["dit"] is self.dit2 + ): + self.load_models_to_device(self.in_iteration_models_2) + models["dit"] = self.dit2 + models["vace"] = self.vace2 + + # Timestep + timestep = timestep.unsqueeze(0).to( + dtype=self.torch_dtype, device=self.device + ) + + # Inference + noise_pred_posi = self.model_fn( + **models, **inputs_shared, **inputs_posi, timestep=timestep + ) + if cfg_scale != 1.0: + if cfg_merge: + noise_pred_posi, noise_pred_nega = noise_pred_posi.chunk(2, dim=0) + else: + noise_pred_nega = self.model_fn( + **models, **inputs_shared, **inputs_nega, timestep=timestep + ) + + noise_pred = noise_pred_nega + cfg_scale * ( + noise_pred_posi - noise_pred_nega + ) + else: + noise_pred = noise_pred_posi + + # Scheduler + inputs_shared["latents"] = self.scheduler.step( + noise_pred, + self.scheduler.timesteps[progress_id], + inputs_shared["latents"], + inputs_shared["source_latents"], + ) + if "first_frame_latents" in inputs_shared: + inputs_shared["latents"][:, :, 0:1] = inputs_shared[ + "first_frame_latents" + ] + + # post-denoising, pre-decoding processing logic + for unit in self.post_units: + inputs_shared, _, _ = self.unit_runner( + unit, self, inputs_shared, inputs_posi, inputs_nega + ) + # Decode + self.load_models_to_device(["vae"]) + video = self.vae.decode( + inputs_shared["latents"], + device=self.device, + tiled=tiled, + tile_size=tile_size, + tile_stride=tile_stride, + ) + video = self.vae_output_to_video(video) + self.load_models_to_device([]) + + return video diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..15185217903ffb20cd2c9834b20e47813aaa4895 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap.py @@ -0,0 +1,170 @@ +"""Inference-only visualization of target-Q/reference-K attention.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch +from PIL import Image + + +class ReferenceAttentionRecorder: + """Collect head-averaged reference-key heatmaps without changing inference.""" + + def __init__(self, block_ids: list[int], num_heads: int, query_stride: int = 8) -> None: + self.block_ids = set(block_ids) + self.num_heads = int(num_heads) + self.query_stride = max(int(query_stride), 1) + self.records: dict[tuple[int, int, str], np.ndarray] = {} + self.injections: dict[tuple[int, int], np.ndarray] = {} + self.energy_biases: dict[tuple[int, int], np.ndarray] = {} + self.grids: dict[int, tuple[int, int, int]] = {} + + @torch.no_grad() + def capture(self, block_id: int, q: torch.Tensor, k: torch.Tensor, + scaled_delta: torch.Tensor, grid: tuple[int, int, int], + attention_bias: torch.Tensor | None = None) -> None: + frames, height, width = grid + if block_id not in self.block_ids: + return + if q.shape[0] < frames: + raise ValueError(f"Attention batch/time shape {q.shape[0]} is smaller than T={frames}") + spatial = height * width + head_dim = q.shape[-1] // self.num_heads + self.grids[block_id] = grid + yy, xx = torch.meshgrid( + torch.arange(height, device=q.device), + torch.arange(width, device=q.device), indexing="ij", + ) + all_indices = torch.arange(spatial, device=q.device)[::self.query_stride] + face_indices = torch.nonzero( + (yy >= round(.08 * height)) & (yy < round(.36 * height)) + & (xx >= round(.25 * width)) & (xx < round(.75 * width)), + as_tuple=False, + ) + face_indices = (face_indices[:, 0] * width + face_indices[:, 1]).long() + + for frame in range(frames): + qh = q[frame].reshape(spatial, self.num_heads, head_dim).permute(1, 0, 2) + kh = k[frame].reshape(spatial, self.num_heads, head_dim).permute(1, 0, 2) + key_bias = ( + torch.zeros(spatial, device=q.device, dtype=torch.float32) + if attention_bias is None + else attention_bias[frame].float() + ) + for name, indices in (("global", all_indices), ("face_queries", face_indices)): + mass_before = torch.zeros(spatial, device=q.device, dtype=torch.float32) + mass_after = torch.zeros(spatial, device=q.device, dtype=torch.float32) + for chunk in indices.split(64): + logits = torch.matmul( + qh[:, chunk].float(), kh.float().transpose(-1, -2) + ) * (head_dim ** -0.5) + mass_before.add_(logits.softmax(dim=-1).sum(dim=(0, 1))) + mass_after.add_((logits + key_bias[None, None, :]).softmax(dim=-1).sum(dim=(0, 1))) + denominator = self.num_heads * max(indices.numel(), 1) + mass_before.div_(denominator) + mass_after.div_(denominator) + self.records[(block_id, frame, f"{name}_before")] = mass_before.cpu().numpy() + self.records[(block_id, frame, f"{name}_after")] = mass_after.cpu().numpy() + injection = scaled_delta[frame].reshape(spatial, -1).float().abs().mean(dim=-1) + self.injections[(block_id, frame)] = injection.cpu().numpy() + self.energy_biases[(block_id, frame)] = key_bias.cpu().numpy() + + @staticmethod + def _overlay(image_rgb: np.ndarray, values: np.ndarray, height: int, width: int, + probability: bool) -> np.ndarray: + values = values.reshape(height, width) + if probability: + # Show enrichment relative to uniform attention. Zero means uniform; + # one means four times uniform after log2 compression. + score = np.log2(np.maximum(values * values.size, 1e-6)) + score = np.clip((score + 1.0) / 3.0, 0, 1) + else: + upper = max(float(np.quantile(values, .99)), 1e-8) + score = np.clip(values / upper, 0, 1) + score = cv2.resize(score.astype(np.float32), (image_rgb.shape[1], image_rgb.shape[0])) + heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_TURBO) + heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB).astype(np.float32) / 255 + return np.clip(.48 * image_rgb + .52 * heat, 0, 1) + + @staticmethod + def _signed_overlay(image_rgb: np.ndarray, values: np.ndarray, + height: int, width: int) -> np.ndarray: + values = values.reshape(height, width) + upper = max(float(np.quantile(np.abs(values), .99)), 1e-8) + score = np.clip(values / upper, -1, 1) + # OpenCV's cool-warm map takes 0=blue, .5=neutral, 1=red. + score = cv2.resize(((score + 1) * .5).astype(np.float32), + (image_rgb.shape[1], image_rgb.shape[0])) + heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_COOL) + heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB).astype(np.float32) / 255 + return np.clip(.42 * image_rgb + .58 * heat, 0, 1) + + @staticmethod + def _panel(image: np.ndarray, label: str, size: tuple[int, int] = (240, 416)) -> np.ndarray: + bgr = cv2.cvtColor((image * 255).round().clip(0, 255).astype(np.uint8), cv2.COLOR_RGB2BGR) + bgr = cv2.resize(bgr, size, interpolation=cv2.INTER_AREA) + cv2.rectangle(bgr, (0, 0), (size[0], 36), (0, 0, 0), -1) + cv2.putText(bgr, label, (7, 25), cv2.FONT_HERSHEY_SIMPLEX, .48, + (255, 255, 255), 1, cv2.LINE_AA) + return bgr + + def save(self, output_dir: str | Path, target_video_btchw: torch.Tensor, + reference_image: Image.Image, fps: int = 20) -> None: + output_dir = Path(output_dir); output_dir.mkdir(parents=True, exist_ok=True) + target = target_video_btchw[0].permute(0, 2, 3, 1).float().cpu().numpy() + reference = np.asarray(reference_image.convert("RGB").resize((480, 832))).astype(np.float32) / 255 + stats = [] + for block_id in sorted(self.block_ids): + if block_id not in self.grids: + continue + frames, height, width = self.grids[block_id] + writer = cv2.VideoWriter( + str(output_dir / f"attention_block{block_id:02d}.mp4"), + cv2.VideoWriter_fourcc(*"mp4v"), max(fps / 4, 1), (1440, 416), + ) + contact = [] + chosen = {0, frames // 4, frames // 2, 3 * frames // 4, frames - 1} + for frame in range(frames): + rgb_id = round(frame * (len(target) - 1) / max(frames - 1, 1)) + global_before = self.records[(block_id, frame, "global_before")] + global_after = self.records[(block_id, frame, "global_after")] + face_before = self.records[(block_id, frame, "face_queries_before")] + face_after = self.records[(block_id, frame, "face_queries_after")] + energy_bias = self.energy_biases[(block_id, frame)] + panels = [ + self._panel(target[rgb_id], f"target RGB {rgb_id}"), + self._panel(self._signed_overlay(reference, energy_bias, height, width), "wavelet energy bias"), + self._panel(self._overlay(reference, global_before, height, width, True), "global QK (before)"), + self._panel(self._overlay(reference, global_after, height, width, True), "global QK+bias (after)"), + self._panel(self._overlay(reference, face_before, height, width, True), "face QK (before)"), + self._panel(self._overlay(reference, face_after, height, width, True), "face QK+bias (after)"), + ] + row = np.concatenate(panels, axis=1) + writer.write(row) + if frame in chosen: + contact.append(row) + for name, values in ( + ("global_before", global_before), + ("global_after", global_after), + ("face_queries_before", face_before), + ("face_queries_after", face_after), + ): + p = np.maximum(values, 1e-12); p = p / p.sum() + peak = int(p.argmax()) + stats.append({ + "block": block_id, "latent_frame": frame, "rgb_frame": rgb_id, + "query_region": name, + "normalized_entropy": float(-(p * np.log(p)).sum() / np.log(p.size)), + "peak_over_uniform": float(p.max() * p.size), + "top_10_percent_key_mass": float(np.sort(p)[-max(p.size // 10, 1):].sum()), + "peak_reference_xy": [peak % width, peak // width], + }) + writer.release() + cv2.imwrite(str(output_dir / f"attention_block{block_id:02d}_contact.jpg"), np.concatenate(contact, axis=0)) + (output_dir / "attention_stats.json").write_text( + json.dumps(stats, indent=2), encoding="utf-8" + ) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap_edit.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..b95c69cedc4e5aa81bd5197744a572d98b91f99a --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap_edit.py @@ -0,0 +1,204 @@ +"""Capture selected Wan edit token-prefix attention heads during inference.""" + +from __future__ import annotations + +import argparse +import json +import random +import types +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from diffsynth.bridge.wan_bridge.model_inference.infer_sr_wan22_ti2v_edit import ( + load_pipe, + prepare, + read_video, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + decode_latents_to_btchw_01, + make_lr_source, + tensor_btchw_01_to_pil, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v_edit import ( + normalize_wan_num_frames, +) +from diffsynth.data.video import save_video + + +def parse_ints(value: str) -> list[int]: + return [int(item.strip()) for item in value.split(",") if item.strip()] + + +class EditAttentionRecorder: + def __init__(self, block_ids: list[int], head_ids: list[int], frame_ids: list[int], query_stride: int, num_heads: int): + self.block_ids = set(block_ids) + self.head_ids = set(head_ids) + self.frame_ids = set(frame_ids) + self.query_stride = max(int(query_stride), 1) + self.num_heads = int(num_heads) + self.values: dict[tuple[int, int, int, int], np.ndarray] = {} + self.grid: tuple[int, int, int] | None = None + self.calls: dict[int, int] = {block: 0 for block in block_ids} + + @torch.no_grad() + def capture(self, block_id: int, q: torch.Tensor, k: torch.Tensor, attn_mask: torch.Tensor | None) -> None: + if block_id not in self.block_ids: + return + if q.shape[0] != 1: + raise ValueError("Attention heatmap currently expects batch size 1") + total = int(q.shape[1]) + if total % 2: + raise ValueError(f"Expected equal [c,z] token streams, got {total} tokens") + prefix_tokens = total // 2 + # Wan2.1 uses the same patch grid for c and z in this edit pipeline. + if self.grid is None: + raise RuntimeError("Attention recorder grid was not initialized") + frames, height, width = self.grid + expected = frames * height * width + if expected != prefix_tokens: + raise ValueError(f"Attention grid {self.grid} has {expected} tokens, expected {prefix_tokens}") + call_id = self.calls[block_id] + self.calls[block_id] += 1 + selected_heads = sorted(self.head_ids) + qh = q.float().reshape(1, total, self.num_heads, -1).permute(0, 2, 1, 3)[:, selected_heads] + kh = k.float().reshape(1, total, self.num_heads, -1).permute(0, 2, 1, 3)[:, selected_heads] + scale = qh.shape[-1] ** -0.5 + if attn_mask is None: + mask = None + elif attn_mask.dtype == torch.bool: + mask = attn_mask.to(device=q.device) + else: + mask = attn_mask.to(device=q.device, dtype=torch.float32) + for frame in sorted(self.frame_ids): + if frame < 0 or frame >= frames: + continue + query_start = prefix_tokens + frame * height * width + query_ids = torch.arange(query_start, query_start + height * width, self.query_stride, device=q.device) + key_start = frame * height * width + key_ids = torch.arange(key_start, key_start + height * width, device=q.device) + logits = torch.matmul(qh[:, :, query_ids], kh.transpose(-1, -2)) * scale + if mask is not None: + query_mask = mask[:, :, query_ids, :] + if query_mask.dtype == torch.bool: + logits = logits.masked_fill(~query_mask, torch.finfo(logits.dtype).min) + else: + logits = logits + query_mask + probs = logits.softmax(dim=-1)[0] + for local_head, head_id in enumerate(selected_heads): + # Keep only same-frame reference keys and average selected z queries. + heat = probs[local_head, :, key_ids].mean(dim=0) + self.values[(block_id, head_id, frame, call_id)] = heat.cpu().numpy() + + def save(self, output_dir: Path, reference_frames: list, fps: float) -> None: + output_dir.mkdir(parents=True, exist_ok=True) + manifest = [] + assert self.grid is not None + _, height, width = self.grid + for (block, head, frame, call_id), values in sorted(self.values.items()): + npy = output_dir / f"block{block:02d}_head{head:02d}_frame{frame:02d}_call{call_id:02d}.npy" + np.save(npy, values.reshape(height, width)) + ref = np.asarray(reference_frames[min(frame, len(reference_frames) - 1)].convert("RGB")) + ref = cv2.resize(ref, (width * 32, height * 32), interpolation=cv2.INTER_LINEAR) + score = values.reshape(height, width) + score = score / max(float(score.max()), 1e-12) + score = cv2.resize(score.astype(np.float32), (ref.shape[1], ref.shape[0])) + heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_TURBO) + heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB) + overlay = np.clip(.42 * ref.astype(np.float32) + .58 * heat.astype(np.float32), 0, 255).astype(np.uint8) + image_path = output_dir / f"block{block:02d}_head{head:02d}_frame{frame:02d}_call{call_id:02d}.jpg" + cv2.imwrite(str(image_path), cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 92]) + manifest.append({"block": block, "head": head, "latent_frame": frame, "attention_call": call_id, "npy": str(npy), "jpg": str(image_path), "max_over_uniform": float(values.max() * values.size)}) + (output_dir / "attention_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") + + +def install_recorder(pipe, recorder: EditAttentionRecorder) -> list[tuple[object, object]]: + originals = [] + for block_id in sorted(recorder.block_ids): + module = pipe.dit.blocks[block_id].self_attn.attn + original = module.forward + def wrapped(q, k, v, attn_mask=None, *, _original=original, _block=block_id): + recorder.capture(_block, q, k, attn_mask) + return _original(q, k, v, attn_mask=attn_mask) + module.forward = types.MethodType(lambda self, q, k, v, attn_mask=None, _wrapped=wrapped: _wrapped(q, k, v, attn_mask), module) + originals.append((module, original)) + return originals + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--input_video", required=True) + parser.add_argument("--bridge_video", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--steps", type=int, default=12) + parser.add_argument("--blocks", default="0,14,29") + parser.add_argument("--heads", default="0,5,11") + parser.add_argument("--frames", default="0,4,8") + parser.add_argument("--query_stride", type=int, default=16) + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--sr_scale", type=int, default=4) + parser.add_argument("--sigma_shift", type=float, default=5.0) + parser.add_argument("--sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--prompt", default="") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--tiled", action="store_true") + args = parser.parse_args() + args.num_frames = normalize_wan_num_frames(args.num_frames) + random.seed(args.seed) + torch.manual_seed(args.seed) + reference, fps = read_video(Path(args.input_video), args.height, args.width, args.num_frames) + bridge, _ = read_video(Path(args.bridge_video), args.height, args.width, args.num_frames) + source = [make_lr_source(frame, args.height, args.width, args.sr_scale, upsample_to_hr=False) for frame in bridge] + pipe = load_pipe(args) + prepared = prepare(pipe, reference, source, args) + target_latents = prepared[0]["source_latents"] + _, _, frames, height, width = target_latents.shape + # Wan2.1 patchifies latent tensors with patch_size=(1, 2, 2). + token_grid = (int(frames), int(height // 2), int(width // 2)) + recorder = EditAttentionRecorder( + parse_ints(args.blocks), parse_ints(args.heads), parse_ints(args.frames), + args.query_stride, int(pipe.dit.blocks[0].num_heads), + ) + recorder.grid = token_grid + originals = install_recorder(pipe, recorder) + try: + shared, pos, _ = prepared + pipe.scheduler.set_timesteps(args.steps, shift=args.sigma_shift) + latents = shared["source_latents"].clone() + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + pipe.load_models_to_device(pipe.in_iteration_models) + model_inputs = dict(shared) + model_inputs.pop("latents", None) + model_inputs.pop("original_latents", None) + model_inputs["token_prefix_latents"] = shared["original_latents"].detach() + model_inputs["token_prefix_block_self_attention"] = True + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype) + pred = pipe.model_fn(**models, **model_inputs, **pos, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, shared["source_latents"]) + video = decode_latents_to_btchw_01(pipe, latents, args.tiled, (30, 52), (15, 26)).cpu() + save_video(tensor_btchw_01_to_pil(video[0]), str(Path(args.output_dir) / "prediction_steps_12.mp4"), fps=max(1, round(fps)), quality=5) + finally: + for module, original in originals: + module.forward = original + recorder.save(Path(args.output_dir), reference, fps) + (Path(args.output_dir) / "run_config.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe6cca66e099e4eb3aa9980dcaa644808b91400 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps.py @@ -0,0 +1,257 @@ +"""Compare frozen Wan Bridge SR quality over several inference step counts.""" + +from __future__ import annotations + +import argparse +import json +import math +import random +import time +from pathlib import Path + +import torch +import torch.nn.functional as F + +from diffsynth.bridge.wan_bridge.model_inference.infer_sr import ( + build_pipeline, + default_model_paths, + read_video, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + decode_latents_to_btchw_01, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, + wavelet_hf_loss, +) +from diffsynth.data.video import save_video + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--input_video", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--steps", default="1,2,4,8,20") + parser.add_argument("--sigma_shift", type=float, default=5.0) + parser.add_argument("--sampling_noise_scale", type=float, default=0.0) + parser.add_argument("--cfg_scale", type=float, default=1.0) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--prompt", default="a person is speaking") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--height", type=int, default=832) + parser.add_argument("--width", type=int, default=480) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler") + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument("--device", default="cuda") + parser.add_argument("--rand_device", default="cpu") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--tiled", action="store_true") + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + args = parser.parse_args() + args.num_inference_steps = 1 + args.input_height = args.height // args.sr_scale + args.input_width = args.width // args.sr_scale + args.save_input_compare = False + args.output = None + args.model_paths = args.model_paths or default_model_paths(args.base_model_dir) + return args + + +def prepare_once(pipe, source_video, args): + pipe.scheduler.set_timesteps(1, shift=args.sigma_shift) + inputs_posi = {"prompt": args.prompt, "num_inference_steps": max(args.step_values)} + inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": max(args.step_values)} + inputs_shared = { + "input_video": None, + "source_video": source_video, + "seed": args.seed, + "rand_device": args.rand_device, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "cfg_scale": args.cfg_scale, + "cfg_merge": False, + "sigma_shift": args.sigma_shift, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + } + for unit in pipe.units: + inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner( + unit, pipe, inputs_shared, inputs_posi, inputs_nega + ) + return inputs_shared, inputs_posi, inputs_nega + + +@torch.no_grad() +def sample(pipe, prepared, steps: int, args): + shared, positive, negative = prepared + pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift) + source = shared["source_latents"] + latents = source.clone() + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + pipe.load_models_to_device(pipe.in_iteration_models) + model_inputs = dict(shared) + model_inputs.pop("latents", None) + torch.cuda.reset_peak_memory_stats() + torch.cuda.synchronize() + started = time.perf_counter() + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn(**models, **model_inputs, **positive, latents=latents, timestep=timestep) + if args.cfg_scale != 1.0: + pred_negative = pipe.model_fn( + **models, **model_inputs, **negative, latents=latents, timestep=timestep + ) + pred = pred_negative + args.cfg_scale * (pred - pred_negative) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, source) + torch.cuda.synchronize() + seconds = time.perf_counter() - started + peak_gib = torch.cuda.max_memory_allocated() / 1024**3 + video = decode_latents_to_btchw_01( + pipe, + latents, + args.tiled, + (args.tile_h, args.tile_w), + (args.tile_stride_h, args.tile_stride_w), + ).cpu() + return video, seconds, peak_gib, pipe.scheduler.sigmas.tolist() + + +def center_lpips(model, pred, target, frames=4, crop=224): + count = min(pred.shape[1], target.shape[1]) + ids = torch.linspace(0, count - 1, steps=min(frames, count)).round().long() + pred, target = pred[:, ids], target[:, ids] + crop_h, crop_w = min(crop, pred.shape[-2]), min(crop, pred.shape[-1]) + top, left = (pred.shape[-2] - crop_h) // 2, (pred.shape[-1] - crop_w) // 2 + pred = pred[..., top:top + crop_h, left:left + crop_w] + target = target[..., top:top + crop_h, left:left + crop_w] + pred = pred.reshape(-1, 3, crop_h, crop_w).mul(2).sub(1) + target = target.reshape(-1, 3, crop_h, crop_w).mul(2).sub(1) + return model(pred, target).mean() + + +@torch.no_grad() +def metrics(pred, target, lpips_model): + count = min(pred.shape[1], target.shape[1]) + pred, target = pred[:, :count].float(), target[:, :count].float() + mse = F.mse_loss(pred, target) + delta_pred, delta_target = pred[:, 1:] - pred[:, :-1], target[:, 1:] - target[:, :-1] + color_error = (pred - target).mean(dim=(-2, -1)) + return { + "mse": mse.item(), + "psnr_db": (-10 * torch.log10(mse.clamp_min(1e-12))).item(), + "mae": F.l1_loss(pred, target).item(), + "wavelet_hf_l1": wavelet_hf_loss(pred, target, levels=1, loss_type="l1").item(), + "lpips_vgg": center_lpips(lpips_model, pred, target).item(), + "temporal_delta_l1": delta_pred.abs().mean().item(), + "temporal_delta_error": F.l1_loss(delta_pred, delta_target).item(), + "frame_color_error_std": color_error.std(dim=1).mean().item(), + } + + +def main(): + args = parse_args() + args.step_values = [int(item) for item in args.steps.split(",")] + random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + source_video, _ = read_video( + Path(args.input_video), args.input_height, args.input_width, args.num_frames, 0 + ) + original_video, _ = read_video( + Path(args.input_video), args.height, args.width, args.num_frames, 0 + ) + original = pil_video_to_tensor_01(original_video, torch.device("cpu")).unsqueeze(0) + + pipe = build_pipeline(args) + prepared = prepare_once(pipe, source_video, args) + source_latents = prepared[0]["source_latents"] + ultraflash_video = decode_latents_to_btchw_01( + pipe, + source_latents, + args.tiled, + (args.tile_h, args.tile_w), + (args.tile_stride_h, args.tile_stride_w), + ).cpu() + save_video( + tensor_btchw_01_to_pil(ultraflash_video[0]), + str(output_dir / "ultraflash_only.mp4"), + fps=args.fps, + quality=5, + ) + + outputs = {} + runtime = {} + schedules = {} + for steps in args.step_values: + print(f"[StepSweep] running steps={steps} shift={args.sigma_shift}", flush=True) + video, seconds, peak_gib, sigmas = sample(pipe, prepared, steps, args) + outputs[steps] = video + runtime[steps] = {"seconds": seconds, "peak_allocated_gib": peak_gib} + schedules[steps] = sigmas + save_video( + tensor_btchw_01_to_pil(video[0]), + str(output_dir / f"bridge_steps_{steps:02d}.mp4"), + fps=args.fps, + quality=5, + ) + + pipe.load_models_to_device([]) + import lpips + + lpips_model = lpips.LPIPS(net="vgg", verbose=False).eval() + results = {"ultraflash_only": metrics(ultraflash_video, original, lpips_model)} + for steps, video in outputs.items(): + results[f"steps_{steps}"] = metrics(video, original, lpips_model) + results[f"steps_{steps}"].update(runtime[steps]) + + comparison = torch.cat( + [ultraflash_video] + [outputs[step] for step in args.step_values] + [original], dim=-1 + ) + save_video( + tensor_btchw_01_to_pil(comparison[0]), + str(output_dir / "comparison_ultraflash_steps1-2-4-8-20_original.mp4"), + fps=args.fps, + quality=5, + ) + payload = { + "input_video": str(Path(args.input_video).resolve()), + "checkpoint": args.checkpoint, + "comparison_order": ["ultraflash_only"] + [f"steps_{s}" for s in args.step_values] + ["original"], + "settings": { + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "sr_scale": args.sr_scale, + "sigma_shift": args.sigma_shift, + "sampling_noise_scale": args.sampling_noise_scale, + "cfg_scale": args.cfg_scale, + "target": args.target, + "prompt": args.prompt, + "seed": args.seed, + }, + "sigma_schedules": schedules, + "metrics": results, + } + (output_dir / "metrics.json").write_text(json.dumps(payload, indent=2), encoding="utf-8") + print(json.dumps(results, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps_firstframe_anchor.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps_firstframe_anchor.py new file mode 100644 index 0000000000000000000000000000000000000000..ce80477d85292dbd17e4c929cdf28ee4ca820975 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps_firstframe_anchor.py @@ -0,0 +1,419 @@ +"""Compare first-frame-anchor Wan Bridge SR over several inference step counts.""" + +from __future__ import annotations + +import argparse +import json +import random +import shutil +import subprocess +import sys +import time +from pathlib import Path + +import cv2 +import torch + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from PIL import Image # noqa: E402 + +from diffsynth.bridge.wan_bridge.model_inference.infer_sr import ( # noqa: E402 + default_model_paths, + pick_video, + read_video, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + decode_latents_to_btchw_01, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr_firstframe_anchor import ( # noqa: E402 + FirstFrameAnchorWanVideoSRBridgePipeline, + replace_first_latent_frame, +) +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 +from safetensors.torch import load_file # noqa: E402 + + +def probe_video(path: Path) -> tuple[int, int, int, float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video: {path}") + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0) + cap.release() + if width <= 0 or height <= 0 or frames <= 0: + raise RuntimeError(f"Invalid video metadata for {path}: {width}x{height}, frames={frames}") + return width, height, frames, fps + + +def fit_reference(image: Image.Image, height: int, width: int, mode: str) -> Image.Image: + image = image.convert("RGB") + if mode == "resize": + return image.resize((width, height), Image.Resampling.BICUBIC) + src_w, src_h = image.size + scale = max(width / src_w, height / src_h) + resized = image.resize( + (max(width, round(src_w * scale)), max(height, round(src_h * scale))), + Image.Resampling.BICUBIC, + ) + left = (resized.width - width) // 2 + top = (resized.height - height) // 2 + return resized.crop((left, top, left + width, top + height)) + + +def load_dit_checkpoint(pipe: FirstFrameAnchorWanVideoSRBridgePipeline, checkpoint: str) -> str: + state_dict = load_file(checkpoint, device="cpu") + prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.") + candidates = [("raw", state_dict)] + for prefix in prefixes: + if any(k.startswith(prefix) for k in state_dict): + candidates.append(( + f"strip:{prefix}", + {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state_dict.items()}, + )) + errors = [] + for name, candidate in candidates: + try: + pipe.dit.load_state_dict(candidate, strict=True) + print(f"[FirstFrameAnchorSR] Loaded DiT checkpoint with strategy: {name}", flush=True) + return name + except Exception as exc: + errors.append((name, str(exc).splitlines()[0])) + msg = "\n".join(f"{name}: {err}" for name, err in errors) + raise RuntimeError(f"Could not strictly load first-frame-anchor checkpoint:\n{msg}") + + +def build_pipeline(args) -> FirstFrameAnchorWanVideoSRBridgePipeline: + model_paths = args.model_paths or default_model_paths(args.base_model_dir) + model_configs = [ModelConfig(path=path) for path in model_paths.split(",")] + pipe = FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device=args.device, + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_strategy = load_dit_checkpoint(pipe, args.checkpoint) + pipe.latent_upsampler = None + if int(getattr(pipe.vae, "z_dim", 0)) == 48 and not getattr( + pipe.dit, "fuse_vae_embedding_in_latents", False + ): + raise RuntimeError( + "Wan2.2-TI2V VAE was loaded, but the DiT does not support fused first-frame input" + ) + pipe.scheduler.noise_scale = args.sampling_noise_scale + pipe.scheduler.bridge_type = "brownian" + pipe.scheduler.training_weight_type = "uniform" + pipe.scheduler.target = args.target + pipe.eval().requires_grad_(False) + args.load_strategy = load_strategy + return pipe + + +def reset_seed(seed: int) -> None: + random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + + +def upscale_and_anchor_source( + lr_video: list[Image.Image], + reference_image: Image.Image, + height: int, + width: int, +) -> list[Image.Image]: + source = [frame.resize((width, height), Image.Resampling.BICUBIC) for frame in lr_video] + source[0] = reference_image.copy() + return source + + +@torch.no_grad() +def encode_reference(pipe, reference_image: Image.Image, args) -> torch.Tensor: + pipe.load_models_to_device(["vae"]) + reference_video = pipe.preprocess_video([reference_image]) + anchor = pipe.vae.encode( + reference_video, + device=pipe.device, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).to(dtype=pipe.torch_dtype, device=pipe.device) + if anchor.shape[2] != 1: + raise RuntimeError(f"Expected one reference latent frame, got {tuple(anchor.shape)}") + return anchor + + +@torch.no_grad() +def prepare_once(pipe, source_video: list[Image.Image], reference_image: Image.Image, args): + pipe.scheduler.set_timesteps(1000, training=True) + inputs_posi = {"prompt": args.prompt, "num_inference_steps": max(args.step_values)} + inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": max(args.step_values)} + inputs_shared = { + "input_video": None, + "source_video": source_video, + "seed": args.seed, + "rand_device": args.rand_device, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "cfg_scale": args.cfg_scale, + "cfg_merge": False, + "sigma_shift": args.sigma_shift, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + "fuse_vae_embedding_in_latents": bool( + getattr(pipe.dit, "fuse_vae_embedding_in_latents", False) + ), + } + for unit in pipe.units: + inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner( + unit, pipe, inputs_shared, inputs_posi, inputs_nega + ) + inputs_shared["first_frame_latents"] = encode_reference(pipe, reference_image, args) + inputs_shared["source_latents"] = replace_first_latent_frame( + inputs_shared["source_latents"], inputs_shared["first_frame_latents"] + ) + return inputs_shared, inputs_posi, inputs_nega + + +@torch.no_grad() +def sample(pipe, prepared, steps: int, args): + shared, positive, negative = prepared + reset_seed(args.seed) + pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift) + source = replace_first_latent_frame(shared["source_latents"], shared["first_frame_latents"]) + latents = source.clone() + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + pipe.load_models_to_device(pipe.in_iteration_models) + model_inputs = dict(shared) + model_inputs.pop("latents", None) + model_inputs.pop("first_frame_latents", None) + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + torch.cuda.synchronize() + started = time.perf_counter() + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn(**models, **model_inputs, **positive, latents=latents, timestep=timestep) + if args.cfg_scale != 1.0: + pred_neg = pipe.model_fn( + **models, **model_inputs, **negative, latents=latents, timestep=timestep + ) + pred = pred_neg + args.cfg_scale * (pred - pred_neg) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, source) + if args.anchor_each_step: + latents = replace_first_latent_frame(latents, shared["first_frame_latents"]) + if torch.cuda.is_available(): + torch.cuda.synchronize() + peak_gib = torch.cuda.max_memory_allocated() / 1024**3 + else: + peak_gib = 0.0 + seconds = time.perf_counter() - started + return latents, seconds, peak_gib, [float(s) for s in pipe.scheduler.sigmas] + + +@torch.no_grad() +def decode(pipe, latents: torch.Tensor, args) -> torch.Tensor: + pipe.load_models_to_device(["vae"]) + return decode_latents_to_btchw_01( + pipe, + latents, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).cpu() + + +def save_with_optional_audio(video: torch.Tensor, output: Path, source_audio_video: Path, fps: int, copy_audio: bool): + output.parent.mkdir(parents=True, exist_ok=True) + if not copy_audio: + save_video(tensor_btchw_01_to_pil(video[0]), str(output), fps=fps, quality=5) + return + silent = output.with_name(f".{output.stem}_silent{output.suffix}") + save_video(tensor_btchw_01_to_pil(video[0]), str(silent), fps=fps, quality=5) + try: + subprocess.run( + [ + "ffmpeg", "-y", "-loglevel", "error", + "-i", str(silent), "-i", str(source_audio_video), + "-map", "0:v:0", "-map", "1:a?", + "-c:v", "copy", "-c:a", "aac", "-shortest", str(output), + ], + check=True, + ) + finally: + silent.unlink(missing_ok=True) + + +def save_lr_copy(source_path: Path, output: Path, copy_audio: bool, fps: int, lr_video: list[Image.Image]) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + if copy_audio: + shutil.copy2(source_path, output) + else: + save_video(lr_video, str(output), fps=fps, quality=5) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--input_video", required=True) + parser.add_argument("--reference_image", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--output_stem", default=None) + parser.add_argument("--steps", default="1,2,4,8,12") + parser.add_argument("--sigma_shift", type=float, default=5.0) + parser.add_argument("--sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--cfg_scale", type=float, default=1.0) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--prompt", default="a person is speaking") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--height", type=int, default=832) + parser.add_argument("--width", type=int, default=480) + parser.add_argument("--input_height", type=int, default=None) + parser.add_argument("--input_width", type=int, default=None) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--start_frame", type=int, default=0) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--device", default="cuda") + parser.add_argument("--rand_device", default="cpu") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--fps", type=int, default=None) + parser.add_argument("--reference_resize_mode", choices=["crop", "resize"], default="resize") + parser.add_argument("--copy_audio", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument( + "--anchor_each_step", + action=argparse.BooleanOptionalAction, + default=True, + help="Re-lock latent frame 0 to the reference after every denoise step. Disable to anchor only at initialization.", + ) + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + args = parser.parse_args() + args.step_values = [int(item) for item in args.steps.split(",") if item.strip()] + if not args.step_values: + raise ValueError("--steps must contain at least one integer") + args.model_paths = args.model_paths or default_model_paths(args.base_model_dir) + return args + + +def main(): + args = parse_args() + reset_seed(args.seed) + source_path = pick_video(args.input_video).resolve() + source_w, source_h, source_frames, source_fps = probe_video(source_path) + args.num_frames = min(args.num_frames, source_frames) + args.fps = args.fps or max(1, int(round(source_fps))) + args.input_height = args.input_height or source_h + args.input_width = args.input_width or source_w + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + stem = args.output_stem or source_path.stem + + lr_video, _ = read_video( + source_path, + args.input_height, + args.input_width, + args.num_frames, + args.start_frame, + ) + reference_image = fit_reference( + Image.open(args.reference_image), args.height, args.width, args.reference_resize_mode + ) + source_video = upscale_and_anchor_source(lr_video, reference_image, args.height, args.width) + + lr_output = output_dir / f"{stem}_liveact_lr.mp4" + anchored_source_output = output_dir / f"{stem}_bicubic_anchor_source.mp4" + save_lr_copy(source_path, lr_output, args.copy_audio, args.fps, lr_video) + save_video(source_video, str(anchored_source_output), fps=args.fps, quality=5) + + print( + f"[FirstFrameAnchorCascade] LR={source_path} {source_w}x{source_h} frames={args.num_frames}; " + f"target={args.width}x{args.height}; steps={args.step_values}; shift={args.sigma_shift}; noise={args.sampling_noise_scale}", + flush=True, + ) + pipe = build_pipeline(args) + prepared = prepare_once(pipe, source_video, reference_image, args) + source_preview = decode(pipe, prepared[0]["source_latents"], args) + source_preview_output = output_dir / f"{stem}_source_latents_decoded.mp4" + save_with_optional_audio(source_preview, source_preview_output, source_path, args.fps, args.copy_audio) + + outputs = {} + runtime = {} + schedules = {} + for steps in args.step_values: + print(f"[FirstFrameAnchorCascade] Running steps={steps}", flush=True) + latents, seconds, peak_gib, sigmas = sample(pipe, prepared, steps, args) + video = decode(pipe, latents, args) + outputs[steps] = video + runtime[steps] = {"seconds": seconds, "peak_allocated_gib": peak_gib} + schedules[str(steps)] = sigmas + save_with_optional_audio( + video, + output_dir / f"{stem}_bridge_ffanchor_steps_{steps:02d}.mp4", + source_path, + args.fps, + args.copy_audio, + ) + + comparison = torch.cat([source_preview] + [outputs[step] for step in args.step_values], dim=-1) + comparison_name = f"{stem}_comparison_source_{'_'.join(f's{s}' for s in args.step_values)}.mp4" + comparison_output = output_dir / comparison_name + save_with_optional_audio(comparison, comparison_output, source_path, args.fps, args.copy_audio) + + metadata = { + "input_video": str(source_path), + "reference_image": str(Path(args.reference_image).resolve()), + "checkpoint": args.checkpoint, + "load_strategy": getattr(args, "load_strategy", None), + "outputs": { + "liveact_lr": str(lr_output), + "bicubic_anchor_source": str(anchored_source_output), + "source_latents_decoded": str(source_preview_output), + "comparison": str(comparison_output), + "steps": { + str(step): str(output_dir / f"{stem}_bridge_ffanchor_steps_{step:02d}.mp4") + for step in args.step_values + }, + }, + "runtime": runtime, + "sigma_schedules": schedules, + "settings": { + "input_size_hw": [args.input_height, args.input_width], + "target_size_hw": [args.height, args.width], + "num_frames": args.num_frames, + "fps": args.fps, + "steps": args.step_values, + "sigma_shift": args.sigma_shift, + "sampling_noise_scale": args.sampling_noise_scale, + "cfg_scale": args.cfg_scale, + "target": args.target, + "prompt": args.prompt, + "seed": args.seed, + "first_frame_anchor": True, + "anchor_each_step": args.anchor_each_step, + "source_mode": "bicubic_upscaled_liveact_lr_with_hr_reference_first_frame", + }, + } + (output_dir / f"{stem}_ffanchor_step_sweep.json").write_text( + json.dumps(metadata, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + print(f"[FirstFrameAnchorCascade] Outputs written to: {output_dir}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/diagnose_flicker.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/diagnose_flicker.py new file mode 100644 index 0000000000000000000000000000000000000000..9ae91dcb4b77a67457ed902e6cfa7743a4f3e9f6 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/diagnose_flicker.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Measure temporal brightness/color/structure jumps and align them to chunks.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import cv2 +import numpy as np + + +def read_frames(path: Path) -> tuple[np.ndarray, float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Cannot open {path}") + fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0) + frames = [] + while True: + ok, frame = cap.read() + if not ok: + break + frames.append(frame) + cap.release() + if not frames: + raise RuntimeError(f"No frames in {path}") + return np.stack(frames), fps + + +def robust_z(x: np.ndarray) -> np.ndarray: + med = np.median(x) + mad = np.median(np.abs(x - med)) + 1e-8 + return 0.6745 * (x - med) / mad + + +def analyze(frames: np.ndarray, fps: float, chunk_latent: int, temporal_stride: int) -> dict: + rgb = frames[:, :, :, ::-1].astype(np.float32) / 255.0 + gray = np.stack([ + cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for frame in frames + ]).astype(np.float32) / 255.0 + lab = np.stack([ + cv2.cvtColor(frame, cv2.COLOR_BGR2LAB) for frame in frames + ]).astype(np.float32) + # OpenCV LAB is approximately [0,255] for all channels. + lum = gray.mean(axis=(1, 2)) + lab_mean = lab.mean(axis=(1, 2)) + sat = rgb.max(axis=3).mean(axis=(1, 2)) - rgb.min(axis=3).mean(axis=(1, 2)) + frame_diff = np.abs(gray[1:] - gray[:-1]).mean(axis=(1, 2)) + color_diff = np.abs(lab_mean[1:] - lab_mean[:-1]).mean(axis=1) + edge = np.stack([ + cv2.Laplacian(gray[i], cv2.CV_32F).var() for i in range(len(gray)) + ]) + edge_diff = np.abs(edge[1:] - edge[:-1]) + + scores = ( + robust_z(frame_diff) + + robust_z(color_diff) + + 0.25 * robust_z(edge_diff) + ) + order = np.argsort(scores)[::-1] + boundaries = list(range(1 + chunk_latent * temporal_stride, len(frames), chunk_latent * temporal_stride)) + + def around(index: int) -> dict: + lo = max(0, index - 2) + hi = min(len(frames) - 1, index + 2) + return { + "frame": int(index), + "time_sec": round(index / fps, 4), + "lum": round(float(lum[index]), 6), + "lab": [round(float(v), 4) for v in lab_mean[index]], + "sat": round(float(sat[index]), 6), + "window_lum_range": round(float(lum[lo:hi + 1].max() - lum[lo:hi + 1].min()), 6), + } + + boundary_stats = [] + for b in boundaries: + left = max(0, b - 3) + right = min(len(frames) - 1, b + 2) + boundary_stats.append({ + "boundary_frame": b, + "boundary_time_sec": round(b / fps, 4), + "lum_jump_at_boundary": round(float(abs(lum[b] - lum[b - 1])), 6), + "color_jump_at_boundary": round(float(color_diff[b - 1]), 6), + "frame_diff_at_boundary": round(float(frame_diff[b - 1]), 6), + "left_mean_lum": round(float(lum[left:b].mean()), 6), + "right_mean_lum": round(float(lum[b:right + 1].mean()), 6), + }) + + return { + "frames": int(len(frames)), + "fps": fps, + "duration_sec": round(len(frames) / fps, 4), + "size": [int(frames.shape[2]), int(frames.shape[1])], + "chunk_latent_frames": chunk_latent, + "temporal_stride": temporal_stride, + "predicted_chunk_boundaries": boundaries, + "top_temporal_jumps": [around(int(i + 1)) | { + "frame_diff": round(float(frame_diff[i]), 6), + "color_diff": round(float(color_diff[i]), 6), + "edge_diff": round(float(edge_diff[i]), 6), + "combined_robust_score": round(float(scores[i]), 4), + } for i in order[:12]], + "boundary_stats": boundary_stats, + "summary": { + "lum_min": round(float(lum.min()), 6), + "lum_max": round(float(lum.max()), 6), + "lum_std": round(float(lum.std()), 6), + "max_frame_diff": round(float(frame_diff.max(initial=0)), 6), + "max_color_diff": round(float(color_diff.max(initial=0)), 6), + "median_frame_diff": round(float(np.median(frame_diff)), 6), + }, + "series": { + "luminance": [round(float(v), 6) for v in lum], + "lab_mean": [[round(float(v), 4) for v in row] for row in lab_mean], + "saturation": [round(float(v), 6) for v in sat], + "frame_diff": [round(float(v), 6) for v in frame_diff], + "color_diff": [round(float(v), 6) for v in color_diff], + "edge_variance": [round(float(v), 4) for v in edge], + }, + } + + +def save_plot(report: dict, path: Path) -> None: + import matplotlib.pyplot as plt + + n = report["frames"] + x = np.arange(n) + boundaries = report["predicted_chunk_boundaries"] + fig, axes = plt.subplots(3, 1, figsize=(15, 9), sharex=True) + axes[0].plot(x, report["series"]["luminance"], label="mean luminance") + axes[0].plot(x, report["series"]["saturation"], label="mean saturation", alpha=0.8) + axes[0].set_ylabel("brightness / sat") + axes[0].legend(loc="upper right") + axes[1].plot(x[1:], report["series"]["frame_diff"], label="gray frame diff") + axes[1].plot(x[1:], report["series"]["color_diff"], label="Lab color diff") + axes[1].set_ylabel("temporal change") + axes[1].legend(loc="upper right") + axes[2].plot(x, report["series"]["edge_variance"], label="Laplacian variance") + axes[2].set_ylabel("structure") + axes[2].set_xlabel("pixel frame") + for ax in axes: + for b in boundaries: + ax.axvline(b, color="red", alpha=0.35, linestyle="--") + fig.suptitle(f"{report['frames']} frames; red lines = predicted chunk boundaries") + fig.tight_layout() + fig.savefig(path, dpi=160) + plt.close(fig) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("video", type=Path) + parser.add_argument("--output_dir", type=Path, default=None) + parser.add_argument("--chunk_latent_frames", type=int, default=4) + parser.add_argument("--temporal_stride", type=int, default=4) + args = parser.parse_args() + out = args.output_dir or args.video.with_suffix("") + out.mkdir(parents=True, exist_ok=True) + frames, fps = read_frames(args.video) + report = analyze(frames, fps, args.chunk_latent_frames, args.temporal_stride) + (out / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8") + save_plot(report, out / "flicker_diagnostic.png") + print(json.dumps({ + "report": str(out / "report.json"), + "plot": str(out / "flicker_diagnostic.png"), + "top_temporal_jumps": report["top_temporal_jumps"][:8], + "boundary_stats": report["boundary_stats"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr.py new file mode 100644 index 0000000000000000000000000000000000000000..8bed915386a60a5081664e06b3c691b73886a691 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr.py @@ -0,0 +1,293 @@ +import argparse +import json +import os +import random +import sys +from pathlib import Path + +import cv2 +import numpy as np +import torch +from PIL import Image +from safetensors.torch import load_file + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + WanVideoSRBridgePipeline, + WanVideoSRUnit_UltraFlashLatentUpsampler, + center_crop_resize, + decode_latents_to_btchw_01, + load_ultraflash_latent_upsampler, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, +) + + +def load_dit_checkpoint(pipe: WanVideoSRBridgePipeline, checkpoint: str): + state_dict = load_file(checkpoint, device="cpu") + prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.") + candidates = [("raw", state_dict)] + for prefix in prefixes: + if any(k.startswith(prefix) for k in state_dict): + candidates.append(( + f"strip:{prefix}", + {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state_dict.items()}, + )) + + errors = [] + for name, candidate in candidates: + try: + pipe.dit.load_state_dict(candidate, strict=True) + print(f"[WanBridgeSR] Loaded DiT checkpoint with strategy: {name}") + return + except Exception as exc: + errors.append((name, str(exc))) + msg = "\n".join(f"{name}: {err}" for name, err in errors) + raise RuntimeError(f"Could not strictly load SR bridge checkpoint:\n{msg}") + + +def default_model_paths(base_model_dir: str) -> str: + base = Path(base_model_dir) + paths = [ + base / "diffusion_pytorch_model.safetensors", + base / "models_t5_umt5-xxl-enc-bf16.pth", + base / "Wan2.1_VAE.pth", + ] + for path in paths: + if not path.exists(): + raise FileNotFoundError(f"Missing Wan model file: {path}") + return ",".join(str(path) for path in paths) + + +def build_pipeline(args) -> WanVideoSRBridgePipeline: + model_paths = args.model_paths or default_model_paths(args.base_model_dir) + model_configs = [ModelConfig(path=path) for path in model_paths.split(",")] + pipe = WanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device=args.device, + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_dit_checkpoint(pipe, args.checkpoint) + if args.source_mode == "upsampler": + pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device=args.device) + pipe.units = pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()] + print(f"[WanBridgeSR] source_mode=upsampler ckpt={args.latent_upsampler_ckpt}") + else: + pipe.latent_upsampler = None + print("[WanBridgeSR] source_mode=bicubic") + pipe.scheduler.noise_scale = args.sampling_noise_scale + pipe.scheduler.bridge_type = "brownian" + pipe.scheduler.training_weight_type = "uniform" + pipe.scheduler.target = args.target + pipe.eval().requires_grad_(False) + return pipe + + +def pick_video(path: str | Path) -> Path: + path = Path(path) + if path.is_file(): + return path + if path.is_dir(): + videos = sorted( + p for p in path.rglob("*") + if p.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".avi") + ) + if videos: + return videos[0] + raise FileNotFoundError(f"No input video found: {path}") + + +def read_video(path: Path, height: int, width: int, frames: int, start_frame: int = 0) -> tuple[list[Image.Image], float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video: {path}") + fps = cap.get(cv2.CAP_PROP_FPS) or 16 + frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + start_frame = max(int(start_frame), 0) + if frame_count > 0: + start_frame = min(start_frame, max(frame_count - 1, 0)) + cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame) + out = [] + last = None + while len(out) < frames: + ok, frame = cap.read() + if not ok: + if last is None: + break + frame = last.copy() + last = frame + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + image = Image.fromarray(frame) + out.append(center_crop_resize(image, height, width)) + cap.release() + if not out: + raise RuntimeError(f"No frames decoded from: {path}") + while len(out) < frames: + out.append(out[-1].copy()) + return out, float(fps) + + +def save_input_pred_video(path: Path, source_video: list[Image.Image], pred_video_btchw_01: torch.Tensor, fps: int): + source = pil_video_to_tensor_01(source_video, pred_video_btchw_01.device).unsqueeze(0) + if source.shape[-2:] != pred_video_btchw_01.shape[-2:]: + b, t, c, h, w = source.shape + source = torch.nn.functional.interpolate( + source.reshape(b * t, c, h, w), + size=pred_video_btchw_01.shape[-2:], + mode="bicubic", + align_corners=False, + antialias=True, + ).reshape(b, t, c, pred_video_btchw_01.shape[-2], pred_video_btchw_01.shape[-1]).clamp(0, 1) + min_t = min(source.shape[1], pred_video_btchw_01.shape[1]) + strip = torch.cat([source[:, :min_t], pred_video_btchw_01[:, :min_t]], dim=-1) + save_video(tensor_btchw_01_to_pil(strip[0]), str(path), fps=fps, quality=5) + + +@torch.no_grad() +def run_sr(pipe: WanVideoSRBridgePipeline, source_video: list[Image.Image], prompt: str, args) -> torch.Tensor: + random.seed(args.seed) + torch.manual_seed(args.seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(args.seed) + + pipe.scheduler.set_timesteps(args.num_inference_steps, shift=args.sigma_shift) + inputs_posi = {"prompt": prompt, "num_inference_steps": args.num_inference_steps} + inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": args.num_inference_steps} + inputs_shared = { + "input_video": None, + "source_video": source_video, + "seed": args.seed, + "rand_device": args.rand_device, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "cfg_scale": args.cfg_scale, + "cfg_merge": False, + "sigma_shift": args.sigma_shift, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + } + + for unit in pipe.units: + inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner(unit, pipe, inputs_shared, inputs_posi, inputs_nega) + + latents = inputs_shared["source_latents"].clone() + pipe.load_models_to_device(pipe.in_iteration_models) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs_shared) + model_inputs.pop("latents", None) + + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred_pos = pipe.model_fn(**models, **model_inputs, **inputs_posi, latents=latents, timestep=timestep) + if args.cfg_scale != 1.0: + pred_neg = pipe.model_fn(**models, **model_inputs, **inputs_nega, latents=latents, timestep=timestep) + pred = pred_neg + args.cfg_scale * (pred_pos - pred_neg) + else: + pred = pred_pos + latents = pipe.scheduler.step(pred, timestep_cpu, latents, inputs_shared["source_latents"]) + + pipe.load_models_to_device(["vae"]) + return decode_latents_to_btchw_01( + pipe, + latents, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Wan bridge-SR inference for SR checkpoints trained by train_sr.py.") + parser.add_argument("--checkpoint", required=True, help="SR bridge DiT safetensors checkpoint.") + parser.add_argument("--input_video", required=True, help="LR/base input video or directory.") + parser.add_argument("--output", default=None) + parser.add_argument("--prompt", default="") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--input_height", type=int, default=None) + parser.add_argument("--input_width", type=int, default=None) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--start_frame", type=int, default=0) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler") + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument("--num_inference_steps", type=int, default=8) + parser.add_argument("--sampling_noise_scale", type=float, default=0.0) + parser.add_argument("--sigma_shift", type=float, default=1.0) + parser.add_argument("--cfg_scale", type=float, default=1.0) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--fps", type=int, default=None) + parser.add_argument("--device", default="cuda") + parser.add_argument("--rand_device", default="cpu") + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--save_input_compare", action="store_true", default=False) + return parser.parse_args() + + +def main(): + args = parse_args() + source_path = pick_video(args.input_video) + input_h = args.input_height or (args.height if args.source_mode == "bicubic" else args.height // args.sr_scale) + input_w = args.input_width or (args.width if args.source_mode == "bicubic" else args.width // args.sr_scale) + source_video, source_fps = read_video(source_path, input_h, input_w, args.num_frames, args.start_frame) + fps = args.fps or int(round(source_fps)) or 16 + output = Path(args.output) if args.output else Path(f"{source_path.stem}_wan_bridge_sr.mp4") + output.parent.mkdir(parents=True, exist_ok=True) + + print(f"[WanBridgeSR] input={source_path} read={input_h}x{input_w} frames={args.num_frames}") + print(f"[WanBridgeSR] target={args.height}x{args.width} source_mode={args.source_mode} steps={args.num_inference_steps}") + pipe = build_pipeline(args) + pred_video = run_sr(pipe, source_video, args.prompt, args) + save_video(tensor_btchw_01_to_pil(pred_video[0]), str(output), fps=fps, quality=5) + print(f"[WanBridgeSR] Saved: {output}") + + if args.save_input_compare: + compare = output.with_name(output.stem + "_input_pred.mp4") + save_input_pred_video(compare, source_video, pred_video, fps) + print(f"[WanBridgeSR] Saved compare: {compare}") + + meta = { + "checkpoint": args.checkpoint, + "input_video": str(source_path), + "output": str(output), + "prompt": args.prompt, + "height": args.height, + "width": args.width, + "input_height": input_h, + "input_width": input_w, + "num_frames": args.num_frames, + "source_mode": args.source_mode, + "latent_upsampler_ckpt": args.latent_upsampler_ckpt, + "num_inference_steps": args.num_inference_steps, + "sampling_noise_scale": args.sampling_noise_scale, + "sigma_shift": args.sigma_shift, + "cfg_scale": args.cfg_scale, + "target": args.target, + "seed": args.seed, + "output_shape_btchw": list(pred_video.shape), + } + output.with_suffix(".json").write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_reference.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..94df73020bb0f4ded838ed153b0bd8994b27c2c1 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_reference.py @@ -0,0 +1,400 @@ +"""Run frozen Wan Bridge SR and reference-adapted Bridge SR on one LR video. + +This is the post-processing half of the SoulX-LiveAct cascade. It loads the +frozen Bridge once, runs the exact same prepared LR source through the base and +reference paths, and writes LR/base/adapter videos for direct comparison. +""" + +from __future__ import annotations + +import argparse +import json +import random +import shutil +import subprocess +import sys +from pathlib import Path + +import cv2 +import torch +from PIL import Image + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.model_inference.infer_sr import ( # noqa: E402 + build_pipeline, + default_model_paths, + pick_video, + read_video, +) +from diffsynth.bridge.wan_bridge.model_training.reference_adapter import ( # noqa: E402 + clear_reference_condition, + install_reference_adapters, + parse_block_ids, + prepare_reference_condition, + reference_blocks, + set_reference_adapters_enabled, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + decode_latents_to_btchw_01, + tensor_btchw_01_to_pil, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr_reference import ( # noqa: E402 + load_adapter_checkpoint, +) +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.bridge.wan_bridge.model_inference.attention_heatmap import ( # noqa: E402 + ReferenceAttentionRecorder, +) + + +def probe_video(path: Path) -> tuple[int, int, int, float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video: {path}") + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0) + cap.release() + if width <= 0 or height <= 0 or frames <= 0: + raise RuntimeError(f"Invalid video metadata for {path}: {width}x{height}, frames={frames}") + return width, height, frames, fps + + +def fit_reference(image: Image.Image, height: int, width: int, mode: str) -> Image.Image: + image = image.convert("RGB") + if mode == "resize": + return image.resize((width, height), Image.Resampling.BICUBIC) + src_w, src_h = image.size + scale = max(width / src_w, height / src_h) + resized = image.resize( + (max(width, round(src_w * scale)), max(height, round(src_h * scale))), + Image.Resampling.BICUBIC, + ) + left = (resized.width - width) // 2 + top = (resized.height - height) // 2 + return resized.crop((left, top, left + width, top + height)) + + +@torch.no_grad() +def encode_reference(pipe, reference_image: Image.Image, args) -> torch.Tensor: + pipe.load_models_to_device(["vae"]) + reference_video = pipe.preprocess_video([reference_image]) + reference_latents = pipe.vae.encode( + reference_video, + device=pipe.device, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).to(dtype=pipe.torch_dtype, device=pipe.device) + if reference_latents.shape[2] != 1: + raise RuntimeError( + f"A single LiveAct reference image must encode to one latent frame, got {reference_latents.shape[2]}" + ) + return reference_latents + + +@torch.no_grad() +def prepare_inputs(pipe, source_video: list[Image.Image], prompt: str, args): + inputs_posi = {"prompt": prompt, "num_inference_steps": args.num_inference_steps} + inputs_nega = { + "negative_prompt": args.negative_prompt, + "num_inference_steps": args.num_inference_steps, + } + inputs_shared = { + "input_video": None, + "source_video": source_video, + "seed": args.seed, + "rand_device": args.rand_device, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "cfg_scale": args.cfg_scale, + "cfg_merge": False, + "sigma_shift": args.sigma_shift, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + } + for unit in pipe.units: + inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner( + unit, pipe, inputs_shared, inputs_posi, inputs_nega + ) + return inputs_shared, inputs_posi, inputs_nega + + +def reset_seed(seed: int) -> None: + random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + + +@torch.no_grad() +def predict_latents(pipe, prepared, args, reference_latents: torch.Tensor | None) -> torch.Tensor: + inputs_shared, inputs_posi, inputs_nega = prepared + reset_seed(args.seed) + pipe.scheduler.set_timesteps(args.num_inference_steps, shift=args.sigma_shift) + + source_latents = inputs_shared["source_latents"] + latents = source_latents.clone() + if reference_latents is None: + clear_reference_condition(pipe.dit) + set_reference_adapters_enabled(pipe.dit, False) + else: + set_reference_adapters_enabled(pipe.dit, True) + prepare_reference_condition(pipe.dit, source_latents, reference_latents) + + pipe.load_models_to_device(pipe.in_iteration_models) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs_shared) + model_inputs.pop("latents", None) + + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred_pos = pipe.model_fn( + **models, **model_inputs, **inputs_posi, latents=latents, timestep=timestep + ) + if args.cfg_scale != 1.0: + pred_neg = pipe.model_fn( + **models, **model_inputs, **inputs_nega, latents=latents, timestep=timestep + ) + prediction = pred_neg + args.cfg_scale * (pred_pos - pred_neg) + else: + prediction = pred_pos + latents = pipe.scheduler.step(prediction, timestep_cpu, latents, source_latents) + + clear_reference_condition(pipe.dit) + return latents + + +@torch.no_grad() +def decode(pipe, latents: torch.Tensor, args) -> torch.Tensor: + pipe.load_models_to_device(["vae"]) + return decode_latents_to_btchw_01( + pipe, + latents, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).cpu() + + +def save_with_optional_audio(video: torch.Tensor, output: Path, source_audio: Path, fps: int, copy_audio: bool): + output.parent.mkdir(parents=True, exist_ok=True) + if not copy_audio: + save_video(tensor_btchw_01_to_pil(video[0]), str(output), fps=fps, quality=5) + return + + silent = output.with_name(f".{output.stem}_silent{output.suffix}") + save_video(tensor_btchw_01_to_pil(video[0]), str(silent), fps=fps, quality=5) + try: + subprocess.run( + [ + "ffmpeg", "-y", "-loglevel", "error", + "-i", str(silent), "-i", str(source_audio), + "-map", "0:v:0", "-map", "1:a?", + "-c:v", "copy", "-c:a", "aac", "-shortest", str(output), + ], + check=True, + ) + finally: + silent.unlink(missing_ok=True) + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Run LR LiveAct video through frozen Bridge and CrossRoPE reference Adapter." + ) + parser.add_argument("--input_video", required=True) + parser.add_argument("--reference_image", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--output_stem", default=None) + parser.add_argument("--bridge_checkpoint", required=True) + parser.add_argument("--adapter_checkpoint", required=True) + parser.add_argument("--prompt", default="a person is speaking") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--height", type=int, default=832) + parser.add_argument("--width", type=int, default=480) + parser.add_argument("--input_height", type=int, default=None) + parser.add_argument("--input_width", type=int, default=None) + parser.add_argument("--num_frames", type=int, default=0, help="0 uses every LiveAct frame.") + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler") + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument("--adapter_blocks", default="all") + parser.add_argument("--adapter_dim", type=int, default=1536) + parser.add_argument("--adapter_heads", type=int, default=12) + parser.add_argument( + "--wavelet_value_mode", choices=["off", "highpass"], default="off", + help="Use the reference hidden state's reconstructed Haar detail bands as V.", + ) + parser.add_argument( + "--wavelet_energy_bias", type=float, default=0.0, + help="Strength of the normalized Haar-energy additive bias on reference-key logits.", + ) + parser.add_argument( + "--wavelet_energy_clip", type=float, default=3.0, + help="Clamp normalized wavelet energy before applying the attention-bias strength.", + ) + parser.add_argument( + "--attention_heatmap_dir", default=None, + help="Optional directory for exact QK-derived reference attention heatmaps.", + ) + parser.add_argument( + "--attention_heatmap_blocks", default="0,6,12,18,24,29", + help="Wan blocks to visualize when --attention_heatmap_dir is set.", + ) + parser.add_argument("--attention_query_stride", type=int, default=8) + parser.add_argument( + "--diagnostic_active_blocks", + default="all", + help="Inference-only ablation: use checkpoint adapters only at these Wan blocks.", + ) + parser.add_argument("--num_inference_steps", type=int, default=1) + parser.add_argument("--sampling_noise_scale", type=float, default=0.0) + parser.add_argument("--sigma_shift", type=float, default=1.0) + parser.add_argument("--cfg_scale", type=float, default=1.0) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--fps", type=int, default=None) + parser.add_argument("--device", default="cuda") + parser.add_argument("--rand_device", default="cpu") + parser.add_argument("--reference_resize_mode", choices=["crop", "resize"], default="resize") + parser.add_argument("--copy_audio", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + return parser.parse_args() + + +def main(): + args = parse_args() + source_path = pick_video(args.input_video).resolve() + source_w, source_h, source_frames, source_fps = probe_video(source_path) + args.num_frames = args.num_frames or source_frames + args.fps = args.fps or max(1, int(round(source_fps))) + args.input_height = args.input_height or source_h + args.input_width = args.input_width or source_w + args.checkpoint = args.bridge_checkpoint # build_pipeline uses infer_sr's name. + args.model_paths = args.model_paths or default_model_paths(args.base_model_dir) + + source_video, _ = read_video( + source_path, + args.input_height, + args.input_width, + args.num_frames, + ) + reference_image = fit_reference( + Image.open(args.reference_image), args.height, args.width, args.reference_resize_mode + ) + + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + stem = args.output_stem or source_path.stem + lr_output = output_dir / f"{stem}_liveact_lr.mp4" + bridge_output = output_dir / f"{stem}_bridge.mp4" + adapter_output = output_dir / f"{stem}_bridge_adapter.mp4" + if source_path != lr_output.resolve(): + shutil.copy2(source_path, lr_output) + + print( + f"[LiveActCascade] LR={source_path} {source_w}x{source_h} frames={args.num_frames}; " + f"target={args.width}x{args.height}" + ) + pipe = build_pipeline(args) + block_ids = parse_block_ids(args.adapter_blocks, len(pipe.dit.blocks)) + install_reference_adapters( + pipe.dit, + block_ids, + args.adapter_dim, + args.adapter_heads, + wavelet_value_mode=args.wavelet_value_mode, + wavelet_energy_bias=args.wavelet_energy_bias, + wavelet_energy_clip=args.wavelet_energy_clip, + ) + for block in reference_blocks(pipe.dit): + block.adapter.to(dtype=pipe.torch_dtype, device=pipe.device) + load_adapter_checkpoint(pipe.dit, args.adapter_checkpoint) + diagnostic_active = set(parse_block_ids( + args.diagnostic_active_blocks, len(pipe.dit.blocks) + )) + for block_id, block in enumerate(pipe.dit.blocks): + if hasattr(block, "adapter_active"): + block.adapter_active = block_id in diagnostic_active + attention_recorder = None + if args.attention_heatmap_dir: + attention_blocks = parse_block_ids(args.attention_heatmap_blocks, len(pipe.dit.blocks)) + attention_recorder = ReferenceAttentionRecorder( + attention_blocks, args.adapter_heads, args.attention_query_stride + ) + for block_id in attention_blocks: + adapter = pipe.dit.blocks[block_id].adapter + if adapter is None: + raise ValueError(f"Attention heatmap requested for block {block_id} without Adapter") + adapter.attention_probe = ( + lambda q, k, delta, grid, bias, block_id=block_id: + attention_recorder.capture(block_id, q, k, delta, grid, bias) + ) + pipe.eval().requires_grad_(False) + + prepared = prepare_inputs(pipe, source_video, args.prompt, args) + reference_latents = encode_reference(pipe, reference_image, args) + + print("[LiveActCascade] Running frozen Bridge...") + base_latents = predict_latents(pipe, prepared, args, reference_latents=None) + base_video = decode(pipe, base_latents, args) + save_with_optional_audio(base_video, bridge_output, source_path, args.fps, args.copy_audio) + del base_latents, base_video + + print("[LiveActCascade] Running Bridge + reference Adapter...") + adapter_latents = predict_latents(pipe, prepared, args, reference_latents=reference_latents) + adapter_video = decode(pipe, adapter_latents, args) + save_with_optional_audio(adapter_video, adapter_output, source_path, args.fps, args.copy_audio) + if attention_recorder is not None: + attention_recorder.save( + args.attention_heatmap_dir, adapter_video, reference_image, args.fps + ) + + metadata = { + "input_video": str(source_path), + "reference_image": str(Path(args.reference_image).resolve()), + "bridge_checkpoint": args.bridge_checkpoint, + "adapter_checkpoint": args.adapter_checkpoint, + "adapter_architecture": "framewise_target_q_reference_kv_rope2d_residual_zero_scale", + "wavelet_value_mode": args.wavelet_value_mode, + "wavelet_energy_bias": args.wavelet_energy_bias, + "wavelet_energy_clip": args.wavelet_energy_clip, + "diagnostic_active_blocks": sorted(diagnostic_active), + "prompt": args.prompt, + "input_size": [source_h, source_w], + "output_size": [args.height, args.width], + "num_frames": args.num_frames, + "fps": args.fps, + "outputs": { + "liveact_lr": str(lr_output), + "bridge": str(bridge_output), + "bridge_adapter": str(adapter_output), + }, + } + (output_dir / f"{stem}_pipeline.json").write_text( + json.dumps(metadata, indent=2, ensure_ascii=False), encoding="utf-8" + ) + print(f"[LiveActCascade] LR: {lr_output}") + print(f"[LiveActCascade] Bridge: {bridge_output}") + print(f"[LiveActCascade] Bridge+Adapter: {adapter_output}") + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py new file mode 100644 index 0000000000000000000000000000000000000000..be1e5932b253bd68eb8a728de295a341af623062 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py @@ -0,0 +1,245 @@ +"""Chunked Wan2.2-TI2V Brownian-bridge SR inference with clean history.""" + +from __future__ import annotations + +import argparse +import json +import random +import sys +from pathlib import Path + +import cv2 +import torch +from PIL import Image +from safetensors.torch import load_file + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.model_inference.compare_bridge_steps_firstframe_anchor import ( # noqa: E402 + fit_reference, + load_dit_checkpoint, + read_video, + save_with_optional_audio, + upscale_and_anchor_source, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + decode_latents_to_btchw_01, + tensor_btchw_01_to_pil, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v import ( # noqa: E402 + FirstFrameAnchorWanVideoSRBridgePipeline, + default_model_paths, + replace_first_latent_frame, +) +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 + + +def probe_video(path: Path) -> tuple[int, int, int, float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video: {path}") + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0) + cap.release() + return width, height, frames, fps + + +def reset_seed(seed: int) -> None: + random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + + +def build_pipeline(args): + model_paths = args.model_paths or default_model_paths(args.base_model_dir) + pipe = FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device=args.device, + model_configs=[ModelConfig(path=p) for p in model_paths.split(",")], + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_dit_checkpoint(pipe, args.checkpoint) + if not getattr(pipe.dit, "fuse_vae_embedding_in_latents", False): + raise RuntimeError("Checkpoint base DiT is not Wan2.2-TI2V fused-input compatible") + pipe.latent_upsampler = None + pipe.scheduler.noise_scale = args.sampling_noise_scale + pipe.scheduler.bridge_type = "brownian" + pipe.scheduler.target = args.target + pipe.eval().requires_grad_(False) + return pipe + + +@torch.no_grad() +def encode_reference(pipe, image: Image.Image, args): + pipe.load_models_to_device(["vae"]) + video = pipe.preprocess_video([image]) + anchor = pipe.vae.encode( + video, + device=pipe.device, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).to(device=pipe.device, dtype=pipe.torch_dtype) + if anchor.shape[2] != 1: + raise RuntimeError(f"Expected one reference latent frame, got {tuple(anchor.shape)}") + return anchor + + +@torch.no_grad() +def prepare(pipe, source_video, reference_image, args): + pipe.scheduler.set_timesteps(1000, training=True) + shared = { + "input_video": None, + "source_video": source_video, + "height": args.height, + "width": args.width, + "num_frames": args.num_frames, + "seed": args.seed, + "rand_device": args.rand_device, + "cfg_scale": args.cfg_scale, + "cfg_merge": False, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + "fuse_vae_embedding_in_latents": True, + } + positive = {"prompt": args.prompt} + negative = {"negative_prompt": args.negative_prompt} + for unit in pipe.units: + shared, positive, negative = pipe.unit_runner(unit, pipe, shared, positive, negative) + shared["first_frame_latents"] = encode_reference(pipe, reference_image, args) + shared["source_latents"] = replace_first_latent_frame( + shared["source_latents"], shared["first_frame_latents"] + ) + return shared, positive, negative + + +@torch.no_grad() +def sample_chunked(pipe, prepared, steps: int, args): + shared, positive, negative = prepared + anchor = shared["first_frame_latents"] + source_full = replace_first_latent_frame(shared["source_latents"], anchor) + total = source_full.shape[2] + generated = anchor.clone() + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + pipe.load_models_to_device(pipe.in_iteration_models) + + for current_start in range(1, total, args.chunk_latent_frames): + current_end = min(total, current_start + args.chunk_latent_frames) + history = generated[:, :, max(1, generated.shape[2] - args.history_latent_frames):].detach() + current_source = source_full[:, :, current_start:current_end] + chunk_source = torch.cat([anchor, history, current_source], dim=2) + latents = chunk_source.clone() + history_len = history.shape[2] + clean_prefix = torch.cat([anchor, history], dim=2) + + pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift) + model_inputs = dict(shared) + model_inputs.pop("latents", None) + model_inputs.pop("first_frame_latents", None) + model_inputs["fuse_vae_embedding_in_latents"] = True + model_inputs["clean_history_latent_frames"] = history_len + model_inputs["source_latents"] = chunk_source + + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype) + pred = pipe.model_fn( + **models, **model_inputs, **positive, latents=latents, timestep=timestep + ) + if args.cfg_scale != 1.0: + pred_negative = pipe.model_fn( + **models, **model_inputs, **negative, latents=latents, timestep=timestep + ) + pred = pred_negative + args.cfg_scale * (pred - pred_negative) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, chunk_source) + latents[:, :, :1 + history_len] = clean_prefix + + current = latents[:, :, 1 + history_len:].detach() + generated = torch.cat([generated, current], dim=2) + + return generated + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--input_video", required=True) + parser.add_argument("--reference_image", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl") + parser.add_argument("--prompt", default="a person is speaking") + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--input_height", type=int, default=None) + parser.add_argument("--input_width", type=int, default=None) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--chunk_latent_frames", type=int, default=4) + parser.add_argument("--history_latent_frames", type=int, default=2) + parser.add_argument("--steps", type=int, default=4) + parser.add_argument("--sigma_shift", type=float, default=5.0) + parser.add_argument("--sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--cfg_scale", type=float, default=1.0) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--device", default="cuda") + parser.add_argument("--rand_device", default="cpu") + parser.add_argument("--fps", type=int, default=None) + parser.add_argument("--tiled", action="store_true") + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + return parser.parse_args() + + +def main(): + args = parse_args() + if args.chunk_latent_frames < 1 or args.history_latent_frames < 0: + raise ValueError("chunk_latent_frames must be >=1 and history_latent_frames must be >=0") + reset_seed(args.seed) + source_path = Path(args.input_video).resolve() + source_w, source_h, frame_count, source_fps = probe_video(source_path) + args.num_frames = min(args.num_frames, frame_count) + args.fps = args.fps or max(1, int(round(source_fps))) + lr_video, _ = read_video( + source_path, + args.input_height or source_h, + args.input_width or source_w, + args.num_frames, + 0, + ) + reference = fit_reference(Image.open(args.reference_image), args.height, args.width, "resize") + source = upscale_and_anchor_source(lr_video, reference, args.height, args.width) + pipe = build_pipeline(args) + prepared = prepare(pipe, source, reference, args) + latents = sample_chunked(pipe, prepared, args.steps, args) + video = decode_latents_to_btchw_01( + pipe, latents, args.tiled, + (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w) + ).cpu() + output = Path(args.output).resolve() + save_with_optional_audio(video, output, source_path, args.fps, True) + output.with_suffix(".json").write_text(json.dumps({ + "input_video": str(source_path), + "reference_image": str(Path(args.reference_image).resolve()), + "checkpoint": args.checkpoint, + "chunk_latent_frames": args.chunk_latent_frames, + "history_latent_frames": args.history_latent_frames, + "clean_history": True, + "first_frame_anchor": True, + "steps": args.steps, + }, indent=2), encoding="utf-8") + print(f"[Wan22TI2VChunked] output={output}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.sh new file mode 100644 index 0000000000000000000000000000000000000000..770846265725a488ca31f80bda89c34cdb6cfb6a --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="false" + +: "${CHECKPOINT:?Set CHECKPOINT to the trained Wan2.2 bridge checkpoint}" +: "${INPUT_VIDEO:?Set INPUT_VIDEO to the LiveAct/LR video}" +: "${REFERENCE_IMAGE:?Set REFERENCE_IMAGE to the HR first-frame image}" +: "${OUTPUT:?Set OUTPUT to the output mp4 path}" + +"${PYTHON_BIN}" diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py \ + --checkpoint "${CHECKPOINT}" \ + --input_video "${INPUT_VIDEO}" \ + --reference_image "${REFERENCE_IMAGE}" \ + --output "${OUTPUT}" \ + --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \ + --tokenizer_path "${TOKENIZER_PATH:-/cache/Wan2.2-TI2V-5B/google/umt5-xxl}" \ + --prompt "${PROMPT:-a person is speaking}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --chunk_latent_frames "${CHUNK_LATENT_FRAMES:-4}" \ + --history_latent_frames "${HISTORY_LATENT_FRAMES:-2}" \ + --steps "${STEPS:-4}" \ + --sigma_shift "${SIGMA_SHIFT:-5.0}" \ + --sampling_noise_scale "${SAMPLING_NOISE_SCALE:-1.0}" \ + --seed "${SEED:-42}" \ + "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_edit.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..70c76a32195412360b186e4bd9831664b66d1e3a --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_edit.py @@ -0,0 +1,246 @@ +"""Run the Wan2.1 tiny-ditto edit bridge on a LiveAct video.""" + +from __future__ import annotations + +import argparse +import json +import random +import sys +from pathlib import Path + +import cv2 +import torch +from PIL import Image +from safetensors.torch import load_file +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + center_crop_resize, + decode_latents_to_btchw_01, + make_lr_source, + tensor_btchw_01_to_pil, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v_edit import ( # noqa: E402 + TinyDittoEditBridgePipeline, + default_model_paths, + normalize_wan_num_frames, + resize_latents_to_match, +) +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 + + +def load_checkpoint(pipe, path: str) -> None: + state = load_file(path, device="cpu") + candidates = [("raw", state)] + for prefix in ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit."): + if any(k.startswith(prefix) for k in state): + candidates.append((prefix, {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state.items()})) + errors = [] + for name, candidate in candidates: + try: + pipe.dit.load_state_dict(candidate, strict=True) + print(f"[EditInfer] loaded checkpoint strategy={name}", flush=True) + return + except Exception as exc: + errors.append(f"{name}: {str(exc).splitlines()[0]}") + raise RuntimeError("Could not load checkpoint:\n" + "\n".join(errors)) + + +def read_video(path: Path, height: int, width: int, frames: int) -> tuple[list[Image.Image], float]: + cap = cv2.VideoCapture(str(path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open {path}") + fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0) + out, last = [], None + while len(out) < frames: + ok, frame = cap.read() + if not ok: + if last is None: + break + frame = last + last = frame + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + out.append(center_crop_resize(Image.fromarray(frame), height, width)) + cap.release() + if not out: + raise RuntimeError(f"No frames decoded from {path}") + while len(out) < frames: + out.append(out[-1].copy()) + return out, fps + + +def make_comparison_video( + original: list[Image.Image], + bridge: list[Image.Image], +) -> list[Image.Image]: + frame_count = min(len(original), len(bridge)) + comparison = [] + for index in range(frame_count): + panels = [original[index].convert("RGB"), bridge[index].convert("RGB")] + width = panels[0].width + height = panels[0].height + canvas = Image.new("RGB", (width * 2, height)) + for column, panel in enumerate(panels): + canvas.paste(panel.resize((width, height)), (column * width, 0)) + comparison.append(canvas) + return comparison + + +def load_pipe(args): + paths = args.model_paths or default_model_paths(args.base_model_dir) + pipe = TinyDittoEditBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device=args.device, + model_configs=[ModelConfig(path=p) for p in paths.split(",")], + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_checkpoint(pipe, args.checkpoint) + pipe.requires_grad_(False).eval() + pipe.latent_upsampler = None + dit_in_dim = int(getattr(pipe.dit, "in_dim", 0)) + vae_z_dim = int(getattr(pipe.vae, "z_dim", 0)) + if dit_in_dim != 16 or vae_z_dim != 16: + raise RuntimeError( + "Expected Wan2.1-T2V-1.3B with a 16-channel DiT/VAE, " + f"got dit.in_dim={dit_in_dim}, vae.z_dim={vae_z_dim}" + ) + pipe.scheduler.noise_scale = args.sampling_noise_scale + pipe.scheduler.bridge_type = "brownian" + pipe.scheduler.target = args.target + return pipe + + +@torch.no_grad() +def prepare(pipe, reference_video, source_video, args): + pipe.scheduler.set_timesteps(1000, training=True) + shared = { + "input_video": reference_video, + "source_video": source_video, + "height": args.height, + "width": args.width, + "num_frames": len(source_video), + "cfg_scale": 1, + "cfg_merge": False, + "tiled": args.tiled, + "tile_size": (args.tile_h, args.tile_w), + "tile_stride": (args.tile_stride_h, args.tile_stride_w), + "rand_device": pipe.device, + "seed": args.seed, + "use_gradient_checkpointing": False, + "use_gradient_checkpointing_offload": False, + "fuse_vae_embedding_in_latents": False, + "token_prefix_clean_timestep": True, + "token_prefix_aligned_rope": True, + "token_prefix_block_self_attention": True, + } + pos = {"prompt": args.prompt} + neg = {"negative_prompt": args.negative_prompt} + for unit in pipe.units: + shared, pos, neg = pipe.unit_runner(unit, pipe, shared, pos, neg) + pipe.load_models_to_device(["vae"]) + original_video = pipe.preprocess_video(reference_video) + shared["original_latents"] = pipe.vae.encode( + original_video, + device=pipe.device, + tiled=args.tiled, + tile_size=(args.tile_h, args.tile_w), + tile_stride=(args.tile_stride_h, args.tile_stride_w), + ).to(dtype=pipe.torch_dtype, device=pipe.device) + shared["source_latents"] = resize_latents_to_match( + shared["source_latents"], shared["original_latents"] + ) + return shared, pos, neg + + +@torch.no_grad() +def sample(pipe, prepared, steps: int, args): + shared, pos, neg = prepared + pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift) + source = shared["source_latents"] + latents = source.clone() + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + pipe.load_models_to_device(pipe.in_iteration_models) + model_inputs = dict(shared) + model_inputs.pop("latents", None) + model_inputs["token_prefix_latents"] = shared["original_latents"].detach() + model_inputs["token_prefix_block_self_attention"] = True + model_inputs.pop("original_latents", None) + for timestep_cpu in tqdm( + pipe.scheduler.timesteps, + desc=f"Bridge denoise ({steps} steps)", + leave=False, + ): + timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype) + pred = pipe.model_fn(**models, **model_inputs, **pos, latents=latents, timestep=timestep) + if args.cfg_scale != 1: + neg_pred = pipe.model_fn(**models, **model_inputs, **neg, latents=latents, timestep=timestep) + pred = neg_pred + args.cfg_scale * (pred - neg_pred) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, source) + return latents + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--checkpoint", required=True) + p.add_argument("--input_video", required=True) + p.add_argument("--bridge_video", default=None, help="Optional coarse/edited video used as bridge source.") + p.add_argument("--target_video", default=None, help="Optional target video saved for comparison only.") + p.add_argument("--output_dir", required=True) + p.add_argument("--steps", default="1,2,4,8,20") + p.add_argument("--base_model_dir", default="/cache/Wan2.1-T2V-1.3B") + p.add_argument("--model_paths", default=None) + p.add_argument("--tokenizer_path", default="/cache/Wan2.1-T2V-1.3B/google/umt5-xxl") + p.add_argument("--height", type=int, default=480) + p.add_argument("--width", type=int, default=832) + p.add_argument("--num_frames", type=int, default=81) + p.add_argument("--sr_scale", type=int, default=4) + p.add_argument("--sigma_shift", type=float, default=5.0) + p.add_argument("--sampling_noise_scale", type=float, default=1.0) + p.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + p.add_argument("--cfg_scale", type=float, default=1.0) + p.add_argument("--prompt", default="") + p.add_argument("--negative_prompt", default="") + p.add_argument("--seed", type=int, default=42) + p.add_argument("--device", default="cuda") + p.add_argument("--tiled", action="store_true") + p.add_argument("--tile_h", type=int, default=30) + p.add_argument("--tile_w", type=int, default=52) + p.add_argument("--tile_stride_h", type=int, default=15) + p.add_argument("--tile_stride_w", type=int, default=26) + args = p.parse_args() + random.seed(args.seed) + torch.manual_seed(args.seed) + source_path = Path(args.input_video).resolve() + bridge_path = Path(args.bridge_video).resolve() if args.bridge_video else source_path + args.num_frames = normalize_wan_num_frames(args.num_frames) + reference_video, fps = read_video(source_path, args.height, args.width, args.num_frames) + bridge_video, bridge_fps = read_video(bridge_path, args.height, args.width, args.num_frames) + source_video = [make_lr_source(frame, args.height, args.width, args.sr_scale, upsample_to_hr=False) for frame in bridge_video] + pipe = load_pipe(args) + prepared = prepare(pipe, reference_video, source_video, args) + out = Path(args.output_dir) + out.mkdir(parents=True, exist_ok=True) + steps_list = [int(x) for x in args.steps.split(",") if x.strip()] + outputs = {} + for steps in steps_list: + print(f"[EditInfer] sampling steps={steps}", flush=True) + latents = sample(pipe, prepared, steps, args) + video = decode_latents_to_btchw_01(pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)).cpu() + generated_frames = tensor_btchw_01_to_pil(video[0]) + path = out / f"{source_path.stem}_edit_x{args.sr_scale}_steps_{steps:02d}.mp4" + save_video(generated_frames, str(path), fps=fps, quality=5) + outputs[str(steps)] = str(path) + comparison = make_comparison_video(reference_video, generated_frames) + comparison_path = out / f"{source_path.stem}_steps_{steps:02d}_comparison.mp4" + save_video(comparison, str(comparison_path), fps=fps, quality=5) + outputs[f"{steps}_comparison"] = str(comparison_path) + (out / f"{source_path.stem}_metadata.json").write_text(json.dumps({"checkpoint": args.checkpoint, "reference_video": str(source_path), "bridge_video": str(bridge_path), "target_video": args.target_video, "outputs": outputs, "steps": steps_list, "num_frames": args.num_frames, "fps": fps, "duration_seconds": args.num_frames / fps, "sampling_noise_scale": args.sampling_noise_scale}, indent=2), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_vibt.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_vibt.py new file mode 100644 index 0000000000000000000000000000000000000000..2731365622bf49c8036c98230135b405943dfd62 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_vibt.py @@ -0,0 +1,180 @@ +import argparse +import os +import random + +import pandas as pd +import torch +from safetensors.torch import load_file + +from diffsynth.data.video import VideoData, save_video +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline +from diffsynth.pipelines.wan_video_new import ModelConfig + + +def load_dit_checkpoint(pipe: WanVideoBridgePipeline, checkpoint: str): + """Load a full single-head DiT checkpoint saved by ViBT training.""" + state_dict = load_file(checkpoint, device="cpu") + prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.") + + candidates = [("raw", state_dict)] + for prefix in prefixes: + if any(k.startswith(prefix) for k in state_dict): + stripped = { + k[len(prefix):] if k.startswith(prefix) else k: v + for k, v in state_dict.items() + } + candidates.append((f"strip:{prefix}", stripped)) + + errors = [] + for name, candidate in candidates: + try: + pipe.dit.load_state_dict(candidate, strict=True) + print(f"[ViBT] Loaded checkpoint with strategy: {name}") + return + except Exception as exc: + errors.append((name, str(exc))) + + msg = "\n".join(f"{name}: {err}" for name, err in errors) + raise RuntimeError(f"Could not strictly load ViBT checkpoint:\n{msg}") + + +def build_pipeline(args): + model_configs = [ + ModelConfig( + model_id="Wan-AI/Wan2.1-T2V-1.3B", + origin_file_pattern="diffusion_pytorch_model*.safetensors", + offload_device="cpu", + ), + ModelConfig( + model_id="Wan-AI/Wan2.1-T2V-1.3B", + origin_file_pattern="models_t5_umt5-xxl-enc-bf16.pth", + offload_device="cpu", + ), + ModelConfig( + model_id="Wan-AI/Wan2.1-T2V-1.3B", + origin_file_pattern="Wan2.1_VAE.pth", + offload_device="cpu", + ), + ] + + pipe = WanVideoBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cuda", + model_configs=model_configs, + ) + load_dit_checkpoint(pipe, args.checkpoint) + + if args.bridge_type != "brownian" or args.bridge_path_type != "brownian": + raise ValueError("Final ViBT uses --bridge_type brownian --bridge_path_type brownian") + if args.target != "stabilized_drift": + print(f"[ViBT warning] final reported model used target=stabilized_drift, got {args.target}") + + pipe.scheduler.noise_scale = args.sampling_noise_scale + pipe.scheduler.bridge_type = args.bridge_type + pipe.scheduler.training_weight_type = "uniform" + pipe.scheduler.target = args.target + return pipe + + +def infer_one(pipe, source_path, prompt, output_path, args): + # BridgeScheduler.step() samples stochastic noise with torch.randn_like, + # so set the global RNG as well as passing the seed into the pipeline. + random.seed(args.seed) + torch.manual_seed(args.seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(args.seed) + + source_video = VideoData(source_path, height=args.height, width=args.width) + source_video.set_length(args.num_frames) + + video = pipe( + prompt=prompt, + negative_prompt=args.negative_prompt, + source_video=source_video, + seed=args.seed, + height=args.height, + width=args.width, + num_frames=args.num_frames, + cfg_scale=args.cfg_scale, + num_inference_steps=args.num_inference_steps, + sigma_shift=args.sigma_shift, + tiled=args.tiled, + ) + + os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) + save_video(video, output_path, fps=args.fps, quality=5) + print(f"[ViBT] Saved: {output_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Final single-head ViBT inference (Wan2.1-T2V-1.3B).") + parser.add_argument("--checkpoint", required=True) + + # Single-video mode. + parser.add_argument("--source_video", default=None) + parser.add_argument("--prompt", default=None) + parser.add_argument("--output", default=None) + + # Metadata/batch mode, compatible with the historical ViBT command. + parser.add_argument("--dataset_root", default=None) + parser.add_argument("--metadata", default=None) + parser.add_argument("--output_dir", default=None) + parser.add_argument("--num_samples", type=int, default=5) + parser.add_argument("--row_index", type=int, default=None) + parser.add_argument("--tag", default="vibt_strict") + + parser.add_argument("--negative_prompt", default="") + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + + # Final ViBT inference settings used in the experiment command. + parser.add_argument("--num_inference_steps", type=int, default=30) + parser.add_argument("--cfg_scale", type=float, default=2.0) + parser.add_argument("--sigma_shift", type=float, default=1.0) + parser.add_argument("--seed", type=int, default=8888) + parser.add_argument("--target", default="stabilized_drift", choices=["stabilized_drift", "drift", "x0"]) + parser.add_argument("--bridge_type", default="brownian") + parser.add_argument("--bridge_path_type", default="brownian") + parser.add_argument("--sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--fps", type=int, default=15) + parser.add_argument("--tiled", action="store_true", default=True) + parser.add_argument("--no_tiled", dest="tiled", action="store_false") + args = parser.parse_args() + + pipe = build_pipeline(args) + + if args.source_video is not None: + if args.prompt is None: + raise ValueError("--prompt is required in single-video mode") + output = args.output or f"outputs/{args.tag}.mp4" + infer_one(pipe, args.source_video, args.prompt, output, args) + return + + if args.metadata is None or args.dataset_root is None or args.output_dir is None: + raise ValueError( + "Use either single-video mode (--source_video --prompt [--output]) or " + "batch mode (--dataset_root --metadata --output_dir)." + ) + + df = pd.read_csv(args.metadata) + if args.row_index is not None: + indices = [int(args.row_index)] + else: + rng = random.Random(args.seed) + indices = rng.sample(range(len(df)), min(args.num_samples, len(df))) + + os.makedirs(args.output_dir, exist_ok=True) + for idx in indices: + row = df.iloc[idx] + source = str(row["source_video"]) + if not os.path.isabs(source): + source = os.path.join(args.dataset_root, source) + prompt = str(row["prompt"]) + output = os.path.join(args.output_dir, f"{args.tag}_row_{idx:05d}.mp4") + print(f"[ViBT] row={idx}\n source={source}\n prompt={prompt}") + infer_one(pipe, source, prompt, output, args) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/full/Wan2.1-T2V-1.3B.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/full/Wan2.1-T2V-1.3B.sh new file mode 100644 index 0000000000000000000000000000000000000000..619aa323554e658e7437389bb9264f3170945d80 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/full/Wan2.1-T2V-1.3B.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Final single-head ViBT training recipe used in the experiments. +# Replace dataset/output paths as needed. + +accelerate launch --num_processes 1 \ + diffsynth/bridge/wan_bridge/model_training/train.py \ + --dataset_base_path /path/to/Ditto-1M \ + --dataset_metadata_path /path/to/style_bridge_2000_random.csv \ + --data_file_keys "video,source_video" \ + --extra_inputs "source_video" \ + --height 480 \ + --width 832 \ + --num_frames 81 \ + --dataset_repeat 10 \ + --dataset_num_workers 2 \ + --model_id_with_origin_paths "Wan-AI/Wan2.1-T2V-1.3B:diffusion_pytorch_model.safetensors,Wan-AI/Wan2.1-T2V-1.3B:models_t5_umt5-xxl-enc-bf16.pth,Wan-AI/Wan2.1-T2V-1.3B:Wan2.1_VAE.pth" \ + --trainable_models "dit" \ + --learning_rate 1 \ + --weight_decay 0.01 \ + --d_coef 1.0 \ + --num_epochs 1 \ + --save_steps 1000 \ + --test_steps 1000 \ + --use_gradient_checkpointing \ + --max_timestep_boundary 0.9999 \ + --min_timestep_boundary 0.0001 \ + --noise_sigma 1.0 \ + --bridge_type brownian \ + --bridge_path_type brownian \ + --training_weight_type uniform \ + --target stabilized_drift \ + --remove_prefix_in_ckpt "pipe.dit." \ + --output_path /path/to/output/vibt diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/sobel_utils.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/sobel_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0bba52712ca0ac70a94a867fb5ee4357f888e1 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/sobel_utils.py @@ -0,0 +1,44 @@ +"""Shared Sobel operators for adapter training and visualization.""" + +import torch +import torch.nn.functional as F + + +def sobel_rgb_gradients(video_btchw_01: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Return normalized RGB Sobel gradients as [B*T, C, H, W].""" + video = video_btchw_01.reshape(-1, *video_btchw_01.shape[2:]).float() + channels = video.shape[1] + kernel_x = video.new_tensor([ + [-1.0, 0.0, 1.0], + [-2.0, 0.0, 2.0], + [-1.0, 0.0, 1.0], + ]).div(8.0).view(1, 1, 3, 3).repeat(channels, 1, 1, 1) + kernel_y = kernel_x.transpose(-1, -2).contiguous() + + video = F.pad(video, (1, 1, 1, 1), mode="reflect") + return ( + F.conv2d(video, kernel_x, groups=channels), + F.conv2d(video, kernel_y, groups=channels), + ) + + +def dilated_sobel_edge_mask( + gradient_x: torch.Tensor, + gradient_y: torch.Tensor, + dilation_radius: int = 2, + threshold_multiplier: float = 1.0, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Return magnitude, per-frame threshold, thin mask, and dilated mask.""" + magnitude = torch.sqrt(gradient_x.square() + gradient_y.square() + 1e-12).mean(dim=1, keepdim=True) + threshold = magnitude.mean(dim=(-2, -1), keepdim=True) * float(threshold_multiplier) + edge_mask = (magnitude >= threshold).to(gradient_x.dtype) + dilated_mask = edge_mask + radius = max(int(dilation_radius), 0) + if radius: + dilated_mask = F.max_pool2d( + edge_mask, + kernel_size=2 * radius + 1, + stride=1, + padding=radius, + ) + return magnitude, threshold, edge_mask, dilated_mask diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..01478e212c1de915bb7762286aa0c77fd5eeb406 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train.py @@ -0,0 +1,405 @@ +import torch, os +from diffsynth.trainers.utils import ( + DiffusionTrainingModule, + ModelLogger, + wan_parser, +) +from diffsynth.trainers.unified_dataset import UnifiedDataset +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import ( + WanVideoBridgePipeline, + WanVideoBridgeUnit_InputVideoEmbedder_FSR, +) +from accelerate import Accelerator +from tqdm import tqdm +from accelerate.utils import DistributedDataParallelKwargs +from torch.nn.parallel.distributed import DistributedDataParallel +from prodigyopt import Prodigy +from diffsynth.data.video import save_video, VideoData +import wandb +import copy +import random + +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +is_main_process = os.getenv("LOCAL_RANK", "0") == "0" + + +class WanBridgeTrainingModule(DiffusionTrainingModule): + def __init__( + self, + model_paths=None, + model_id_with_origin_paths=None, + trainable_models=None, + lora_base_model=None, + lora_target_modules="q,k,v,o,ffn.0,ffn.2", + lora_rank=32, + lora_checkpoint=None, + use_gradient_checkpointing=True, + use_gradient_checkpointing_offload=False, + extra_inputs=None, + max_timestep_boundary=1.0, + min_timestep_boundary=0.0, + image_drop_probability=0.0, + text_drop_probability=0.0, + ): + super().__init__() + # Load models + model_configs = self.parse_model_configs( + model_paths, model_id_with_origin_paths, enable_fp8_training=False + ) + self.pipe: WanVideoBridgePipeline = WanVideoBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, device="cpu", model_configs=model_configs + ) + + # Training mode + self.switch_pipe_to_training_mode( + self.pipe, + trainable_models, + lora_base_model, + lora_target_modules, + lora_rank, + lora_checkpoint=lora_checkpoint, + enable_fp8_training=False, + ) + + # Store other configs + self.use_gradient_checkpointing = use_gradient_checkpointing + self.use_gradient_checkpointing_offload = use_gradient_checkpointing_offload + self.extra_inputs = extra_inputs.split(",") if extra_inputs is not None else [] + self.max_timestep_boundary = max_timestep_boundary + self.min_timestep_boundary = min_timestep_boundary + self.image_drop_probability = image_drop_probability + self.text_drop_probability = text_drop_probability + + def forward_preprocess(self, data): + # CFG-sensitive parameters + inputs_posi = {"prompt": data["prompt"]} + if random.random() < self.text_drop_probability: + inputs_posi["prompt"] = " " + inputs_nega = {} + + # CFG-unsensitive parameters + inputs_shared = { + # Assume you are using this pipeline for inference, + # please fill in the input parameters. + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + # Please do not modify the following parameters + # unless you clearly know what this will cause. + "cfg_scale": 1, + "tiled": False, + "rand_device": self.pipe.device, + "use_gradient_checkpointing": self.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + "max_timestep_boundary": self.max_timestep_boundary, + "min_timestep_boundary": self.min_timestep_boundary, + } + + # Extra inputs + for extra_input in self.extra_inputs: + if extra_input == "input_image": + inputs_shared["input_image"] = data["video"][0] + elif extra_input == "end_image": + inputs_shared["end_image"] = data["video"][-1] + elif ( + extra_input == "reference_image" + or extra_input == "vace_reference_image" + ): + inputs_shared[extra_input] = data[extra_input][0] + else: + inputs_shared[extra_input] = data[extra_input] + + # Pipeline units will automatically process the input parameters. + for unit in self.pipe.units: + inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner( + unit, self.pipe, inputs_shared, inputs_posi, inputs_nega + ) + if random.random() < self.image_drop_probability: + inputs_shared["source_latents"] = torch.zeros_like( + inputs_shared["source_latents"] + ) + return {**inputs_shared, **inputs_posi} + + def forward(self, data, inputs=None): + if inputs is None: + inputs = self.forward_preprocess(data) + models = { + name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models + } + loss = self.pipe.training_loss(**models, **inputs) + return loss + + +class BridgeLogger(ModelLogger): + def __init__( + self, *args, test_video, test_prompt, ema_decay=0.95, log_fps=15, **kwargs + ): + super().__init__(*args, **kwargs) + self.ema_decay = ema_decay + self.ema_loss = None + self.test_video = test_video + self.test_prompt = test_prompt + self.log_fps = log_fps or 15 + self.wandb_init() + + def wandb_init(self): + if not is_main_process: + return + wandb.init(project="ViBT-Wan") + + def on_step_end( + self, accelerator, model, save_steps=None, test_steps=None, loss=None + ): + super().on_step_end(accelerator, model, save_steps) + if not accelerator.is_main_process: + return + # Log loss and ema_loss + if loss is not None: + if self.ema_loss is None: + self.ema_loss = loss + else: + self.ema_loss *= self.ema_decay + self.ema_loss += loss * (1 - self.ema_decay) + wandb.log({"loss": loss}, step=self.num_steps) + # Generate video samples + if test_steps is not None and self.num_steps % test_steps == 0: + self.generate_video(model) + + @torch.no_grad() + def generate_video(self, model): + if not is_main_process: + return + source_video = VideoData(self.test_video, height=480, width=832) + if isinstance(model, DistributedDataParallel): + pipe = model.module.pipe + else: + pipe = model.pipe + scheduler_backup = pipe.scheduler + new_scheduler = copy.deepcopy(scheduler_backup) + pipe.scheduler = new_scheduler + video = pipe( + prompt=self.test_prompt, + negative_prompt="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走", + seed=0, + tiled=True, + num_inference_steps=20, + source_video=source_video, + cfg_scale=2, + sigma_shift=5, + ) + pipe.scheduler = scheduler_backup + save_path = os.path.join(self.output_path, "generated_videos") + os.makedirs(save_path, exist_ok=True) + file_name = os.path.join(save_path, f"step-{self.num_steps}-video.mp4") + fps = self.log_fps or 15 + save_video(video, file_name, fps=fps, quality=5) + wandb_video = wandb.Video(file_name, fps=fps, format="mp4") + wandb.log({"generated_video": wandb_video}, step=self.num_steps) + + +def launch_prodigy_training_task( + dataset: torch.utils.data.Dataset, + model: DiffusionTrainingModule, + model_logger: ModelLogger, + learning_rate: float = 1e-5, + weight_decay: float = 1e-2, + num_workers: int = 8, + save_steps: int = None, + test_steps: int = None, + num_epochs: int = 1, + gradient_accumulation_steps: int = 1, + find_unused_parameters: bool = False, + args=None, +): + if args is not None: + learning_rate = args.learning_rate + weight_decay = args.weight_decay + num_workers = args.dataset_num_workers + save_steps = args.save_steps + test_steps = args.test_steps + num_epochs = args.num_epochs + d_coef = args.d_coef + gradient_accumulation_steps = args.gradient_accumulation_steps + find_unused_parameters = args.find_unused_parameters + + optimizer = Prodigy( + model.trainable_modules(), + lr=learning_rate, + weight_decay=weight_decay, + safeguard_warmup=True, + d_coef=d_coef, + ) + + dataloader = torch.utils.data.DataLoader( + dataset, shuffle=True, collate_fn=lambda x: x[0], num_workers=num_workers + ) + accelerator = Accelerator( + gradient_accumulation_steps=gradient_accumulation_steps, + kwargs_handlers=[ + DistributedDataParallelKwargs(find_unused_parameters=find_unused_parameters) + ], + ) + model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + + for epoch_id in range(num_epochs): + for data in tqdm(dataloader): + with accelerator.accumulate(model): + optimizer.zero_grad() + if dataset.load_from_cache: + loss = model({}, inputs=data) + else: + loss = model(data) + accelerator.backward(loss) + optimizer.step() + gathered_loss = accelerator.gather(loss.detach()) + gathered_loss = gathered_loss.mean().item() + model_logger.on_step_end( + accelerator, model, save_steps, test_steps, gathered_loss + ) + if save_steps is None: + model_logger.on_epoch_end(accelerator, model, epoch_id) + model_logger.on_training_end(accelerator, model, save_steps) + + +if __name__ == "__main__": + parser = wan_parser() + parser.add_argument( + "--test_steps", + type=int, + default=None, + help="Number of testing intervals. If None, testing will be done every epoch.", + ) + parser.add_argument( + "--d_coef", + type=float, + default=1.0, + help="d_coef for Prodigy optimizer.", + ) + parser.add_argument( + "--test_video", + type=str, + default="assets/test_video_l.mp4", + help="Path to the test video for logging.", + ) + parser.add_argument( + "--test_prompt", + type=str, + default="纪实摄影风格画面,一只活泼的小狗在绿茵茵的草地上迅速奔跑。小狗毛色棕黄,两只耳朵立起,神情专注而欢快。阳光洒在它身上,使得毛发看上去格外柔软而闪亮。背景是一片开阔的草地,偶尔点缀着几朵野花,远处隐约可见蓝天和几片白云。透视感鲜明,捕捉小狗奔跑时的动感和四周草地的生机。中景侧面移动视角。", + help="Prompt used for test video generation.", + ) + parser.add_argument( + "--noise_sigma", + type=float, + default=1.0, + help="Noise sigma for video generation.", + ) + parser.add_argument( + "--bridge_type", + type=str, + default="brownian", + help="ViBT bridge type. Final ViBT uses 'brownian'.", + ) + parser.add_argument( + "--bridge_path_type", + type=str, + default="brownian", + help="Compatibility flag for the released ViBT command. Must be 'brownian'.", + ) + parser.add_argument( + "--training_weight_type", + type=str, + default="uniform", + help="Training weight type, one of 'uniform', 'time', ...", + ) + parser.add_argument( + "--fsr_factor", + type=int, + default=1, + help="Whether to use FSR input embedder.", + ) + parser.add_argument( + "--target", + type=str, + default="stabilized_drift", + choices=["stabilized_drift", "drift", "x0"], + help="Prediction target. Final ViBT uses stabilized_drift to avoid small-t target explosion.", + ) + parser.add_argument( + "--image_drop_probability", + type=float, + default=0.0, + help="Dropout probability for the image condition.", + ) + parser.add_argument( + "--text_drop_probability", + type=float, + default=0.0, + help="Dropout probability for the text condition.", + ) + args = parser.parse_args() + dataset = UnifiedDataset( + base_path=args.dataset_base_path, + metadata_path=args.dataset_metadata_path, + repeat=args.dataset_repeat, + data_file_keys=args.data_file_keys.split(","), + main_data_operator=UnifiedDataset.default_video_operator( + base_path=args.dataset_base_path, + max_pixels=args.max_pixels, + height=args.height, + width=args.width, + height_division_factor=16, + width_division_factor=16, + num_frames=args.num_frames, + time_division_factor=4, + time_division_remainder=1, + ), + ) + model = WanBridgeTrainingModule( + model_paths=args.model_paths, + model_id_with_origin_paths=args.model_id_with_origin_paths, + trainable_models=args.trainable_models, + lora_base_model=args.lora_base_model, + lora_target_modules=args.lora_target_modules, + lora_rank=args.lora_rank, + lora_checkpoint=args.lora_checkpoint, + use_gradient_checkpointing_offload=args.use_gradient_checkpointing_offload, + extra_inputs=args.extra_inputs, + max_timestep_boundary=args.max_timestep_boundary, + min_timestep_boundary=args.min_timestep_boundary, + image_drop_probability=args.image_drop_probability, + text_drop_probability=args.text_drop_probability, + ) + if args.bridge_type != "brownian" or args.bridge_path_type != "brownian": + raise ValueError("Final ViBT uses --bridge_type brownian --bridge_path_type brownian") + model.pipe.scheduler.noise_scale = args.noise_sigma + model.pipe.scheduler.bridge_type = args.bridge_type + model.pipe.scheduler.training_weight_type = args.training_weight_type + model.pipe.scheduler.target = args.target + print("Scheduler noise scale:", model.pipe.scheduler.noise_scale) + print("Scheduler bridge type:", model.pipe.scheduler.bridge_type) + print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type) + print("Scheduler target:", model.pipe.scheduler.target) + if args.fsr_factor > 1: + fps = 15 * args.fsr_factor + target_frames = 80 * args.fsr_factor + 1 + processor = WanVideoBridgeUnit_InputVideoEmbedder_FSR( + target_frames=target_frames, + fsr_factor=args.fsr_factor, + ) + model.pipe.units = model.pipe.units[:-1] + [processor] + print("Using FSR input embedder.") + else: + fps = 15 + model_logger = BridgeLogger( + args.output_path, + remove_prefix_in_ckpt=args.remove_prefix_in_ckpt, + test_video=args.test_video, + test_prompt=args.test_prompt, + log_fps=fps, + ) + launch_prodigy_training_task(dataset, model, model_logger, args=args) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr.py new file mode 100644 index 0000000000000000000000000000000000000000..78b050b290a28931229d788de21d5ffc72e20efc --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr.py @@ -0,0 +1,929 @@ +import argparse +import copy +import csv +import json +import math +import os +import random +import sys +from pathlib import Path + +import imageio +import numpy as np +import torch +import torch.nn.functional as F +import torchvision.transforms.functional as TVF +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image +from safetensors.torch import load_file +from torch.nn.parallel.distributed import DistributedDataParallel +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline # noqa: E402 +from diffsynth.pipelines.wan_video_new import PipelineUnit # noqa: E402 +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 + + +def format_run_value(value: object) -> str: + text = f"{value:g}" if isinstance(value, float) else str(value) + return text.replace(".", "p").replace("-", "m").replace("/", "_") + + +def build_run_name(args) -> str: + upsampler = Path(args.latent_upsampler_ckpt).stem if args.source_mode == "upsampler" else "none" + parts = [ + "wan_sr", + f"x{args.sr_scale}", + f"{args.height}x{args.width}", + f"f{args.num_frames}", + args.source_mode, + f"up_{upsampler}", + f"lr{format_run_value(args.learning_rate)}", + f"noise{format_run_value(args.noise_sigma)}", + f"bridge{format_run_value(args.bridge_loss_weight)}", + f"lpips{format_run_value(args.lpips_weight)}", + f"ssim{format_run_value(args.ssim_weight)}", + f"wav{format_run_value(args.wavelet_hf_weight)}", + f"pix{format_run_value(args.pixel_loss_weight)}", + f"pcrop{args.pixel_loss_crop_size}", + f"plf{args.pixel_loss_latent_frames}", + f"seed{args.seed}", + ] + return "_".join(parts) + + +def center_crop_resize(image: Image.Image, height: int, width: int) -> Image.Image: + image_w, image_h = image.size + scale = max(width / image_w, height / image_h) + resized = TVF.resize( + image, + (round(image_h * scale), round(image_w * scale)), + interpolation=TVF.InterpolationMode.BICUBIC, + ) + return TVF.center_crop(resized, (height, width)) + + +def make_lr_source(image: Image.Image, height: int, width: int, scale: int, upsample_to_hr: bool) -> Image.Image: + lr_h = max(height // int(scale), 1) + lr_w = max(width // int(scale), 1) + lr = image.resize((lr_w, lr_h), Image.Resampling.BICUBIC) + if upsample_to_hr: + return lr.resize((width, height), Image.Resampling.BICUBIC) + return lr + + +def load_metadata_prompts(prompt_json: str | None, valid_stems: set[str], prompt_field: str) -> dict[str, str]: + if not prompt_json: + return {} + path = Path(prompt_json) + if not path.exists(): + raise FileNotFoundError(f"prompt metadata not found: {path}") + if path.suffix.lower() == ".jsonl": + items = [] + bad_lines = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + try: + items.append(json.loads(line)) + except json.JSONDecodeError: + bad_lines += 1 + if bad_lines: + print(f"[SRDataset] skipped {bad_lines} malformed metadata jsonl lines from {path}") + elif path.suffix.lower() == ".json": + data = json.loads(path.read_text(encoding="utf-8")) + items = data if isinstance(data, list) else [ + {"video": key, "prompt": value} for key, value in data.items() + ] if isinstance(data, dict) else [] + else: + with path.open("r", encoding="utf-8") as f: + items = list(csv.DictReader(f)) + + prompts = {} + for item in items: + if not isinstance(item, dict): + continue + video = item.get("video") or item.get("path") or item.get("file") or item.get("file_name") or item.get("id") + media = item.get("media") + if isinstance(media, dict): + video = media.get("v") or video + if not video: + continue + stem = Path(str(video)).stem + if stem not in valid_stems: + continue + prompt = str(item.get("prompt") or item.get("caption") or item.get("raw_p") or "") + i18n = item.get("i18n") + if prompt_field != "raw_p" and isinstance(i18n, dict): + if prompt_field in ("en", "zh"): + block = i18n.get(prompt_field) + if isinstance(block, dict): + prompt = str(block.get("p") or block.get("t") or prompt) + elif prompt_field in ("en_title", "zh_title"): + block = i18n.get(prompt_field.split("_", 1)[0]) + if isinstance(block, dict): + prompt = str(block.get("t") or block.get("p") or prompt) + if prompt: + prompts[stem] = prompt + return prompts + + +class SeedanceSRDataset(Dataset): + def __init__( + self, + video_dir: str, + prompt_json: str | None, + prompt_field: str, + default_prompt: str, + height: int, + width: int, + num_frames: int, + sr_scale: int, + source_mode: str = "upsampler", + repeat: int = 1, + limit_videos: int | None = None, + seed: int = 0, + ) -> None: + self.video_dir = Path(video_dir) + self.height = int(height) + self.width = int(width) + self.num_frames = int(num_frames) + self.sr_scale = int(sr_scale) + self.source_mode = source_mode + self.repeat = int(repeat) + self.default_prompt = default_prompt + self.rng = random.Random(seed) + self.videos = sorted( + p for p in self.video_dir.rglob("*") + if p.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".avi") + ) + if limit_videos is not None: + self.videos = self.videos[: int(limit_videos)] + if not self.videos: + raise FileNotFoundError(f"No videos found under {self.video_dir}") + self.prompts = load_metadata_prompts(prompt_json, {p.stem for p in self.videos}, prompt_field) + if prompt_json: + print(f"[SRDataset] matched {len(self.prompts)}/{len(self.videos)} prompts from {prompt_json}") + + def __len__(self) -> int: + return len(self.videos) * self.repeat + + def _read_frames(self, path: Path) -> list[Image.Image]: + reader = imageio.get_reader(str(path)) + try: + frame_count = int(reader.count_frames()) + except Exception: + frame_count = self.num_frames + max_start = max(frame_count - self.num_frames, 0) + start = self.rng.randint(0, max_start) if max_start > 0 else 0 + frames = [] + last = None + for frame_id in range(start, start + self.num_frames): + try: + array = reader.get_data(frame_id) + last = array + except Exception: + if last is None: + break + array = last + image = Image.fromarray(np.asarray(array)).convert("RGB") + frames.append(center_crop_resize(image, self.height, self.width)) + reader.close() + if not frames: + raise RuntimeError(f"No frames decoded from {path}") + while len(frames) < self.num_frames: + frames.append(frames[-1].copy()) + return frames + + def __getitem__(self, idx: int) -> dict: + path = self.videos[idx % len(self.videos)] + target_video = self._read_frames(path) + source_video = [ + make_lr_source(frame, self.height, self.width, self.sr_scale, upsample_to_hr=self.source_mode == "bicubic") + for frame in target_video + ] + return { + "video": target_video, + "source_video": source_video, + "prompt": self.prompts.get(path.stem, self.default_prompt), + "path": str(path), + } + + +def pil_video_to_tensor_01(video: list[Image.Image], device: torch.device) -> torch.Tensor: + frames = [torch.from_numpy(np.asarray(frame).copy()).float().div(255.0) for frame in video] + return torch.stack(frames, dim=0).permute(0, 3, 1, 2).to(device=device) + + +def tensor_btchw_01_to_pil(video: torch.Tensor) -> list[Image.Image]: + video = video.detach().float().clamp(0, 1).cpu() + frames = video.permute(0, 2, 3, 1).numpy() + return [Image.fromarray((frame * 255.0).round().astype("uint8")) for frame in frames] + + +def decode_latents_to_btchw_01(pipe: WanVideoBridgePipeline, latents: torch.Tensor, tiled: bool, tile_size, tile_stride) -> torch.Tensor: + vae_dtype = next(pipe.vae.parameters()).dtype + decoded = pipe.vae.decode( + latents.to(dtype=vae_dtype), + device=pipe.device, + tiled=tiled, + tile_size=tile_size, + tile_stride=tile_stride, + ) + return decoded.add(1.0).div(2.0).clamp(0, 1).permute(0, 2, 1, 3, 4).contiguous() + + +def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + if min_t <= 0: + return pred_btchw_01.new_tensor(0.0) + pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float() + target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float() + channels = pred.shape[1] + window_size = max(1, int(window_size)) + if window_size % 2 == 0: + window_size += 1 + padding = window_size // 2 + weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size) + + mu_x = F.conv2d(pred, weight, padding=padding, groups=channels) + mu_y = F.conv2d(target, weight, padding=padding, groups=channels) + mu_x_sq = mu_x.square() + mu_y_sq = mu_y.square() + mu_xy = mu_x * mu_y + + sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq + sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy + + c1 = 0.01 ** 2 + c2 = 0.03 ** 2 + ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / ( + (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8 + ) + return (1.0 - ssim.clamp(-1.0, 1.0)).mean() + + +def crop_latent_pair_for_pixel_losses( + pred_latents: torch.Tensor, + target_latents: torch.Tensor, + crop_size_pixels: int, + latent_frames: int, + vae_factor: int, + return_crop_info: bool = False, +): + _, _, t, h, w = pred_latents.shape + if latent_frames > 0 and t > latent_frames: + crop_t = int(latent_frames) + start_t = int(torch.randint(t - crop_t + 1, (1,), device=pred_latents.device).item()) + else: + crop_t = t + start_t = 0 + + if crop_size_pixels > 0: + crop_h = max(int(crop_size_pixels) // max(int(vae_factor), 1), 1) + crop_w = crop_h + crop_h = min(crop_h, h) + crop_w = min(crop_w, w) + start_h = int(torch.randint(h - crop_h + 1, (1,), device=pred_latents.device).item()) if h > crop_h else 0 + start_w = int(torch.randint(w - crop_w + 1, (1,), device=pred_latents.device).item()) if w > crop_w else 0 + else: + crop_h, crop_w = h, w + start_h, start_w = 0, 0 + + pred = pred_latents[:, :, start_t:start_t + crop_t, start_h:start_h + crop_h, start_w:start_w + crop_w] + target = target_latents[:, :, start_t:start_t + crop_t, start_h:start_h + crop_h, start_w:start_w + crop_w] + if return_crop_info: + return pred.contiguous(), target.contiguous(), { + "start_t": start_t, + "start_h": start_h, + "start_w": start_w, + "crop_t": crop_t, + "crop_h": crop_h, + "crop_w": crop_w, + "full_t": t, + "full_h": h, + "full_w": w, + } + return pred.contiguous(), target.contiguous() + + +def crop_original_rgb_for_latent_crop( + original_frames: list[Image.Image], + crop_info: dict, + decoded_crop: torch.Tensor, + device: torch.device, +) -> torch.Tensor: + """Map a decoded latent crop to the same region of the on-disk RGB clip.""" + device = decoded_crop.device if decoded_crop is not None else device + original = pil_video_to_tensor_01(original_frames, device).unsqueeze(0) + full_t, full_h, full_w = crop_info["full_t"], crop_info["full_h"], crop_info["full_w"] + if full_t > 1: + if (original.shape[1] - 1) % (full_t - 1): + raise ValueError(f"Cannot align RGB/latent time lengths {original.shape[1]} and {full_t}") + temporal_stride = (original.shape[1] - 1) // (full_t - 1) + else: + temporal_stride = 1 + if original.shape[-2] % full_h or original.shape[-1] % full_w: + raise ValueError(f"Cannot align RGB size {original.shape[-2:]} with latent grid {(full_h, full_w)}") + spatial_stride_h = original.shape[-2] // full_h + spatial_stride_w = original.shape[-1] // full_w + start_t = crop_info["start_t"] * temporal_stride + start_h = crop_info["start_h"] * spatial_stride_h + start_w = crop_info["start_w"] * spatial_stride_w + target = original[ + :, + start_t:start_t + decoded_crop.shape[1], + :, + start_h:start_h + decoded_crop.shape[-2], + start_w:start_w + decoded_crop.shape[-1], + ] + if target.shape != decoded_crop.shape: + raise ValueError( + f"Aligned original crop shape {tuple(target.shape)} != decoded prediction {tuple(decoded_crop.shape)}" + ) + return target.to(device=decoded_crop.device, dtype=decoded_crop.dtype) + + +def random_spatial_crop_pair(pred: torch.Tensor, target: torch.Tensor, crop_size: int) -> tuple[torch.Tensor, torch.Tensor]: + if crop_size <= 0: + return pred, target + h, w = pred.shape[-2:] + crop_h = min(int(crop_size), h) + crop_w = min(int(crop_size), w) + if crop_h == h and crop_w == w: + return pred, target + top = torch.randint(h - crop_h + 1, (1,), device=pred.device).item() if h > crop_h else 0 + left = torch.randint(w - crop_w + 1, (1,), device=pred.device).item() if w > crop_w else 0 + return pred[..., top:top + crop_h, left:left + crop_w], target[..., top:top + crop_h, left:left + crop_w] + + +def lpips_video_loss(lpips_model, pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, num_frames: int, crop_size: int) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + pred = pred_btchw_01[:, :min_t] + target = target_btchw_01[:, :min_t] + pred, target = random_spatial_crop_pair(pred, target, crop_size) + if num_frames > 0 and pred.shape[1] > num_frames: + frame_idx = torch.linspace(0, pred.shape[1] - 1, steps=num_frames, device=pred.device).round().long() + pred = pred.index_select(1, frame_idx) + target = target.index_select(1, frame_idx) + pred_frames = pred.reshape(-1, pred.shape[2], pred.shape[3], pred.shape[4]).mul(2).sub(1).clamp(-1, 1) + target_frames = target.reshape(-1, target.shape[2], target.shape[3], target.shape[4]).mul(2).sub(1).clamp(-1, 1) + return lpips_model(pred_frames.float(), target_frames.float()).mean() + + +def haar_highfreq_bands(video_btchw_01: torch.Tensor, levels: int) -> list[torch.Tensor]: + x = video_btchw_01.reshape(-1, video_btchw_01.shape[2], video_btchw_01.shape[3], video_btchw_01.shape[4]).float() + bands = [] + for _ in range(max(int(levels), 1)): + h_even = x.shape[-2] - (x.shape[-2] % 2) + w_even = x.shape[-1] - (x.shape[-1] % 2) + if h_even < 2 or w_even < 2: + break + x = x[..., :h_even, :w_even] + a = x[..., 0::2, 0::2] + b = x[..., 0::2, 1::2] + c = x[..., 1::2, 0::2] + d = x[..., 1::2, 1::2] + ll = (a + b + c + d) * 0.5 + lh = (a - b + c - d) * 0.5 + hl = (a + b - c - d) * 0.5 + hh = (a - b - c + d) * 0.5 + bands.extend([lh, hl, hh]) + x = ll + return bands + + +def wavelet_hf_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, levels: int, loss_type: str) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + pred_bands = haar_highfreq_bands(pred_btchw_01[:, :min_t], levels) + target_bands = haar_highfreq_bands(target_btchw_01[:, :min_t], levels) + if not pred_bands: + return pred_btchw_01.new_tensor(0.0) + losses = [] + for pred_band, target_band in zip(pred_bands, target_bands): + if loss_type == "l2": + losses.append(F.mse_loss(pred_band, target_band)) + else: + losses.append(F.l1_loss(pred_band, target_band)) + return torch.stack(losses).mean() + + +class WanVideoSRBridgePipeline(WanVideoBridgePipeline): + def training_loss(self, **inputs): + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps) + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + + x0 = inputs["input_latents"] + x1 = inputs["source_latents"] + noise = inputs["noise"] + xt = self.scheduler.add_noise(x0, x1, noise, timestep) + inputs["latents"] = xt + + target = self.scheduler.training_target(x0, xt, timestep) + model_output = self.model_fn(**inputs, timestep=timestep) + + if self.scheduler.target == "stabilized_drift": + sigma = self.scheduler.get_sigma(timestep) + factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5 + velocity_target = target / factor + velocity_for_endpoint = model_output * factor + elif self.scheduler.target == "drift": + velocity_target = target + velocity_for_endpoint = model_output + else: + raise ValueError("SR bridge training supports --target stabilized_drift or drift") + + bridge_loss = F.mse_loss(model_output.float(), velocity_target.float()) + total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss + metrics = { + "bridge_loss": float(bridge_loss.detach().cpu()), + "lpips_loss": 0.0, + "ssim_loss": 0.0, + "wavelet_hf_loss": 0.0, + "pixel_loss": 0.0, + } + + lpips_model = inputs.get("lpips_model") + lpips_weight = float(inputs.get("lpips_weight", 0.0)) + ssim_weight = float(inputs.get("ssim_weight", 0.0)) + wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0)) + pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0)) + if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0: + sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + endpoint_pred = xt.float() - sigma * velocity_for_endpoint.float() + endpoint_pred, target_latents_for_pixel, crop_info = crop_latent_pair_for_pixel_losses( + endpoint_pred, + x0.detach(), + crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 256)), + latent_frames=int(inputs.get("pixel_loss_latent_frames", 3)), + vae_factor=int(getattr(self.vae, "upsampling_factor", 8)), + return_crop_info=True, + ) + pred_video = decode_latents_to_btchw_01( + self, + endpoint_pred, + tiled=bool(inputs.get("tiled", False)), + tile_size=inputs.get("tile_size", (30, 52)), + tile_stride=inputs.get("tile_stride", (15, 26)), + ) + raw_target_video = inputs.get("raw_target_video") + if raw_target_video is None: + raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses") + target_video = crop_original_rgb_for_latent_crop( + raw_target_video, crop_info, pred_video, self.device + ) + if lpips_weight > 0: + if lpips_model is None: + raise ValueError("lpips_model is required when lpips_weight > 0") + loss = lpips_video_loss( + lpips_model, + pred_video, + target_video, + num_frames=int(inputs.get("lpips_num_frames", 4)), + crop_size=int(inputs.get("lpips_crop_size", 224)), + ) + total_loss = total_loss + lpips_weight * loss + metrics["lpips_loss"] = float(loss.detach().cpu()) + if ssim_weight > 0: + loss = ssim_video_loss( + pred_video, + target_video, + window_size=int(inputs.get("ssim_window_size", 11)), + ) + total_loss = total_loss + ssim_weight * loss + metrics["ssim_loss"] = float(loss.detach().cpu()) + if wavelet_hf_weight > 0: + loss = wavelet_hf_loss( + pred_video, + target_video, + levels=int(inputs.get("wavelet_hf_levels", 1)), + loss_type=str(inputs.get("wavelet_hf_loss", "l1")), + ) + total_loss = total_loss + wavelet_hf_weight * loss + metrics["wavelet_hf_loss"] = float(loss.detach().cpu()) + if pixel_loss_weight > 0: + loss = F.mse_loss(pred_video.float(), target_video.float()) + total_loss = total_loss + pixel_loss_weight * loss + metrics["pixel_loss"] = float(loss.detach().cpu()) + + return total_loss, metrics + + +class WanVideoSRUnit_UltraFlashLatentUpsampler(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("source_video", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae", "latent_upsampler"), + ) + + def process(self, pipe: WanVideoBridgePipeline, source_video, tiled, tile_size, tile_stride): + pipe.load_models_to_device(["vae", "latent_upsampler"]) + source_video = pipe.preprocess_video(source_video) + lr_latents = pipe.vae.encode( + source_video, + device=pipe.device, + tiled=tiled, + tile_size=tile_size, + tile_stride=tile_stride, + ).to(dtype=next(pipe.latent_upsampler.parameters()).dtype, device=pipe.device) + source_latents, _ = pipe.latent_upsampler( + lr_latents, + parallel=True, + caches=None, + return_caches=True, + detach_caches=True, + ) + return {"source_latents": source_latents.to(dtype=pipe.torch_dtype, device=pipe.device)} + + +def load_ultraflash_latent_upsampler(args, device: str | torch.device): + ultraflash_dir = Path(args.ultraflash_dir).resolve() + if str(ultraflash_dir) not in sys.path: + sys.path.insert(0, str(ultraflash_dir)) + from sr.config import load_config_class_from_pyfile + from sr.load_utils import load_latent_upsampler + + cfg = load_config_class_from_pyfile(str(Path(args.ultraflash_sr_config).resolve()))() + cfg.latent_upsampler_ckpt = args.latent_upsampler_ckpt + cfg.latent_upsampler_precision = args.upsampler_dtype + cfg.latent_upsampler_arch_config["params"]["upsample_scale"] = int(args.sr_scale) + upsampler = load_latent_upsampler(cfg, torch.device(device)) + upsampler.eval().requires_grad_(False) + return upsampler + + +class WanSRTrainingModule(DiffusionTrainingModule): + def __init__(self, args): + super().__init__() + model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cpu", + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + if args.source_mode == "upsampler": + self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu") + self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()] + print(f"[SRBridge] source_mode=upsampler ckpt={args.latent_upsampler_ckpt}") + else: + self.pipe.latent_upsampler = None + print("[SRBridge] source_mode=bicubic") + self.switch_pipe_to_training_mode( + self.pipe, + args.trainable_models, + args.lora_base_model, + args.lora_target_modules, + args.lora_rank, + lora_checkpoint=args.lora_checkpoint, + enable_fp8_training=False, + ) + self.args = args + self.extra_loss_inputs = {} + if args.lpips_weight > 0 or args.val_lpips: + import lpips + + self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False) + else: + self.lpips_model = None + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + if self.lpips_model is not None: + self.lpips_model.to(*args, **kwargs) + return self + + def forward_preprocess(self, data): + prompt = data["prompt"] + if random.random() < self.args.text_drop_probability: + prompt = " " + inputs_posi = {"prompt": prompt} + inputs_nega = {} + inputs_shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + "cfg_scale": 1, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + "max_timestep_boundary": self.args.max_timestep_boundary, + "min_timestep_boundary": self.args.min_timestep_boundary, + "bridge_loss_weight": self.args.bridge_loss_weight, + "lpips_weight": self.args.lpips_weight, + "lpips_model": self.lpips_model, + "lpips_num_frames": self.args.lpips_num_frames, + "lpips_crop_size": self.args.lpips_crop_size, + "ssim_weight": self.args.ssim_weight, + "ssim_window_size": self.args.ssim_window_size, + "pixel_loss_crop_size": self.args.pixel_loss_crop_size, + "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames, + "wavelet_hf_weight": self.args.wavelet_hf_weight, + "wavelet_hf_levels": self.args.wavelet_hf_levels, + "wavelet_hf_loss": self.args.wavelet_hf_loss, + "pixel_loss_weight": self.args.pixel_loss_weight, + } + for unit in self.pipe.units: + inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner( + unit, self.pipe, inputs_shared, inputs_posi, inputs_nega + ) + # Keep the preprocessed frames loaded from disk as the direct RGB loss target. + inputs_shared["raw_target_video"] = data["video"] + return {**inputs_shared, **inputs_posi} + + def forward(self, data, inputs=None): + if inputs is None: + inputs = self.forward_preprocess(data) + return self.pipe.training_loss(**{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}, **inputs) + + +class SRModelLogger(ModelLogger): + def on_step_end(self, accelerator, model, save_steps=None): + super().on_step_end(accelerator, model, save_steps) + + +@torch.no_grad() +def validate(args, accelerator: Accelerator, model: WanSRTrainingModule, dataset: Dataset, step: int) -> dict: + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + pipe.eval() + backup_scheduler = pipe.scheduler + pipe.scheduler = copy.deepcopy(backup_scheduler) + pipe.scheduler.noise_scale = args.val_sampling_noise_scale + pipe.scheduler.target = args.target + + rows = [] + out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}" + out_dir.mkdir(parents=True, exist_ok=True) + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + pipe.scheduler.set_timesteps(1000, training=True) + inputs = module.forward_preprocess(data) + pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift) + x0 = inputs["input_latents"] + x1 = inputs["source_latents"] + latents = x1.clone() + pipe.load_models_to_device(pipe.in_iteration_models) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, x1) + + pred_video = decode_latents_to_btchw_01(pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + target_video = decode_latents_to_btchw_01(pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0) + target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0) + if source_tensor.shape[-2:] != target_tensor.shape[-2:]: + b, t, c, h, w = source_tensor.shape + source_tensor = F.interpolate( + source_tensor.reshape(b * t, c, h, w), + size=target_tensor.shape[-2:], + mode="bicubic", + align_corners=False, + antialias=True, + ).reshape(b, t, c, target_tensor.shape[-2], target_tensor.shape[-1]).clamp(0, 1) + min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1]) + strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1) + save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(strip[0]), str(out_dir / f"val_{idx:03d}_source_pred_target.mp4"), fps=args.fps, quality=5) + mse = F.mse_loss(pred_video.float(), target_video.float()).item() + row = {"idx": idx, "latent_mse": F.mse_loss(latents.float(), x0.float()).item(), "pixel_mse": mse} + if module.lpips_model is not None and args.val_lpips: + row["lpips"] = float(lpips_video_loss(module.lpips_model, pred_video, target_video, args.lpips_num_frames, args.lpips_crop_size).detach().cpu()) + if args.val_wavelet_hf_loss: + row["wavelet_hf"] = float(wavelet_hf_loss(pred_video, target_video, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu()) + if args.val_ssim or args.ssim_weight > 0: + row["ssim"] = float(ssim_video_loss(pred_video, target_video, args.ssim_window_size).detach().cpu()) + rows.append(row) + + pipe.scheduler = backup_scheduler + metrics = {} + if rows: + for key in rows[0]: + if key != "idx": + metrics[f"val_{key}"] = float(sum(row[key] for row in rows if key in row) / max(sum(1 for row in rows if key in row), 1)) + (out_dir / "metrics.json").write_text(json.dumps({"step": step, "rows": rows, "metrics": metrics}, indent=2), encoding="utf-8") + print(f"[Validation step {step}] {metrics}") + pipe.train() + return metrics + + +def train(args): + save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None + if args.output_path is None: + args.output_path = str(Path(args.output_root) / build_run_name(args)) + train_set = SeedanceSRDataset( + args.video_dir, + args.prompt_json, + args.prompt_field, + args.default_prompt, + args.height, + args.width, + args.num_frames, + args.sr_scale, + source_mode=args.source_mode, + repeat=args.dataset_repeat, + limit_videos=args.limit_videos, + seed=args.seed, + ) + val_set = SeedanceSRDataset( + args.video_dir, + args.prompt_json, + args.prompt_field, + args.default_prompt, + args.height, + args.width, + args.num_frames, + args.sr_scale, + source_mode=args.source_mode, + repeat=1, + limit_videos=max(args.val_batches, 1), + seed=args.seed + 1, + ) + model = WanSRTrainingModule(args) + model.pipe.scheduler.noise_scale = args.noise_sigma + model.pipe.scheduler.bridge_type = "brownian" + model.pipe.scheduler.training_weight_type = args.training_weight_type + model.pipe.scheduler.target = args.target + print("Scheduler noise scale:", model.pipe.scheduler.noise_scale) + print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type) + print("Scheduler target:", model.pipe.scheduler.target) + + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + print(f"[Output] {args.output_path}") + + if args.validation_only or args.max_train_steps <= 0: + model = accelerator.prepare(model) + validate(args, accelerator, model, val_set, 0) + return + + from prodigyopt import Prodigy + + optimizer = Prodigy( + model.trainable_modules(), + lr=args.learning_rate, + weight_decay=args.weight_decay, + safeguard_warmup=True, + d_coef=args.d_coef, + ) + dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers) + model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + logger = SRModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt) + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + + global_step = 0 + while global_step < args.max_train_steps: + for data in tqdm(dataloader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad() + loss, metrics = model(data) + accelerator.backward(loss) + if args.max_grad_norm > 0: + accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step() + global_step += 1 + gathered_loss = accelerator.gather(loss.detach()).mean().item() + if accelerator.is_main_process and global_step % args.log_interval == 0: + print( + f"[Train step {global_step}] loss={gathered_loss:.6f} " + f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} " + f"ssim={metrics['ssim_loss']:.6f} " + f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}" + ) + logger.on_step_end(accelerator, model, save_steps) + if args.val_interval > 0 and global_step % args.val_interval == 0: + validate(args, accelerator, model, val_set, global_step) + if global_step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, save_steps) + + +def default_model_paths(base_model_dir: str) -> str: + base = Path(base_model_dir) + paths = [ + base / "diffusion_pytorch_model.safetensors", + base / "models_t5_umt5-xxl-enc-bf16.pth", + base / "Wan2.1_VAE.pth", + ] + for path in paths: + if not path.exists(): + raise FileNotFoundError(f"Missing Wan model file: {path}") + return ",".join(str(path) for path in paths) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Train a Wan2.1 Brownian-Bridge super-resolution DiT with native Wan VAE.") + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p") + parser.add_argument("--default_prompt", default="") + parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr") + parser.add_argument("--output_path", default=None) + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler") + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--limit_videos", type=int, default=None) + parser.add_argument("--dataset_repeat", type=int, default=1) + parser.add_argument("--dataset_num_workers", type=int, default=0) + parser.add_argument("--trainable_models", default="dit") + parser.add_argument("--lora_base_model", default=None) + parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2") + parser.add_argument("--lora_rank", type=int, default=32) + parser.add_argument("--lora_checkpoint", default=None) + parser.add_argument("--learning_rate", type=float, default=1.0) + parser.add_argument("--weight_decay", type=float, default=0.01) + parser.add_argument("--d_coef", type=float, default=1.0) + parser.add_argument("--max_train_steps", type=int, default=5000) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--max_grad_norm", type=float, default=1.0) + parser.add_argument("--save_steps", type=int, default=500) + parser.add_argument("--log_interval", type=int, default=1) + parser.add_argument("--val_interval", type=int, default=100) + parser.add_argument("--val_batches", type=int, default=1) + parser.add_argument("--validate_at_start", action="store_true", default=False) + parser.add_argument("--validation_only", action="store_true", default=False) + parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.") + parser.add_argument("--noise_sigma", type=float, default=1.0) + parser.add_argument("--training_weight_type", default="uniform") + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--bridge_loss_weight", type=float, default=1.0) + parser.add_argument("--lpips_weight", type=float, default=0.2) + parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg") + parser.add_argument("--lpips_num_frames", type=int, default=4) + parser.add_argument("--lpips_crop_size", type=int, default=224) + parser.add_argument("--ssim_weight", type=float, default=0.0) + parser.add_argument("--ssim_window_size", type=int, default=11) + parser.add_argument("--val_ssim", action="store_true", default=False) + parser.add_argument("--pixel_loss_crop_size", type=int, default=256, help="Decode only this pixel-sized latent crop for LPIPS/wavelet/pixel losses; <=0 decodes full spatial latent.") + parser.add_argument("--pixel_loss_latent_frames", type=int, default=3, help="Decode only this many latent frames for pixel-space losses; <=0 decodes all latent frames.") + parser.add_argument("--val_lpips", action="store_true", default=False) + parser.add_argument("--wavelet_hf_weight", type=float, default=0.1) + parser.add_argument("--wavelet_hf_levels", type=int, default=1) + parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1") + parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False) + parser.add_argument("--pixel_loss_weight", type=float, default=0.0) + parser.add_argument("--val_inference_steps", type=int, default=8) + parser.add_argument("--val_sampling_noise_scale", type=float, default=0.0) + parser.add_argument("--val_sigma_shift", type=float, default=1.0) + parser.add_argument("--max_timestep_boundary", type=float, default=0.9999) + parser.add_argument("--min_timestep_boundary", type=float, default=0.0001) + parser.add_argument("--text_drop_probability", type=float, default=0.0) + parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True) + parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False) + parser.add_argument("--find_unused_parameters", action="store_true", default=False) + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + if args.model_paths is None: + args.model_paths = default_model_paths(args.base_model_dir) + return args + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4b9928b76ba58942abe210a06b14003c6eec054 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +ARGS=( + diffsynth/bridge/wan_bridge/model_training/train_sr.py + --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" \ + --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --num_frames "${NUM_FRAMES:-81}" \ + --sr_scale "${SR_SCALE:-2}" \ + --source_mode "${SOURCE_MODE:-upsampler}" \ + --ultraflash_dir "${ULTRAFLASH_DIR:-/home/ma-user/workspace/rongxiang/UltraFlash/inference}" \ + --ultraflash_sr_config "${ULTRAFLASH_SR_CONFIG:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py}" \ + --latent_upsampler_ckpt "${LATENT_UPSAMPLER_CKPT:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth}" \ + --upsampler_dtype "${UPSAMPLER_DTYPE:-bf16}" \ + --dataset_repeat "${DATASET_REPEAT:-1}" \ + --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \ + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --learning_rate "${LEARNING_RATE:-1.0}" \ + --weight_decay "${WEIGHT_DECAY:-0.01}" \ + --d_coef "${D_COEF:-1.0}" \ + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \ + --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --lpips_net "${LPIPS_NET:-vgg}" \ + --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \ + --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \ + --ssim_weight "${SSIM_WEIGHT:-1.0}" \ + --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \ + --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \ + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \ + --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-50.0}" \ + --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \ + --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \ + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-8}" \ + --noise_sigma "${NOISE_SIGMA:-1.0}" \ + --val_interval "${VAL_INTERVAL:-100}" \ + --val_batches "${VAL_BATCHES:-1}" \ + --val_inference_steps "${VAL_INFERENCE_STEPS:-1}" \ + --save_steps "${SAVE_STEPS:-500}" \ + --validate_at_start +) + +if [[ -n "${LIMIT_VIDEOS:-}" ]]; then + ARGS+=(--limit_videos "${LIMIT_VIDEOS}") +fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then + ARGS+=(--output_path "${OUTPUT_PATH}") +fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor.sh new file mode 100644 index 0000000000000000000000000000000000000000..3b4d2676996367c2e418fbbbb611c0ec5ad2ef9e --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +ARGS=( + diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py + --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" \ + --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + --output_root "${OUTPUT_ROOT:-/cache/outputs2_bridge_wan_srfirst}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --num_frames "${NUM_FRAMES:-81}" \ + --sr_scale "${SR_SCALE:-2}" \ + --dataset_repeat "${DATASET_REPEAT:-1}" \ + --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \ + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --learning_rate "${LEARNING_RATE:-1.0}" \ + --weight_decay "${WEIGHT_DECAY:-0.01}" \ + --d_coef "${D_COEF:-1.0}" \ + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \ + --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --lpips_net "${LPIPS_NET:-vgg}" \ + --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \ + --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \ + --ssim_weight "${SSIM_WEIGHT:-1.0}" \ + --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \ + --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \ + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \ + --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-0.0}" \ + --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \ + --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \ + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-2}" \ + --noise_sigma "${NOISE_SIGMA:-1.0}" \ + --val_interval "${VAL_INTERVAL:-100}" \ + --val_batches "${VAL_BATCHES:-1}" \ + --val_inference_steps "${VAL_INFERENCE_STEPS:-10}" \ + --save_steps "${SAVE_STEPS:-500}" \ + --validate_at_start \ + --no-anchor_each_step +) + +if [[ -n "${LIMIT_VIDEOS:-}" ]]; then + ARGS+=(--limit_videos "${LIMIT_VIDEOS}") +fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then + ARGS+=(--output_path "${OUTPUT_PATH}") +fi +if [[ "${ANCHOR_EACH_STEP:-1}" == "0" || "${ANCHOR_EACH_STEP:-1}" == "false" ]]; then + ARGS+=(--no-anchor_each_step) +else + ARGS+=(--anchor_each_step) +fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor_flashvsr.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor_flashvsr.sh new file mode 100644 index 0000000000000000000000000000000000000000..7cef305eb08b62066f8f6893c0afb01a8289a714 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor_flashvsr.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +FLASHVSR_DIT="${FLASHVSR_DIT:-/cache/FlashVSR-v1.1/diffusion_pytorch_model_streaming_dmd.safetensors}" +WAN_MODEL_DIR="${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" +MODEL_PATHS_DEFAULT="${FLASHVSR_DIT},${WAN_MODEL_DIR}/models_t5_umt5-xxl-enc-bf16.pth,${WAN_MODEL_DIR}/Wan2.1_VAE.pth" + +ARGS=( + diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py + --base_model_dir "${WAN_MODEL_DIR}" \ + --model_paths "${MODEL_PATHS:-${MODEL_PATHS_DEFAULT}}" \ + --tokenizer_path "${TOKENIZER_PATH:-${WAN_MODEL_DIR}/google/umt5-xxl}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_flashvsr_ffanchor}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --num_frames "${NUM_FRAMES:-81}" \ + --sr_scale "${SR_SCALE:-2}" \ + --dataset_repeat "${DATASET_REPEAT:-1}" \ + --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \ + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --learning_rate "${LEARNING_RATE:-1.0}" \ + --weight_decay "${WEIGHT_DECAY:-0.01}" \ + --d_coef "${D_COEF:-1.0}" \ + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \ + --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --lpips_net "${LPIPS_NET:-vgg}" \ + --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \ + --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \ + --ssim_weight "${SSIM_WEIGHT:-1.0}" \ + --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \ + --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \ + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \ + --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-50.0}" \ + --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \ + --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \ + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-8}" \ + --noise_sigma "${NOISE_SIGMA:-1.0}" \ + --val_interval "${VAL_INTERVAL:-100}" \ + --val_batches "${VAL_BATCHES:-1}" \ + --val_inference_steps "${VAL_INFERENCE_STEPS:-1}" \ + --save_steps "${SAVE_STEPS:-500}" \ + --validate_at_start +) + +if [[ -n "${LIMIT_VIDEOS:-}" ]]; then + ARGS+=(--limit_videos "${LIMIT_VIDEOS}") +fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then + ARGS+=(--output_path "${OUTPUT_PATH}") +fi +if [[ "${ANCHOR_EACH_STEP:-1}" == "0" || "${ANCHOR_EACH_STEP:-1}" == "false" ]]; then + ARGS+=(--no-anchor_each_step) +else + ARGS+=(--anchor_each_step) +fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py new file mode 100644 index 0000000000000000000000000000000000000000..b970337ed340baab75002b93433955399cd0190c --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py @@ -0,0 +1,707 @@ +"""Train Wan Bridge SR with bicubic source video and first-frame latent anchoring. + +This keeps the Wan text prompt branch enabled, removes the UltraFlash latent +upsampler source branch, and follows the Wan2.2 TI2V-style strong anchor: +the first latent temporal index is replaced by the encoded HR reference frame +during training and after every validation sampling step. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +from pathlib import Path + +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + SeedanceSRDataset, + crop_original_rgb_for_latent_crop, + crop_latent_pair_for_pixel_losses, + decode_latents_to_btchw_01, + default_model_paths, + lpips_video_loss, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, + wavelet_hf_loss, +) +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline +from diffsynth.data.video import save_video +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger +from diffsynth.utils import ModelConfig + + +def format_run_value(value: object) -> str: + text = f"{value:g}" if isinstance(value, float) else str(value) + return text.replace(".", "p").replace("-", "m").replace("/", "_") + + +def build_run_name(args) -> str: + parts = [ + "wan_sr_ffanchor", + f"x{args.sr_scale}", + f"{args.height}x{args.width}", + f"f{args.num_frames}", + "bicubic", + "prompt", + "relock" if args.anchor_each_step else "initanchor", + f"lr{format_run_value(args.learning_rate)}", + f"noise{format_run_value(args.noise_sigma)}", + f"bridge{format_run_value(args.bridge_loss_weight)}", + f"lpips{format_run_value(args.lpips_weight)}", + f"ssim{format_run_value(args.ssim_weight)}", + f"wav{format_run_value(args.wavelet_hf_weight)}", + f"pix{format_run_value(args.pixel_loss_weight)}", + f"pcrop{args.pixel_loss_crop_size}", + f"plf{args.pixel_loss_latent_frames}", + f"seed{args.seed}", + ] + return "_".join(parts) + + +class FirstFrameAnchorSRDataset(SeedanceSRDataset): + """Bicubic-upsampled SR source whose first frame is replaced by HR reference.""" + + def __init__(self, *args, **kwargs) -> None: + kwargs["source_mode"] = "bicubic" + super().__init__(*args, **kwargs) + + def __getitem__(self, idx: int) -> dict: + item = super().__getitem__(idx) + reference = item["video"][0].copy() + item["source_video"][0] = reference.copy() + item["reference_image"] = reference + return item + + +def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor: + if anchor is None: + return latents + if anchor.shape[2] != 1: + raise ValueError(f"first_frame_latents must have exactly one latent frame, got {tuple(anchor.shape)}") + if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]: + raise ValueError( + f"anchor shape {tuple(anchor.shape)} is incompatible with latents {tuple(latents.shape)}" + ) + out = latents.clone() + out[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype) + return out + + +def drop_first_time_frame_btchw(video: torch.Tensor) -> torch.Tensor: + if video.shape[1] <= 1: + return video[:, :0] + return video[:, 1:] + + +def drop_first_time_frame_bcthw(latents: torch.Tensor) -> torch.Tensor: + if latents.shape[2] <= 1: + return latents[:, :, :0] + return latents[:, :, 1:] + + +def drop_global_first_frame_from_crop_btchw(video: torch.Tensor, crop_info: dict) -> torch.Tensor: + if int(crop_info.get("start_t", 0)) != 0: + return video + return drop_first_time_frame_btchw(video) + + +def mse_after_first_latent_frame(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + pred_main = drop_first_time_frame_bcthw(pred) + target_main = drop_first_time_frame_bcthw(target) + if pred_main.numel() == 0: + return pred.new_tensor(0.0) + return F.mse_loss(pred_main.float(), target_main.float()) + + +def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + if min_t <= 0: + return pred_btchw_01.new_tensor(0.0) + pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float() + target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float() + channels = pred.shape[1] + window_size = max(1, int(window_size)) + if window_size % 2 == 0: + window_size += 1 + padding = window_size // 2 + weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size) + + mu_x = F.conv2d(pred, weight, padding=padding, groups=channels) + mu_y = F.conv2d(target, weight, padding=padding, groups=channels) + mu_x_sq = mu_x.square() + mu_y_sq = mu_y.square() + mu_xy = mu_x * mu_y + + sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq + sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy + + c1 = 0.01 ** 2 + c2 = 0.03 ** 2 + ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / ( + (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8 + ) + return (1.0 - ssim.clamp(-1.0, 1.0)).mean() + + +class FirstFrameAnchorWanVideoSRBridgePipeline(WanVideoBridgePipeline): + def training_loss(self, **inputs): + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps) + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + anchor_each_step = bool(inputs.get("anchor_each_step", True)) + + anchor = inputs.get("first_frame_latents") + x0 = replace_first_latent_frame(inputs["input_latents"], anchor) + x1 = replace_first_latent_frame(inputs["source_latents"], anchor) + noise = inputs["noise"] + + xt = self.scheduler.add_noise(x0, x1, noise, timestep) + if anchor_each_step: + xt = replace_first_latent_frame(xt, anchor) + + model_inputs = dict(inputs) + model_inputs["latents"] = xt + model_inputs["input_latents"] = x0 + model_inputs["source_latents"] = x1 + model_inputs.pop("first_frame_latents", None) + + target = self.scheduler.training_target(x0, xt, timestep) + model_output = self.model_fn(**model_inputs, timestep=timestep) + + if self.scheduler.target == "stabilized_drift": + sigma = self.scheduler.get_sigma(timestep) + factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5 + velocity_target = target / factor + velocity_for_endpoint = model_output * factor + elif self.scheduler.target == "drift": + velocity_target = target + velocity_for_endpoint = model_output + else: + raise ValueError("First-frame-anchor SR bridge training supports --target stabilized_drift or drift") + + bridge_loss = ( + mse_after_first_latent_frame(model_output, velocity_target) + if anchor_each_step + else F.mse_loss(model_output.float(), velocity_target.float()) + ) + total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss + metrics = { + "bridge_loss": float(bridge_loss.detach().cpu()), + "lpips_loss": 0.0, + "ssim_loss": 0.0, + "wavelet_hf_loss": 0.0, + "pixel_loss": 0.0, + } + + lpips_model = inputs.get("lpips_model") + lpips_weight = float(inputs.get("lpips_weight", 0.0)) + ssim_weight = float(inputs.get("ssim_weight", 0.0)) + wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0)) + pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0)) + if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0: + sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + endpoint_pred = xt.float() - sigma * velocity_for_endpoint.float() + if bool(inputs.get("anchor_each_step", True)): + endpoint_pred = replace_first_latent_frame(endpoint_pred, anchor) + endpoint_pred, _, crop_info = crop_latent_pair_for_pixel_losses( + endpoint_pred, + x0.detach(), + crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 256)), + latent_frames=int(inputs.get("pixel_loss_latent_frames", 3)), + vae_factor=int(getattr(self.vae, "upsampling_factor", 8)), + return_crop_info=True, + ) + pred_video = decode_latents_to_btchw_01( + self, + endpoint_pred, + tiled=bool(inputs.get("tiled", False)), + tile_size=inputs.get("tile_size", (30, 52)), + tile_stride=inputs.get("tile_stride", (15, 26)), + ) + raw_target_video = inputs.get("raw_target_video") + if raw_target_video is None: + raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses") + target_video = crop_original_rgb_for_latent_crop(raw_target_video, crop_info, pred_video, self.device) + if anchor_each_step: + pred_video_main = drop_global_first_frame_from_crop_btchw(pred_video, crop_info) + target_video_main = drop_global_first_frame_from_crop_btchw(target_video, crop_info) + else: + pred_video_main = pred_video + target_video_main = target_video + if lpips_weight > 0: + if lpips_model is None: + raise ValueError("lpips_model is required when lpips_weight > 0") + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = lpips_video_loss( + lpips_model, + pred_video_main, + target_video_main, + num_frames=int(inputs.get("lpips_num_frames", 4)), + crop_size=int(inputs.get("lpips_crop_size", 224)), + ) + total_loss = total_loss + lpips_weight * loss + metrics["lpips_loss"] = float(loss.detach().cpu()) + if ssim_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = ssim_video_loss( + pred_video_main, + target_video_main, + window_size=int(inputs.get("ssim_window_size", 11)), + ) + total_loss = total_loss + ssim_weight * loss + metrics["ssim_loss"] = float(loss.detach().cpu()) + if wavelet_hf_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = wavelet_hf_loss( + pred_video_main, + target_video_main, + levels=int(inputs.get("wavelet_hf_levels", 1)), + loss_type=str(inputs.get("wavelet_hf_loss", "l1")), + ) + total_loss = total_loss + wavelet_hf_weight * loss + metrics["wavelet_hf_loss"] = float(loss.detach().cpu()) + if pixel_loss_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = F.mse_loss(pred_video_main.float(), target_video_main.float()) + total_loss = total_loss + pixel_loss_weight * loss + metrics["pixel_loss"] = float(loss.detach().cpu()) + + return total_loss, metrics + + +class FirstFrameAnchorSRTrainingModule(DiffusionTrainingModule): + def __init__(self, args): + super().__init__() + model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe: FirstFrameAnchorWanVideoSRBridgePipeline = ( + FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cpu", + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + ) + self.pipe.latent_upsampler = None + print("[FirstFrameAnchorSR] source=bicubic_upscale_with_hr_first_frame text=prompt anchor=strong") + self.switch_pipe_to_training_mode( + self.pipe, + args.trainable_models, + args.lora_base_model, + args.lora_target_modules, + args.lora_rank, + lora_checkpoint=args.lora_checkpoint, + enable_fp8_training=False, + ) + self.args = args + if args.lpips_weight > 0 or args.val_lpips: + import lpips + + self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False) + else: + self.lpips_model = None + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + if self.lpips_model is not None: + self.lpips_model.to(*args, **kwargs) + return self + + def _encode_first_frame_anchor(self, reference_image: Image.Image) -> torch.Tensor: + self.pipe.load_models_to_device(["vae"]) + reference_video = self.pipe.preprocess_video([reference_image]) + anchor = self.pipe.vae.encode( + reference_video, + device=self.pipe.device, + tiled=self.args.tiled, + tile_size=(self.args.tile_h, self.args.tile_w), + tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w), + ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + if anchor.shape[2] != 1: + raise ValueError(f"Expected reference image to encode to one latent frame, got {tuple(anchor.shape)}") + return anchor + + def forward_preprocess(self, data): + prompt = data["prompt"] + if random.random() < self.args.text_drop_probability: + prompt = " " + inputs_posi = {"prompt": prompt} + inputs_nega = {} + inputs_shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + "cfg_scale": 1, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + "anchor_each_step": self.args.anchor_each_step, + "max_timestep_boundary": self.args.max_timestep_boundary, + "min_timestep_boundary": self.args.min_timestep_boundary, + "bridge_loss_weight": self.args.bridge_loss_weight, + "lpips_weight": self.args.lpips_weight, + "lpips_model": self.lpips_model, + "lpips_num_frames": self.args.lpips_num_frames, + "lpips_crop_size": self.args.lpips_crop_size, + "ssim_weight": self.args.ssim_weight, + "ssim_window_size": self.args.ssim_window_size, + "pixel_loss_crop_size": self.args.pixel_loss_crop_size, + "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames, + "wavelet_hf_weight": self.args.wavelet_hf_weight, + "wavelet_hf_levels": self.args.wavelet_hf_levels, + "wavelet_hf_loss": self.args.wavelet_hf_loss, + "pixel_loss_weight": self.args.pixel_loss_weight, + } + for unit in self.pipe.units: + inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner( + unit, self.pipe, inputs_shared, inputs_posi, inputs_nega + ) + inputs_shared["first_frame_latents"] = self._encode_first_frame_anchor(data["reference_image"]) + inputs_shared["raw_target_video"] = data["video"] + return {**inputs_shared, **inputs_posi} + + def forward(self, data, inputs=None): + if inputs is None: + inputs = self.forward_preprocess(data) + return self.pipe.training_loss( + **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}, + **inputs, + ) + + +class FirstFrameAnchorModelLogger(ModelLogger): + def on_step_end(self, accelerator, model, save_steps=None): + super().on_step_end(accelerator, model, save_steps) + + +@torch.no_grad() +def validate(args, accelerator: Accelerator, model: FirstFrameAnchorSRTrainingModule, dataset: Dataset, step: int) -> dict: + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + pipe.eval() + backup_scheduler = pipe.scheduler + pipe.scheduler = copy.deepcopy(backup_scheduler) + pipe.scheduler.noise_scale = args.val_sampling_noise_scale + pipe.scheduler.target = args.target + + rows = [] + out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}" + out_dir.mkdir(parents=True, exist_ok=True) + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + pipe.scheduler.set_timesteps(1000, training=True) + inputs = module.forward_preprocess(data) + pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift) + x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"]) + x1 = replace_first_latent_frame(inputs["source_latents"], inputs["first_frame_latents"]) + latents = x1.clone() + pipe.load_models_to_device(pipe.in_iteration_models) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("first_frame_latents", None) + model_inputs["input_latents"] = x0 + model_inputs["source_latents"] = x1 + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, x1) + if args.anchor_each_step: + latents = replace_first_latent_frame(latents, inputs["first_frame_latents"]) + + pred_video = decode_latents_to_btchw_01( + pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w) + ) + target_video = decode_latents_to_btchw_01( + pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w) + ) + if args.anchor_each_step: + pred_video_main = drop_first_time_frame_btchw(pred_video) + target_video_main = drop_first_time_frame_btchw(target_video) + else: + pred_video_main = pred_video + target_video_main = target_video + source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0) + target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0) + min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1]) + strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1) + save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(strip[0]), str(out_dir / f"val_{idx:03d}_source_pred_target.mp4"), fps=args.fps, quality=5) + data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png") + + row = { + "idx": idx, + "latent_mse": ( + mse_after_first_latent_frame(latents, x0).item() + if args.anchor_each_step + else F.mse_loss(latents.float(), x0.float()).item() + ), + "pixel_mse": ( + F.mse_loss(pred_video_main.float(), target_video_main.float()).item() + if pred_video_main.shape[1] > 0 + else 0.0 + ), + "anchor_latent_mse": F.mse_loss( + latents[:, :, :1].float(), inputs["first_frame_latents"].float() + ).item(), + } + if module.lpips_model is not None and args.val_lpips: + row["lpips"] = float( + lpips_video_loss( + module.lpips_model, + pred_video_main, + target_video_main, + args.lpips_num_frames, + args.lpips_crop_size, + ).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + if args.val_ssim or args.ssim_weight > 0: + row["ssim"] = float( + ssim_video_loss(pred_video_main, target_video_main, args.ssim_window_size).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + if args.val_wavelet_hf_loss: + row["wavelet_hf"] = float( + wavelet_hf_loss(pred_video_main, target_video_main, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + rows.append(row) + + pipe.scheduler = backup_scheduler + metrics = {} + if rows: + for key in rows[0]: + if key != "idx": + metrics[f"val_{key}"] = float( + sum(row[key] for row in rows if key in row) / max(sum(1 for row in rows if key in row), 1) + ) + (out_dir / "metrics.json").write_text( + json.dumps( + { + "step": step, + "rows": rows, + "metrics": metrics, + "pipeline": "bicubic_source_hr_first_frame_strong_latent_anchor_with_prompt", + "anchor_each_step": args.anchor_each_step, + }, + indent=2, + ), + encoding="utf-8", + ) + print(f"[Validation step {step}] {metrics}") + pipe.train() + return metrics + + +def build_dataset(args, repeat: int, limit_videos: int | None, seed: int) -> FirstFrameAnchorSRDataset: + return FirstFrameAnchorSRDataset( + args.video_dir, + args.prompt_json, + args.prompt_field, + args.default_prompt, + args.height, + args.width, + args.num_frames, + args.sr_scale, + repeat=repeat, + limit_videos=limit_videos, + seed=seed, + ) + + +def train(args): + save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None + if args.output_path is None: + args.output_path = str(Path(args.output_root) / build_run_name(args)) + train_set = build_dataset( + args, + repeat=args.dataset_repeat, + limit_videos=args.limit_videos, + seed=args.seed, + ) + val_set = build_dataset( + args, + repeat=1, + limit_videos=max(args.val_batches, 1), + seed=args.seed + 1, + ) + model = FirstFrameAnchorSRTrainingModule(args) + model.pipe.scheduler.noise_scale = args.noise_sigma + model.pipe.scheduler.bridge_type = "brownian" + model.pipe.scheduler.training_weight_type = args.training_weight_type + model.pipe.scheduler.target = args.target + print("Scheduler noise scale:", model.pipe.scheduler.noise_scale) + print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type) + print("Scheduler target:", model.pipe.scheduler.target) + + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + print(f"[Output] {args.output_path}") + + if args.validation_only or args.max_train_steps <= 0: + model = accelerator.prepare(model) + validate(args, accelerator, model, val_set, 0) + return + + from prodigyopt import Prodigy + + optimizer = Prodigy( + model.trainable_modules(), + lr=args.learning_rate, + weight_decay=args.weight_decay, + safeguard_warmup=True, + d_coef=args.d_coef, + ) + dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers) + model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + logger = FirstFrameAnchorModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt) + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + + global_step = 0 + while global_step < args.max_train_steps: + for data in tqdm(dataloader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad() + loss, metrics = model(data) + accelerator.backward(loss) + if args.max_grad_norm > 0: + accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step() + global_step += 1 + gathered_loss = accelerator.gather(loss.detach()).mean().item() + if accelerator.is_main_process and global_step % args.log_interval == 0: + print( + f"[Train step {global_step}] loss={gathered_loss:.6f} " + f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} " + f"ssim={metrics['ssim_loss']:.6f} " + f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}" + ) + logger.on_step_end(accelerator, model, save_steps) + if args.val_interval > 0 and global_step % args.val_interval == 0: + validate(args, accelerator, model, val_set, global_step) + if global_step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, save_steps) + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Train Wan2.1 Bridge SR with bicubic source video, prompt text, and strong first-frame latent anchoring." + ) + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p") + parser.add_argument("--default_prompt", default="") + parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr") + parser.add_argument("--output_path", default=None) + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--limit_videos", type=int, default=None) + parser.add_argument("--dataset_repeat", type=int, default=1) + parser.add_argument("--dataset_num_workers", type=int, default=0) + parser.add_argument("--trainable_models", default="dit") + parser.add_argument("--lora_base_model", default=None) + parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2") + parser.add_argument("--lora_rank", type=int, default=32) + parser.add_argument("--lora_checkpoint", default=None) + parser.add_argument("--learning_rate", type=float, default=1.0) + parser.add_argument("--weight_decay", type=float, default=0.01) + parser.add_argument("--d_coef", type=float, default=1.0) + parser.add_argument("--max_train_steps", type=int, default=5000) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--max_grad_norm", type=float, default=1.0) + parser.add_argument("--save_steps", type=int, default=500) + parser.add_argument("--log_interval", type=int, default=1) + parser.add_argument("--val_interval", type=int, default=100) + parser.add_argument("--val_batches", type=int, default=1) + parser.add_argument("--validate_at_start", action="store_true", default=False) + parser.add_argument("--validation_only", action="store_true", default=False) + parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.") + parser.add_argument("--noise_sigma", type=float, default=1.0) + parser.add_argument("--training_weight_type", default="uniform") + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--bridge_loss_weight", type=float, default=1.0) + parser.add_argument("--lpips_weight", type=float, default=1.0) + parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg") + parser.add_argument("--lpips_num_frames", type=int, default=4) + parser.add_argument("--lpips_crop_size", type=int, default=400) + parser.add_argument("--ssim_weight", type=float, default=0.0) + parser.add_argument("--ssim_window_size", type=int, default=11) + parser.add_argument("--val_ssim", action="store_true", default=False) + parser.add_argument("--pixel_loss_crop_size", type=int, default=400) + parser.add_argument("--pixel_loss_latent_frames", type=int, default=3) + parser.add_argument("--val_lpips", action="store_true", default=False) + parser.add_argument("--wavelet_hf_weight", type=float, default=50.0) + parser.add_argument("--wavelet_hf_levels", type=int, default=1) + parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1") + parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False) + parser.add_argument("--pixel_loss_weight", type=float, default=8.0) + parser.add_argument("--val_inference_steps", type=int, default=1) + parser.add_argument("--val_sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--val_sigma_shift", type=float, default=5.0) + parser.add_argument("--max_timestep_boundary", type=float, default=0.9999) + parser.add_argument("--min_timestep_boundary", type=float, default=0.0001) + parser.add_argument("--text_drop_probability", type=float, default=0.0) + parser.add_argument( + "--anchor_each_step", + action=argparse.BooleanOptionalAction, + default=True, + help="Re-lock latent frame 0 to the reference for RGB endpoint prediction and after validation denoise steps. Disable to anchor only at initialization.", + ) + parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True) + parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False) + parser.add_argument("--find_unused_parameters", action="store_true", default=False) + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + if args.model_paths is None: + args.model_paths = default_model_paths(args.base_model_dir) + return args + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..ecdf3588d4b2642234b2c7768aa45b62719a96a0 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.py @@ -0,0 +1,752 @@ +"""Stage-2 training for a reference-aware Wan Brownian-Bridge SR adapter. + +Only the state-aware adapters are optimized. The Wan backbone, the trained +Brownian-Bridge SR checkpoint, VAE, text encoder, and UltraFlash latent +upsampler remain frozen. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +import sys +from pathlib import Path + +import imageio +import numpy as np +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from safetensors.torch import load_file +from PIL import Image +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.model_training.reference_adapter import ( + install_reference_adapters, + parse_block_ids, + prepare_reference_condition, + reference_blocks, + set_reference_adapters_enabled, +) +from diffsynth.bridge.wan_bridge.model_training.sobel_utils import ( + dilated_sobel_edge_mask, + sobel_rgb_gradients, +) +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + SeedanceSRDataset, + WanVideoSRBridgePipeline, + WanVideoSRUnit_UltraFlashLatentUpsampler, + center_crop_resize, + crop_original_rgb_for_latent_crop, + crop_latent_pair_for_pixel_losses, + decode_latents_to_btchw_01, + default_model_paths, + load_ultraflash_latent_upsampler, + lpips_video_loss, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, + wavelet_hf_loss, +) +from diffsynth.data.video import save_video +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger +from diffsynth.utils import ModelConfig + + +def _run_value(value: object) -> str: + text = f"{value:g}" if isinstance(value, float) else str(value) + return text.replace(".", "p").replace("-", "m").replace("/", "_").replace(",", "-") + + +def build_reference_run_name(args) -> str: + """Deterministic experiment directory name from all result-defining knobs.""" + parts = [ + f"ref_{args.reference_mode}", + "onestep", + "onewaycross2d_reszero", + f"wv{args.wavelet_value_mode}", + f"wb{_run_value(args.wavelet_energy_bias)}-c{_run_value(args.wavelet_energy_clip)}", + f"x{args.sr_scale}", + f"{args.height}x{args.width}", + f"f{args.num_frames}", + args.source_mode, + f"blocks{_run_value(args.adapter_blocks)}", + f"d{args.adapter_dim}", + f"h{args.adapter_heads}", + f"l1{_run_value(args.pixel_l1_weight)}", + f"hf{_run_value(args.hf_weight)}-{args.hf_loss_type}{args.hf_levels}", + f"sobel{_run_value(args.sobel_edge_weight)}-d{args.sobel_edge_dilation_radius}-thr{_run_value(args.sobel_edge_threshold)}", + f"lpips{_run_value(args.lpips_weight)}", + f"crop{args.loss_crop_size}", + f"lf{args.loss_latent_frames}", + f"lr{_run_value(args.learning_rate)}", + f"seed{args.seed}", + ] + return "_".join(parts) + + +class FirstFrameReferenceSRDataset(SeedanceSRDataset): + """Video SR samples whose identity reference is absolute video frame zero.""" + + def _read_reference_image(self, path: Path) -> Image.Image: + reader = imageio.get_reader(str(path)) + try: + frame = reader.get_data(0) + finally: + reader.close() + image = Image.fromarray(np.asarray(frame)).convert("RGB") + return center_crop_resize(image, self.height, self.width) + + def __getitem__(self, idx: int) -> dict: + item = super().__getitem__(idx) + item["reference_image"] = self._read_reference_image(Path(item["path"])) + return item + + +def sobel_edge_loss( + pred_btchw_01: torch.Tensor, + target_btchw_01: torch.Tensor, + dilation_radius: int = 2, + threshold_multiplier: float = 1.0, +) -> torch.Tensor: + """Sobel-L1 inside a target-edge mask dilated into a learnable band.""" + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + pred_x, pred_y = sobel_rgb_gradients(pred_btchw_01[:, :min_t]) + target_x, target_y = sobel_rgb_gradients(target_btchw_01[:, :min_t]) + channels = pred_x.shape[1] + + with torch.no_grad(): + _, _, _, edge_mask = dilated_sobel_edge_mask( + target_x, target_y, dilation_radius, threshold_multiplier + ) + directional_error = (pred_x - target_x).abs() + (pred_y - target_y).abs() + denominator = edge_mask.sum().clamp_min(1.0) * channels + return 0.5 * (directional_error * edge_mask).sum() / denominator + + +def load_bridge_checkpoint(pipe: WanVideoSRBridgePipeline, checkpoint: str) -> None: + state_dict = load_file(checkpoint, device="cpu") + prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.") + candidates = [("raw", state_dict)] + for prefix in prefixes: + if any(key.startswith(prefix) for key in state_dict): + candidates.append( + (f"strip:{prefix}", {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state_dict.items()}) + ) + errors = [] + for name, candidate in candidates: + try: + pipe.dit.load_state_dict(candidate, strict=True) + print(f"[ReferenceSR] loaded frozen Bridge checkpoint ({name}): {checkpoint}") + return + except Exception as exc: + errors.append(f"{name}: {exc}") + raise RuntimeError("Could not load Bridge checkpoint:\n" + "\n".join(errors)) + + +def load_adapter_checkpoint(dit: torch.nn.Module, checkpoint: str) -> None: + state_dict = load_file(checkpoint, device="cpu") + for prefix in ("pipe.dit.", "dit.", "module.pipe.dit."): + if any(key.startswith(prefix) for key in state_dict): + state_dict = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state_dict.items()} + break + incompatible_markers = ( + ".q_state.", ".q_source.", ".k_reference.", ".v_reference", + ".adapter.q_proj.", ".adapter.k_proj.", ".adapter.v_proj.", + ".adapter.target_q_proj.", ".adapter.reference_k_proj.", + ".adapter.reference_v_proj.", ".adapter.out_proj.", + ".adapter.pair_norm.", ".adapter.target_stream_embedding", + ".adapter.reference_stream_embedding", + ) + if any(marker in key for key in state_dict for marker in incompatible_markers): + raise RuntimeError( + "This checkpoint belongs to an older reference-adapter architecture. " + "The one-way target-Q/reference-KV residual Adapter has different " + "parameters; start a new run or provide a onewaycross2d_reszero checkpoint." + ) + result = dit.load_state_dict(state_dict, strict=False) + unexpected = [key for key in result.unexpected_keys if ".base_block." not in key] + if unexpected: + raise RuntimeError(f"Unexpected adapter checkpoint keys: {unexpected[:20]}") + missing_adapter = [key for key in result.missing_keys if ".adapter." in key] + if missing_adapter: + raise RuntimeError( + "Adapter checkpoint does not cover every configured Wan block. " + f"Missing {len(missing_adapter)} adapter tensors, for example: {missing_adapter[:10]}. " + "Use a checkpoint trained with the same --adapter_blocks setting." + ) + loaded = [key for key in state_dict if ".adapter." in key] + if not loaded: + raise RuntimeError(f"No adapter keys found in {checkpoint}") + print(f"[ReferenceSR] resumed {len(loaded)} adapter tensors from {checkpoint}") + + +class ReferenceSRTrainingModule(DiffusionTrainingModule): + def __init__(self, args) -> None: + super().__init__() + model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cpu", + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_bridge_checkpoint(self.pipe, args.bridge_checkpoint) + if args.source_mode == "upsampler": + self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu") + self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()] + else: + self.pipe.latent_upsampler = None + + self.pipe.requires_grad_(False) + block_ids = parse_block_ids(args.adapter_blocks, len(self.pipe.dit.blocks)) + install_reference_adapters( + self.pipe.dit, + block_ids, + adapter_dim=args.adapter_dim, + adapter_heads=args.adapter_heads, + wavelet_value_mode=args.wavelet_value_mode, + wavelet_energy_bias=args.wavelet_energy_bias, + wavelet_energy_clip=args.wavelet_energy_clip, + ) + for block in reference_blocks(self.pipe.dit): + block.adapter.to(dtype=self.pipe.torch_dtype) + if args.adapter_checkpoint: + load_adapter_checkpoint(self.pipe.dit, args.adapter_checkpoint) + + # Strict one-step Bridge: sigma=1 source endpoint to sigma=0 target. + # The adapter itself has no timestep input. + self.pipe.scheduler.set_timesteps(1, training=True, shift=args.bridge_sigma_shift) + self.pipe.scheduler.noise_scale = 0.0 + self.pipe.scheduler.bridge_type = "brownian" + self.pipe.scheduler.target = args.target + self.args = args + + import lpips + + self.lpips_model = lpips.LPIPS(net="vgg", verbose=False).eval().requires_grad_(False) + trainable = sum(param.numel() for param in self.parameters() if param.requires_grad) + total = sum(param.numel() for param in self.pipe.dit.parameters()) + print( + f"[ReferenceSR] one-way target-Q/reference-KV + 2D RoPE + zero-init residual " + f"blocks={block_ids}; wavelet_V={args.wavelet_value_mode} " + f"energy_bias={args.wavelet_energy_bias:g}; " + f"trainable={trainable / 1e6:.2f}M / DiT={total / 1e9:.3f}B" + ) + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + self.lpips_model.to(*args, **kwargs) + return self + + def forward_preprocess(self, data: dict, apply_text_dropout: bool = True) -> dict: + if self.args.reference_mode == "image": + # Temporary fixed conditioning for digital-human image animation. + prompt = "a person is speaking" + else: + prompt = data["prompt"] + if self.args.reference_mode != "image" and apply_text_dropout and random.random() < self.args.text_drop_probability: + prompt = " " + inputs_posi = {"prompt": prompt} + inputs_nega = {} + inputs_shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + "cfg_scale": 1, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + } + for unit in self.pipe.units: + inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner( + unit, self.pipe, inputs_shared, inputs_posi, inputs_nega + ) + if self.args.reference_mode == "image": + if "reference_image" not in data: + raise KeyError("image reference mode requires data['reference_image']") + self.pipe.load_models_to_device(["vae"]) + reference_video = self.pipe.preprocess_video([data["reference_image"]]) + with torch.no_grad(): + reference_latents = self.pipe.vae.encode( + reference_video, + device=self.pipe.device, + tiled=self.args.tiled, + tile_size=(self.args.tile_h, self.args.tile_w), + tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w), + ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + if reference_latents.shape[2] != 1: + raise RuntimeError( + f"A single reference image must encode to one latent frame, got {reference_latents.shape[2]}" + ) + inputs_shared["adapter_reference_latents"] = reference_latents + return {**inputs_shared, **inputs_posi} + + def _endpoint_prediction(self, inputs: dict) -> tuple[torch.Tensor, torch.Tensor]: + x0 = inputs["input_latents"] + x1 = inputs["source_latents"] + timestep = self.pipe.scheduler.timesteps[0].unsqueeze(0).to( + dtype=self.pipe.torch_dtype, device=self.pipe.device + ) + reference_latents = inputs.get("adapter_reference_latents", x0) + prepare_reference_condition(self.pipe.dit, x1.detach(), reference_latents.detach()) + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("input_latents", None) + model_inputs.pop("adapter_reference_latents", None) + model_output = self.pipe.model_fn( + **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}, + **model_inputs, + latents=x1, + timestep=timestep, + ) + # With one step sigma=1 and the final scheduler endpoint is sigma=0. + endpoint = self.pipe.scheduler.step( + model_output, + self.pipe.scheduler.timesteps[0], + x1, + x1, + ) + return endpoint.float(), x0.detach() + + def forward(self, data: dict, inputs: dict | None = None): + inputs = self.forward_preprocess(data) if inputs is None else inputs + endpoint, target = self._endpoint_prediction(inputs) + endpoint, target, crop_info = crop_latent_pair_for_pixel_losses( + endpoint, + target, + crop_size_pixels=self.args.loss_crop_size, + latent_frames=self.args.loss_latent_frames, + vae_factor=int(getattr(self.pipe.vae, "upsampling_factor", 8)), + return_crop_info=True, + ) + pred_video = decode_latents_to_btchw_01( + self.pipe, endpoint, self.args.tiled, (self.args.tile_h, self.args.tile_w), + (self.args.tile_stride_h, self.args.tile_stride_w), + ) + original_rgb = crop_original_rgb_for_latent_crop( + data["video"], crop_info, pred_video, self.pipe.device + ) + # Exactly three objectives, all supervised by the on-disk original RGB crop. + pixel_l1 = F.l1_loss(pred_video.float(), original_rgb.float()) + wavelet = wavelet_hf_loss( + pred_video, original_rgb, levels=self.args.hf_levels, loss_type=self.args.hf_loss_type + ) + sobel = sobel_edge_loss( + pred_video, + original_rgb, + dilation_radius=self.args.sobel_edge_dilation_radius, + threshold_multiplier=self.args.sobel_edge_threshold, + ) + high_frequency = wavelet + self.args.sobel_edge_weight * sobel + perceptual = lpips_video_loss( + self.lpips_model, pred_video, original_rgb, + num_frames=self.args.lpips_num_frames, crop_size=self.args.lpips_crop_size, + ) + loss = ( + self.args.pixel_l1_weight * pixel_l1 + + self.args.hf_weight * high_frequency + + self.args.lpips_weight * perceptual + ) + metrics = { + "pixel_l1": float(pixel_l1.detach().cpu()), + "high_frequency": float(high_frequency.detach().cpu()), + "wavelet": float(wavelet.detach().cpu()), + "sobel_edge": float(sobel.detach().cpu()), + "vgg_lpips": float(perceptual.detach().cpu()), + } + return loss, metrics + + +def _align_video(video: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + min_t = min(video.shape[1], target.shape[1]) + video = video[:, :min_t] + if video.shape[-2:] != target.shape[-2:]: + b, t, c, h, w = video.shape + video = F.interpolate( + video.reshape(b * t, c, h, w), size=target.shape[-2:], mode="bicubic", + align_corners=False, antialias=True, + ).reshape(b, t, c, target.shape[-2], target.shape[-1]) + return video.clamp(0, 1) + + +def _quality_metrics(module: ReferenceSRTrainingModule, pred: torch.Tensor, original: torch.Tensor) -> dict: + min_t = min(pred.shape[1], original.shape[1]) + pred, original = pred[:, :min_t], original[:, :min_t] + mse = F.mse_loss(pred.float(), original.float()) + return { + "mse_to_original": float(mse.cpu()), + "psnr_to_original": float((-10 * torch.log10(mse.clamp_min(1e-12))).cpu()), + "mean_abs_gap_to_original": float(F.l1_loss(pred.float(), original.float()).cpu()), + "high_frequency_gap": float(wavelet_hf_loss(pred, original, module.args.hf_levels, module.args.hf_loss_type).cpu()), + "sobel_edge_gap": float(sobel_edge_loss( + pred, + original, + module.args.sobel_edge_dilation_radius, + module.args.sobel_edge_threshold, + ).cpu()), + "vgg_lpips_gap": float(_deterministic_lpips( + module.lpips_model, pred, original, module.args.lpips_num_frames, module.args.lpips_crop_size + ).cpu()), + } + + +def _deterministic_lpips(lpips_model, pred: torch.Tensor, target: torch.Tensor, num_frames: int, crop_size: int) -> torch.Tensor: + """Validation-only LPIPS with the same temporal indices and center crop.""" + min_t = min(pred.shape[1], target.shape[1]) + pred, target = pred[:, :min_t], target[:, :min_t] + if num_frames > 0 and min_t > num_frames: + indices = torch.linspace(0, min_t - 1, steps=num_frames, device=pred.device).round().long() + pred, target = pred.index_select(1, indices), target.index_select(1, indices) + if crop_size > 0: + crop_h = min(crop_size, pred.shape[-2]) + crop_w = min(crop_size, pred.shape[-1]) + top = (pred.shape[-2] - crop_h) // 2 + left = (pred.shape[-1] - crop_w) // 2 + pred = pred[..., top:top + crop_h, left:left + crop_w] + target = target[..., top:top + crop_h, left:left + crop_w] + pred_frames = pred.reshape(-1, *pred.shape[2:]).mul(2).sub(1).clamp(-1, 1) + target_frames = target.reshape(-1, *target.shape[2:]).mul(2).sub(1).clamp(-1, 1) + return lpips_model(pred_frames.float(), target_frames.float()).mean() + + +@torch.no_grad() +def _sample(module: ReferenceSRTrainingModule, inputs: dict, enabled: bool) -> torch.Tensor: + pipe = module.pipe + x1 = inputs["source_latents"] + x0 = inputs["input_latents"] + latents = x1.clone() + set_reference_adapters_enabled(pipe.dit, enabled) + if enabled: + reference_latents = inputs.get("adapter_reference_latents", x0) + prepare_reference_condition(pipe.dit, x1, reference_latents) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("input_latents", None) + model_inputs.pop("adapter_reference_latents", None) + model_inputs.pop("use_gradient_checkpointing", None) + model_inputs.pop("use_gradient_checkpointing_offload", None) + if len(pipe.scheduler.timesteps) != 1: + raise RuntimeError(f"Reference SR requires exactly one Bridge step, got {len(pipe.scheduler.timesteps)}") + timestep_cpu = pipe.scheduler.timesteps[0] + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn( + **models, + **model_inputs, + latents=latents, + timestep=timestep, + use_gradient_checkpointing=False, + use_gradient_checkpointing_offload=False, + ) + return pipe.scheduler.step(pred, timestep_cpu, latents, x1) + + +@torch.no_grad() +def validate(args, accelerator: Accelerator, model: ReferenceSRTrainingModule, dataset: Dataset, step: int) -> dict: + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + pipe.eval() + scheduler_backup = pipe.scheduler + pipe.scheduler = copy.deepcopy(scheduler_backup) + pipe.scheduler.noise_scale = 0.0 + pipe.scheduler.target = args.target + out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}" + out_dir.mkdir(parents=True, exist_ok=True) + rows = [] + try: + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + pipe.scheduler.set_timesteps(1, training=True, shift=args.bridge_sigma_shift) + inputs = module.forward_preprocess(data, apply_text_dropout=False) + pipe.load_models_to_device(pipe.in_iteration_models) + pipe.scheduler.set_timesteps(1, shift=args.bridge_sigma_shift) + base_latents = _sample(module, inputs, enabled=False) + pipe.scheduler.set_timesteps(1, shift=args.bridge_sigma_shift) + ref_latents = _sample(module, inputs, enabled=True) + + ultraflash_video = decode_latents_to_btchw_01( + pipe, inputs["source_latents"], args.tiled, + (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w), + ) + base_video = decode_latents_to_btchw_01(pipe, base_latents, args.tiled, + (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + ref_video = decode_latents_to_btchw_01(pipe, ref_latents, args.tiled, + (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + original = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0) + source = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0) + ultraflash_video = _align_video(ultraflash_video, original) + base_video = _align_video(base_video, original) + ref_video = _align_video(ref_video, original) + source = _align_video(source, original) + min_t = min(source.shape[1], ultraflash_video.shape[1], base_video.shape[1], ref_video.shape[1], original.shape[1]) + original = original[:, :min_t] + source, ultraflash_video, base_video, ref_video = ( + source[:, :min_t], ultraflash_video[:, :min_t], + base_video[:, :min_t], ref_video[:, :min_t], + ) + diff = (ref_video - original).abs().mul(args.val_diff_amplification).clamp(0, 1) + comparison = torch.cat([source, ultraflash_video, base_video, ref_video, original, diff], dim=-1) + adapter_video_path = out_dir / f"val_{idx:03d}_adapter_output.mp4" + comparison_video_path = out_dir / f"val_{idx:03d}_lr_ultraflash_base_ref_original_diff.mp4" + reference_image_path = None + if "reference_image" in data: + reference_image_path = out_dir / f"val_{idx:03d}_input_reference.png" + data["reference_image"].save(reference_image_path) + save_video( + tensor_btchw_01_to_pil(ref_video[0]), + str(adapter_video_path), + fps=args.fps, + quality=5, + ) + save_video( + tensor_btchw_01_to_pil(comparison[0]), + str(comparison_video_path), + fps=args.fps, + quality=5, + ) + + ultraflash_metrics = _quality_metrics(module, ultraflash_video, original) + base_metrics = _quality_metrics(module, base_video, original) + ref_metrics = _quality_metrics(module, ref_video, original) + rows.append({ + "idx": idx, + "video": data["path"], + "artifacts": { + "adapter_output_video": adapter_video_path.name, + "comparison_video": comparison_video_path.name, + "input_reference_image": reference_image_path.name if reference_image_path else None, + }, + "ultraflash": ultraflash_metrics, + "base": base_metrics, + "reference": ref_metrics, + "reference_minus_base": {key: ref_metrics[key] - base_metrics[key] for key in ref_metrics}, + "psnr_gain_db": ref_metrics["psnr_to_original"] - base_metrics["psnr_to_original"], + }) + finally: + set_reference_adapters_enabled(pipe.dit, True) + pipe.scheduler = scheduler_backup + pipe.train() + + summary = {} + if rows: + for section in ("ultraflash", "base", "reference", "reference_minus_base"): + for key in rows[0][section]: + summary[f"{section}/{key}"] = sum(row[section][key] for row in rows) / len(rows) + summary["reference/psnr_gain_db"] = sum(row["psnr_gain_db"] for row in rows) / len(rows) + payload = { + "step": step, + "bridge_inference_steps": 1, + "bridge_sigma_shift": args.bridge_sigma_shift, + "adapter_architecture": "framewise_target_q_reference_kv_rope2d_residual_zero_scale", + "reference_mode": args.reference_mode, + "comparison_order": ["LR bicubic", "UltraFlash only", "frozen Bridge", "reference adapter", "original video", f"absolute difference x{args.val_diff_amplification:g}"], + "rows": rows, + "summary": summary, + } + (out_dir / "metrics.json").write_text(json.dumps(payload, indent=2), encoding="utf-8") + print(f"[Validation step {step}] {summary}") + return summary + + +def build_dataset(args, validation: bool = False) -> SeedanceSRDataset: + dataset_class = FirstFrameReferenceSRDataset if args.reference_mode == "image" else SeedanceSRDataset + return dataset_class( + args.video_dir, args.prompt_json, args.prompt_field, args.default_prompt, + args.height, args.width, args.num_frames, args.sr_scale, + source_mode=args.source_mode, repeat=1 if validation else args.dataset_repeat, + limit_videos=max(args.val_batches, 1) if validation else args.limit_videos, + seed=args.seed + int(validation), + ) + + +def train(args) -> None: + random.seed(args.seed) + torch.manual_seed(args.seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(args.seed) + args.output_path = args.output_path or str(Path(args.output_root) / build_reference_run_name(args)) + train_set = build_dataset(args) + val_dataset = build_dataset(args, validation=True) + # Materialize once so every validation step uses exactly the same clips. + val_set = [val_dataset[idx] for idx in range(min(args.val_batches, len(val_dataset)))] + model = ReferenceSRTrainingModule(args) + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=False)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + print(f"[Output] {args.output_path}") + + if args.validation_only or args.max_train_steps <= 0: + model = accelerator.prepare(model) + validate(args, accelerator, model, val_set, 0) + return + + optimizer = torch.optim.AdamW(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay) + loader = DataLoader(train_set, shuffle=True, collate_fn=lambda batch: batch[0], num_workers=args.dataset_num_workers) + model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + logger = ModelLogger(args.output_path, remove_prefix_in_ckpt="pipe.dit.") + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + + global_step = 0 + while global_step < args.max_train_steps: + for data in tqdm(loader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad(set_to_none=True) + loss, metrics = model(data) + accelerator.backward(loss) + if args.max_grad_norm > 0: + accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step() + global_step += 1 + if accelerator.is_main_process and global_step % args.log_interval == 0: + print(f"[Train step {global_step}] total={loss.detach().float().item():.6f} " + f"pixel_l1={metrics['pixel_l1']:.6f} hf={metrics['high_frequency']:.6f} " + f"wavelet={metrics['wavelet']:.6f} sobel={metrics['sobel_edge']:.6f} " + f"vgg_lpips={metrics['vgg_lpips']:.6f}") + logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + if args.val_interval > 0 and global_step % args.val_interval == 0: + validate(args, accelerator, model, val_set, global_step) + if global_step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Train identity-safe target-Q/reference-KV 2D-RoPE attention inside a frozen one-step Wan Bridge SR model." + ) + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--bridge_checkpoint", default="/cache/outputs_bridge_wan_sr/wan_sr_x2_480x832_f81_upsampler_up_1K-ultraLatentUpsampler-step_19900_lr1_noise1_bridge1_lpips1_wav15_pix8_pcrop256_plf3_seed42/step-3500.safetensors") + parser.add_argument("--adapter_checkpoint", default=None) + parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p") + parser.add_argument("--default_prompt", default="") + parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr_reference") + parser.add_argument("--output_path", default=None) + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler") + parser.add_argument( + "--reference_mode", + choices=["video", "image"], + default="video", + help="video uses the target clip as reference; image uses absolute frame 0 of each source video.", + ) + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument( + "--adapter_blocks", + default="all", + help="Wan blocks preceded by one-way target-Q/reference-KV attention with 2D RoPE and zero-init residual scale.", + ) + parser.add_argument("--adapter_dim", type=int, default=1536, help="Must equal the Wan hidden width.") + parser.add_argument("--adapter_heads", type=int, default=12, help="Must equal the Wan head count.") + parser.add_argument( + "--wavelet_value_mode", choices=["off", "highpass"], default="off", + help="highpass uses the reference hidden state's reconstructed Haar detail bands as V.", + ) + parser.add_argument( + "--wavelet_energy_bias", type=float, default=0.0, + help="Strength of the normalized Haar-energy additive reference-key logit bias.", + ) + parser.add_argument( + "--wavelet_energy_clip", type=float, default=3.0, + help="Clamp normalized wavelet energy before multiplying by its bias strength.", + ) + parser.add_argument( + "--pixel_l1_weight", "--mse_weight", + dest="pixel_l1_weight", type=float, default=1.0, + help="Weight of decoded-RGB pixel L1 loss. --mse_weight is a deprecated compatibility alias.", + ) + parser.add_argument("--hf_weight", type=float, default=0.1) + parser.add_argument("--lpips_weight", type=float, default=0.2) + parser.add_argument("--hf_levels", type=int, default=1) + parser.add_argument("--hf_loss_type", choices=["l1", "l2"], default="l1") + parser.add_argument( + "--sobel_edge_weight", + type=float, + default=0.5, + help="Relative Sobel-L1 weight inside the single high-frequency loss term.", + ) + parser.add_argument( + "--sobel_edge_dilation_radius", + type=int, + default=2, + help="Dilate the GT Sobel edge mask by this many decoded RGB pixels.", + ) + parser.add_argument( + "--sobel_edge_threshold", + type=float, + default=1.0, + help="Binary edge threshold as a multiple of each frame's mean GT gradient magnitude.", + ) + parser.add_argument("--lpips_num_frames", type=int, default=4) + parser.add_argument("--lpips_crop_size", type=int, default=400) + parser.add_argument("--loss_crop_size", type=int, default=400) + parser.add_argument("--loss_latent_frames", type=int, default=3) + parser.add_argument("--learning_rate", type=float, default=5e-5) + parser.add_argument("--weight_decay", type=float, default=0.01) + parser.add_argument("--max_train_steps", type=int, default=5000) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--max_grad_norm", type=float, default=1.0) + parser.add_argument("--save_steps", type=int, default=500) + parser.add_argument("--log_interval", type=int, default=1) + parser.add_argument("--val_interval", type=int, default=100) + parser.add_argument("--val_batches", type=int, default=1) + parser.add_argument("--bridge_sigma_shift", type=float, default=5.0, help="Fixed scheduler shift for the one-step frozen-Bridge call.") + parser.add_argument("--val_diff_amplification", type=float, default=4.0) + parser.add_argument("--validate_at_start", action="store_true") + parser.add_argument("--validation_only", action="store_true") + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--text_drop_probability", type=float, default=0.0) + parser.add_argument("--dataset_repeat", type=int, default=1) + parser.add_argument("--dataset_num_workers", type=int, default=0) + parser.add_argument("--limit_videos", type=int, default=None) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--use_gradient_checkpointing", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument("--use_gradient_checkpointing_offload", action="store_true") + parser.add_argument("--tiled", action="store_true") + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + if args.model_paths is None: + args.model_paths = default_model_paths(args.base_model_dir) + return args + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c71a07cc1c8811812f86ef730eaf55311aaed9b --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +OUTPUT_ARGS=(--output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_reference}") +if [[ -n "${OUTPUT_PATH:-}" ]]; then + OUTPUT_ARGS+=(--output_path "${OUTPUT_PATH}") +fi + +"${PYTHON_BIN}" "${SCRIPT_DIR}/train_sr_reference.py" \ + --bridge_checkpoint "${BRIDGE_CHECKPOINT:-/cache/outputs_bridge_wan_sr/wan_sr_x2_480x832_f81_upsampler_up_1K-ultraLatentUpsampler-step_19900_lr1_noise1_bridge1_lpips1_wav15_pix8_pcrop256_plf3_seed42/step-3500.safetensors}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + "${OUTPUT_ARGS[@]}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --num_frames "${NUM_FRAMES:-81}" \ + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --val_interval "${VAL_INTERVAL:-100}" \ + --save_steps "${SAVE_STEPS:-500}" \ + --adapter_blocks "${ADAPTER_BLOCKS:-all}" \ + --adapter_dim "${ADAPTER_DIM:-1536}" \ + --adapter_heads "${ADAPTER_HEADS:-12}" \ + --wavelet_value_mode "${WAVELET_VALUE_MODE:-off}" \ + --wavelet_energy_bias "${WAVELET_ENERGY_BIAS:-0.0}" \ + --wavelet_energy_clip "${WAVELET_ENERGY_CLIP:-3.0}" \ + --bridge_sigma_shift "${BRIDGE_SIGMA_SHIFT:-5.0}" \ + --pixel_l1_weight "${PIXEL_L1_WEIGHT:-${MSE_WEIGHT:-1.0}}" \ + --hf_weight "${HF_WEIGHT:-30}" \ + --sobel_edge_weight "${SOBEL_EDGE_WEIGHT:-0.5}" \ + --sobel_edge_dilation_radius "${SOBEL_EDGE_DILATION_RADIUS:-2}" \ + --sobel_edge_threshold "${SOBEL_EDGE_THRESHOLD:-1.0}" \ + --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --validate_at_start \ + "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image.sh new file mode 100644 index 0000000000000000000000000000000000000000..02a229932ff4e9873d1ce7386fa53ac4fcea89b3 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Digital-human image-reference training: every target clip comes from a video, +# while absolute frame 0 of that video is encoded once as the reference image. +# Sobel dilation defaults off; set IMAGE_SOBEL_EDGE_DILATION_RADIUS=1/2 for a +# 3x3/5x5 edge band. +VIDEO_DIR="${VIDEO_DIR:-/cache/Human-Image-Animation-Data/videos/000}" \ +PROMPT_JSON="${PROMPT_JSON-}" \ +OUTPUT_ROOT="${OUTPUT_ROOT:-/cache/outputs_wavbridge_wan_sr_reference}" \ +HEIGHT="${HEIGHT:-832}" \ +WIDTH="${WIDTH:-480}" \ +NUM_FRAMES="${NUM_FRAMES:-81}" \ +MAX_TRAIN_STEPS="${MAX_TRAIN_STEPS:-5000}" \ +VAL_INTERVAL="${VAL_INTERVAL:-100}" \ +SAVE_STEPS="${SAVE_STEPS:-200}" \ +PIXEL_L1_WEIGHT="${IMAGE_PIXEL_L1_WEIGHT:-${IMAGE_MSE_WEIGHT:-2.0}}" \ +HF_WEIGHT="${IMAGE_HF_WEIGHT:-0.0}" \ +SOBEL_EDGE_WEIGHT="${IMAGE_SOBEL_EDGE_WEIGHT:-1.0}" \ +SOBEL_EDGE_DILATION_RADIUS="${IMAGE_SOBEL_EDGE_DILATION_RADIUS:-0}" \ +SOBEL_EDGE_THRESHOLD="${IMAGE_SOBEL_EDGE_THRESHOLD:-1.0}" \ +LPIPS_WEIGHT="${IMAGE_LPIPS_WEIGHT:-1.0}" \ +bash "${SCRIPT_DIR}/train_sr_reference.sh" \ + --reference_mode image \ + --default_prompt "a person is speaking" \ + "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image_wavelet.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image_wavelet.sh new file mode 100644 index 0000000000000000000000000000000000000000..f472394ac829c51c79c3a4f15ce4d2bf277d95c5 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image_wavelet.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Train a fresh image-reference Adapter whose K remains the full reference +# hidden state, while V carries reconstructed Haar LH/HL/HH detail features. +# The modest default bias favors detailed reference patches without letting +# background edges overwhelm target/reference correspondence. +WAVELET_VALUE_MODE="${WAVELET_VALUE_MODE:-highpass}" \ +WAVELET_ENERGY_BIAS="${WAVELET_ENERGY_BIAS:-0.50}" \ +WAVELET_ENERGY_CLIP="${WAVELET_ENERGY_CLIP:-3.0}" \ +bash "${SCRIPT_DIR}/train_sr_reference_image.sh" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py new file mode 100644 index 0000000000000000000000000000000000000000..cad06309a4b4786cf6e2536c13fea18e279cf3a7 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py @@ -0,0 +1,828 @@ +"""Train a Wan2.2-TI2V Brownian bridge for video super-resolution. + +This keeps the Wan text prompt branch enabled, removes the UltraFlash latent +upsampler source branch, and follows the Wan2.2 TI2V-style strong anchor: +the first latent temporal index is replaced by the encoded HR reference frame +during training and after every validation sampling step. The TI2V fused +input path additionally gives the first-frame tokens timestep zero, matching +the native Wan2.2 TI2V implementation. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +from pathlib import Path + +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + SeedanceSRDataset, + crop_original_rgb_for_latent_crop, + crop_latent_pair_for_pixel_losses, + decode_latents_to_btchw_01, + default_model_paths, + lpips_video_loss, + pil_video_to_tensor_01, + random_spatial_crop_pair, + tensor_btchw_01_to_pil, + wavelet_hf_loss, +) +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline +from diffsynth.data.video import save_video +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger +from diffsynth.utils import ModelConfig + + +def format_run_value(value: object) -> str: + text = f"{value:g}" if isinstance(value, float) else str(value) + return text.replace(".", "p").replace("-", "m").replace("/", "_") + + +def default_model_paths(base_model_dir: str) -> str: + """Resolve the three files required by a local Wan2.2-TI2V checkpoint.""" + base = Path(base_model_dir) + dit = base / "diffusion_pytorch_model.safetensors.index.json" + if not dit.exists(): + dit = base / "diffusion_pytorch_model.safetensors" + paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.2_VAE.pth"] + for path in paths: + if not path.exists(): + raise FileNotFoundError(f"Missing Wan2.2-TI2V model file: {path}") + return ",".join(str(path) for path in paths) + + +def build_run_name(args) -> str: + parts = [ + "wan22_ti2v_sr_ffanchor", + f"x{args.sr_scale}", + f"{args.height}x{args.width}", + f"f{args.num_frames}", + "bicubic", + "prompt", + "relock" if args.anchor_each_step else "initanchor", + f"lr{format_run_value(args.learning_rate)}", + f"noise{format_run_value(args.noise_sigma)}", + f"bridge{format_run_value(args.bridge_loss_weight)}", + f"lpips{format_run_value(args.lpips_weight)}", + f"ssim{format_run_value(args.ssim_weight)}", + f"wav{format_run_value(args.wavelet_hf_weight)}", + f"pix{format_run_value(args.pixel_loss_weight)}", + f"pcrop{args.pixel_loss_crop_size}", + f"plf{args.pixel_loss_latent_frames}", + f"seed{args.seed}", + ] + return "_".join(parts) + + +class FirstFrameAnchorSRDataset(SeedanceSRDataset): + """Bicubic-upsampled SR source whose first frame is replaced by HR reference.""" + + def __init__(self, *args, **kwargs) -> None: + kwargs["source_mode"] = "bicubic" + super().__init__(*args, **kwargs) + + def __getitem__(self, idx: int) -> dict: + item = super().__getitem__(idx) + reference = item["video"][0].copy() + item["source_video"][0] = reference.copy() + item["reference_image"] = reference + return item + + +def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor: + if anchor is None: + return latents + if anchor.shape[2] != 1: + raise ValueError(f"first_frame_latents must have exactly one latent frame, got {tuple(anchor.shape)}") + if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]: + raise ValueError( + f"anchor shape {tuple(anchor.shape)} is incompatible with latents {tuple(latents.shape)}" + ) + out = latents.clone() + out[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype) + return out + + +def drop_first_time_frame_btchw(video: torch.Tensor) -> torch.Tensor: + if video.shape[1] <= 1: + return video[:, :0] + return video[:, 1:] + + +def drop_first_time_frame_bcthw(latents: torch.Tensor) -> torch.Tensor: + if latents.shape[2] <= 1: + return latents[:, :, :0] + return latents[:, :, 1:] + + +def drop_global_first_frame_from_crop_btchw(video: torch.Tensor, crop_info: dict) -> torch.Tensor: + if int(crop_info.get("start_t", 0)) != 0: + return video + return drop_first_time_frame_btchw(video) + + +def mse_after_first_latent_frame(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + pred_main = drop_first_time_frame_bcthw(pred) + target_main = drop_first_time_frame_bcthw(target) + if pred_main.numel() == 0: + return pred.new_tensor(0.0) + return F.mse_loss(pred_main.float(), target_main.float()) + + +def choose_chunk_bounds(total_latent_frames: int, chunk_latent_frames: int, history_latent_frames: int): + if total_latent_frames <= 1: + raise ValueError("A video must contain at least one future latent frame") + chunk = min(max(int(chunk_latent_frames), 1), total_latent_frames - 1) + max_start = total_latent_frames - chunk + start = random.randint(1, max_start) if max_start > 1 else 1 + history_start = max(1, start - max(int(history_latent_frames), 0)) + return history_start, start, start + chunk + + +def chunk_rgb_target(frames: list[Image.Image], history_start: int, start: int, end: int) -> list[Image.Image]: + """Map Wan2.2 latent indices back to RGB frames (latent 0 is RGB frame 0).""" + prefix = [frames[0]] + if start > history_start: + prefix.extend(frames[4 * history_start - 3:4 * start - 3]) + current = frames[4 * start - 3:4 * end - 3] + return prefix + current + + +def crop_current_rgb_for_latent_region( + frames: list[Image.Image], + latent_start: int, + latent_count: int, + crop_info: dict, + device: torch.device, +) -> torch.Tensor: + rgb_start = 4 * latent_start - 3 + rgb_end = rgb_start + 4 * latent_count + current = pil_video_to_tensor_01(frames[rgb_start:rgb_end], device).unsqueeze(0) + vae_factor_h = current.shape[-2] // int(crop_info["full_h"]) + vae_factor_w = current.shape[-1] // int(crop_info["full_w"]) + top = int(crop_info["start_h"]) * vae_factor_h + left = int(crop_info["start_w"]) * vae_factor_w + height = int(crop_info["crop_h"]) * vae_factor_h + width = int(crop_info["crop_w"]) * vae_factor_w + return current[..., top:top + height, left:left + width] + + +def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + if min_t <= 0: + return pred_btchw_01.new_tensor(0.0) + pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float() + target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float() + channels = pred.shape[1] + window_size = max(1, int(window_size)) + if window_size % 2 == 0: + window_size += 1 + padding = window_size // 2 + weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size) + + mu_x = F.conv2d(pred, weight, padding=padding, groups=channels) + mu_y = F.conv2d(target, weight, padding=padding, groups=channels) + mu_x_sq = mu_x.square() + mu_y_sq = mu_y.square() + mu_xy = mu_x * mu_y + + sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq + sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy + + c1 = 0.01 ** 2 + c2 = 0.03 ** 2 + ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / ( + (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8 + ) + return (1.0 - ssim.clamp(-1.0, 1.0)).mean() + + +class FirstFrameAnchorWanVideoSRBridgePipeline(WanVideoBridgePipeline): + def training_loss(self, **inputs): + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps) + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + anchor_each_step = bool(inputs.get("anchor_each_step", True)) + + anchor = inputs.get("first_frame_latents") + full_x0 = replace_first_latent_frame(inputs["input_latents"], anchor) + full_x1 = replace_first_latent_frame(inputs["source_latents"], anchor) + noise = inputs["noise"] + history_start, current_start, current_end = choose_chunk_bounds( + full_x0.shape[2], + int(inputs.get("chunk_latent_frames", 4)), + int(inputs.get("history_latent_frames", 2)), + ) + history = full_x0[:, :, history_start:current_start].detach() + current_x0 = full_x0[:, :, current_start:current_end] + current_x1 = full_x1[:, :, current_start:current_end] + current_noise = noise[:, :, current_start:current_end] + current_xt = self.scheduler.add_noise(current_x0, current_x1, current_noise, timestep) + x0 = torch.cat([anchor, history, current_x0], dim=2) + x1 = torch.cat([anchor, history, current_x1], dim=2) + xt = torch.cat([anchor, history, current_xt], dim=2) + prefix_frames = 1 + history.shape[2] + + model_inputs = dict(inputs) + model_inputs["latents"] = xt + model_inputs["input_latents"] = x0 + model_inputs["source_latents"] = x1 + model_inputs.pop("first_frame_latents", None) + model_inputs["clean_history_latent_frames"] = int(history.shape[2]) + + target = self.scheduler.training_target(current_x0, current_xt, timestep) + model_output = self.model_fn(**model_inputs, timestep=timestep) + + if self.scheduler.target == "stabilized_drift": + sigma = self.scheduler.get_sigma(timestep) + factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5 + velocity_target = target / factor + velocity_for_endpoint = model_output[:, :, prefix_frames:] * factor + elif self.scheduler.target == "drift": + velocity_target = target + velocity_for_endpoint = model_output[:, :, prefix_frames:] + else: + raise ValueError("First-frame-anchor SR bridge training supports --target stabilized_drift or drift") + + bridge_loss = F.mse_loss( + model_output[:, :, prefix_frames:].float(), velocity_target.float() + ) + total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss + metrics = { + "bridge_loss": float(bridge_loss.detach().cpu()), + "lpips_loss": 0.0, + "ssim_loss": 0.0, + "wavelet_hf_loss": 0.0, + "pixel_loss": 0.0, + } + + lpips_model = inputs.get("lpips_model") + lpips_weight = float(inputs.get("lpips_weight", 0.0)) + ssim_weight = float(inputs.get("ssim_weight", 0.0)) + wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0)) + pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0)) + if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0: + sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + endpoint_current = current_xt.float() - sigma * velocity_for_endpoint.float() + loss_latent_frames = min( + max(int(inputs.get("pixel_loss_latent_frames", 3)), 1), + endpoint_current.shape[2], + ) + max_loss_start = endpoint_current.shape[2] - loss_latent_frames + loss_start = ( + int(torch.randint(max_loss_start + 1, (1,), device=endpoint_current.device).item()) + if max_loss_start > 0 else 0 + ) + global_loss_start = current_start + loss_start + endpoint_loss = endpoint_current[:, :, loss_start:loss_start + loss_latent_frames] + target_loss = current_x0[:, :, loss_start:loss_start + loss_latent_frames].detach() + # Prepend one clean GT latent as causal VAE context. It is removed + # after decoding, while the current region retains all 4 RGB frames + # per latent index. + context_latent = full_x0[:, :, global_loss_start - 1:global_loss_start].detach() + endpoint_decode = torch.cat([context_latent, endpoint_loss], dim=2) + target_decode = torch.cat([context_latent, target_loss], dim=2) + endpoint_decode, _, crop_info = crop_latent_pair_for_pixel_losses( + endpoint_decode, + target_decode, + crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 400)), + latent_frames=0, + vae_factor=int(getattr(self.vae, "upsampling_factor", 16)), + return_crop_info=True, + ) + pred_video = decode_latents_to_btchw_01( + self, + endpoint_decode, + tiled=bool(inputs.get("tiled", False)), + tile_size=inputs.get("tile_size", (30, 52)), + tile_stride=inputs.get("tile_stride", (15, 26)), + ) + raw_target_video = inputs.get("raw_target_video") + if raw_target_video is None: + raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses") + pred_video_main = pred_video[:, 1:] + target_video_main = crop_current_rgb_for_latent_region( + raw_target_video, + global_loss_start, + loss_latent_frames, + crop_info, + self.device, + ) + if lpips_weight > 0: + if lpips_model is None: + raise ValueError("lpips_model is required when lpips_weight > 0") + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = lpips_video_loss( + lpips_model, + pred_video_main, + target_video_main, + num_frames=int(inputs.get("lpips_num_frames", 4)), + crop_size=int(inputs.get("lpips_crop_size", 224)), + ) + total_loss = total_loss + lpips_weight * loss + metrics["lpips_loss"] = float(loss.detach().cpu()) + if ssim_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = ssim_video_loss( + pred_video_main, + target_video_main, + window_size=int(inputs.get("ssim_window_size", 11)), + ) + total_loss = total_loss + ssim_weight * loss + metrics["ssim_loss"] = float(loss.detach().cpu()) + if wavelet_hf_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = wavelet_hf_loss( + pred_video_main, + target_video_main, + levels=int(inputs.get("wavelet_hf_levels", 1)), + loss_type=str(inputs.get("wavelet_hf_loss", "l1")), + ) + total_loss = total_loss + wavelet_hf_weight * loss + metrics["wavelet_hf_loss"] = float(loss.detach().cpu()) + if pixel_loss_weight > 0: + if pred_video_main.shape[1] == 0: + loss = pred_video.new_tensor(0.0) + else: + loss = F.mse_loss(pred_video_main.float(), target_video_main.float()) + total_loss = total_loss + pixel_loss_weight * loss + metrics["pixel_loss"] = float(loss.detach().cpu()) + + return total_loss, metrics + + +class FirstFrameAnchorSRTrainingModule(DiffusionTrainingModule): + def __init__(self, args): + super().__init__() + model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe: FirstFrameAnchorWanVideoSRBridgePipeline = ( + FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cpu", + model_configs=model_configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + ) + self.pipe.latent_upsampler = None + if not getattr(self.pipe.dit, "fuse_vae_embedding_in_latents", False): + raise RuntimeError( + "The loaded DiT is not Wan2.2-TI2V fused-input compatible. " + "Use the Wan2.2-TI2V-5B checkpoint and its 48-channel VAE." + ) + if int(getattr(self.pipe.vae, "z_dim", 0)) != 48: + raise RuntimeError( + f"Expected Wan2.2-TI2V VAE z_dim=48, got {getattr(self.pipe.vae, 'z_dim', None)}" + ) + print( + "[Wan22TI2VBridge] source=bicubic_upscale_with_hr_first_frame " + "text=prompt fused_vae_input=true first_frame_timestep=0 anchor=strong" + ) + self.switch_pipe_to_training_mode( + self.pipe, + args.trainable_models, + args.lora_base_model, + args.lora_target_modules, + args.lora_rank, + lora_checkpoint=args.lora_checkpoint, + enable_fp8_training=False, + ) + self.args = args + if args.lpips_weight > 0 or args.val_lpips: + import lpips + + self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False) + else: + self.lpips_model = None + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + if self.lpips_model is not None: + self.lpips_model.to(*args, **kwargs) + return self + + def _encode_first_frame_anchor(self, reference_image: Image.Image) -> torch.Tensor: + self.pipe.load_models_to_device(["vae"]) + reference_video = self.pipe.preprocess_video([reference_image]) + anchor = self.pipe.vae.encode( + reference_video, + device=self.pipe.device, + tiled=self.args.tiled, + tile_size=(self.args.tile_h, self.args.tile_w), + tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w), + ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + if anchor.shape[2] != 1: + raise ValueError(f"Expected reference image to encode to one latent frame, got {tuple(anchor.shape)}") + return anchor + + def forward_preprocess(self, data): + prompt = data["prompt"] + if random.random() < self.args.text_drop_probability: + prompt = " " + inputs_posi = {"prompt": prompt} + inputs_nega = {} + inputs_shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + "cfg_scale": 1, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + "anchor_each_step": self.args.anchor_each_step, + # Wan2.2-TI2V model_fn expands this scalar to per-token timesteps: + # frame-0 tokens receive zero and future tokens receive t. + "fuse_vae_embedding_in_latents": True, + "chunk_latent_frames": self.args.chunk_latent_frames, + "history_latent_frames": self.args.history_latent_frames, + "max_timestep_boundary": self.args.max_timestep_boundary, + "min_timestep_boundary": self.args.min_timestep_boundary, + "bridge_loss_weight": self.args.bridge_loss_weight, + "lpips_weight": self.args.lpips_weight, + "lpips_model": self.lpips_model, + "lpips_num_frames": self.args.lpips_num_frames, + "lpips_crop_size": self.args.lpips_crop_size, + "ssim_weight": self.args.ssim_weight, + "ssim_window_size": self.args.ssim_window_size, + "pixel_loss_crop_size": self.args.pixel_loss_crop_size, + "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames, + "wavelet_hf_weight": self.args.wavelet_hf_weight, + "wavelet_hf_levels": self.args.wavelet_hf_levels, + "wavelet_hf_loss": self.args.wavelet_hf_loss, + "pixel_loss_weight": self.args.pixel_loss_weight, + } + for unit in self.pipe.units: + inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner( + unit, self.pipe, inputs_shared, inputs_posi, inputs_nega + ) + inputs_shared["first_frame_latents"] = self._encode_first_frame_anchor(data["reference_image"]) + inputs_shared["raw_target_video"] = data["video"] + return {**inputs_shared, **inputs_posi} + + def forward(self, data, inputs=None): + if inputs is None: + inputs = self.forward_preprocess(data) + return self.pipe.training_loss( + **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}, + **inputs, + ) + + +class FirstFrameAnchorModelLogger(ModelLogger): + def on_step_end(self, accelerator, model, save_steps=None): + super().on_step_end(accelerator, model, save_steps) + + +@torch.no_grad() +def sample_chunked_latents(pipe, inputs: dict, args) -> torch.Tensor: + """Validation sampler matching inference: clean reference/history, noisy current.""" + anchor = inputs["first_frame_latents"] + source_full = replace_first_latent_frame(inputs["source_latents"], anchor) + generated = anchor.clone() + pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift) + pipe.load_models_to_device(pipe.in_iteration_models) + models = {name: getattr(pipe, name) for name in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("first_frame_latents", None) + model_inputs["fuse_vae_embedding_in_latents"] = True + + for current_start in range(1, source_full.shape[2], args.chunk_latent_frames): + current_end = min(source_full.shape[2], current_start + args.chunk_latent_frames) + history = generated[:, :, max(1, generated.shape[2] - args.history_latent_frames):].detach() + chunk_source = torch.cat([anchor, history, source_full[:, :, current_start:current_end]], dim=2) + latents = chunk_source.clone() + history_len = history.shape[2] + clean_prefix = torch.cat([anchor, history], dim=2) + model_inputs["source_latents"] = chunk_source + model_inputs["clean_history_latent_frames"] = history_len + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, chunk_source) + latents[:, :, :1 + history_len] = clean_prefix + generated = torch.cat([generated, latents[:, :, 1 + history_len:].detach()], dim=2) + return generated + + +@torch.no_grad() +def validate(args, accelerator: Accelerator, model: FirstFrameAnchorSRTrainingModule, dataset: Dataset, step: int) -> dict: + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + pipe.eval() + backup_scheduler = pipe.scheduler + pipe.scheduler = copy.deepcopy(backup_scheduler) + pipe.scheduler.noise_scale = args.val_sampling_noise_scale + pipe.scheduler.target = args.target + + rows = [] + out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}" + out_dir.mkdir(parents=True, exist_ok=True) + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + pipe.scheduler.set_timesteps(1000, training=True) + inputs = module.forward_preprocess(data) + x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"]) + x1 = replace_first_latent_frame(inputs["source_latents"], inputs["first_frame_latents"]) + latents = sample_chunked_latents(pipe, inputs, args) + + pred_video = decode_latents_to_btchw_01( + pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w) + ) + target_video = decode_latents_to_btchw_01( + pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w) + ) + if args.anchor_each_step: + pred_video_main = drop_first_time_frame_btchw(pred_video) + target_video_main = drop_first_time_frame_btchw(target_video) + else: + pred_video_main = pred_video + target_video_main = target_video + source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0) + target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0) + min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1]) + strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1) + save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(strip[0]), str(out_dir / f"val_{idx:03d}_source_pred_target.mp4"), fps=args.fps, quality=5) + data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png") + + row = { + "idx": idx, + "latent_mse": ( + mse_after_first_latent_frame(latents, x0).item() + if args.anchor_each_step + else F.mse_loss(latents.float(), x0.float()).item() + ), + "pixel_mse": ( + F.mse_loss(pred_video_main.float(), target_video_main.float()).item() + if pred_video_main.shape[1] > 0 + else 0.0 + ), + "anchor_latent_mse": F.mse_loss( + latents[:, :, :1].float(), inputs["first_frame_latents"].float() + ).item(), + } + if module.lpips_model is not None and args.val_lpips: + row["lpips"] = float( + lpips_video_loss( + module.lpips_model, + pred_video_main, + target_video_main, + args.lpips_num_frames, + args.lpips_crop_size, + ).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + if args.val_ssim or args.ssim_weight > 0: + row["ssim"] = float( + ssim_video_loss(pred_video_main, target_video_main, args.ssim_window_size).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + if args.val_wavelet_hf_loss: + row["wavelet_hf"] = float( + wavelet_hf_loss(pred_video_main, target_video_main, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu() + ) if pred_video_main.shape[1] > 0 else 0.0 + rows.append(row) + + pipe.scheduler = backup_scheduler + metrics = {} + if rows: + for key in rows[0]: + if key != "idx": + metrics[f"val_{key}"] = float( + sum(row[key] for row in rows if key in row) / max(sum(1 for row in rows if key in row), 1) + ) + (out_dir / "metrics.json").write_text( + json.dumps( + { + "step": step, + "rows": rows, + "metrics": metrics, + "pipeline": "bicubic_source_hr_first_frame_strong_latent_anchor_with_prompt", + "anchor_each_step": args.anchor_each_step, + }, + indent=2, + ), + encoding="utf-8", + ) + print(f"[Validation step {step}] {metrics}") + pipe.train() + return metrics + + +def build_dataset(args, repeat: int, limit_videos: int | None, seed: int) -> FirstFrameAnchorSRDataset: + return FirstFrameAnchorSRDataset( + args.video_dir, + args.prompt_json, + args.prompt_field, + args.default_prompt, + args.height, + args.width, + args.num_frames, + args.sr_scale, + repeat=repeat, + limit_videos=limit_videos, + seed=seed, + ) + + +def train(args): + save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None + if args.output_path is None: + args.output_path = str(Path(args.output_root) / build_run_name(args)) + train_set = build_dataset( + args, + repeat=args.dataset_repeat, + limit_videos=args.limit_videos, + seed=args.seed, + ) + val_set = build_dataset( + args, + repeat=1, + limit_videos=max(args.val_batches, 1), + seed=args.seed + 1, + ) + model = FirstFrameAnchorSRTrainingModule(args) + model.pipe.scheduler.noise_scale = args.noise_sigma + model.pipe.scheduler.bridge_type = "brownian" + model.pipe.scheduler.training_weight_type = args.training_weight_type + model.pipe.scheduler.target = args.target + print("Scheduler noise scale:", model.pipe.scheduler.noise_scale) + print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type) + print("Scheduler target:", model.pipe.scheduler.target) + + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + print(f"[Output] {args.output_path}") + + if args.validation_only or args.max_train_steps <= 0: + model = accelerator.prepare(model) + validate(args, accelerator, model, val_set, 0) + return + + from prodigyopt import Prodigy + + optimizer = Prodigy( + model.trainable_modules(), + lr=args.learning_rate, + weight_decay=args.weight_decay, + safeguard_warmup=True, + d_coef=args.d_coef, + ) + dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers) + model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + logger = FirstFrameAnchorModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt) + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + + global_step = 0 + while global_step < args.max_train_steps: + for data in tqdm(dataloader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad() + loss, metrics = model(data) + accelerator.backward(loss) + if args.max_grad_norm > 0: + accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step() + global_step += 1 + gathered_loss = accelerator.gather(loss.detach()).mean().item() + if accelerator.is_main_process and global_step % args.log_interval == 0: + print( + f"[Train step {global_step}] loss={gathered_loss:.6f} " + f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} " + f"ssim={metrics['ssim_loss']:.6f} " + f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}" + ) + logger.on_step_end(accelerator, model, save_steps) + if args.val_interval > 0 and global_step % args.val_interval == 0: + validate(args, accelerator, model, val_set, global_step) + if global_step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, save_steps) + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Train a Wan2.2-TI2V Brownian-Bridge SR model with strong first-frame latent anchoring." + ) + parser.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl") + parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p") + parser.add_argument("--default_prompt", default="") + parser.add_argument("--output_root", default="/cache/outputs_bridge_wan22_ti2v_sr") + parser.add_argument("--output_path", default=None) + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--chunk_latent_frames", type=int, default=4, + help="Number of current Wan2.2 latent frames trained per chunk.") + parser.add_argument("--history_latent_frames", type=int, default=2, + help="Number of clean GT history latent frames used as teacher-forcing context.") + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--limit_videos", type=int, default=None) + parser.add_argument("--dataset_repeat", type=int, default=1) + parser.add_argument("--dataset_num_workers", type=int, default=0) + parser.add_argument("--trainable_models", default="dit") + parser.add_argument("--lora_base_model", default=None) + parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2") + parser.add_argument("--lora_rank", type=int, default=32) + parser.add_argument("--lora_checkpoint", default=None) + parser.add_argument("--learning_rate", type=float, default=1.0) + parser.add_argument("--weight_decay", type=float, default=0.01) + parser.add_argument("--d_coef", type=float, default=1.0) + parser.add_argument("--max_train_steps", type=int, default=5000) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--max_grad_norm", type=float, default=1.0) + parser.add_argument("--save_steps", type=int, default=500) + parser.add_argument("--log_interval", type=int, default=1) + parser.add_argument("--val_interval", type=int, default=100) + parser.add_argument("--val_batches", type=int, default=1) + parser.add_argument("--validate_at_start", action="store_true", default=False) + parser.add_argument("--validation_only", action="store_true", default=False) + parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.") + parser.add_argument("--noise_sigma", type=float, default=1.0) + parser.add_argument("--training_weight_type", default="uniform") + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--bridge_loss_weight", type=float, default=1.0) + parser.add_argument("--lpips_weight", type=float, default=1.0) + parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg") + parser.add_argument("--lpips_num_frames", type=int, default=4) + parser.add_argument("--lpips_crop_size", type=int, default=400) + parser.add_argument("--ssim_weight", type=float, default=0.0) + parser.add_argument("--ssim_window_size", type=int, default=11) + parser.add_argument("--val_ssim", action="store_true", default=False) + parser.add_argument("--pixel_loss_crop_size", type=int, default=400) + parser.add_argument("--pixel_loss_latent_frames", type=int, default=3) + parser.add_argument("--val_lpips", action="store_true", default=False) + parser.add_argument("--wavelet_hf_weight", type=float, default=50.0) + parser.add_argument("--wavelet_hf_levels", type=int, default=1) + parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1") + parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False) + parser.add_argument("--pixel_loss_weight", type=float, default=4.0) + parser.add_argument("--val_inference_steps", type=int, default=1) + parser.add_argument("--val_sampling_noise_scale", type=float, default=1.0) + parser.add_argument("--val_sigma_shift", type=float, default=5.0) + parser.add_argument("--max_timestep_boundary", type=float, default=0.9999) + parser.add_argument("--min_timestep_boundary", type=float, default=0.0001) + parser.add_argument("--text_drop_probability", type=float, default=0.0) + parser.add_argument( + "--anchor_each_step", + action=argparse.BooleanOptionalAction, + default=True, + help="Compatibility flag. This chunked TI2V trainer always keeps reference/history clean and re-locks them every step.", + ) + parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True) + parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False) + parser.add_argument("--find_unused_parameters", action="store_true", default=False) + parser.add_argument("--tiled", action="store_true", default=False) + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + if not args.anchor_each_step: + raise ValueError("Wan2.2-TI2V clean-history chunk training requires --anchor_each_step") + if args.model_paths is None: + args.model_paths = default_model_paths(args.base_model_dir) + return args + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..748aa71be210edb6c79ff394cc6b755999bd6727 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +ARGS=( + diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py + --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \ + --tokenizer_path "${TOKENIZER_PATH:-/cache/Wan2.2-TI2V-5B/google/umt5-xxl}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + --output_root "${OUTPUT_ROOT:-/cache/rongxiang/outputs_chunkbridge_wan22_ti2v_sr}" \ + --height "${HEIGHT:-480}" \ + --width "${WIDTH:-832}" \ + --num_frames "${NUM_FRAMES:-81}" \ + --chunk_latent_frames "${CHUNK_LATENT_FRAMES:-4}" \ + --history_latent_frames "${HISTORY_LATENT_FRAMES:-2}" \ + --sr_scale "${SR_SCALE:-2}" \ + --dataset_repeat "${DATASET_REPEAT:-1}" \ + --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \ + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --learning_rate "${LEARNING_RATE:-1.0}" \ + --weight_decay "${WEIGHT_DECAY:-0.01}" \ + --d_coef "${D_COEF:-1.0}" \ + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \ + --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --lpips_net "${LPIPS_NET:-vgg}" \ + --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \ + --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \ + --ssim_weight "${SSIM_WEIGHT:-1.0}" \ + --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \ + --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \ + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \ + --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-0.0}" \ + --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \ + --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \ + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-4.0}" \ + --noise_sigma "${NOISE_SIGMA:-1.0}" \ + --val_interval "${VAL_INTERVAL:-100}" \ + --val_batches "${VAL_BATCHES:-1}" \ + --val_inference_steps "${VAL_INFERENCE_STEPS:-8}" \ + --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}" \ + --save_steps "${SAVE_STEPS:-500}" \ + --validate_at_start +) + +if [[ -n "${LIMIT_VIDEOS:-}" ]]; then + ARGS+=(--limit_videos "${LIMIT_VIDEOS}") +fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then + ARGS+=(--output_path "${OUTPUT_PATH}") +fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..accbac7536b7c1c8f731ed404116f4964eaef84d --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py @@ -0,0 +1,1015 @@ +"""Train a Wan2.1 Brownian bridge for tiny-ditto video editing. + +The clean edited clip is the bridge target. The coarse edited clip is the +bridge source. Original reference latents are concatenated with the current +bridge latents along channels; there is no reference token prefix. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +import sys +from collections import Counter +from pathlib import Path + +import imageio +import numpy as np +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402 + center_crop_resize, + crop_latent_pair_for_pixel_losses, + crop_original_rgb_for_latent_crop, + decode_latents_to_btchw_01, + lpips_video_loss, + make_lr_source, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, +) +from diffsynth.data.video import save_video # noqa: E402 +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger # noqa: E402 +from diffsynth.utils import ModelConfig # noqa: E402 + +try: + import torch_npu # noqa: F401 +except ModuleNotFoundError: + torch_npu = None + + +def format_run_value(value: object) -> str: + text = f"{value:g}" if isinstance(value, float) else str(value) + return text.replace(".", "p").replace("-", "m").replace("/", "_") + + +def default_model_paths(base_model_dir: str) -> str: + base = Path(base_model_dir) + dit = base / "diffusion_pytorch_model.safetensors.index.json" + if not dit.exists(): + dit = base / "diffusion_pytorch_model.safetensors" + paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.1_VAE.pth"] + missing = [str(p) for p in paths if not p.exists()] + if missing: + raise FileNotFoundError("Missing Wan2.1-T2V files: " + ", ".join(missing)) + return ",".join(str(p) for p in paths) + + +def load_dit_init_state(path: str | os.PathLike) -> dict[str, torch.Tensor]: + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if isinstance(checkpoint, dict) and "model" in checkpoint: + checkpoint = checkpoint["model"] + elif isinstance(checkpoint, dict) and "state_dict" in checkpoint: + checkpoint = checkpoint["state_dict"] + if not isinstance(checkpoint, dict) or not all(torch.is_tensor(value) for value in checkpoint.values()): + raise ValueError(f"Unsupported DiT initialization checkpoint: {path}") + return { + str(key).removeprefix("module.").removeprefix("model."): value + for key, value in checkpoint.items() + } + + +def configure_dit_channel_concat(pipe, checkpoint_path: str | None) -> None: + """Load UltraFlash's 32-channel weights for [bridge latent, reference].""" + dit = pipe.dit + current_in_dim = int(getattr(dit, "in_dim", 0)) + if current_in_dim != 32: + if current_in_dim != 16: + raise RuntimeError( + f"Expected a 16-channel Wan DiT before adaptation, got in_dim={current_in_dim}" + ) + old_embedding = dit.patch_embedding + new_embedding = torch.nn.Conv3d( + 32, + old_embedding.out_channels, + kernel_size=old_embedding.kernel_size, + stride=old_embedding.stride, + padding=old_embedding.padding, + dilation=old_embedding.dilation, + groups=old_embedding.groups, + bias=old_embedding.bias is not None, + ).to(device=old_embedding.weight.device, dtype=old_embedding.weight.dtype) + with torch.no_grad(): + new_embedding.weight[:, :16].copy_(old_embedding.weight) + new_embedding.weight[:, 16:].copy_(old_embedding.weight) + if old_embedding.bias is not None: + new_embedding.bias.copy_(old_embedding.bias) + dit.patch_embedding = new_embedding + dit.in_dim = 32 + if checkpoint_path: + init_state = load_dit_init_state(checkpoint_path) + result = dit.load_state_dict(init_state, strict=True) + if result.missing_keys or result.unexpected_keys: + raise RuntimeError( + f"DiT initialization mismatch for {checkpoint_path}: " + f"missing={result.missing_keys[:8]}, unexpected={result.unexpected_keys[:8]}" + ) + print(f"[TinyDittoEdit] loaded 32-channel DiT initialization: {checkpoint_path}", flush=True) + + +def normalize_wan_num_frames(num_frames: int) -> int: + num_frames = max(int(num_frames), 1) + if num_frames % 4 == 1: + return num_frames + return ((num_frames - 1 + 3) // 4) * 4 + 1 + + +def resolve_media_path(root: Path, rel_path: str, recursive_fallback: bool = True) -> Path: + path = Path(rel_path) + if path.is_absolute() and path.exists(): + return path + candidate = root / path + if candidate.exists(): + return candidate + if not recursive_fallback: + raise FileNotFoundError(f"Missing tiny-ditto media file: {candidate}") + matches = sorted(root.rglob(path.name)) + if matches: + preferred = [match for match in matches if path.parts and path.parts[0] in match.parts] + return preferred[0] if preferred else matches[0] + raise FileNotFoundError(f"Missing tiny-ditto media file: {candidate}") + + +def load_tiny_ditto_manifest( + manifest_path: str, + limit: int | None = None, + dataset_root: str | Path | None = None, +) -> list[dict]: + path = Path(manifest_path) + if not path.exists(): + raise FileNotFoundError(f"Missing tiny-ditto manifest: {path}") + + if path.is_dir(): + root = Path(dataset_root) if dataset_root is not None else None + videos_dir = root / "videos" if root is not None else None + if videos_dir is not None and videos_dir.is_dir(): + # GOKU ships metadata for more cases than may be extracted locally. + # Build the manifest list from available case directories so missing + # archives never trigger repeated recursive media searches. + manifest_files = [ + path / f"{case_dir.name}_all.json" + for case_dir in sorted(videos_dir.iterdir()) + if case_dir.is_dir() + and (case_dir / "source.mp4").is_file() + and (case_dir / "edited.mp4").is_file() + ] + manifest_files = [manifest_file for manifest_file in manifest_files if manifest_file.is_file()] + else: + manifest_files = sorted(path.rglob("*.json")) + if not manifest_files: + raise FileNotFoundError(f"No JSON manifests found under {path}") + if limit is not None: + manifest_files = manifest_files[: max(int(limit), 0)] + items = [] + for manifest_file in manifest_files: + value = json.loads(manifest_file.read_text(encoding="utf-8")) + if isinstance(value, list): + items.extend(value) + elif isinstance(value, dict): + items.append(value) + elif path.suffix.lower() == ".jsonl": + items = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + else: + items = json.loads(path.read_text(encoding="utf-8")) + if isinstance(items, dict): + items = [items] + if not isinstance(items, list): + raise ValueError(f"tiny-ditto manifest must contain JSON objects or a list: {path}") + samples = [] + for item in items: + if not isinstance(item, dict): + continue + source_path = item.get("source_path") or item.get("source_video") + edited_path = item.get("edited_path") or item.get("edited_video") + instruction = str( + item.get("instruction") + or item.get("prompt") + or item.get("instruction_en") + or item.get("instruction_cn") + or "" + ).strip() + if source_path and edited_path: + samples.append( + { + "source_path": str(source_path), + "edited_path": str(edited_path), + "instruction": instruction, + "task": str(item.get("task") or item.get("category") or "unknown").strip() or "unknown", + } + ) + if not samples: + raise ValueError(f"No valid source/edited pairs found in {path}") + return samples + + +def probe_video_readable(path: Path) -> bool: + try: + reader = imageio.get_reader(str(path)) + except (OSError, RuntimeError, ValueError): + return False + try: + reader.get_data(0) + return True + except (OSError, RuntimeError, ValueError): + return False + finally: + reader.close() + + +def read_video_clip(path: Path, height: int, width: int, num_frames: int, start: int) -> list[Image.Image]: + reader = imageio.get_reader(str(path)) + frames = [] + last = None + try: + for frame_id in range(start, start + num_frames): + try: + array = reader.get_data(frame_id) + last = array + except Exception: + if last is None: + break + array = last + image = Image.fromarray(np.asarray(array)).convert("RGB") + frames.append(center_crop_resize(image, height, width)) + finally: + reader.close() + if not frames: + raise RuntimeError(f"No frames decoded from {path}") + while len(frames) < num_frames: + frames.append(frames[-1].copy()) + return frames + + +class TinyDittoEditDataset(Dataset): + def __init__( + self, + dataset_root: str, + manifest_path: str, + height: int, + width: int, + num_frames: int, + sr_scale: int, + default_prompt: str = "", + repeat: int = 1, + limit_samples: int | None = None, + seed: int = 0, + ) -> None: + self.dataset_root = Path(dataset_root) + self.height = int(height) + self.width = int(width) + self.num_frames = int(num_frames) + self.sr_scale = int(sr_scale) + self.default_prompt = default_prompt + self.repeat = int(repeat) + self.rng = random.Random(seed) + manifest_path_obj = Path(manifest_path) + samples = load_tiny_ditto_manifest( + manifest_path, + limit=limit_samples, + dataset_root=self.dataset_root, + ) + self.samples = [] + missing_samples = 0 + task_counts = Counter() + missing_examples = [] + for sample in samples: + try: + # The OpenVE manifest stores paths relative to dataset_root. + # Keep the fallback for older per-case GOKU manifests. + source_path = resolve_media_path(self.dataset_root, sample["source_path"]) + edited_path = resolve_media_path(self.dataset_root, sample["edited_path"]) + except FileNotFoundError: + missing_samples += 1 + if len(missing_examples) < 3: + missing_examples.append( + (sample["source_path"], sample["edited_path"]) + ) + continue + task = sample.get("task", "unknown") + task_counts[task] += 1 + self.samples.append( + { + "source_path": source_path, + "edited_path": edited_path, + "instruction": sample["instruction"] or self.default_prompt, + "task": task, + } + ) + if missing_samples: + print( + f"[TinyDittoEditDataset] skipped {missing_samples} samples with missing media; " + f"examples={missing_examples}", + flush=True, + ) + self.rng.shuffle(self.samples) + if limit_samples is not None: + self.samples = self.samples[: int(limit_samples)] + if not self.samples: + raise FileNotFoundError(f"No tiny-ditto pairs found under {self.dataset_root}") + if manifest_path_obj.name == "metadata.json" and (self.dataset_root / ".complete").is_file(): + summary_path = self.dataset_root / "summary.json" + if summary_path.is_file(): + summary = json.loads(summary_path.read_text(encoding="utf-8")) + expected = int(summary.get("num_samples", len(samples))) + if limit_samples is None and expected != len(samples): + raise ValueError( + f"Dataset summary expects {expected} samples but manifest has {len(samples)}: " + f"{manifest_path_obj}" + ) + print( + f"[TinyDittoEditDataset] OpenVE tasks={dict(sorted(task_counts.items()))}", + flush=True, + ) + else: + print( + f"[TinyDittoEditDataset] warning: missing dataset summary {summary_path}", + flush=True, + ) + print( + f"[TinyDittoEditDataset] manifest_entries={len(samples)}, " + f"usable_pairs={len(self.samples)}, repeat={self.repeat}, " + f"root={self.dataset_root}, manifest={manifest_path_obj}", + flush=True, + ) + + def __len__(self) -> int: + return len(self.samples) * self.repeat + + def __getitem__(self, idx: int) -> dict: + for attempt in range(len(self.samples)): + sample = self.samples[(idx + attempt) % len(self.samples)] + # GOKU clips are already short clips. Avoid full-frame-count probing + # here because imageio's count_frames launches a complete FFmpeg scan. + start = 0 + try: + reference_video = read_video_clip(sample["source_path"], self.height, self.width, self.num_frames, start) + target_video = read_video_clip(sample["edited_path"], self.height, self.width, self.num_frames, start) + except (OSError, RuntimeError, ValueError): + continue + source_video = [ + make_lr_source(frame, self.height, self.width, self.sr_scale, upsample_to_hr=False) + for frame in target_video + ] + return { + "video": target_video, + "source_video": source_video, + "reference_video": reference_video, + "prompt": sample["instruction"] or self.default_prompt, + "task": sample.get("task", "unknown"), + "source_path": str(sample["source_path"]), + "edited_path": str(sample["edited_path"]), + } + raise RuntimeError(f"No readable video pair found while loading dataset index {idx}") + + +def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor: + min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1]) + if min_t <= 0: + return pred_btchw_01.new_tensor(0.0) + pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float() + target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float() + channels = pred.shape[1] + window_size = max(1, int(window_size)) + if window_size % 2 == 0: + window_size += 1 + padding = window_size // 2 + weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size) + mu_x = F.conv2d(pred, weight, padding=padding, groups=channels) + mu_y = F.conv2d(target, weight, padding=padding, groups=channels) + mu_x_sq = mu_x.square() + mu_y_sq = mu_y.square() + mu_xy = mu_x * mu_y + sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq + sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy + c1 = 0.01**2 + c2 = 0.03**2 + ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / ( + (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8 + ) + return (1.0 - ssim.clamp(-1.0, 1.0)).mean() + + +def align_noise_to_latents(noise: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + if noise.shape[:2] != latents.shape[:2] or noise.shape[-2:] != latents.shape[-2:]: + raise ValueError( + f"Noise shape {tuple(noise.shape)} is incompatible with latents {tuple(latents.shape)}" + ) + if noise.shape[2] == latents.shape[2]: + return noise.to(device=latents.device, dtype=latents.dtype) + if noise.shape[2] > latents.shape[2]: + noise = noise[:, :, : latents.shape[2]] + else: + tail = torch.randn( + (*noise.shape[:2], latents.shape[2] - noise.shape[2], *noise.shape[-2:]), + device=noise.device, + dtype=noise.dtype, + ) + noise = torch.cat([noise, tail], dim=2) + return noise.to(device=latents.device, dtype=latents.dtype) + + +def resize_latents_to_match(source_latents: torch.Tensor, target_latents: torch.Tensor) -> torch.Tensor: + if source_latents.shape == target_latents.shape: + return source_latents + if source_latents.shape[:2] != target_latents.shape[:2]: + raise ValueError( + f"Cannot resize latents with different batch/channel shapes: " + f"{tuple(source_latents.shape)} vs {tuple(target_latents.shape)}" + ) + resized = F.interpolate( + source_latents.float(), + size=(target_latents.shape[2], target_latents.shape[3], target_latents.shape[4]), + mode="trilinear", + align_corners=False, + ) + return resized.to(device=target_latents.device, dtype=target_latents.dtype) + + +def ensure_module_device(module: torch.nn.Module | None, device: torch.device) -> torch.nn.Module | None: + if module is None: + return None + param = next(module.parameters(), None) + buffer = next(module.buffers(), None) + current_device = param.device if param is not None else buffer.device if buffer is not None else None + if current_device != device: + module = module.to(device=device) + return module + + +def concat_pil_clips(clips: list[list[Image.Image]]) -> list[Image.Image]: + if not clips: + return [] + frame_count = min(len(clip) for clip in clips) + out = [] + for frame_idx in range(frame_count): + frames = [clip[frame_idx].convert("RGB") for clip in clips] + width = sum(frame.width for frame in frames) + height = max(frame.height for frame in frames) + canvas = Image.new("RGB", (width, height)) + offset = 0 + for frame in frames: + canvas.paste(frame, (offset, 0)) + offset += frame.width + out.append(canvas) + return out + + +def build_run_name(args) -> str: + manifest_name = Path(args.manifest_path).stem + parts = [ + "wan21_t2v_edit", + manifest_name, + f"concat", + f"x{args.sr_scale}", + f"{args.height}x{args.width}", + f"f{args.num_frames}", + f"lr{format_run_value(args.learning_rate)}", + f"noise{format_run_value(args.noise_sigma)}", + f"bridge{format_run_value(args.bridge_loss_weight)}", + f"lpips{format_run_value(args.lpips_weight)}", + f"ssim{format_run_value(args.ssim_weight)}", + f"pix{format_run_value(args.pixel_loss_weight)}", + f"pcrop{args.pixel_loss_crop_size}", + f"plf{args.pixel_loss_latent_frames}", + f"seed{args.seed}", + ] + return "_".join(parts) + + +class TinyDittoEditBridgePipeline(WanVideoBridgePipeline): + def training_loss(self, **inputs): + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0.0) * self.scheduler.num_train_timesteps) + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 0.9999) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + + x0 = inputs["input_latents"] + x1 = inputs["source_latents"] + noise = align_noise_to_latents(inputs["noise"], x0) + xt = self.scheduler.add_noise(x0, x1, noise, timestep) + target = self.scheduler.training_target(x0, xt, timestep) + + model_inputs = dict(inputs) + model_inputs["latents"] = xt + model_inputs["input_latents"] = x0 + model_inputs["source_latents"] = x1 + model_inputs.pop("reference_latents", None) + model_inputs["token_prefix_latents"] = None + model_inputs["condition_latents"] = inputs["original_latents"].detach() + model_inputs["channel_concat_condition"] = True + model_output = self.model_fn(**model_inputs, timestep=timestep) + + sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + if self.scheduler.target == "stabilized_drift": + factor = (1 + (1 - sigma) / (sigma + 1e-5)).sqrt() + velocity_target = target / factor + endpoint = xt.float() - sigma * (model_output.float() * factor) + elif self.scheduler.target == "drift": + velocity_target = target + endpoint = xt.float() - sigma * model_output.float() + else: + raise ValueError(f"Unsupported target: {self.scheduler.target}") + + bridge_loss = F.mse_loss(model_output.float(), velocity_target.float()) + total = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss + metrics = {"bridge_loss": float(bridge_loss.detach()), "pixel_loss": 0.0, "lpips_loss": 0.0, "ssim_loss": 0.0} + + pixel_weight = float(inputs.get("pixel_loss_weight", 0.0)) + lpips_weight = float(inputs.get("lpips_weight", 0.0)) + ssim_weight = float(inputs.get("ssim_weight", 0.0)) + if pixel_weight > 0 or lpips_weight > 0 or ssim_weight > 0: + pred_cropped, _, crop_info = crop_latent_pair_for_pixel_losses( + endpoint, + x0, + int(inputs.get("pixel_loss_crop_size", 400)), + int(inputs.get("pixel_loss_latent_frames", 3)), + int(getattr(self.vae, "upsampling_factor", 16)), + return_crop_info=True, + ) + pred_video = decode_latents_to_btchw_01( + self, + pred_cropped, + bool(inputs.get("tiled", False)), + inputs.get("tile_size", (30, 52)), + inputs.get("tile_stride", (15, 26)), + ) + raw_target = inputs.get("raw_target_video") + if raw_target is None: + raise ValueError("raw_target_video is required for pixel losses") + target_video = crop_original_rgb_for_latent_crop(raw_target, crop_info, pred_video, self.device) + if pred_video.shape != target_video.shape: + raise RuntimeError(f"Prediction shape {tuple(pred_video.shape)} != target shape {tuple(target_video.shape)}") + if pixel_weight > 0: + value = F.mse_loss(pred_video.float(), target_video.float()) + total = total + pixel_weight * value + metrics["pixel_loss"] = float(value.detach()) + if lpips_weight > 0: + lpips_model = ensure_module_device(inputs.get("lpips_model"), pred_video.device) + value = lpips_video_loss( + lpips_model, + pred_video, + target_video, + int(inputs.get("lpips_num_frames", 4)), + int(inputs.get("lpips_crop_size", 224)), + ) + total = total + lpips_weight * value + metrics["lpips_loss"] = float(value.detach()) + if ssim_weight > 0: + value = ssim_video_loss(pred_video, target_video, int(inputs.get("ssim_window_size", 11))) + total = total + ssim_weight * value + metrics["ssim_loss"] = float(value.detach()) + return total, metrics + + +class TinyDittoEditTrainingModule(DiffusionTrainingModule): + def __init__(self, args) -> None: + super().__init__() + configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe = TinyDittoEditBridgePipeline.from_pretrained( + torch_dtype=args.torch_dtype, + device="cpu", + model_configs=configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + self.pipe.requires_grad_(False) + self.pipe.latent_upsampler = None + configure_dit_channel_concat(self.pipe, args.dit_init_checkpoint) + dit_in_dim = int(getattr(self.pipe.dit, "in_dim", 0)) + vae_z_dim = int(getattr(self.pipe.vae, "z_dim", 0)) + if dit_in_dim != 32 or vae_z_dim != 16: + raise RuntimeError( + "Expected a 32-channel concatenated DiT and 16-channel Wan2.1 VAE, " + f"got dit.in_dim={dit_in_dim}, vae.z_dim={vae_z_dim}" + ) + self.pipe.scheduler.noise_scale = args.noise_sigma + self.pipe.scheduler.bridge_type = "brownian" + self.pipe.scheduler.training_weight_type = args.training_weight_type + self.pipe.scheduler.target = args.target + self.switch_pipe_to_training_mode( + self.pipe, + args.trainable_models, + args.lora_base_model, + args.lora_target_modules, + args.lora_rank, + lora_checkpoint=args.lora_checkpoint, + enable_fp8_training=False, + ) + self.args = args + if args.lpips_weight > 0 or args.val_lpips: + import lpips + + self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False) + else: + self.lpips_model = None + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + if self.lpips_model is not None: + self.lpips_model = self.lpips_model.to(*args, **kwargs) + return self + + @torch.no_grad() + def encode_reference(self, frames: list[Image.Image]) -> torch.Tensor: + self.pipe.load_models_to_device(["vae"]) + video = self.pipe.preprocess_video(frames) + latents = self.pipe.vae.encode( + video, + device=self.pipe.device, + tiled=self.args.tiled, + tile_size=(self.args.tile_h, self.args.tile_w), + tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w), + ) + return latents.to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + + def forward_preprocess(self, data: dict) -> dict: + self.pipe.scheduler.set_timesteps(1000, training=True) + shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].height, + "width": data["video"][0].width, + "num_frames": len(data["video"]), + "cfg_scale": 1, + "cfg_merge": False, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": "cpu" if str(self.pipe.device).startswith("npu") else self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + # All prediction tokens use the bridge timestep. Reference is a + # channel condition, with no separate token/timestep stream. + "fuse_vae_embedding_in_latents": False, + "token_prefix_clean_timestep": False, + "token_prefix_aligned_rope": False, + "token_prefix_block_self_attention": False, + "clean_history_latent_frames": 0, + "bridge_loss_weight": self.args.bridge_loss_weight, + "pixel_loss_weight": self.args.pixel_loss_weight, + "lpips_weight": self.args.lpips_weight, + "lpips_model": self.lpips_model, + "lpips_num_frames": self.args.lpips_num_frames, + "lpips_crop_size": self.args.lpips_crop_size, + "ssim_weight": self.args.ssim_weight, + "ssim_window_size": self.args.ssim_window_size, + "pixel_loss_crop_size": self.args.pixel_loss_crop_size, + "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames, + "min_timestep_boundary": self.args.min_timestep_boundary, + "max_timestep_boundary": self.args.max_timestep_boundary, + "raw_target_video": data["video"], + } + pos, neg = {"prompt": data["prompt"]}, {} + for unit in self.pipe.units: + shared, pos, neg = self.pipe.unit_runner(unit, self.pipe, shared, pos, neg) + # Re-assert channel-only conditioning after all pipeline units. + shared["fuse_vae_embedding_in_latents"] = False + shared["token_prefix_clean_timestep"] = False + shared["token_prefix_aligned_rope"] = False + shared["token_prefix_block_self_attention"] = False + shared["original_latents"] = self.encode_reference(data["reference_video"]) + shared["source_latents"] = resize_latents_to_match( + shared["source_latents"], shared["input_latents"] + ) + return {**shared, **pos} + + def forward(self, data: dict, inputs: dict | None = None): + inputs = self.forward_preprocess(data) if inputs is None else inputs + return self.pipe.training_loss(**{n: getattr(self.pipe, n) for n in self.pipe.in_iteration_models}, **inputs) + + +@torch.no_grad() +def sample_edit(pipe, inputs, args): + source = inputs["source_latents"] + latents = source.clone() + pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift) + pipe.load_models_to_device(pipe.in_iteration_models) + models = {n: getattr(pipe, n) for n in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("original_latents", None) + model_inputs.pop("reference_latents", None) + model_inputs["token_prefix_latents"] = None + model_inputs["token_prefix_block_self_attention"] = False + model_inputs["condition_latents"] = inputs["original_latents"].detach() + model_inputs["channel_concat_condition"] = True + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype) + pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, source) + return latents + + +def build_dataset(args, repeat, limit, seed): + return TinyDittoEditDataset( + dataset_root=args.dataset_root, + manifest_path=args.manifest_path, + height=args.height, + width=args.width, + num_frames=args.num_frames, + sr_scale=args.sr_scale, + default_prompt=args.default_prompt, + repeat=repeat, + limit_samples=limit, + seed=seed, + ) + + +def build_validation_dataset(args): + """Build one deterministic validation subset with equal task coverage.""" + dataset = build_dataset(args, repeat=1, limit=None, seed=args.seed + 1) + samples_per_task = max(int(args.val_samples_per_task), 1) + grouped = {} + for sample in dataset.samples: + grouped.setdefault(sample.get("task", "unknown"), []).append(sample) + + selected = [] + for task in sorted(grouped): + if task not in {"background_change", "camera_edit"}: + continue + task_samples = list(grouped[task]) + task_seed = args.seed + 1009 * (sum(ord(char) for char in task) + 1) + random.Random(task_seed).shuffle(task_samples) + selected.extend(task_samples[:samples_per_task]) + dataset.samples = selected + if not dataset.samples: + raise ValueError("No samples available for task-stratified validation") + print( + f"[TinyDittoEdit] validation samples/task={samples_per_task}, " + f"count={len(dataset.samples)}, " + f"tasks={dict(sorted(Counter(s.get('task', 'unknown') for s in dataset.samples).items()))}", + flush=True, + ) + return dataset + + +@torch.no_grad() +def validate(args, accelerator, model, dataset, step): + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + backup = pipe.scheduler + pipe.scheduler = copy.deepcopy(backup) + pipe.scheduler.noise_scale = args.val_sampling_noise_scale + pipe.scheduler.target = args.target + out = Path(args.output_path) / "validation" / f"step-{step:06d}" + out.mkdir(parents=True, exist_ok=True) + rows = [] + for idx in range(len(dataset)): + data = dataset[idx] + task_out = out / Path(str(data.get("task", "unknown"))).name + task_out.mkdir(parents=True, exist_ok=True) + inputs = module.forward_preprocess(data) + pred_latent = sample_edit(pipe, inputs, args) + pred = decode_latents_to_btchw_01(pipe, pred_latent, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + target = decode_latents_to_btchw_01(pipe, inputs["input_latents"], args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + source = decode_latents_to_btchw_01(pipe, inputs["source_latents"], args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + row = { + "idx": idx, + "task": data.get("task", "unknown"), + "latent_mse": F.mse_loss(pred_latent.float(), inputs["input_latents"].float()).item(), + "source_latent_mse": F.mse_loss(inputs["source_latents"].float(), inputs["input_latents"].float()).item(), + "pixel_mse": F.mse_loss(pred.float(), target.float()).item(), + } + if args.val_lpips and module.lpips_model is not None: + module.lpips_model = ensure_module_device(module.lpips_model, pred.device) + row["lpips"] = float(lpips_video_loss(module.lpips_model, pred, target, args.lpips_num_frames, args.lpips_crop_size)) + if args.val_ssim or args.ssim_weight > 0: + row["ssim"] = float(ssim_video_loss(pred, target, args.ssim_window_size)) + rows.append(row) + save_video(data["reference_video"], str(task_out / f"val_{idx:03d}_reference.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(source[0]), str(task_out / f"val_{idx:03d}_coarse.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(target[0]), str(task_out / f"val_{idx:03d}_target.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(pred[0]), str(task_out / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5) + comparison = concat_pil_clips([data["reference_video"], tensor_btchw_01_to_pil(pred[0])]) + save_video(comparison, str(task_out / f"val_{idx:03d}_comparison.mp4"), fps=args.fps, quality=5) + metric_names = ["latent_mse", "source_latent_mse", "pixel_mse", "lpips", "ssim"] + metrics = { + f"val_{name}": sum(row[name] for row in rows if name in row) / sum(name in row for row in rows) + for name in metric_names + if rows and any(name in row for row in rows) + } + task_metrics = {} + for task in sorted({row["task"] for row in rows}): + task_rows = [row for row in rows if row["task"] == task] + task_metrics[task] = { + name: sum(row[name] for row in task_rows if name in row) / sum(name in row for row in task_rows) + for name in metric_names + if any(name in row for row in task_rows) + } + (out / "metrics.json").write_text( + json.dumps( + { + "step": step, + "rows": rows, + "metrics": metrics, + "task_metrics": task_metrics, + "pipeline": "tinyditto_edit_reference_concat", + "reference_concat": True, + }, + indent=2, + ensure_ascii=False, + ), + encoding="utf-8", + ) + print(f"[Validation step {step}] {metrics}", flush=True) + pipe.scheduler = backup + pipe.train() + return metrics + + +class Logger(ModelLogger): + pass + + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--base_model_dir", default="/cache/Wan2.1-T2V-1.3B") + p.add_argument("--model_paths", default=None) + p.add_argument("--lora_checkpoint", default=None) + p.add_argument("--dit_init_checkpoint", default=None) + p.add_argument("--tokenizer_path", default="/cache/Wan2.1-T2V-1.3B/google/umt5-xxl") + p.add_argument("--dataset_root", default="/cache/OpenVE-OneShard-5k") + p.add_argument("--manifest_path", default="/cache/OpenVE-OneShard-5k/metadata.json") + p.add_argument("--default_prompt", default="") + p.add_argument("--output_root", default="/cache/outputs_bridge_wan21_t2v_edit") + p.add_argument("--output_path", default=None) + p.add_argument("--height", type=int, default=480) + p.add_argument("--width", type=int, default=832) + p.add_argument("--num_frames", type=int, default=81) + p.add_argument("--sr_scale", type=int, default=2) + p.add_argument("--fps", type=int, default=20) + p.add_argument("--dataset_repeat", type=int, default=1) + p.add_argument("--limit_samples", type=int, default=None) + p.add_argument("--dataset_num_workers", type=int, default=0) + p.add_argument("--trainable_models", default="dit") + p.add_argument("--lora_base_model", default=None) + p.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2") + p.add_argument("--lora_rank", type=int, default=32) + p.add_argument("--learning_rate", type=float, default=1.0) + p.add_argument("--weight_decay", type=float, default=0.01) + p.add_argument("--d_coef", type=float, default=1.0) + p.add_argument("--max_train_steps", type=int, default=5000) + p.add_argument("--gradient_accumulation_steps", type=int, default=1) + p.add_argument("--max_grad_norm", type=float, default=1.0) + p.add_argument("--save_steps", type=int, default=500) + p.add_argument("--log_interval", type=int, default=1) + p.add_argument("--val_interval", type=int, default=100) + p.add_argument("--val_samples_per_task", type=int, default=2) + p.add_argument("--validate_at_start", action="store_true") + p.add_argument("--validation_only", action="store_true") + p.add_argument("--noise_sigma", type=float, default=1.0) + p.add_argument("--val_sampling_noise_scale", type=float, default=0.0) + p.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + p.add_argument("--training_weight_type", default="uniform") + p.add_argument("--bridge_loss_weight", type=float, default=1.0) + p.add_argument("--pixel_loss_weight", type=float, default=4.0) + p.add_argument("--pixel_loss_crop_size", type=int, default=400) + p.add_argument("--pixel_loss_latent_frames", type=int, default=3) + p.add_argument("--lpips_weight", type=float, default=1.0) + p.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg") + p.add_argument("--lpips_num_frames", type=int, default=4) + p.add_argument("--lpips_crop_size", type=int, default=224) + p.add_argument("--ssim_weight", type=float, default=1.0) + p.add_argument("--ssim_window_size", type=int, default=11) + p.add_argument("--torch_dtype", choices=["float16", "bfloat16"], default="float16") + p.add_argument("--val_lpips", action="store_true") + p.add_argument("--val_ssim", action="store_true") + p.add_argument("--val_inference_steps", type=int, default=4) + p.add_argument("--val_sigma_shift", type=float, default=5.0) + p.add_argument("--min_timestep_boundary", type=float, default=0.0001) + p.add_argument("--max_timestep_boundary", type=float, default=0.9999) + p.add_argument("--use_gradient_checkpointing", action="store_true", default=True) + p.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False) + p.add_argument("--find_unused_parameters", action="store_true", default=False) + p.add_argument("--tiled", action="store_true") + p.add_argument("--tile_h", type=int, default=30) + p.add_argument("--tile_w", type=int, default=52) + p.add_argument("--tile_stride_h", type=int, default=15) + p.add_argument("--tile_stride_w", type=int, default=26) + p.add_argument("--seed", type=int, default=42) + args = p.parse_args() + args.requested_num_frames = args.num_frames + args.num_frames = normalize_wan_num_frames(args.num_frames) + if args.num_frames != args.requested_num_frames: + print( + f"[TinyDittoEdit] num_frames={args.requested_num_frames} is invalid for Wan; " + f"using {args.num_frames} (required layout: 4n+1).", + flush=True, + ) + args.model_paths = args.model_paths or default_model_paths(args.base_model_dir) + args.torch_dtype = getattr(torch, args.torch_dtype) + # Persist the effective stream semantics in args.json for reproducibility. + args.bridge_first_frame_uses_timestep = True + args.clean_original_prefix_timestep = False + args.aligned_stream_rope = False + args.block_prefix_to_bridge_attention = False + args.conditioning_mode = "channel_concat_reference_no_token_prefix" + if args.output_path is None: + args.output_path = str( + Path(args.output_root) + / f"{Path(args.manifest_path).stem}_wan21_t2v_edit_x{args.sr_scale}_{args.height}x{args.width}_f{args.num_frames}_seed{args.seed}" + ) + return args + + +def train(args): + random.seed(args.seed) + torch.manual_seed(args.seed) + if torch_npu is not None and torch.npu.is_available(): + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + torch.npu.set_device(local_rank) + torch.npu.set_compile_mode(jit_compile=False) + torch.npu.config.allow_internal_format = False + print( + f"[TinyDittoEdit] loading dataset root={args.dataset_root} manifest={args.manifest_path}", + flush=True, + ) + train_set = build_dataset(args, args.dataset_repeat, args.limit_samples, args.seed) + val_set = build_validation_dataset(args) + print( + f"[TinyDittoEdit] dataset ready: train={len(train_set)}, validation={len(val_set)}", + flush=True, + ) + print( + "[TinyDittoEdit] stream semantics: " + "bridge_frame0_timestep=sampled, channel_concat=[z_t,reference], " + "token_prefix=none", + flush=True, + ) + model = TinyDittoEditTrainingModule(args) + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text( + json.dumps(vars(args), indent=2, default=str), + encoding="utf-8", + ) + if args.validation_only or args.max_train_steps <= 0: + validate(args, accelerator, accelerator.prepare(model), val_set, 0) + return + from prodigyopt import Prodigy + + optimizer = Prodigy(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay, safeguard_warmup=True, d_coef=args.d_coef) + loader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers) + model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + print(f"[Precision rank {accelerator.process_index}] world_size={accelerator.num_processes} trainable_dtypes={dict(Counter(str(p.dtype) for p in model.parameters() if p.requires_grad))} optimizer=Prodigy lr={args.learning_rate}", flush=True) + logger = Logger(args.output_path, remove_prefix_in_ckpt="pipe.dit.") + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + accelerator.wait_for_everyone() + step = 0 + while step < args.max_train_steps: + for data in tqdm(loader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad() + loss, metrics = model(data) + finite = accelerator.gather(torch.isfinite(loss.detach()).reshape(1)) + if not finite.all(): + raise FloatingPointError(f"Nonfinite loss before update {step + 1}") + accelerator.backward(loss) + if args.max_grad_norm > 0: + grad_norm = accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + if grad_norm is not None and not torch.isfinite(grad_norm).all(): + raise FloatingPointError(f"Nonfinite gradient before update {step + 1}") + optimizer.step() + step += 1 + if step % args.log_interval == 0: + mean_loss = accelerator.gather(loss.detach().reshape(1)).mean().item() + if accelerator.is_main_process and step % args.log_interval == 0: + print( + f"[Train step {step}] loss={mean_loss:.6f} " + f"bridge={metrics['bridge_loss']:.6f} pixel={metrics['pixel_loss']:.6f} " + f"lpips={metrics['lpips_loss']:.6f} ssim={metrics['ssim_loss']:.6f}", + flush=True, + ) + logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + if args.val_interval > 0 and step % args.val_interval == 0: + validate(args, accelerator, model, val_set, step) + accelerator.wait_for_everyone() + if step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.sh new file mode 100644 index 0000000000000000000000000000000000000000..5515c2926b6037080d72a042aa528c948be902dd --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Compatibility wrapper. The edit pipeline now runs on Wan2.1-T2V-1.3B. +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "${SCRIPT_DIR}/train_wan21_t2v_edit.sh" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1e3c1da4cef38c3cf98d9f2556a6fc12dfd035 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py @@ -0,0 +1,457 @@ +"""Full-video Wan2.2-TI2V Brownian-bridge SR training. + +The DiT sees one complete video at a time. Latent frame zero is always the +encoded HR reference image; all later latent frames are the bicubic-upsampled +LR video path. There is no chunk/history teacher forcing and no wavelet loss. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +import sys +from pathlib import Path + +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image +from torch.utils.data import DataLoader +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + SeedanceSRDataset, + decode_latents_to_btchw_01, + lpips_video_loss, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, +) +from diffsynth.data.video import save_video +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger +from diffsynth.utils import ModelConfig + + +def default_model_paths(base_model_dir: str) -> str: + base = Path(base_model_dir) + dit = base / "diffusion_pytorch_model.safetensors.index.json" + if not dit.exists(): + dit = base / "diffusion_pytorch_model.safetensors" + paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.2_VAE.pth"] + missing = [str(p) for p in paths if not p.exists()] + if missing: + raise FileNotFoundError("Missing Wan2.2-TI2V files: " + ", ".join(missing)) + return ",".join(str(p) for p in paths) + + +def normalize_wan_num_frames(num_frames: int) -> int: + """Round a requested RGB length up to Wan's required 4n+1 layout.""" + num_frames = max(int(num_frames), 1) + if num_frames % 4 == 1: + return num_frames + return ((num_frames - 1 + 3) // 4) * 4 + 1 + + +def align_noise_to_latents(noise: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + """Match initializer noise to the VAE output, which is the shape authority.""" + if noise.shape[:2] != latents.shape[:2] or noise.shape[-2:] != latents.shape[-2:]: + raise ValueError( + f"Noise shape {tuple(noise.shape)} is spatially incompatible with " + f"encoded latents {tuple(latents.shape)}" + ) + if noise.shape[2] == latents.shape[2]: + return noise.to(device=latents.device, dtype=latents.dtype) + if noise.shape[2] > latents.shape[2]: + noise = noise[:, :, :latents.shape[2]] + else: + tail = torch.randn( + (*noise.shape[:2], latents.shape[2] - noise.shape[2], *noise.shape[-2:]), + device=noise.device, + dtype=noise.dtype, + ) + noise = torch.cat([noise, tail], dim=2) + return noise.to(device=latents.device, dtype=latents.dtype) + + +def ensure_module_device(module: torch.nn.Module | None, device: torch.device) -> torch.nn.Module | None: + if module is None: + return None + param = next(module.parameters(), None) + buffer = next(module.buffers(), None) + current_device = param.device if param is not None else buffer.device if buffer is not None else None + if current_device != device: + module = module.to(device=device) + return module + + +def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor: + if anchor is None: + return latents + if anchor.shape[2] != 1: + raise ValueError(f"Expected one anchor latent frame, got {tuple(anchor.shape)}") + if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]: + raise ValueError(f"Anchor {tuple(anchor.shape)} incompatible with {tuple(latents.shape)}") + result = latents.clone() + result[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype) + return result + + +def drop_first(video: torch.Tensor) -> torch.Tensor: + return video[:, 1:] if video.shape[1] > 1 else video[:, :0] + + +def drop_first_latent(latents: torch.Tensor) -> torch.Tensor: + return latents[:, :, 1:] if latents.shape[2] > 1 else latents[:, :, :0] + + +def spatial_crop_latents_for_rgb_loss( + latents: torch.Tensor, + crop_size_pixels: int, + vae_factor: int, +) -> tuple[torch.Tensor, dict[str, int]]: + """Randomly crop latent space before differentiable VAE decoding.""" + _, _, _, height, width = latents.shape + vae_factor = max(int(vae_factor), 1) + if crop_size_pixels > 0: + crop_height = min(max(int(crop_size_pixels) // vae_factor, 1), height) + crop_width = min(max(int(crop_size_pixels) // vae_factor, 1), width) + else: + crop_height, crop_width = height, width + top = int(torch.randint(height - crop_height + 1, (1,), device=latents.device).item()) if height > crop_height else 0 + left = int(torch.randint(width - crop_width + 1, (1,), device=latents.device).item()) if width > crop_width else 0 + cropped = latents[..., top:top + crop_height, left:left + crop_width].contiguous() + return cropped, { + "top": top, + "left": left, + "height": crop_height, + "width": crop_width, + "full_height": height, + "full_width": width, + } + + +def ssim_video_loss(pred: torch.Tensor, target: torch.Tensor, window_size: int = 11) -> torch.Tensor: + count = min(pred.shape[1], target.shape[1]) + if count == 0: + return pred.new_tensor(0.0) + pred = pred[:, :count].reshape(-1, *pred.shape[2:]).float() + target = target[:, :count].reshape(-1, *target.shape[2:]).float() + channels = pred.shape[1] + window_size = max(1, int(window_size) | 1) + weight = pred.new_ones((channels, 1, window_size, window_size)) / (window_size**2) + padding = window_size // 2 + mu_x = F.conv2d(pred, weight, padding=padding, groups=channels) + mu_y = F.conv2d(target, weight, padding=padding, groups=channels) + mu_x2, mu_y2, mu_xy = mu_x.square(), mu_y.square(), mu_x * mu_y + sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x2 + sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y2 + sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy + c1, c2 = 0.01**2, 0.03**2 + value = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / ( + (mu_x2 + mu_y2 + c1) * (sigma_x + sigma_y + c2) + 1e-8 + ) + return (1.0 - value.clamp(-1, 1)).mean() + + +class FirstFrameAnchorSRDataset(SeedanceSRDataset): + def __init__(self, *args, **kwargs): + kwargs["source_mode"] = "bicubic" + super().__init__(*args, **kwargs) + + def __getitem__(self, idx): + item = super().__getitem__(idx) + item["source_video"][0] = item["video"][0].copy() + item["reference_image"] = item["video"][0].copy() + return item + + +class FullVideoWan22BridgePipeline(WanVideoBridgePipeline): + def training_loss(self, **inputs): + lo = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + hi = int(inputs.get("max_timestep_boundary", 0.9999) * self.scheduler.num_train_timesteps) + timestep = self.scheduler.timesteps[torch.randint(lo, hi, (1,))].to( + device=self.device, dtype=self.torch_dtype + ) + anchor = inputs["first_frame_latents"] + x0 = replace_first_latent_frame(inputs["input_latents"], anchor) + x1 = replace_first_latent_frame(inputs["source_latents"], anchor) + if x0.shape != x1.shape: + raise ValueError( + f"Target latent shape {tuple(x0.shape)} does not match " + f"source latent shape {tuple(x1.shape)}" + ) + noise = align_noise_to_latents(inputs["noise"], x0) + # The anchor is clean and never receives Brownian noise. + future_xt = self.scheduler.add_noise(x0[:, :, 1:], x1[:, :, 1:], noise[:, :, 1:], timestep) + xt = torch.cat([anchor, future_xt], dim=2) + model_inputs = dict(inputs) + model_inputs.update({"latents": xt, "input_latents": x0, "source_latents": x1}) + model_inputs.pop("first_frame_latents", None) + output = self.model_fn(**model_inputs, timestep=timestep) + sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + target = self.scheduler.training_target(x0[:, :, 1:], future_xt, timestep) + if self.scheduler.target == "stabilized_drift": + factor = (1 + (1 - sigma) / (sigma + 1e-5)).sqrt() + velocity_target = target / factor + endpoint = future_xt.float() - sigma * (output[:, :, 1:].float() * factor) + elif self.scheduler.target == "drift": + velocity_target = target + endpoint = future_xt.float() - sigma * output[:, :, 1:].float() + else: + raise ValueError(f"Unsupported target: {self.scheduler.target}") + + bridge = F.mse_loss(output[:, :, 1:].float(), velocity_target.float()) + total = float(inputs.get("bridge_loss_weight", 1.0)) * bridge + metrics = {"bridge_loss": float(bridge.detach()), "pixel_loss": 0.0, "lpips_loss": 0.0, "ssim_loss": 0.0} + pixel_weight = float(inputs.get("pixel_loss_weight", 0.0)) + lpips_weight = float(inputs.get("lpips_weight", 0.0)) + ssim_weight = float(inputs.get("ssim_weight", 0.0)) + if pixel_weight > 0 or lpips_weight > 0 or ssim_weight > 0: + # Decode a temporal subset for memory efficiency; frame zero is + # deliberately absent from both prediction and target losses. + count = int(inputs.get("pixel_loss_latent_frames", 3)) + if count <= 0 or count >= endpoint.shape[2]: + start, count = 0, endpoint.shape[2] + else: + start = int(torch.randint(endpoint.shape[2] - count + 1, (1,), device=endpoint.device)) + context_index = start + decode_latent = torch.cat([x0[:, :, context_index:context_index + 1].detach(), endpoint[:, :, start:start + count]], dim=2) + decode_latent, crop_info = spatial_crop_latents_for_rgb_loss( + decode_latent, + int(inputs.get("pixel_loss_crop_size", 400)), + int(getattr(self.vae, "upsampling_factor", 16)), + ) + pred_video = decode_latents_to_btchw_01(self, decode_latent, bool(inputs.get("tiled", False)), inputs.get("tile_size", (30, 52)), inputs.get("tile_stride", (15, 26))) + pred_video = pred_video[:, 1:] + raw_target = inputs.get("raw_target_video") + if raw_target is None: + raise ValueError("raw_target_video is required for pixel losses") + # Under Accelerate, module parameters can be moved without updating + # BasePipeline.device. The decoded prediction is the authoritative + # device for all RGB-space losses. + rgb_start = 1 + 4 * start + rgb_count = min(pred_video.shape[1], 4 * count, len(raw_target) - rgb_start) + if rgb_count <= 0: + raise ValueError( + f"No RGB frames align with latent range start={start}, count={count}; " + f"decoded={pred_video.shape[1]}, target={len(raw_target)}" + ) + spatial_factor_h = raw_target[0].height // crop_info["full_height"] + spatial_factor_w = raw_target[0].width // crop_info["full_width"] + top = crop_info["top"] * spatial_factor_h + left = crop_info["left"] * spatial_factor_w + crop_height = pred_video.shape[-2] + crop_width = pred_video.shape[-1] + target_frames = [ + frame.crop((left, top, left + crop_width, top + crop_height)) + for frame in raw_target[rgb_start:rgb_start + rgb_count] + ] + target_video = pil_video_to_tensor_01(target_frames, pred_video.device).unsqueeze(0).to( + device=pred_video.device, dtype=pred_video.dtype + ) + pred_video = pred_video[:, :rgb_count] + if pred_video.shape != target_video.shape: + raise ValueError( + f"RGB prediction shape {tuple(pred_video.shape)} does not match " + f"target shape {tuple(target_video.shape)}" + ) + if pixel_weight > 0: + value = F.mse_loss(pred_video.float(), target_video.float()) + total = total + pixel_weight * value + metrics["pixel_loss"] = float(value.detach()) + if lpips_weight > 0: + lpips_model = inputs.get("lpips_model") + if lpips_model is None: + raise ValueError("lpips_model is required when lpips_weight > 0") + lpips_model = ensure_module_device(lpips_model, pred_video.device) + value = lpips_video_loss(lpips_model, pred_video, target_video, int(inputs.get("lpips_num_frames", 4)), int(inputs.get("lpips_crop_size", 224))) + total = total + lpips_weight * value + metrics["lpips_loss"] = float(value.detach()) + if ssim_weight > 0: + value = ssim_video_loss(pred_video, target_video, int(inputs.get("ssim_window_size", 11))) + total = total + ssim_weight * value + metrics["ssim_loss"] = float(value.detach()) + return total, metrics + + +class FullVideoTrainingModule(DiffusionTrainingModule): + def __init__(self, args): + super().__init__() + configs = [ModelConfig(path=p) for p in args.model_paths.split(",")] + self.pipe = FullVideoWan22BridgePipeline.from_pretrained(torch_dtype=torch.bfloat16, device="cpu", model_configs=configs, tokenizer_config=ModelConfig(path=args.tokenizer_path)) + self.pipe.latent_upsampler = None + if not getattr(self.pipe.dit, "fuse_vae_embedding_in_latents", False) or int(getattr(self.pipe.vae, "z_dim", 0)) != 48: + raise RuntimeError("Expected a Wan2.2-TI2V-5B fused-input DiT with 48-channel VAE") + self.switch_pipe_to_training_mode(self.pipe, args.trainable_models, args.lora_base_model, args.lora_target_modules, args.lora_rank, lora_checkpoint=args.lora_checkpoint, enable_fp8_training=False) + self.args = args + if args.lpips_weight > 0 or args.val_lpips: + import lpips + self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False) + else: + self.lpips_model = None + + def to(self, *args, **kwargs): + super().to(*args, **kwargs) + if self.lpips_model is not None: + self.lpips_model = self.lpips_model.to(*args, **kwargs) + return self + + @torch.no_grad() + def encode_anchor(self, image): + self.pipe.load_models_to_device(["vae"]) + encoded = self.pipe.vae.encode(self.pipe.preprocess_video([image]), device=self.pipe.device, tiled=self.args.tiled, tile_size=(self.args.tile_h, self.args.tile_w), tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w)) + return encoded.to(device=self.pipe.device, dtype=self.pipe.torch_dtype) + + def forward_preprocess(self, data): + shared = {"input_video": data["video"], "source_video": data["source_video"], "height": data["video"][0].height, "width": data["video"][0].width, "num_frames": len(data["video"]), "cfg_scale": 1, "cfg_merge": False, "tiled": self.args.tiled, "tile_size": (self.args.tile_h, self.args.tile_w), "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), "rand_device": self.pipe.device, "seed": None, "use_gradient_checkpointing": self.args.use_gradient_checkpointing, "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, "fuse_vae_embedding_in_latents": True, "bridge_loss_weight": self.args.bridge_loss_weight, "pixel_loss_weight": self.args.pixel_loss_weight, "lpips_weight": self.args.lpips_weight, "lpips_model": self.lpips_model, "lpips_num_frames": self.args.lpips_num_frames, "lpips_crop_size": self.args.lpips_crop_size, "ssim_weight": self.args.ssim_weight, "ssim_window_size": self.args.ssim_window_size, "pixel_loss_crop_size": self.args.pixel_loss_crop_size, "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames, "min_timestep_boundary": self.args.min_timestep_boundary, "max_timestep_boundary": self.args.max_timestep_boundary, "raw_target_video": data["video"]} + pos, neg = {"prompt": data["prompt"]}, {} + for unit in self.pipe.units: + shared, pos, neg = self.pipe.unit_runner(unit, self.pipe, shared, pos, neg) + shared["first_frame_latents"] = self.encode_anchor(data["reference_image"]) + return {**shared, **pos} + + def forward(self, data, inputs=None): + inputs = self.forward_preprocess(data) if inputs is None else inputs + return self.pipe.training_loss(**{n: getattr(self.pipe, n) for n in self.pipe.in_iteration_models}, **inputs) + + +@torch.no_grad() +def sample_full(pipe, inputs, args): + anchor = inputs["first_frame_latents"] + source = replace_first_latent_frame(inputs["source_latents"], anchor) + latents = source.clone() + pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift) + pipe.load_models_to_device(pipe.in_iteration_models) + models = {n: getattr(pipe, n) for n in pipe.in_iteration_models} + model_inputs = dict(inputs) + model_inputs.pop("latents", None) + model_inputs.pop("first_frame_latents", None) + model_inputs["source_latents"] = source + for timestep_cpu in pipe.scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype) + pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep) + latents = pipe.scheduler.step(pred, timestep_cpu, latents, source) + latents[:, :, :1] = anchor + return latents + + +def build_dataset(args, repeat, limit, seed): + return FirstFrameAnchorSRDataset(args.video_dir, args.prompt_json, args.prompt_field, args.default_prompt, args.height, args.width, args.num_frames, args.sr_scale, repeat=repeat, limit_videos=limit, seed=seed) + + +def validate(args, accelerator, model, dataset, step): + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + backup = pipe.scheduler + pipe.scheduler = copy.deepcopy(backup) + pipe.scheduler.noise_scale = args.val_sampling_noise_scale + pipe.scheduler.target = args.target + out = Path(args.output_path) / "validation" / f"step-{step:06d}" + out.mkdir(parents=True, exist_ok=True) + rows = [] + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + inputs = module.forward_preprocess(data) + x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"]) + pred_latent = sample_full(pipe, inputs, args) + pred = decode_latents_to_btchw_01(pipe, pred_latent, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + target = decode_latents_to_btchw_01(pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + pred_main, target_main = drop_first(pred), drop_first(target) + row = {"idx": idx, "latent_mse": F.mse_loss(drop_first_latent(pred_latent).float(), drop_first_latent(x0).float()).item(), "anchor_latent_mse": F.mse_loss(pred_latent[:, :, :1].float(), inputs["first_frame_latents"].float()).item(), "pixel_mse": F.mse_loss(pred_main.float(), target_main.float()).item()} + if args.val_lpips and module.lpips_model is not None: + module.lpips_model = ensure_module_device(module.lpips_model, pred_main.device) + row["lpips"] = float(lpips_video_loss(module.lpips_model, pred_main, target_main, args.lpips_num_frames, args.lpips_crop_size)) + if args.val_ssim or args.ssim_weight > 0: + row["ssim"] = float(ssim_video_loss(pred_main, target_main, args.ssim_window_size)) + rows.append(row) + save_video(tensor_btchw_01_to_pil(pred[0]), str(out / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5) + data["reference_image"].save(out / f"val_{idx:03d}_reference.png") + metrics = {f"val_{k}": sum(r[k] for r in rows) / len(rows) for k in rows[0] if k != "idx"} if rows else {} + (out / "metrics.json").write_text(json.dumps({"step": step, "rows": rows, "metrics": metrics, "pipeline": "full_video_hr_first_frame_anchor", "anchor_each_step": True}, indent=2), encoding="utf-8") + print(f"[Validation step {step}] {metrics}", flush=True) + pipe.scheduler = backup + pipe.train() + return metrics + + +class Logger(ModelLogger): + pass + + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B") + p.add_argument("--model_paths", default=None) + p.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl") + p.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + p.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + p.add_argument("--prompt_field", default="raw_p") + p.add_argument("--default_prompt", default="") + p.add_argument("--output_root", default="/cache/outputs_bridge_wan22_ti2v_full") + p.add_argument("--output_path", default=None) + p.add_argument("--height", type=int, default=480); p.add_argument("--width", type=int, default=832); p.add_argument("--num_frames", type=int, default=81); p.add_argument("--sr_scale", type=int, default=2); p.add_argument("--fps", type=int, default=16) + p.add_argument("--limit_videos", type=int, default=None); p.add_argument("--dataset_repeat", type=int, default=1); p.add_argument("--dataset_num_workers", type=int, default=0) + p.add_argument("--trainable_models", default="dit"); p.add_argument("--lora_base_model", default=None); p.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2"); p.add_argument("--lora_rank", type=int, default=32); p.add_argument("--lora_checkpoint", default=None) + p.add_argument("--learning_rate", type=float, default=1.0); p.add_argument("--weight_decay", type=float, default=0.01); p.add_argument("--d_coef", type=float, default=1.0); p.add_argument("--max_train_steps", type=int, default=5000); p.add_argument("--gradient_accumulation_steps", type=int, default=1); p.add_argument("--max_grad_norm", type=float, default=1.0); p.add_argument("--save_steps", type=int, default=500); p.add_argument("--log_interval", type=int, default=1); p.add_argument("--val_interval", type=int, default=100); p.add_argument("--val_batches", type=int, default=1); p.add_argument("--validate_at_start", action="store_true"); p.add_argument("--validation_only", action="store_true") + p.add_argument("--noise_sigma", type=float, default=1.0); p.add_argument("--val_sampling_noise_scale", type=float, default=1.0); p.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift"); p.add_argument("--training_weight_type", default="uniform"); p.add_argument("--bridge_loss_weight", type=float, default=1.0); p.add_argument("--pixel_loss_weight", type=float, default=4.0); p.add_argument("--pixel_loss_crop_size", type=int, default=400); p.add_argument("--pixel_loss_latent_frames", type=int, default=3); p.add_argument("--lpips_weight", type=float, default=1.0); p.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg"); p.add_argument("--lpips_num_frames", type=int, default=4); p.add_argument("--lpips_crop_size", type=int, default=224); p.add_argument("--ssim_weight", type=float, default=1.0); p.add_argument("--ssim_window_size", type=int, default=11); p.add_argument("--val_lpips", action="store_true"); p.add_argument("--val_ssim", action="store_true"); p.add_argument("--val_inference_steps", type=int, default=4); p.add_argument("--val_sigma_shift", type=float, default=5.0); p.add_argument("--min_timestep_boundary", type=float, default=0.0001); p.add_argument("--max_timestep_boundary", type=float, default=0.9999) + p.add_argument("--use_gradient_checkpointing", action="store_true", default=True); p.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False); p.add_argument("--find_unused_parameters", action="store_true", default=False); p.add_argument("--tiled", action="store_true"); p.add_argument("--tile_h", type=int, default=30); p.add_argument("--tile_w", type=int, default=52); p.add_argument("--tile_stride_h", type=int, default=15); p.add_argument("--tile_stride_w", type=int, default=26); p.add_argument("--seed", type=int, default=42) + args = p.parse_args() + args.requested_num_frames = args.num_frames + args.num_frames = normalize_wan_num_frames(args.num_frames) + if args.num_frames != args.requested_num_frames: + print( + f"[Wan22TI2VFull] num_frames={args.requested_num_frames} is invalid for Wan; " + f"using {args.num_frames} (required layout: 4n+1).", + flush=True, + ) + args.model_paths = args.model_paths or default_model_paths(args.base_model_dir) + if args.output_path is None: + args.output_path = str(Path(args.output_root) / f"wan22_ti2v_full_x{args.sr_scale}_{args.height}x{args.width}_f{args.num_frames}_mse_lpips_ssim_seed{args.seed}") + return args + + +def train(args): + random.seed(args.seed); torch.manual_seed(args.seed) + train_set = build_dataset(args, args.dataset_repeat, args.limit_videos, args.seed) + val_set = build_dataset(args, 1, max(args.val_batches, 1), args.seed + 1) + model = FullVideoTrainingModule(args) + model.pipe.scheduler.noise_scale = args.noise_sigma; model.pipe.scheduler.bridge_type = "brownian"; model.pipe.scheduler.training_weight_type = args.training_weight_type; model.pipe.scheduler.target = args.target + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)]) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True); (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + if args.validation_only or args.max_train_steps <= 0: + validate(args, accelerator, accelerator.prepare(model), val_set, 0); return + from prodigyopt import Prodigy + optimizer = Prodigy(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay, safeguard_warmup=True, d_coef=args.d_coef) + loader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers) + model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + logger = Logger(args.output_path, remove_prefix_in_ckpt="pipe.dit.") + if args.validate_at_start: validate(args, accelerator, model, val_set, 0) + step = 0 + while step < args.max_train_steps: + for data in tqdm(loader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad(); loss, metrics = model(data); accelerator.backward(loss) + if args.max_grad_norm > 0: accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step(); step += 1 + if accelerator.is_main_process and step % args.log_interval == 0: + print(f"[Train step {step}] loss={accelerator.gather(loss.detach()).mean().item():.6f} bridge={metrics['bridge_loss']:.6f} pixel={metrics['pixel_loss']:.6f} lpips={metrics['lpips_loss']:.6f} ssim={metrics['ssim_loss']:.6f}", flush=True) + logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + if args.val_interval > 0 and step % args.val_interval == 0: validate(args, accelerator, model, val_set, step) + if step >= args.max_train_steps: break + logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None) + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ef64ecc74a39ddd72f7c9974a80e76c4a23af6f --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM=false + +"${PYTHON_BIN}" diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py \ + --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \ + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \ + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \ + --output_root "${OUTPUT_ROOT:-/cache/4xoutputs_bridge_wan22_ti2v_full}" \ + --height "${HEIGHT:-480}" --width "${WIDTH:-832}" --num_frames "${NUM_FRAMES:-33}" \ + --sr_scale "${SR_SCALE:-4}" --fps "${FPS:-16}" \ + --learning_rate "${LEARNING_RATE:-1.0}" --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \ + --save_steps "${SAVE_STEPS:-500}" --val_interval "${VAL_INTERVAL:-100}" \ + --noise_sigma "${NOISE_SIGMA:-1.0}" --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \ + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-4.0}" --lpips_weight "${LPIPS_WEIGHT:-1.0}" \ + --ssim_weight "${SSIM_WEIGHT:-1.0}" --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \ + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \ + --val_inference_steps "${VAL_INFERENCE_STEPS:-4}" --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}" \ + --val_lpips --val_ssim --tiled \ + "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b828f9271e86ea7fb5b9559dee6a8b11cad8bbad --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py @@ -0,0 +1,583 @@ +"""Train a Brownian bridge directly in latent Haar high-frequency subbands. + +This is intentionally a separate training entry point. It imports reusable data, +VAE and UltraFlash helpers from ``train_sr.py`` but does not alter the original SR +bridge training path. + +Latent pipeline (one level, orthonormal Haar): + + LR video -> Wan VAE -> UltraFlash -> z_up -> LL_up + HD reference frame -> Wan VAE -> (HL_ref, LH_ref, HH_ref) -> repeat in time + Brownian bridge: reference HF -> target-video HF, conditioned on LL_up + IDWT(LL_up, predicted HF) -> reconstructed HR video latent +""" + +from __future__ import annotations + +import argparse +import copy +import json +import math +import os +import random +import sys +from pathlib import Path + +import imageio +import torch +import torch.nn as nn +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs +from PIL import Image, ImageDraw +from safetensors.torch import load_file +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from diffsynth.bridge.wan_bridge.model_training.train_sr import ( + SeedanceSRDataset, + WanVideoSRBridgePipeline, + WanVideoSRUnit_UltraFlashLatentUpsampler, + center_crop_resize, + decode_latents_to_btchw_01, + default_model_paths, + load_ultraflash_latent_upsampler, + pil_video_to_tensor_01, + tensor_btchw_01_to_pil, +) +from diffsynth.data.video import save_video +from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger +from diffsynth.utils import ModelConfig + + +BAND_ORDER = ("HL", "LH", "HH") + + +def haar_dwt2(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Orthonormal 2D Haar DWT over the last two dimensions. + + Returns LL and high-frequency channels concatenated as [HL, LH, HH]. For an + input [B, C, T, H, W], the shapes are [B, C, T, H/2, W/2] and + [B, 3C, T, H/2, W/2]. + """ + if x.ndim != 5: + raise ValueError(f"Expected BCTHW latent, got {tuple(x.shape)}") + if x.shape[-2] % 2 or x.shape[-1] % 2: + raise ValueError(f"Haar DWT requires even H/W, got {tuple(x.shape[-2:])}") + a = x[..., 0::2, 0::2] + b = x[..., 0::2, 1::2] + c = x[..., 1::2, 0::2] + d = x[..., 1::2, 1::2] + ll = (a + b + c + d) * 0.5 + hl = (a - b + c - d) * 0.5 + lh = (a + b - c - d) * 0.5 + hh = (a - b - c + d) * 0.5 + return ll, torch.cat((hl, lh, hh), dim=1) + + +def haar_idwt2(ll: torch.Tensor, hf: torch.Tensor) -> torch.Tensor: + """Exact inverse of :func:`haar_dwt2`; HF order is [HL, LH, HH].""" + if ll.ndim != 5 or hf.ndim != 5: + raise ValueError("LL and HF must both be BCTHW tensors") + channels = ll.shape[1] + if hf.shape[1] != channels * 3 or hf.shape[0] != ll.shape[0] or hf.shape[2:] != ll.shape[2:]: + raise ValueError(f"Incompatible LL/HF shapes: {tuple(ll.shape)}, {tuple(hf.shape)}") + hl, lh, hh = hf.split(channels, dim=1) + a = (ll + hl + lh + hh) * 0.5 + b = (ll - hl + lh - hh) * 0.5 + c = (ll + hl - lh - hh) * 0.5 + d = (ll - hl - lh + hh) * 0.5 + out = ll.new_empty((*ll.shape[:-2], ll.shape[-2] * 2, ll.shape[-1] * 2)) + out[..., 0::2, 0::2] = a + out[..., 0::2, 1::2] = b + out[..., 1::2, 0::2] = c + out[..., 1::2, 1::2] = d + return out + + +def load_bridge_checkpoint(dit: nn.Module, checkpoint: str) -> None: + state = load_file(checkpoint, device="cpu") + prefixes = ("pipe.dit.", "dit.", "module.pipe.dit.", "module.dit.") + for prefix in prefixes: + if any(key.startswith(prefix) for key in state): + state = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state.items()} + break + dit.load_state_dict(state, strict=True) + print(f"[WaveletBridge] initialized Wan DiT from {checkpoint}") + + +def expand_dit_wavelet_io(dit: nn.Module, latent_channels: int = 16) -> None: + """Change Wan's input 16->64 and output 16->48 without touching its body.""" + old_patch = dit.patch_embedding + if old_patch.in_channels != latent_channels: + raise ValueError(f"Expected {latent_channels}-channel Wan input, got {old_patch.in_channels}") + new_patch = nn.Conv3d( + latent_channels * 4, + old_patch.out_channels, + kernel_size=old_patch.kernel_size, + stride=old_patch.stride, + padding=old_patch.padding, + dilation=old_patch.dilation, + bias=old_patch.bias is not None, + ).to(device=old_patch.weight.device, dtype=old_patch.weight.dtype) + with torch.no_grad(): + new_patch.weight.zero_() + # Input order is [LL_up, xt_HL, xt_LH, xt_HH]. Preserve the old + # Bridge's input behaviour through LL and initially ignore HF state. + new_patch.weight[:, :latent_channels].copy_(old_patch.weight) + if old_patch.bias is not None: + new_patch.bias.copy_(old_patch.bias) + dit.patch_embedding = new_patch + dit.in_dim = latent_channels * 4 + + old_linear = dit.head.head + patch_volume = math.prod(dit.patch_size) + if old_linear.out_features != latent_channels * patch_volume: + raise ValueError(f"Unexpected Wan head size {old_linear.out_features}") + new_linear = nn.Linear( + old_linear.in_features, latent_channels * 3 * patch_volume, bias=old_linear.bias is not None + ).to(device=old_linear.weight.device, dtype=old_linear.weight.dtype) + with torch.no_grad(): + # Each subband starts from the pretrained Bridge head. They immediately + # separate because each third receives a different subband target. + for band_id in range(3): + start = band_id * old_linear.out_features + stop = start + old_linear.out_features + new_linear.weight[start:stop].copy_(old_linear.weight) + if old_linear.bias is not None: + new_linear.bias[start:stop].copy_(old_linear.bias) + dit.head.head = new_linear + print("[WaveletBridge] DiT I/O: 64=[LL,HL,LH,HH] input channels, 48=[HL,LH,HH] output channels") + + +def load_wavelet_checkpoint(dit: nn.Module, checkpoint: str) -> None: + state = load_file(checkpoint, device="cpu") + for prefix in ("pipe.dit.", "dit.", "module.pipe.dit."): + if any(key.startswith(prefix) for key in state): + state = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state.items()} + break + result = dit.load_state_dict(state, strict=False) + if result.missing_keys or result.unexpected_keys: + raise RuntimeError( + f"Wavelet checkpoint mismatch; missing={result.missing_keys[:8]}, unexpected={result.unexpected_keys[:8]}" + ) + print(f"[WaveletBridge] resumed {checkpoint}") + + +class SeedanceWaveletBridgeDataset(SeedanceSRDataset): + """Seedance SR clip plus the actual first frame of the same disk video.""" + + def _read_reference(self, path: Path) -> Image.Image: + reader = imageio.get_reader(str(path)) + try: + frame = reader.get_data(0) + finally: + reader.close() + return center_crop_resize(Image.fromarray(frame).convert("RGB"), self.height, self.width) + + def __getitem__(self, idx: int) -> dict: + data = super().__getitem__(idx) + data["reference_image"] = self._read_reference(Path(data["path"])) + return data + + +def normalized_band_l1(pred: torch.Tensor, target: torch.Tensor, channels: int) -> tuple[torch.Tensor, dict]: + losses = [] + metrics = {} + for band_id, name in enumerate(BAND_ORDER): + p = pred[:, band_id * channels:(band_id + 1) * channels].float() + y = target[:, band_id * channels:(band_id + 1) * channels].float() + scale = y.detach().abs().mean(dim=(1, 2, 3, 4), keepdim=True).clamp_min(1e-3) + raw = F.l1_loss(p, y) + losses.append(((p - y).abs() / scale).mean()) + metrics[f"{name.lower()}_l1"] = float(raw.detach().cpu()) + return torch.stack(losses).mean(), metrics + + +class WaveletBridgeTrainingModule(DiffusionTrainingModule): + def __init__(self, args) -> None: + super().__init__() + configs = [ModelConfig(path=path) for path in args.model_paths.split(",")] + self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained( + torch_dtype=torch.bfloat16, + device="cpu", + model_configs=configs, + tokenizer_config=ModelConfig(path=args.tokenizer_path), + ) + load_bridge_checkpoint(self.pipe.dit, args.bridge_checkpoint) + expand_dit_wavelet_io(self.pipe.dit, args.latent_channels) + if args.resume_checkpoint: + load_wavelet_checkpoint(self.pipe.dit, args.resume_checkpoint) + + self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu") + self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()] + self.pipe.scheduler.noise_scale = args.noise_sigma + self.pipe.scheduler.target = args.target + # We sample this explicit short schedule ourselves. ``training=True`` + # builds an auxiliary timestep-weight table which is undefined for a + # single point and is not used by this objective. + self.pipe.scheduler.set_timesteps(args.train_timesteps, shift=args.sigma_shift) + # The generic Wan input-video unit uses this flag to return the clean + # encoded target latent. Leaving it False would make that unit call the + # ordinary diffusion add_noise signature, which is not Bridge-compatible. + self.pipe.scheduler.training = True + valid_ids = torch.where( + (self.pipe.scheduler.sigmas >= args.min_train_sigma) + & (self.pipe.scheduler.sigmas <= args.max_train_sigma) + )[0] + if valid_ids.numel() == 0: + raise ValueError( + f"No training sigmas in [{args.min_train_sigma}, {args.max_train_sigma}] " + f"for a {args.train_timesteps}-point schedule" + ) + # Keep this CPU-side index table non-persistent: it is schedule metadata, + # not a learned model tensor and should not enter checkpoints. + self.train_timestep_ids = valid_ids + print( + f"[WaveletBridge] random Brownian training: {valid_ids.numel()} sigmas in " + f"[{float(self.pipe.scheduler.sigmas[valid_ids].min()):.4f}, " + f"{float(self.pipe.scheduler.sigmas[valid_ids].max()):.4f}], " + f"noise_scale={self.pipe.scheduler.noise_scale:g}" + ) + + self.pipe.requires_grad_(False) + self.pipe.dit.requires_grad_(True) + self.args = args + + @torch.no_grad() + def _encode_reference(self, reference_image: Image.Image) -> torch.Tensor: + self.pipe.load_models_to_device(["vae"]) + video = self.pipe.preprocess_video([reference_image]) + return self.pipe.vae.encode( + video, + device=self.pipe.device, + tiled=self.args.tiled, + tile_size=(self.args.tile_h, self.args.tile_w), + tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w), + ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + + def forward_preprocess(self, data: dict, apply_text_dropout: bool = True) -> dict: + prompt = data["prompt"] + if apply_text_dropout and random.random() < self.args.text_drop_probability: + prompt = " " + positive = {"prompt": prompt} + negative = {} + shared = { + "input_video": data["video"], + "source_video": data["source_video"], + "height": data["video"][0].size[1], + "width": data["video"][0].size[0], + "num_frames": len(data["video"]), + "cfg_scale": 1, + "tiled": self.args.tiled, + "tile_size": (self.args.tile_h, self.args.tile_w), + "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w), + "rand_device": self.pipe.device, + "seed": None, + "use_gradient_checkpointing": self.args.use_gradient_checkpointing, + "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload, + "cfg_merge": False, + "vace_scale": 1, + } + with torch.no_grad(): + for unit in self.pipe.units: + shared, positive, negative = self.pipe.unit_runner(unit, self.pipe, shared, positive, negative) + reference_latent = self._encode_reference(data["reference_image"]) + + target_latent = shared["input_latents"] + upsampled_latent = shared["source_latents"] + target_ll, target_hf = haar_dwt2(target_latent) + source_ll, _ = haar_dwt2(upsampled_latent) + _, reference_hf = haar_dwt2(reference_latent) + reference_hf = reference_hf.repeat(1, 1, target_hf.shape[2], 1, 1) + + shared.update({ + "target_latent": target_latent, + "upsampled_latent": upsampled_latent, + "target_ll": target_ll, + "target_hf": target_hf, + "source_ll": source_ll, + "reference_hf": reference_hf, + "noise": torch.randn_like(target_hf), + }) + return {**shared, **positive} + + def _predict(self, inputs: dict, xt: torch.Tensor, timestep: torch.Tensor) -> torch.Tensor: + self.pipe.load_models_to_device(self.pipe.in_iteration_models) + models = {name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models} + model_inputs = dict(inputs) + for key in ( + "target_latent", "upsampled_latent", "target_ll", "target_hf", "source_ll", + "reference_hf", "source_latents", "input_latents", "noise", "latents", + ): + model_inputs.pop(key, None) + # Conditioning is explicit and spatially aligned. The scheduler never + # evolves LL; it only evolves the 48 HF channels. + dit_input = torch.cat((inputs["source_ll"], xt), dim=1) + return self.pipe.model_fn(**models, **model_inputs, latents=dit_input, timestep=timestep) + + def forward(self, data: dict, inputs: dict | None = None): + if inputs is None: + inputs = self.forward_preprocess(data) + scheduler = self.pipe.scheduler + random_id = int(torch.randint(0, self.train_timestep_ids.numel(), (1,)).item()) + timestep_id = self.train_timestep_ids[random_id:random_id + 1] + timestep = scheduler.timesteps[timestep_id].to(dtype=self.pipe.torch_dtype, device=self.pipe.device) + x0, x1 = inputs["target_hf"], inputs["reference_hf"] + xt = scheduler.add_noise(x0, x1, inputs["noise"], timestep) + target_velocity = scheduler.training_target(x0, xt, timestep) + output = self._predict(inputs, xt, timestep) + sigma = torch.as_tensor(scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32) + + if self.args.target == "stabilized_drift": + factor = (1.0 + (1.0 - sigma) / (sigma + 1e-5)).sqrt() + velocity_target = target_velocity.float() / factor + velocity = output.float() * factor + else: + velocity_target = target_velocity.float() + velocity = output.float() + endpoint_hf = xt.float() - sigma * velocity + + bridge_loss = F.mse_loss(output.float(), velocity_target) + band_loss, band_metrics = normalized_band_l1(endpoint_hf, x0, self.args.latent_channels) + pred_latent = haar_idwt2(inputs["source_ll"].float(), endpoint_hf) + reconstruction_loss = F.l1_loss(pred_latent, inputs["target_latent"].float()) + if endpoint_hf.shape[2] > 1: + temporal_loss = F.l1_loss( + endpoint_hf[:, :, 1:] - endpoint_hf[:, :, :-1], + x0.float()[:, :, 1:] - x0.float()[:, :, :-1], + ) + else: + temporal_loss = endpoint_hf.new_zeros(()) + loss = ( + self.args.bridge_loss_weight * bridge_loss + + self.args.band_loss_weight * band_loss + + self.args.reconstruction_loss_weight * reconstruction_loss + + self.args.temporal_loss_weight * temporal_loss + ) + metrics = { + "sigma": float(sigma.detach().cpu()), + "brownian_noise_rms": float( + (scheduler.get_noise_coeff(sigma.detach().cpu()) * inputs["noise"].float()) + .square().mean().sqrt().detach().cpu() + ), + "bridge": float(bridge_loss.detach().cpu()), + "band": float(band_loss.detach().cpu()), + "reconstruction": float(reconstruction_loss.detach().cpu()), + "temporal": float(temporal_loss.detach().cpu()), + **band_metrics, + } + return loss, metrics + + +def add_label(frame: Image.Image, labels: list[str]) -> Image.Image: + out = frame.copy() + draw = ImageDraw.Draw(out) + cell_w = out.width // len(labels) + for index, label in enumerate(labels): + x = index * cell_w + 8 + draw.rectangle((x - 4, 4, x + max(90, len(label) * 8), 28), fill=(0, 0, 0)) + draw.text((x, 8), label, fill=(255, 255, 255)) + return out + + +@torch.no_grad() +def validate(args, accelerator: Accelerator, model: WaveletBridgeTrainingModule, dataset: Dataset, step: int) -> dict: + if not accelerator.is_main_process: + return {} + module = accelerator.unwrap_model(model) + pipe = module.pipe + pipe.eval() + out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}" + out_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for idx in range(min(args.val_batches, len(dataset))): + data = dataset[idx] + inputs = module.forward_preprocess(data, apply_text_dropout=False) + scheduler = copy.deepcopy(pipe.scheduler) + scheduler.noise_scale = args.val_noise_sigma + scheduler.set_timesteps(args.val_inference_steps, shift=args.sigma_shift) + hf = inputs["reference_hf"].clone() + for timestep_cpu in scheduler.timesteps: + timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device) + output = module._predict(inputs, hf, timestep) + hf = scheduler.step(output, timestep_cpu, hf, inputs["reference_hf"]) + pred_latent = haar_idwt2(inputs["source_ll"], hf) + + pred_video = decode_latents_to_btchw_01(pipe, pred_latent, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + up_video = decode_latents_to_btchw_01(pipe, inputs["upsampled_latent"], args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)) + target_video = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0) + lr_video = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0) + b, t, c, h, w = lr_video.shape + lr_video = F.interpolate(lr_video.reshape(b * t, c, h, w), size=target_video.shape[-2:], mode="bicubic", align_corners=False, antialias=True).reshape(b, t, c, *target_video.shape[-2:]).clamp(0, 1) + ref = pil_video_to_tensor_01([data["reference_image"]], pipe.device).unsqueeze(0).repeat(1, target_video.shape[1], 1, 1, 1) + min_t = min(lr_video.shape[1], up_video.shape[1], pred_video.shape[1], target_video.shape[1]) + diff = (pred_video[:, :min_t] - target_video[:, :min_t]).abs() + strip = torch.cat((lr_video[:, :min_t], up_video[:, :min_t], ref[:, :min_t], pred_video[:, :min_t], target_video[:, :min_t], diff), dim=-1) + labels = ["LR", "UltraFlash", "Reference", "Wavelet Bridge", "Original", "Abs Difference"] + strip_frames = [add_label(frame, labels) for frame in tensor_btchw_01_to_pil(strip[0])] + save_video(strip_frames, str(out_dir / f"val_{idx:03d}_lr_up_ref_bridge_original_diff.mp4"), fps=args.fps, quality=5) + save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_wavelet_bridge.mp4"), fps=args.fps, quality=5) + data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png") + + pixel_mse = F.mse_loss(pred_video[:, :min_t].float(), target_video[:, :min_t].float()).item() + row = { + "idx": idx, + "pixel_mse": pixel_mse, + "psnr": -10.0 * math.log10(max(pixel_mse, 1e-12)), + "latent_l1": F.l1_loss(pred_latent.float(), inputs["target_latent"].float()).item(), + "hf_l1": F.l1_loss(hf.float(), inputs["target_hf"].float()).item(), + "source_path": data["path"], + } + for band_id, name in enumerate(BAND_ORDER): + sl = slice(band_id * args.latent_channels, (band_id + 1) * args.latent_channels) + row[f"{name.lower()}_l1"] = F.l1_loss(hf[:, sl].float(), inputs["target_hf"][:, sl].float()).item() + rows.append(row) + numeric_keys = [key for key in rows[0] if key not in ("idx", "source_path")] if rows else [] + metrics = {f"val_{key}": sum(float(row[key]) for row in rows) / len(rows) for key in numeric_keys} + (out_dir / "metrics.json").write_text(json.dumps({"step": step, "rows": rows, "metrics": metrics}, indent=2), encoding="utf-8") + print(f"[Validation step {step}] {metrics}") + pipe.train() + return metrics + + +def build_run_name(args) -> str: + bridge = Path(args.bridge_checkpoint).stem + return ( + f"wavelet_hf_bridge_x{args.sr_scale}_{args.width}x{args.height}_f{args.num_frames}" + f"_init-{bridge}_steps{args.train_timesteps}_shift{args.sigma_shift:g}" + f"_noise{args.noise_sigma:g}_s{args.min_train_sigma:g}-{args.max_train_sigma:g}" + f"_b{args.bridge_loss_weight:g}_band{args.band_loss_weight:g}" + f"_rec{args.reconstruction_loss_weight:g}_temp{args.temporal_loss_weight:g}" + f"_lr{args.learning_rate:g}_seed{args.seed}" + ).replace(".", "p") + + +def train(args) -> None: + random.seed(args.seed) + torch.manual_seed(args.seed) + save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None + if args.output_path is None: + args.output_path = str(Path(args.output_root) / build_run_name(args)) + dataset_kwargs = dict( + video_dir=args.video_dir, prompt_json=args.prompt_json, prompt_field=args.prompt_field, + default_prompt=args.default_prompt, height=args.height, width=args.width, + num_frames=args.num_frames, sr_scale=args.sr_scale, source_mode="upsampler", + ) + train_set = SeedanceWaveletBridgeDataset(**dataset_kwargs, repeat=args.dataset_repeat, limit_videos=args.limit_videos, seed=args.seed) + val_set = SeedanceWaveletBridgeDataset(**dataset_kwargs, repeat=1, limit_videos=max(args.val_batches, 1), seed=args.seed + 1) + model = WaveletBridgeTrainingModule(args) + accelerator = Accelerator( + gradient_accumulation_steps=args.gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)], + ) + if accelerator.is_main_process: + Path(args.output_path).mkdir(parents=True, exist_ok=True) + (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8") + print(f"[Output] {args.output_path}") + if args.validation_only or args.max_train_steps <= 0: + model = accelerator.prepare(model) + validate(args, accelerator, model, val_set, 0) + return + + optimizer = torch.optim.AdamW(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay) + loader = DataLoader(train_set, shuffle=True, collate_fn=lambda batch: batch[0], num_workers=args.dataset_num_workers) + model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + logger = ModelLogger(args.output_path, remove_prefix_in_ckpt="pipe.dit.") + if args.validate_at_start: + validate(args, accelerator, model, val_set, 0) + step = 0 + while step < args.max_train_steps: + for data in tqdm(loader, disable=not accelerator.is_local_main_process): + with accelerator.accumulate(model): + optimizer.zero_grad() + loss, metrics = model(data) + accelerator.backward(loss) + if args.max_grad_norm > 0: + accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) + optimizer.step() + if accelerator.sync_gradients: + step += 1 + logger.on_step_end(accelerator, model, save_steps) + if accelerator.is_main_process and step % args.log_interval == 0: + fields = " ".join(f"{key}={value:.6f}" for key, value in metrics.items()) + print(f"[Train step {step}] total={float(loss.detach().cpu()):.6f} {fields}") + if args.val_interval > 0 and step % args.val_interval == 0: + validate(args, accelerator, model, val_set, step) + if step >= args.max_train_steps: + break + logger.on_training_end(accelerator, model, save_steps) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Train a random Brownian Wan Bridge in latent Haar HF subbands, with optional one-step inference.") + parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B") + parser.add_argument("--model_paths", default=None) + parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl") + parser.add_argument("--bridge_checkpoint", default="/cache/outputs_bridge_wan_sr/wan_sr_x2_480x832_f81_upsampler_up_1K-ultraLatentUpsampler-step_19900_lr1_noise1_bridge1_lpips1_wav15_pix8_pcrop256_plf3_seed42/step-3500.safetensors") + parser.add_argument("--resume_checkpoint", default=None) + parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0") + parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl") + parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p") + parser.add_argument("--default_prompt", default="") + parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr_wavelet") + parser.add_argument("--output_path", default=None) + parser.add_argument("--height", type=int, default=480) + parser.add_argument("--width", type=int, default=832) + parser.add_argument("--num_frames", type=int, default=81) + parser.add_argument("--sr_scale", type=int, default=2) + parser.add_argument("--latent_channels", type=int, default=16) + parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference") + parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py") + parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth") + parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16") + parser.add_argument("--train_timesteps", type=int, default=1000, help="Resolution of the random Brownian training-sigma schedule; inference can still use one step.") + parser.add_argument("--sigma_shift", type=float, default=5.0) + parser.add_argument("--noise_sigma", type=float, default=1.0, help="Brownian noise amplitude multiplying sqrt(sigma*(1-sigma))*epsilon.") + parser.add_argument("--min_train_sigma", type=float, default=0.02) + parser.add_argument("--max_train_sigma", type=float, default=0.98) + parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift") + parser.add_argument("--bridge_loss_weight", type=float, default=1.0) + parser.add_argument("--band_loss_weight", type=float, default=1.0) + parser.add_argument("--reconstruction_loss_weight", type=float, default=1.0) + parser.add_argument("--temporal_loss_weight", type=float, default=0.2) + parser.add_argument("--learning_rate", type=float, default=1e-5) + parser.add_argument("--weight_decay", type=float, default=0.01) + parser.add_argument("--max_train_steps", type=int, default=5000) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--max_grad_norm", type=float, default=1.0) + parser.add_argument("--save_steps", type=int, default=500) + parser.add_argument("--log_interval", type=int, default=1) + parser.add_argument("--val_interval", type=int, default=100) + parser.add_argument("--val_batches", type=int, default=1) + parser.add_argument("--val_inference_steps", type=int, default=1) + parser.add_argument("--val_noise_sigma", type=float, default=0.0) + parser.add_argument("--validate_at_start", action="store_true") + parser.add_argument("--validation_only", action="store_true") + parser.add_argument("--limit_videos", type=int, default=None) + parser.add_argument("--dataset_repeat", type=int, default=1) + parser.add_argument("--dataset_num_workers", type=int, default=0) + parser.add_argument("--text_drop_probability", type=float, default=0.0) + parser.add_argument("--use_gradient_checkpointing", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument("--use_gradient_checkpointing_offload", action="store_true") + parser.add_argument("--find_unused_parameters", action="store_true") + parser.add_argument("--tiled", action="store_true") + parser.add_argument("--tile_h", type=int, default=30) + parser.add_argument("--tile_w", type=int, default=52) + parser.add_argument("--tile_stride_h", type=int, default=15) + parser.add_argument("--tile_stride_w", type=int, default=26) + parser.add_argument("--fps", type=int, default=16) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + if args.model_paths is None: + args.model_paths = default_model_paths(args.base_model_dir) + return args + + +if __name__ == "__main__": + os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + train(parse_args()) diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7c60faa995440c6b51c51f72fb53654ad1dc597 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +ARGS=( + diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py + --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" + --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" + --bridge_checkpoint "${BRIDGE_CHECKPOINT:-/cache/outputs_bridge_wan_sr/wan_sr_x2_480x832_f81_upsampler_up_1K-ultraLatentUpsampler-step_19900_lr1_noise1_bridge1_lpips1_wav15_pix8_pcrop256_plf3_seed42/step-3500.safetensors}" + --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" + --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" + --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_wavelet}" + --height "${HEIGHT:-480}" + --width "${WIDTH:-832}" + --num_frames "${NUM_FRAMES:-81}" + --sr_scale "${SR_SCALE:-2}" + --ultraflash_dir "${ULTRAFLASH_DIR:-/home/ma-user/workspace/rongxiang/UltraFlash/inference}" + --ultraflash_sr_config "${ULTRAFLASH_SR_CONFIG:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py}" + --latent_upsampler_ckpt "${LATENT_UPSAMPLER_CKPT:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth}" + --train_timesteps "${TRAIN_TIMESTEPS:-1000}" + --sigma_shift "${SIGMA_SHIFT:-5}" + --noise_sigma "${NOISE_SIGMA:-1}" + --min_train_sigma "${MIN_TRAIN_SIGMA:-0.02}" + --max_train_sigma "${MAX_TRAIN_SIGMA:-0.98}" + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1}" + --band_loss_weight "${BAND_LOSS_WEIGHT:-1}" + --reconstruction_loss_weight "${RECONSTRUCTION_LOSS_WEIGHT:-1}" + --temporal_loss_weight "${TEMPORAL_LOSS_WEIGHT:-0.5}" + --learning_rate "${LEARNING_RATE:-1e-5}" + --weight_decay "${WEIGHT_DECAY:-0.01}" + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" + --gradient_accumulation_steps "${GRADIENT_ACCUMULATION_STEPS:-1}" + --save_steps "${SAVE_STEPS:-500}" + --val_interval "${VAL_INTERVAL:-100}" + --val_batches "${VAL_BATCHES:-1}" + --val_inference_steps "${VAL_INFERENCE_STEPS:-1}" + --dataset_repeat "${DATASET_REPEAT:-1}" + --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" + --validate_at_start +) + +if [[ -n "${LIMIT_VIDEOS:-}" ]]; then ARGS+=(--limit_videos "${LIMIT_VIDEOS}"); fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then ARGS+=(--output_path "${OUTPUT_PATH}"); fi +if [[ -n "${RESUME_CHECKPOINT:-}" ]]; then ARGS+=(--resume_checkpoint "${RESUME_CHECKPOINT}"); fi +if [[ "${TILED:-0}" == "1" ]]; then ARGS+=(--tiled); fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh new file mode 100644 index 0000000000000000000000000000000000000000..d825afd483a804dccb3afa6afffefdb0f820131d --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}" +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" + +TRAIN_SCRIPT="diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py" + +ARGS=( + "${TRAIN_SCRIPT}" + --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" + --dit_init_checkpoint "${DIT_INIT_CHECKPOINT:-/cache/UltraFlash/2K-Causal-Sparse-SR-Dit-fidelity-step_12800.pth}" + --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" + --dataset_root "${DATASET_ROOT:-/cache/OpenVE-OneShard-5k}" + --manifest_path "${MANIFEST_PATH:-/cache/OpenVE-OneShard-5k/metadata.json}" + --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan21_openve_one_shard_5k}" + --height "${HEIGHT:-480}" + --width "${WIDTH:-832}" + --num_frames "${NUM_FRAMES:-81}" + --sr_scale "${SR_SCALE:-4}" + --fps "${FPS:-20}" + --dataset_repeat "${DATASET_REPEAT:-1}" + --dataset_num_workers "${DATASET_NUM_WORKERS:-8}" + --torch_dtype "${TORCH_DTYPE:-float16}" + --max_train_steps "${MAX_TRAIN_STEPS:-5000}" + --gradient_accumulation_steps "${GRADIENT_ACCUMULATION_STEPS:-1}" + --trainable_models "${TRAINABLE_MODELS:-dit}" + --lora_target_modules "${LORA_TARGET_MODULES:-q,k,v,o,ffn.0,ffn.2}" + --lora_rank "${LORA_RANK:-32}" + --learning_rate "${LEARNING_RATE:-1.0}" + --weight_decay "${WEIGHT_DECAY:-0.01}" + --d_coef "${D_COEF:-1.0}" + --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" + --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-2.0}" + --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" + --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" + --lpips_weight "${LPIPS_WEIGHT:-1.0}" + --lpips_net "${LPIPS_NET:-vgg}" + --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" + --lpips_crop_size "${LPIPS_CROP_SIZE:-224}" + --ssim_weight "${SSIM_WEIGHT:-1.0}" + --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" + --noise_sigma "${NOISE_SIGMA:-1.0}" + --val_sampling_noise_scale "${VAL_SAMPLING_NOISE_SCALE:-0.0}" + --val_interval "${VAL_INTERVAL:-100}" + --val_samples_per_task "${VAL_SAMPLES_PER_TASK:-2}" + --val_inference_steps "${VAL_INFERENCE_STEPS:-8}" + --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}" + --save_steps "${SAVE_STEPS:-400}" + --seed "${SEED:-42}" +) + +if [[ -n "${LORA_CHECKPOINT:-}" ]]; then + ARGS+=(--lora_checkpoint "${LORA_CHECKPOINT}") +fi +if [[ -n "${OUTPUT_PATH:-}" ]]; then + ARGS+=(--output_path "${OUTPUT_PATH}") +fi +if [[ -n "${LIMIT_SAMPLES:-}" ]]; then + ARGS+=(--limit_samples "${LIMIT_SAMPLES}") +fi +if [[ "${VAL_LPIPS:-1}" != "0" ]]; then + ARGS+=(--val_lpips) +fi +if [[ "${VAL_SSIM:-1}" != "0" ]]; then + ARGS+=(--val_ssim) +fi +if [[ "${TILED:-0}" != "0" ]]; then + ARGS+=(--tiled) +fi +if [[ "${VALIDATE_AT_START:-1}" != "0" ]]; then + ARGS+=(--validate_at_start) +fi +if [[ "${USE_GRADIENT_CHECKPOINTING_OFFLOAD:-0}" != "0" ]]; then + ARGS+=(--use_gradient_checkpointing_offload) +fi + +"${PYTHON_BIN}" "${ARGS[@]}" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit_npu.sh b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit_npu.sh new file mode 100644 index 0000000000000000000000000000000000000000..1fec786fe9612977d7767ee274f86fb5b31e86f3 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit_npu.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +cd "${REPO_DIR}" + +SYSTEM_CANN_ROOT="${SYSTEM_CANN_ROOT:-/usr/local/Ascend/cann-8.5.2}" +CANN_ROOT="${CANN_ROOT:-/temp/rongxiang/cann-user-8.5.2}" + +# The ModelArts image has the compiler/runtime but an incomplete 910B OPP +# directory. Use the persistent user-space CANN archive for OPP kernels and +# keep the system compiler/runtime as the ABI-compatible base. +source "${SYSTEM_CANN_ROOT}/set_env.sh" 2>/dev/null || true +if [[ -d "${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe/kernel/ascend910b" ]]; then + export ASCEND_HOME_PATH="${SYSTEM_CANN_ROOT}" + export ASCEND_TOOLKIT_HOME="${SYSTEM_CANN_ROOT}" + export ASCEND_AICPU_PATH="${SYSTEM_CANN_ROOT}" + export ASCEND_COMPILER_PATH="${SYSTEM_CANN_ROOT}/compiler" + export ASCEND_OPP_PATH="${CANN_ROOT}/opp" + export TBE_IMPL_PATH="${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe" + export PYTHONPATH="${CANN_ROOT}/python/site-packages:${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe:${PYTHONPATH:-}" + export LD_LIBRARY_PATH="${CANN_ROOT}/aarch64-linux/lib64/plugin/opskernel:${CANN_ROOT}/aarch64-linux/lib64/plugin/nnengine:${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe/op_tiling/lib/linux/aarch64:${CANN_ROOT}/aarch64-linux/lib64:${CANN_ROOT}/opp/lib64:${SYSTEM_CANN_ROOT}/compiler/lib64:${SYSTEM_CANN_ROOT}/lib64:${SYSTEM_CANN_ROOT}/runtime/lib64:${LD_LIBRARY_PATH:-}" +else + echo "Warning: complete CANN OPP archive not found at ${CANN_ROOT}; using system CANN." >&2 +fi + +PYTHON_BIN="${PYTHON_BIN:-/home/ma-user/anaconda3/envs/PyTorch-2.7.1/bin/python}" +export PYTHON_BIN +export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}" +export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}" +export ASCEND_RT_VISIBLE_DEVICES="${ASCEND_RT_VISIBLE_DEVICES:-0,1,2,3,4,5,6,7}" +export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-1800}" +export TASK_QUEUE_ENABLE="${TASK_QUEUE_ENABLE:-2}" +export COMBINED_ENABLE="${COMBINED_ENABLE:-1}" +export SOC_VERSION="${SOC_VERSION:-Ascend910B3}" +export ASCEND_SOC_VERSION="${ASCEND_SOC_VERSION:-${SOC_VERSION}}" + +# Some ModelArts login profiles export stale custom paths. They must not +# override the selected OPP archive. +unset ASCEND_CUSTOM_OPP_PATH ME_TBE_PLUGIN_PATH OPTION_EXEC_EXTERN_PLUGIN_PATH + +# Keep NPU assets and outputs separate from the A100 run. +export BASE_MODEL_DIR="${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" +export DATASET_ROOT="${DATASET_ROOT:-/cache/OpenVE-OneShard-5k}" +export MANIFEST_PATH="${MANIFEST_PATH:-/cache/OpenVE-OneShard-5k/metadata.json}" +export OUTPUT_ROOT="${OUTPUT_ROOT:-/cache/outputs_bridge_wan21_openve_one_shard_5k_npu}" +export DATASET_NUM_WORKERS="${DATASET_NUM_WORKERS:-1}" +export TORCH_DTYPE="${TORCH_DTYPE:-float16}" +export VAL_LPIPS="${VAL_LPIPS:-0}" +export VAL_SSIM="${VAL_SSIM:-0}" +export VALIDATE_AT_START="${VALIDATE_AT_START:-0}" + +NNODES="${NNODES:-1}" +NPROC_PER_NODE="${NPROC_PER_NODE:-8}" +MASTER_ADDR="${MASTER_ADDR:-127.0.0.1}" +MASTER_PORT="${MASTER_PORT:-29688}" + +export MASTER_ADDR MASTER_PORT + +exec "${PYTHON_BIN}" -m torch.distributed.run \ + --no_python \ + --nnodes="${NNODES}" \ + --nproc_per_node="${NPROC_PER_NODE}" \ + --master_addr="${MASTER_ADDR}" \ + --master_port="${MASTER_PORT}" \ + "${REPO_DIR}/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh" "$@" diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/visualize_sobel_edges.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/visualize_sobel_edges.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ded6ce319064a3a4a79492c081ee32d4a2cce0 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/visualize_sobel_edges.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Visualize the exact Sobel edge mask used by reference-adapter training.""" + +import argparse +import json +from pathlib import Path + +import imageio +import numpy as np +import torch +import torchvision.transforms.functional as TVF +from PIL import Image, ImageDraw + +from sobel_utils import dilated_sobel_edge_mask, sobel_rgb_gradients + +REPO_ROOT = Path(__file__).resolve().parents[4] + + +def center_crop_resize(image: Image.Image, height: int, width: int) -> Image.Image: + """Match the training pipeline's bicubic resize followed by center crop.""" + image_w, image_h = image.size + scale = max(width / image_w, height / image_h) + resized = TVF.resize( + image, + (round(image_h * scale), round(image_w * scale)), + interpolation=TVF.InterpolationMode.BICUBIC, + ) + return TVF.center_crop(resized, (height, width)) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Render original/Sobel/thin-mask/dilated-mask/overlay panels for a video." + ) + parser.add_argument("--input_video", required=True) + parser.add_argument("--output_video", default=None) + parser.add_argument("--height", type=int, default=832) + parser.add_argument("--width", type=int, default=480) + parser.add_argument( + "--no_resize", + action="store_true", + help="Keep the source resolution instead of applying the training center-crop resize.", + ) + parser.add_argument("--start_frame", type=int, default=0) + parser.add_argument("--num_frames", type=int, default=0, help="0 means all remaining frames.") + parser.add_argument("--fps", type=float, default=None, help="Defaults to the source FPS, then 16.") + parser.add_argument("--sobel_edge_dilation_radius", type=int, default=0) + parser.add_argument("--sobel_edge_threshold", type=float, default=1.0) + parser.add_argument( + "--magnitude_display_scale", + type=float, + default=3.0, + help="Display white is threshold times this value; this affects visualization only.", + ) + return parser.parse_args() + + +def default_output_path(input_path: Path, radius: int, threshold: float) -> Path: + threshold_text = f"{threshold:g}".replace(".", "p") + return REPO_ROOT / "outputs" / "sobel_visualizations" / ( + f"{input_path.stem}_sobel_r{radius}_thr{threshold_text}.mp4" + ) + + +def uint8_rgb(tensor_chw: torch.Tensor) -> np.ndarray: + return ( + tensor_chw.detach() + .clamp(0, 1) + .mul(255) + .round() + .byte() + .permute(1, 2, 0) + .cpu() + .numpy() + ) + + +def add_labels(canvas: np.ndarray, labels: list[str], panel_width: int) -> np.ndarray: + image = Image.fromarray(canvas) + draw = ImageDraw.Draw(image) + bar_height = 30 + for index, label in enumerate(labels): + left = index * panel_width + draw.rectangle((left, 0, left + panel_width, bar_height), fill=(0, 0, 0)) + draw.text((left + 8, 8), label, fill=(255, 255, 255)) + return np.asarray(image) + + +def render_frame( + frame: np.ndarray, + height: int, + width: int, + no_resize: bool, + dilation_radius: int, + threshold_multiplier: float, + magnitude_display_scale: float, +) -> tuple[np.ndarray, dict[str, float]]: + image = Image.fromarray(np.asarray(frame)).convert("RGB") + if not no_resize: + image = center_crop_resize(image, height, width) + + original = torch.from_numpy(np.asarray(image).copy()).permute(2, 0, 1).float().div(255.0) + video = original.unsqueeze(0).unsqueeze(0) + gradient_x, gradient_y = sobel_rgb_gradients(video) + magnitude, threshold, thin_mask, dilated_mask = dilated_sobel_edge_mask( + gradient_x, + gradient_y, + dilation_radius=dilation_radius, + threshold_multiplier=threshold_multiplier, + ) + + display_denominator = threshold * max(float(magnitude_display_scale), 1e-6) + 1e-12 + magnitude_rgb = (magnitude / display_denominator).clamp(0, 1).repeat(1, 3, 1, 1)[0] + thin_rgb = thin_mask.repeat(1, 3, 1, 1)[0] + dilated_rgb = dilated_mask.repeat(1, 3, 1, 1)[0] + + overlay = original.clone() + dilated = dilated_mask[0] + thin = thin_mask[0] + red = original.new_tensor([1.0, 0.0, 0.0]).view(3, 1, 1) + yellow = original.new_tensor([1.0, 1.0, 0.0]).view(3, 1, 1) + overlay = overlay * (1.0 - 0.40 * dilated) + red * (0.40 * dilated) + overlay = overlay * (1.0 - 0.85 * thin) + yellow * (0.85 * thin) + + panels = [ + uint8_rgb(original), + uint8_rgb(magnitude_rgb), + uint8_rgb(thin_rgb), + uint8_rgb(dilated_rgb), + uint8_rgb(overlay), + ] + labels = [ + "Original", + "Sobel magnitude", + "Thin edge mask", + f"Dilated mask (r={dilation_radius})", + "Overlay", + ] + visualization = add_labels(np.concatenate(panels, axis=1), labels, original.shape[-1]) + metrics = { + "threshold": float(threshold.item()), + "thin_edge_ratio": float(thin_mask.mean().item()), + "dilated_edge_ratio": float(dilated_mask.mean().item()), + "mean_magnitude": float(magnitude.mean().item()), + } + return visualization, metrics + + +def main() -> None: + args = parse_args() + input_path = Path(args.input_video).expanduser().resolve() + if not input_path.is_file(): + raise FileNotFoundError(f"Input video does not exist: {input_path}") + if args.start_frame < 0 or args.num_frames < 0: + raise ValueError("start_frame and num_frames must be non-negative") + + output_path = ( + Path(args.output_video).expanduser().resolve() + if args.output_video + else default_output_path(input_path, args.sobel_edge_dilation_radius, args.sobel_edge_threshold) + ) + output_path.parent.mkdir(parents=True, exist_ok=True) + + reader = imageio.get_reader(str(input_path)) + metadata = reader.get_meta_data() + fps = float(args.fps or metadata.get("fps") or 16.0) + writer = imageio.get_writer( + str(output_path), fps=fps, codec="libx264", quality=7, macro_block_size=1 + ) + + frame_metrics: list[dict[str, float | int]] = [] + preview_path = output_path.with_name(f"{output_path.stem}_preview.jpg") + try: + frame_index = args.start_frame + while args.num_frames == 0 or len(frame_metrics) < args.num_frames: + try: + frame = reader.get_data(frame_index) + except (IndexError, EOFError): + break + visualization, metrics = render_frame( + frame=frame, + height=args.height, + width=args.width, + no_resize=args.no_resize, + dilation_radius=args.sobel_edge_dilation_radius, + threshold_multiplier=args.sobel_edge_threshold, + magnitude_display_scale=args.magnitude_display_scale, + ) + writer.append_data(visualization) + if not frame_metrics: + Image.fromarray(visualization).save(preview_path, quality=95) + frame_metrics.append({"frame_index": frame_index, **metrics}) + frame_index += 1 + finally: + writer.close() + reader.close() + + if not frame_metrics: + output_path.unlink(missing_ok=True) + raise RuntimeError(f"No frames were read from {input_path} at start_frame={args.start_frame}") + + summary = { + "input_video": str(input_path), + "output_video": str(output_path), + "preview_image": str(preview_path), + "fps": fps, + "processed_frames": len(frame_metrics), + "preprocessing": "source resolution" if args.no_resize else "training center-crop resize", + "height": int(frame_metrics and visualization.shape[0]), + "panel_width": int(visualization.shape[1] // 5), + "sobel_kernel_normalization": "1/8", + "sobel_edge_dilation_radius": args.sobel_edge_dilation_radius, + "dilation_kernel_size": 2 * args.sobel_edge_dilation_radius + 1, + "sobel_edge_threshold_multiplier": args.sobel_edge_threshold, + "threshold_rule": "per-frame mean RGB Sobel magnitude * multiplier", + "mean_threshold": float(np.mean([row["threshold"] for row in frame_metrics])), + "mean_thin_edge_ratio": float(np.mean([row["thin_edge_ratio"] for row in frame_metrics])), + "mean_dilated_edge_ratio": float(np.mean([row["dilated_edge_ratio"] for row in frame_metrics])), + "frames": frame_metrics, + } + json_path = output_path.with_suffix(".json") + with json_path.open("w", encoding="utf-8") as file: + json.dump(summary, file, ensure_ascii=False, indent=2) + + print(f"Saved visualization: {output_path}") + print(f"Saved preview: {preview_path}") + print(f"Saved statistics: {json_path}") + print( + f"Frames={len(frame_metrics)}, thin={summary['mean_thin_edge_ratio']:.4f}, " + f"dilated={summary['mean_dilated_edge_ratio']:.4f}" + ) + + +if __name__ == "__main__": + main() diff --git a/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/wan_video_new.py b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/wan_video_new.py new file mode 100644 index 0000000000000000000000000000000000000000..88752da63f6514a5ebfdb5681203bcff2e192845 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/wan_video_new.py @@ -0,0 +1,1751 @@ +import torch, warnings, glob, os, types +import numpy as np +from PIL import Image +from einops import repeat, reduce +from typing import Optional, Union +from dataclasses import dataclass +try: + from modelscope import snapshot_download +except ModuleNotFoundError: + snapshot_download = None +from einops import rearrange +import numpy as np +from PIL import Image +from tqdm import tqdm +from typing import Optional +from typing_extensions import Literal + +from ..utils import BasePipeline, ModelConfig, PipelineUnit, PipelineUnitRunner +from ..models.model_manager import ModelManager +from ..models.utils import load_state_dict +from ..models.wan_video_dit import WanModel, RMSNorm, sinusoidal_embedding_1d +from ..models.wan_video_dit_s2v import rope_precompute +from ..models.wan_video_text_encoder import WanTextEncoder, T5RelativeEmbedding, T5LayerNorm +from ..models.wan_video_vae import WanVideoVAE, RMS_norm, CausalConv3d, Upsample +from ..models.wan_video_image_encoder import WanImageEncoder +from ..models.wan_video_vace import VaceWanModel +from ..models.wan_video_motion_controller import WanMotionControllerModel +from ..models.wan_video_animate_adapter import WanAnimateAdapter +from ..schedulers.flow_match import FlowMatchScheduler +from ..prompters.wan_prompter import WanPrompter +from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear, WanAutoCastLayerNorm +from ..lora import GeneralLoRALoader +from .attention_masks import build_token_prefix_attention_spec + + + +def make_device_tensor(values, device, dtype): + return torch.as_tensor(values, dtype=torch.float32).to(device=device, dtype=dtype) + + +class WanVideoPipeline(BasePipeline): + + def __init__(self, device="npu", torch_dtype=torch.float16, tokenizer_path=None): + super().__init__( + device=device, torch_dtype=torch_dtype, + height_division_factor=16, width_division_factor=16, time_division_factor=4, time_division_remainder=1 + ) + 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.image_encoder: WanImageEncoder = None + self.dit: WanModel = None + self.dit2: WanModel = None + self.vae: WanVideoVAE = None + self.motion_controller: WanMotionControllerModel = None + self.vace: VaceWanModel = None + self.vace2: VaceWanModel = None + self.animate_adapter: WanAnimateAdapter = None + self.in_iteration_models = ("dit", "motion_controller", "vace", "animate_adapter") + self.in_iteration_models_2 = ("dit2", "motion_controller", "vace2", "animate_adapter") + self.unit_runner = PipelineUnitRunner() + self.units = [ + WanVideoUnit_ShapeChecker(), + WanVideoUnit_NoiseInitializer(), + WanVideoUnit_PromptEmbedder(), + WanVideoUnit_S2V(), + WanVideoUnit_InputVideoEmbedder(), + WanVideoUnit_ImageEmbedderVAE(), + WanVideoUnit_ImageEmbedderCLIP(), + WanVideoUnit_ImageEmbedderFused(), + WanVideoUnit_FunControl(), + WanVideoUnit_FunReference(), + WanVideoUnit_FunCameraControl(), + WanVideoUnit_SpeedControl(), + WanVideoUnit_VACE(), + WanVideoPostUnit_AnimateVideoSplit(), + WanVideoPostUnit_AnimatePoseLatents(), + WanVideoPostUnit_AnimateFacePixelValues(), + WanVideoPostUnit_AnimateInpaint(), + WanVideoUnit_UnifiedSequenceParallel(), + WanVideoUnit_TeaCache(), + WanVideoUnit_CfgMerger(), + ] + self.post_units = [ + WanVideoPostUnit_S2V(), + ] + self.model_fn = model_fn_wan_video + + def load_lora( + self, + module: torch.nn.Module, + lora_config: Union[ModelConfig, str] = None, + alpha=1, + hotload=False, + state_dict=None, + ): + if state_dict is None: + if isinstance(lora_config, str): + lora = load_state_dict(lora_config, torch_dtype=self.torch_dtype, device=self.device) + else: + lora_config.download_if_necessary() + lora = load_state_dict(lora_config.path, torch_dtype=self.torch_dtype, device=self.device) + else: + lora = state_dict + if hotload: + for name, module in module.named_modules(): + if isinstance(module, AutoWrappedLinear): + lora_a_name = f'{name}.lora_A.default.weight' + lora_b_name = f'{name}.lora_B.default.weight' + if lora_a_name in lora and lora_b_name in lora: + module.lora_A_weights.append(lora[lora_a_name] * alpha) + module.lora_B_weights.append(lora[lora_b_name]) + else: + loader = GeneralLoRALoader(torch_dtype=self.torch_dtype, device=self.device) + loader.load(module, lora, alpha=alpha) + + def training_loss(self, **inputs): + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps) + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + + inputs["latents"] = self.scheduler.add_noise(inputs["input_latents"], inputs["noise"], timestep) + training_target = self.scheduler.training_target(inputs["input_latents"], inputs["noise"], timestep) + + noise_pred = self.model_fn(**inputs, timestep=timestep) + + loss = torch.nn.functional.mse_loss(noise_pred.float(), training_target.float()) + loss = loss * self.scheduler.training_weight(timestep) + return loss + + + def enable_vram_management(self, num_persistent_param_in_dit=None, vram_limit=None, vram_buffer=0.5): + self.vram_management_enabled = True + if num_persistent_param_in_dit is not None: + vram_limit = None + else: + if vram_limit is None: + vram_limit = self.get_vram() + vram_limit = vram_limit - vram_buffer + if self.text_encoder is not 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, + ), + vram_limit=vram_limit, + ) + if self.dit is not None: + dtype = next(iter(self.dit.parameters())).dtype + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.dit, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv3d: AutoWrappedModule, + torch.nn.LayerNorm: WanAutoCastLayerNorm, + RMSNorm: AutoWrappedModule, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.Conv1d: AutoWrappedModule, + torch.nn.Embedding: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device=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, + ), + vram_limit=vram_limit, + ) + if self.dit2 is not None: + dtype = next(iter(self.dit2.parameters())).dtype + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.dit2, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv3d: AutoWrappedModule, + torch.nn.LayerNorm: WanAutoCastLayerNorm, + RMSNorm: AutoWrappedModule, + torch.nn.Conv2d: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device=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, + ), + vram_limit=vram_limit, + ) + if self.vae is not None: + 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, + ), + ) + if self.image_encoder is not None: + dtype = next(iter(self.image_encoder.parameters())).dtype + enable_vram_management( + self.image_encoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.LayerNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=dtype, + computation_device=self.device, + ), + ) + if self.motion_controller is not None: + dtype = next(iter(self.motion_controller.parameters())).dtype + enable_vram_management( + self.motion_controller, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=dtype, + computation_device=self.device, + ), + ) + if self.vace is not None: + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.vace, + 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=device, + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + vram_limit=vram_limit, + ) + if self.audio_encoder is not None: + # TODO: need check + dtype = next(iter(self.audio_encoder.parameters())).dtype + enable_vram_management( + self.audio_encoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.LayerNorm: AutoWrappedModule, + torch.nn.Conv1d: 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, + ), + ) + + + def initialize_usp(self): + import torch.distributed as dist + from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment + backend = "hccl" if getattr(torch, "npu", None) is not None and torch.npu.is_available() else "nccl" + dist.init_process_group(backend=backend, init_method="env://") + init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size()) + initialize_model_parallel( + sequence_parallel_degree=dist.get_world_size(), + ring_degree=1, + ulysses_degree=dist.get_world_size(), + ) + if backend == "hccl": + torch.npu.set_device(dist.get_rank()) + else: + torch.cuda.set_device(dist.get_rank()) + + + def enable_usp(self): + from xfuser.core.distributed import get_sequence_parallel_world_size + from ..distributed.xdit_context_parallel import usp_attn_forward, usp_dit_forward + + for block in self.dit.blocks: + block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn) + self.dit.forward = types.MethodType(usp_dit_forward, self.dit) + if self.dit2 is not None: + for block in self.dit2.blocks: + block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn) + self.dit2.forward = types.MethodType(usp_dit_forward, self.dit2) + self.sp_size = get_sequence_parallel_world_size() + self.use_unified_sequence_parallel = True + + + @classmethod + def from_pretrained( + cls, + torch_dtype: torch.dtype = torch.float16, + device: Union[str, torch.device] = "npu", + model_configs: list[ModelConfig] = [], + tokenizer_config: ModelConfig = ModelConfig(model_id="Wan-AI/Wan2.1-T2V-1.3B", origin_file_pattern="google/*"), + audio_processor_config: ModelConfig = None, + redirect_common_files: bool = True, + use_usp=False, + ): + # Redirect model path + if redirect_common_files: + redirect_dict = { + "models_t5_umt5-xxl-enc-bf16.pth": "Wan-AI/Wan2.1-T2V-1.3B", + "Wan2.1_VAE.pth": "Wan-AI/Wan2.1-T2V-1.3B", + "models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth": "Wan-AI/Wan2.1-I2V-14B-480P", + } + for model_config in model_configs: + if model_config.origin_file_pattern is None or model_config.model_id is None: + continue + if model_config.origin_file_pattern in redirect_dict and model_config.model_id != redirect_dict[model_config.origin_file_pattern]: + print(f"To avoid repeatedly downloading model files, ({model_config.model_id}, {model_config.origin_file_pattern}) is redirected to ({redirect_dict[model_config.origin_file_pattern]}, {model_config.origin_file_pattern}). You can use `redirect_common_files=False` to disable file redirection.") + model_config.model_id = redirect_dict[model_config.origin_file_pattern] + + # Initialize pipeline + pipe = cls(device=device, torch_dtype=torch_dtype) + if use_usp: pipe.initialize_usp() + + # Download and load models + model_manager = ModelManager() + for model_config in model_configs: + model_config.download_if_necessary(use_usp=use_usp) + model_manager.load_model( + model_config.path, + device=model_config.offload_device or device, + torch_dtype=model_config.offload_dtype or torch_dtype + ) + + # Load models + pipe.text_encoder = model_manager.fetch_model("wan_video_text_encoder") + dit = model_manager.fetch_model("wan_video_dit", index=2) + if isinstance(dit, list): + pipe.dit, pipe.dit2 = dit + else: + pipe.dit = dit + pipe.vae = model_manager.fetch_model("wan_video_vae") + pipe.image_encoder = model_manager.fetch_model("wan_video_image_encoder") + pipe.motion_controller = model_manager.fetch_model("wan_video_motion_controller") + vace = model_manager.fetch_model("wan_video_vace", index=2) + if isinstance(vace, list): + pipe.vace, pipe.vace2 = vace + else: + pipe.vace = vace + pipe.audio_encoder = model_manager.fetch_model("wans2v_audio_encoder") + pipe.animate_adapter = model_manager.fetch_model("wan_video_animate_adapter") + + # Size division factor + if pipe.vae is not None: + pipe.height_division_factor = pipe.vae.upsampling_factor * 2 + pipe.width_division_factor = pipe.vae.upsampling_factor * 2 + + # Initialize tokenizer + tokenizer_config.download_if_necessary(use_usp=use_usp) + pipe.prompter.fetch_models(pipe.text_encoder) + pipe.prompter.fetch_tokenizer(tokenizer_config.path) + + if audio_processor_config is not None: + audio_processor_config.download_if_necessary(use_usp=use_usp) + from transformers import Wav2Vec2Processor + pipe.audio_processor = Wav2Vec2Processor.from_pretrained(audio_processor_config.path) + # Unified Sequence Parallel + if use_usp: pipe.enable_usp() + return pipe + + + @torch.no_grad() + def __call__( + self, + # Prompt + prompt: str, + negative_prompt: Optional[str] = "", + # Image-to-video + input_image: Optional[Image.Image] = None, + # First-last-frame-to-video + end_image: Optional[Image.Image] = None, + # Video-to-video + input_video: Optional[list[Image.Image]] = None, + denoising_strength: Optional[float] = 1.0, + # Speech-to-video + input_audio: Optional[np.array] = None, + audio_embeds: Optional[torch.Tensor] = None, + audio_sample_rate: Optional[int] = 16000, + s2v_pose_video: Optional[list[Image.Image]] = None, + s2v_pose_latents: Optional[torch.Tensor] = None, + motion_video: Optional[list[Image.Image]] = None, + # ControlNet + control_video: Optional[list[Image.Image]] = None, + reference_image: Optional[Image.Image] = None, + # Camera control + camera_control_direction: Optional[Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown"]] = None, + camera_control_speed: Optional[float] = 1/54, + camera_control_origin: Optional[tuple] = (0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0), + # VACE + vace_video: Optional[list[Image.Image]] = None, + vace_video_mask: Optional[Image.Image] = None, + vace_reference_image: Optional[Image.Image] = None, + vace_scale: Optional[float] = 1.0, + # Animate + animate_pose_video: Optional[list[Image.Image]] = None, + animate_face_video: Optional[list[Image.Image]] = None, + animate_inpaint_video: Optional[list[Image.Image]] = None, + animate_mask_video: Optional[list[Image.Image]] = None, + # Randomness + seed: Optional[int] = None, + rand_device: Optional[str] = "cpu", + # Shape + height: Optional[int] = 480, + width: Optional[int] = 832, + num_frames=81, + # Classifier-free guidance + cfg_scale: Optional[float] = 5.0, + cfg_merge: Optional[bool] = False, + # Boundary + switch_DiT_boundary: Optional[float] = 0.875, + # Scheduler + num_inference_steps: Optional[int] = 50, + sigma_shift: Optional[float] = 5.0, + # Speed control + motion_bucket_id: Optional[int] = None, + # VAE tiling + tiled: Optional[bool] = True, + tile_size: Optional[tuple[int, int]] = (30, 52), + tile_stride: Optional[tuple[int, int]] = (15, 26), + # Sliding window + sliding_window_size: Optional[int] = None, + sliding_window_stride: Optional[int] = None, + # Teacache + tea_cache_l1_thresh: Optional[float] = None, + tea_cache_model_id: Optional[str] = "", + # progress_bar + progress_bar_cmd=tqdm, + ): + # Scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength, shift=sigma_shift) + + # Inputs + inputs_posi = { + "prompt": prompt, + "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps, + } + inputs_nega = { + "negative_prompt": negative_prompt, + "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps, + } + inputs_shared = { + "input_image": input_image, + "end_image": end_image, + "input_video": input_video, "denoising_strength": denoising_strength, + "control_video": control_video, "reference_image": reference_image, + "camera_control_direction": camera_control_direction, "camera_control_speed": camera_control_speed, "camera_control_origin": camera_control_origin, + "vace_video": vace_video, "vace_video_mask": vace_video_mask, "vace_reference_image": vace_reference_image, "vace_scale": vace_scale, + "seed": seed, "rand_device": rand_device, + "height": height, "width": width, "num_frames": num_frames, + "cfg_scale": cfg_scale, "cfg_merge": cfg_merge, + "sigma_shift": sigma_shift, + "motion_bucket_id": motion_bucket_id, + "tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride, + "sliding_window_size": sliding_window_size, "sliding_window_stride": sliding_window_stride, + "input_audio": input_audio, "audio_sample_rate": audio_sample_rate, "s2v_pose_video": s2v_pose_video, "audio_embeds": audio_embeds, "s2v_pose_latents": s2v_pose_latents, "motion_video": motion_video, + "animate_pose_video": animate_pose_video, "animate_face_video": animate_face_video, "animate_inpaint_video": animate_inpaint_video, "animate_mask_video": animate_mask_video, + } + for unit in self.units: + inputs_shared, inputs_posi, inputs_nega = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega) + + # Denoise + self.load_models_to_device(self.in_iteration_models) + models = {name: getattr(self, name) for name in self.in_iteration_models} + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + # Switch DiT if necessary + if timestep.item() < switch_DiT_boundary * self.scheduler.num_train_timesteps and self.dit2 is not None and not models["dit"] is self.dit2: + self.load_models_to_device(self.in_iteration_models_2) + models["dit"] = self.dit2 + models["vace"] = self.vace2 + + # Timestep + timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device) + + # Inference + noise_pred_posi = self.model_fn(**models, **inputs_shared, **inputs_posi, timestep=timestep) + if cfg_scale != 1.0: + if cfg_merge: + noise_pred_posi, noise_pred_nega = noise_pred_posi.chunk(2, dim=0) + else: + noise_pred_nega = self.model_fn(**models, **inputs_shared, **inputs_nega, timestep=timestep) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # Scheduler + inputs_shared["latents"] = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], inputs_shared["latents"]) + if "first_frame_latents" in inputs_shared: + inputs_shared["latents"][:, :, 0:1] = inputs_shared["first_frame_latents"] + + # VACE (TODO: remove it) + if vace_reference_image is not None or (animate_pose_video is not None and animate_face_video is not None): + if vace_reference_image is not None and isinstance(vace_reference_image, list): + f = len(vace_reference_image) + else: + f = 1 + inputs_shared["latents"] = inputs_shared["latents"][:, :, f:] + # post-denoising, pre-decoding processing logic + for unit in self.post_units: + inputs_shared, _, _ = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega) + # Decode + self.load_models_to_device(['vae']) + video = self.vae.decode(inputs_shared["latents"], device=self.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + video = self.vae_output_to_video(video) + self.load_models_to_device([]) + + return video + + + +class WanVideoUnit_ShapeChecker(PipelineUnit): + def __init__(self): + super().__init__(input_params=("height", "width", "num_frames")) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames): + height, width, num_frames = pipe.check_resize_height_width(height, width, num_frames) + return {"height": height, "width": width, "num_frames": num_frames} + + + +class WanVideoUnit_NoiseInitializer(PipelineUnit): + def __init__(self): + super().__init__(input_params=("height", "width", "num_frames", "seed", "rand_device", "vace_reference_image")) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames, seed, rand_device, vace_reference_image): + length = (num_frames - 1) // 4 + 1 + if vace_reference_image is not None: + f = len(vace_reference_image) if isinstance(vace_reference_image, list) else 1 + length += f + shape = (1, pipe.vae.model.z_dim, length, height // pipe.vae.upsampling_factor, width // pipe.vae.upsampling_factor) + noise = pipe.generate_noise(shape, seed=seed, rand_device=rand_device) + if vace_reference_image is not None: + noise = torch.concat((noise[:, :, -f:], noise[:, :, :-f]), dim=2) + return {"noise": noise} + + + +class WanVideoUnit_InputVideoEmbedder(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_video", "noise", "tiled", "tile_size", "tile_stride", "vace_reference_image"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_video, noise, tiled, tile_size, tile_stride, vace_reference_image): + if input_video is None: + return {"latents": noise} + pipe.load_models_to_device(["vae"]) + input_video = pipe.preprocess_video(input_video) + input_latents = pipe.vae.encode(input_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + if vace_reference_image is not None: + if not isinstance(vace_reference_image, list): + vace_reference_image = [vace_reference_image] + vace_reference_image = pipe.preprocess_video(vace_reference_image) + vace_reference_latents = pipe.vae.encode(vace_reference_image, device=pipe.device).to(dtype=pipe.torch_dtype, device=pipe.device) + input_latents = torch.concat([vace_reference_latents, input_latents], dim=2) + if pipe.scheduler.training: + return {"latents": noise, "input_latents": input_latents} + else: + latents = pipe.scheduler.add_noise(input_latents, noise, timestep=pipe.scheduler.timesteps[0]) + return {"latents": latents} + + + +class WanVideoUnit_PromptEmbedder(PipelineUnit): + def __init__(self): + super().__init__( + seperate_cfg=True, + input_params_posi={"prompt": "prompt", "positive": "positive"}, + input_params_nega={"prompt": "negative_prompt", "positive": "positive"}, + onload_model_names=("text_encoder",) + ) + + def process(self, pipe: WanVideoPipeline, prompt, positive) -> dict: + pipe.load_models_to_device(self.onload_model_names) + prompt_emb = pipe.prompter.encode_prompt(prompt, positive=positive, device=pipe.device) + return {"context": prompt_emb} + + + +class WanVideoUnit_ImageEmbedder(PipelineUnit): + """ + Deprecated + """ + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("image_encoder", "vae") + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride): + if input_image is None or pipe.image_encoder is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + clip_context = pipe.image_encoder.encode_image([image]) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0,1), torch.zeros(3, num_frames-2, height, width).to(image.device), end_image.transpose(0,1)],dim=1) + if pipe.dit.has_image_pos_emb: + clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1) + msk[:, -1:] = 1 + else: + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + y = torch.concat([msk, y]) + y = y.unsqueeze(0) + clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"clip_feature": clip_context, "y": y} + + + +class WanVideoUnit_ImageEmbedderCLIP(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "height", "width"), + onload_model_names=("image_encoder",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, height, width): + if input_image is None or pipe.image_encoder is None or not pipe.dit.require_clip_embedding: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + clip_context = pipe.image_encoder.encode_image([image]) + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + if pipe.dit.has_image_pos_emb: + clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1) + clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"clip_feature": clip_context} + + + +class WanVideoUnit_ImageEmbedderVAE(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride): + if input_image is None or not pipe.dit.require_vae_embedding: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0,1), torch.zeros(3, num_frames-2, height, width).to(image.device), end_image.transpose(0,1)],dim=1) + msk[:, -1:] = 1 + else: + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + y = torch.concat([msk, y]) + y = y.unsqueeze(0) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"y": y} + + + +class WanVideoUnit_ImageEmbedderFused(PipelineUnit): + """ + Encode input image to latents using VAE. This unit is for Wan-AI/Wan2.2-TI2V-5B. + """ + def __init__(self): + super().__init__( + input_params=("input_image", "latents", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, latents, height, width, tiled, tile_size, tile_stride): + if input_image is None or not pipe.dit.fuse_vae_embedding_in_latents: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).transpose(0, 1) + z = pipe.vae.encode([image], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + latents[:, :, 0: 1] = z + return {"latents": latents, "fuse_vae_embedding_in_latents": True, "first_frame_latents": z} + + + +class WanVideoUnit_FunControl(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("control_video", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride", "clip_feature", "y", "latents"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, control_video, num_frames, height, width, tiled, tile_size, tile_stride, clip_feature, y, latents): + if control_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + control_video = pipe.preprocess_video(control_video) + control_latents = pipe.vae.encode(control_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + control_latents = control_latents.to(dtype=pipe.torch_dtype, device=pipe.device) + y_dim = pipe.dit.in_dim-control_latents.shape[1]-latents.shape[1] + if clip_feature is None or y is None: + clip_feature = torch.zeros((1, 257, 1280), dtype=pipe.torch_dtype, device=pipe.device) + y = torch.zeros((1, y_dim, (num_frames - 1) // 4 + 1, height//8, width//8), dtype=pipe.torch_dtype, device=pipe.device) + else: + y = y[:, -y_dim:] + y = torch.concat([control_latents, y], dim=1) + return {"clip_feature": clip_feature, "y": y} + + + +class WanVideoUnit_FunReference(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("reference_image", "height", "width", "reference_image"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, reference_image, height, width): + if reference_image is None: + return {} + pipe.load_models_to_device(["vae"]) + reference_image = reference_image.resize((width, height)) + reference_latents = pipe.preprocess_video([reference_image]) + reference_latents = pipe.vae.encode(reference_latents, device=pipe.device) + if pipe.image_encoder is None: + return {"reference_latents": reference_latents} + clip_feature = pipe.preprocess_image(reference_image) + clip_feature = pipe.image_encoder.encode_image([clip_feature]) + return {"reference_latents": reference_latents, "clip_feature": clip_feature} + + + +class WanVideoUnit_FunCameraControl(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("height", "width", "num_frames", "camera_control_direction", "camera_control_speed", "camera_control_origin", "latents", "input_image", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames, camera_control_direction, camera_control_speed, camera_control_origin, latents, input_image, tiled, tile_size, tile_stride): + if camera_control_direction is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + camera_control_plucker_embedding = pipe.dit.control_adapter.process_camera_coordinates( + camera_control_direction, num_frames, height, width, camera_control_speed, camera_control_origin) + + control_camera_video = camera_control_plucker_embedding[:num_frames].permute([3, 0, 1, 2]).unsqueeze(0) + control_camera_latents = torch.concat( + [ + torch.repeat_interleave(control_camera_video[:, :, 0:1], repeats=4, dim=2), + control_camera_video[:, :, 1:] + ], dim=2 + ).transpose(1, 2) + b, f, c, h, w = control_camera_latents.shape + control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, 4, c, h, w).transpose(2, 3) + control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, c * 4, h, w).transpose(1, 2) + control_camera_latents_input = control_camera_latents.to(device=pipe.device, dtype=pipe.torch_dtype) + + input_image = input_image.resize((width, height)) + input_latents = pipe.preprocess_video([input_image]) + input_latents = pipe.vae.encode(input_latents, device=pipe.device) + y = torch.zeros_like(latents).to(pipe.device) + y[:, :, :1] = input_latents + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + + if y.shape[1] != pipe.dit.in_dim - latents.shape[1]: + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + y = torch.cat([msk,y]) + y = y.unsqueeze(0) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"control_camera_latents_input": control_camera_latents_input, "y": y} + + + +class WanVideoUnit_SpeedControl(PipelineUnit): + def __init__(self): + super().__init__(input_params=("motion_bucket_id",)) + + def process(self, pipe: WanVideoPipeline, motion_bucket_id): + if motion_bucket_id is None: + return {} + motion_bucket_id = torch.Tensor((motion_bucket_id,)).to(dtype=pipe.torch_dtype, device=pipe.device) + return {"motion_bucket_id": motion_bucket_id} + + + +class WanVideoUnit_VACE(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("vace_video", "vace_video_mask", "vace_reference_image", "vace_scale", "height", "width", "num_frames", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process( + self, + pipe: WanVideoPipeline, + vace_video, vace_video_mask, vace_reference_image, vace_scale, + height, width, num_frames, + tiled, tile_size, tile_stride + ): + if vace_video is not None or vace_video_mask is not None or vace_reference_image is not None: + pipe.load_models_to_device(["vae"]) + if vace_video is None: + vace_video = torch.zeros((1, 3, num_frames, height, width), dtype=pipe.torch_dtype, device=pipe.device) + else: + vace_video = pipe.preprocess_video(vace_video) + + if vace_video_mask is None: + vace_video_mask = torch.ones_like(vace_video) + else: + vace_video_mask = pipe.preprocess_video(vace_video_mask, min_value=0, max_value=1) + + inactive = vace_video * (1 - vace_video_mask) + 0 * vace_video_mask + reactive = vace_video * vace_video_mask + 0 * (1 - vace_video_mask) + inactive = pipe.vae.encode(inactive, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + reactive = pipe.vae.encode(reactive, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + vace_video_latents = torch.concat((inactive, reactive), dim=1) + + vace_mask_latents = rearrange(vace_video_mask[0,0], "T (H P) (W Q) -> 1 (P Q) T H W", P=8, Q=8) + vace_mask_latents = torch.nn.functional.interpolate(vace_mask_latents, size=((vace_mask_latents.shape[2] + 3) // 4, vace_mask_latents.shape[3], vace_mask_latents.shape[4]), mode='nearest-exact') + + if vace_reference_image is None: + pass + else: + if not isinstance(vace_reference_image,list): + vace_reference_image = [vace_reference_image] + + vace_reference_image = pipe.preprocess_video(vace_reference_image) + + bs, c, f, h, w = vace_reference_image.shape + new_vace_ref_images = [] + for j in range(f): + new_vace_ref_images.append(vace_reference_image[0, :, j:j+1]) + vace_reference_image = new_vace_ref_images + + vace_reference_latents = pipe.vae.encode(vace_reference_image, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + vace_reference_latents = torch.concat((vace_reference_latents, torch.zeros_like(vace_reference_latents)), dim=1) + vace_reference_latents = [u.unsqueeze(0) for u in vace_reference_latents] + + vace_video_latents = torch.concat((*vace_reference_latents, vace_video_latents), dim=2) + vace_mask_latents = torch.concat((torch.zeros_like(vace_mask_latents[:, :, :f]), vace_mask_latents), dim=2) + + vace_context = torch.concat((vace_video_latents, vace_mask_latents), dim=1) + return {"vace_context": vace_context, "vace_scale": vace_scale} + else: + return {"vace_context": None, "vace_scale": vace_scale} + + + +class WanVideoUnit_UnifiedSequenceParallel(PipelineUnit): + def __init__(self): + super().__init__(input_params=()) + + def process(self, pipe: WanVideoPipeline): + if hasattr(pipe, "use_unified_sequence_parallel"): + if pipe.use_unified_sequence_parallel: + return {"use_unified_sequence_parallel": True} + return {} + + + +class WanVideoUnit_TeaCache(PipelineUnit): + def __init__(self): + super().__init__( + seperate_cfg=True, + input_params_posi={"num_inference_steps": "num_inference_steps", "tea_cache_l1_thresh": "tea_cache_l1_thresh", "tea_cache_model_id": "tea_cache_model_id"}, + input_params_nega={"num_inference_steps": "num_inference_steps", "tea_cache_l1_thresh": "tea_cache_l1_thresh", "tea_cache_model_id": "tea_cache_model_id"}, + ) + + def process(self, pipe: WanVideoPipeline, num_inference_steps, tea_cache_l1_thresh, tea_cache_model_id): + if tea_cache_l1_thresh is None: + return {} + return {"tea_cache": TeaCache(num_inference_steps, rel_l1_thresh=tea_cache_l1_thresh, model_id=tea_cache_model_id)} + + + +class WanVideoUnit_CfgMerger(PipelineUnit): + def __init__(self): + super().__init__(take_over=True) + self.concat_tensor_names = ["context", "clip_feature", "y", "reference_latents"] + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if not inputs_shared["cfg_merge"]: + return inputs_shared, inputs_posi, inputs_nega + for name in self.concat_tensor_names: + tensor_posi = inputs_posi.get(name) + tensor_nega = inputs_nega.get(name) + tensor_shared = inputs_shared.get(name) + if tensor_posi is not None and tensor_nega is not None: + inputs_shared[name] = torch.concat((tensor_posi, tensor_nega), dim=0) + elif tensor_shared is not None: + inputs_shared[name] = torch.concat((tensor_shared, tensor_shared), dim=0) + inputs_posi.clear() + inputs_nega.clear() + return inputs_shared, inputs_posi, inputs_nega + + +class WanVideoUnit_S2V(PipelineUnit): + def __init__(self): + super().__init__( + take_over=True, + onload_model_names=("audio_encoder", "vae",) + ) + + def process_audio(self, pipe: WanVideoPipeline, input_audio, audio_sample_rate, num_frames, fps=16, audio_embeds=None, return_all=False): + if audio_embeds is not None: + return {"audio_embeds": audio_embeds} + pipe.load_models_to_device(["audio_encoder"]) + audio_embeds = pipe.audio_encoder.get_audio_feats_per_inference(input_audio, audio_sample_rate, pipe.audio_processor, fps=fps, batch_frames=num_frames-1, dtype=pipe.torch_dtype, device=pipe.device) + if return_all: + return audio_embeds + else: + return {"audio_embeds": audio_embeds[0]} + + def process_motion_latents(self, pipe: WanVideoPipeline, height, width, tiled, tile_size, tile_stride, motion_video=None): + pipe.load_models_to_device(["vae"]) + motion_frames = 73 + kwargs = {} + if motion_video is not None and len(motion_video) > 0: + assert len(motion_video) == motion_frames, f"motion video must have {motion_frames} frames, but got {len(motion_video)}" + motion_latents = pipe.preprocess_video(motion_video) + kwargs["drop_motion_frames"] = False + else: + motion_latents = torch.zeros([1, 3, motion_frames, height, width], dtype=pipe.torch_dtype, device=pipe.device) + kwargs["drop_motion_frames"] = True + motion_latents = pipe.vae.encode(motion_latents, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + kwargs.update({"motion_latents": motion_latents}) + return kwargs + + def process_pose_cond(self, pipe: WanVideoPipeline, s2v_pose_video, num_frames, height, width, tiled, tile_size, tile_stride, s2v_pose_latents=None, num_repeats=1, return_all=False): + if s2v_pose_latents is not None: + return {"s2v_pose_latents": s2v_pose_latents} + if s2v_pose_video is None: + return {"s2v_pose_latents": None} + pipe.load_models_to_device(["vae"]) + infer_frames = num_frames - 1 + input_video = pipe.preprocess_video(s2v_pose_video)[:, :, :infer_frames * num_repeats] + # pad if not enough frames + padding_frames = infer_frames * num_repeats - input_video.shape[2] + input_video = torch.cat([input_video, -torch.ones(1, 3, padding_frames, height, width, device=input_video.device, dtype=input_video.dtype)], dim=2) + input_videos = input_video.chunk(num_repeats, dim=2) + pose_conds = [] + for r in range(num_repeats): + cond = input_videos[r] + cond = torch.cat([cond[:, :, 0:1].repeat(1, 1, 1, 1, 1), cond], dim=2) + cond_latents = pipe.vae.encode(cond, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + pose_conds.append(cond_latents[:,:,1:]) + if return_all: + return pose_conds + else: + return {"s2v_pose_latents": pose_conds[0]} + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if (inputs_shared.get("input_audio") is None and inputs_shared.get("audio_embeds") is None) or pipe.audio_encoder is None or pipe.audio_processor is None: + return inputs_shared, inputs_posi, inputs_nega + num_frames, height, width, tiled, tile_size, tile_stride = inputs_shared.get("num_frames"), inputs_shared.get("height"), inputs_shared.get("width"), inputs_shared.get("tiled"), inputs_shared.get("tile_size"), inputs_shared.get("tile_stride") + input_audio, audio_embeds, audio_sample_rate = inputs_shared.pop("input_audio"), inputs_shared.pop("audio_embeds"), inputs_shared.get("audio_sample_rate") + s2v_pose_video, s2v_pose_latents, motion_video = inputs_shared.pop("s2v_pose_video"), inputs_shared.pop("s2v_pose_latents"), inputs_shared.pop("motion_video") + + audio_input_positive = self.process_audio(pipe, input_audio, audio_sample_rate, num_frames, audio_embeds=audio_embeds) + inputs_posi.update(audio_input_positive) + inputs_nega.update({"audio_embeds": 0.0 * audio_input_positive["audio_embeds"]}) + + inputs_shared.update(self.process_motion_latents(pipe, height, width, tiled, tile_size, tile_stride, motion_video)) + inputs_shared.update(self.process_pose_cond(pipe, s2v_pose_video, num_frames, height, width, tiled, tile_size, tile_stride, s2v_pose_latents=s2v_pose_latents)) + return inputs_shared, inputs_posi, inputs_nega + + @staticmethod + def pre_calculate_audio_pose(pipe: WanVideoPipeline, input_audio=None, audio_sample_rate=16000, s2v_pose_video=None, num_frames=81, height=448, width=832, fps=16, tiled=True, tile_size=(30, 52), tile_stride=(15, 26)): + assert pipe.audio_encoder is not None and pipe.audio_processor is not None, "Please load audio encoder and audio processor first." + shapes = WanVideoUnit_ShapeChecker().process(pipe, height, width, num_frames) + height, width, num_frames = shapes["height"], shapes["width"], shapes["num_frames"] + unit = WanVideoUnit_S2V() + audio_embeds = unit.process_audio(pipe, input_audio, audio_sample_rate, num_frames, fps, return_all=True) + pose_latents = unit.process_pose_cond(pipe, s2v_pose_video, num_frames, height, width, num_repeats=len(audio_embeds), return_all=True, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + pose_latents = None if s2v_pose_video is None else pose_latents + return audio_embeds, pose_latents, len(audio_embeds) + + +class WanVideoPostUnit_S2V(PipelineUnit): + def __init__(self): + super().__init__(input_params=("latents", "motion_latents", "drop_motion_frames")) + + def process(self, pipe: WanVideoPipeline, latents, motion_latents, drop_motion_frames): + if pipe.audio_encoder is None or motion_latents is None or drop_motion_frames: + return {} + latents = torch.cat([motion_latents, latents[:,:,1:]], dim=2) + return {"latents": latents} + + +class WanVideoPostUnit_AnimateVideoSplit(PipelineUnit): + def __init__(self): + super().__init__(input_params=("input_video", "animate_pose_video", "animate_face_video", "animate_inpaint_video", "animate_mask_video")) + + def process(self, pipe: WanVideoPipeline, input_video, animate_pose_video, animate_face_video, animate_inpaint_video, animate_mask_video): + if input_video is None: + return {} + if animate_pose_video is not None: + animate_pose_video = animate_pose_video[:len(input_video) - 4] + if animate_face_video is not None: + animate_face_video = animate_face_video[:len(input_video) - 4] + if animate_inpaint_video is not None: + animate_inpaint_video = animate_inpaint_video[:len(input_video) - 4] + if animate_mask_video is not None: + animate_mask_video = animate_mask_video[:len(input_video) - 4] + return {"animate_pose_video": animate_pose_video, "animate_face_video": animate_face_video, "animate_inpaint_video": animate_inpaint_video, "animate_mask_video": animate_mask_video} + + +class WanVideoPostUnit_AnimatePoseLatents(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("animate_pose_video", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, animate_pose_video, tiled, tile_size, tile_stride): + if animate_pose_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + animate_pose_video = pipe.preprocess_video(animate_pose_video) + pose_latents = pipe.vae.encode(animate_pose_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + return {"pose_latents": pose_latents} + + +class WanVideoPostUnit_AnimateFacePixelValues(PipelineUnit): + def __init__(self): + super().__init__(take_over=True) + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if inputs_shared.get("animate_face_video", None) is None: + return {} + inputs_posi["face_pixel_values"] = pipe.preprocess_video(inputs_shared["animate_face_video"]) + inputs_nega["face_pixel_values"] = torch.zeros_like(inputs_posi["face_pixel_values"]) - 1 + return inputs_shared, inputs_posi, inputs_nega + + +class WanVideoPostUnit_AnimateInpaint(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("animate_inpaint_video", "animate_mask_video", "input_image", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def get_i2v_mask(self, lat_t, lat_h, lat_w, mask_len=1, mask_pixel_values=None, device="cuda"): + if mask_pixel_values is None: + msk = torch.zeros(1, (lat_t-1) * 4 + 1, lat_h, lat_w, device=device) + else: + msk = mask_pixel_values.clone() + msk[:, :mask_len] = 1 + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w) + msk = msk.transpose(1, 2)[0] + return msk + + def process(self, pipe: WanVideoPipeline, animate_inpaint_video, animate_mask_video, input_image, tiled, tile_size, tile_stride): + if animate_inpaint_video is None or animate_mask_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + + bg_pixel_values = pipe.preprocess_video(animate_inpaint_video) + y_reft = pipe.vae.encode(bg_pixel_values, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0].to(dtype=pipe.torch_dtype, device=pipe.device) + _, lat_t, lat_h, lat_w = y_reft.shape + + ref_pixel_values = pipe.preprocess_video([input_image]) + ref_latents = pipe.vae.encode(ref_pixel_values, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + mask_ref = self.get_i2v_mask(1, lat_h, lat_w, 1, device=pipe.device) + y_ref = torch.concat([mask_ref, ref_latents[0]]).to(dtype=torch.bfloat16, device=pipe.device) + + mask_pixel_values = 1 - pipe.preprocess_video(animate_mask_video, max_value=1, min_value=0) + mask_pixel_values = rearrange(mask_pixel_values, "b c t h w -> (b t) c h w") + mask_pixel_values = torch.nn.functional.interpolate(mask_pixel_values, size=(lat_h, lat_w), mode='nearest') + mask_pixel_values = rearrange(mask_pixel_values, "(b t) c h w -> b t c h w", b=1)[:,:,0] + msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, 0, mask_pixel_values=mask_pixel_values, device=pipe.device) + + y_reft = torch.concat([msk_reft, y_reft]).to(dtype=torch.bfloat16, device=pipe.device) + y = torch.concat([y_ref, y_reft], dim=1).unsqueeze(0) + return {"y": y} + + +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.21862437e+04, 9.23041404e+03, -5.28275948e+02, 1.36987616e+01, -4.99875664e-02], + "Wan2.1-T2V-14B": [-3.03318725e+05, 4.90537029e+04, -2.65530556e+03, 5.87365115e+01, -3.15583525e-01], + "Wan2.1-I2V-14B-480P": [2.57151496e+05, -3.54229917e+04, 1.40286849e+03, -1.35890334e+01, 1.32517977e-01], + "Wan2.1-I2V-14B-720P": [ 8.10705460e+03, 2.13393892e+03, -3.72934672e+02, 1.66203073e+01, -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 + + + +class TemporalTiler_BCTHW: + def __init__(self): + pass + + def build_1d_mask(self, length, left_bound, right_bound, border_width): + x = torch.ones((length,)) + if border_width == 0: + return x + + shift = 0.5 + if not left_bound: + x[:border_width] = (torch.arange(border_width) + shift) / border_width + if not right_bound: + x[-border_width:] = torch.flip((torch.arange(border_width) + shift) / border_width, dims=(0,)) + return x + + def build_mask(self, data, is_bound, border_width): + _, _, T, _, _ = data.shape + t = self.build_1d_mask(T, is_bound[0], is_bound[1], border_width[0]) + mask = repeat(t, "T -> 1 1 T 1 1") + return mask + + def run(self, model_fn, sliding_window_size, sliding_window_stride, computation_device, computation_dtype, model_kwargs, tensor_names, batch_size=None): + tensor_names = [tensor_name for tensor_name in tensor_names if model_kwargs.get(tensor_name) is not None] + tensor_dict = {tensor_name: model_kwargs[tensor_name] for tensor_name in tensor_names} + B, C, T, H, W = tensor_dict[tensor_names[0]].shape + if batch_size is not None: + B *= batch_size + data_device, data_dtype = tensor_dict[tensor_names[0]].device, tensor_dict[tensor_names[0]].dtype + value = torch.zeros((B, C, T, H, W), device=data_device, dtype=data_dtype) + weight = torch.zeros((1, 1, T, 1, 1), device=data_device, dtype=data_dtype) + for t in range(0, T, sliding_window_stride): + if t - sliding_window_stride >= 0 and t - sliding_window_stride + sliding_window_size >= T: + continue + t_ = min(t + sliding_window_size, T) + model_kwargs.update({ + tensor_name: tensor_dict[tensor_name][:, :, t: t_:, :].to(device=computation_device, dtype=computation_dtype) \ + for tensor_name in tensor_names + }) + model_output = model_fn(**model_kwargs).to(device=data_device, dtype=data_dtype) + mask = self.build_mask( + model_output, + is_bound=(t == 0, t_ == T), + border_width=(sliding_window_size - sliding_window_stride,) + ).to(device=data_device, dtype=data_dtype) + value[:, :, t: t_, :, :] += model_output * mask + weight[:, :, t: t_, :, :] += mask + value /= weight + model_kwargs.update(tensor_dict) + return value + + + +def model_fn_wan_video( + dit: WanModel, + motion_controller: WanMotionControllerModel = None, + vace: VaceWanModel = None, + animate_adapter: WanAnimateAdapter = None, + latents: torch.Tensor = None, + token_prefix_latents: Optional[torch.Tensor] = None, + timestep: torch.Tensor = None, + context: torch.Tensor = None, + clip_feature: Optional[torch.Tensor] = None, + y: Optional[torch.Tensor] = None, + reference_latents = None, + vace_context = None, + vace_scale = 1.0, + audio_embeds: Optional[torch.Tensor] = None, + motion_latents: Optional[torch.Tensor] = None, + s2v_pose_latents: Optional[torch.Tensor] = None, + drop_motion_frames: bool = True, + tea_cache: TeaCache = None, + use_unified_sequence_parallel: bool = False, + motion_bucket_id: Optional[torch.Tensor] = None, + pose_latents=None, + face_pixel_values=None, + sliding_window_size: Optional[int] = None, + sliding_window_stride: Optional[int] = None, + cfg_merge: bool = False, + use_gradient_checkpointing: bool = False, + use_gradient_checkpointing_offload: bool = False, + control_camera_latents_input = None, + fuse_vae_embedding_in_latents: bool = False, + token_prefix_clean_timestep: bool = False, + token_prefix_aligned_rope: bool = False, + token_prefix_block_self_attention: bool = False, + clean_history_latent_frames: int = 0, + condition_latents: Optional[torch.Tensor] = None, + channel_concat_condition: bool = False, + **kwargs, +): + if sliding_window_size is not None and sliding_window_stride is not None: + model_kwargs = dict( + dit=dit, + motion_controller=motion_controller, + vace=vace, + latents=latents, + token_prefix_latents=token_prefix_latents, + timestep=timestep, + context=context, + clip_feature=clip_feature, + y=y, + reference_latents=reference_latents, + vace_context=vace_context, + vace_scale=vace_scale, + tea_cache=tea_cache, + use_unified_sequence_parallel=use_unified_sequence_parallel, + motion_bucket_id=motion_bucket_id, + fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents, + token_prefix_clean_timestep=token_prefix_clean_timestep, + token_prefix_aligned_rope=token_prefix_aligned_rope, + token_prefix_block_self_attention=token_prefix_block_self_attention, + clean_history_latent_frames=clean_history_latent_frames, + condition_latents=condition_latents, + channel_concat_condition=channel_concat_condition, + ) + return TemporalTiler_BCTHW().run( + model_fn_wan_video, + sliding_window_size, sliding_window_stride, + latents.device, latents.dtype, + model_kwargs=model_kwargs, + tensor_names=["latents", "y"], + batch_size=2 if cfg_merge else 1 + ) + # wan2.2 s2v + if audio_embeds is not None: + return model_fn_wans2v( + dit=dit, + latents=latents, + timestep=timestep, + context=context, + audio_embeds=audio_embeds, + motion_latents=motion_latents, + s2v_pose_latents=s2v_pose_latents, + drop_motion_frames=drop_motion_frames, + use_gradient_checkpointing_offload=use_gradient_checkpointing_offload, + use_gradient_checkpointing=use_gradient_checkpointing, + use_unified_sequence_parallel=use_unified_sequence_parallel, + ) + + if use_unified_sequence_parallel: + import torch.distributed as dist + from xfuser.core.distributed import (get_sequence_parallel_rank, + get_sequence_parallel_world_size, + get_sp_group) + + has_reference_latents = reference_latents is not None + separated_fused_timestep = bool(dit.seperated_timestep and fuse_vae_embedding_in_latents) + separated_prefix_timestep = bool(token_prefix_clean_timestep and token_prefix_latents is not None and not has_reference_latents) + if not separated_fused_timestep and not separated_prefix_timestep: + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep)) + t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim)) + + # Motion Controller + if motion_bucket_id is not None and motion_controller is not None: + t_mod = t_mod + motion_controller(motion_bucket_id).unflatten(1, (6, dit.dim)) + context = dit.text_embedding(context) + + x = latents + # Merged cfg + if x.shape[0] != context.shape[0]: + x = torch.concat([x] * context.shape[0], dim=0) + if timestep.shape[0] != context.shape[0]: + timestep = torch.concat([timestep] * context.shape[0], dim=0) + if channel_concat_condition: + if condition_latents is None: + raise ValueError("channel_concat_condition=True requires condition_latents") + condition_latents = condition_latents.to(device=x.device, dtype=x.dtype) + if condition_latents.shape[0] != x.shape[0]: + if x.shape[0] % condition_latents.shape[0] != 0: + raise ValueError( + f"Cannot expand condition batch {condition_latents.shape[0]} " + f"to latent batch {x.shape[0]}" + ) + condition_latents = torch.cat( + [condition_latents] * (x.shape[0] // condition_latents.shape[0]), dim=0 + ) + if condition_latents.shape[2:] != x.shape[2:]: + raise ValueError( + f"Condition latent shape {tuple(condition_latents.shape)} does not match " + f"bridge latent shape {tuple(x.shape)}" + ) + x = torch.cat([x, condition_latents], dim=1) + + # Image Embedding + if y is not None and dit.require_vae_embedding: + x = torch.cat([x, y], dim=1) + if clip_feature is not None and dit.require_clip_embedding: + clip_embdding = dit.img_emb(clip_feature) + context = torch.cat([clip_embdding, context], dim=1) + + # Camera control + x = dit.patchify(x, control_camera_latents_input) + + # Animate + if animate_adapter is not None: + x, motion_vec = animate_adapter.after_patch_embedding(x, pose_latents, face_pixel_values) + else: + motion_vec = None + + # Patchify. For token-concat conditioning, the clean original video is a + # prefix stream and the Brownian-bridge video is the prediction stream. + f, h, w = x.shape[2:] + target_frames = int(f) + x = rearrange(x, 'b c f h w -> b (f h w) c').contiguous() + prefix_token_count = 0 + prefix_frames = 0 + prefix_h = 0 + prefix_w = 0 + if token_prefix_latents is not None: + prefix_latents = token_prefix_latents.to(device=latents.device, dtype=latents.dtype) + if channel_concat_condition and prefix_latents.shape[1] * 2 == int(dit.in_dim): + prefix_latents = torch.cat([prefix_latents, torch.zeros_like(prefix_latents)], dim=1) + if prefix_latents.shape[0] != latents.shape[0]: + if latents.shape[0] % prefix_latents.shape[0] != 0: + raise ValueError( + f"Cannot expand token prefix batch {prefix_latents.shape[0]} " + f"to latent batch {latents.shape[0]}" + ) + prefix_latents = torch.cat( + [prefix_latents] * (latents.shape[0] // prefix_latents.shape[0]), dim=0 + ) + prefix_grid = dit.patchify(prefix_latents) + prefix_frames, prefix_h, prefix_w = prefix_grid.shape[2:] + prefix_tokens = rearrange(prefix_grid, 'b c f h w -> b (f h w) c').contiguous() + prefix_token_count = int(prefix_tokens.shape[1]) + x = torch.cat([prefix_tokens, x], dim=1) + f += int(prefix_frames) + + if (separated_fused_timestep or separated_prefix_timestep) and not has_reference_latents: + target_clean_frames = 1 + max(int(clean_history_latent_frames), 0) if separated_fused_timestep else 0 + target_clean_frames = min(target_clean_frames, int(latents.shape[2])) + prefix_tokens_per_frame = int(prefix_h * prefix_w) if prefix_token_count else 0 + target_tokens_per_frame = int(h * w) + token_timestep_parts = [] + if prefix_token_count: + prefix_time = make_device_tensor([0.0] * int(prefix_frames), latents.device, latents.dtype) + token_timestep_parts.append(prefix_time.repeat_interleave(prefix_tokens_per_frame)) + target_time = make_device_tensor( + [0.0] * target_clean_frames + + [float(timestep.flatten()[0].item())] * (int(latents.shape[2]) - target_clean_frames), + latents.device, + latents.dtype, + ) + token_timestep_parts.append(target_time.repeat_interleave(target_tokens_per_frame)) + token_timestep = torch.cat(token_timestep_parts, dim=0) + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, token_timestep).unsqueeze(0)) + if t.shape[0] != x.shape[0]: + t = torch.cat([t] * x.shape[0], dim=0) + t_mod = dit.time_projection(t).unflatten(2, (6, dit.dim)) + + # Reference image + if reference_latents is not None: + if len(reference_latents.shape) == 5: + reference_latents = reference_latents[:, :, 0] + reference_latents = dit.ref_conv(reference_latents).flatten(2).transpose(1, 2) + x = torch.concat([reference_latents, x], dim=1) + f += 1 + + def build_rope_grid(frame_count: int, grid_h: int, grid_w: int) -> torch.Tensor: + rope_freqs = dit.get_rope_freqs(x.device) + return torch.cat([ + rope_freqs[0][:frame_count].view(frame_count, 1, 1, -1).expand(frame_count, grid_h, grid_w, -1), + rope_freqs[1][:grid_h].view(1, grid_h, 1, -1).expand(frame_count, grid_h, grid_w, -1), + rope_freqs[2][:grid_w].view(1, 1, grid_w, -1).expand(frame_count, grid_h, grid_w, -1), + ], dim=-1).reshape(frame_count * grid_h * grid_w, 1, -1) + + if token_prefix_aligned_rope and prefix_frames: + # Keep token order [reference, prefix, target], but reset the temporal + # RoPE coordinate for each stream. Corresponding prefix/target patches + # therefore receive exactly the same (time, height, width) rotation. + rope_streams = [] + if has_reference_latents: + rope_streams.append(build_rope_grid(1, h, w)) + rope_streams.extend([ + build_rope_grid(int(prefix_frames), int(prefix_h), int(prefix_w)), + build_rope_grid(target_frames, h, w), + ]) + freqs = torch.cat(rope_streams, dim=0).to(x.device) + else: + freqs = build_rope_grid(int(f), h, w).to(x.device) + + attn_mask = None + if token_prefix_block_self_attention and prefix_token_count: + if has_reference_latents: + raise NotImplementedError( + "token_prefix_block_self_attention is currently only supported without reference_latents" + ) + attn_mask = build_token_prefix_attention_spec( + prefix_token_count=prefix_token_count, + target_token_count=int(target_frames * h * w), + ) + if use_unified_sequence_parallel: + raise NotImplementedError("Token-prefix attention masks do not support unified sequence parallelism") + + # TeaCache + if tea_cache is not None: + tea_cache_update = tea_cache.check(dit, x, t_mod) + else: + tea_cache_update = False + + if vace_context is not None: + vace_hints = vace( + x, vace_context, context, t_mod, freqs, + use_gradient_checkpointing=use_gradient_checkpointing, + use_gradient_checkpointing_offload=use_gradient_checkpointing_offload + ) + + # Optional layer-aligned reference stream. It is kept as an explicit + # checkpoint input/output instead of mutable module state, so recomputation + # during gradient checkpointing is deterministic. + reference_condition = getattr(dit, "_reference_condition", None) + reference_x = None + if getattr(dit, "_reference_adapters_enabled", False) and reference_condition is not None: + reference_x = reference_condition.reference_tokens.to(dtype=x.dtype, device=x.device) + if reference_x.shape[0] != x.shape[0]: + if x.shape[0] % reference_x.shape[0] != 0: + raise ValueError( + f"Cannot expand reference batch {reference_x.shape[0]} to target batch {x.shape[0]}" + ) + reference_x = torch.cat([reference_x] * (x.shape[0] // reference_x.shape[0]), dim=0) + if use_unified_sequence_parallel: + raise NotImplementedError( + "Dual-stream frame-wise pair attention does not yet support unified sequence parallelism" + ) + # TeaCache may skip transformer blocks and would therefore skip the + # evolving reference stream and frame-wise pair-attention layers. + tea_cache_update = False + if reference_x is not None and attn_mask is not None: + raise NotImplementedError("Dual-stream reference adapters do not support token-prefix attention masks") + + # blocks + if use_unified_sequence_parallel: + if dist.is_initialized() and dist.get_world_size() > 1: + chunks = torch.chunk(x, get_sequence_parallel_world_size(), dim=1) + pad_shape = chunks[0].shape[1] - chunks[-1].shape[1] + chunks = [torch.nn.functional.pad(chunk, (0, 0, 0, chunks[0].shape[1]-chunk.shape[1]), value=0) for chunk in chunks] + x = chunks[get_sequence_parallel_rank()] + if tea_cache_update: + x = tea_cache.update(x) + else: + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + def create_dual_custom_forward(module): + def custom_forward(*inputs): + return module.forward_dual(*inputs) + return custom_forward + + for block_id, block in enumerate(dit.blocks): + # Block + dual_stream = reference_x is not None and hasattr(block, "forward_dual") + if dual_stream and use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x, reference_x = torch.utils.checkpoint.checkpoint( + create_dual_custom_forward(block), + x, reference_x, context, t_mod, freqs, + use_reentrant=False, + ) + elif dual_stream and use_gradient_checkpointing: + x, reference_x = torch.utils.checkpoint.checkpoint( + create_dual_custom_forward(block), + x, reference_x, context, t_mod, freqs, + use_reentrant=False, + ) + elif dual_stream: + x, reference_x = block.forward_dual(x, reference_x, context, t_mod, freqs) + elif use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, freqs, attn_mask=attn_mask) + + # VACE + if vace_context is not None and block_id in vace.vace_layers_mapping: + current_vace_hint = vace_hints[vace.vace_layers_mapping[block_id]] + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + current_vace_hint = torch.chunk(current_vace_hint, get_sequence_parallel_world_size(), dim=1)[get_sequence_parallel_rank()] + current_vace_hint = torch.nn.functional.pad(current_vace_hint, (0, 0, 0, chunks[0].shape[1] - current_vace_hint.shape[1]), value=0) + x = x + current_vace_hint * vace_scale + + # Animate + if animate_adapter is not None and pose_latents is not None and face_pixel_values is not None: + x = animate_adapter.after_transformer_block(block_id, x, motion_vec) + if tea_cache is not None: + tea_cache.store(x) + + x = dit.head(x, t) + if use_unified_sequence_parallel: + if dist.is_initialized() and dist.get_world_size() > 1: + x = get_sp_group().all_gather(x, dim=1) + x = x[:, :-pad_shape] if pad_shape > 0 else x + # Remove a token-concat prefix. The model predicts both streams, but only + # the edited-video stream is part of the bridge output. + if prefix_token_count: + x = x[:, prefix_token_count:] + f -= prefix_frames + # Remove legacy Wan reference-image latents + if reference_latents is not None: + x = x[:, reference_latents.shape[1]:] + f -= 1 + x = dit.unpatchify(x, (f, h, w)) + return x + + +def model_fn_wans2v( + dit, + latents, + timestep, + context, + audio_embeds, + motion_latents, + s2v_pose_latents, + drop_motion_frames=True, + use_gradient_checkpointing_offload=False, + use_gradient_checkpointing=False, + use_unified_sequence_parallel=False, +): + if use_unified_sequence_parallel: + import torch.distributed as dist + from xfuser.core.distributed import (get_sequence_parallel_rank, + get_sequence_parallel_world_size, + get_sp_group) + origin_ref_latents = latents[:, :, 0:1] + x = latents[:, :, 1:] + + # context embedding + context = dit.text_embedding(context) + + # audio encode + audio_emb_global, merged_audio_emb = dit.cal_audio_emb(audio_embeds) + + # x and s2v_pose_latents + s2v_pose_latents = torch.zeros_like(x) if s2v_pose_latents is None else s2v_pose_latents + x, (f, h, w) = dit.patchify(dit.patch_embedding(x) + dit.cond_encoder(s2v_pose_latents)) + seq_len_x = seq_len_x_global = x.shape[1] # global used for unified sequence parallel + + # reference image + ref_latents, (rf, rh, rw) = dit.patchify(dit.patch_embedding(origin_ref_latents)) + grid_sizes = dit.get_grid_sizes((f, h, w), (rf, rh, rw)) + x = torch.cat([x, ref_latents], dim=1) + # mask + mask = torch.cat([torch.zeros([1, seq_len_x]), torch.ones([1, ref_latents.shape[1]])], dim=1).to(torch.long).to(x.device) + # freqs + pre_compute_freqs = rope_precompute(x.detach().view(1, x.size(1), dit.num_heads, dit.dim // dit.num_heads), grid_sizes, dit.freqs, start=None) + # motion + x, pre_compute_freqs, mask = dit.inject_motion(x, pre_compute_freqs, mask, motion_latents, drop_motion_frames=drop_motion_frames, add_last_motion=2) + + x = x + dit.trainable_cond_mask(mask).to(x.dtype) + + # tmod + timestep = torch.cat([timestep, torch.zeros([1], dtype=timestep.dtype, device=timestep.device)]) + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep)) + t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim)).unsqueeze(2).transpose(0, 2) + + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + world_size, sp_rank = get_sequence_parallel_world_size(), get_sequence_parallel_rank() + assert x.shape[1] % world_size == 0, f"the dimension after chunk must be divisible by world size, but got {x.shape[1]} and {get_sequence_parallel_world_size()}" + x = torch.chunk(x, world_size, dim=1)[sp_rank] + seg_idxs = [0] + list(torch.cumsum(torch.tensor([x.shape[1]] * world_size), dim=0).cpu().numpy()) + seq_len_x_list = [min(max(0, seq_len_x - seg_idxs[i]), x.shape[1]) for i in range(len(seg_idxs)-1)] + seq_len_x = seq_len_x_list[sp_rank] + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + for block_id, block in enumerate(dit.blocks): + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, seq_len_x, pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, seq_len_x, pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, seq_len_x, pre_compute_freqs[0]) + x = dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x_global, use_unified_sequence_parallel) + + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + x = get_sp_group().all_gather(x, dim=1) + + x = x[:, :seq_len_x_global] + x = dit.head(x, t[:-1]) + x = dit.unpatchify(x, (f, h, w)) + # make compatible with wan video + x = torch.cat([origin_ref_latents, x], dim=2) + return x diff --git a/releases/2026-10-20-code/diffsynth/configs/__init__.py b/releases/2026-10-20-code/diffsynth/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/releases/2026-10-20-code/diffsynth/configs/model_config.py b/releases/2026-10-20-code/diffsynth/configs/model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac479b87c624d961e1544e88ceca2bb9cf8f079 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/configs/model_config.py @@ -0,0 +1,52 @@ +"""Wan-only model detector configuration used by the ViBT release.""" +from typing import TypeAlias + +# Minimal compatibility definitions required by diffsynth.models.downloader. +# ViBT loads Wan weights through ModelConfig(model_id=..., origin_file_pattern=...), +# so the legacy preset-model tables are intentionally left empty. +preset_models_on_huggingface = {} +preset_models_on_modelscope = {} +Preset_model_id: TypeAlias = str + +from ..models.wan_video_dit import WanModel +from ..models.wan_video_dit_s2v import WanS2VModel +from ..models.wan_video_text_encoder import WanTextEncoder +from ..models.wan_video_image_encoder import WanImageEncoder +from ..models.wan_video_vae import WanVideoVAE, WanVideoVAE38 +from ..models.wan_video_motion_controller import WanMotionControllerModel +from ..models.wan_video_vace import VaceWanModel +from ..models.wav2vec import WanS2VAudioEncoder +from ..models.wan_video_animate_adapter import WanAnimateAdapter + +model_loader_configs = [ + (None, "9269f8db9040a9d860eaca435be61814", ["wan_video_dit"], [WanModel], "civitai"), + (None, "aafcfd9672c3a2456dc46e1cb6e52c70", ["wan_video_dit"], [WanModel], "civitai"), + (None, "6bfcfb3b342cb286ce886889d519a77e", ["wan_video_dit"], [WanModel], "civitai"), + (None, "6d6ccde6845b95ad9114ab993d917893", ["wan_video_dit"], [WanModel], "civitai"), + (None, "349723183fc063b2bfc10bb2835cf677", ["wan_video_dit"], [WanModel], "civitai"), + (None, "efa44cddf936c70abd0ea28b6cbe946c", ["wan_video_dit"], [WanModel], "civitai"), + (None, "3ef3b1f8e1dab83d5b71fd7b617f859f", ["wan_video_dit"], [WanModel], "civitai"), + (None, "70ddad9d3a133785da5ea371aae09504", ["wan_video_dit"], [WanModel], "civitai"), + (None, "26bde73488a92e64cc20b0a7485b9e5b", ["wan_video_dit"], [WanModel], "civitai"), + (None, "ac6a5aa74f4a0aab6f64eb9a72f19901", ["wan_video_dit"], [WanModel], "civitai"), + (None, "b61c605c2adbd23124d152ed28e049ae", ["wan_video_dit"], [WanModel], "civitai"), + (None, "1f5ab7703c6fc803fdded85ff040c316", ["wan_video_dit"], [WanModel], "civitai"), + (None, "5b013604280dd715f8457c6ed6d6a626", ["wan_video_dit"], [WanModel], "civitai"), + (None, "2267d489f0ceb9f21836532952852ee5", ["wan_video_dit"], [WanModel], "civitai"), + (None, "47dbeab5e560db3180adf51dc0232fb1", ["wan_video_dit"], [WanModel], "civitai"), + (None, "a61453409b67cd3246cf0c3bebad47ba", ["wan_video_dit", "wan_video_vace"], [WanModel, VaceWanModel], "civitai"), + (None, "7a513e1f257a861512b1afd387a8ecd9", ["wan_video_dit", "wan_video_vace"], [WanModel, VaceWanModel], "civitai"), + (None, "cb104773c6c2cb6df4f9529ad5c60d0b", ["wan_video_dit"], [WanModel], "diffusers"), + (None, "966cffdcc52f9c46c391768b27637614", ["wan_video_dit"], [WanS2VModel], "civitai"), + (None, "9c8818c2cbea55eca56c7b447df170da", ["wan_video_text_encoder"], [WanTextEncoder], "civitai"), + (None, "5941c53e207d62f20f9025686193c40b", ["wan_video_image_encoder"], [WanImageEncoder], "civitai"), + (None, "1378ea763357eea97acdef78e65d6d96", ["wan_video_vae"], [WanVideoVAE], "civitai"), + (None, "ccc42284ea13e1ad04693284c7a09be6", ["wan_video_vae"], [WanVideoVAE], "civitai"), + (None, "e1de6c02cdac79f8b739f4d3698cd216", ["wan_video_vae"], [WanVideoVAE38], "civitai"), + (None, "dbd5ec76bbf977983f972c151d545389", ["wan_video_motion_controller"], [WanMotionControllerModel], "civitai"), + (None, "06be60f3a4526586d8431cd038a71486", ["wans2v_audio_encoder"], [WanS2VAudioEncoder], "civitai"), + (None, "31fa352acb8a1b1d33cd8764273d80a2", ["wan_video_dit", "wan_video_animate_adapter"], [WanModel, WanAnimateAdapter], "civitai"), +] + +huggingface_model_loader_configs = [] +patch_model_loader_configs = [] diff --git a/releases/2026-10-20-code/diffsynth/data/__init__.py b/releases/2026-10-20-code/diffsynth/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..282239ad472c77659ed752a109bb6dd8da9ef2ca --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/data/__init__.py @@ -0,0 +1 @@ +from .video import VideoData, save_video, save_video_with_audio diff --git a/releases/2026-10-20-code/diffsynth/data/video.py b/releases/2026-10-20-code/diffsynth/data/video.py new file mode 100644 index 0000000000000000000000000000000000000000..12f90b8578a9fb307c492a7ee0e093f68702a925 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/data/video.py @@ -0,0 +1,217 @@ +import imageio, os +import numpy as np +from PIL import Image +from tqdm import tqdm +import subprocess +import shutil + + +class LowMemoryVideo: + def __init__(self, file_name): + self.reader = imageio.get_reader(file_name) + + def __len__(self): + return self.reader.count_frames() + + def __getitem__(self, item): + return Image.fromarray(np.array(self.reader.get_data(item))).convert("RGB") + + def __del__(self): + self.reader.close() + + +def split_file_name(file_name): + result = [] + number = -1 + for i in file_name: + if ord(i)>=ord("0") and ord(i)<=ord("9"): + if number == -1: + number = 0 + number = number*10 + ord(i) - ord("0") + else: + if number != -1: + result.append(number) + number = -1 + result.append(i) + if number != -1: + result.append(number) + result = tuple(result) + return result + + +def search_for_images(folder): + file_list = [i for i in os.listdir(folder) if i.endswith(".jpg") or i.endswith(".png")] + file_list = [(split_file_name(file_name), file_name) for file_name in file_list] + file_list = [i[1] for i in sorted(file_list)] + file_list = [os.path.join(folder, i) for i in file_list] + return file_list + + +class LowMemoryImageFolder: + def __init__(self, folder, file_list=None): + if file_list is None: + self.file_list = search_for_images(folder) + else: + self.file_list = [os.path.join(folder, file_name) for file_name in file_list] + + def __len__(self): + return len(self.file_list) + + def __getitem__(self, item): + return Image.open(self.file_list[item]).convert("RGB") + + def __del__(self): + pass + + +def crop_and_resize(image, height, width): + image = np.array(image) + image_height, image_width, _ = image.shape + if image_height / image_width < height / width: + croped_width = int(image_height / height * width) + left = (image_width - croped_width) // 2 + image = image[:, left: left+croped_width] + image = Image.fromarray(image).resize((width, height)) + else: + croped_height = int(image_width / width * height) + left = (image_height - croped_height) // 2 + image = image[left: left+croped_height, :] + image = Image.fromarray(image).resize((width, height)) + return image + + +class VideoData: + def __init__(self, video_file=None, image_folder=None, height=None, width=None, **kwargs): + if video_file is not None: + self.data_type = "video" + self.data = LowMemoryVideo(video_file, **kwargs) + elif image_folder is not None: + self.data_type = "images" + self.data = LowMemoryImageFolder(image_folder, **kwargs) + else: + raise ValueError("Cannot open video or image folder") + self.length = None + self.set_shape(height, width) + + def raw_data(self): + frames = [] + for i in range(self.__len__()): + frames.append(self.__getitem__(i)) + return frames + + def set_length(self, length): + self.length = length + + def set_shape(self, height, width): + self.height = height + self.width = width + + def __len__(self): + if self.length is None: + return len(self.data) + else: + return self.length + + def shape(self): + if self.height is not None and self.width is not None: + return self.height, self.width + else: + height, width, _ = self.__getitem__(0).shape + return height, width + + def __getitem__(self, item): + frame = self.data.__getitem__(item) + width, height = frame.size + if self.height is not None and self.width is not None: + if self.height != height or self.width != width: + frame = crop_and_resize(frame, self.height, self.width) + return frame + + def __del__(self): + pass + + def save_images(self, folder): + os.makedirs(folder, exist_ok=True) + for i in tqdm(range(self.__len__()), desc="Saving images"): + frame = self.__getitem__(i) + frame.save(os.path.join(folder, f"{i}.png")) + + +def save_video(frames, save_path, fps, quality=9, ffmpeg_params=None): + # quality and ffmpeg_params belong to the legacy FFMPEG backend, not PyAV. + with imageio.get_writer(save_path, format="FFMPEG", fps=fps, + quality=quality, ffmpeg_params=ffmpeg_params) as writer: + for frame in tqdm(frames, desc="Saving video"): + writer.append_data(np.array(frame)) + +def save_frames(frames, save_path): + os.makedirs(save_path, exist_ok=True) + for i, frame in enumerate(tqdm(frames, desc="Saving images")): + frame.save(os.path.join(save_path, f"{i}.png")) + + +def merge_video_audio(video_path: str, audio_path: str): + # TODO: may need a in-python implementation to avoid subprocess dependency + """ + Merge the video and audio into a new video, with the duration set to the shorter of the two, + and overwrite the original video file. + + Parameters: + video_path (str): Path to the original video file + audio_path (str): Path to the audio file + """ + + # check + if not os.path.exists(video_path): + raise FileNotFoundError(f"video file {video_path} does not exist") + if not os.path.exists(audio_path): + raise FileNotFoundError(f"audio file {audio_path} does not exist") + + base, ext = os.path.splitext(video_path) + temp_output = f"{base}_temp{ext}" + + try: + # create ffmpeg command + command = [ + 'ffmpeg', + '-y', # overwrite + '-i', + video_path, + '-i', + audio_path, + '-c:v', + 'copy', # copy video stream + '-c:a', + 'aac', # use AAC audio encoder + '-b:a', + '192k', # set audio bitrate (optional) + '-map', + '0:v:0', # select the first video stream + '-map', + '1:a:0', # select the first audio stream + '-shortest', # choose the shortest duration + temp_output + ] + + # execute the command + result = subprocess.run( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + # check result + if result.returncode != 0: + error_msg = f"FFmpeg execute failed: {result.stderr}" + print(error_msg) + raise RuntimeError(error_msg) + + shutil.move(temp_output, video_path) + print(f"Merge completed, saved to {video_path}") + + except Exception as e: + if os.path.exists(temp_output): + os.remove(temp_output) + print(f"merge_video_audio failed with error: {e}") + + +def save_video_with_audio(frames, save_path, audio_path, fps=16, quality=9, ffmpeg_params=None): + save_video(frames, save_path, fps, quality, ffmpeg_params) + merge_video_audio(save_path, audio_path) diff --git a/releases/2026-10-20-code/diffsynth/lora/__init__.py b/releases/2026-10-20-code/diffsynth/lora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33bd89c21b74ec0bba8b7b69468a3901e45360fd --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/lora/__init__.py @@ -0,0 +1,45 @@ +import torch + + + +class GeneralLoRALoader: + def __init__(self, device="cpu", torch_dtype=torch.float32): + self.device = device + self.torch_dtype = torch_dtype + + + def get_name_dict(self, lora_state_dict): + lora_name_dict = {} + for key in lora_state_dict: + if ".lora_B." not in key: + continue + keys = key.split(".") + if len(keys) > keys.index("lora_B") + 2: + keys.pop(keys.index("lora_B") + 1) + keys.pop(keys.index("lora_B")) + if keys[0] == "diffusion_model": + keys.pop(0) + keys.pop(-1) + target_name = ".".join(keys) + lora_name_dict[target_name] = (key, key.replace(".lora_B.", ".lora_A.")) + return lora_name_dict + + + def load(self, model: torch.nn.Module, state_dict_lora, alpha=1.0): + updated_num = 0 + lora_name_dict = self.get_name_dict(state_dict_lora) + for name, module in model.named_modules(): + if name in lora_name_dict: + weight_up = state_dict_lora[lora_name_dict[name][0]].to(device=self.device, dtype=self.torch_dtype) + weight_down = state_dict_lora[lora_name_dict[name][1]].to(device=self.device, dtype=self.torch_dtype) + if len(weight_up.shape) == 4: + weight_up = weight_up.squeeze(3).squeeze(2) + weight_down = weight_down.squeeze(3).squeeze(2) + weight_lora = alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3) + else: + weight_lora = alpha * torch.mm(weight_up, weight_down) + state_dict = module.state_dict() + state_dict["weight"] = state_dict["weight"].to(device=self.device, dtype=self.torch_dtype) + weight_lora + module.load_state_dict(state_dict) + updated_num += 1 + print(f"{updated_num} tensors are updated by LoRA.") diff --git a/releases/2026-10-20-code/diffsynth/models/__init__.py b/releases/2026-10-20-code/diffsynth/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/releases/2026-10-20-code/diffsynth/models/downloader.py b/releases/2026-10-20-code/diffsynth/models/downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..84fad0d36171b1c1d4b9dfd08972606c9c60ce52 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/downloader.py @@ -0,0 +1,116 @@ +from huggingface_hub import hf_hub_download +try: + from modelscope import snapshot_download +except ModuleNotFoundError: + snapshot_download = None +import os, shutil +from typing_extensions import Literal, TypeAlias +from typing import List +from ..configs.model_config import preset_models_on_huggingface, preset_models_on_modelscope, Preset_model_id + + +def download_from_modelscope(model_id, origin_file_path, local_dir): + if snapshot_download is None: + raise ModuleNotFoundError("modelscope is required to download models from ModelScope.") + os.makedirs(local_dir, exist_ok=True) + file_name = os.path.basename(origin_file_path) + if file_name in os.listdir(local_dir): + print(f" {file_name} has been already in {local_dir}.") + else: + print(f" Start downloading {os.path.join(local_dir, file_name)}") + snapshot_download(model_id, allow_file_pattern=origin_file_path, local_dir=local_dir) + downloaded_file_path = os.path.join(local_dir, origin_file_path) + target_file_path = os.path.join(local_dir, os.path.split(origin_file_path)[-1]) + if downloaded_file_path != target_file_path: + shutil.move(downloaded_file_path, target_file_path) + shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0])) + + +def download_from_huggingface(model_id, origin_file_path, local_dir): + os.makedirs(local_dir, exist_ok=True) + file_name = os.path.basename(origin_file_path) + if file_name in os.listdir(local_dir): + print(f" {file_name} has been already in {local_dir}.") + else: + print(f" Start downloading {os.path.join(local_dir, file_name)}") + hf_hub_download(model_id, origin_file_path, local_dir=local_dir) + downloaded_file_path = os.path.join(local_dir, origin_file_path) + target_file_path = os.path.join(local_dir, file_name) + if downloaded_file_path != target_file_path: + shutil.move(downloaded_file_path, target_file_path) + shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0])) + + +Preset_model_website: TypeAlias = Literal[ + "HuggingFace", + "ModelScope", +] +website_to_preset_models = { + "HuggingFace": preset_models_on_huggingface, + "ModelScope": preset_models_on_modelscope, +} +website_to_download_fn = { + "HuggingFace": download_from_huggingface, + "ModelScope": download_from_modelscope, +} + + +def download_customized_models( + model_id, + origin_file_path, + local_dir, + downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"], +): + downloaded_files = [] + for website in downloading_priority: + # Check if the file is downloaded. + file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path)) + if file_to_download in downloaded_files: + continue + # Download + website_to_download_fn[website](model_id, origin_file_path, local_dir) + if os.path.basename(origin_file_path) in os.listdir(local_dir): + downloaded_files.append(file_to_download) + return downloaded_files + + +def download_models( + model_id_list: List[Preset_model_id] = [], + downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"], +): + print(f"Downloading models: {model_id_list}") + downloaded_files = [] + load_files = [] + + for model_id in model_id_list: + for website in downloading_priority: + if model_id in website_to_preset_models[website]: + + # Parse model metadata + model_metadata = website_to_preset_models[website][model_id] + if isinstance(model_metadata, list): + file_data = model_metadata + else: + file_data = model_metadata.get("file_list", []) + + # Try downloading the model from this website. + model_files = [] + for model_id, origin_file_path, local_dir in file_data: + # Check if the file is downloaded. + file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path)) + if file_to_download in downloaded_files: + continue + # Download + website_to_download_fn[website](model_id, origin_file_path, local_dir) + if os.path.basename(origin_file_path) in os.listdir(local_dir): + downloaded_files.append(file_to_download) + model_files.append(file_to_download) + + # If the model is successfully downloaded, break. + if len(model_files) > 0: + if isinstance(model_metadata, dict) and "load_path" in model_metadata: + model_files = model_metadata["load_path"] + load_files.extend(model_files) + break + + return load_files diff --git a/releases/2026-10-20-code/diffsynth/models/model_manager.py b/releases/2026-10-20-code/diffsynth/models/model_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..df4aa90159f48d9ae5b47e84fbcd37a199df3c31 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/model_manager.py @@ -0,0 +1,404 @@ +import os, torch, json, importlib +from typing import List + +from .downloader import download_models, download_customized_models, Preset_model_id, Preset_model_website + + +from ..configs.model_config import model_loader_configs, huggingface_model_loader_configs, patch_model_loader_configs +from .utils import load_state_dict, init_weights_on_device, hash_state_dict_keys, split_state_dict_with_prefix + + +def load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device): + loaded_model_names, loaded_models = [], [] + for model_name, model_class in zip(model_names, model_classes): + print(f" model_name: {model_name} model_class: {model_class.__name__}") + state_dict_converter = model_class.state_dict_converter() + if model_resource == "civitai": + state_dict_results = state_dict_converter.from_civitai(state_dict) + elif model_resource == "diffusers": + state_dict_results = state_dict_converter.from_diffusers(state_dict) + if isinstance(state_dict_results, tuple): + model_state_dict, extra_kwargs = state_dict_results + print(f" This model is initialized with extra kwargs: {extra_kwargs}") + else: + model_state_dict, extra_kwargs = state_dict_results, {} + torch_dtype = torch.float32 if extra_kwargs.get("upcast_to_float32", False) else torch_dtype + with init_weights_on_device(): + model = model_class(**extra_kwargs) + if hasattr(model, "eval"): + model = model.eval() + model.load_state_dict(model_state_dict, assign=True) + model = model.to(dtype=torch_dtype, device=device) + loaded_model_names.append(model_name) + loaded_models.append(model) + return loaded_model_names, loaded_models + + +def load_model_from_huggingface_folder(file_path, model_names, model_classes, torch_dtype, device): + loaded_model_names, loaded_models = [], [] + for model_name, model_class in zip(model_names, model_classes): + if torch_dtype in [torch.float32, torch.float16, torch.bfloat16]: + model = model_class.from_pretrained(file_path, torch_dtype=torch_dtype).eval() + else: + model = model_class.from_pretrained(file_path).eval().to(dtype=torch_dtype) + if torch_dtype == torch.float16 and hasattr(model, "half"): + model = model.half() + try: + model = model.to(device=device) + except: + pass + loaded_model_names.append(model_name) + loaded_models.append(model) + return loaded_model_names, loaded_models + + +def load_single_patch_model_from_single_file(state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device): + print(f" model_name: {model_name} model_class: {model_class.__name__} extra_kwargs: {extra_kwargs}") + base_state_dict = base_model.state_dict() + base_model.to("cpu") + del base_model + model = model_class(**extra_kwargs) + model.load_state_dict(base_state_dict, strict=False) + model.load_state_dict(state_dict, strict=False) + model.to(dtype=torch_dtype, device=device) + return model + + +def load_patch_model_from_single_file(state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device): + loaded_model_names, loaded_models = [], [] + for model_name, model_class in zip(model_names, model_classes): + while True: + for model_id in range(len(model_manager.model)): + base_model_name = model_manager.model_name[model_id] + if base_model_name == model_name: + base_model_path = model_manager.model_path[model_id] + base_model = model_manager.model[model_id] + print(f" Adding patch model to {base_model_name} ({base_model_path})") + patched_model = load_single_patch_model_from_single_file( + state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device) + loaded_model_names.append(base_model_name) + loaded_models.append(patched_model) + model_manager.model.pop(model_id) + model_manager.model_path.pop(model_id) + model_manager.model_name.pop(model_id) + break + else: + break + return loaded_model_names, loaded_models + + + +class ModelDetectorTemplate: + def __init__(self): + pass + + def match(self, file_path="", state_dict={}): + return False + + def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs): + return [], [] + + + +class ModelDetectorFromSingleFile: + def __init__(self, model_loader_configs=[]): + self.keys_hash_with_shape_dict = {} + self.keys_hash_dict = {} + for metadata in model_loader_configs: + self.add_model_metadata(*metadata) + + + def add_model_metadata(self, keys_hash, keys_hash_with_shape, model_names, model_classes, model_resource): + self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_names, model_classes, model_resource) + if keys_hash is not None: + self.keys_hash_dict[keys_hash] = (model_names, model_classes, model_resource) + + + def match(self, file_path="", state_dict={}): + if isinstance(file_path, str) and os.path.isdir(file_path): + return False + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True) + if keys_hash_with_shape in self.keys_hash_with_shape_dict: + return True + keys_hash = hash_state_dict_keys(state_dict, with_shape=False) + if keys_hash in self.keys_hash_dict: + return True + return False + + + def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs): + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + + # Load models with strict matching + keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True) + if keys_hash_with_shape in self.keys_hash_with_shape_dict: + model_names, model_classes, model_resource = self.keys_hash_with_shape_dict[keys_hash_with_shape] + loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device) + return loaded_model_names, loaded_models + + # Load models without strict matching + # (the shape of parameters may be inconsistent, and the state_dict_converter will modify the model architecture) + keys_hash = hash_state_dict_keys(state_dict, with_shape=False) + if keys_hash in self.keys_hash_dict: + model_names, model_classes, model_resource = self.keys_hash_dict[keys_hash] + loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device) + return loaded_model_names, loaded_models + + return loaded_model_names, loaded_models + + + +class ModelDetectorFromSplitedSingleFile(ModelDetectorFromSingleFile): + def __init__(self, model_loader_configs=[]): + super().__init__(model_loader_configs) + + + def match(self, file_path="", state_dict={}): + if isinstance(file_path, str) and os.path.isdir(file_path): + return False + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + splited_state_dict = split_state_dict_with_prefix(state_dict) + for sub_state_dict in splited_state_dict: + if super().match(file_path, sub_state_dict): + return True + return False + + + def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs): + # Split the state_dict and load from each component + splited_state_dict = split_state_dict_with_prefix(state_dict) + valid_state_dict = {} + for sub_state_dict in splited_state_dict: + if super().match(file_path, sub_state_dict): + valid_state_dict.update(sub_state_dict) + if super().match(file_path, valid_state_dict): + loaded_model_names, loaded_models = super().load(file_path, valid_state_dict, device, torch_dtype) + else: + loaded_model_names, loaded_models = [], [] + for sub_state_dict in splited_state_dict: + if super().match(file_path, sub_state_dict): + loaded_model_names_, loaded_models_ = super().load(file_path, valid_state_dict, device, torch_dtype) + loaded_model_names += loaded_model_names_ + loaded_models += loaded_models_ + return loaded_model_names, loaded_models + + + +class ModelDetectorFromHuggingfaceFolder: + def __init__(self, model_loader_configs=[]): + self.architecture_dict = {} + for metadata in model_loader_configs: + self.add_model_metadata(*metadata) + + + def add_model_metadata(self, architecture, huggingface_lib, model_name, redirected_architecture): + self.architecture_dict[architecture] = (huggingface_lib, model_name, redirected_architecture) + + + def match(self, file_path="", state_dict={}): + if not isinstance(file_path, str) or os.path.isfile(file_path): + return False + file_list = os.listdir(file_path) + if "config.json" not in file_list: + return False + with open(os.path.join(file_path, "config.json"), "r") as f: + config = json.load(f) + if "architectures" not in config and "_class_name" not in config: + return False + return True + + + def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs): + with open(os.path.join(file_path, "config.json"), "r") as f: + config = json.load(f) + loaded_model_names, loaded_models = [], [] + architectures = config["architectures"] if "architectures" in config else [config["_class_name"]] + for architecture in architectures: + huggingface_lib, model_name, redirected_architecture = self.architecture_dict[architecture] + if redirected_architecture is not None: + architecture = redirected_architecture + model_class = importlib.import_module(huggingface_lib).__getattribute__(architecture) + loaded_model_names_, loaded_models_ = load_model_from_huggingface_folder(file_path, [model_name], [model_class], torch_dtype, device) + loaded_model_names += loaded_model_names_ + loaded_models += loaded_models_ + return loaded_model_names, loaded_models + + + +class ModelDetectorFromPatchedSingleFile: + def __init__(self, model_loader_configs=[]): + self.keys_hash_with_shape_dict = {} + for metadata in model_loader_configs: + self.add_model_metadata(*metadata) + + + def add_model_metadata(self, keys_hash_with_shape, model_name, model_class, extra_kwargs): + self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_name, model_class, extra_kwargs) + + + def match(self, file_path="", state_dict={}): + if not isinstance(file_path, str) or os.path.isdir(file_path): + return False + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True) + if keys_hash_with_shape in self.keys_hash_with_shape_dict: + return True + return False + + + def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, model_manager=None, **kwargs): + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + + # Load models with strict matching + loaded_model_names, loaded_models = [], [] + keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True) + if keys_hash_with_shape in self.keys_hash_with_shape_dict: + model_names, model_classes, extra_kwargs = self.keys_hash_with_shape_dict[keys_hash_with_shape] + loaded_model_names_, loaded_models_ = load_patch_model_from_single_file( + state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device) + loaded_model_names += loaded_model_names_ + loaded_models += loaded_models_ + return loaded_model_names, loaded_models + + + +class ModelManager: + def __init__( + self, + torch_dtype=torch.float16, + device="cuda", + model_id_list: List[Preset_model_id] = [], + downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"], + file_path_list: List[str] = [], + ): + self.torch_dtype = torch_dtype + self.device = device + self.model = [] + self.model_path = [] + self.model_name = [] + downloaded_files = download_models(model_id_list, downloading_priority) if len(model_id_list) > 0 else [] + self.model_detector = [ + ModelDetectorFromSingleFile(model_loader_configs), + ModelDetectorFromSplitedSingleFile(model_loader_configs), + ModelDetectorFromHuggingfaceFolder(huggingface_model_loader_configs), + ModelDetectorFromPatchedSingleFile(patch_model_loader_configs), + ] + self.load_models(downloaded_files + file_path_list) + + + def load_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], model_resource=None): + print(f"Loading models from file: {file_path}") + if len(state_dict) == 0: + state_dict = load_state_dict(file_path) + model_names, models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, self.torch_dtype, self.device) + for model_name, model in zip(model_names, models): + self.model.append(model) + self.model_path.append(file_path) + self.model_name.append(model_name) + print(f" The following models are loaded: {model_names}.") + + + def load_model_from_huggingface_folder(self, file_path="", model_names=[], model_classes=[]): + print(f"Loading models from folder: {file_path}") + model_names, models = load_model_from_huggingface_folder(file_path, model_names, model_classes, self.torch_dtype, self.device) + for model_name, model in zip(model_names, models): + self.model.append(model) + self.model_path.append(file_path) + self.model_name.append(model_name) + print(f" The following models are loaded: {model_names}.") + + + def load_patch_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], extra_kwargs={}): + print(f"Loading patch models from file: {file_path}") + model_names, models = load_patch_model_from_single_file( + state_dict, model_names, model_classes, extra_kwargs, self, self.torch_dtype, self.device) + for model_name, model in zip(model_names, models): + self.model.append(model) + self.model_path.append(file_path) + self.model_name.append(model_name) + print(f" The following patched models are loaded: {model_names}.") + + + def load_lora(self, *args, **kwargs): + raise NotImplementedError("LoRA loading is omitted from the Wan-only ViBT release.") + + + def load_model(self, file_path, model_names=None, device=None, torch_dtype=None): + print(f"Loading models from: {file_path}") + if device is None: device = self.device + if torch_dtype is None: torch_dtype = self.torch_dtype + if isinstance(file_path, list): + state_dict = {} + for path in file_path: + state_dict.update(load_state_dict(path)) + elif os.path.isfile(file_path): + state_dict = load_state_dict(file_path) + else: + state_dict = None + for model_detector in self.model_detector: + if model_detector.match(file_path, state_dict): + model_names, models = model_detector.load( + file_path, state_dict, + device=device, torch_dtype=torch_dtype, + allowed_model_names=model_names, model_manager=self + ) + for model_name, model in zip(model_names, models): + self.model.append(model) + self.model_path.append(file_path) + self.model_name.append(model_name) + print(f" The following models are loaded: {model_names}.") + break + else: + print(f" We cannot detect the model type. No models are loaded.") + + + def load_models(self, file_path_list, model_names=None, device=None, torch_dtype=None): + for file_path in file_path_list: + self.load_model(file_path, model_names, device=device, torch_dtype=torch_dtype) + + + def fetch_model(self, model_name, file_path=None, require_model_path=False, index=None): + fetched_models = [] + fetched_model_paths = [] + for model, model_path, model_name_ in zip(self.model, self.model_path, self.model_name): + if file_path is not None and file_path != model_path: + continue + if model_name == model_name_: + fetched_models.append(model) + fetched_model_paths.append(model_path) + if len(fetched_models) == 0: + print(f"No {model_name} models available.") + return None + if len(fetched_models) == 1: + print(f"Using {model_name} from {fetched_model_paths[0]}.") + model = fetched_models[0] + path = fetched_model_paths[0] + else: + if index is None: + model = fetched_models[0] + path = fetched_model_paths[0] + print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths[0]}.") + elif isinstance(index, int): + model = fetched_models[:index] + path = fetched_model_paths[:index] + print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths[:index]}.") + else: + model = fetched_models + path = fetched_model_paths + print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths}.") + if require_model_path: + return model, path + else: + return model + + + def to(self, device): + for model in self.model: + model.to(device) + diff --git a/releases/2026-10-20-code/diffsynth/models/utils.py b/releases/2026-10-20-code/diffsynth/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..845813d91498c5cba3b09623fc7064936fd44c8d --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/utils.py @@ -0,0 +1,196 @@ +import json +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) + if file_path.endswith(".safetensors.index.json"): + with open(file_path, "r", encoding="utf-8") as f: + index = json.load(f) + shard_names = sorted(set(index["weight_map"].values())) + state_dict = {} + for shard_name in shard_names: + shard_path = os.path.join(os.path.dirname(file_path), shard_name) + state_dict.update( + load_state_dict_from_safetensors( + shard_path, torch_dtype=torch_dtype, device=device + ) + ) + return state_dict + 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() diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_animate_adapter.py b/releases/2026-10-20-code/diffsynth/models/wan_video_animate_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..771280a2e2e26c08025cf528cfcea98a85e0b6b0 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_animate_adapter.py @@ -0,0 +1,670 @@ +import torch +import torch.nn as nn +from torch.nn import functional as F +import math +from typing import Tuple, Optional, List +from einops import rearrange + + + +MEMORY_LAYOUT = { + "flash": ( + lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]), + lambda x: x, + ), + "torch": ( + lambda x: x.transpose(1, 2), + lambda x: x.transpose(1, 2), + ), + "vanilla": ( + lambda x: x.transpose(1, 2), + lambda x: x.transpose(1, 2), + ), +} + + +def attention( + q, + k, + v, + mode="torch", + drop_rate=0, + attn_mask=None, + causal=False, + max_seqlen_q=None, + batch_size=1, +): + pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode] + + if mode == "torch": + if attn_mask is not None and attn_mask.dtype != torch.bool: + attn_mask = attn_mask.to(q.dtype) + x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal) + + x = post_attn_layout(x) + b, s, a, d = x.shape + out = x.reshape(b, s, -1) + return out + + +class CausalConv1d(nn.Module): + + def __init__(self, chan_in, chan_out, kernel_size=3, stride=1, dilation=1, pad_mode="replicate", **kwargs): + super().__init__() + + self.pad_mode = pad_mode + padding = (kernel_size - 1, 0) # T + self.time_causal_padding = padding + + self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs) + + def forward(self, x): + x = F.pad(x, self.time_causal_padding, mode=self.pad_mode) + return self.conv(x) + + + +class FaceEncoder(nn.Module): + def __init__(self, in_dim: int, hidden_dim: int, num_heads=int, dtype=None, device=None): + factory_kwargs = {"dtype": dtype, "device": device} + super().__init__() + + self.num_heads = num_heads + self.conv1_local = CausalConv1d(in_dim, 1024 * num_heads, 3, stride=1) + self.norm1 = nn.LayerNorm(hidden_dim // 8, elementwise_affine=False, eps=1e-6, **factory_kwargs) + self.act = nn.SiLU() + self.conv2 = CausalConv1d(1024, 1024, 3, stride=2) + self.conv3 = CausalConv1d(1024, 1024, 3, stride=2) + + self.out_proj = nn.Linear(1024, hidden_dim) + self.norm1 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs) + + self.norm2 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs) + + self.norm3 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs) + + self.padding_tokens = nn.Parameter(torch.zeros(1, 1, 1, hidden_dim)) + + def forward(self, x): + + x = rearrange(x, "b t c -> b c t") + b, c, t = x.shape + + x = self.conv1_local(x) + x = rearrange(x, "b (n c) t -> (b n) t c", n=self.num_heads) + + x = self.norm1(x) + x = self.act(x) + x = rearrange(x, "b t c -> b c t") + x = self.conv2(x) + x = rearrange(x, "b c t -> b t c") + x = self.norm2(x) + x = self.act(x) + x = rearrange(x, "b t c -> b c t") + x = self.conv3(x) + x = rearrange(x, "b c t -> b t c") + x = self.norm3(x) + x = self.act(x) + x = self.out_proj(x) + x = rearrange(x, "(b n) t c -> b t n c", b=b) + padding = self.padding_tokens.repeat(b, x.shape[1], 1, 1) + x = torch.cat([x, padding], dim=-2) + x_local = x.clone() + + return x_local + + + +class RMSNorm(nn.Module): + def __init__( + self, + dim: int, + elementwise_affine=True, + eps: float = 1e-6, + device=None, + dtype=None, + ): + """ + Initialize the RMSNorm normalization layer. + + Args: + dim (int): The dimension of the input tensor. + eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6. + + Attributes: + eps (float): A small value added to the denominator for numerical stability. + weight (nn.Parameter): Learnable scaling parameter. + + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + if elementwise_affine: + self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs)) + + def _norm(self, x): + """ + Apply the RMSNorm normalization to the input tensor. + + Args: + x (torch.Tensor): The input tensor. + + Returns: + torch.Tensor: The normalized tensor. + + """ + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x): + """ + Forward pass through the RMSNorm layer. + + Args: + x (torch.Tensor): The input tensor. + + Returns: + torch.Tensor: The output tensor after applying RMSNorm. + + """ + output = self._norm(x.float()).type_as(x) + if hasattr(self, "weight"): + output = output * self.weight + return output + + +def get_norm_layer(norm_layer): + """ + Get the normalization layer. + + Args: + norm_layer (str): The type of normalization layer. + + Returns: + norm_layer (nn.Module): The normalization layer. + """ + if norm_layer == "layer": + return nn.LayerNorm + elif norm_layer == "rms": + return RMSNorm + else: + raise NotImplementedError(f"Norm layer {norm_layer} is not implemented") + + +class FaceAdapter(nn.Module): + def __init__( + self, + hidden_dim: int, + heads_num: int, + qk_norm: bool = True, + qk_norm_type: str = "rms", + num_adapter_layers: int = 1, + dtype=None, + device=None, + ): + + factory_kwargs = {"dtype": dtype, "device": device} + super().__init__() + self.hidden_size = hidden_dim + self.heads_num = heads_num + self.fuser_blocks = nn.ModuleList( + [ + FaceBlock( + self.hidden_size, + self.heads_num, + qk_norm=qk_norm, + qk_norm_type=qk_norm_type, + **factory_kwargs, + ) + for _ in range(num_adapter_layers) + ] + ) + + def forward( + self, + x: torch.Tensor, + motion_embed: torch.Tensor, + idx: int, + freqs_cis_q: Tuple[torch.Tensor, torch.Tensor] = None, + freqs_cis_k: Tuple[torch.Tensor, torch.Tensor] = None, + ) -> torch.Tensor: + + return self.fuser_blocks[idx](x, motion_embed, freqs_cis_q, freqs_cis_k) + + + +class FaceBlock(nn.Module): + def __init__( + self, + hidden_size: int, + heads_num: int, + qk_norm: bool = True, + qk_norm_type: str = "rms", + qk_scale: float = None, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + + self.deterministic = False + self.hidden_size = hidden_size + self.heads_num = heads_num + head_dim = hidden_size // heads_num + self.scale = qk_scale or head_dim**-0.5 + + self.linear1_kv = nn.Linear(hidden_size, hidden_size * 2, **factory_kwargs) + self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs) + + self.linear2 = nn.Linear(hidden_size, hidden_size, **factory_kwargs) + + qk_norm_layer = get_norm_layer(qk_norm_type) + self.q_norm = ( + qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() + ) + self.k_norm = ( + qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() + ) + + self.pre_norm_feat = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) + + self.pre_norm_motion = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) + + def forward( + self, + x: torch.Tensor, + motion_vec: torch.Tensor, + motion_mask: Optional[torch.Tensor] = None, + use_context_parallel=False, + ) -> torch.Tensor: + + B, T, N, C = motion_vec.shape + T_comp = T + + x_motion = self.pre_norm_motion(motion_vec) + x_feat = self.pre_norm_feat(x) + + kv = self.linear1_kv(x_motion) + q = self.linear1_q(x_feat) + + k, v = rearrange(kv, "B L N (K H D) -> K B L N H D", K=2, H=self.heads_num) + q = rearrange(q, "B S (H D) -> B S H D", H=self.heads_num) + + # Apply QK-Norm if needed. + q = self.q_norm(q).to(v) + k = self.k_norm(k).to(v) + + k = rearrange(k, "B L N H D -> (B L) H N D") + v = rearrange(v, "B L N H D -> (B L) H N D") + + q = rearrange(q, "B (L S) H D -> (B L) H S D", L=T_comp) + # Compute attention. + attn = F.scaled_dot_product_attention(q, k, v) + + attn = rearrange(attn, "(B L) H S D -> B (L S) (H D)", L=T_comp) + + output = self.linear2(attn) + + if motion_mask is not None: + output = output * rearrange(motion_mask, "B T H W -> B (T H W)").unsqueeze(-1) + + return output + + + +def custom_qr(input_tensor): + original_dtype = input_tensor.dtype + if original_dtype == torch.bfloat16: + q, r = torch.linalg.qr(input_tensor.to(torch.float32)) + return q.to(original_dtype), r.to(original_dtype) + return torch.linalg.qr(input_tensor) + +def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): + return F.leaky_relu(input + bias, negative_slope) * scale + + +def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): + _, minor, in_h, in_w = input.shape + kernel_h, kernel_w = kernel.shape + + out = input.view(-1, minor, in_h, 1, in_w, 1) + out = F.pad(out, [0, up_x - 1, 0, 0, 0, up_y - 1, 0, 0]) + out = out.view(-1, minor, in_h * up_y, in_w * up_x) + + out = F.pad(out, [max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) + out = out[:, :, max(-pad_y0, 0): out.shape[2] - max(-pad_y1, 0), + max(-pad_x0, 0): out.shape[3] - max(-pad_x1, 0), ] + + out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) + w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) + out = F.conv2d(out, w) + out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, + in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, ) + return out[:, :, ::down_y, ::down_x] + + +def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): + return upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) + + +def make_kernel(k): + k = torch.tensor(k, dtype=torch.float32) + if k.ndim == 1: + k = k[None, :] * k[:, None] + k /= k.sum() + return k + + +class FusedLeakyReLU(nn.Module): + def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5): + super().__init__() + self.bias = nn.Parameter(torch.zeros(1, channel, 1, 1)) + self.negative_slope = negative_slope + self.scale = scale + + def forward(self, input): + out = fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) + return out + + +class Blur(nn.Module): + def __init__(self, kernel, pad, upsample_factor=1): + super().__init__() + + kernel = make_kernel(kernel) + + if upsample_factor > 1: + kernel = kernel * (upsample_factor ** 2) + + self.register_buffer('kernel', kernel) + + self.pad = pad + + def forward(self, input): + return upfirdn2d(input, self.kernel, pad=self.pad) + + +class ScaledLeakyReLU(nn.Module): + def __init__(self, negative_slope=0.2): + super().__init__() + + self.negative_slope = negative_slope + + def forward(self, input): + return F.leaky_relu(input, negative_slope=self.negative_slope) + + +class EqualConv2d(nn.Module): + def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True): + super().__init__() + + self.weight = nn.Parameter(torch.randn(out_channel, in_channel, kernel_size, kernel_size)) + self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2) + + self.stride = stride + self.padding = padding + + if bias: + self.bias = nn.Parameter(torch.zeros(out_channel)) + else: + self.bias = None + + def forward(self, input): + + return F.conv2d(input, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding) + + def __repr__(self): + return ( + f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},' + f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})' + ) + + +class EqualLinear(nn.Module): + def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None): + super().__init__() + + self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul)) + + if bias: + self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init)) + else: + self.bias = None + + self.activation = activation + + self.scale = (1 / math.sqrt(in_dim)) * lr_mul + self.lr_mul = lr_mul + + def forward(self, input): + + if self.activation: + out = F.linear(input, self.weight * self.scale) + out = fused_leaky_relu(out, self.bias * self.lr_mul) + else: + out = F.linear(input, self.weight * self.scale, bias=self.bias * self.lr_mul) + + return out + + def __repr__(self): + return (f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})') + + +class ConvLayer(nn.Sequential): + def __init__( + self, + in_channel, + out_channel, + kernel_size, + downsample=False, + blur_kernel=[1, 3, 3, 1], + bias=True, + activate=True, + ): + layers = [] + + if downsample: + factor = 2 + p = (len(blur_kernel) - factor) + (kernel_size - 1) + pad0 = (p + 1) // 2 + pad1 = p // 2 + + layers.append(Blur(blur_kernel, pad=(pad0, pad1))) + + stride = 2 + self.padding = 0 + + else: + stride = 1 + self.padding = kernel_size // 2 + + layers.append(EqualConv2d(in_channel, out_channel, kernel_size, padding=self.padding, stride=stride, + bias=bias and not activate)) + + if activate: + if bias: + layers.append(FusedLeakyReLU(out_channel)) + else: + layers.append(ScaledLeakyReLU(0.2)) + + super().__init__(*layers) + + +class ResBlock(nn.Module): + def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]): + super().__init__() + + self.conv1 = ConvLayer(in_channel, in_channel, 3) + self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True) + + self.skip = ConvLayer(in_channel, out_channel, 1, downsample=True, activate=False, bias=False) + + def forward(self, input): + out = self.conv1(input) + out = self.conv2(out) + + skip = self.skip(input) + out = (out + skip) / math.sqrt(2) + + return out + + +class EncoderApp(nn.Module): + def __init__(self, size, w_dim=512): + super(EncoderApp, self).__init__() + + channels = { + 4: 512, + 8: 512, + 16: 512, + 32: 512, + 64: 256, + 128: 128, + 256: 64, + 512: 32, + 1024: 16 + } + + self.w_dim = w_dim + log_size = int(math.log(size, 2)) + + self.convs = nn.ModuleList() + self.convs.append(ConvLayer(3, channels[size], 1)) + + in_channel = channels[size] + for i in range(log_size, 2, -1): + out_channel = channels[2 ** (i - 1)] + self.convs.append(ResBlock(in_channel, out_channel)) + in_channel = out_channel + + self.convs.append(EqualConv2d(in_channel, self.w_dim, 4, padding=0, bias=False)) + + def forward(self, x): + + res = [] + h = x + for conv in self.convs: + h = conv(h) + res.append(h) + + return res[-1].squeeze(-1).squeeze(-1), res[::-1][2:] + + +class Encoder(nn.Module): + def __init__(self, size, dim=512, dim_motion=20): + super(Encoder, self).__init__() + + # appearance netmork + self.net_app = EncoderApp(size, dim) + + # motion network + fc = [EqualLinear(dim, dim)] + for i in range(3): + fc.append(EqualLinear(dim, dim)) + + fc.append(EqualLinear(dim, dim_motion)) + self.fc = nn.Sequential(*fc) + + def enc_app(self, x): + h_source = self.net_app(x) + return h_source + + def enc_motion(self, x): + h, _ = self.net_app(x) + h_motion = self.fc(h) + return h_motion + + +class Direction(nn.Module): + def __init__(self, motion_dim): + super(Direction, self).__init__() + self.weight = nn.Parameter(torch.randn(512, motion_dim)) + + def forward(self, input): + + weight = self.weight + 1e-8 + Q, R = custom_qr(weight) + if input is None: + return Q + else: + input_diag = torch.diag_embed(input) # alpha, diagonal matrix + out = torch.matmul(input_diag, Q.T) + out = torch.sum(out, dim=1) + return out + + +class Synthesis(nn.Module): + def __init__(self, motion_dim): + super(Synthesis, self).__init__() + self.direction = Direction(motion_dim) + + +class Generator(nn.Module): + def __init__(self, size, style_dim=512, motion_dim=20): + super().__init__() + + self.enc = Encoder(size, style_dim, motion_dim) + self.dec = Synthesis(motion_dim) + + def get_motion(self, img): + #motion_feat = self.enc.enc_motion(img) + motion_feat = torch.utils.checkpoint.checkpoint((self.enc.enc_motion), img, use_reentrant=True) + motion = self.dec.direction(motion_feat) + return motion + + +class WanAnimateAdapter(torch.nn.Module): + def __init__(self): + super().__init__() + self.pose_patch_embedding = torch.nn.Conv3d(16, 5120, kernel_size=(1, 2, 2), stride=(1, 2, 2)) + self.motion_encoder = Generator(size=512, style_dim=512, motion_dim=20) + self.face_adapter = FaceAdapter(heads_num=40, hidden_dim=5120, num_adapter_layers=40 // 5) + self.face_encoder = FaceEncoder(in_dim=512, hidden_dim=5120, num_heads=4) + + def after_patch_embedding(self, x: List[torch.Tensor], pose_latents, face_pixel_values): + pose_latents = self.pose_patch_embedding(pose_latents) + x[:, :, 1:] += pose_latents + + b,c,T,h,w = face_pixel_values.shape + face_pixel_values = rearrange(face_pixel_values, "b c t h w -> (b t) c h w") + + encode_bs = 8 + face_pixel_values_tmp = [] + for i in range(math.ceil(face_pixel_values.shape[0]/encode_bs)): + face_pixel_values_tmp.append(self.motion_encoder.get_motion(face_pixel_values[i*encode_bs:(i+1)*encode_bs])) + + motion_vec = torch.cat(face_pixel_values_tmp) + + motion_vec = rearrange(motion_vec, "(b t) c -> b t c", t=T) + motion_vec = self.face_encoder(motion_vec) + + B, L, H, C = motion_vec.shape + pad_face = torch.zeros(B, 1, H, C).type_as(motion_vec) + motion_vec = torch.cat([pad_face, motion_vec], dim=1) + return x, motion_vec + + def after_transformer_block(self, block_idx, x, motion_vec, motion_masks=None): + if block_idx % 5 == 0: + adapter_args = [x, motion_vec, motion_masks, False] + residual_out = self.face_adapter.fuser_blocks[block_idx // 5](*adapter_args) + x = residual_out + x + return x + + @staticmethod + def state_dict_converter(): + return WanAnimateAdapterStateDictConverter() + + +class WanAnimateAdapterStateDictConverter: + def __init__(self): + pass + + def from_diffusers(self, state_dict): + return state_dict + + def from_civitai(self, state_dict): + state_dict_ = {} + for name, param in state_dict.items(): + if name.startswith("pose_patch_embedding.") or name.startswith("face_adapter") or name.startswith("face_encoder") or name.startswith("motion_encoder"): + state_dict_[name] = param + return state_dict_ + diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_camera_controller.py b/releases/2026-10-20-code/diffsynth/models/wan_video_camera_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..45a44ee6bcd408d7ee9d18653f933151ce351a72 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_camera_controller.py @@ -0,0 +1,206 @@ +import torch +import torch.nn as nn +import numpy as np +from einops import rearrange +import os +from typing_extensions import Literal + +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/releases/2026-10-20-code/diffsynth/models/wan_video_dit.py b/releases/2026-10-20-code/diffsynth/models/wan_video_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..42dd91d4c3e89acd2dd374b7b989b25d395f7894 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_dit.py @@ -0,0 +1,834 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import math +from typing import Tuple, Optional +from einops import rearrange +from .utils import hash_state_dict_keys +from .wan_video_camera_controller import SimpleAdapter +from diffsynth.pipelines.attention_masks import TokenPrefixAttentionSpec, ReferenceSequenceAttentionSpec, CausalReferenceSequenceAttentionSpec +try: + import torch_npu +except ModuleNotFoundError: + torch_npu = None +try: + import flash_attn_interface + FLASH_ATTN_3_AVAILABLE = True +except ModuleNotFoundError: + FLASH_ATTN_3_AVAILABLE = False + +try: + import flash_attn + FLASH_ATTN_2_AVAILABLE = True +except ModuleNotFoundError: + FLASH_ATTN_2_AVAILABLE = False + +try: + from sageattention import sageattn + SAGE_ATTN_AVAILABLE = True +except ModuleNotFoundError: + SAGE_ATTN_AVAILABLE = False + + +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: + 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: + 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) + 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) + return freqs_cis.to(torch.complex64) + + +def rope_apply(x, freqs, num_heads): + x = rearrange(x, "b s (n d) -> b s n d", n=num_heads) + rope_dtype = torch.float32 if x.device.type == "npu" else torch.float64 + x_out = torch.view_as_complex(x.to(rope_dtype).reshape( + x.shape[0], x.shape[1], x.shape[2], -1, 2)) + if freqs.device != x.device: + freqs = freqs.to(device=x.device) + x_out = torch.view_as_real(x_out * freqs).flatten(2) + return x_out.to(x.dtype) + + +class RMSNorm(nn.Module): + def __init__(self, dim, eps=1e-5): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def norm(self, x): + return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) + + def forward(self, x): + if x.device.type == "npu" and torch_npu is not None: + out = torch_npu.npu_rms_norm(x, self.weight, epsilon=self.eps) + return out[0] if isinstance(out, tuple) else out + 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, attn_mask=None): + if isinstance(attn_mask, CausalReferenceSequenceAttentionSpec): + b, s, _ = q.shape; l = attn_mask.latent_token_count + if s != attn_mask.total_token_count: raise ValueError("causal reference attention shape mismatch") + qh = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads) + kh = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads) + vh = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads) + f, n = int(attn_mask.latent_frames), int(attn_mask.tokens_per_frame) + frame_ids = torch.arange(l, device=q.device) // n + causal = frame_ids[:, None] >= frame_ids[None, :] + latent = F.scaled_dot_product_attention(qh[:, :, :l], kh[:, :, :l], vh[:, :, :l], attn_mask=causal) + qf = qh[:, :, :l].reshape(b, self.num_heads, f, n, -1) + kr = kh[:, :, l:].reshape(b, self.num_heads, f, n, -1) + vr = vh[:, :, l:].reshape(b, self.num_heads, f, n, -1) + cross = F.scaled_dot_product_attention(qf.reshape(b*f,self.num_heads,n,-1), kr.reshape(b*f,self.num_heads,n,-1), vr.reshape(b*f,self.num_heads,n,-1)).reshape(b,self.num_heads,l,-1) + ref = torch.zeros_like(qh[:, :, l:]) + return rearrange(torch.cat([latent + cross, ref], dim=2), "b n s d -> b s (n d)", n=self.num_heads) + if isinstance(attn_mask, ReferenceSequenceAttentionSpec): + b, s, _ = q.shape; l = attn_mask.latent_token_count + if s != attn_mask.total_token_count: raise ValueError("reference attention shape mismatch") + qh = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads) + kh = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads) + vh = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads) + latent = F.scaled_dot_product_attention(qh[:, :, :l], kh[:, :, :l], vh[:, :, :l]) + f, n = int(attn_mask.latent_frames), int(attn_mask.tokens_per_frame) + qf = qh[:, :, :l].reshape(b, self.num_heads, f, n, -1) + kr = kh[:, :, l:].reshape(b, self.num_heads, f, n, -1) + vr = vh[:, :, l:].reshape(b, self.num_heads, f, n, -1) + cross = F.scaled_dot_product_attention(qf.reshape(b*f,self.num_heads,n,-1), kr.reshape(b*f,self.num_heads,n,-1), vr.reshape(b*f,self.num_heads,n,-1)).reshape(b,self.num_heads,l,-1) + ref = torch.zeros_like(qh[:, :, l:]) + return rearrange(torch.cat([latent + cross, ref], dim=2), "b n s d -> b s (n d)", n=self.num_heads) + if isinstance(attn_mask, TokenPrefixAttentionSpec): + q = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads) + k = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads) + v = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads) + prefix = int(attn_mask.prefix_token_count) + total = int(attn_mask.total_token_count) + if q.shape[2] != total or k.shape[2] != total or v.shape[2] != total: + raise ValueError( + "Token-prefix attention spec does not match q/k/v sequence length: " + f"spec={total}, q={q.shape[2]}, k={k.shape[2]}, v={v.shape[2]}" + ) + # The explicit mask has all-false prefix query rows. Their SDPA + # output is zero, while target queries attend to every key. + target_output = F.scaled_dot_product_attention( + q[:, :, prefix:, :], k, v + ) + prefix_output = torch.zeros_like(q[:, :, :prefix, :]) + x = torch.cat([prefix_output, target_output], dim=2) + return rearrange(x, "b n s d -> b s (n d)", n=self.num_heads) + if attn_mask is not None: + q = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads) + k = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads) + v = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads) + if attn_mask.dtype != torch.bool: + attn_mask = attn_mask.to(device=q.device, dtype=q.dtype) + else: + attn_mask = attn_mask.to(device=q.device) + x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + return rearrange(x, "b n s d -> b s (n d)", n=self.num_heads) + x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads) + return x + + +class SelfAttention(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, freqs, attn_mask=None): + 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, attn_mask=attn_mask) + return self.o(x) + + +class CrossAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, eps: float = 1e-6, has_image_input: bool = False): + 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 GateModule(nn.Module): + def __init__(self,): + super().__init__() + + def forward(self, x, gate, residual): + return x + gate * residual + +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.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, context, t_mod, freqs, attn_mask=None): + 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), + ) + input_x = modulate(self.norm1(x), shift_msa, scale_msa) + x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, attn_mask=attn_mask)) + x = x + self.cross_attn(self.norm3(x), context) + input_x = modulate(self.norm2(x), shift_mlp, scale_mlp) + x = self.gate(x, gate_mlp, self.ffn(input_x)) + return x + + +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) + ) + 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) + + +class Head(nn.Module): + def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float): + 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: + 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)) + return x + + +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) + self.text_embedding = nn.Sequential( + nn.Linear(text_dim, dim), + nn.GELU(approximate='tanh'), + nn.Linear(dim, dim) + ) + self.time_embedding = nn.Sequential( + nn.Linear(freq_dim, dim), + nn.SiLU(), + nn.Linear(dim, 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) + self._freqs_device_cache = {} + + 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 get_rope_freqs(self, device: torch.device | str): + device = torch.device(device) + key = str(device) + if key not in self._freqs_device_cache: + self._freqs_device_cache[key] = tuple(freq.to(device=device, dtype=torch.complex64) for freq in self.freqs) + return self._freqs_device_cache[key] + + 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) + return x + + def unpatchify(self, x: torch.Tensor, grid_size: 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] + ) + + def forward(self, + x: torch.Tensor, + timestep: torch.Tensor, + context: torch.Tensor, + clip_feature: Optional[torch.Tensor] = None, + y: Optional[torch.Tensor] = None, + use_gradient_checkpointing: bool = False, + use_gradient_checkpointing_offload: bool = False, + attn_mask: Optional[torch.Tensor] = None, + **kwargs, + ): + t = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, timestep)) + t_mod = self.time_projection(t).unflatten(1, (6, self.dim)) + context = self.text_embedding(context) + + 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) + + rope_freqs = self.get_rope_freqs(x.device) + freqs = torch.cat([ + rope_freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1), + rope_freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1), + rope_freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1) + ], dim=-1).reshape(f * h * w, 1, -1).to(device=x.device, dtype=torch.complex64) + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + for block in self.blocks: + if self.training and use_gradient_checkpointing: + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + else: + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, freqs, attn_mask=attn_mask) + + x = self.head(x, t) + x = self.unpatchify(x, (f, h, w)) + 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")} + state_dict = {name: param for name, param in state_dict.items() if name.split(".")[0] not in ["pose_patch_embedding", "face_adapter", "face_encoder", "motion_encoder"]} + 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) == "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 diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_dit_s2v.py b/releases/2026-10-20-code/diffsynth/models/wan_video_dit_s2v.py new file mode 100644 index 0000000000000000000000000000000000000000..70881e6da3c1bcc13e97dc1aeddcbfbf1f691486 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_dit_s2v.py @@ -0,0 +1,625 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Tuple +from .utils import hash_state_dict_keys +from .wan_video_dit import rearrange, precompute_freqs_cis_3d, DiTBlock, Head, CrossAttention, modulate, sinusoidal_embedding_1d + + +def torch_dfs(model: nn.Module, parent_name='root'): + module_names, modules = [], [] + current_name = parent_name if parent_name else 'root' + module_names.append(current_name) + modules.append(model) + + for name, child in model.named_children(): + if parent_name: + child_name = f'{parent_name}.{name}' + else: + child_name = name + child_modules, child_names = torch_dfs(child, child_name) + module_names += child_names + modules += child_modules + return modules, module_names + + +def rope_precompute(x, grid_sizes, freqs, start=None): + b, s, n, c = x.size(0), x.size(1), x.size(2), x.size(3) // 2 + + # split freqs + if type(freqs) is list: + trainable_freqs = freqs[1] + freqs = freqs[0] + freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1) + + # loop over samples + output = torch.view_as_complex(x.detach().reshape(b, s, n, -1, 2).to(torch.float64)) + seq_bucket = [0] + if not type(grid_sizes) is list: + grid_sizes = [grid_sizes] + for g in grid_sizes: + if not type(g) is list: + g = [torch.zeros_like(g), g] + batch_size = g[0].shape[0] + for i in range(batch_size): + if start is None: + f_o, h_o, w_o = g[0][i] + else: + f_o, h_o, w_o = start[i] + + f, h, w = g[1][i] + t_f, t_h, t_w = g[2][i] + seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o + seq_len = int(seq_f * seq_h * seq_w) + if seq_len > 0: + if t_f > 0: + factor_f, factor_h, factor_w = (t_f / seq_f).item(), (t_h / seq_h).item(), (t_w / seq_w).item() + # Generate a list of seq_f integers starting from f_o and ending at math.ceil(factor_f * seq_f.item() + f_o.item()) + if f_o >= 0: + f_sam = np.linspace(f_o.item(), (t_f + f_o).item() - 1, seq_f).astype(int).tolist() + else: + f_sam = np.linspace(-f_o.item(), (-t_f - f_o).item() + 1, seq_f).astype(int).tolist() + h_sam = np.linspace(h_o.item(), (t_h + h_o).item() - 1, seq_h).astype(int).tolist() + w_sam = np.linspace(w_o.item(), (t_w + w_o).item() - 1, seq_w).astype(int).tolist() + + assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0 + freqs_0 = freqs[0][f_sam] if f_o >= 0 else freqs[0][f_sam].conj() + freqs_0 = freqs_0.view(seq_f, 1, 1, -1) + + freqs_i = torch.cat( + [ + freqs_0.expand(seq_f, seq_h, seq_w, -1), + freqs[1][h_sam].view(1, seq_h, 1, -1).expand(seq_f, seq_h, seq_w, -1), + freqs[2][w_sam].view(1, 1, seq_w, -1).expand(seq_f, seq_h, seq_w, -1), + ], + dim=-1 + ).reshape(seq_len, 1, -1) + elif t_f < 0: + freqs_i = trainable_freqs.unsqueeze(1) + # apply rotary embedding + output[i, seq_bucket[-1]:seq_bucket[-1] + seq_len] = freqs_i + seq_bucket.append(seq_bucket[-1] + seq_len) + return output + + +class CausalConv1d(nn.Module): + + def __init__(self, chan_in, chan_out, kernel_size=3, stride=1, dilation=1, pad_mode='replicate', **kwargs): + super().__init__() + + self.pad_mode = pad_mode + padding = (kernel_size - 1, 0) # T + self.time_causal_padding = padding + + self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs) + + def forward(self, x): + x = F.pad(x, self.time_causal_padding, mode=self.pad_mode) + return self.conv(x) + + +class MotionEncoder_tc(nn.Module): + + def __init__(self, in_dim: int, hidden_dim: int, num_heads=int, need_global=True, dtype=None, device=None): + factory_kwargs = {"dtype": dtype, "device": device} + super().__init__() + + self.num_heads = num_heads + self.need_global = need_global + self.conv1_local = CausalConv1d(in_dim, hidden_dim // 4 * num_heads, 3, stride=1) + if need_global: + self.conv1_global = CausalConv1d(in_dim, hidden_dim // 4, 3, stride=1) + self.norm1 = nn.LayerNorm(hidden_dim // 4, elementwise_affine=False, eps=1e-6, **factory_kwargs) + self.act = nn.SiLU() + self.conv2 = CausalConv1d(hidden_dim // 4, hidden_dim // 2, 3, stride=2) + self.conv3 = CausalConv1d(hidden_dim // 2, hidden_dim, 3, stride=2) + + if need_global: + self.final_linear = nn.Linear(hidden_dim, hidden_dim, **factory_kwargs) + + self.norm1 = nn.LayerNorm(hidden_dim // 4, elementwise_affine=False, eps=1e-6, **factory_kwargs) + self.norm2 = nn.LayerNorm(hidden_dim // 2, elementwise_affine=False, eps=1e-6, **factory_kwargs) + self.norm3 = nn.LayerNorm(hidden_dim, elementwise_affine=False, eps=1e-6, **factory_kwargs) + self.padding_tokens = nn.Parameter(torch.zeros(1, 1, 1, hidden_dim)) + + def forward(self, x): + x = rearrange(x, 'b t c -> b c t') + x_ori = x.clone() + b, c, t = x.shape + x = self.conv1_local(x) + x = rearrange(x, 'b (n c) t -> (b n) t c', n=self.num_heads) + x = self.norm1(x) + x = self.act(x) + x = rearrange(x, 'b t c -> b c t') + x = self.conv2(x) + x = rearrange(x, 'b c t -> b t c') + x = self.norm2(x) + x = self.act(x) + x = rearrange(x, 'b t c -> b c t') + x = self.conv3(x) + x = rearrange(x, 'b c t -> b t c') + x = self.norm3(x) + x = self.act(x) + x = rearrange(x, '(b n) t c -> b t n c', b=b) + padding = self.padding_tokens.repeat(b, x.shape[1], 1, 1).to(device=x.device, dtype=x.dtype) + x = torch.cat([x, padding], dim=-2) + x_local = x.clone() + + if not self.need_global: + return x_local + + x = self.conv1_global(x_ori) + x = rearrange(x, 'b c t -> b t c') + x = self.norm1(x) + x = self.act(x) + x = rearrange(x, 'b t c -> b c t') + x = self.conv2(x) + x = rearrange(x, 'b c t -> b t c') + x = self.norm2(x) + x = self.act(x) + x = rearrange(x, 'b t c -> b c t') + x = self.conv3(x) + x = rearrange(x, 'b c t -> b t c') + x = self.norm3(x) + x = self.act(x) + x = self.final_linear(x) + x = rearrange(x, '(b n) t c -> b t n c', b=b) + + return x, x_local + + +class FramePackMotioner(nn.Module): + + def __init__(self, inner_dim=1024, num_heads=16, zip_frame_buckets=[1, 2, 16], drop_mode="drop", *args, **kwargs): + super().__init__(*args, **kwargs) + self.proj = nn.Conv3d(16, inner_dim, kernel_size=(1, 2, 2), stride=(1, 2, 2)) + self.proj_2x = nn.Conv3d(16, inner_dim, kernel_size=(2, 4, 4), stride=(2, 4, 4)) + self.proj_4x = nn.Conv3d(16, inner_dim, kernel_size=(4, 8, 8), stride=(4, 8, 8)) + self.zip_frame_buckets = torch.tensor(zip_frame_buckets, dtype=torch.long) + + self.inner_dim = inner_dim + self.num_heads = num_heads + self.freqs = torch.cat(precompute_freqs_cis_3d(inner_dim // num_heads), dim=1) + self.drop_mode = drop_mode + + def forward(self, motion_latents, add_last_motion=2): + motion_frames = motion_latents[0].shape[1] + mot = [] + mot_remb = [] + for m in motion_latents: + lat_height, lat_width = m.shape[2], m.shape[3] + padd_lat = torch.zeros(16, self.zip_frame_buckets.sum(), lat_height, lat_width).to(device=m.device, dtype=m.dtype) + overlap_frame = min(padd_lat.shape[1], m.shape[1]) + if overlap_frame > 0: + padd_lat[:, -overlap_frame:] = m[:, -overlap_frame:] + + if add_last_motion < 2 and self.drop_mode != "drop": + zero_end_frame = self.zip_frame_buckets[:self.zip_frame_buckets.__len__() - add_last_motion - 1].sum() + padd_lat[:, -zero_end_frame:] = 0 + + padd_lat = padd_lat.unsqueeze(0) + clean_latents_4x, clean_latents_2x, clean_latents_post = padd_lat[:, :, -self.zip_frame_buckets.sum():, :, :].split( + list(self.zip_frame_buckets)[::-1], dim=2 + ) # 16, 2 ,1 + + # patchfy + clean_latents_post = self.proj(clean_latents_post).flatten(2).transpose(1, 2) + clean_latents_2x = self.proj_2x(clean_latents_2x).flatten(2).transpose(1, 2) + clean_latents_4x = self.proj_4x(clean_latents_4x).flatten(2).transpose(1, 2) + + if add_last_motion < 2 and self.drop_mode == "drop": + clean_latents_post = clean_latents_post[:, :0] if add_last_motion < 2 else clean_latents_post + clean_latents_2x = clean_latents_2x[:, :0] if add_last_motion < 1 else clean_latents_2x + + motion_lat = torch.cat([clean_latents_post, clean_latents_2x, clean_latents_4x], dim=1) + + # rope + start_time_id = -(self.zip_frame_buckets[:1].sum()) + end_time_id = start_time_id + self.zip_frame_buckets[0] + grid_sizes = [] if add_last_motion < 2 and self.drop_mode == "drop" else \ + [ + [torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1), + torch.tensor([end_time_id, lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), + torch.tensor([self.zip_frame_buckets[0], lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), ] + ] + + start_time_id = -(self.zip_frame_buckets[:2].sum()) + end_time_id = start_time_id + self.zip_frame_buckets[1] // 2 + grid_sizes_2x = [] if add_last_motion < 1 and self.drop_mode == "drop" else \ + [ + [torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1), + torch.tensor([end_time_id, lat_height // 4, lat_width // 4]).unsqueeze(0).repeat(1, 1), + torch.tensor([self.zip_frame_buckets[1], lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), ] + ] + + start_time_id = -(self.zip_frame_buckets[:3].sum()) + end_time_id = start_time_id + self.zip_frame_buckets[2] // 4 + grid_sizes_4x = [ + [ + torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1), + torch.tensor([end_time_id, lat_height // 8, lat_width // 8]).unsqueeze(0).repeat(1, 1), + torch.tensor([self.zip_frame_buckets[2], lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), + ] + ] + + grid_sizes = grid_sizes + grid_sizes_2x + grid_sizes_4x + + motion_rope_emb = rope_precompute( + motion_lat.detach().view(1, motion_lat.shape[1], self.num_heads, self.inner_dim // self.num_heads), + grid_sizes, + self.freqs, + start=None + ) + + mot.append(motion_lat) + mot_remb.append(motion_rope_emb) + return mot, mot_remb + + +class AdaLayerNorm(nn.Module): + + def __init__( + self, + embedding_dim: int, + output_dim: int, + norm_eps: float = 1e-5, + ): + super().__init__() + self.silu = nn.SiLU() + self.linear = nn.Linear(embedding_dim, output_dim) + self.norm = nn.LayerNorm(output_dim // 2, norm_eps, elementwise_affine=False) + + def forward(self, x, temb): + temb = self.linear(F.silu(temb)) + shift, scale = temb.chunk(2, dim=1) + shift = shift[:, None, :] + scale = scale[:, None, :] + x = self.norm(x) * (1 + scale) + shift + return x + + +class AudioInjector_WAN(nn.Module): + + def __init__( + self, + all_modules, + all_modules_names, + dim=2048, + num_heads=32, + inject_layer=[0, 27], + enable_adain=False, + adain_dim=2048, + ): + super().__init__() + self.injected_block_id = {} + audio_injector_id = 0 + for mod_name, mod in zip(all_modules_names, all_modules): + if isinstance(mod, DiTBlock): + for inject_id in inject_layer: + if f'transformer_blocks.{inject_id}' in mod_name: + self.injected_block_id[inject_id] = audio_injector_id + audio_injector_id += 1 + + self.injector = nn.ModuleList([CrossAttention( + dim=dim, + num_heads=num_heads, + ) for _ in range(audio_injector_id)]) + self.injector_pre_norm_feat = nn.ModuleList([nn.LayerNorm( + dim, + elementwise_affine=False, + eps=1e-6, + ) for _ in range(audio_injector_id)]) + self.injector_pre_norm_vec = nn.ModuleList([nn.LayerNorm( + dim, + elementwise_affine=False, + eps=1e-6, + ) for _ in range(audio_injector_id)]) + if enable_adain: + self.injector_adain_layers = nn.ModuleList([AdaLayerNorm(output_dim=dim * 2, embedding_dim=adain_dim) for _ in range(audio_injector_id)]) + + +class CausalAudioEncoder(nn.Module): + + def __init__(self, dim=5120, num_layers=25, out_dim=2048, num_token=4, need_global=False): + super().__init__() + self.encoder = MotionEncoder_tc(in_dim=dim, hidden_dim=out_dim, num_heads=num_token, need_global=need_global) + weight = torch.ones((1, num_layers, 1, 1)) * 0.01 + + self.weights = torch.nn.Parameter(weight) + self.act = torch.nn.SiLU() + + def forward(self, features): + # features B * num_layers * dim * video_length + weights = self.act(self.weights.to(device=features.device, dtype=features.dtype)) + weights_sum = weights.sum(dim=1, keepdims=True) + weighted_feat = ((features * weights) / weights_sum).sum(dim=1) # b dim f + weighted_feat = weighted_feat.permute(0, 2, 1) # b f dim + res = self.encoder(weighted_feat) # b f n dim + return res # b f n dim + + +class WanS2VDiTBlock(DiTBlock): + + def forward(self, x, context, t_mod, seq_len_x, freqs): + t_mod = (self.modulation.unsqueeze(2).to(dtype=t_mod.dtype, device=t_mod.device) + t_mod).chunk(6, dim=1) + # t_mod[:, :, 0] for x, t_mod[:, :, 1] for other like ref, motion, etc. + t_mod = [ + torch.cat([element[:, :, 0].expand(1, seq_len_x, x.shape[-1]), element[:, :, 1].expand(1, x.shape[1] - seq_len_x, x.shape[-1])], dim=1) + for element in t_mod + ] + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = t_mod + input_x = modulate(self.norm1(x), shift_msa, scale_msa) + x = self.gate(x, gate_msa, self.self_attn(input_x, freqs)) + x = x + self.cross_attn(self.norm3(x), context) + input_x = modulate(self.norm2(x), shift_mlp, scale_mlp) + x = self.gate(x, gate_mlp, self.ffn(input_x)) + return x + + +class WanS2VModel(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, + cond_dim: int, + audio_dim: int, + num_audio_token: int, + enable_adain: bool = True, + audio_inject_layers: list = [0, 4, 8, 12, 16, 20, 24, 27, 30, 33, 36, 39], + zero_timestep: bool = True, + add_last_motion: bool = True, + framepack_drop_mode: str = "padd", + fuse_vae_embedding_in_latents: bool = True, + require_vae_embedding: bool = False, + seperated_timestep: bool = False, + require_clip_embedding: bool = False, + ): + super().__init__() + self.dim = dim + self.in_dim = in_dim + self.freq_dim = freq_dim + self.patch_size = patch_size + self.num_heads = num_heads + self.enbale_adain = enable_adain + self.add_last_motion = add_last_motion + self.zero_timestep = zero_timestep + self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents + self.require_vae_embedding = require_vae_embedding + self.seperated_timestep = seperated_timestep + self.require_clip_embedding = require_clip_embedding + + self.patch_embedding = nn.Conv3d(in_dim, 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)) + self.time_embedding = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) + self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6)) + + self.blocks = nn.ModuleList([WanS2VDiTBlock(False, dim, num_heads, ffn_dim, eps) for _ in range(num_layers)]) + self.head = Head(dim, out_dim, patch_size, eps) + self.freqs = torch.cat(precompute_freqs_cis_3d(dim // num_heads), dim=1) + + self.cond_encoder = nn.Conv3d(cond_dim, dim, kernel_size=patch_size, stride=patch_size) + self.casual_audio_encoder = CausalAudioEncoder(dim=audio_dim, out_dim=dim, num_token=num_audio_token, need_global=enable_adain) + all_modules, all_modules_names = torch_dfs(self.blocks, parent_name="root.transformer_blocks") + self.audio_injector = AudioInjector_WAN( + all_modules, + all_modules_names, + dim=dim, + num_heads=num_heads, + inject_layer=audio_inject_layers, + enable_adain=enable_adain, + adain_dim=dim, + ) + self.trainable_cond_mask = nn.Embedding(3, dim) + self.frame_packer = FramePackMotioner(inner_dim=dim, num_heads=num_heads, zip_frame_buckets=[1, 2, 16], drop_mode=framepack_drop_mode) + + def patchify(self, x: torch.Tensor): + 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): + 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] + ) + + def process_motion_frame_pack(self, motion_latents, drop_motion_frames=False, add_last_motion=2): + flattern_mot, mot_remb = self.frame_packer(motion_latents, add_last_motion) + if drop_motion_frames: + return [m[:, :0] for m in flattern_mot], [m[:, :0] for m in mot_remb] + else: + return flattern_mot, mot_remb + + def inject_motion(self, x, rope_embs, mask_input, motion_latents, drop_motion_frames=True, add_last_motion=2): + # inject the motion frames token to the hidden states + mot, mot_remb = self.process_motion_frame_pack(motion_latents, drop_motion_frames=drop_motion_frames, add_last_motion=add_last_motion) + if len(mot) > 0: + x = torch.cat([x, mot[0]], dim=1) + rope_embs = torch.cat([rope_embs, mot_remb[0]], dim=1) + mask_input = torch.cat( + [mask_input, 2 * torch.ones([1, x.shape[1] - mask_input.shape[1]], device=mask_input.device, dtype=mask_input.dtype)], dim=1 + ) + return x, rope_embs, mask_input + + def after_transformer_block(self, block_idx, hidden_states, audio_emb_global, audio_emb, original_seq_len, use_unified_sequence_parallel=False): + if block_idx in self.audio_injector.injected_block_id.keys(): + audio_attn_id = self.audio_injector.injected_block_id[block_idx] + num_frames = audio_emb.shape[1] + if use_unified_sequence_parallel: + from xfuser.core.distributed import get_sp_group + hidden_states = get_sp_group().all_gather(hidden_states, dim=1) + + input_hidden_states = hidden_states[:, :original_seq_len].clone() # b (f h w) c + input_hidden_states = rearrange(input_hidden_states, "b (t n) c -> (b t) n c", t=num_frames) + + audio_emb_global = rearrange(audio_emb_global, "b t n c -> (b t) n c") + adain_hidden_states = self.audio_injector.injector_adain_layers[audio_attn_id](input_hidden_states, temb=audio_emb_global[:, 0]) + attn_hidden_states = adain_hidden_states + + audio_emb = rearrange(audio_emb, "b t n c -> (b t) n c", t=num_frames) + attn_audio_emb = audio_emb + residual_out = self.audio_injector.injector[audio_attn_id](attn_hidden_states, attn_audio_emb) + residual_out = rearrange(residual_out, "(b t) n c -> b (t n) c", t=num_frames) + hidden_states[:, :original_seq_len] = hidden_states[:, :original_seq_len] + residual_out + if use_unified_sequence_parallel: + from xfuser.core.distributed import get_sequence_parallel_world_size, get_sequence_parallel_rank + hidden_states = torch.chunk(hidden_states, get_sequence_parallel_world_size(), dim=1)[get_sequence_parallel_rank()] + return hidden_states + + def cal_audio_emb(self, audio_input, motion_frames=[73, 19]): + audio_input = torch.cat([audio_input[..., 0:1].repeat(1, 1, 1, motion_frames[0]), audio_input], dim=-1) + audio_emb_global, audio_emb = self.casual_audio_encoder(audio_input) + audio_emb_global = audio_emb_global[:, motion_frames[1]:].clone() + merged_audio_emb = audio_emb[:, motion_frames[1]:, :] + return audio_emb_global, merged_audio_emb + + def get_grid_sizes(self, grid_size_x, grid_size_ref): + f, h, w = grid_size_x + rf, rh, rw = grid_size_ref + grid_sizes_x = torch.tensor([f, h, w], dtype=torch.long).unsqueeze(0) + grid_sizes_x = [[torch.zeros_like(grid_sizes_x), grid_sizes_x, grid_sizes_x]] + grid_sizes_ref = [[ + torch.tensor([30, 0, 0]).unsqueeze(0), + torch.tensor([31, rh, rw]).unsqueeze(0), + torch.tensor([1, rh, rw]).unsqueeze(0), + ]] + return grid_sizes_x + grid_sizes_ref + + def forward( + self, + latents, + timestep, + context, + audio_input, + motion_latents, + pose_cond, + use_gradient_checkpointing_offload=False, + use_gradient_checkpointing=False + ): + origin_ref_latents = latents[:, :, 0:1] + x = latents[:, :, 1:] + + # context embedding + context = self.text_embedding(context) + + # audio encode + audio_emb_global, merged_audio_emb = self.cal_audio_emb(audio_input) + + # x and pose_cond + pose_cond = torch.zeros_like(x) if pose_cond is None else pose_cond + x, (f, h, w) = self.patchify(self.patch_embedding(x) + self.cond_encoder(pose_cond)) # torch.Size([1, 29120, 5120]) + seq_len_x = x.shape[1] + + # reference image + ref_latents, (rf, rh, rw) = self.patchify(self.patch_embedding(origin_ref_latents)) # torch.Size([1, 1456, 5120]) + grid_sizes = self.get_grid_sizes((f, h, w), (rf, rh, rw)) + x = torch.cat([x, ref_latents], dim=1) + # mask + mask = torch.cat([torch.zeros([1, seq_len_x]), torch.ones([1, ref_latents.shape[1]])], dim=1).to(torch.long).to(x.device) + # freqs + pre_compute_freqs = rope_precompute( + x.detach().view(1, x.size(1), self.num_heads, self.dim // self.num_heads), grid_sizes, self.freqs, start=None + ) + # motion + x, pre_compute_freqs, mask = self.inject_motion(x, pre_compute_freqs, mask, motion_latents, add_last_motion=2) + + x = x + self.trainable_cond_mask(mask).to(x.dtype) + + # t_mod + timestep = torch.cat([timestep, torch.zeros([1], dtype=timestep.dtype, device=timestep.device)]) + t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep)) + t_mod = self.time_projection(t).unflatten(1, (6, self.dim)).unsqueeze(2).transpose(0, 2) + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + for block_id, block in enumerate(self.blocks): + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, + context, + t_mod, + seq_len_x, + pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: self.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, + context, + t_mod, + seq_len_x, + pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: self.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, seq_len_x, pre_compute_freqs[0]) + x = self.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x) + + x = x[:, :seq_len_x] + x = self.head(x, t[:-1]) + x = self.unpatchify(x, (f, h, w)) + # make compatible with wan video + x = torch.cat([origin_ref_latents, x], dim=2) + return x + + @staticmethod + def state_dict_converter(): + return WanS2VModelStateDictConverter() + + +class WanS2VModelStateDictConverter: + + def __init__(self): + pass + + def from_civitai(self, state_dict): + config = {} + if hash_state_dict_keys(state_dict) == "966cffdcc52f9c46c391768b27637614": + config = { + "dim": 5120, + "in_dim": 16, + "ffn_dim": 13824, + "out_dim": 16, + "text_dim": 4096, + "freq_dim": 256, + "eps": 1e-06, + "patch_size": (1, 2, 2), + "num_heads": 40, + "num_layers": 40, + "cond_dim": 16, + "audio_dim": 1024, + "num_audio_token": 4, + } + return state_dict, config diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_image_encoder.py b/releases/2026-10-20-code/diffsynth/models/wan_video_image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca878b1fd6ed6dc00420f092f87479fb65ef63a --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_image_encoder.py @@ -0,0 +1,902 @@ +""" +Concise re-implementation of +``https://github.com/openai/CLIP'' and +``https://github.com/mlfoundations/open_clip''. +""" +import math +import torch +import torch.nn as nn +import torch.nn.functional as F +import torchvision.transforms as T +from .wan_video_dit import flash_attention + + +class SelfAttention(nn.Module): + + def __init__(self, dim, num_heads, dropout=0.1, eps=1e-5): + assert dim % num_heads == 0 + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.eps = eps + + # layers + 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.dropout = nn.Dropout(dropout) + + def forward(self, x, mask): + """ + x: [B, L, C]. + """ + b, s, c, n, d = *x.size(), self.num_heads, self.head_dim + + # compute query, key, value + q = self.q(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + k = self.k(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + v = self.v(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + + # compute attention + p = self.dropout.p if self.training else 0.0 + x = F.scaled_dot_product_attention(q, k, v, mask, p) + x = x.permute(0, 2, 1, 3).reshape(b, s, c) + + # output + x = self.o(x) + x = self.dropout(x) + return x + + +class AttentionBlock(nn.Module): + + def __init__(self, dim, num_heads, post_norm, dropout=0.1, eps=1e-5): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.post_norm = post_norm + self.eps = eps + + # layers + self.attn = SelfAttention(dim, num_heads, dropout, eps) + self.norm1 = nn.LayerNorm(dim, eps=eps) + self.ffn = nn.Sequential( + nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim), + nn.Dropout(dropout)) + self.norm2 = nn.LayerNorm(dim, eps=eps) + + def forward(self, x, mask): + if self.post_norm: + x = self.norm1(x + self.attn(x, mask)) + x = self.norm2(x + self.ffn(x)) + else: + x = x + self.attn(self.norm1(x), mask) + x = x + self.ffn(self.norm2(x)) + return x + + +class XLMRoberta(nn.Module): + """ + XLMRobertaModel with no pooler and no LM head. + """ + + def __init__(self, + vocab_size=250002, + max_seq_len=514, + type_size=1, + pad_id=1, + dim=1024, + num_heads=16, + num_layers=24, + post_norm=True, + dropout=0.1, + eps=1e-5): + super().__init__() + self.vocab_size = vocab_size + self.max_seq_len = max_seq_len + self.type_size = type_size + self.pad_id = pad_id + self.dim = dim + self.num_heads = num_heads + self.num_layers = num_layers + self.post_norm = post_norm + self.eps = eps + + # embeddings + self.token_embedding = nn.Embedding(vocab_size, dim, padding_idx=pad_id) + self.type_embedding = nn.Embedding(type_size, dim) + self.pos_embedding = nn.Embedding(max_seq_len, dim, padding_idx=pad_id) + self.dropout = nn.Dropout(dropout) + + # blocks + self.blocks = nn.ModuleList([ + AttentionBlock(dim, num_heads, post_norm, dropout, eps) + for _ in range(num_layers) + ]) + + # norm layer + self.norm = nn.LayerNorm(dim, eps=eps) + + def forward(self, ids): + """ + ids: [B, L] of torch.LongTensor. + """ + b, s = ids.shape + mask = ids.ne(self.pad_id).long() + + # embeddings + x = self.token_embedding(ids) + \ + self.type_embedding(torch.zeros_like(ids)) + \ + self.pos_embedding(self.pad_id + torch.cumsum(mask, dim=1) * mask) + if self.post_norm: + x = self.norm(x) + x = self.dropout(x) + + # blocks + mask = torch.where( + mask.view(b, 1, 1, s).gt(0), 0.0, + torch.finfo(x.dtype).min) + for block in self.blocks: + x = block(x, mask) + + # output + if not self.post_norm: + x = self.norm(x) + return x + + +def xlm_roberta_large(pretrained=False, + return_tokenizer=False, + device='cpu', + **kwargs): + """ + XLMRobertaLarge adapted from Huggingface. + """ + # params + cfg = dict( + vocab_size=250002, + max_seq_len=514, + type_size=1, + pad_id=1, + dim=1024, + num_heads=16, + num_layers=24, + post_norm=True, + dropout=0.1, + eps=1e-5) + cfg.update(**kwargs) + + # init model + if pretrained: + from sora import DOWNLOAD_TO_CACHE + + # init a meta model + with torch.device('meta'): + model = XLMRoberta(**cfg) + + # load checkpoint + model.load_state_dict( + torch.load( + DOWNLOAD_TO_CACHE('models/xlm_roberta/xlm_roberta_large.pth'), + map_location=device), + assign=True) + else: + # init a model on device + with torch.device(device): + model = XLMRoberta(**cfg) + + # init tokenizer + if return_tokenizer: + from sora.data import HuggingfaceTokenizer + tokenizer = HuggingfaceTokenizer( + name='xlm-roberta-large', + seq_len=model.text_len, + clean='whitespace') + return model, tokenizer + else: + return model + + + +def pos_interpolate(pos, seq_len): + if pos.size(1) == seq_len: + return pos + else: + src_grid = int(math.sqrt(pos.size(1))) + tar_grid = int(math.sqrt(seq_len)) + n = pos.size(1) - src_grid * src_grid + return torch.cat([ + pos[:, :n], + F.interpolate( + pos[:, n:].float().reshape(1, src_grid, src_grid, -1).permute( + 0, 3, 1, 2), + size=(tar_grid, tar_grid), + mode='bicubic', + align_corners=False).flatten(2).transpose(1, 2) + ], + dim=1) + + +class QuickGELU(nn.Module): + + def forward(self, x): + return x * torch.sigmoid(1.702 * x) + + +class LayerNorm(nn.LayerNorm): + + def forward(self, x): + return super().forward(x).type_as(x) + + +class SelfAttention(nn.Module): + + def __init__(self, + dim, + num_heads, + causal=False, + attn_dropout=0.0, + proj_dropout=0.0): + assert dim % num_heads == 0 + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.causal = causal + self.attn_dropout = attn_dropout + self.proj_dropout = proj_dropout + + # layers + self.to_qkv = nn.Linear(dim, dim * 3) + self.proj = nn.Linear(dim, dim) + + def forward(self, x): + """ + x: [B, L, C]. + """ + # compute query, key, value + q, k, v = self.to_qkv(x).chunk(3, dim=-1) + + # compute attention + x = flash_attention(q, k, v, num_heads=self.num_heads, compatibility_mode=True) + + # output + x = self.proj(x) + x = F.dropout(x, self.proj_dropout, self.training) + return x + + +class SwiGLU(nn.Module): + + def __init__(self, dim, mid_dim): + super().__init__() + self.dim = dim + self.mid_dim = mid_dim + + # layers + self.fc1 = nn.Linear(dim, mid_dim) + self.fc2 = nn.Linear(dim, mid_dim) + self.fc3 = nn.Linear(mid_dim, dim) + + def forward(self, x): + x = F.silu(self.fc1(x)) * self.fc2(x) + x = self.fc3(x) + return x + + +class AttentionBlock(nn.Module): + + def __init__(self, + dim, + mlp_ratio, + num_heads, + post_norm=False, + causal=False, + activation='quick_gelu', + attn_dropout=0.0, + proj_dropout=0.0, + norm_eps=1e-5): + assert activation in ['quick_gelu', 'gelu', 'swi_glu'] + super().__init__() + self.dim = dim + self.mlp_ratio = mlp_ratio + self.num_heads = num_heads + self.post_norm = post_norm + self.causal = causal + self.norm_eps = norm_eps + + # layers + self.norm1 = LayerNorm(dim, eps=norm_eps) + self.attn = SelfAttention(dim, num_heads, causal, attn_dropout, + proj_dropout) + self.norm2 = LayerNorm(dim, eps=norm_eps) + if activation == 'swi_glu': + self.mlp = SwiGLU(dim, int(dim * mlp_ratio)) + else: + self.mlp = nn.Sequential( + nn.Linear(dim, int(dim * mlp_ratio)), + QuickGELU() if activation == 'quick_gelu' else nn.GELU(), + nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(proj_dropout)) + + def forward(self, x): + if self.post_norm: + x = x + self.norm1(self.attn(x)) + x = x + self.norm2(self.mlp(x)) + else: + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x + + +class AttentionPool(nn.Module): + + def __init__(self, + dim, + mlp_ratio, + num_heads, + activation='gelu', + proj_dropout=0.0, + norm_eps=1e-5): + assert dim % num_heads == 0 + super().__init__() + self.dim = dim + self.mlp_ratio = mlp_ratio + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.proj_dropout = proj_dropout + self.norm_eps = norm_eps + + # layers + gain = 1.0 / math.sqrt(dim) + self.cls_embedding = nn.Parameter(gain * torch.randn(1, 1, dim)) + self.to_q = nn.Linear(dim, dim) + self.to_kv = nn.Linear(dim, dim * 2) + self.proj = nn.Linear(dim, dim) + self.norm = LayerNorm(dim, eps=norm_eps) + self.mlp = nn.Sequential( + nn.Linear(dim, int(dim * mlp_ratio)), + QuickGELU() if activation == 'quick_gelu' else nn.GELU(), + nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(proj_dropout)) + + def forward(self, x): + """ + x: [B, L, C]. + """ + b, s, c, n, d = *x.size(), self.num_heads, self.head_dim + + # compute query, key, value + q = self.to_q(self.cls_embedding).view(1, 1, n*d).expand(b, -1, -1) + k, v = self.to_kv(x).chunk(2, dim=-1) + + # compute attention + x = flash_attention(q, k, v, num_heads=self.num_heads, compatibility_mode=True) + x = x.reshape(b, 1, c) + + # output + x = self.proj(x) + x = F.dropout(x, self.proj_dropout, self.training) + + # mlp + x = x + self.mlp(self.norm(x)) + return x[:, 0] + + +class VisionTransformer(nn.Module): + + def __init__(self, + image_size=224, + patch_size=16, + dim=768, + mlp_ratio=4, + out_dim=512, + num_heads=12, + num_layers=12, + pool_type='token', + pre_norm=True, + post_norm=False, + activation='quick_gelu', + attn_dropout=0.0, + proj_dropout=0.0, + embedding_dropout=0.0, + norm_eps=1e-5): + if image_size % patch_size != 0: + print( + '[WARNING] image_size is not divisible by patch_size', + flush=True) + assert pool_type in ('token', 'token_fc', 'attn_pool') + out_dim = out_dim or dim + super().__init__() + self.image_size = image_size + self.patch_size = patch_size + self.num_patches = (image_size // patch_size)**2 + self.dim = dim + self.mlp_ratio = mlp_ratio + self.out_dim = out_dim + self.num_heads = num_heads + self.num_layers = num_layers + self.pool_type = pool_type + self.post_norm = post_norm + self.norm_eps = norm_eps + + # embeddings + gain = 1.0 / math.sqrt(dim) + self.patch_embedding = nn.Conv2d( + 3, + dim, + kernel_size=patch_size, + stride=patch_size, + bias=not pre_norm) + if pool_type in ('token', 'token_fc'): + self.cls_embedding = nn.Parameter(gain * torch.randn(1, 1, dim)) + self.pos_embedding = nn.Parameter(gain * torch.randn( + 1, self.num_patches + + (1 if pool_type in ('token', 'token_fc') else 0), dim)) + self.dropout = nn.Dropout(embedding_dropout) + + # transformer + self.pre_norm = LayerNorm(dim, eps=norm_eps) if pre_norm else None + self.transformer = nn.Sequential(*[ + AttentionBlock(dim, mlp_ratio, num_heads, post_norm, False, + activation, attn_dropout, proj_dropout, norm_eps) + for _ in range(num_layers) + ]) + self.post_norm = LayerNorm(dim, eps=norm_eps) + + # head + if pool_type == 'token': + self.head = nn.Parameter(gain * torch.randn(dim, out_dim)) + elif pool_type == 'token_fc': + self.head = nn.Linear(dim, out_dim) + elif pool_type == 'attn_pool': + self.head = AttentionPool(dim, mlp_ratio, num_heads, activation, + proj_dropout, norm_eps) + + def forward(self, x, interpolation=False, use_31_block=False): + b = x.size(0) + + # embeddings + x = self.patch_embedding(x).flatten(2).permute(0, 2, 1) + if self.pool_type in ('token', 'token_fc'): + x = torch.cat([self.cls_embedding.expand(b, -1, -1).to(dtype=x.dtype, device=x.device), x], dim=1) + if interpolation: + e = pos_interpolate(self.pos_embedding, x.size(1)) + else: + e = self.pos_embedding + e = e.to(dtype=x.dtype, device=x.device) + x = self.dropout(x + e) + if self.pre_norm is not None: + x = self.pre_norm(x) + + # transformer + if use_31_block: + x = self.transformer[:-1](x) + return x + else: + x = self.transformer(x) + return x + + +class CLIP(nn.Module): + + def __init__(self, + embed_dim=512, + image_size=224, + patch_size=16, + vision_dim=768, + vision_mlp_ratio=4, + vision_heads=12, + vision_layers=12, + vision_pool='token', + vision_pre_norm=True, + vision_post_norm=False, + vocab_size=49408, + text_len=77, + text_dim=512, + text_mlp_ratio=4, + text_heads=8, + text_layers=12, + text_causal=True, + text_pool='argmax', + text_head_bias=False, + logit_bias=None, + activation='quick_gelu', + attn_dropout=0.0, + proj_dropout=0.0, + embedding_dropout=0.0, + norm_eps=1e-5): + super().__init__() + self.embed_dim = embed_dim + self.image_size = image_size + self.patch_size = patch_size + self.vision_dim = vision_dim + self.vision_mlp_ratio = vision_mlp_ratio + self.vision_heads = vision_heads + self.vision_layers = vision_layers + self.vision_pool = vision_pool + self.vision_pre_norm = vision_pre_norm + self.vision_post_norm = vision_post_norm + self.vocab_size = vocab_size + self.text_len = text_len + self.text_dim = text_dim + self.text_mlp_ratio = text_mlp_ratio + self.text_heads = text_heads + self.text_layers = text_layers + self.text_causal = text_causal + self.text_pool = text_pool + self.text_head_bias = text_head_bias + self.norm_eps = norm_eps + + # models + self.visual = VisionTransformer( + image_size=image_size, + patch_size=patch_size, + dim=vision_dim, + mlp_ratio=vision_mlp_ratio, + out_dim=embed_dim, + num_heads=vision_heads, + num_layers=vision_layers, + pool_type=vision_pool, + pre_norm=vision_pre_norm, + post_norm=vision_post_norm, + activation=activation, + attn_dropout=attn_dropout, + proj_dropout=proj_dropout, + embedding_dropout=embedding_dropout, + norm_eps=norm_eps) + self.textual = TextTransformer( + vocab_size=vocab_size, + text_len=text_len, + dim=text_dim, + mlp_ratio=text_mlp_ratio, + out_dim=embed_dim, + num_heads=text_heads, + num_layers=text_layers, + causal=text_causal, + pool_type=text_pool, + head_bias=text_head_bias, + activation=activation, + attn_dropout=attn_dropout, + proj_dropout=proj_dropout, + embedding_dropout=embedding_dropout, + norm_eps=norm_eps) + self.log_scale = nn.Parameter(math.log(1 / 0.07) * torch.ones([])) + if logit_bias is not None: + self.logit_bias = nn.Parameter(logit_bias * torch.ones([])) + + # initialize weights + self.init_weights() + + def forward(self, imgs, txt_ids): + """ + imgs: [B, 3, H, W] of torch.float32. + - mean: [0.48145466, 0.4578275, 0.40821073] + - std: [0.26862954, 0.26130258, 0.27577711] + txt_ids: [B, L] of torch.long. Encoded by data.CLIPTokenizer. + """ + xi = self.visual(imgs) + xt = self.textual(txt_ids) + return xi, xt + + def init_weights(self): + # embeddings + nn.init.normal_(self.textual.token_embedding.weight, std=0.02) + nn.init.normal_(self.visual.patch_embedding.weight, std=0.1) + + # attentions + for modality in ['visual', 'textual']: + dim = self.vision_dim if modality == 'visual' else self.text_dim + transformer = getattr(self, modality).transformer + proj_gain = (1.0 / math.sqrt(dim)) * ( + 1.0 / math.sqrt(2 * len(transformer))) + attn_gain = 1.0 / math.sqrt(dim) + mlp_gain = 1.0 / math.sqrt(2.0 * dim) + for block in transformer: + nn.init.normal_(block.attn.to_qkv.weight, std=attn_gain) + nn.init.normal_(block.attn.proj.weight, std=proj_gain) + nn.init.normal_(block.mlp[0].weight, std=mlp_gain) + nn.init.normal_(block.mlp[2].weight, std=proj_gain) + + def param_groups(self): + groups = [{ + 'params': [ + p for n, p in self.named_parameters() + if 'norm' in n or n.endswith('bias') + ], + 'weight_decay': 0.0 + }, { + 'params': [ + p for n, p in self.named_parameters() + if not ('norm' in n or n.endswith('bias')) + ] + }] + return groups + + +class XLMRobertaWithHead(XLMRoberta): + + def __init__(self, **kwargs): + self.out_dim = kwargs.pop('out_dim') + super().__init__(**kwargs) + + # head + mid_dim = (self.dim + self.out_dim) // 2 + self.head = nn.Sequential( + nn.Linear(self.dim, mid_dim, bias=False), nn.GELU(), + nn.Linear(mid_dim, self.out_dim, bias=False)) + + def forward(self, ids): + # xlm-roberta + x = super().forward(ids) + + # average pooling + mask = ids.ne(self.pad_id).unsqueeze(-1).to(x) + x = (x * mask).sum(dim=1) / mask.sum(dim=1) + + # head + x = self.head(x) + return x + + +class XLMRobertaCLIP(nn.Module): + + def __init__(self, + embed_dim=1024, + image_size=224, + patch_size=14, + vision_dim=1280, + vision_mlp_ratio=4, + vision_heads=16, + vision_layers=32, + vision_pool='token', + vision_pre_norm=True, + vision_post_norm=False, + activation='gelu', + vocab_size=250002, + max_text_len=514, + type_size=1, + pad_id=1, + text_dim=1024, + text_heads=16, + text_layers=24, + text_post_norm=True, + text_dropout=0.1, + attn_dropout=0.0, + proj_dropout=0.0, + embedding_dropout=0.0, + norm_eps=1e-5): + super().__init__() + self.embed_dim = embed_dim + self.image_size = image_size + self.patch_size = patch_size + self.vision_dim = vision_dim + self.vision_mlp_ratio = vision_mlp_ratio + self.vision_heads = vision_heads + self.vision_layers = vision_layers + self.vision_pre_norm = vision_pre_norm + self.vision_post_norm = vision_post_norm + self.activation = activation + self.vocab_size = vocab_size + self.max_text_len = max_text_len + self.type_size = type_size + self.pad_id = pad_id + self.text_dim = text_dim + self.text_heads = text_heads + self.text_layers = text_layers + self.text_post_norm = text_post_norm + self.norm_eps = norm_eps + + # models + self.visual = VisionTransformer( + image_size=image_size, + patch_size=patch_size, + dim=vision_dim, + mlp_ratio=vision_mlp_ratio, + out_dim=embed_dim, + num_heads=vision_heads, + num_layers=vision_layers, + pool_type=vision_pool, + pre_norm=vision_pre_norm, + post_norm=vision_post_norm, + activation=activation, + attn_dropout=attn_dropout, + proj_dropout=proj_dropout, + embedding_dropout=embedding_dropout, + norm_eps=norm_eps) + self.textual = None + self.log_scale = nn.Parameter(math.log(1 / 0.07) * torch.ones([])) + + def forward(self, imgs, txt_ids): + """ + imgs: [B, 3, H, W] of torch.float32. + - mean: [0.48145466, 0.4578275, 0.40821073] + - std: [0.26862954, 0.26130258, 0.27577711] + txt_ids: [B, L] of torch.long. + Encoded by data.CLIPTokenizer. + """ + xi = self.visual(imgs) + xt = self.textual(txt_ids) + return xi, xt + + def param_groups(self): + groups = [{ + 'params': [ + p for n, p in self.named_parameters() + if 'norm' in n or n.endswith('bias') + ], + 'weight_decay': 0.0 + }, { + 'params': [ + p for n, p in self.named_parameters() + if not ('norm' in n or n.endswith('bias')) + ] + }] + return groups + + +def _clip(pretrained=False, + pretrained_name=None, + model_cls=CLIP, + return_transforms=False, + return_tokenizer=False, + tokenizer_padding='eos', + dtype=torch.float32, + device='cpu', + **kwargs): + # init model + if pretrained and pretrained_name: + from sora import BUCKET, DOWNLOAD_TO_CACHE + + # init a meta model + with torch.device('meta'): + model = model_cls(**kwargs) + + # checkpoint path + checkpoint = f'models/clip/{pretrained_name}' + if dtype in (torch.float16, torch.bfloat16): + suffix = '-' + { + torch.float16: 'fp16', + torch.bfloat16: 'bf16' + }[dtype] + if object_exists(BUCKET, f'{checkpoint}{suffix}.pth'): + checkpoint = f'{checkpoint}{suffix}' + checkpoint += '.pth' + + # load + model.load_state_dict( + torch.load(DOWNLOAD_TO_CACHE(checkpoint), map_location=device), + assign=True, + strict=False) + else: + # init a model on device + with torch.device(device): + model = model_cls(**kwargs) + + # set device + output = (model,) + + # init transforms + if return_transforms: + # mean and std + if 'siglip' in pretrained_name.lower(): + mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5] + else: + mean = [0.48145466, 0.4578275, 0.40821073] + std = [0.26862954, 0.26130258, 0.27577711] + + # transforms + transforms = T.Compose([ + T.Resize((model.image_size, model.image_size), + interpolation=T.InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(mean=mean, std=std) + ]) + output += (transforms,) + + # init tokenizer + if return_tokenizer: + from sora import data + if 'siglip' in pretrained_name.lower(): + tokenizer = data.HuggingfaceTokenizer( + name=f'timm/{pretrained_name}', + seq_len=model.text_len, + clean='canonicalize') + elif 'xlm' in pretrained_name.lower(): + tokenizer = data.HuggingfaceTokenizer( + name='xlm-roberta-large', + seq_len=model.max_text_len - 2, + clean='whitespace') + elif 'mba' in pretrained_name.lower(): + tokenizer = data.HuggingfaceTokenizer( + name='facebook/xlm-roberta-xl', + seq_len=model.max_text_len - 2, + clean='whitespace') + else: + tokenizer = data.CLIPTokenizer( + seq_len=model.text_len, padding=tokenizer_padding) + output += (tokenizer,) + return output[0] if len(output) == 1 else output + + +def clip_xlm_roberta_vit_h_14( + pretrained=False, + pretrained_name='open-clip-xlm-roberta-large-vit-huge-14', + **kwargs): + cfg = dict( + embed_dim=1024, + image_size=224, + patch_size=14, + vision_dim=1280, + vision_mlp_ratio=4, + vision_heads=16, + vision_layers=32, + vision_pool='token', + activation='gelu', + vocab_size=250002, + max_text_len=514, + type_size=1, + pad_id=1, + text_dim=1024, + text_heads=16, + text_layers=24, + text_post_norm=True, + text_dropout=0.1, + attn_dropout=0.0, + proj_dropout=0.0, + embedding_dropout=0.0) + cfg.update(**kwargs) + return _clip(pretrained, pretrained_name, XLMRobertaCLIP, **cfg) + + +class WanImageEncoder(torch.nn.Module): + + def __init__(self): + super().__init__() + # init model + self.model, self.transforms = clip_xlm_roberta_vit_h_14( + pretrained=False, + return_transforms=True, + return_tokenizer=False, + dtype=torch.float32, + device="cpu") + + def encode_image(self, videos): + # preprocess + size = (self.model.image_size,) * 2 + videos = torch.cat([ + F.interpolate( + u, + size=size, + mode='bicubic', + align_corners=False) for u in videos + ]) + videos = self.transforms.transforms[-1](videos.mul_(0.5).add_(0.5)) + + # forward + dtype = next(iter(self.model.visual.parameters())).dtype + videos = videos.to(dtype) + out = self.model.visual(videos, use_31_block=True) + return out + + @staticmethod + def state_dict_converter(): + return WanImageEncoderStateDictConverter() + + +class WanImageEncoderStateDictConverter: + def __init__(self): + pass + + def from_diffusers(self, state_dict): + return state_dict + + def from_civitai(self, state_dict): + state_dict_ = {} + for name, param in state_dict.items(): + if name.startswith("textual."): + continue + name = "model." + name + state_dict_[name] = param + return state_dict_ + diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_motion_controller.py b/releases/2026-10-20-code/diffsynth/models/wan_video_motion_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..518c1c66edca1cae11d5f3371af0455808b2a66a --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_motion_controller.py @@ -0,0 +1,44 @@ +import torch +import torch.nn as nn +from .wan_video_dit import sinusoidal_embedding_1d + + + +class WanMotionControllerModel(torch.nn.Module): + def __init__(self, freq_dim=256, dim=1536): + super().__init__() + self.freq_dim = freq_dim + self.linear = nn.Sequential( + nn.Linear(freq_dim, dim), + nn.SiLU(), + nn.Linear(dim, dim), + nn.SiLU(), + nn.Linear(dim, dim * 6), + ) + + def forward(self, motion_bucket_id): + emb = sinusoidal_embedding_1d(self.freq_dim, motion_bucket_id * 10) + emb = self.linear(emb) + return emb + + def init(self): + state_dict = self.linear[-1].state_dict() + state_dict = {i: state_dict[i] * 0 for i in state_dict} + self.linear[-1].load_state_dict(state_dict) + + @staticmethod + def state_dict_converter(): + return WanMotionControllerModelDictConverter() + + + +class WanMotionControllerModelDictConverter: + 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/releases/2026-10-20-code/diffsynth/models/wan_video_text_encoder.py b/releases/2026-10-20-code/diffsynth/models/wan_video_text_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c28873722ee92f23914712c9d5b2c3a26fd2adb7 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_text_encoder.py @@ -0,0 +1,269 @@ +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/releases/2026-10-20-code/diffsynth/models/wan_video_vace.py b/releases/2026-10-20-code/diffsynth/models/wan_video_vace.py new file mode 100644 index 0000000000000000000000000000000000000000..40f38048fe07184084c76e3b1a5abac062bb0ab8 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_vace.py @@ -0,0 +1,113 @@ +import torch +from .wan_video_dit import DiTBlock +from .utils import hash_state_dict_keys + +class VaceWanAttentionBlock(DiTBlock): + def __init__(self, has_image_input, dim, num_heads, ffn_dim, eps=1e-6, block_id=0): + super().__init__(has_image_input, dim, num_heads, ffn_dim, eps=eps) + self.block_id = block_id + if block_id == 0: + self.before_proj = torch.nn.Linear(self.dim, self.dim) + self.after_proj = torch.nn.Linear(self.dim, self.dim) + + def forward(self, c, x, context, t_mod, freqs): + if self.block_id == 0: + c = self.before_proj(c) + x + all_c = [] + else: + all_c = list(torch.unbind(c)) + c = all_c.pop(-1) + c = super().forward(c, context, t_mod, freqs) + c_skip = self.after_proj(c) + all_c += [c_skip, c] + c = torch.stack(all_c) + return c + + +class VaceWanModel(torch.nn.Module): + def __init__( + self, + vace_layers=(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28), + vace_in_dim=96, + patch_size=(1, 2, 2), + has_image_input=False, + dim=1536, + num_heads=12, + ffn_dim=8960, + eps=1e-6, + ): + super().__init__() + self.vace_layers = vace_layers + self.vace_in_dim = vace_in_dim + self.vace_layers_mapping = {i: n for n, i in enumerate(self.vace_layers)} + + # vace blocks + self.vace_blocks = torch.nn.ModuleList([ + VaceWanAttentionBlock(has_image_input, dim, num_heads, ffn_dim, eps, block_id=i) + for i in self.vace_layers + ]) + + # vace patch embeddings + self.vace_patch_embedding = torch.nn.Conv3d(vace_in_dim, dim, kernel_size=patch_size, stride=patch_size) + + def forward( + self, x, vace_context, context, t_mod, freqs, + use_gradient_checkpointing: bool = False, + use_gradient_checkpointing_offload: bool = False, + ): + c = [self.vace_patch_embedding(u.unsqueeze(0)) for u in vace_context] + c = [u.flatten(2).transpose(1, 2) for u in c] + c = torch.cat([ + torch.cat([u, u.new_zeros(1, x.shape[1] - u.size(1), u.size(2))], + dim=1) for u in c + ]) + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + for block in self.vace_blocks: + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + c = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + c, x, context, t_mod, freqs, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + c = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + c, x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + c = block(c, x, context, t_mod, freqs) + hints = torch.unbind(c)[:-1] + return hints + + @staticmethod + def state_dict_converter(): + return VaceWanModelDictConverter() + + +class VaceWanModelDictConverter: + def __init__(self): + pass + + def from_civitai(self, state_dict): + state_dict_ = {name: param for name, param in state_dict.items() if name.startswith("vace")} + if hash_state_dict_keys(state_dict_) == '3b2726384e4f64837bdf216eea3f310d': # vace 14B + config = { + "vace_layers": (0, 5, 10, 15, 20, 25, 30, 35), + "vace_in_dim": 96, + "patch_size": (1, 2, 2), + "has_image_input": False, + "dim": 5120, + "num_heads": 40, + "ffn_dim": 13824, + "eps": 1e-06, + } + else: + config = {} + return state_dict_, config diff --git a/releases/2026-10-20-code/diffsynth/models/wan_video_vae.py b/releases/2026-10-20-code/diffsynth/models/wan_video_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..c24e04a287017691897b6901e234bc52d7621dbf --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wan_video_vae.py @@ -0,0 +1,1382 @@ +from einops import rearrange, repeat + +import torch +import torch.nn as nn +import torch.nn.functional as F +from tqdm import tqdm + +CACHE_T = 2 + + +def check_is_instance(model, module_class): + if isinstance(model, module_class): + return True + if hasattr(model, "module") and isinstance(model.module, module_class): + return True + return False + + +def block_causal_mask(x, block_size): + # params + b, n, s, _, device = *x.size(), x.device + assert s % block_size == 0 + num_blocks = s // block_size + + # build mask + mask = torch.zeros(b, n, s, s, dtype=torch.bool, device=device) + for i in range(num_blocks): + mask[:, :, + i * block_size:(i + 1) * block_size, :(i + 1) * block_size] = 1 + return mask + + +class CausalConv3d(nn.Conv3d): + """ + Causal 3d convolusion. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._padding = (self.padding[2], self.padding[2], self.padding[1], + self.padding[1], 2 * self.padding[0], 0) + self.padding = (0, 0, 0) + + def forward(self, x, cache_x=None): + padding = list(self._padding) + if cache_x is not None and self._padding[4] > 0: + cache_x = cache_x.to(x.device) + x = torch.cat([cache_x, x], dim=2) + padding[4] -= cache_x.shape[2] + x = F.pad(x, padding) + + return super().forward(x) + + +class RMS_norm(nn.Module): + + def __init__(self, dim, channel_first=True, images=True, bias=False): + super().__init__() + broadcastable_dims = (1, 1, 1) if not images else (1, 1) + shape = (dim, *broadcastable_dims) if channel_first else (dim,) + + self.channel_first = channel_first + self.scale = dim**0.5 + self.gamma = nn.Parameter(torch.ones(shape)) + self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0. + + def forward(self, x): + return F.normalize( + x, dim=(1 if self.channel_first else + -1)) * self.scale * self.gamma + self.bias + + +class Upsample(nn.Upsample): + + def forward(self, x): + """ + Fix bfloat16 support for nearest neighbor interpolation. + """ + return super().forward(x.float()).type_as(x) + + +class Resample(nn.Module): + + def __init__(self, dim, mode): + assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d', + 'downsample3d') + super().__init__() + self.dim = dim + self.mode = mode + + # layers + if mode == 'upsample2d': + self.resample = nn.Sequential( + Upsample(scale_factor=(2., 2.), mode='nearest-exact'), + nn.Conv2d(dim, dim // 2, 3, padding=1)) + elif mode == 'upsample3d': + self.resample = nn.Sequential( + Upsample(scale_factor=(2., 2.), mode='nearest-exact'), + nn.Conv2d(dim, dim // 2, 3, padding=1)) + self.time_conv = CausalConv3d(dim, + dim * 2, (3, 1, 1), + padding=(1, 0, 0)) + + elif mode == 'downsample2d': + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), + nn.Conv2d(dim, dim, 3, stride=(2, 2))) + elif mode == 'downsample3d': + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), + nn.Conv2d(dim, dim, 3, stride=(2, 2))) + self.time_conv = CausalConv3d(dim, + dim, (3, 1, 1), + stride=(2, 1, 1), + padding=(0, 0, 0)) + + else: + self.resample = nn.Identity() + + def forward(self, x, feat_cache=None, feat_idx=[0]): + b, c, t, h, w = x.size() + if self.mode == 'upsample3d': + if feat_cache is not None: + idx = feat_idx[0] + if feat_cache[idx] is None: + feat_cache[idx] = 'Rep' + feat_idx[0] += 1 + else: + + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[ + idx] is not None and feat_cache[idx] != 'Rep': + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + if cache_x.shape[2] < 2 and feat_cache[ + idx] is not None and feat_cache[idx] == 'Rep': + cache_x = torch.cat([ + torch.zeros_like(cache_x).to(cache_x.device), + cache_x + ], + dim=2) + if feat_cache[idx] == 'Rep': + x = self.time_conv(x) + else: + x = self.time_conv(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + + x = x.reshape(b, 2, c, t, h, w) + x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]), + 3) + x = x.reshape(b, c, t * 2, h, w) + t = x.shape[2] + x = rearrange(x, 'b c t h w -> (b t) c h w') + x = self.resample(x) + x = rearrange(x, '(b t) c h w -> b c t h w', t=t) + + if self.mode == 'downsample3d': + if feat_cache is not None: + idx = feat_idx[0] + if feat_cache[idx] is None: + feat_cache[idx] = x.clone() + feat_idx[0] += 1 + else: + cache_x = x[:, :, -1:, :, :].contiguous() + x = self.time_conv( + torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2)) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + return x + + def init_weight(self, conv): + conv_weight = conv.weight + nn.init.zeros_(conv_weight) + c1, c2, t, h, w = conv_weight.size() + one_matrix = torch.eye(c1, c2) + init_matrix = one_matrix + nn.init.zeros_(conv_weight) + conv_weight.data[:, :, 1, 0, 0] = init_matrix + conv.weight.data.copy_(conv_weight) + nn.init.zeros_(conv.bias.data) + + def init_weight2(self, conv): + conv_weight = conv.weight.data + nn.init.zeros_(conv_weight) + c1, c2, t, h, w = conv_weight.size() + init_matrix = torch.eye(c1 // 2, c2) + conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix + conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix + conv.weight.data.copy_(conv_weight) + nn.init.zeros_(conv.bias.data) + + + +def patchify(x, patch_size): + if patch_size == 1: + return x + if x.dim() == 4: + x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size) + elif x.dim() == 5: + x = rearrange(x, + "b c f (h q) (w r) -> b (c r q) f h w", + q=patch_size, + r=patch_size) + else: + raise ValueError(f"Invalid input shape: {x.shape}") + return x + + +def unpatchify(x, patch_size): + if patch_size == 1: + return x + if x.dim() == 4: + x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size) + elif x.dim() == 5: + x = rearrange(x, + "b (c r q) f h w -> b c f (h q) (w r)", + q=patch_size, + r=patch_size) + return x + + +class Resample38(Resample): + + def __init__(self, dim, mode): + assert mode in ( + "none", + "upsample2d", + "upsample3d", + "downsample2d", + "downsample3d", + ) + super(Resample, self).__init__() + self.dim = dim + self.mode = mode + + # layers + if mode == "upsample2d": + self.resample = nn.Sequential( + Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"), + nn.Conv2d(dim, dim, 3, padding=1), + ) + elif mode == "upsample3d": + self.resample = nn.Sequential( + Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"), + nn.Conv2d(dim, dim, 3, padding=1), + ) + self.time_conv = CausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0)) + elif mode == "downsample2d": + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2)) + ) + elif mode == "downsample3d": + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2)) + ) + self.time_conv = CausalConv3d( + dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0) + ) + else: + self.resample = nn.Identity() + +class ResidualBlock(nn.Module): + + def __init__(self, in_dim, out_dim, dropout=0.0): + super().__init__() + self.in_dim = in_dim + self.out_dim = out_dim + + # layers + self.residual = nn.Sequential( + RMS_norm(in_dim, images=False), nn.SiLU(), + CausalConv3d(in_dim, out_dim, 3, padding=1), + RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout), + CausalConv3d(out_dim, out_dim, 3, padding=1)) + self.shortcut = CausalConv3d(in_dim, out_dim, 1) \ + if in_dim != out_dim else nn.Identity() + + def forward(self, x, feat_cache=None, feat_idx=[0]): + h = self.shortcut(x) + for layer in self.residual: + if check_is_instance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + h + + +class AttentionBlock(nn.Module): + """ + Causal self-attention with a single head. + """ + + def __init__(self, dim): + super().__init__() + self.dim = dim + + # layers + self.norm = RMS_norm(dim) + self.to_qkv = nn.Conv2d(dim, dim * 3, 1) + self.proj = nn.Conv2d(dim, dim, 1) + + # zero out the last layer params + nn.init.zeros_(self.proj.weight) + + def forward(self, x): + identity = x + b, c, t, h, w = x.size() + x = rearrange(x, 'b c t h w -> (b t) c h w') + x = self.norm(x) + # compute query, key, value + q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, -1).permute( + 0, 1, 3, 2).contiguous().chunk(3, dim=-1) + + # apply attention + x = F.scaled_dot_product_attention( + q, + k, + v, + #attn_mask=block_causal_mask(q, block_size=h * w) + ) + x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w) + + # output + x = self.proj(x) + x = rearrange(x, '(b t) c h w-> b c t h w', t=t) + return x + identity + + +class AvgDown3D(nn.Module): + def __init__( + self, + in_channels, + out_channels, + factor_t, + factor_s=1, + ): + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.factor_t = factor_t + self.factor_s = factor_s + self.factor = self.factor_t * self.factor_s * self.factor_s + + assert in_channels * self.factor % out_channels == 0 + self.group_size = in_channels * self.factor // out_channels + + def forward(self, x: torch.Tensor) -> torch.Tensor: + pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t + pad = (0, 0, 0, 0, pad_t, 0) + x = F.pad(x, pad) + B, C, T, H, W = x.shape + x = x.view( + B, + C, + T // self.factor_t, + self.factor_t, + H // self.factor_s, + self.factor_s, + W // self.factor_s, + self.factor_s, + ) + x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous() + x = x.view( + B, + C * self.factor, + T // self.factor_t, + H // self.factor_s, + W // self.factor_s, + ) + x = x.view( + B, + self.out_channels, + self.group_size, + T // self.factor_t, + H // self.factor_s, + W // self.factor_s, + ) + x = x.mean(dim=2) + return x + + +class DupUp3D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + factor_t, + factor_s=1, + ): + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + + self.factor_t = factor_t + self.factor_s = factor_s + self.factor = self.factor_t * self.factor_s * self.factor_s + + assert out_channels * self.factor % in_channels == 0 + self.repeats = out_channels * self.factor // in_channels + + def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor: + x = x.repeat_interleave(self.repeats, dim=1) + x = x.view( + x.size(0), + self.out_channels, + self.factor_t, + self.factor_s, + self.factor_s, + x.size(2), + x.size(3), + x.size(4), + ) + x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous() + x = x.view( + x.size(0), + self.out_channels, + x.size(2) * self.factor_t, + x.size(4) * self.factor_s, + x.size(6) * self.factor_s, + ) + if first_chunk: + x = x[:, :, self.factor_t - 1 :, :, :] + return x + + +class Down_ResidualBlock(nn.Module): + def __init__( + self, in_dim, out_dim, dropout, mult, temperal_downsample=False, down_flag=False + ): + super().__init__() + + # Shortcut path with downsample + self.avg_shortcut = AvgDown3D( + in_dim, + out_dim, + factor_t=2 if temperal_downsample else 1, + factor_s=2 if down_flag else 1, + ) + + # Main path with residual blocks and downsample + downsamples = [] + for _ in range(mult): + downsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + in_dim = out_dim + + # Add the final downsample block + if down_flag: + mode = "downsample3d" if temperal_downsample else "downsample2d" + downsamples.append(Resample38(out_dim, mode=mode)) + + self.downsamples = nn.Sequential(*downsamples) + + def forward(self, x, feat_cache=None, feat_idx=[0]): + x_copy = x.clone() + for module in self.downsamples: + x = module(x, feat_cache, feat_idx) + + return x + self.avg_shortcut(x_copy) + + +class Up_ResidualBlock(nn.Module): + def __init__( + self, in_dim, out_dim, dropout, mult, temperal_upsample=False, up_flag=False + ): + super().__init__() + # Shortcut path with upsample + if up_flag: + self.avg_shortcut = DupUp3D( + in_dim, + out_dim, + factor_t=2 if temperal_upsample else 1, + factor_s=2 if up_flag else 1, + ) + else: + self.avg_shortcut = None + + # Main path with residual blocks and upsample + upsamples = [] + for _ in range(mult): + upsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + in_dim = out_dim + + # Add the final upsample block + if up_flag: + mode = "upsample3d" if temperal_upsample else "upsample2d" + upsamples.append(Resample38(out_dim, mode=mode)) + + self.upsamples = nn.Sequential(*upsamples) + + def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False): + x_main = x.clone() + for module in self.upsamples: + x_main = module(x_main, feat_cache, feat_idx) + if self.avg_shortcut is not None: + x_shortcut = self.avg_shortcut(x, first_chunk) + return x_main + x_shortcut + else: + return x_main + + +class Encoder3d(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[True, True, False], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + + # dimensions + dims = [dim * u for u in [1] + dim_mult] + scale = 1.0 + + # init block + self.conv1 = CausalConv3d(3, dims[0], 3, padding=1) + + # downsample blocks + downsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + # residual (+attention) blocks + for _ in range(num_res_blocks): + downsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + if scale in attn_scales: + downsamples.append(AttentionBlock(out_dim)) + in_dim = out_dim + + # downsample block + if i != len(dim_mult) - 1: + mode = 'downsample3d' if temperal_downsample[ + i] else 'downsample2d' + downsamples.append(Resample(out_dim, mode=mode)) + scale /= 2.0 + self.downsamples = nn.Sequential(*downsamples) + + # middle blocks + self.middle = nn.Sequential(ResidualBlock(out_dim, out_dim, dropout), + AttentionBlock(out_dim), + ResidualBlock(out_dim, out_dim, dropout)) + + # output blocks + self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(), + CausalConv3d(out_dim, z_dim, 3, padding=1)) + + def forward(self, x, feat_cache=None, feat_idx=[0]): + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + ## downsamples + for layer in self.downsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## middle + for layer in self.middle: + if check_is_instance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## head + for layer in self.head: + if check_is_instance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + + +class Encoder3d_38(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[False, True, True], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + + # dimensions + dims = [dim * u for u in [1] + dim_mult] + scale = 1.0 + + # init block + self.conv1 = CausalConv3d(12, dims[0], 3, padding=1) + + # downsample blocks + downsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + t_down_flag = ( + temperal_downsample[i] if i < len(temperal_downsample) else False + ) + downsamples.append( + Down_ResidualBlock( + in_dim=in_dim, + out_dim=out_dim, + dropout=dropout, + mult=num_res_blocks, + temperal_downsample=t_down_flag, + down_flag=i != len(dim_mult) - 1, + ) + ) + scale /= 2.0 + self.downsamples = nn.Sequential(*downsamples) + + # middle blocks + self.middle = nn.Sequential( + ResidualBlock(out_dim, out_dim, dropout), + AttentionBlock(out_dim), + ResidualBlock(out_dim, out_dim, dropout), + ) + + # # output blocks + self.head = nn.Sequential( + RMS_norm(out_dim, images=False), + nn.SiLU(), + CausalConv3d(out_dim, z_dim, 3, padding=1), + ) + + + def forward(self, x, feat_cache=None, feat_idx=[0]): + + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + cache_x = torch.cat( + [ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), + cache_x, + ], + dim=2, + ) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + ## downsamples + for layer in self.downsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## middle + for layer in self.middle: + if isinstance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## head + for layer in self.head: + if isinstance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + cache_x = torch.cat( + [ + feat_cache[idx][:, :, -1, :, :] + .unsqueeze(2) + .to(cache_x.device), + cache_x, + ], + dim=2, + ) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + + return x + + +class Decoder3d(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_upsample=[False, True, True], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_upsample = temperal_upsample + + # dimensions + dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]] + scale = 1.0 / 2**(len(dim_mult) - 2) + + # init block + self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1) + + # middle blocks + self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout), + AttentionBlock(dims[0]), + ResidualBlock(dims[0], dims[0], dropout)) + + # upsample blocks + upsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + # residual (+attention) blocks + if i == 1 or i == 2 or i == 3: + in_dim = in_dim // 2 + for _ in range(num_res_blocks + 1): + upsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + if scale in attn_scales: + upsamples.append(AttentionBlock(out_dim)) + in_dim = out_dim + + # upsample block + if i != len(dim_mult) - 1: + mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d' + upsamples.append(Resample(out_dim, mode=mode)) + scale *= 2.0 + self.upsamples = nn.Sequential(*upsamples) + + # output blocks + self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(), + CausalConv3d(out_dim, 3, 3, padding=1)) + + def forward(self, x, feat_cache=None, feat_idx=[0]): + ## conv1 + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + ## middle + for layer in self.middle: + if check_is_instance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## upsamples + for layer in self.upsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## head + for layer in self.head: + if check_is_instance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + + + +class Decoder3d_38(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_upsample=[False, True, True], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_upsample = temperal_upsample + + # dimensions + dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]] + scale = 1.0 / 2 ** (len(dim_mult) - 2) + # init block + self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1) + + # middle blocks + self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout), + AttentionBlock(dims[0]), + ResidualBlock(dims[0], dims[0], dropout)) + + # upsample blocks + upsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + t_up_flag = temperal_upsample[i] if i < len(temperal_upsample) else False + upsamples.append( + Up_ResidualBlock(in_dim=in_dim, + out_dim=out_dim, + dropout=dropout, + mult=num_res_blocks + 1, + temperal_upsample=t_up_flag, + up_flag=i != len(dim_mult) - 1)) + self.upsamples = nn.Sequential(*upsamples) + + # output blocks + self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(), + CausalConv3d(out_dim, 12, 3, padding=1)) + + + def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False): + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + cache_x = torch.cat( + [ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), + cache_x, + ], + dim=2, + ) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + for layer in self.middle: + if check_is_instance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + ## upsamples + for layer in self.upsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx, first_chunk) + else: + x = layer(x) + + ## head + for layer in self.head: + if check_is_instance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].contiguous() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + cache_x = torch.cat( + [ + feat_cache[idx][:, :, -1, :, :] + .unsqueeze(2) + .to(cache_x.device), + cache_x, + ], + dim=2, + ) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + + +def count_conv3d(model): + count = 0 + for m in model.modules(): + if isinstance(m, CausalConv3d): + count += 1 + return count + + +class VideoVAE_(nn.Module): + + def __init__(self, + dim=96, + z_dim=16, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[False, True, True], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + self.temperal_upsample = temperal_downsample[::-1] + + # modules + self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks, + attn_scales, self.temperal_downsample, dropout) + self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1) + self.conv2 = CausalConv3d(z_dim, z_dim, 1) + self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks, + attn_scales, self.temperal_upsample, dropout) + + def forward(self, x): + mu, log_var = self.encode(x) + z = self.reparameterize(mu, log_var) + x_recon = self.decode(z) + return x_recon, mu, log_var + + def encode(self, x, scale): + self.clear_cache() + ## cache + t = x.shape[2] + iter_ = 1 + (t - 1) // 4 + + for i in range(iter_): + self._enc_conv_idx = [0] + if i == 0: + out = self.encoder(x[:, :, :1, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + else: + out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + out = torch.cat([out, out_], 2) + mu, log_var = self.conv1(out).chunk(2, dim=1) + if isinstance(scale[0], torch.Tensor): + scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale] + mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view( + 1, self.z_dim, 1, 1, 1) + else: + scale = scale.to(dtype=mu.dtype, device=mu.device) + mu = (mu - scale[0]) * scale[1] + return mu + + def decode(self, z, scale): + self.clear_cache() + # z: [b,c,t,h,w] + if isinstance(scale[0], torch.Tensor): + scale = [s.to(dtype=z.dtype, device=z.device) for s in scale] + z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view( + 1, self.z_dim, 1, 1, 1) + else: + scale = scale.to(dtype=z.dtype, device=z.device) + z = z / scale[1] + scale[0] + iter_ = z.shape[2] + x = self.conv2(z) + for i in range(iter_): + self._conv_idx = [0] + if i == 0: + out = self.decoder(x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + else: + out_ = self.decoder(x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + out = torch.cat([out, out_], 2) # may add tensor offload + return out + + def reparameterize(self, mu, log_var): + std = torch.exp(0.5 * log_var) + eps = torch.randn_like(std) + return eps * std + mu + + def sample(self, imgs, deterministic=False): + mu, log_var = self.encode(imgs) + if deterministic: + return mu + std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0)) + return mu + std * torch.randn_like(std) + + def clear_cache(self): + self._conv_num = count_conv3d(self.decoder) + self._conv_idx = [0] + self._feat_map = [None] * self._conv_num + # cache encode + self._enc_conv_num = count_conv3d(self.encoder) + self._enc_conv_idx = [0] + self._enc_feat_map = [None] * self._enc_conv_num + + +class WanVideoVAE(nn.Module): + + def __init__(self, z_dim=16): + super().__init__() + + mean = [ + -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508, + 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921 + ] + std = [ + 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, + 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160 + ] + self.mean = torch.tensor(mean) + self.std = torch.tensor(std) + self.scale = [self.mean, 1.0 / self.std] + + # init model + self.model = VideoVAE_(z_dim=z_dim).eval().requires_grad_(False) + self.upsampling_factor = 8 + self.z_dim = z_dim + + + def build_1d_mask(self, length, left_bound, right_bound, border_width): + x = torch.ones((length,)) + if not left_bound: + x[:border_width] = (torch.arange(border_width) + 1) / border_width + if not right_bound: + x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,)) + return x + + + def build_mask(self, data, is_bound, border_width): + _, _, _, H, W = data.shape + h = self.build_1d_mask(H, is_bound[0], is_bound[1], border_width[0]) + w = self.build_1d_mask(W, is_bound[2], is_bound[3], border_width[1]) + + h = repeat(h, "H -> H W", H=H, W=W) + w = repeat(w, "W -> H W", H=H, W=W) + + mask = torch.stack([h, w]).min(dim=0).values + mask = rearrange(mask, "H W -> 1 1 1 H W") + return mask + + + def tiled_decode(self, hidden_states, device, tile_size, tile_stride): + _, _, T, H, W = hidden_states.shape + size_h, size_w = tile_size + stride_h, stride_w = tile_stride + + # Split tasks + tasks = [] + for h in range(0, H, stride_h): + if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue + for w in range(0, W, stride_w): + if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue + h_, w_ = h + size_h, w + size_w + tasks.append((h, h_, w, w_)) + + data_device = "cpu" + computation_device = device + + out_T = T * 4 - 3 + weight = torch.zeros((1, 1, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device) + values = torch.zeros((1, 3, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device) + + for h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"): + hidden_states_batch = hidden_states[:, :, :, h:h_, w:w_].to(computation_device) + hidden_states_batch = self.model.decode(hidden_states_batch, self.scale).to(data_device) + + mask = self.build_mask( + hidden_states_batch, + is_bound=(h==0, h_>=H, w==0, w_>=W), + border_width=((size_h - stride_h) * self.upsampling_factor, (size_w - stride_w) * self.upsampling_factor) + ).to(dtype=hidden_states.dtype, device=data_device) + + target_h = h * self.upsampling_factor + target_w = w * self.upsampling_factor + values[ + :, + :, + :, + target_h:target_h + hidden_states_batch.shape[3], + target_w:target_w + hidden_states_batch.shape[4], + ] += hidden_states_batch * mask + weight[ + :, + :, + :, + target_h: target_h + hidden_states_batch.shape[3], + target_w: target_w + hidden_states_batch.shape[4], + ] += mask + values = values / weight + values = values.clamp_(-1, 1) + return values + + + def tiled_encode(self, video, device, tile_size, tile_stride): + _, _, T, H, W = video.shape + size_h, size_w = tile_size + stride_h, stride_w = tile_stride + + # Split tasks + tasks = [] + for h in range(0, H, stride_h): + if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue + for w in range(0, W, stride_w): + if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue + h_, w_ = h + size_h, w + size_w + tasks.append((h, h_, w, w_)) + + data_device = "cpu" + computation_device = device + + out_T = (T + 3) // 4 + weight = torch.zeros((1, 1, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device) + values = torch.zeros((1, self.z_dim, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device) + + for h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"): + hidden_states_batch = video[:, :, :, h:h_, w:w_].to(computation_device) + hidden_states_batch = self.model.encode(hidden_states_batch, self.scale).to(data_device) + + mask = self.build_mask( + hidden_states_batch, + is_bound=(h==0, h_>=H, w==0, w_>=W), + border_width=((size_h - stride_h) // self.upsampling_factor, (size_w - stride_w) // self.upsampling_factor) + ).to(dtype=video.dtype, device=data_device) + + target_h = h // self.upsampling_factor + target_w = w // self.upsampling_factor + values[ + :, + :, + :, + target_h:target_h + hidden_states_batch.shape[3], + target_w:target_w + hidden_states_batch.shape[4], + ] += hidden_states_batch * mask + weight[ + :, + :, + :, + target_h: target_h + hidden_states_batch.shape[3], + target_w: target_w + hidden_states_batch.shape[4], + ] += mask + values = values / weight + return values + + + def single_encode(self, video, device): + video = video.to(device) + x = self.model.encode(video, self.scale) + return x + + + def single_decode(self, hidden_state, device): + hidden_state = hidden_state.to(device) + video = self.model.decode(hidden_state, self.scale) + return video.clamp_(-1, 1) + + + def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)): + videos = [video.to("cpu") for video in videos] + hidden_states = [] + for video in videos: + video = video.unsqueeze(0) + if tiled: + tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor) + tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor) + hidden_state = self.tiled_encode(video, device, tile_size, tile_stride) + else: + hidden_state = self.single_encode(video, device) + hidden_state = hidden_state.squeeze(0) + hidden_states.append(hidden_state) + hidden_states = torch.stack(hidden_states) + return hidden_states + + + def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)): + hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states] + videos = [] + for hidden_state in hidden_states: + hidden_state = hidden_state.unsqueeze(0) + if tiled: + video = self.tiled_decode(hidden_state, device, tile_size, tile_stride) + else: + video = self.single_decode(hidden_state, device) + video = video.squeeze(0) + videos.append(video) + videos = torch.stack(videos) + return videos + + + @staticmethod + def state_dict_converter(): + return WanVideoVAEStateDictConverter() + + +class WanVideoVAEStateDictConverter: + + def __init__(self): + pass + + def from_civitai(self, state_dict): + state_dict_ = {} + if 'model_state' in state_dict: + state_dict = state_dict['model_state'] + for name in state_dict: + state_dict_['model.' + name] = state_dict[name] + return state_dict_ + + +class VideoVAE38_(VideoVAE_): + + def __init__(self, + dim=160, + z_dim=48, + dec_dim=256, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[False, True, True], + dropout=0.0): + super(VideoVAE_, self).__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + self.temperal_upsample = temperal_downsample[::-1] + + # modules + self.encoder = Encoder3d_38(dim, z_dim * 2, dim_mult, num_res_blocks, + attn_scales, self.temperal_downsample, dropout) + self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1) + self.conv2 = CausalConv3d(z_dim, z_dim, 1) + self.decoder = Decoder3d_38(dec_dim, z_dim, dim_mult, num_res_blocks, + attn_scales, self.temperal_upsample, dropout) + + + def encode(self, x, scale): + self.clear_cache() + x = patchify(x, patch_size=2) + t = x.shape[2] + iter_ = 1 + (t - 1) // 4 + for i in range(iter_): + self._enc_conv_idx = [0] + if i == 0: + out = self.encoder(x[:, :, :1, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + else: + out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + out = torch.cat([out, out_], 2) + mu, log_var = self.conv1(out).chunk(2, dim=1) + if isinstance(scale[0], torch.Tensor): + scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale] + mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view( + 1, self.z_dim, 1, 1, 1) + else: + scale = scale.to(dtype=mu.dtype, device=mu.device) + mu = (mu - scale[0]) * scale[1] + self.clear_cache() + return mu + + + def decode(self, z, scale): + self.clear_cache() + if isinstance(scale[0], torch.Tensor): + scale = [s.to(dtype=z.dtype, device=z.device) for s in scale] + z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view( + 1, self.z_dim, 1, 1, 1) + else: + scale = scale.to(dtype=z.dtype, device=z.device) + z = z / scale[1] + scale[0] + iter_ = z.shape[2] + x = self.conv2(z) + for i in range(iter_): + self._conv_idx = [0] + if i == 0: + out = self.decoder(x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx, + first_chunk=True) + else: + out_ = self.decoder(x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + out = torch.cat([out, out_], 2) + out = unpatchify(out, patch_size=2) + self.clear_cache() + return out + + +class WanVideoVAE38(WanVideoVAE): + + 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] + + # init model + self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False) + self.upsampling_factor = 16 + self.z_dim = z_dim diff --git a/releases/2026-10-20-code/diffsynth/models/wav2vec.py b/releases/2026-10-20-code/diffsynth/models/wav2vec.py new file mode 100644 index 0000000000000000000000000000000000000000..f98b721bc8b844581d3712ca8a9503fdf8e69919 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/models/wav2vec.py @@ -0,0 +1,204 @@ +import math +import numpy as np +import torch +import torch.nn.functional as F + + +def get_sample_indices(original_fps, total_frames, target_fps, num_sample, fixed_start=None): + required_duration = num_sample / target_fps + required_origin_frames = int(np.ceil(required_duration * original_fps)) + if required_duration > total_frames / original_fps: + raise ValueError("required_duration must be less than video length") + + if not fixed_start is None and fixed_start >= 0: + start_frame = fixed_start + else: + max_start = total_frames - required_origin_frames + if max_start < 0: + raise ValueError("video length is too short") + start_frame = np.random.randint(0, max_start + 1) + start_time = start_frame / original_fps + + end_time = start_time + required_duration + time_points = np.linspace(start_time, end_time, num_sample, endpoint=False) + + frame_indices = np.round(np.array(time_points) * original_fps).astype(int) + frame_indices = np.clip(frame_indices, 0, total_frames - 1) + return frame_indices + + +def linear_interpolation(features, input_fps, output_fps, output_len=None): + """ + features: shape=[1, T, 512] + input_fps: fps for audio, f_a + output_fps: fps for video, f_m + output_len: video length + """ + features = features.transpose(1, 2) + seq_len = features.shape[2] / float(input_fps) + if output_len is None: + output_len = int(seq_len * output_fps) + output_features = F.interpolate(features, size=output_len, align_corners=True, mode='linear') # [1, 512, output_len] + return output_features.transpose(1, 2) + + +class WanS2VAudioEncoder(torch.nn.Module): + + def __init__(self): + super().__init__() + from transformers import Wav2Vec2ForCTC, Wav2Vec2Config + config = { + "_name_or_path": "facebook/wav2vec2-large-xlsr-53", + "activation_dropout": 0.05, + "apply_spec_augment": True, + "architectures": ["Wav2Vec2ForCTC"], + "attention_dropout": 0.1, + "bos_token_id": 1, + "conv_bias": True, + "conv_dim": [512, 512, 512, 512, 512, 512, 512], + "conv_kernel": [10, 3, 3, 3, 3, 2, 2], + "conv_stride": [5, 2, 2, 2, 2, 2, 2], + "ctc_loss_reduction": "mean", + "ctc_zero_infinity": True, + "do_stable_layer_norm": True, + "eos_token_id": 2, + "feat_extract_activation": "gelu", + "feat_extract_dropout": 0.0, + "feat_extract_norm": "layer", + "feat_proj_dropout": 0.05, + "final_dropout": 0.0, + "hidden_act": "gelu", + "hidden_dropout": 0.05, + "hidden_size": 1024, + "initializer_range": 0.02, + "intermediate_size": 4096, + "layer_norm_eps": 1e-05, + "layerdrop": 0.05, + "mask_channel_length": 10, + "mask_channel_min_space": 1, + "mask_channel_other": 0.0, + "mask_channel_prob": 0.0, + "mask_channel_selection": "static", + "mask_feature_length": 10, + "mask_feature_prob": 0.0, + "mask_time_length": 10, + "mask_time_min_space": 1, + "mask_time_other": 0.0, + "mask_time_prob": 0.05, + "mask_time_selection": "static", + "model_type": "wav2vec2", + "num_attention_heads": 16, + "num_conv_pos_embedding_groups": 16, + "num_conv_pos_embeddings": 128, + "num_feat_extract_layers": 7, + "num_hidden_layers": 24, + "pad_token_id": 0, + "transformers_version": "4.7.0.dev0", + "vocab_size": 33 + } + self.model = Wav2Vec2ForCTC(Wav2Vec2Config(**config)) + self.video_rate = 30 + + def extract_audio_feat(self, input_audio, sample_rate, processor, return_all_layers=False, dtype=torch.float32, device='cpu'): + input_values = processor(input_audio, sampling_rate=sample_rate, return_tensors="pt").input_values.to(dtype=dtype, device=device) + + # retrieve logits & take argmax + res = self.model(input_values, output_hidden_states=True) + if return_all_layers: + feat = torch.cat(res.hidden_states) + else: + feat = res.hidden_states[-1] + feat = linear_interpolation(feat, input_fps=50, output_fps=self.video_rate) + return feat + + def get_audio_embed_bucket(self, audio_embed, stride=2, batch_frames=12, m=2): + num_layers, audio_frame_num, audio_dim = audio_embed.shape + + if num_layers > 1: + return_all_layers = True + else: + return_all_layers = False + + min_batch_num = int(audio_frame_num / (batch_frames * stride)) + 1 + + bucket_num = min_batch_num * batch_frames + batch_idx = [stride * i for i in range(bucket_num)] + batch_audio_eb = [] + for bi in batch_idx: + if bi < audio_frame_num: + audio_sample_stride = 2 + chosen_idx = list(range(bi - m * audio_sample_stride, bi + (m + 1) * audio_sample_stride, audio_sample_stride)) + chosen_idx = [0 if c < 0 else c for c in chosen_idx] + chosen_idx = [audio_frame_num - 1 if c >= audio_frame_num else c for c in chosen_idx] + + if return_all_layers: + frame_audio_embed = audio_embed[:, chosen_idx].flatten(start_dim=-2, end_dim=-1) + else: + frame_audio_embed = audio_embed[0][chosen_idx].flatten() + else: + frame_audio_embed = \ + torch.zeros([audio_dim * (2 * m + 1)], device=audio_embed.device) if not return_all_layers \ + else torch.zeros([num_layers, audio_dim * (2 * m + 1)], device=audio_embed.device) + batch_audio_eb.append(frame_audio_embed) + batch_audio_eb = torch.cat([c.unsqueeze(0) for c in batch_audio_eb], dim=0) + + return batch_audio_eb, min_batch_num + + def get_audio_embed_bucket_fps(self, audio_embed, fps=16, batch_frames=81, m=0): + num_layers, audio_frame_num, audio_dim = audio_embed.shape + + if num_layers > 1: + return_all_layers = True + else: + return_all_layers = False + + scale = self.video_rate / fps + + min_batch_num = int(audio_frame_num / (batch_frames * scale)) + 1 + + bucket_num = min_batch_num * batch_frames + padd_audio_num = math.ceil(min_batch_num * batch_frames / fps * self.video_rate) - audio_frame_num + batch_idx = get_sample_indices( + original_fps=self.video_rate, total_frames=audio_frame_num + padd_audio_num, target_fps=fps, num_sample=bucket_num, fixed_start=0 + ) + batch_audio_eb = [] + audio_sample_stride = int(self.video_rate / fps) + for bi in batch_idx: + if bi < audio_frame_num: + + chosen_idx = list(range(bi - m * audio_sample_stride, bi + (m + 1) * audio_sample_stride, audio_sample_stride)) + chosen_idx = [0 if c < 0 else c for c in chosen_idx] + chosen_idx = [audio_frame_num - 1 if c >= audio_frame_num else c for c in chosen_idx] + + if return_all_layers: + frame_audio_embed = audio_embed[:, chosen_idx].flatten(start_dim=-2, end_dim=-1) + else: + frame_audio_embed = audio_embed[0][chosen_idx].flatten() + else: + frame_audio_embed = \ + torch.zeros([audio_dim * (2 * m + 1)], device=audio_embed.device) if not return_all_layers \ + else torch.zeros([num_layers, audio_dim * (2 * m + 1)], device=audio_embed.device) + batch_audio_eb.append(frame_audio_embed) + batch_audio_eb = torch.cat([c.unsqueeze(0) for c in batch_audio_eb], dim=0) + + return batch_audio_eb, min_batch_num + + def get_audio_feats_per_inference(self, input_audio, sample_rate, processor, fps=16, batch_frames=80, m=0, dtype=torch.float32, device='cpu'): + audio_feat = self.extract_audio_feat(input_audio, sample_rate, processor, return_all_layers=True, dtype=dtype, device=device) + audio_embed_bucket, min_batch_num = self.get_audio_embed_bucket_fps(audio_feat, fps=fps, batch_frames=batch_frames, m=m) + audio_embed_bucket = audio_embed_bucket.unsqueeze(0).permute(0, 2, 3, 1).to(device, dtype) + audio_embeds = [audio_embed_bucket[..., i * batch_frames:(i + 1) * batch_frames] for i in range(min_batch_num)] + return audio_embeds + + @staticmethod + def state_dict_converter(): + return WanS2VAudioEncoderStateDictConverter() + + +class WanS2VAudioEncoderStateDictConverter(): + def __init__(self): + pass + + def from_civitai(self, state_dict): + state_dict = {'model.' + k: v for k, v in state_dict.items()} + return state_dict diff --git a/releases/2026-10-20-code/diffsynth/pipelines/__init__.py b/releases/2026-10-20-code/diffsynth/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/releases/2026-10-20-code/diffsynth/pipelines/attention_masks.py b/releases/2026-10-20-code/diffsynth/pipelines/attention_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..635e11200b1f35f71b21af5c3454fd84856a4772 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/pipelines/attention_masks.py @@ -0,0 +1,67 @@ +from dataclasses import dataclass + +import torch + + +@dataclass(frozen=True) +class TokenPrefixAttentionSpec: + """Compact form of the [prefix, target] directed attention mask.""" + + prefix_token_count: int + target_token_count: int + + @property + def total_token_count(self) -> int: + return int(self.prefix_token_count) + int(self.target_token_count) + + +@dataclass(frozen=True) +class CausalReferenceSequenceAttentionSpec: + """Causal latent stream plus same-frame reference cross attention.""" + latent_frames: int + tokens_per_frame: int + @property + def latent_token_count(self): + return int(self.latent_frames) * int(self.tokens_per_frame) + @property + def total_token_count(self): + return 2 * self.latent_token_count + + +@dataclass(frozen=True) +class ReferenceSequenceAttentionSpec: + latent_frames: int + tokens_per_frame: int + @property + def latent_token_count(self): + return int(self.latent_frames) * int(self.tokens_per_frame) + @property + def total_token_count(self): + return 2 * self.latent_token_count + + +def build_token_prefix_attention_spec( + prefix_token_count: int, + target_token_count: int, +) -> TokenPrefixAttentionSpec: + prefix_token_count = int(prefix_token_count) + target_token_count = int(target_token_count) + if prefix_token_count < 0 or target_token_count < 0: + raise ValueError("Token counts must be non-negative") + return TokenPrefixAttentionSpec(prefix_token_count, target_token_count) + + +def build_token_prefix_attention_mask( + prefix_token_count: int, + target_token_count: int, + device: torch.device, +) -> torch.Tensor: + """Build the explicit mask used by small tests and debugging.""" + total_tokens = int(prefix_token_count) + int(target_token_count) + attn_mask = torch.ones( + (1, 1, total_tokens, total_tokens), + dtype=torch.bool, + device=device, + ) + attn_mask[..., :prefix_token_count, :] = False + return attn_mask diff --git a/releases/2026-10-20-code/diffsynth/pipelines/wan_video_new.py b/releases/2026-10-20-code/diffsynth/pipelines/wan_video_new.py new file mode 100644 index 0000000000000000000000000000000000000000..d357c3795900d08b48a9a532e056e6374e778d39 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/pipelines/wan_video_new.py @@ -0,0 +1,1758 @@ +import torch, warnings, glob, os, types +import numpy as np +from PIL import Image +from einops import repeat, reduce +from typing import Optional, Union +from dataclasses import dataclass +try: + from modelscope import snapshot_download +except ModuleNotFoundError: + snapshot_download = None +from einops import rearrange +import numpy as np +from PIL import Image +from tqdm import tqdm +from typing import Optional +from typing_extensions import Literal + +from ..utils import BasePipeline, ModelConfig, PipelineUnit, PipelineUnitRunner +from ..models.model_manager import ModelManager +from ..models.utils import load_state_dict +from ..models.wan_video_dit import WanModel, RMSNorm, sinusoidal_embedding_1d +from ..models.wan_video_dit_s2v import rope_precompute +from ..models.wan_video_text_encoder import WanTextEncoder, T5RelativeEmbedding, T5LayerNorm +from ..models.wan_video_vae import WanVideoVAE, RMS_norm, CausalConv3d, Upsample +from ..models.wan_video_image_encoder import WanImageEncoder +from ..models.wan_video_vace import VaceWanModel +from ..models.wan_video_motion_controller import WanMotionControllerModel +from ..models.wan_video_animate_adapter import WanAnimateAdapter +from ..schedulers.flow_match import FlowMatchScheduler +from ..prompters.wan_prompter import WanPrompter +from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear, WanAutoCastLayerNorm +from ..lora import GeneralLoRALoader +from .attention_masks import build_token_prefix_attention_spec, ReferenceSequenceAttentionSpec, CausalReferenceSequenceAttentionSpec + + + +def make_device_tensor(values, device, dtype): + return torch.as_tensor(values, dtype=torch.float32).to(device=device, dtype=dtype) + + +class WanVideoPipeline(BasePipeline): + + def __init__(self, device="npu", torch_dtype=torch.float16, tokenizer_path=None): + super().__init__( + device=device, torch_dtype=torch_dtype, + height_division_factor=16, width_division_factor=16, time_division_factor=4, time_division_remainder=1 + ) + 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.image_encoder: WanImageEncoder = None + self.dit: WanModel = None + self.dit2: WanModel = None + self.vae: WanVideoVAE = None + self.motion_controller: WanMotionControllerModel = None + self.vace: VaceWanModel = None + self.vace2: VaceWanModel = None + self.animate_adapter: WanAnimateAdapter = None + self.in_iteration_models = ("dit", "motion_controller", "vace", "animate_adapter") + self.in_iteration_models_2 = ("dit2", "motion_controller", "vace2", "animate_adapter") + self.unit_runner = PipelineUnitRunner() + self.units = [ + WanVideoUnit_ShapeChecker(), + WanVideoUnit_NoiseInitializer(), + WanVideoUnit_PromptEmbedder(), + WanVideoUnit_S2V(), + WanVideoUnit_InputVideoEmbedder(), + WanVideoUnit_ImageEmbedderVAE(), + WanVideoUnit_ImageEmbedderCLIP(), + WanVideoUnit_ImageEmbedderFused(), + WanVideoUnit_FunControl(), + WanVideoUnit_FunReference(), + WanVideoUnit_FunCameraControl(), + WanVideoUnit_SpeedControl(), + WanVideoUnit_VACE(), + WanVideoPostUnit_AnimateVideoSplit(), + WanVideoPostUnit_AnimatePoseLatents(), + WanVideoPostUnit_AnimateFacePixelValues(), + WanVideoPostUnit_AnimateInpaint(), + WanVideoUnit_UnifiedSequenceParallel(), + WanVideoUnit_TeaCache(), + WanVideoUnit_CfgMerger(), + ] + self.post_units = [ + WanVideoPostUnit_S2V(), + ] + self.model_fn = model_fn_wan_video + + def load_lora( + self, + module: torch.nn.Module, + lora_config: Union[ModelConfig, str] = None, + alpha=1, + hotload=False, + state_dict=None, + ): + if state_dict is None: + if isinstance(lora_config, str): + lora = load_state_dict(lora_config, torch_dtype=self.torch_dtype, device=self.device) + else: + lora_config.download_if_necessary() + lora = load_state_dict(lora_config.path, torch_dtype=self.torch_dtype, device=self.device) + else: + lora = state_dict + if hotload: + for name, module in module.named_modules(): + if isinstance(module, AutoWrappedLinear): + lora_a_name = f'{name}.lora_A.default.weight' + lora_b_name = f'{name}.lora_B.default.weight' + if lora_a_name in lora and lora_b_name in lora: + module.lora_A_weights.append(lora[lora_a_name] * alpha) + module.lora_B_weights.append(lora[lora_b_name]) + else: + loader = GeneralLoRALoader(torch_dtype=self.torch_dtype, device=self.device) + loader.load(module, lora, alpha=alpha) + + def training_loss(self, **inputs): + max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps) + min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps) + timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,)) + timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device) + + inputs["latents"] = self.scheduler.add_noise(inputs["input_latents"], inputs["noise"], timestep) + training_target = self.scheduler.training_target(inputs["input_latents"], inputs["noise"], timestep) + + noise_pred = self.model_fn(**inputs, timestep=timestep) + + loss = torch.nn.functional.mse_loss(noise_pred.float(), training_target.float()) + loss = loss * self.scheduler.training_weight(timestep) + return loss + + + def enable_vram_management(self, num_persistent_param_in_dit=None, vram_limit=None, vram_buffer=0.5): + self.vram_management_enabled = True + if num_persistent_param_in_dit is not None: + vram_limit = None + else: + if vram_limit is None: + vram_limit = self.get_vram() + vram_limit = vram_limit - vram_buffer + if self.text_encoder is not 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, + ), + vram_limit=vram_limit, + ) + if self.dit is not None: + dtype = next(iter(self.dit.parameters())).dtype + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.dit, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv3d: AutoWrappedModule, + torch.nn.LayerNorm: WanAutoCastLayerNorm, + RMSNorm: AutoWrappedModule, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.Conv1d: AutoWrappedModule, + torch.nn.Embedding: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device=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, + ), + vram_limit=vram_limit, + ) + if self.dit2 is not None: + dtype = next(iter(self.dit2.parameters())).dtype + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.dit2, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv3d: AutoWrappedModule, + torch.nn.LayerNorm: WanAutoCastLayerNorm, + RMSNorm: AutoWrappedModule, + torch.nn.Conv2d: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device=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, + ), + vram_limit=vram_limit, + ) + if self.vae is not None: + 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, + ), + ) + if self.image_encoder is not None: + dtype = next(iter(self.image_encoder.parameters())).dtype + enable_vram_management( + self.image_encoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.Conv2d: AutoWrappedModule, + torch.nn.LayerNorm: AutoWrappedModule, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=dtype, + computation_device=self.device, + ), + ) + if self.motion_controller is not None: + dtype = next(iter(self.motion_controller.parameters())).dtype + enable_vram_management( + self.motion_controller, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + }, + module_config = dict( + offload_dtype=dtype, + offload_device="cpu", + onload_dtype=dtype, + onload_device="cpu", + computation_dtype=dtype, + computation_device=self.device, + ), + ) + if self.vace is not None: + device = "cpu" if vram_limit is not None else self.device + enable_vram_management( + self.vace, + 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=device, + computation_dtype=self.torch_dtype, + computation_device=self.device, + ), + vram_limit=vram_limit, + ) + if self.audio_encoder is not None: + # TODO: need check + dtype = next(iter(self.audio_encoder.parameters())).dtype + enable_vram_management( + self.audio_encoder, + module_map = { + torch.nn.Linear: AutoWrappedLinear, + torch.nn.LayerNorm: AutoWrappedModule, + torch.nn.Conv1d: 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, + ), + ) + + + def initialize_usp(self): + import torch.distributed as dist + from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment + backend = "hccl" if getattr(torch, "npu", None) is not None and torch.npu.is_available() else "nccl" + dist.init_process_group(backend=backend, init_method="env://") + init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size()) + initialize_model_parallel( + sequence_parallel_degree=dist.get_world_size(), + ring_degree=1, + ulysses_degree=dist.get_world_size(), + ) + if backend == "hccl": + torch.npu.set_device(dist.get_rank()) + else: + torch.cuda.set_device(dist.get_rank()) + + + def enable_usp(self): + from xfuser.core.distributed import get_sequence_parallel_world_size + from ..distributed.xdit_context_parallel import usp_attn_forward, usp_dit_forward + + for block in self.dit.blocks: + block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn) + self.dit.forward = types.MethodType(usp_dit_forward, self.dit) + if self.dit2 is not None: + for block in self.dit2.blocks: + block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn) + self.dit2.forward = types.MethodType(usp_dit_forward, self.dit2) + self.sp_size = get_sequence_parallel_world_size() + self.use_unified_sequence_parallel = True + + + @classmethod + def from_pretrained( + cls, + torch_dtype: torch.dtype = torch.float16, + device: Union[str, torch.device] = "npu", + model_configs: list[ModelConfig] = [], + tokenizer_config: ModelConfig = ModelConfig(model_id="Wan-AI/Wan2.1-T2V-1.3B", origin_file_pattern="google/*"), + audio_processor_config: ModelConfig = None, + redirect_common_files: bool = True, + use_usp=False, + ): + # Redirect model path + if redirect_common_files: + redirect_dict = { + "models_t5_umt5-xxl-enc-bf16.pth": "Wan-AI/Wan2.1-T2V-1.3B", + "Wan2.1_VAE.pth": "Wan-AI/Wan2.1-T2V-1.3B", + "models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth": "Wan-AI/Wan2.1-I2V-14B-480P", + } + for model_config in model_configs: + if model_config.origin_file_pattern is None or model_config.model_id is None: + continue + if model_config.origin_file_pattern in redirect_dict and model_config.model_id != redirect_dict[model_config.origin_file_pattern]: + print(f"To avoid repeatedly downloading model files, ({model_config.model_id}, {model_config.origin_file_pattern}) is redirected to ({redirect_dict[model_config.origin_file_pattern]}, {model_config.origin_file_pattern}). You can use `redirect_common_files=False` to disable file redirection.") + model_config.model_id = redirect_dict[model_config.origin_file_pattern] + + # Initialize pipeline + pipe = cls(device=device, torch_dtype=torch_dtype) + if use_usp: pipe.initialize_usp() + + # Download and load models + model_manager = ModelManager() + for model_config in model_configs: + model_config.download_if_necessary(use_usp=use_usp) + model_manager.load_model( + model_config.path, + device=model_config.offload_device or device, + torch_dtype=model_config.offload_dtype or torch_dtype + ) + + # Load models + pipe.text_encoder = model_manager.fetch_model("wan_video_text_encoder") + dit = model_manager.fetch_model("wan_video_dit", index=2) + if isinstance(dit, list): + pipe.dit, pipe.dit2 = dit + else: + pipe.dit = dit + pipe.vae = model_manager.fetch_model("wan_video_vae") + pipe.image_encoder = model_manager.fetch_model("wan_video_image_encoder") + pipe.motion_controller = model_manager.fetch_model("wan_video_motion_controller") + vace = model_manager.fetch_model("wan_video_vace", index=2) + if isinstance(vace, list): + pipe.vace, pipe.vace2 = vace + else: + pipe.vace = vace + pipe.audio_encoder = model_manager.fetch_model("wans2v_audio_encoder") + pipe.animate_adapter = model_manager.fetch_model("wan_video_animate_adapter") + + # Size division factor + if pipe.vae is not None: + pipe.height_division_factor = pipe.vae.upsampling_factor * 2 + pipe.width_division_factor = pipe.vae.upsampling_factor * 2 + + # Initialize tokenizer + tokenizer_config.download_if_necessary(use_usp=use_usp) + pipe.prompter.fetch_models(pipe.text_encoder) + pipe.prompter.fetch_tokenizer(tokenizer_config.path) + + if audio_processor_config is not None: + audio_processor_config.download_if_necessary(use_usp=use_usp) + from transformers import Wav2Vec2Processor + pipe.audio_processor = Wav2Vec2Processor.from_pretrained(audio_processor_config.path) + # Unified Sequence Parallel + if use_usp: pipe.enable_usp() + return pipe + + + @torch.no_grad() + def __call__( + self, + # Prompt + prompt: str, + negative_prompt: Optional[str] = "", + # Image-to-video + input_image: Optional[Image.Image] = None, + # First-last-frame-to-video + end_image: Optional[Image.Image] = None, + # Video-to-video + input_video: Optional[list[Image.Image]] = None, + denoising_strength: Optional[float] = 1.0, + # Speech-to-video + input_audio: Optional[np.array] = None, + audio_embeds: Optional[torch.Tensor] = None, + audio_sample_rate: Optional[int] = 16000, + s2v_pose_video: Optional[list[Image.Image]] = None, + s2v_pose_latents: Optional[torch.Tensor] = None, + motion_video: Optional[list[Image.Image]] = None, + # ControlNet + control_video: Optional[list[Image.Image]] = None, + reference_image: Optional[Image.Image] = None, + # Camera control + camera_control_direction: Optional[Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown"]] = None, + camera_control_speed: Optional[float] = 1/54, + camera_control_origin: Optional[tuple] = (0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0), + # VACE + vace_video: Optional[list[Image.Image]] = None, + vace_video_mask: Optional[Image.Image] = None, + vace_reference_image: Optional[Image.Image] = None, + vace_scale: Optional[float] = 1.0, + # Animate + animate_pose_video: Optional[list[Image.Image]] = None, + animate_face_video: Optional[list[Image.Image]] = None, + animate_inpaint_video: Optional[list[Image.Image]] = None, + animate_mask_video: Optional[list[Image.Image]] = None, + # Randomness + seed: Optional[int] = None, + rand_device: Optional[str] = "cpu", + # Shape + height: Optional[int] = 480, + width: Optional[int] = 832, + num_frames=81, + # Classifier-free guidance + cfg_scale: Optional[float] = 5.0, + cfg_merge: Optional[bool] = False, + # Boundary + switch_DiT_boundary: Optional[float] = 0.875, + # Scheduler + num_inference_steps: Optional[int] = 50, + sigma_shift: Optional[float] = 5.0, + # Speed control + motion_bucket_id: Optional[int] = None, + # VAE tiling + tiled: Optional[bool] = True, + tile_size: Optional[tuple[int, int]] = (30, 52), + tile_stride: Optional[tuple[int, int]] = (15, 26), + # Sliding window + sliding_window_size: Optional[int] = None, + sliding_window_stride: Optional[int] = None, + # Teacache + tea_cache_l1_thresh: Optional[float] = None, + tea_cache_model_id: Optional[str] = "", + # progress_bar + progress_bar_cmd=tqdm, + ): + # Scheduler + self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength, shift=sigma_shift) + + # Inputs + inputs_posi = { + "prompt": prompt, + "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps, + } + inputs_nega = { + "negative_prompt": negative_prompt, + "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps, + } + inputs_shared = { + "input_image": input_image, + "end_image": end_image, + "input_video": input_video, "denoising_strength": denoising_strength, + "control_video": control_video, "reference_image": reference_image, + "camera_control_direction": camera_control_direction, "camera_control_speed": camera_control_speed, "camera_control_origin": camera_control_origin, + "vace_video": vace_video, "vace_video_mask": vace_video_mask, "vace_reference_image": vace_reference_image, "vace_scale": vace_scale, + "seed": seed, "rand_device": rand_device, + "height": height, "width": width, "num_frames": num_frames, + "cfg_scale": cfg_scale, "cfg_merge": cfg_merge, + "sigma_shift": sigma_shift, + "motion_bucket_id": motion_bucket_id, + "tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride, + "sliding_window_size": sliding_window_size, "sliding_window_stride": sliding_window_stride, + "input_audio": input_audio, "audio_sample_rate": audio_sample_rate, "s2v_pose_video": s2v_pose_video, "audio_embeds": audio_embeds, "s2v_pose_latents": s2v_pose_latents, "motion_video": motion_video, + "animate_pose_video": animate_pose_video, "animate_face_video": animate_face_video, "animate_inpaint_video": animate_inpaint_video, "animate_mask_video": animate_mask_video, + } + for unit in self.units: + inputs_shared, inputs_posi, inputs_nega = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega) + + # Denoise + self.load_models_to_device(self.in_iteration_models) + models = {name: getattr(self, name) for name in self.in_iteration_models} + for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)): + # Switch DiT if necessary + if timestep.item() < switch_DiT_boundary * self.scheduler.num_train_timesteps and self.dit2 is not None and not models["dit"] is self.dit2: + self.load_models_to_device(self.in_iteration_models_2) + models["dit"] = self.dit2 + models["vace"] = self.vace2 + + # Timestep + timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device) + + # Inference + noise_pred_posi = self.model_fn(**models, **inputs_shared, **inputs_posi, timestep=timestep) + if cfg_scale != 1.0: + if cfg_merge: + noise_pred_posi, noise_pred_nega = noise_pred_posi.chunk(2, dim=0) + else: + noise_pred_nega = self.model_fn(**models, **inputs_shared, **inputs_nega, timestep=timestep) + noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega) + else: + noise_pred = noise_pred_posi + + # Scheduler + inputs_shared["latents"] = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], inputs_shared["latents"]) + if "first_frame_latents" in inputs_shared: + inputs_shared["latents"][:, :, 0:1] = inputs_shared["first_frame_latents"] + + # VACE (TODO: remove it) + if vace_reference_image is not None or (animate_pose_video is not None and animate_face_video is not None): + if vace_reference_image is not None and isinstance(vace_reference_image, list): + f = len(vace_reference_image) + else: + f = 1 + inputs_shared["latents"] = inputs_shared["latents"][:, :, f:] + # post-denoising, pre-decoding processing logic + for unit in self.post_units: + inputs_shared, _, _ = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega) + # Decode + self.load_models_to_device(['vae']) + video = self.vae.decode(inputs_shared["latents"], device=self.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + video = self.vae_output_to_video(video) + self.load_models_to_device([]) + + return video + + + +class WanVideoUnit_ShapeChecker(PipelineUnit): + def __init__(self): + super().__init__(input_params=("height", "width", "num_frames")) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames): + height, width, num_frames = pipe.check_resize_height_width(height, width, num_frames) + return {"height": height, "width": width, "num_frames": num_frames} + + + +class WanVideoUnit_NoiseInitializer(PipelineUnit): + def __init__(self): + super().__init__(input_params=("height", "width", "num_frames", "seed", "rand_device", "vace_reference_image")) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames, seed, rand_device, vace_reference_image): + length = (num_frames - 1) // 4 + 1 + if vace_reference_image is not None: + f = len(vace_reference_image) if isinstance(vace_reference_image, list) else 1 + length += f + shape = (1, pipe.vae.model.z_dim, length, height // pipe.vae.upsampling_factor, width // pipe.vae.upsampling_factor) + noise = pipe.generate_noise(shape, seed=seed, rand_device=rand_device) + if vace_reference_image is not None: + noise = torch.concat((noise[:, :, -f:], noise[:, :, :-f]), dim=2) + return {"noise": noise} + + + +class WanVideoUnit_InputVideoEmbedder(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_video", "noise", "tiled", "tile_size", "tile_stride", "vace_reference_image"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_video, noise, tiled, tile_size, tile_stride, vace_reference_image): + if input_video is None: + return {"latents": noise} + pipe.load_models_to_device(["vae"]) + input_video = pipe.preprocess_video(input_video) + input_latents = pipe.vae.encode(input_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + if vace_reference_image is not None: + if not isinstance(vace_reference_image, list): + vace_reference_image = [vace_reference_image] + vace_reference_image = pipe.preprocess_video(vace_reference_image) + vace_reference_latents = pipe.vae.encode(vace_reference_image, device=pipe.device).to(dtype=pipe.torch_dtype, device=pipe.device) + input_latents = torch.concat([vace_reference_latents, input_latents], dim=2) + if pipe.scheduler.training: + return {"latents": noise, "input_latents": input_latents} + else: + latents = pipe.scheduler.add_noise(input_latents, noise, timestep=pipe.scheduler.timesteps[0]) + return {"latents": latents} + + + +class WanVideoUnit_PromptEmbedder(PipelineUnit): + def __init__(self): + super().__init__( + seperate_cfg=True, + input_params_posi={"prompt": "prompt", "positive": "positive"}, + input_params_nega={"prompt": "negative_prompt", "positive": "positive"}, + onload_model_names=("text_encoder",) + ) + + def process(self, pipe: WanVideoPipeline, prompt, positive) -> dict: + pipe.load_models_to_device(self.onload_model_names) + prompt_emb = pipe.prompter.encode_prompt(prompt, positive=positive, device=pipe.device) + return {"context": prompt_emb} + + + +class WanVideoUnit_ImageEmbedder(PipelineUnit): + """ + Deprecated + """ + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("image_encoder", "vae") + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride): + if input_image is None or pipe.image_encoder is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + clip_context = pipe.image_encoder.encode_image([image]) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0,1), torch.zeros(3, num_frames-2, height, width).to(image.device), end_image.transpose(0,1)],dim=1) + if pipe.dit.has_image_pos_emb: + clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1) + msk[:, -1:] = 1 + else: + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + y = torch.concat([msk, y]) + y = y.unsqueeze(0) + clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"clip_feature": clip_context, "y": y} + + + +class WanVideoUnit_ImageEmbedderCLIP(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "height", "width"), + onload_model_names=("image_encoder",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, height, width): + if input_image is None or pipe.image_encoder is None or not pipe.dit.require_clip_embedding: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + clip_context = pipe.image_encoder.encode_image([image]) + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + if pipe.dit.has_image_pos_emb: + clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1) + clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"clip_feature": clip_context} + + + +class WanVideoUnit_ImageEmbedderVAE(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride): + if input_image is None or not pipe.dit.require_vae_embedding: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + if end_image is not None: + end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0,1), torch.zeros(3, num_frames-2, height, width).to(image.device), end_image.transpose(0,1)],dim=1) + msk[:, -1:] = 1 + else: + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + y = torch.concat([msk, y]) + y = y.unsqueeze(0) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"y": y} + + + +class WanVideoUnit_ImageEmbedderFused(PipelineUnit): + """ + Encode input image to latents using VAE. This unit is for Wan-AI/Wan2.2-TI2V-5B. + """ + def __init__(self): + super().__init__( + input_params=("input_image", "latents", "height", "width", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, input_image, latents, height, width, tiled, tile_size, tile_stride): + if input_image is None or not pipe.dit.fuse_vae_embedding_in_latents: + return {} + pipe.load_models_to_device(self.onload_model_names) + image = pipe.preprocess_image(input_image.resize((width, height))).transpose(0, 1) + z = pipe.vae.encode([image], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + latents[:, :, 0: 1] = z + return {"latents": latents, "fuse_vae_embedding_in_latents": True, "first_frame_latents": z} + + + +class WanVideoUnit_FunControl(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("control_video", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride", "clip_feature", "y", "latents"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, control_video, num_frames, height, width, tiled, tile_size, tile_stride, clip_feature, y, latents): + if control_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + control_video = pipe.preprocess_video(control_video) + control_latents = pipe.vae.encode(control_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + control_latents = control_latents.to(dtype=pipe.torch_dtype, device=pipe.device) + y_dim = pipe.dit.in_dim-control_latents.shape[1]-latents.shape[1] + if clip_feature is None or y is None: + clip_feature = torch.zeros((1, 257, 1280), dtype=pipe.torch_dtype, device=pipe.device) + y = torch.zeros((1, y_dim, (num_frames - 1) // 4 + 1, height//8, width//8), dtype=pipe.torch_dtype, device=pipe.device) + else: + y = y[:, -y_dim:] + y = torch.concat([control_latents, y], dim=1) + return {"clip_feature": clip_feature, "y": y} + + + +class WanVideoUnit_FunReference(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("reference_image", "height", "width", "reference_image"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, reference_image, height, width): + if reference_image is None: + return {} + pipe.load_models_to_device(["vae"]) + reference_image = reference_image.resize((width, height)) + reference_latents = pipe.preprocess_video([reference_image]) + reference_latents = pipe.vae.encode(reference_latents, device=pipe.device) + if pipe.image_encoder is None: + return {"reference_latents": reference_latents} + clip_feature = pipe.preprocess_image(reference_image) + clip_feature = pipe.image_encoder.encode_image([clip_feature]) + return {"reference_latents": reference_latents, "clip_feature": clip_feature} + + + +class WanVideoUnit_FunCameraControl(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("height", "width", "num_frames", "camera_control_direction", "camera_control_speed", "camera_control_origin", "latents", "input_image", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, height, width, num_frames, camera_control_direction, camera_control_speed, camera_control_origin, latents, input_image, tiled, tile_size, tile_stride): + if camera_control_direction is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + camera_control_plucker_embedding = pipe.dit.control_adapter.process_camera_coordinates( + camera_control_direction, num_frames, height, width, camera_control_speed, camera_control_origin) + + control_camera_video = camera_control_plucker_embedding[:num_frames].permute([3, 0, 1, 2]).unsqueeze(0) + control_camera_latents = torch.concat( + [ + torch.repeat_interleave(control_camera_video[:, :, 0:1], repeats=4, dim=2), + control_camera_video[:, :, 1:] + ], dim=2 + ).transpose(1, 2) + b, f, c, h, w = control_camera_latents.shape + control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, 4, c, h, w).transpose(2, 3) + control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, c * 4, h, w).transpose(1, 2) + control_camera_latents_input = control_camera_latents.to(device=pipe.device, dtype=pipe.torch_dtype) + + input_image = input_image.resize((width, height)) + input_latents = pipe.preprocess_video([input_image]) + input_latents = pipe.vae.encode(input_latents, device=pipe.device) + y = torch.zeros_like(latents).to(pipe.device) + y[:, :, :1] = input_latents + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + + if y.shape[1] != pipe.dit.in_dim - latents.shape[1]: + image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device) + vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1) + y = pipe.vae.encode([vae_input.to(dtype=pipe.torch_dtype, device=pipe.device)], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0] + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device) + msk[:, 1:] = 0 + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8) + msk = msk.transpose(1, 2)[0] + y = torch.cat([msk,y]) + y = y.unsqueeze(0) + y = y.to(dtype=pipe.torch_dtype, device=pipe.device) + return {"control_camera_latents_input": control_camera_latents_input, "y": y} + + + +class WanVideoUnit_SpeedControl(PipelineUnit): + def __init__(self): + super().__init__(input_params=("motion_bucket_id",)) + + def process(self, pipe: WanVideoPipeline, motion_bucket_id): + if motion_bucket_id is None: + return {} + motion_bucket_id = torch.Tensor((motion_bucket_id,)).to(dtype=pipe.torch_dtype, device=pipe.device) + return {"motion_bucket_id": motion_bucket_id} + + + +class WanVideoUnit_VACE(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("vace_video", "vace_video_mask", "vace_reference_image", "vace_scale", "height", "width", "num_frames", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process( + self, + pipe: WanVideoPipeline, + vace_video, vace_video_mask, vace_reference_image, vace_scale, + height, width, num_frames, + tiled, tile_size, tile_stride + ): + if vace_video is not None or vace_video_mask is not None or vace_reference_image is not None: + pipe.load_models_to_device(["vae"]) + if vace_video is None: + vace_video = torch.zeros((1, 3, num_frames, height, width), dtype=pipe.torch_dtype, device=pipe.device) + else: + vace_video = pipe.preprocess_video(vace_video) + + if vace_video_mask is None: + vace_video_mask = torch.ones_like(vace_video) + else: + vace_video_mask = pipe.preprocess_video(vace_video_mask, min_value=0, max_value=1) + + inactive = vace_video * (1 - vace_video_mask) + 0 * vace_video_mask + reactive = vace_video * vace_video_mask + 0 * (1 - vace_video_mask) + inactive = pipe.vae.encode(inactive, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + reactive = pipe.vae.encode(reactive, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + vace_video_latents = torch.concat((inactive, reactive), dim=1) + + vace_mask_latents = rearrange(vace_video_mask[0,0], "T (H P) (W Q) -> 1 (P Q) T H W", P=8, Q=8) + vace_mask_latents = torch.nn.functional.interpolate(vace_mask_latents, size=((vace_mask_latents.shape[2] + 3) // 4, vace_mask_latents.shape[3], vace_mask_latents.shape[4]), mode='nearest-exact') + + if vace_reference_image is None: + pass + else: + if not isinstance(vace_reference_image,list): + vace_reference_image = [vace_reference_image] + + vace_reference_image = pipe.preprocess_video(vace_reference_image) + + bs, c, f, h, w = vace_reference_image.shape + new_vace_ref_images = [] + for j in range(f): + new_vace_ref_images.append(vace_reference_image[0, :, j:j+1]) + vace_reference_image = new_vace_ref_images + + vace_reference_latents = pipe.vae.encode(vace_reference_image, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + vace_reference_latents = torch.concat((vace_reference_latents, torch.zeros_like(vace_reference_latents)), dim=1) + vace_reference_latents = [u.unsqueeze(0) for u in vace_reference_latents] + + vace_video_latents = torch.concat((*vace_reference_latents, vace_video_latents), dim=2) + vace_mask_latents = torch.concat((torch.zeros_like(vace_mask_latents[:, :, :f]), vace_mask_latents), dim=2) + + vace_context = torch.concat((vace_video_latents, vace_mask_latents), dim=1) + return {"vace_context": vace_context, "vace_scale": vace_scale} + else: + return {"vace_context": None, "vace_scale": vace_scale} + + + +class WanVideoUnit_UnifiedSequenceParallel(PipelineUnit): + def __init__(self): + super().__init__(input_params=()) + + def process(self, pipe: WanVideoPipeline): + if hasattr(pipe, "use_unified_sequence_parallel"): + if pipe.use_unified_sequence_parallel: + return {"use_unified_sequence_parallel": True} + return {} + + + +class WanVideoUnit_TeaCache(PipelineUnit): + def __init__(self): + super().__init__( + seperate_cfg=True, + input_params_posi={"num_inference_steps": "num_inference_steps", "tea_cache_l1_thresh": "tea_cache_l1_thresh", "tea_cache_model_id": "tea_cache_model_id"}, + input_params_nega={"num_inference_steps": "num_inference_steps", "tea_cache_l1_thresh": "tea_cache_l1_thresh", "tea_cache_model_id": "tea_cache_model_id"}, + ) + + def process(self, pipe: WanVideoPipeline, num_inference_steps, tea_cache_l1_thresh, tea_cache_model_id): + if tea_cache_l1_thresh is None: + return {} + return {"tea_cache": TeaCache(num_inference_steps, rel_l1_thresh=tea_cache_l1_thresh, model_id=tea_cache_model_id)} + + + +class WanVideoUnit_CfgMerger(PipelineUnit): + def __init__(self): + super().__init__(take_over=True) + self.concat_tensor_names = ["context", "clip_feature", "y", "reference_latents"] + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if not inputs_shared["cfg_merge"]: + return inputs_shared, inputs_posi, inputs_nega + for name in self.concat_tensor_names: + tensor_posi = inputs_posi.get(name) + tensor_nega = inputs_nega.get(name) + tensor_shared = inputs_shared.get(name) + if tensor_posi is not None and tensor_nega is not None: + inputs_shared[name] = torch.concat((tensor_posi, tensor_nega), dim=0) + elif tensor_shared is not None: + inputs_shared[name] = torch.concat((tensor_shared, tensor_shared), dim=0) + inputs_posi.clear() + inputs_nega.clear() + return inputs_shared, inputs_posi, inputs_nega + + +class WanVideoUnit_S2V(PipelineUnit): + def __init__(self): + super().__init__( + take_over=True, + onload_model_names=("audio_encoder", "vae",) + ) + + def process_audio(self, pipe: WanVideoPipeline, input_audio, audio_sample_rate, num_frames, fps=16, audio_embeds=None, return_all=False): + if audio_embeds is not None: + return {"audio_embeds": audio_embeds} + pipe.load_models_to_device(["audio_encoder"]) + audio_embeds = pipe.audio_encoder.get_audio_feats_per_inference(input_audio, audio_sample_rate, pipe.audio_processor, fps=fps, batch_frames=num_frames-1, dtype=pipe.torch_dtype, device=pipe.device) + if return_all: + return audio_embeds + else: + return {"audio_embeds": audio_embeds[0]} + + def process_motion_latents(self, pipe: WanVideoPipeline, height, width, tiled, tile_size, tile_stride, motion_video=None): + pipe.load_models_to_device(["vae"]) + motion_frames = 73 + kwargs = {} + if motion_video is not None and len(motion_video) > 0: + assert len(motion_video) == motion_frames, f"motion video must have {motion_frames} frames, but got {len(motion_video)}" + motion_latents = pipe.preprocess_video(motion_video) + kwargs["drop_motion_frames"] = False + else: + motion_latents = torch.zeros([1, 3, motion_frames, height, width], dtype=pipe.torch_dtype, device=pipe.device) + kwargs["drop_motion_frames"] = True + motion_latents = pipe.vae.encode(motion_latents, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + kwargs.update({"motion_latents": motion_latents}) + return kwargs + + def process_pose_cond(self, pipe: WanVideoPipeline, s2v_pose_video, num_frames, height, width, tiled, tile_size, tile_stride, s2v_pose_latents=None, num_repeats=1, return_all=False): + if s2v_pose_latents is not None: + return {"s2v_pose_latents": s2v_pose_latents} + if s2v_pose_video is None: + return {"s2v_pose_latents": None} + pipe.load_models_to_device(["vae"]) + infer_frames = num_frames - 1 + input_video = pipe.preprocess_video(s2v_pose_video)[:, :, :infer_frames * num_repeats] + # pad if not enough frames + padding_frames = infer_frames * num_repeats - input_video.shape[2] + input_video = torch.cat([input_video, -torch.ones(1, 3, padding_frames, height, width, device=input_video.device, dtype=input_video.dtype)], dim=2) + input_videos = input_video.chunk(num_repeats, dim=2) + pose_conds = [] + for r in range(num_repeats): + cond = input_videos[r] + cond = torch.cat([cond[:, :, 0:1].repeat(1, 1, 1, 1, 1), cond], dim=2) + cond_latents = pipe.vae.encode(cond, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + pose_conds.append(cond_latents[:,:,1:]) + if return_all: + return pose_conds + else: + return {"s2v_pose_latents": pose_conds[0]} + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if (inputs_shared.get("input_audio") is None and inputs_shared.get("audio_embeds") is None) or pipe.audio_encoder is None or pipe.audio_processor is None: + return inputs_shared, inputs_posi, inputs_nega + num_frames, height, width, tiled, tile_size, tile_stride = inputs_shared.get("num_frames"), inputs_shared.get("height"), inputs_shared.get("width"), inputs_shared.get("tiled"), inputs_shared.get("tile_size"), inputs_shared.get("tile_stride") + input_audio, audio_embeds, audio_sample_rate = inputs_shared.pop("input_audio"), inputs_shared.pop("audio_embeds"), inputs_shared.get("audio_sample_rate") + s2v_pose_video, s2v_pose_latents, motion_video = inputs_shared.pop("s2v_pose_video"), inputs_shared.pop("s2v_pose_latents"), inputs_shared.pop("motion_video") + + audio_input_positive = self.process_audio(pipe, input_audio, audio_sample_rate, num_frames, audio_embeds=audio_embeds) + inputs_posi.update(audio_input_positive) + inputs_nega.update({"audio_embeds": 0.0 * audio_input_positive["audio_embeds"]}) + + inputs_shared.update(self.process_motion_latents(pipe, height, width, tiled, tile_size, tile_stride, motion_video)) + inputs_shared.update(self.process_pose_cond(pipe, s2v_pose_video, num_frames, height, width, tiled, tile_size, tile_stride, s2v_pose_latents=s2v_pose_latents)) + return inputs_shared, inputs_posi, inputs_nega + + @staticmethod + def pre_calculate_audio_pose(pipe: WanVideoPipeline, input_audio=None, audio_sample_rate=16000, s2v_pose_video=None, num_frames=81, height=448, width=832, fps=16, tiled=True, tile_size=(30, 52), tile_stride=(15, 26)): + assert pipe.audio_encoder is not None and pipe.audio_processor is not None, "Please load audio encoder and audio processor first." + shapes = WanVideoUnit_ShapeChecker().process(pipe, height, width, num_frames) + height, width, num_frames = shapes["height"], shapes["width"], shapes["num_frames"] + unit = WanVideoUnit_S2V() + audio_embeds = unit.process_audio(pipe, input_audio, audio_sample_rate, num_frames, fps, return_all=True) + pose_latents = unit.process_pose_cond(pipe, s2v_pose_video, num_frames, height, width, num_repeats=len(audio_embeds), return_all=True, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride) + pose_latents = None if s2v_pose_video is None else pose_latents + return audio_embeds, pose_latents, len(audio_embeds) + + +class WanVideoPostUnit_S2V(PipelineUnit): + def __init__(self): + super().__init__(input_params=("latents", "motion_latents", "drop_motion_frames")) + + def process(self, pipe: WanVideoPipeline, latents, motion_latents, drop_motion_frames): + if pipe.audio_encoder is None or motion_latents is None or drop_motion_frames: + return {} + latents = torch.cat([motion_latents, latents[:,:,1:]], dim=2) + return {"latents": latents} + + +class WanVideoPostUnit_AnimateVideoSplit(PipelineUnit): + def __init__(self): + super().__init__(input_params=("input_video", "animate_pose_video", "animate_face_video", "animate_inpaint_video", "animate_mask_video")) + + def process(self, pipe: WanVideoPipeline, input_video, animate_pose_video, animate_face_video, animate_inpaint_video, animate_mask_video): + if input_video is None: + return {} + if animate_pose_video is not None: + animate_pose_video = animate_pose_video[:len(input_video) - 4] + if animate_face_video is not None: + animate_face_video = animate_face_video[:len(input_video) - 4] + if animate_inpaint_video is not None: + animate_inpaint_video = animate_inpaint_video[:len(input_video) - 4] + if animate_mask_video is not None: + animate_mask_video = animate_mask_video[:len(input_video) - 4] + return {"animate_pose_video": animate_pose_video, "animate_face_video": animate_face_video, "animate_inpaint_video": animate_inpaint_video, "animate_mask_video": animate_mask_video} + + +class WanVideoPostUnit_AnimatePoseLatents(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("animate_pose_video", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def process(self, pipe: WanVideoPipeline, animate_pose_video, tiled, tile_size, tile_stride): + if animate_pose_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + animate_pose_video = pipe.preprocess_video(animate_pose_video) + pose_latents = pipe.vae.encode(animate_pose_video, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + return {"pose_latents": pose_latents} + + +class WanVideoPostUnit_AnimateFacePixelValues(PipelineUnit): + def __init__(self): + super().__init__(take_over=True) + + def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega): + if inputs_shared.get("animate_face_video", None) is None: + return {} + inputs_posi["face_pixel_values"] = pipe.preprocess_video(inputs_shared["animate_face_video"]) + inputs_nega["face_pixel_values"] = torch.zeros_like(inputs_posi["face_pixel_values"]) - 1 + return inputs_shared, inputs_posi, inputs_nega + + +class WanVideoPostUnit_AnimateInpaint(PipelineUnit): + def __init__(self): + super().__init__( + input_params=("animate_inpaint_video", "animate_mask_video", "input_image", "tiled", "tile_size", "tile_stride"), + onload_model_names=("vae",) + ) + + def get_i2v_mask(self, lat_t, lat_h, lat_w, mask_len=1, mask_pixel_values=None, device="cuda"): + if mask_pixel_values is None: + msk = torch.zeros(1, (lat_t-1) * 4 + 1, lat_h, lat_w, device=device) + else: + msk = mask_pixel_values.clone() + msk[:, :mask_len] = 1 + msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1) + msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w) + msk = msk.transpose(1, 2)[0] + return msk + + def process(self, pipe: WanVideoPipeline, animate_inpaint_video, animate_mask_video, input_image, tiled, tile_size, tile_stride): + if animate_inpaint_video is None or animate_mask_video is None: + return {} + pipe.load_models_to_device(self.onload_model_names) + + bg_pixel_values = pipe.preprocess_video(animate_inpaint_video) + y_reft = pipe.vae.encode(bg_pixel_values, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)[0].to(dtype=pipe.torch_dtype, device=pipe.device) + _, lat_t, lat_h, lat_w = y_reft.shape + + ref_pixel_values = pipe.preprocess_video([input_image]) + ref_latents = pipe.vae.encode(ref_pixel_values, device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride).to(dtype=pipe.torch_dtype, device=pipe.device) + mask_ref = self.get_i2v_mask(1, lat_h, lat_w, 1, device=pipe.device) + y_ref = torch.concat([mask_ref, ref_latents[0]]).to(dtype=torch.bfloat16, device=pipe.device) + + mask_pixel_values = 1 - pipe.preprocess_video(animate_mask_video, max_value=1, min_value=0) + mask_pixel_values = rearrange(mask_pixel_values, "b c t h w -> (b t) c h w") + mask_pixel_values = torch.nn.functional.interpolate(mask_pixel_values, size=(lat_h, lat_w), mode='nearest') + mask_pixel_values = rearrange(mask_pixel_values, "(b t) c h w -> b t c h w", b=1)[:,:,0] + msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, 0, mask_pixel_values=mask_pixel_values, device=pipe.device) + + y_reft = torch.concat([msk_reft, y_reft]).to(dtype=torch.bfloat16, device=pipe.device) + y = torch.concat([y_ref, y_reft], dim=1).unsqueeze(0) + return {"y": y} + + +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.21862437e+04, 9.23041404e+03, -5.28275948e+02, 1.36987616e+01, -4.99875664e-02], + "Wan2.1-T2V-14B": [-3.03318725e+05, 4.90537029e+04, -2.65530556e+03, 5.87365115e+01, -3.15583525e-01], + "Wan2.1-I2V-14B-480P": [2.57151496e+05, -3.54229917e+04, 1.40286849e+03, -1.35890334e+01, 1.32517977e-01], + "Wan2.1-I2V-14B-720P": [ 8.10705460e+03, 2.13393892e+03, -3.72934672e+02, 1.66203073e+01, -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 + + + +class TemporalTiler_BCTHW: + def __init__(self): + pass + + def build_1d_mask(self, length, left_bound, right_bound, border_width): + x = torch.ones((length,)) + if border_width == 0: + return x + + shift = 0.5 + if not left_bound: + x[:border_width] = (torch.arange(border_width) + shift) / border_width + if not right_bound: + x[-border_width:] = torch.flip((torch.arange(border_width) + shift) / border_width, dims=(0,)) + return x + + def build_mask(self, data, is_bound, border_width): + _, _, T, _, _ = data.shape + t = self.build_1d_mask(T, is_bound[0], is_bound[1], border_width[0]) + mask = repeat(t, "T -> 1 1 T 1 1") + return mask + + def run(self, model_fn, sliding_window_size, sliding_window_stride, computation_device, computation_dtype, model_kwargs, tensor_names, batch_size=None): + tensor_names = [tensor_name for tensor_name in tensor_names if model_kwargs.get(tensor_name) is not None] + tensor_dict = {tensor_name: model_kwargs[tensor_name] for tensor_name in tensor_names} + B, C, T, H, W = tensor_dict[tensor_names[0]].shape + if batch_size is not None: + B *= batch_size + data_device, data_dtype = tensor_dict[tensor_names[0]].device, tensor_dict[tensor_names[0]].dtype + value = torch.zeros((B, C, T, H, W), device=data_device, dtype=data_dtype) + weight = torch.zeros((1, 1, T, 1, 1), device=data_device, dtype=data_dtype) + for t in range(0, T, sliding_window_stride): + if t - sliding_window_stride >= 0 and t - sliding_window_stride + sliding_window_size >= T: + continue + t_ = min(t + sliding_window_size, T) + model_kwargs.update({ + tensor_name: tensor_dict[tensor_name][:, :, t: t_:, :].to(device=computation_device, dtype=computation_dtype) \ + for tensor_name in tensor_names + }) + model_output = model_fn(**model_kwargs).to(device=data_device, dtype=data_dtype) + mask = self.build_mask( + model_output, + is_bound=(t == 0, t_ == T), + border_width=(sliding_window_size - sliding_window_stride,) + ).to(device=data_device, dtype=data_dtype) + value[:, :, t: t_, :, :] += model_output * mask + weight[:, :, t: t_, :, :] += mask + value /= weight + model_kwargs.update(tensor_dict) + return value + + + +def model_fn_wan_video( + dit: WanModel, + motion_controller: WanMotionControllerModel = None, + vace: VaceWanModel = None, + animate_adapter: WanAnimateAdapter = None, + latents: torch.Tensor = None, + token_prefix_latents: Optional[torch.Tensor] = None, + timestep: torch.Tensor = None, + context: torch.Tensor = None, + clip_feature: Optional[torch.Tensor] = None, + y: Optional[torch.Tensor] = None, + reference_latents = None, + vace_context = None, + vace_scale = 1.0, + audio_embeds: Optional[torch.Tensor] = None, + motion_latents: Optional[torch.Tensor] = None, + s2v_pose_latents: Optional[torch.Tensor] = None, + drop_motion_frames: bool = True, + tea_cache: TeaCache = None, + use_unified_sequence_parallel: bool = False, + motion_bucket_id: Optional[torch.Tensor] = None, + pose_latents=None, + face_pixel_values=None, + sliding_window_size: Optional[int] = None, + sliding_window_stride: Optional[int] = None, + cfg_merge: bool = False, + use_gradient_checkpointing: bool = False, + use_gradient_checkpointing_offload: bool = False, + control_camera_latents_input = None, + fuse_vae_embedding_in_latents: bool = False, + token_prefix_clean_timestep: bool = False, + token_prefix_aligned_rope: bool = False, + token_prefix_block_self_attention: bool = False, + causal_reference_attention: bool = False, + clean_history_latent_frames: int = 0, + condition_latents: Optional[torch.Tensor] = None, + channel_concat_condition: bool = False, + **kwargs, +): + if sliding_window_size is not None and sliding_window_stride is not None: + model_kwargs = dict( + dit=dit, + motion_controller=motion_controller, + vace=vace, + latents=latents, + token_prefix_latents=token_prefix_latents, + timestep=timestep, + context=context, + clip_feature=clip_feature, + y=y, + reference_latents=reference_latents, + vace_context=vace_context, + vace_scale=vace_scale, + tea_cache=tea_cache, + use_unified_sequence_parallel=use_unified_sequence_parallel, + motion_bucket_id=motion_bucket_id, + fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents, + token_prefix_clean_timestep=token_prefix_clean_timestep, + token_prefix_aligned_rope=token_prefix_aligned_rope, + token_prefix_block_self_attention=token_prefix_block_self_attention, + clean_history_latent_frames=clean_history_latent_frames, + condition_latents=condition_latents, + channel_concat_condition=channel_concat_condition, + ) + return TemporalTiler_BCTHW().run( + model_fn_wan_video, + sliding_window_size, sliding_window_stride, + latents.device, latents.dtype, + model_kwargs=model_kwargs, + tensor_names=["latents", "y"], + batch_size=2 if cfg_merge else 1 + ) + # wan2.2 s2v + if audio_embeds is not None: + return model_fn_wans2v( + dit=dit, + latents=latents, + timestep=timestep, + context=context, + audio_embeds=audio_embeds, + motion_latents=motion_latents, + s2v_pose_latents=s2v_pose_latents, + drop_motion_frames=drop_motion_frames, + use_gradient_checkpointing_offload=use_gradient_checkpointing_offload, + use_gradient_checkpointing=use_gradient_checkpointing, + use_unified_sequence_parallel=use_unified_sequence_parallel, + ) + + if use_unified_sequence_parallel: + import torch.distributed as dist + from xfuser.core.distributed import (get_sequence_parallel_rank, + get_sequence_parallel_world_size, + get_sp_group) + + has_reference_latents = reference_latents is not None + separated_fused_timestep = bool(dit.seperated_timestep and fuse_vae_embedding_in_latents) + separated_prefix_timestep = bool(token_prefix_clean_timestep and token_prefix_latents is not None and not has_reference_latents) + if not separated_fused_timestep and not separated_prefix_timestep: + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep)) + t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim)) + + # Motion Controller + if motion_bucket_id is not None and motion_controller is not None: + t_mod = t_mod + motion_controller(motion_bucket_id).unflatten(1, (6, dit.dim)) + context = dit.text_embedding(context) + + x = latents + # Merged cfg + if x.shape[0] != context.shape[0]: + x = torch.concat([x] * context.shape[0], dim=0) + if timestep.shape[0] != context.shape[0]: + timestep = torch.concat([timestep] * context.shape[0], dim=0) + if channel_concat_condition: + if condition_latents is None: + raise ValueError("channel_concat_condition=True requires condition_latents") + condition_latents = condition_latents.to(device=x.device, dtype=x.dtype) + if condition_latents.shape[0] != x.shape[0]: + if x.shape[0] % condition_latents.shape[0] != 0: + raise ValueError( + f"Cannot expand condition batch {condition_latents.shape[0]} " + f"to latent batch {x.shape[0]}" + ) + condition_latents = torch.cat( + [condition_latents] * (x.shape[0] // condition_latents.shape[0]), dim=0 + ) + if condition_latents.shape[2:] != x.shape[2:]: + raise ValueError( + f"Condition latent shape {tuple(condition_latents.shape)} does not match " + f"bridge latent shape {tuple(x.shape)}" + ) + x = torch.cat([x, condition_latents], dim=1) + + # Image Embedding + if y is not None and dit.require_vae_embedding: + x = torch.cat([x, y], dim=1) + if clip_feature is not None and dit.require_clip_embedding: + clip_embdding = dit.img_emb(clip_feature) + context = torch.cat([clip_embdding, context], dim=1) + + # Camera control + x = dit.patchify(x, control_camera_latents_input) + + # Animate + if animate_adapter is not None: + x, motion_vec = animate_adapter.after_patch_embedding(x, pose_latents, face_pixel_values) + else: + motion_vec = None + + # Patchify. For token-concat conditioning, the clean original video is a + # prefix stream and the Brownian-bridge video is the prediction stream. + f, h, w = x.shape[2:] + target_frames = int(f) + x = rearrange(x, 'b c f h w -> b (f h w) c').contiguous() + prefix_token_count = 0 + prefix_frames = 0 + prefix_h = 0 + prefix_w = 0 + if token_prefix_latents is not None: + prefix_latents = token_prefix_latents.to(device=latents.device, dtype=latents.dtype) + if channel_concat_condition and prefix_latents.shape[1] * 2 == int(dit.in_dim): + prefix_latents = torch.cat([prefix_latents, torch.zeros_like(prefix_latents)], dim=1) + if prefix_latents.shape[0] != latents.shape[0]: + if latents.shape[0] % prefix_latents.shape[0] != 0: + raise ValueError( + f"Cannot expand token prefix batch {prefix_latents.shape[0]} " + f"to latent batch {latents.shape[0]}" + ) + prefix_latents = torch.cat( + [prefix_latents] * (latents.shape[0] // prefix_latents.shape[0]), dim=0 + ) + prefix_grid = dit.patchify(prefix_latents) + prefix_frames, prefix_h, prefix_w = prefix_grid.shape[2:] + prefix_tokens = rearrange(prefix_grid, 'b c f h w -> b (f h w) c').contiguous() + prefix_token_count = int(prefix_tokens.shape[1]) + x = torch.cat([prefix_tokens, x], dim=1) + f += int(prefix_frames) + + if (separated_fused_timestep or separated_prefix_timestep) and not has_reference_latents: + target_clean_frames = 1 + max(int(clean_history_latent_frames), 0) if separated_fused_timestep else 0 + target_clean_frames = min(target_clean_frames, int(latents.shape[2])) + prefix_tokens_per_frame = int(prefix_h * prefix_w) if prefix_token_count else 0 + target_tokens_per_frame = int(h * w) + token_timestep_parts = [] + if prefix_token_count: + prefix_time = make_device_tensor([0.0] * int(prefix_frames), latents.device, latents.dtype) + token_timestep_parts.append(prefix_time.repeat_interleave(prefix_tokens_per_frame)) + target_time = make_device_tensor( + [0.0] * target_clean_frames + + [float(timestep.flatten()[0].item())] * (int(latents.shape[2]) - target_clean_frames), + latents.device, + latents.dtype, + ) + token_timestep_parts.append(target_time.repeat_interleave(target_tokens_per_frame)) + token_timestep = torch.cat(token_timestep_parts, dim=0) + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, token_timestep).unsqueeze(0)) + if t.shape[0] != x.shape[0]: + t = torch.cat([t] * x.shape[0], dim=0) + t_mod = dit.time_projection(t).unflatten(2, (6, dit.dim)) + + # Reference video token stream follows latent tokens. + reference_token_count = 0 + if reference_latents is not None: + if reference_latents.ndim != 5 or reference_latents.shape[2:] != latents.shape[2:]: + raise ValueError("reference_latents must match latents in B,C,F,H,W") + ref_grid = dit.patchify(reference_latents.to(dtype=latents.dtype)) + ref_tokens = rearrange(ref_grid, 'b c f h w -> b (f h w) c').contiguous() + reference_token_count = int(ref_tokens.shape[1]) + x = torch.cat([x, ref_tokens], dim=1) + + def build_rope_grid(frame_count: int, grid_h: int, grid_w: int) -> torch.Tensor: + rope_freqs = dit.get_rope_freqs(x.device) + return torch.cat([ + rope_freqs[0][:frame_count].view(frame_count, 1, 1, -1).expand(frame_count, grid_h, grid_w, -1), + rope_freqs[1][:grid_h].view(1, grid_h, 1, -1).expand(frame_count, grid_h, grid_w, -1), + rope_freqs[2][:grid_w].view(1, 1, grid_w, -1).expand(frame_count, grid_h, grid_w, -1), + ], dim=-1).reshape(frame_count * grid_h * grid_w, 1, -1) + + if token_prefix_aligned_rope and prefix_frames: + # Keep token order [reference, prefix, target], but reset the temporal + # RoPE coordinate for each stream. Corresponding prefix/target patches + # therefore receive exactly the same (time, height, width) rotation. + rope_streams = [] + if has_reference_latents: + rope_streams.append(build_rope_grid(1, h, w)) + rope_streams.extend([ + build_rope_grid(int(prefix_frames), int(prefix_h), int(prefix_w)), + build_rope_grid(target_frames, h, w), + ]) + freqs = torch.cat(rope_streams, dim=0).to(x.device) + else: + freqs = build_rope_grid(target_frames, h, w).to(x.device) + if reference_token_count: + freqs = torch.cat([freqs, freqs], dim=0) + + attn_mask = None + if reference_token_count: + spec = CausalReferenceSequenceAttentionSpec if causal_reference_attention else ReferenceSequenceAttentionSpec + attn_mask = spec(latent_frames=target_frames, tokens_per_frame=int(h * w)) + if token_prefix_block_self_attention and prefix_token_count: + if has_reference_latents: + raise NotImplementedError( + "token_prefix_block_self_attention is currently only supported without reference_latents" + ) + attn_mask = build_token_prefix_attention_spec( + prefix_token_count=prefix_token_count, + target_token_count=int(target_frames * h * w), + ) + if use_unified_sequence_parallel: + raise NotImplementedError("Token-prefix attention masks do not support unified sequence parallelism") + + # TeaCache + if tea_cache is not None: + tea_cache_update = tea_cache.check(dit, x, t_mod) + else: + tea_cache_update = False + + if vace_context is not None: + vace_hints = vace( + x, vace_context, context, t_mod, freqs, + use_gradient_checkpointing=use_gradient_checkpointing, + use_gradient_checkpointing_offload=use_gradient_checkpointing_offload + ) + + # Optional layer-aligned reference stream. It is kept as an explicit + # checkpoint input/output instead of mutable module state, so recomputation + # during gradient checkpointing is deterministic. + reference_condition = getattr(dit, "_reference_condition", None) + reference_x = None + if getattr(dit, "_reference_adapters_enabled", False) and reference_condition is not None: + reference_x = reference_condition.reference_tokens.to(dtype=x.dtype, device=x.device) + if reference_x.shape[0] != x.shape[0]: + if x.shape[0] % reference_x.shape[0] != 0: + raise ValueError( + f"Cannot expand reference batch {reference_x.shape[0]} to target batch {x.shape[0]}" + ) + reference_x = torch.cat([reference_x] * (x.shape[0] // reference_x.shape[0]), dim=0) + if use_unified_sequence_parallel: + raise NotImplementedError( + "Dual-stream frame-wise pair attention does not yet support unified sequence parallelism" + ) + # TeaCache may skip transformer blocks and would therefore skip the + # evolving reference stream and frame-wise pair-attention layers. + tea_cache_update = False + if reference_x is not None and attn_mask is not None: + raise NotImplementedError("Dual-stream reference adapters do not support token-prefix attention masks") + + # blocks + if use_unified_sequence_parallel: + if dist.is_initialized() and dist.get_world_size() > 1: + chunks = torch.chunk(x, get_sequence_parallel_world_size(), dim=1) + pad_shape = chunks[0].shape[1] - chunks[-1].shape[1] + chunks = [torch.nn.functional.pad(chunk, (0, 0, 0, chunks[0].shape[1]-chunk.shape[1]), value=0) for chunk in chunks] + x = chunks[get_sequence_parallel_rank()] + if tea_cache_update: + x = tea_cache.update(x) + else: + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + def create_dual_custom_forward(module): + def custom_forward(*inputs): + return module.forward_dual(*inputs) + return custom_forward + + for block_id, block in enumerate(dit.blocks): + # Block + dual_stream = reference_x is not None and hasattr(block, "forward_dual") + if dual_stream and use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x, reference_x = torch.utils.checkpoint.checkpoint( + create_dual_custom_forward(block), + x, reference_x, context, t_mod, freqs, + use_reentrant=False, + ) + elif dual_stream and use_gradient_checkpointing: + x, reference_x = torch.utils.checkpoint.checkpoint( + create_dual_custom_forward(block), + x, reference_x, context, t_mod, freqs, + use_reentrant=False, + ) + elif dual_stream: + x, reference_x = block.forward_dual(x, reference_x, context, t_mod, freqs) + elif use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + if attn_mask is None: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, + use_reentrant=False, + ) + else: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, freqs, attn_mask, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, freqs, attn_mask=attn_mask) + + # VACE + if vace_context is not None and block_id in vace.vace_layers_mapping: + current_vace_hint = vace_hints[vace.vace_layers_mapping[block_id]] + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + current_vace_hint = torch.chunk(current_vace_hint, get_sequence_parallel_world_size(), dim=1)[get_sequence_parallel_rank()] + current_vace_hint = torch.nn.functional.pad(current_vace_hint, (0, 0, 0, chunks[0].shape[1] - current_vace_hint.shape[1]), value=0) + x = x + current_vace_hint * vace_scale + + # Animate + if animate_adapter is not None and pose_latents is not None and face_pixel_values is not None: + x = animate_adapter.after_transformer_block(block_id, x, motion_vec) + if tea_cache is not None: + tea_cache.store(x) + + x = dit.head(x, t) + if use_unified_sequence_parallel: + if dist.is_initialized() and dist.get_world_size() > 1: + x = get_sp_group().all_gather(x, dim=1) + x = x[:, :-pad_shape] if pad_shape > 0 else x + # Remove a token-concat prefix. The model predicts both streams, but only + # the edited-video stream is part of the bridge output. + if prefix_token_count: + x = x[:, prefix_token_count:] + f -= prefix_frames + # Return only predicted latent tokens; the reference stream has no head output. + if reference_token_count: + x = x[:, :target_frames * h * w] + x = dit.unpatchify(x, (target_frames, h, w)) + return x + + +def model_fn_wans2v( + dit, + latents, + timestep, + context, + audio_embeds, + motion_latents, + s2v_pose_latents, + drop_motion_frames=True, + use_gradient_checkpointing_offload=False, + use_gradient_checkpointing=False, + use_unified_sequence_parallel=False, +): + if use_unified_sequence_parallel: + import torch.distributed as dist + from xfuser.core.distributed import (get_sequence_parallel_rank, + get_sequence_parallel_world_size, + get_sp_group) + origin_ref_latents = latents[:, :, 0:1] + x = latents[:, :, 1:] + + # context embedding + context = dit.text_embedding(context) + + # audio encode + audio_emb_global, merged_audio_emb = dit.cal_audio_emb(audio_embeds) + + # x and s2v_pose_latents + s2v_pose_latents = torch.zeros_like(x) if s2v_pose_latents is None else s2v_pose_latents + x, (f, h, w) = dit.patchify(dit.patch_embedding(x) + dit.cond_encoder(s2v_pose_latents)) + seq_len_x = seq_len_x_global = x.shape[1] # global used for unified sequence parallel + + # reference image + ref_latents, (rf, rh, rw) = dit.patchify(dit.patch_embedding(origin_ref_latents)) + grid_sizes = dit.get_grid_sizes((f, h, w), (rf, rh, rw)) + x = torch.cat([x, ref_latents], dim=1) + # mask + mask = torch.cat([torch.zeros([1, seq_len_x]), torch.ones([1, ref_latents.shape[1]])], dim=1).to(torch.long).to(x.device) + # freqs + pre_compute_freqs = rope_precompute(x.detach().view(1, x.size(1), dit.num_heads, dit.dim // dit.num_heads), grid_sizes, dit.freqs, start=None) + # motion + x, pre_compute_freqs, mask = dit.inject_motion(x, pre_compute_freqs, mask, motion_latents, drop_motion_frames=drop_motion_frames, add_last_motion=2) + + x = x + dit.trainable_cond_mask(mask).to(x.dtype) + + # tmod + timestep = torch.cat([timestep, torch.zeros([1], dtype=timestep.dtype, device=timestep.device)]) + t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep)) + t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim)).unsqueeze(2).transpose(0, 2) + + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + world_size, sp_rank = get_sequence_parallel_world_size(), get_sequence_parallel_rank() + assert x.shape[1] % world_size == 0, f"the dimension after chunk must be divisible by world size, but got {x.shape[1]} and {get_sequence_parallel_world_size()}" + x = torch.chunk(x, world_size, dim=1)[sp_rank] + seg_idxs = [0] + list(torch.cumsum(torch.tensor([x.shape[1]] * world_size), dim=0).cpu().numpy()) + seq_len_x_list = [min(max(0, seq_len_x - seg_idxs[i]), x.shape[1]) for i in range(len(seg_idxs)-1)] + seq_len_x = seq_len_x_list[sp_rank] + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + return custom_forward + + for block_id, block in enumerate(dit.blocks): + if use_gradient_checkpointing_offload: + with torch.autograd.graph.save_on_cpu(): + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, seq_len_x, pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + elif use_gradient_checkpointing: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, context, t_mod, seq_len_x, pre_compute_freqs[0], + use_reentrant=False, + ) + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)), + x, + use_reentrant=False, + ) + else: + x = block(x, context, t_mod, seq_len_x, pre_compute_freqs[0]) + x = dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x_global, use_unified_sequence_parallel) + + if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1: + x = get_sp_group().all_gather(x, dim=1) + + x = x[:, :seq_len_x_global] + x = dit.head(x, t[:-1]) + x = dit.unpatchify(x, (f, h, w)) + # make compatible with wan video + x = torch.cat([origin_ref_latents, x], dim=2) + return x diff --git a/releases/2026-10-20-code/diffsynth/prompters/__init__.py b/releases/2026-10-20-code/diffsynth/prompters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5dca212a6a66071310968aa37badc7bed2b6e3 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/prompters/__init__.py @@ -0,0 +1 @@ +from .wan_prompter import WanPrompter diff --git a/releases/2026-10-20-code/diffsynth/prompters/base_prompter.py b/releases/2026-10-20-code/diffsynth/prompters/base_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..136abd18fabdb04e618f59801420c9ce5fb94634 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/prompters/base_prompter.py @@ -0,0 +1,70 @@ +from ..models.model_manager import ModelManager +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: ModelManager, 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:ModelManager,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 \ No newline at end of file diff --git a/releases/2026-10-20-code/diffsynth/prompters/wan_prompter.py b/releases/2026-10-20-code/diffsynth/prompters/wan_prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..b65678f74d5b0cba5a96d499461f3738b95d3a81 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/prompters/wan_prompter.py @@ -0,0 +1,106 @@ +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) + seq_lens = mask.cpu().gt(0).sum(dim=1).long() + prompt_emb = self.text_encoder(ids.to(device), mask.to(device)) + for i, v in enumerate(seq_lens): + prompt_emb[i, v:] = 0 + return prompt_emb diff --git a/releases/2026-10-20-code/diffsynth/schedulers/__init__.py b/releases/2026-10-20-code/diffsynth/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..744c8dd4bd216c137583dd6f5091d2da731fadf8 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/schedulers/__init__.py @@ -0,0 +1 @@ +from .flow_match import FlowMatchScheduler diff --git a/releases/2026-10-20-code/diffsynth/schedulers/flow_match.py b/releases/2026-10-20-code/diffsynth/schedulers/flow_match.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb2405a0069586595a675896876ce6ad37054b3 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/schedulers/flow_match.py @@ -0,0 +1,125 @@ +import torch, math + + + +class FlowMatchScheduler(): + + def __init__( + self, + num_inference_steps=100, + num_train_timesteps=1000, + shift=3.0, + sigma_max=1.0, + sigma_min=0.003/1.002, + inverse_timesteps=False, + extra_one_step=False, + reverse_sigmas=False, + exponential_shift=False, + exponential_shift_mu=None, + shift_terminal=None, + ): + self.num_train_timesteps = num_train_timesteps + self.shift = shift + self.sigma_max = sigma_max + self.sigma_min = sigma_min + self.inverse_timesteps = inverse_timesteps + self.extra_one_step = extra_one_step + self.reverse_sigmas = reverse_sigmas + self.exponential_shift = exponential_shift + self.exponential_shift_mu = exponential_shift_mu + self.shift_terminal = shift_terminal + self.set_timesteps(num_inference_steps) + + + def set_timesteps(self, num_inference_steps=100, denoising_strength=1.0, training=False, shift=None, dynamic_shift_len=None, exponential_shift_mu=None): + if shift is not None: + self.shift = shift + sigma_start = self.sigma_min + (self.sigma_max - self.sigma_min) * denoising_strength + if self.extra_one_step: + self.sigmas = torch.linspace(sigma_start, self.sigma_min, num_inference_steps + 1)[:-1] + else: + self.sigmas = torch.linspace(sigma_start, self.sigma_min, num_inference_steps) + if self.inverse_timesteps: + self.sigmas = torch.flip(self.sigmas, dims=[0]) + if self.exponential_shift: + if exponential_shift_mu is not None: + mu = exponential_shift_mu + elif dynamic_shift_len is not None: + mu = self.calculate_shift(dynamic_shift_len) + else: + mu = self.exponential_shift_mu + self.sigmas = math.exp(mu) / (math.exp(mu) + (1 / self.sigmas - 1)) + else: + self.sigmas = self.shift * self.sigmas / (1 + (self.shift - 1) * self.sigmas) + if self.shift_terminal is not None: + one_minus_z = 1 - self.sigmas + scale_factor = one_minus_z[-1] / (1 - self.shift_terminal) + self.sigmas = 1 - (one_minus_z / scale_factor) + if self.reverse_sigmas: + self.sigmas = 1 - self.sigmas + self.timesteps = self.sigmas * self.num_train_timesteps + if training: + x = self.timesteps + y = torch.exp(-2 * ((x - num_inference_steps / 2) / num_inference_steps) ** 2) + y_shifted = y - y.min() + bsmntw_weighing = y_shifted * (num_inference_steps / y_shifted.sum()) + self.linear_timesteps_weights = bsmntw_weighing + self.training = True + else: + self.training = False + + + 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_ = 1 if (self.inverse_timesteps or self.reverse_sigmas) else 0 + else: + sigma_ = self.sigmas[timestep_id + 1] + prev_sample = sample + model_output * (sigma_ - sigma) + return prev_sample + + + def return_to_timestep(self, timestep, sample, sample_stablized): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + model_output = (sample - sample_stablized) / sigma + return model_output + + + def add_noise(self, original_samples, noise, timestep): + if isinstance(timestep, torch.Tensor): + timestep = timestep.cpu() + timestep_id = torch.argmin((self.timesteps - timestep).abs()) + sigma = self.sigmas[timestep_id] + sample = (1 - sigma) * original_samples + sigma * noise + return sample + + + def training_target(self, sample, noise, timestep): + target = noise - sample + return target + + + def training_weight(self, timestep): + timestep_id = torch.argmin((self.timesteps - timestep.to(self.timesteps.device)).abs()) + weights = self.linear_timesteps_weights[timestep_id] + return weights + + + def calculate_shift( + self, + image_seq_len, + base_seq_len: int = 256, + max_seq_len: int = 8192, + base_shift: float = 0.5, + max_shift: float = 0.9, + ): + m = (max_shift - base_shift) / (max_seq_len - base_seq_len) + b = base_shift - m * base_seq_len + mu = image_seq_len * m + b + return mu diff --git a/releases/2026-10-20-code/diffsynth/trainers/__init__.py b/releases/2026-10-20-code/diffsynth/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/releases/2026-10-20-code/diffsynth/trainers/unified_dataset.py b/releases/2026-10-20-code/diffsynth/trainers/unified_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0083f4483d8c107c4495c9c01e2eff2d69f0a127 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/trainers/unified_dataset.py @@ -0,0 +1,337 @@ +import torch, torchvision, imageio, os, json, pandas +import imageio.v3 as iio +from PIL import Image + + + +class DataProcessingPipeline: + def __init__(self, operators=None): + self.operators: list[DataProcessingOperator] = [] if operators is None else operators + + def __call__(self, data): + for operator in self.operators: + data = operator(data) + return data + + def __rshift__(self, pipe): + if isinstance(pipe, DataProcessingOperator): + pipe = DataProcessingPipeline([pipe]) + return DataProcessingPipeline(self.operators + pipe.operators) + + + +class DataProcessingOperator: + def __call__(self, data): + raise NotImplementedError("DataProcessingOperator cannot be called directly.") + + def __rshift__(self, pipe): + if isinstance(pipe, DataProcessingOperator): + pipe = DataProcessingPipeline([pipe]) + return DataProcessingPipeline([self]).__rshift__(pipe) + + + +class DataProcessingOperatorRaw(DataProcessingOperator): + def __call__(self, data): + return data + + + +class ToInt(DataProcessingOperator): + def __call__(self, data): + return int(data) + + + +class ToFloat(DataProcessingOperator): + def __call__(self, data): + return float(data) + + + +class ToStr(DataProcessingOperator): + def __init__(self, none_value=""): + self.none_value = none_value + + def __call__(self, data): + if data is None: data = self.none_value + return str(data) + + + +class LoadImage(DataProcessingOperator): + def __init__(self, convert_RGB=True): + self.convert_RGB = convert_RGB + + def __call__(self, data: str): + image = Image.open(data) + if self.convert_RGB: image = image.convert("RGB") + return image + + + +class ImageCropAndResize(DataProcessingOperator): + def __init__(self, height, width, max_pixels, height_division_factor, width_division_factor): + self.height = height + self.width = width + self.max_pixels = max_pixels + self.height_division_factor = height_division_factor + self.width_division_factor = width_division_factor + + def crop_and_resize(self, image, target_height, target_width): + width, height = image.size + scale = max(target_width / width, target_height / height) + image = torchvision.transforms.functional.resize( + image, + (round(height*scale), round(width*scale)), + interpolation=torchvision.transforms.InterpolationMode.BILINEAR + ) + image = torchvision.transforms.functional.center_crop(image, (target_height, target_width)) + return image + + def get_height_width(self, image): + if self.height is None or self.width is None: + width, height = image.size + if width * height > self.max_pixels: + scale = (width * height / self.max_pixels) ** 0.5 + height, width = int(height / scale), int(width / scale) + height = height // self.height_division_factor * self.height_division_factor + width = width // self.width_division_factor * self.width_division_factor + else: + height, width = self.height, self.width + return height, width + + + def __call__(self, data: Image.Image): + image = self.crop_and_resize(data, *self.get_height_width(data)) + return image + + + +class ToList(DataProcessingOperator): + def __call__(self, data): + return [data] + + + +class LoadVideo(DataProcessingOperator): + def __init__(self, num_frames=81, time_division_factor=4, time_division_remainder=1, frame_processor=lambda x: x): + self.num_frames = num_frames + self.time_division_factor = time_division_factor + self.time_division_remainder = time_division_remainder + # frame_processor is build in the video loader for high efficiency. + self.frame_processor = frame_processor + + def get_num_frames(self, reader): + num_frames = self.num_frames + if int(reader.count_frames()) < num_frames: + num_frames = int(reader.count_frames()) + while num_frames > 1 and num_frames % self.time_division_factor != self.time_division_remainder: + num_frames -= 1 + return num_frames + + def __call__(self, data: str): + reader = imageio.get_reader(data) + num_frames = self.get_num_frames(reader) + frames = [] + for frame_id in range(num_frames): + frame = reader.get_data(frame_id) + frame = Image.fromarray(frame) + frame = self.frame_processor(frame) + frames.append(frame) + reader.close() + return frames + + + +class SequencialProcess(DataProcessingOperator): + def __init__(self, operator=lambda x: x): + self.operator = operator + + def __call__(self, data): + return [self.operator(i) for i in data] + + + +class LoadGIF(DataProcessingOperator): + def __init__(self, num_frames=81, time_division_factor=4, time_division_remainder=1, frame_processor=lambda x: x): + self.num_frames = num_frames + self.time_division_factor = time_division_factor + self.time_division_remainder = time_division_remainder + # frame_processor is build in the video loader for high efficiency. + self.frame_processor = frame_processor + + def get_num_frames(self, path): + num_frames = self.num_frames + images = iio.imread(path, mode="RGB") + if len(images) < num_frames: + num_frames = len(images) + while num_frames > 1 and num_frames % self.time_division_factor != self.time_division_remainder: + num_frames -= 1 + return num_frames + + def __call__(self, data: str): + num_frames = self.get_num_frames(data) + frames = [] + images = iio.imread(data, mode="RGB") + for img in images: + frame = Image.fromarray(img) + frame = self.frame_processor(frame) + frames.append(frame) + if len(frames) >= num_frames: + break + return frames + + + +class RouteByExtensionName(DataProcessingOperator): + def __init__(self, operator_map): + self.operator_map = operator_map + + def __call__(self, data: str): + file_ext_name = data.split(".")[-1].lower() + for ext_names, operator in self.operator_map: + if ext_names is None or file_ext_name in ext_names: + return operator(data) + raise ValueError(f"Unsupported file: {data}") + + + +class RouteByType(DataProcessingOperator): + def __init__(self, operator_map): + self.operator_map = operator_map + + def __call__(self, data): + for dtype, operator in self.operator_map: + if dtype is None or isinstance(data, dtype): + return operator(data) + raise ValueError(f"Unsupported data: {data}") + + + +class LoadTorchPickle(DataProcessingOperator): + def __init__(self, map_location="cpu"): + self.map_location = map_location + + def __call__(self, data): + return torch.load(data, map_location=self.map_location, weights_only=False) + + + +class ToAbsolutePath(DataProcessingOperator): + def __init__(self, base_path=""): + self.base_path = base_path + + def __call__(self, data): + return os.path.join(self.base_path, data) + + + +class UnifiedDataset(torch.utils.data.Dataset): + def __init__( + self, + base_path=None, metadata_path=None, + repeat=1, + data_file_keys=tuple(), + main_data_operator=lambda x: x, + special_operator_map=None, + ): + self.base_path = base_path + self.metadata_path = metadata_path + self.repeat = repeat + self.data_file_keys = data_file_keys + self.main_data_operator = main_data_operator + self.cached_data_operator = LoadTorchPickle() + self.special_operator_map = {} if special_operator_map is None else special_operator_map + self.data = [] + self.cached_data = [] + self.load_from_cache = metadata_path is None + self.load_metadata(metadata_path) + + @staticmethod + def default_image_operator( + base_path="", + max_pixels=1920*1080, height=None, width=None, + height_division_factor=16, width_division_factor=16, + ): + return RouteByType(operator_map=[ + (str, ToAbsolutePath(base_path) >> LoadImage() >> ImageCropAndResize(height, width, max_pixels, height_division_factor, width_division_factor)), + (list, SequencialProcess(ToAbsolutePath(base_path) >> LoadImage() >> ImageCropAndResize(height, width, max_pixels, height_division_factor, width_division_factor))), + ]) + + @staticmethod + def default_video_operator( + base_path="", + max_pixels=1920*1080, height=None, width=None, + height_division_factor=16, width_division_factor=16, + num_frames=81, time_division_factor=4, time_division_remainder=1, + ): + return RouteByType(operator_map=[ + (str, ToAbsolutePath(base_path) >> RouteByExtensionName(operator_map=[ + (("jpg", "jpeg", "png", "webp"), LoadImage() >> ImageCropAndResize(height, width, max_pixels, height_division_factor, width_division_factor) >> ToList()), + (("gif",), LoadGIF( + num_frames, time_division_factor, time_division_remainder, + frame_processor=ImageCropAndResize(height, width, max_pixels, height_division_factor, width_division_factor), + )), + (("mp4", "avi", "mov", "wmv", "mkv", "flv", "webm"), LoadVideo( + num_frames, time_division_factor, time_division_remainder, + frame_processor=ImageCropAndResize(height, width, max_pixels, height_division_factor, width_division_factor), + )), + ])), + ]) + + def search_for_cached_data_files(self, path): + for file_name in os.listdir(path): + subpath = os.path.join(path, file_name) + if os.path.isdir(subpath): + self.search_for_cached_data_files(subpath) + elif subpath.endswith(".pth"): + self.cached_data.append(subpath) + + def load_metadata(self, metadata_path): + if metadata_path is None: + print("No metadata_path. Searching for cached data files.") + self.search_for_cached_data_files(self.base_path) + print(f"{len(self.cached_data)} cached data files found.") + elif metadata_path.endswith(".json"): + with open(metadata_path, "r") as f: + metadata = json.load(f) + self.data = metadata + elif metadata_path.endswith(".jsonl"): + metadata = [] + with open(metadata_path, 'r') as f: + for line in f: + metadata.append(json.loads(line.strip())) + self.data = metadata + else: + metadata = pandas.read_csv(metadata_path) + self.data = [metadata.iloc[i].to_dict() for i in range(len(metadata))] + + def __getitem__(self, data_id): + if self.load_from_cache: + data = self.cached_data[data_id % len(self.cached_data)] + data = self.cached_data_operator(data) + else: + data = self.data[data_id % len(self.data)].copy() + for key in self.data_file_keys: + if key in data: + if key in self.special_operator_map: + data[key] = self.special_operator_map[key](data[key]) + elif key in self.data_file_keys: + data[key] = self.main_data_operator(data[key]) + return data + + def __len__(self): + if self.load_from_cache: + return len(self.cached_data) * self.repeat + else: + return len(self.data) * self.repeat + + def check_data_equal(self, data1, data2): + # Debug only + if len(data1) != len(data2): + return False + for k in data1: + if data1[k] != data2[k]: + return False + return True diff --git a/releases/2026-10-20-code/diffsynth/trainers/utils.py b/releases/2026-10-20-code/diffsynth/trainers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..78128619049d91fec37960fc2f91620d4b9336c4 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/trainers/utils.py @@ -0,0 +1,699 @@ +import imageio, os, torch, warnings, torchvision, argparse, json +from ..utils import ModelConfig +from ..models.utils import load_state_dict +try: + from peft import LoraConfig, inject_adapter_in_model +except ModuleNotFoundError: + LoraConfig = None + inject_adapter_in_model = None +from PIL import Image +import pandas as pd +from tqdm import tqdm +from accelerate import Accelerator +from accelerate.utils import DistributedDataParallelKwargs + + + +class ImageDataset(torch.utils.data.Dataset): + def __init__( + self, + base_path=None, metadata_path=None, + max_pixels=1920*1080, height=None, width=None, + height_division_factor=16, width_division_factor=16, + data_file_keys=("image",), + image_file_extension=("jpg", "jpeg", "png", "webp"), + repeat=1, + args=None, + ): + if args is not None: + base_path = args.dataset_base_path + metadata_path = args.dataset_metadata_path + height = args.height + width = args.width + max_pixels = args.max_pixels + data_file_keys = args.data_file_keys.split(",") + repeat = args.dataset_repeat + + self.base_path = base_path + self.max_pixels = max_pixels + self.height = height + self.width = width + self.height_division_factor = height_division_factor + self.width_division_factor = width_division_factor + self.data_file_keys = data_file_keys + self.image_file_extension = image_file_extension + self.repeat = repeat + + if height is not None and width is not None: + print("Height and width are fixed. Setting `dynamic_resolution` to False.") + self.dynamic_resolution = False + elif height is None and width is None: + print("Height and width are none. Setting `dynamic_resolution` to True.") + self.dynamic_resolution = True + + if metadata_path is None: + print("No metadata. Trying to generate it.") + metadata = self.generate_metadata(base_path) + print(f"{len(metadata)} lines in metadata.") + self.data = [metadata.iloc[i].to_dict() for i in range(len(metadata))] + elif metadata_path.endswith(".json"): + with open(metadata_path, "r") as f: + metadata = json.load(f) + self.data = metadata + elif metadata_path.endswith(".jsonl"): + metadata = [] + with open(metadata_path, 'r') as f: + for line in tqdm(f): + metadata.append(json.loads(line.strip())) + self.data = metadata + else: + metadata = pd.read_csv(metadata_path) + self.data = [metadata.iloc[i].to_dict() for i in range(len(metadata))] + + + def generate_metadata(self, folder): + image_list, prompt_list = [], [] + file_set = set(os.listdir(folder)) + for file_name in file_set: + if "." not in file_name: + continue + file_ext_name = file_name.split(".")[-1].lower() + file_base_name = file_name[:-len(file_ext_name)-1] + if file_ext_name not in self.image_file_extension: + continue + prompt_file_name = file_base_name + ".txt" + if prompt_file_name not in file_set: + continue + with open(os.path.join(folder, prompt_file_name), "r", encoding="utf-8") as f: + prompt = f.read().strip() + image_list.append(file_name) + prompt_list.append(prompt) + metadata = pd.DataFrame() + metadata["image"] = image_list + metadata["prompt"] = prompt_list + return metadata + + + def crop_and_resize(self, image, target_height, target_width): + width, height = image.size + scale = max(target_width / width, target_height / height) + image = torchvision.transforms.functional.resize( + image, + (round(height*scale), round(width*scale)), + interpolation=torchvision.transforms.InterpolationMode.BILINEAR + ) + image = torchvision.transforms.functional.center_crop(image, (target_height, target_width)) + return image + + + def get_height_width(self, image): + if self.dynamic_resolution: + width, height = image.size + if width * height > self.max_pixels: + scale = (width * height / self.max_pixels) ** 0.5 + height, width = int(height / scale), int(width / scale) + height = height // self.height_division_factor * self.height_division_factor + width = width // self.width_division_factor * self.width_division_factor + else: + height, width = self.height, self.width + return height, width + + + def load_image(self, file_path): + image = Image.open(file_path).convert("RGB") + image = self.crop_and_resize(image, *self.get_height_width(image)) + return image + + + def load_data(self, file_path): + return self.load_image(file_path) + + + def __getitem__(self, data_id): + data = self.data[data_id % len(self.data)].copy() + for key in self.data_file_keys: + if key in data: + if isinstance(data[key], list): + path = [os.path.join(self.base_path, p) for p in data[key]] + data[key] = [self.load_data(p) for p in path] + else: + path = os.path.join(self.base_path, data[key]) + data[key] = self.load_data(path) + if data[key] is None: + warnings.warn(f"cannot load file {data[key]}.") + return None + return data + + + def __len__(self): + return len(self.data) * self.repeat + + + +class VideoDataset(torch.utils.data.Dataset): + def __init__( + self, + base_path=None, metadata_path=None, + num_frames=81, + time_division_factor=4, time_division_remainder=1, + max_pixels=1920*1080, height=None, width=None, + height_division_factor=16, width_division_factor=16, + data_file_keys=("video",), + image_file_extension=("jpg", "jpeg", "png", "webp"), + video_file_extension=("mp4", "avi", "mov", "wmv", "mkv", "flv", "webm", "gif"), + repeat=1, + args=None, + ): + if args is not None: + base_path = args.dataset_base_path + metadata_path = args.dataset_metadata_path + height = args.height + width = args.width + max_pixels = args.max_pixels + num_frames = args.num_frames + data_file_keys = args.data_file_keys.split(",") + repeat = args.dataset_repeat + + self.base_path = base_path + self.num_frames = num_frames + self.time_division_factor = time_division_factor + self.time_division_remainder = time_division_remainder + self.max_pixels = max_pixels + self.height = height + self.width = width + self.height_division_factor = height_division_factor + self.width_division_factor = width_division_factor + self.data_file_keys = data_file_keys + self.image_file_extension = image_file_extension + self.video_file_extension = video_file_extension + self.repeat = repeat + + if height is not None and width is not None: + print("Height and width are fixed. Setting `dynamic_resolution` to False.") + self.dynamic_resolution = False + elif height is None and width is None: + print("Height and width are none. Setting `dynamic_resolution` to True.") + self.dynamic_resolution = True + + if metadata_path is None: + print("No metadata. Trying to generate it.") + metadata = self.generate_metadata(base_path) + print(f"{len(metadata)} lines in metadata.") + self.data = [metadata.iloc[i].to_dict() for i in range(len(metadata))] + elif metadata_path.endswith(".json"): + with open(metadata_path, "r") as f: + metadata = json.load(f) + self.data = metadata + else: + metadata = pd.read_csv(metadata_path) + self.data = [metadata.iloc[i].to_dict() for i in range(len(metadata))] + + + def generate_metadata(self, folder): + video_list, prompt_list = [], [] + file_set = set(os.listdir(folder)) + for file_name in file_set: + if "." not in file_name: + continue + file_ext_name = file_name.split(".")[-1].lower() + file_base_name = file_name[:-len(file_ext_name)-1] + if file_ext_name not in self.image_file_extension and file_ext_name not in self.video_file_extension: + continue + prompt_file_name = file_base_name + ".txt" + if prompt_file_name not in file_set: + continue + with open(os.path.join(folder, prompt_file_name), "r", encoding="utf-8") as f: + prompt = f.read().strip() + video_list.append(file_name) + prompt_list.append(prompt) + metadata = pd.DataFrame() + metadata["video"] = video_list + metadata["prompt"] = prompt_list + return metadata + + + def crop_and_resize(self, image, target_height, target_width): + width, height = image.size + scale = max(target_width / width, target_height / height) + image = torchvision.transforms.functional.resize( + image, + (round(height*scale), round(width*scale)), + interpolation=torchvision.transforms.InterpolationMode.BILINEAR + ) + image = torchvision.transforms.functional.center_crop(image, (target_height, target_width)) + return image + + + def get_height_width(self, image): + if self.dynamic_resolution: + width, height = image.size + if width * height > self.max_pixels: + scale = (width * height / self.max_pixels) ** 0.5 + height, width = int(height / scale), int(width / scale) + height = height // self.height_division_factor * self.height_division_factor + width = width // self.width_division_factor * self.width_division_factor + else: + height, width = self.height, self.width + return height, width + + + def get_num_frames(self, reader): + num_frames = self.num_frames + if int(reader.count_frames()) < num_frames: + num_frames = int(reader.count_frames()) + while num_frames > 1 and num_frames % self.time_division_factor != self.time_division_remainder: + num_frames -= 1 + return num_frames + + def _load_gif(self, file_path): + gif_img = Image.open(file_path) + frame_count = 0 + delays, frames = [], [] + while True: + delay = gif_img.info.get('duration', 100) # ms + delays.append(delay) + rgb_frame = gif_img.convert("RGB") + croped_frame = self.crop_and_resize(rgb_frame, *self.get_height_width(rgb_frame)) + frames.append(croped_frame) + frame_count += 1 + try: + gif_img.seek(frame_count) + except: + break + # delays canbe used to calculate framerates + # i guess it is better to sample images with stable interval, + # and using minimal_interval as the interval, + # and framerate = 1000 / minimal_interval + if any((delays[0] != i) for i in delays): + minimal_interval = min([i for i in delays if i > 0]) + # make a ((start,end),frameid) struct + start_end_idx_map = [((sum(delays[:i]), sum(delays[:i+1])), i) for i in range(len(delays))] + _frames = [] + # according gemini-code-assist, make it more efficient to locate + # where to sample the frame + last_match = 0 + for i in range(sum(delays) // minimal_interval): + current_time = minimal_interval * i + for idx, ((start, end), frame_idx) in enumerate(start_end_idx_map[last_match:]): + if start <= current_time < end: + _frames.append(frames[frame_idx]) + last_match = idx + last_match + break + frames = _frames + num_frames = len(frames) + if num_frames > self.num_frames: + num_frames = self.num_frames + else: + while num_frames > 1 and num_frames % self.time_division_factor != self.time_division_remainder: + num_frames -= 1 + frames = frames[:num_frames] + return frames + + def load_video(self, file_path): + if file_path.lower().endswith(".gif"): + return self._load_gif(file_path) + reader = imageio.get_reader(file_path) + num_frames = self.get_num_frames(reader) + frames = [] + for frame_id in range(num_frames): + frame = reader.get_data(frame_id) + frame = Image.fromarray(frame) + frame = self.crop_and_resize(frame, *self.get_height_width(frame)) + frames.append(frame) + reader.close() + return frames + + + def load_image(self, file_path): + image = Image.open(file_path).convert("RGB") + image = self.crop_and_resize(image, *self.get_height_width(image)) + frames = [image] + return frames + + + def is_image(self, file_path): + file_ext_name = file_path.split(".")[-1] + return file_ext_name.lower() in self.image_file_extension + + + def is_video(self, file_path): + file_ext_name = file_path.split(".")[-1] + return file_ext_name.lower() in self.video_file_extension + + + def load_data(self, file_path): + if self.is_image(file_path): + return self.load_image(file_path) + elif self.is_video(file_path): + return self.load_video(file_path) + else: + return None + + + def __getitem__(self, data_id): + data = self.data[data_id % len(self.data)].copy() + for key in self.data_file_keys: + if key in data: + path = os.path.join(self.base_path, data[key]) + data[key] = self.load_data(path) + if data[key] is None: + warnings.warn(f"cannot load file {data[key]}.") + return None + return data + + + def __len__(self): + return len(self.data) * self.repeat + + + +class DiffusionTrainingModule(torch.nn.Module): + def __init__(self): + super().__init__() + + + def to(self, *args, **kwargs): + for name, model in self.named_children(): + model.to(*args, **kwargs) + return self + + + def trainable_modules(self): + trainable_modules = filter(lambda p: p.requires_grad, self.parameters()) + return trainable_modules + + + def trainable_param_names(self): + trainable_param_names = list(filter(lambda named_param: named_param[1].requires_grad, self.named_parameters())) + trainable_param_names = set([named_param[0] for named_param in trainable_param_names]) + return trainable_param_names + + + def add_lora_to_model(self, model, target_modules, lora_rank, lora_alpha=None, upcast_dtype=None): + if LoraConfig is None or inject_adapter_in_model is None: + raise ModuleNotFoundError("peft is required when using LoRA training.") + if lora_alpha is None: + lora_alpha = lora_rank + lora_config = LoraConfig(r=lora_rank, lora_alpha=lora_alpha, target_modules=target_modules) + model = inject_adapter_in_model(lora_config, model) + if upcast_dtype is not None: + for param in model.parameters(): + if param.requires_grad: + param.data = param.to(upcast_dtype) + return model + + + def mapping_lora_state_dict(self, state_dict): + new_state_dict = {} + for key, value in state_dict.items(): + if "lora_A.weight" in key or "lora_B.weight" in key: + new_key = key.replace("lora_A.weight", "lora_A.default.weight").replace("lora_B.weight", "lora_B.default.weight") + new_state_dict[new_key] = value + elif "lora_A.default.weight" in key or "lora_B.default.weight" in key: + new_state_dict[key] = value + return new_state_dict + + + def export_trainable_state_dict(self, state_dict, remove_prefix=None): + trainable_param_names = self.trainable_param_names() + state_dict = {name: param for name, param in state_dict.items() if name in trainable_param_names} + if remove_prefix is not None: + state_dict_ = {} + for name, param in state_dict.items(): + if name.startswith(remove_prefix): + name = name[len(remove_prefix):] + state_dict_[name] = param + state_dict = state_dict_ + return state_dict + + + def transfer_data_to_device(self, data, device, torch_float_dtype=None): + for key in data: + if isinstance(data[key], torch.Tensor): + data[key] = data[key].to(device) + if torch_float_dtype is not None and data[key].dtype in [torch.float, torch.float16, torch.bfloat16]: + data[key] = data[key].to(torch_float_dtype) + return data + + + def parse_model_configs(self, model_paths, model_id_with_origin_paths, enable_fp8_training=False): + offload_dtype = torch.float8_e4m3fn if enable_fp8_training else None + model_configs = [] + if model_paths is not None: + model_paths = json.loads(model_paths) + model_configs += [ModelConfig(path=path, offload_dtype=offload_dtype) for path in model_paths] + if model_id_with_origin_paths is not None: + model_id_with_origin_paths = model_id_with_origin_paths.split(",") + model_configs += [ModelConfig(model_id=i.split(":")[0], origin_file_pattern=i.split(":")[1], offload_dtype=offload_dtype) for i in model_id_with_origin_paths] + return model_configs + + + def switch_pipe_to_training_mode( + self, + pipe, + trainable_models, + lora_base_model, lora_target_modules, lora_rank, lora_checkpoint=None, + enable_fp8_training=False, + ): + # Scheduler + pipe.scheduler.set_timesteps(1000, training=True) + + # Freeze untrainable models + pipe.freeze_except([] if trainable_models is None else trainable_models.split(",")) + + # Enable FP8 if pipeline supports + if enable_fp8_training and hasattr(pipe, "_enable_fp8_lora_training"): + pipe._enable_fp8_lora_training(torch.float8_e4m3fn) + + # Add LoRA to the base models + if lora_base_model is not None: + model = self.add_lora_to_model( + getattr(pipe, lora_base_model), + target_modules=lora_target_modules.split(","), + lora_rank=lora_rank, + upcast_dtype=pipe.torch_dtype, + ) + if lora_checkpoint is not None: + state_dict = load_state_dict(lora_checkpoint) + state_dict = self.mapping_lora_state_dict(state_dict) + load_result = model.load_state_dict(state_dict, strict=False) + print(f"LoRA checkpoint loaded: {lora_checkpoint}, total {len(state_dict)} keys") + if len(load_result[1]) > 0: + print(f"Warning, LoRA key mismatch! Unexpected keys in LoRA checkpoint: {load_result[1]}") + setattr(pipe, lora_base_model, model) + + +class ModelLogger: + def __init__(self, output_path, remove_prefix_in_ckpt=None, state_dict_converter=lambda x:x): + self.output_path = output_path + self.remove_prefix_in_ckpt = remove_prefix_in_ckpt + self.state_dict_converter = state_dict_converter + self.num_steps = 0 + + + def on_step_end(self, accelerator, model, save_steps=None): + self.num_steps += 1 + if save_steps is not None and self.num_steps % save_steps == 0: + self.save_model(accelerator, model, f"step-{self.num_steps}.safetensors") + + + def on_epoch_end(self, accelerator, model, epoch_id): + accelerator.wait_for_everyone() + if accelerator.is_main_process: + state_dict = accelerator.get_state_dict(model) + state_dict = accelerator.unwrap_model(model).export_trainable_state_dict(state_dict, remove_prefix=self.remove_prefix_in_ckpt) + state_dict = self.state_dict_converter(state_dict) + os.makedirs(self.output_path, exist_ok=True) + path = os.path.join(self.output_path, f"epoch-{epoch_id}.safetensors") + accelerator.save(state_dict, path, safe_serialization=True) + + + def on_training_end(self, accelerator, model, save_steps=None): + if save_steps is not None and self.num_steps % save_steps != 0: + self.save_model(accelerator, model, f"step-{self.num_steps}.safetensors") + + + def save_model(self, accelerator, model, file_name): + accelerator.wait_for_everyone() + if accelerator.is_main_process: + state_dict = accelerator.get_state_dict(model) + state_dict = accelerator.unwrap_model(model).export_trainable_state_dict(state_dict, remove_prefix=self.remove_prefix_in_ckpt) + state_dict = self.state_dict_converter(state_dict) + os.makedirs(self.output_path, exist_ok=True) + path = os.path.join(self.output_path, file_name) + accelerator.save(state_dict, path, safe_serialization=True) + + +def launch_training_task( + dataset: torch.utils.data.Dataset, + model: DiffusionTrainingModule, + model_logger: ModelLogger, + learning_rate: float = 1e-5, + weight_decay: float = 1e-2, + num_workers: int = 8, + save_steps: int = None, + num_epochs: int = 1, + gradient_accumulation_steps: int = 1, + find_unused_parameters: bool = False, + args = None, +): + if args is not None: + learning_rate = args.learning_rate + weight_decay = args.weight_decay + num_workers = args.dataset_num_workers + save_steps = args.save_steps + num_epochs = args.num_epochs + gradient_accumulation_steps = args.gradient_accumulation_steps + find_unused_parameters = args.find_unused_parameters + + optimizer = torch.optim.AdamW(model.trainable_modules(), lr=learning_rate, weight_decay=weight_decay) + scheduler = torch.optim.lr_scheduler.ConstantLR(optimizer) + dataloader = torch.utils.data.DataLoader(dataset, shuffle=True, collate_fn=lambda x: x[0], num_workers=num_workers) + accelerator = Accelerator( + gradient_accumulation_steps=gradient_accumulation_steps, + kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=find_unused_parameters)], + ) + model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler) + + for epoch_id in range(num_epochs): + for data in tqdm(dataloader): + with accelerator.accumulate(model): + optimizer.zero_grad() + if dataset.load_from_cache: + loss = model({}, inputs=data) + else: + loss = model(data) + accelerator.backward(loss) + optimizer.step() + model_logger.on_step_end(accelerator, model, save_steps) + scheduler.step() + if save_steps is None: + model_logger.on_epoch_end(accelerator, model, epoch_id) + model_logger.on_training_end(accelerator, model, save_steps) + + +def launch_data_process_task( + dataset: torch.utils.data.Dataset, + model: DiffusionTrainingModule, + model_logger: ModelLogger, + num_workers: int = 8, + args = None, +): + if args is not None: + num_workers = args.dataset_num_workers + + dataloader = torch.utils.data.DataLoader(dataset, shuffle=False, collate_fn=lambda x: x[0], num_workers=num_workers) + accelerator = Accelerator() + model, dataloader = accelerator.prepare(model, dataloader) + + for data_id, data in tqdm(enumerate(dataloader)): + with accelerator.accumulate(model): + with torch.no_grad(): + folder = os.path.join(model_logger.output_path, str(accelerator.process_index)) + os.makedirs(folder, exist_ok=True) + save_path = os.path.join(model_logger.output_path, str(accelerator.process_index), f"{data_id}.pth") + data = model(data, return_inputs=True) + torch.save(data, save_path) + + + +def wan_parser(): + parser = argparse.ArgumentParser(description="Simple example of a training script.") + parser.add_argument("--dataset_base_path", type=str, default="", required=True, help="Base path of the dataset.") + parser.add_argument("--dataset_metadata_path", type=str, default=None, help="Path to the metadata file of the dataset.") + parser.add_argument("--max_pixels", type=int, default=1280*720, help="Maximum number of pixels per frame, used for dynamic resolution..") + parser.add_argument("--height", type=int, default=None, help="Height of images or videos. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--width", type=int, default=None, help="Width of images or videos. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--num_frames", type=int, default=81, help="Number of frames per video. Frames are sampled from the video prefix.") + parser.add_argument("--data_file_keys", type=str, default="image,video", help="Data file keys in the metadata. Comma-separated.") + parser.add_argument("--dataset_repeat", type=int, default=1, help="Number of times to repeat the dataset per epoch.") + parser.add_argument("--model_paths", type=str, default=None, help="Paths to load models. In JSON format.") + parser.add_argument("--model_id_with_origin_paths", type=str, default=None, help="Model ID with origin paths, e.g., Wan-AI/Wan2.1-T2V-1.3B:diffusion_pytorch_model*.safetensors. Comma-separated.") + parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate.") + parser.add_argument("--num_epochs", type=int, default=1, help="Number of epochs.") + parser.add_argument("--output_path", type=str, default="./models", help="Output save path.") + parser.add_argument("--remove_prefix_in_ckpt", type=str, default="pipe.dit.", help="Remove prefix in ckpt.") + parser.add_argument("--trainable_models", type=str, default=None, help="Models to train, e.g., dit, vae, text_encoder.") + parser.add_argument("--lora_base_model", type=str, default=None, help="Which model LoRA is added to.") + parser.add_argument("--lora_target_modules", type=str, default="q,k,v,o,ffn.0,ffn.2", help="Which layers LoRA is added to.") + parser.add_argument("--lora_rank", type=int, default=32, help="Rank of LoRA.") + parser.add_argument("--lora_checkpoint", type=str, default=None, help="Path to the LoRA checkpoint. If provided, LoRA will be loaded from this checkpoint.") + parser.add_argument("--extra_inputs", default=None, help="Additional model inputs, comma-separated.") + parser.add_argument("--use_gradient_checkpointing_offload", default=False, action="store_true", help="Whether to offload gradient checkpointing to CPU memory.") + parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Gradient accumulation steps.") + parser.add_argument("--max_timestep_boundary", type=float, default=1.0, help="Max timestep boundary (for mixed models, e.g., Wan-AI/Wan2.2-I2V-A14B).") + parser.add_argument("--min_timestep_boundary", type=float, default=0.0, help="Min timestep boundary (for mixed models, e.g., Wan-AI/Wan2.2-I2V-A14B).") + parser.add_argument("--find_unused_parameters", default=False, action="store_true", help="Whether to find unused parameters in DDP.") + parser.add_argument("--save_steps", type=int, default=None, help="Number of checkpoint saving invervals. If None, checkpoints will be saved every epoch.") + parser.add_argument("--dataset_num_workers", type=int, default=0, help="Number of workers for data loading.") + parser.add_argument("--weight_decay", type=float, default=0.01, help="Weight decay.") + return parser + + + +def flux_parser(): + parser = argparse.ArgumentParser(description="Simple example of a training script.") + parser.add_argument("--dataset_base_path", type=str, default="", required=True, help="Base path of the dataset.") + parser.add_argument("--dataset_metadata_path", type=str, default=None, help="Path to the metadata file of the dataset.") + parser.add_argument("--max_pixels", type=int, default=1024*1024, help="Maximum number of pixels per frame, used for dynamic resolution..") + parser.add_argument("--height", type=int, default=None, help="Height of images. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--width", type=int, default=None, help="Width of images. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--data_file_keys", type=str, default="image", help="Data file keys in the metadata. Comma-separated.") + parser.add_argument("--dataset_repeat", type=int, default=1, help="Number of times to repeat the dataset per epoch.") + parser.add_argument("--model_paths", type=str, default=None, help="Paths to load models. In JSON format.") + parser.add_argument("--model_id_with_origin_paths", type=str, default=None, help="Model ID with origin paths, e.g., Wan-AI/Wan2.1-T2V-1.3B:diffusion_pytorch_model*.safetensors. Comma-separated.") + parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate.") + parser.add_argument("--num_epochs", type=int, default=1, help="Number of epochs.") + parser.add_argument("--output_path", type=str, default="./models", help="Output save path.") + parser.add_argument("--remove_prefix_in_ckpt", type=str, default="pipe.dit.", help="Remove prefix in ckpt.") + parser.add_argument("--trainable_models", type=str, default=None, help="Models to train, e.g., dit, vae, text_encoder.") + parser.add_argument("--lora_base_model", type=str, default=None, help="Which model LoRA is added to.") + parser.add_argument("--lora_target_modules", type=str, default="q,k,v,o,ffn.0,ffn.2", help="Which layers LoRA is added to.") + parser.add_argument("--lora_rank", type=int, default=32, help="Rank of LoRA.") + parser.add_argument("--lora_checkpoint", type=str, default=None, help="Path to the LoRA checkpoint. If provided, LoRA will be loaded from this checkpoint.") + parser.add_argument("--extra_inputs", default=None, help="Additional model inputs, comma-separated.") + parser.add_argument("--align_to_opensource_format", default=False, action="store_true", help="Whether to align the lora format to opensource format. Only for DiT's LoRA.") + parser.add_argument("--use_gradient_checkpointing", default=False, action="store_true", help="Whether to use gradient checkpointing.") + parser.add_argument("--use_gradient_checkpointing_offload", default=False, action="store_true", help="Whether to offload gradient checkpointing to CPU memory.") + parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Gradient accumulation steps.") + parser.add_argument("--find_unused_parameters", default=False, action="store_true", help="Whether to find unused parameters in DDP.") + parser.add_argument("--save_steps", type=int, default=None, help="Number of checkpoint saving invervals. If None, checkpoints will be saved every epoch.") + parser.add_argument("--dataset_num_workers", type=int, default=0, help="Number of workers for data loading.") + parser.add_argument("--weight_decay", type=float, default=0.01, help="Weight decay.") + return parser + + + +def qwen_image_parser(): + parser = argparse.ArgumentParser(description="Simple example of a training script.") + parser.add_argument("--dataset_base_path", type=str, default="", required=True, help="Base path of the dataset.") + parser.add_argument("--dataset_metadata_path", type=str, default=None, help="Path to the metadata file of the dataset.") + parser.add_argument("--max_pixels", type=int, default=1024*1024, help="Maximum number of pixels per frame, used for dynamic resolution..") + parser.add_argument("--height", type=int, default=None, help="Height of images. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--width", type=int, default=None, help="Width of images. Leave `height` and `width` empty to enable dynamic resolution.") + parser.add_argument("--data_file_keys", type=str, default="image", help="Data file keys in the metadata. Comma-separated.") + parser.add_argument("--dataset_repeat", type=int, default=1, help="Number of times to repeat the dataset per epoch.") + parser.add_argument("--model_paths", type=str, default=None, help="Paths to load models. In JSON format.") + parser.add_argument("--model_id_with_origin_paths", type=str, default=None, help="Model ID with origin paths, e.g., Wan-AI/Wan2.1-T2V-1.3B:diffusion_pytorch_model*.safetensors. Comma-separated.") + parser.add_argument("--tokenizer_path", type=str, default=None, help="Paths to tokenizer.") + parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate.") + parser.add_argument("--num_epochs", type=int, default=1, help="Number of epochs.") + parser.add_argument("--output_path", type=str, default="./models", help="Output save path.") + parser.add_argument("--remove_prefix_in_ckpt", type=str, default="pipe.dit.", help="Remove prefix in ckpt.") + parser.add_argument("--trainable_models", type=str, default=None, help="Models to train, e.g., dit, vae, text_encoder.") + parser.add_argument("--lora_base_model", type=str, default=None, help="Which model LoRA is added to.") + parser.add_argument("--lora_target_modules", type=str, default="q,k,v,o,ffn.0,ffn.2", help="Which layers LoRA is added to.") + parser.add_argument("--lora_rank", type=int, default=32, help="Rank of LoRA.") + parser.add_argument("--lora_checkpoint", type=str, default=None, help="Path to the LoRA checkpoint. If provided, LoRA will be loaded from this checkpoint.") + parser.add_argument("--extra_inputs", default=None, help="Additional model inputs, comma-separated.") + parser.add_argument("--use_gradient_checkpointing", default=False, action="store_true", help="Whether to use gradient checkpointing.") + parser.add_argument("--use_gradient_checkpointing_offload", default=False, action="store_true", help="Whether to offload gradient checkpointing to CPU memory.") + parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Gradient accumulation steps.") + parser.add_argument("--find_unused_parameters", default=False, action="store_true", help="Whether to find unused parameters in DDP.") + parser.add_argument("--save_steps", type=int, default=None, help="Number of checkpoint saving invervals. If None, checkpoints will be saved every epoch.") + parser.add_argument("--dataset_num_workers", type=int, default=0, help="Number of workers for data loading.") + parser.add_argument("--weight_decay", type=float, default=0.01, help="Weight decay.") + parser.add_argument("--processor_path", type=str, default=None, help="Path to the processor. If provided, the processor will be used for image editing.") + parser.add_argument("--enable_fp8_training", default=False, action="store_true", help="Whether to enable FP8 training. Only available for LoRA training on a single GPU.") + parser.add_argument("--task", type=str, default="sft", required=False, help="Task type.") + return parser diff --git a/releases/2026-10-20-code/diffsynth/utils/__init__.py b/releases/2026-10-20-code/diffsynth/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19b26257c389c99fa9e1c62599f44f322dd32091 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/utils/__init__.py @@ -0,0 +1,290 @@ +import torch, warnings, glob, os +import numpy as np +from PIL import Image +from einops import repeat, reduce +from typing import Optional, Union +from dataclasses import dataclass +try: + from modelscope import snapshot_download +except ModuleNotFoundError: + snapshot_download = None +import numpy as np +from PIL import Image +from typing import Optional + + +class BasePipeline(torch.nn.Module): + + def __init__( + self, + device="npu", torch_dtype=torch.float16, + height_division_factor=64, width_division_factor=64, + time_division_factor=None, time_division_remainder=None, + ): + super().__init__() + # The device and torch_dtype is used for the storage of intermediate variables, not models. + self.device = device + self.torch_dtype = torch_dtype + # The following parameters are used for shape check. + self.height_division_factor = height_division_factor + self.width_division_factor = width_division_factor + self.time_division_factor = time_division_factor + self.time_division_remainder = time_division_remainder + self.vram_management_enabled = False + + + def to(self, *args, **kwargs): + device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs) + if device is not None: + self.device = device + if dtype is not None: + self.torch_dtype = dtype + super().to(*args, **kwargs) + return self + + + def check_resize_height_width(self, height, width, num_frames=None): + # Shape check + if height % self.height_division_factor != 0: + height = (height + self.height_division_factor - 1) // self.height_division_factor * self.height_division_factor + print(f"height % {self.height_division_factor} != 0. 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"width % {self.width_division_factor} != 0. We round it up to {width}.") + if num_frames is None: + return height, width + else: + if num_frames % self.time_division_factor != self.time_division_remainder: + num_frames = (num_frames + self.time_division_factor - 1) // self.time_division_factor * self.time_division_factor + self.time_division_remainder + print(f"num_frames % {self.time_division_factor} != {self.time_division_remainder}. We round it up to {num_frames}.") + return height, width, num_frames + + + def preprocess_image(self, image, torch_dtype=None, device=None, pattern="B C H W", min_value=-1, max_value=1): + # Transform a PIL.Image to torch.Tensor + image = torch.Tensor(np.array(image, dtype=np.float32)) + # Normalize on CPU; some CANN 8.5.2 images lack the scalar Muls kernel. + image = image * ((max_value - min_value) / 255) + min_value + image = image.to(dtype=torch_dtype or self.torch_dtype, device=device or self.device) + image = repeat(image, f"H W C -> {pattern}", **({"B": 1} if "B" in pattern else {})) + return image + + + def preprocess_video(self, video, torch_dtype=None, device=None, pattern="B C T H W", min_value=-1, max_value=1): + # Transform a list of PIL.Image to torch.Tensor + video = [self.preprocess_image(image, torch_dtype=torch_dtype, device=device, min_value=min_value, max_value=max_value) for image in video] + video = torch.stack(video, dim=pattern.index("T") // 2) + return video + + + def vae_output_to_image(self, vae_output, pattern="B C H W", min_value=-1, max_value=1): + # Transform a torch.Tensor to PIL.Image + if pattern != "H W C": + vae_output = reduce(vae_output, f"{pattern} -> H W C", reduction="mean") + image = ((vae_output - min_value) * (255 / (max_value - min_value))).clip(0, 255) + image = image.to(device="cpu", dtype=torch.uint8) + image = Image.fromarray(image.numpy()) + return image + + + def vae_output_to_video(self, vae_output, pattern="B C T H W", min_value=-1, max_value=1): + # Transform a torch.Tensor to list of PIL.Image + if pattern != "T H W C": + vae_output = reduce(vae_output, f"{pattern} -> T H W C", reduction="mean") + video = [self.vae_output_to_image(image, pattern="H W C", min_value=min_value, max_value=max_value) for image in vae_output] + return video + + + def load_models_to_device(self, model_names=[]): + if self.vram_management_enabled: + # offload models + for name, model in self.named_children(): + if name not in model_names: + 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() + if str(self.device).startswith("npu"): + torch.npu.empty_cache() + else: + torch.cuda.empty_cache() + # onload models + for name, model in self.named_children(): + if name in model_names: + 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) + + + def generate_noise(self, shape, seed=None, rand_device="cpu", rand_torch_dtype=torch.float32, device=None, torch_dtype=None): + # Initialize Gaussian noise + target_device = device or self.device + rand_device = "cpu" if str(target_device).startswith("npu") else rand_device + generator = None if seed is None else torch.Generator(rand_device).manual_seed(seed) + noise = torch.randn(shape, generator=generator, device=rand_device, dtype=rand_torch_dtype) + noise = noise.to(dtype=torch_dtype or self.torch_dtype, device=device or self.device) + return noise + + + def enable_cpu_offload(self): + warnings.warn("`enable_cpu_offload` will be deprecated. Please use `enable_vram_management`.") + self.vram_management_enabled = True + + + def get_vram(self): + if str(self.device).startswith("npu"): + return torch.npu.mem_get_info(self.device)[1] / (1024 ** 3) + return torch.cuda.mem_get_info(self.device)[1] / (1024 ** 3) + + + def freeze_except(self, model_names): + for name, model in self.named_children(): + if name in model_names: + model.train() + model.requires_grad_(True) + else: + model.eval() + model.requires_grad_(False) + + + def blend_with_mask(self, base, addition, mask): + return base * (1 - mask) + addition * mask + + + def step(self, scheduler, latents, progress_id, noise_pred, input_latents=None, inpaint_mask=None, **kwargs): + timestep = scheduler.timesteps[progress_id] + if inpaint_mask is not None: + noise_pred_expected = scheduler.return_to_timestep(scheduler.timesteps[progress_id], latents, input_latents) + noise_pred = self.blend_with_mask(noise_pred_expected, noise_pred, inpaint_mask) + latents_next = scheduler.step(noise_pred, timestep, latents) + return latents_next + + + +@dataclass +class ModelConfig: + path: Union[str, list[str]] = None + model_id: str = None + origin_file_pattern: Union[str, list[str]] = None + download_resource: str = "ModelScope" + offload_device: Optional[Union[str, torch.device]] = None + offload_dtype: Optional[torch.dtype] = None + local_model_path: str = None + skip_download: bool = False + + def download_if_necessary(self, use_usp=False): + if self.path is None: + # Check model_id and origin_file_pattern + if self.model_id is None: + raise ValueError(f"""No valid model files. Please use `ModelConfig(path="xxx")` or `ModelConfig(model_id="xxx/yyy", origin_file_pattern="zzz")`.""") + + # Skip if not in rank 0 + if use_usp: + import torch.distributed as dist + skip_download = self.skip_download or dist.get_rank() != 0 + else: + skip_download = self.skip_download + + # Check whether the origin path is a folder + if self.origin_file_pattern is None or self.origin_file_pattern == "": + self.origin_file_pattern = "" + allow_file_pattern = None + is_folder = True + elif isinstance(self.origin_file_pattern, str) and self.origin_file_pattern.endswith("/"): + allow_file_pattern = self.origin_file_pattern + "*" + is_folder = True + else: + allow_file_pattern = self.origin_file_pattern + is_folder = False + + # Download + if self.local_model_path is None: + self.local_model_path = "./models" + if not skip_download: + _glob_root = os.path.join(self.local_model_path, self.model_id) + downloaded_files = glob.glob(os.path.join(_glob_root, self.origin_file_pattern)) + downloaded_files = [os.path.relpath(x, _glob_root) for x in downloaded_files] + if snapshot_download is None: + raise ModuleNotFoundError("modelscope is required when ModelConfig must download missing model files.") + snapshot_download( + self.model_id, + local_dir=os.path.join(self.local_model_path, self.model_id), + allow_file_pattern=allow_file_pattern, + ignore_file_pattern=downloaded_files, + local_files_only=False + ) + + # Let rank 1, 2, ... wait for rank 0 + if use_usp: + import torch.distributed as dist + dist.barrier(device_ids=[dist.get_rank()]) + + # Return downloaded files + if is_folder: + self.path = os.path.join(self.local_model_path, self.model_id, self.origin_file_pattern) + else: + self.path = glob.glob(os.path.join(self.local_model_path, self.model_id, self.origin_file_pattern)) + if isinstance(self.path, list) and len(self.path) == 1: + self.path = self.path[0] + + + +class PipelineUnit: + def __init__( + self, + seperate_cfg: bool = False, + take_over: bool = False, + input_params: tuple[str] = None, + input_params_posi: dict[str, str] = None, + input_params_nega: dict[str, str] = None, + onload_model_names: tuple[str] = None + ): + self.seperate_cfg = seperate_cfg + self.take_over = take_over + self.input_params = input_params + self.input_params_posi = input_params_posi + self.input_params_nega = input_params_nega + self.onload_model_names = onload_model_names + + + def process(self, pipe: BasePipeline, inputs: dict, positive=True, **kwargs) -> dict: + raise NotImplementedError("`process` is not implemented.") + + + +class PipelineUnitRunner: + def __init__(self): + pass + + def __call__(self, unit: PipelineUnit, pipe: BasePipeline, inputs_shared: dict, inputs_posi: dict, inputs_nega: dict) -> tuple[dict, dict]: + if unit.take_over: + # Let the pipeline unit take over this function. + inputs_shared, inputs_posi, inputs_nega = unit.process(pipe, inputs_shared=inputs_shared, inputs_posi=inputs_posi, inputs_nega=inputs_nega) + elif unit.seperate_cfg: + # Positive side + processor_inputs = {name: inputs_posi.get(name_) for name, name_ in unit.input_params_posi.items()} + if unit.input_params is not None: + for name in unit.input_params: + processor_inputs[name] = inputs_shared.get(name) + processor_outputs = unit.process(pipe, **processor_inputs) + inputs_posi.update(processor_outputs) + # Negative side + if inputs_shared["cfg_scale"] != 1: + processor_inputs = {name: inputs_nega.get(name_) for name, name_ in unit.input_params_nega.items()} + if unit.input_params is not None: + for name in unit.input_params: + processor_inputs[name] = inputs_shared.get(name) + processor_outputs = unit.process(pipe, **processor_inputs) + inputs_nega.update(processor_outputs) + else: + inputs_nega.update(processor_outputs) + else: + processor_inputs = {name: inputs_shared.get(name) for name in unit.input_params} + processor_outputs = unit.process(pipe, **processor_inputs) + inputs_shared.update(processor_outputs) + return inputs_shared, inputs_posi, inputs_nega diff --git a/releases/2026-10-20-code/diffsynth/vram_management/__init__.py b/releases/2026-10-20-code/diffsynth/vram_management/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b075800b6fd5b1702eeb7ff9c619aef1093ed46 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/vram_management/__init__.py @@ -0,0 +1,2 @@ +from .layers import * +from .gradient_checkpointing import * diff --git a/releases/2026-10-20-code/diffsynth/vram_management/gradient_checkpointing.py b/releases/2026-10-20-code/diffsynth/vram_management/gradient_checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..b356415a004f3d74afdd45840f1fc4caf6659e16 --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/vram_management/gradient_checkpointing.py @@ -0,0 +1,34 @@ +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/releases/2026-10-20-code/diffsynth/vram_management/layers.py b/releases/2026-10-20-code/diffsynth/vram_management/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..3e15442081e82cb998a2abc7d18b53e00fb5c17b --- /dev/null +++ b/releases/2026-10-20-code/diffsynth/vram_management/layers.py @@ -0,0 +1,213 @@ +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, + ) -> 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 +