z-rx commited on
Commit
720b873
·
verified ·
1 Parent(s): a0f5f54

Add DiffSynth source code used by UltraFlash

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. releases/2026-10-20-code/diffsynth/__init__.py +1 -0
  2. releases/2026-10-20-code/diffsynth/bridge/__init__.py +0 -0
  3. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/bridge/wan_bridge_pipeline.py +413 -0
  4. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap.py +170 -0
  5. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap_edit.py +204 -0
  6. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps.py +257 -0
  7. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps_firstframe_anchor.py +419 -0
  8. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/diagnose_flicker.py +173 -0
  9. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr.py +293 -0
  10. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_reference.py +400 -0
  11. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py +245 -0
  12. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.sh +31 -0
  13. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_edit.py +246 -0
  14. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_vibt.py +180 -0
  15. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/full/Wan2.1-T2V-1.3B.sh +33 -0
  16. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/sobel_utils.py +44 -0
  17. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train.py +405 -0
  18. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr.py +929 -0
  19. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k.sh +62 -0
  20. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor.sh +63 -0
  21. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor_flashvsr.sh +67 -0
  22. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py +707 -0
  23. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.py +752 -0
  24. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.sh +37 -0
  25. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image.sh +28 -0
  26. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image_wavelet.sh +13 -0
  27. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py +828 -0
  28. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.sh +60 -0
  29. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py +1015 -0
  30. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.sh +6 -0
  31. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py +457 -0
  32. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.sh +25 -0
  33. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py +583 -0
  34. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.sh +54 -0
  35. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh +83 -0
  36. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit_npu.sh +66 -0
  37. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/visualize_sobel_edges.py +235 -0
  38. releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/wan_video_new.py +1751 -0
  39. releases/2026-10-20-code/diffsynth/configs/__init__.py +0 -0
  40. releases/2026-10-20-code/diffsynth/configs/model_config.py +52 -0
  41. releases/2026-10-20-code/diffsynth/data/__init__.py +1 -0
  42. releases/2026-10-20-code/diffsynth/data/video.py +217 -0
  43. releases/2026-10-20-code/diffsynth/lora/__init__.py +45 -0
  44. releases/2026-10-20-code/diffsynth/models/__init__.py +0 -0
  45. releases/2026-10-20-code/diffsynth/models/downloader.py +116 -0
  46. releases/2026-10-20-code/diffsynth/models/model_manager.py +404 -0
  47. releases/2026-10-20-code/diffsynth/models/utils.py +196 -0
  48. releases/2026-10-20-code/diffsynth/models/wan_video_animate_adapter.py +670 -0
  49. releases/2026-10-20-code/diffsynth/models/wan_video_camera_controller.py +206 -0
  50. releases/2026-10-20-code/diffsynth/models/wan_video_dit.py +834 -0
releases/2026-10-20-code/diffsynth/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .data.video import VideoData, save_video, save_video_with_audio
releases/2026-10-20-code/diffsynth/bridge/__init__.py ADDED
File without changes
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/bridge/wan_bridge_pipeline.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, warnings, glob, os, types
2
+ import numpy as np
3
+ from PIL import Image
4
+ from einops import repeat, reduce
5
+ from typing import Optional, Union
6
+ from dataclasses import dataclass
7
+ try:
8
+ from modelscope import snapshot_download
9
+ except ModuleNotFoundError:
10
+ snapshot_download = None
11
+ from einops import rearrange
12
+ import numpy as np
13
+ from PIL import Image
14
+ from tqdm import tqdm
15
+ from typing import Optional
16
+ from typing_extensions import Literal
17
+
18
+ from diffsynth.utils import PipelineUnitRunner
19
+ from diffsynth.models.wan_video_dit import WanModel
20
+ from diffsynth.models.wan_video_text_encoder import WanTextEncoder
21
+ from diffsynth.models.wan_video_vae import WanVideoVAE
22
+ from diffsynth.models.wan_video_image_encoder import WanImageEncoder
23
+ from diffsynth.models.wan_video_vace import VaceWanModel
24
+ from diffsynth.models.wan_video_motion_controller import WanMotionControllerModel
25
+ from diffsynth.schedulers.flow_match import FlowMatchScheduler
26
+ from diffsynth.prompters.wan_prompter import WanPrompter
27
+
28
+ from diffsynth.pipelines.wan_video_new import *
29
+
30
+
31
+ import torch, math
32
+
33
+
34
+ def clip_bf16(x: torch.FloatTensor) -> torch.FloatTensor:
35
+ if x.dtype == torch.float16:
36
+ x = x.clip(-65504, 65504)
37
+ return x
38
+
39
+
40
+ class BridgeScheduler(FlowMatchScheduler):
41
+ def __init__(self, noise_scale=0.05, *args, **kwargs):
42
+ super().__init__(*args, **kwargs)
43
+ self.noise_scale = noise_scale
44
+ self.bridge_type = "brownian"
45
+ self.training_weight_type = "uniform"
46
+
47
+ def get_sigma(self, timestep):
48
+ if isinstance(timestep, torch.Tensor):
49
+ timestep = timestep.cpu()
50
+ timestep_id = torch.argmin((self.timesteps - timestep).abs())
51
+ return self.sigmas[timestep_id]
52
+
53
+ def step(self, model_output, timestep, sample, source_sample, noise=None, **kwargs):
54
+ if isinstance(timestep, torch.Tensor):
55
+ timestep = timestep.cpu()
56
+ timestep_id = torch.argmin((self.timesteps - timestep).abs())
57
+ sigma = self.sigmas[timestep_id]
58
+ if timestep_id + 1 >= len(self.timesteps):
59
+ sigma_ = 1 if (self.inverse_timesteps or self.reverse_sigmas) else 0
60
+ else:
61
+ sigma_ = self.sigmas[timestep_id + 1]
62
+ noise = noise if noise is not None else torch.randn_like(sample)
63
+
64
+ dt = sigma_ - sigma
65
+ if self.target == "x0":
66
+ drift = (sample - model_output) / (sigma + 1e-5)
67
+ elif self.target == "drift":
68
+ drift = model_output
69
+ elif self.target == "stabilized_drift":
70
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5
71
+ drift = model_output * factor
72
+ else:
73
+ raise ValueError(f"Unknown target {self.target}")
74
+ result = sample + drift * dt
75
+ correction_term = (sigma_) / (sigma)
76
+ noise_scale_t = self.noise_scale * (-dt * correction_term).sqrt()
77
+ result += noise_scale_t * noise
78
+
79
+ return result
80
+
81
+ def get_noise_coeff(self, sigma):
82
+ if self.bridge_type == "brownian":
83
+ return (sigma * (1 - sigma)) ** 0.5 * self.noise_scale
84
+ elif self.bridge_type == "brownian2":
85
+ return (sigma * (1 - sigma)) * self.noise_scale
86
+
87
+ def add_noise(self, z0, z1, noise, timestep):
88
+ sigma = self.get_sigma(timestep)
89
+
90
+ zt = (1 - sigma) * z0 + sigma * z1
91
+ noise_scale_t = self.get_noise_coeff(sigma)
92
+
93
+ return zt + noise_scale_t * noise
94
+
95
+ def training_target(self, z0, zt, timestep, epsilon=1e-5):
96
+ sigma = self.get_sigma(timestep)
97
+ target = (zt - z0) / (sigma + epsilon)
98
+ return target
99
+
100
+ def training_weight(self, timestep, **kwargs):
101
+ sigma = self.get_sigma(timestep)
102
+ if self.training_weight_type == "uniform":
103
+ return 1.0
104
+ elif self.training_weight_type == "time":
105
+ return sigma**0.5
106
+ elif self.training_weight_type == "time_linear":
107
+ return sigma
108
+ elif self.training_weight_type == "displacement":
109
+ return sigma**2
110
+ elif self.training_weight_type == "flow_matching":
111
+ return super().training_weight(timestep)
112
+ elif self.training_weight_type == "snr":
113
+ raise NotImplementedError("SNR training weight type is not implemented")
114
+ elif self.training_weight_type == "stablized":
115
+ drift_10 = kwargs.get("drift_10", None)
116
+ assert (
117
+ drift_10 is not None
118
+ ), "drift is required for stablized training weight"
119
+ drift_norm_sq = reduce(drift_10**2, "b ... -> b", "mean")
120
+ weight = (
121
+ sigma * drift_norm_sq / (sigma * drift_norm_sq + (1 - sigma))
122
+ ).item()
123
+ return weight
124
+ else:
125
+ raise ValueError(
126
+ f"Unknown training_weight_type {self.training_weight_type}"
127
+ )
128
+
129
+
130
+ class WanVideoBridgeUnit_InputVideoEmbedder_FSR(PipelineUnit):
131
+ def __init__(self, target_frames=321, fsr_factor=4):
132
+ super().__init__(
133
+ input_params=(
134
+ "source_video",
135
+ "tiled",
136
+ "tile_size",
137
+ "tile_stride",
138
+ ),
139
+ onload_model_names=("vae",),
140
+ )
141
+ self.target_frames = target_frames
142
+ self.fsr_factor = fsr_factor
143
+
144
+ def process(
145
+ self,
146
+ pipe: WanVideoPipeline,
147
+ source_video,
148
+ tiled,
149
+ tile_size,
150
+ tile_stride,
151
+ ):
152
+ pipe.load_models_to_device(["vae"])
153
+ source_video = pipe.preprocess_video(source_video)
154
+ frames_count = source_video.shape[2]
155
+ if frames_count == self.target_frames:
156
+ source_video = source_video[:, :, :: self.fsr_factor]
157
+ elif frames_count - 1 == (self.target_frames - 1) // self.fsr_factor:
158
+ # do_nothing
159
+ pass
160
+ else:
161
+ raise ValueError(
162
+ f"Source video frames {frames_count} not match target frames {self.target_frames} or {(self.target_frames - 1) // self.fsr_factor + 1}"
163
+ )
164
+
165
+ def repeat_frames(source_video: torch.Tensor, n: int) -> torch.Tensor:
166
+ b, c, t, h, w = source_video.shape
167
+ first = source_video[:, :, :1]
168
+ rest = source_video[:, :, 1:]
169
+ rest_repeated = rest.repeat_interleave(n, dim=2)
170
+ out = torch.cat([first, rest_repeated], dim=2)
171
+ return out
172
+
173
+ source_video = repeat_frames(source_video, self.fsr_factor)
174
+ source_latents = pipe.vae.encode(
175
+ source_video,
176
+ device=pipe.device,
177
+ tiled=tiled,
178
+ tile_size=tile_size,
179
+ tile_stride=tile_stride,
180
+ ).to(dtype=pipe.torch_dtype, device=pipe.device)
181
+ return {"source_latents": source_latents}
182
+
183
+
184
+ class WanVideoBridgeUnit_InputVideoEmbedder(PipelineUnit):
185
+ def __init__(self):
186
+ super().__init__(
187
+ input_params=("source_video", "tiled", "tile_size", "tile_stride"),
188
+ onload_model_names=("vae",),
189
+ )
190
+
191
+ def process(
192
+ self, pipe: WanVideoPipeline, source_video, tiled, tile_size, tile_stride
193
+ ):
194
+ pipe.load_models_to_device(["vae"])
195
+ source_video = pipe.preprocess_video(source_video)
196
+ source_latents = pipe.vae.encode(
197
+ source_video,
198
+ device=pipe.device,
199
+ tiled=tiled,
200
+ tile_size=tile_size,
201
+ tile_stride=tile_stride,
202
+ ).to(dtype=pipe.torch_dtype, device=pipe.device)
203
+
204
+ return {"source_latents": source_latents}
205
+
206
+
207
+ class WanVideoBridgePipeline(WanVideoPipeline):
208
+ def __init__(self, device="npu", torch_dtype=torch.float16, tokenizer_path=None):
209
+ super().__init__(
210
+ device=device, torch_dtype=torch_dtype, tokenizer_path=tokenizer_path
211
+ )
212
+
213
+ self.units = [
214
+ WanVideoUnit_ShapeChecker(),
215
+ WanVideoUnit_NoiseInitializer(),
216
+ WanVideoUnit_PromptEmbedder(),
217
+ WanVideoUnit_InputVideoEmbedder(),
218
+ WanVideoUnit_UnifiedSequenceParallel(),
219
+ WanVideoBridgeUnit_InputVideoEmbedder(),
220
+ ]
221
+
222
+ self.scheduler = BridgeScheduler(shift=1.0, sigma_min=0.0, extra_one_step=True)
223
+ # self.scheduler = FlowMatchScheduler(shift=1.0, sigma_min=0.0, extra_one_step=True)
224
+ self.model_fn = model_fn_wan_video
225
+
226
+ def training_loss(self, **inputs):
227
+ """Single-head ViBT training objective.
228
+
229
+ x0: target/style video latent
230
+ x1: source/content video latent
231
+ xt: Brownian-bridge sample between x0 and x1
232
+ The DiT predicts the bridge drift from xt toward x0.
233
+ """
234
+ max_timestep_boundary = int(
235
+ inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps
236
+ )
237
+ min_timestep_boundary = int(
238
+ inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps
239
+ )
240
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
241
+ timestep = self.scheduler.timesteps[timestep_id].to(
242
+ dtype=self.torch_dtype, device=self.device
243
+ )
244
+
245
+ x0 = inputs["input_latents"]
246
+ x1 = inputs["source_latents"]
247
+ noise = inputs["noise"]
248
+
249
+ xt = self.scheduler.add_noise(x0, x1, noise, timestep)
250
+ inputs["latents"] = xt
251
+
252
+ target = self.scheduler.training_target(x0, xt, timestep)
253
+ drift_10 = x1 - x0
254
+ model_output = self.model_fn(**inputs, timestep=timestep)
255
+
256
+ if self.scheduler.target == "drift":
257
+ loss = torch.nn.functional.mse_loss(
258
+ model_output.float(), target.float()
259
+ )
260
+ loss *= self.scheduler.training_weight(timestep, drift_10=drift_10)
261
+ elif self.scheduler.target == "x0":
262
+ sigma = self.scheduler.get_sigma(timestep)
263
+ drift = (xt - model_output) / (sigma + 1e-5)
264
+ loss = torch.nn.functional.mse_loss(drift.float(), target.float())
265
+ loss *= self.scheduler.training_weight(timestep, drift_10=drift_10)
266
+ elif self.scheduler.target == "stabilized_drift":
267
+ sigma = self.scheduler.get_sigma(timestep)
268
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5
269
+ stabilized_target = target / factor
270
+ loss = torch.nn.functional.mse_loss(
271
+ model_output.float(), stabilized_target.float()
272
+ )
273
+ else:
274
+ raise ValueError(f"Unknown target {self.scheduler.target}")
275
+
276
+ return loss
277
+
278
+ @torch.no_grad()
279
+ def __call__(
280
+ self,
281
+ # Prompt
282
+ prompt: str,
283
+ negative_prompt: Optional[str] = "",
284
+ # Video-to-video
285
+ input_video: Optional[list[Image.Image]] = None,
286
+ seed: Optional[int] = None,
287
+ rand_device: Optional[str] = "cpu",
288
+ # Shape
289
+ height: Optional[int] = 480,
290
+ width: Optional[int] = 832,
291
+ num_frames=81,
292
+ # Classifier-free guidance
293
+ cfg_scale: Optional[float] = 5.0,
294
+ cfg_merge: Optional[bool] = False,
295
+ # Boundary
296
+ switch_DiT_boundary: Optional[float] = 0.875,
297
+ # Scheduler
298
+ num_inference_steps: Optional[int] = 50,
299
+ sigma_shift: Optional[float] = 1.0,
300
+ # VAE tiling
301
+ tiled: Optional[bool] = True,
302
+ tile_size: Optional[tuple[int, int]] = (30, 52),
303
+ tile_stride: Optional[tuple[int, int]] = (15, 26),
304
+ # progress_bar
305
+ progress_bar_cmd=tqdm,
306
+ # bridge
307
+ source_video: Optional[Image.Image] = None,
308
+ ):
309
+ # Scheduler
310
+ self.scheduler.set_timesteps(num_inference_steps, shift=sigma_shift)
311
+
312
+ # Inputs
313
+ inputs_posi = {
314
+ "prompt": prompt,
315
+ "num_inference_steps": num_inference_steps,
316
+ }
317
+ inputs_nega = {
318
+ "negative_prompt": negative_prompt,
319
+ "num_inference_steps": num_inference_steps,
320
+ }
321
+ inputs_shared = {
322
+ "input_video": input_video,
323
+ "source_video": source_video,
324
+ "seed": seed,
325
+ "rand_device": rand_device,
326
+ "height": height,
327
+ "width": width,
328
+ "num_frames": num_frames,
329
+ "cfg_scale": cfg_scale,
330
+ "cfg_merge": cfg_merge,
331
+ "sigma_shift": sigma_shift,
332
+ "tiled": tiled,
333
+ "tile_size": tile_size,
334
+ "tile_stride": tile_stride,
335
+ }
336
+
337
+ for unit in self.units:
338
+ inputs_shared, inputs_posi, inputs_nega = self.unit_runner(
339
+ unit, self, inputs_shared, inputs_posi, inputs_nega
340
+ )
341
+
342
+ inputs_shared["latents"] = inputs_shared["source_latents"].clone()
343
+
344
+ # Denoise
345
+ self.load_models_to_device(self.in_iteration_models)
346
+ models = {name: getattr(self, name) for name in self.in_iteration_models}
347
+ for progress_id, timestep in enumerate(
348
+ progress_bar_cmd(self.scheduler.timesteps)
349
+ ):
350
+ # Switch DiT if necessary
351
+ if (
352
+ timestep.item()
353
+ < switch_DiT_boundary * self.scheduler.num_train_timesteps
354
+ and self.dit2 is not None
355
+ and not models["dit"] is self.dit2
356
+ ):
357
+ self.load_models_to_device(self.in_iteration_models_2)
358
+ models["dit"] = self.dit2
359
+ models["vace"] = self.vace2
360
+
361
+ # Timestep
362
+ timestep = timestep.unsqueeze(0).to(
363
+ dtype=self.torch_dtype, device=self.device
364
+ )
365
+
366
+ # Inference
367
+ noise_pred_posi = self.model_fn(
368
+ **models, **inputs_shared, **inputs_posi, timestep=timestep
369
+ )
370
+ if cfg_scale != 1.0:
371
+ if cfg_merge:
372
+ noise_pred_posi, noise_pred_nega = noise_pred_posi.chunk(2, dim=0)
373
+ else:
374
+ noise_pred_nega = self.model_fn(
375
+ **models, **inputs_shared, **inputs_nega, timestep=timestep
376
+ )
377
+
378
+ noise_pred = noise_pred_nega + cfg_scale * (
379
+ noise_pred_posi - noise_pred_nega
380
+ )
381
+ else:
382
+ noise_pred = noise_pred_posi
383
+
384
+ # Scheduler
385
+ inputs_shared["latents"] = self.scheduler.step(
386
+ noise_pred,
387
+ self.scheduler.timesteps[progress_id],
388
+ inputs_shared["latents"],
389
+ inputs_shared["source_latents"],
390
+ )
391
+ if "first_frame_latents" in inputs_shared:
392
+ inputs_shared["latents"][:, :, 0:1] = inputs_shared[
393
+ "first_frame_latents"
394
+ ]
395
+
396
+ # post-denoising, pre-decoding processing logic
397
+ for unit in self.post_units:
398
+ inputs_shared, _, _ = self.unit_runner(
399
+ unit, self, inputs_shared, inputs_posi, inputs_nega
400
+ )
401
+ # Decode
402
+ self.load_models_to_device(["vae"])
403
+ video = self.vae.decode(
404
+ inputs_shared["latents"],
405
+ device=self.device,
406
+ tiled=tiled,
407
+ tile_size=tile_size,
408
+ tile_stride=tile_stride,
409
+ )
410
+ video = self.vae_output_to_video(video)
411
+ self.load_models_to_device([])
412
+
413
+ return video
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference-only visualization of target-Q/reference-K attention."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import torch
11
+ from PIL import Image
12
+
13
+
14
+ class ReferenceAttentionRecorder:
15
+ """Collect head-averaged reference-key heatmaps without changing inference."""
16
+
17
+ def __init__(self, block_ids: list[int], num_heads: int, query_stride: int = 8) -> None:
18
+ self.block_ids = set(block_ids)
19
+ self.num_heads = int(num_heads)
20
+ self.query_stride = max(int(query_stride), 1)
21
+ self.records: dict[tuple[int, int, str], np.ndarray] = {}
22
+ self.injections: dict[tuple[int, int], np.ndarray] = {}
23
+ self.energy_biases: dict[tuple[int, int], np.ndarray] = {}
24
+ self.grids: dict[int, tuple[int, int, int]] = {}
25
+
26
+ @torch.no_grad()
27
+ def capture(self, block_id: int, q: torch.Tensor, k: torch.Tensor,
28
+ scaled_delta: torch.Tensor, grid: tuple[int, int, int],
29
+ attention_bias: torch.Tensor | None = None) -> None:
30
+ frames, height, width = grid
31
+ if block_id not in self.block_ids:
32
+ return
33
+ if q.shape[0] < frames:
34
+ raise ValueError(f"Attention batch/time shape {q.shape[0]} is smaller than T={frames}")
35
+ spatial = height * width
36
+ head_dim = q.shape[-1] // self.num_heads
37
+ self.grids[block_id] = grid
38
+ yy, xx = torch.meshgrid(
39
+ torch.arange(height, device=q.device),
40
+ torch.arange(width, device=q.device), indexing="ij",
41
+ )
42
+ all_indices = torch.arange(spatial, device=q.device)[::self.query_stride]
43
+ face_indices = torch.nonzero(
44
+ (yy >= round(.08 * height)) & (yy < round(.36 * height))
45
+ & (xx >= round(.25 * width)) & (xx < round(.75 * width)),
46
+ as_tuple=False,
47
+ )
48
+ face_indices = (face_indices[:, 0] * width + face_indices[:, 1]).long()
49
+
50
+ for frame in range(frames):
51
+ qh = q[frame].reshape(spatial, self.num_heads, head_dim).permute(1, 0, 2)
52
+ kh = k[frame].reshape(spatial, self.num_heads, head_dim).permute(1, 0, 2)
53
+ key_bias = (
54
+ torch.zeros(spatial, device=q.device, dtype=torch.float32)
55
+ if attention_bias is None
56
+ else attention_bias[frame].float()
57
+ )
58
+ for name, indices in (("global", all_indices), ("face_queries", face_indices)):
59
+ mass_before = torch.zeros(spatial, device=q.device, dtype=torch.float32)
60
+ mass_after = torch.zeros(spatial, device=q.device, dtype=torch.float32)
61
+ for chunk in indices.split(64):
62
+ logits = torch.matmul(
63
+ qh[:, chunk].float(), kh.float().transpose(-1, -2)
64
+ ) * (head_dim ** -0.5)
65
+ mass_before.add_(logits.softmax(dim=-1).sum(dim=(0, 1)))
66
+ mass_after.add_((logits + key_bias[None, None, :]).softmax(dim=-1).sum(dim=(0, 1)))
67
+ denominator = self.num_heads * max(indices.numel(), 1)
68
+ mass_before.div_(denominator)
69
+ mass_after.div_(denominator)
70
+ self.records[(block_id, frame, f"{name}_before")] = mass_before.cpu().numpy()
71
+ self.records[(block_id, frame, f"{name}_after")] = mass_after.cpu().numpy()
72
+ injection = scaled_delta[frame].reshape(spatial, -1).float().abs().mean(dim=-1)
73
+ self.injections[(block_id, frame)] = injection.cpu().numpy()
74
+ self.energy_biases[(block_id, frame)] = key_bias.cpu().numpy()
75
+
76
+ @staticmethod
77
+ def _overlay(image_rgb: np.ndarray, values: np.ndarray, height: int, width: int,
78
+ probability: bool) -> np.ndarray:
79
+ values = values.reshape(height, width)
80
+ if probability:
81
+ # Show enrichment relative to uniform attention. Zero means uniform;
82
+ # one means four times uniform after log2 compression.
83
+ score = np.log2(np.maximum(values * values.size, 1e-6))
84
+ score = np.clip((score + 1.0) / 3.0, 0, 1)
85
+ else:
86
+ upper = max(float(np.quantile(values, .99)), 1e-8)
87
+ score = np.clip(values / upper, 0, 1)
88
+ score = cv2.resize(score.astype(np.float32), (image_rgb.shape[1], image_rgb.shape[0]))
89
+ heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
90
+ heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB).astype(np.float32) / 255
91
+ return np.clip(.48 * image_rgb + .52 * heat, 0, 1)
92
+
93
+ @staticmethod
94
+ def _signed_overlay(image_rgb: np.ndarray, values: np.ndarray,
95
+ height: int, width: int) -> np.ndarray:
96
+ values = values.reshape(height, width)
97
+ upper = max(float(np.quantile(np.abs(values), .99)), 1e-8)
98
+ score = np.clip(values / upper, -1, 1)
99
+ # OpenCV's cool-warm map takes 0=blue, .5=neutral, 1=red.
100
+ score = cv2.resize(((score + 1) * .5).astype(np.float32),
101
+ (image_rgb.shape[1], image_rgb.shape[0]))
102
+ heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_COOL)
103
+ heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB).astype(np.float32) / 255
104
+ return np.clip(.42 * image_rgb + .58 * heat, 0, 1)
105
+
106
+ @staticmethod
107
+ def _panel(image: np.ndarray, label: str, size: tuple[int, int] = (240, 416)) -> np.ndarray:
108
+ bgr = cv2.cvtColor((image * 255).round().clip(0, 255).astype(np.uint8), cv2.COLOR_RGB2BGR)
109
+ bgr = cv2.resize(bgr, size, interpolation=cv2.INTER_AREA)
110
+ cv2.rectangle(bgr, (0, 0), (size[0], 36), (0, 0, 0), -1)
111
+ cv2.putText(bgr, label, (7, 25), cv2.FONT_HERSHEY_SIMPLEX, .48,
112
+ (255, 255, 255), 1, cv2.LINE_AA)
113
+ return bgr
114
+
115
+ def save(self, output_dir: str | Path, target_video_btchw: torch.Tensor,
116
+ reference_image: Image.Image, fps: int = 20) -> None:
117
+ output_dir = Path(output_dir); output_dir.mkdir(parents=True, exist_ok=True)
118
+ target = target_video_btchw[0].permute(0, 2, 3, 1).float().cpu().numpy()
119
+ reference = np.asarray(reference_image.convert("RGB").resize((480, 832))).astype(np.float32) / 255
120
+ stats = []
121
+ for block_id in sorted(self.block_ids):
122
+ if block_id not in self.grids:
123
+ continue
124
+ frames, height, width = self.grids[block_id]
125
+ writer = cv2.VideoWriter(
126
+ str(output_dir / f"attention_block{block_id:02d}.mp4"),
127
+ cv2.VideoWriter_fourcc(*"mp4v"), max(fps / 4, 1), (1440, 416),
128
+ )
129
+ contact = []
130
+ chosen = {0, frames // 4, frames // 2, 3 * frames // 4, frames - 1}
131
+ for frame in range(frames):
132
+ rgb_id = round(frame * (len(target) - 1) / max(frames - 1, 1))
133
+ global_before = self.records[(block_id, frame, "global_before")]
134
+ global_after = self.records[(block_id, frame, "global_after")]
135
+ face_before = self.records[(block_id, frame, "face_queries_before")]
136
+ face_after = self.records[(block_id, frame, "face_queries_after")]
137
+ energy_bias = self.energy_biases[(block_id, frame)]
138
+ panels = [
139
+ self._panel(target[rgb_id], f"target RGB {rgb_id}"),
140
+ self._panel(self._signed_overlay(reference, energy_bias, height, width), "wavelet energy bias"),
141
+ self._panel(self._overlay(reference, global_before, height, width, True), "global QK (before)"),
142
+ self._panel(self._overlay(reference, global_after, height, width, True), "global QK+bias (after)"),
143
+ self._panel(self._overlay(reference, face_before, height, width, True), "face QK (before)"),
144
+ self._panel(self._overlay(reference, face_after, height, width, True), "face QK+bias (after)"),
145
+ ]
146
+ row = np.concatenate(panels, axis=1)
147
+ writer.write(row)
148
+ if frame in chosen:
149
+ contact.append(row)
150
+ for name, values in (
151
+ ("global_before", global_before),
152
+ ("global_after", global_after),
153
+ ("face_queries_before", face_before),
154
+ ("face_queries_after", face_after),
155
+ ):
156
+ p = np.maximum(values, 1e-12); p = p / p.sum()
157
+ peak = int(p.argmax())
158
+ stats.append({
159
+ "block": block_id, "latent_frame": frame, "rgb_frame": rgb_id,
160
+ "query_region": name,
161
+ "normalized_entropy": float(-(p * np.log(p)).sum() / np.log(p.size)),
162
+ "peak_over_uniform": float(p.max() * p.size),
163
+ "top_10_percent_key_mass": float(np.sort(p)[-max(p.size // 10, 1):].sum()),
164
+ "peak_reference_xy": [peak % width, peak // width],
165
+ })
166
+ writer.release()
167
+ cv2.imwrite(str(output_dir / f"attention_block{block_id:02d}_contact.jpg"), np.concatenate(contact, axis=0))
168
+ (output_dir / "attention_stats.json").write_text(
169
+ json.dumps(stats, indent=2), encoding="utf-8"
170
+ )
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/attention_heatmap_edit.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture selected Wan edit token-prefix attention heads during inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import random
8
+ import types
9
+ from pathlib import Path
10
+
11
+ import cv2
12
+ import numpy as np
13
+ import torch
14
+
15
+ from diffsynth.bridge.wan_bridge.model_inference.infer_sr_wan22_ti2v_edit import (
16
+ load_pipe,
17
+ prepare,
18
+ read_video,
19
+ )
20
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
21
+ decode_latents_to_btchw_01,
22
+ make_lr_source,
23
+ tensor_btchw_01_to_pil,
24
+ )
25
+ from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v_edit import (
26
+ normalize_wan_num_frames,
27
+ )
28
+ from diffsynth.data.video import save_video
29
+
30
+
31
+ def parse_ints(value: str) -> list[int]:
32
+ return [int(item.strip()) for item in value.split(",") if item.strip()]
33
+
34
+
35
+ class EditAttentionRecorder:
36
+ def __init__(self, block_ids: list[int], head_ids: list[int], frame_ids: list[int], query_stride: int, num_heads: int):
37
+ self.block_ids = set(block_ids)
38
+ self.head_ids = set(head_ids)
39
+ self.frame_ids = set(frame_ids)
40
+ self.query_stride = max(int(query_stride), 1)
41
+ self.num_heads = int(num_heads)
42
+ self.values: dict[tuple[int, int, int, int], np.ndarray] = {}
43
+ self.grid: tuple[int, int, int] | None = None
44
+ self.calls: dict[int, int] = {block: 0 for block in block_ids}
45
+
46
+ @torch.no_grad()
47
+ def capture(self, block_id: int, q: torch.Tensor, k: torch.Tensor, attn_mask: torch.Tensor | None) -> None:
48
+ if block_id not in self.block_ids:
49
+ return
50
+ if q.shape[0] != 1:
51
+ raise ValueError("Attention heatmap currently expects batch size 1")
52
+ total = int(q.shape[1])
53
+ if total % 2:
54
+ raise ValueError(f"Expected equal [c,z] token streams, got {total} tokens")
55
+ prefix_tokens = total // 2
56
+ # Wan2.1 uses the same patch grid for c and z in this edit pipeline.
57
+ if self.grid is None:
58
+ raise RuntimeError("Attention recorder grid was not initialized")
59
+ frames, height, width = self.grid
60
+ expected = frames * height * width
61
+ if expected != prefix_tokens:
62
+ raise ValueError(f"Attention grid {self.grid} has {expected} tokens, expected {prefix_tokens}")
63
+ call_id = self.calls[block_id]
64
+ self.calls[block_id] += 1
65
+ selected_heads = sorted(self.head_ids)
66
+ qh = q.float().reshape(1, total, self.num_heads, -1).permute(0, 2, 1, 3)[:, selected_heads]
67
+ kh = k.float().reshape(1, total, self.num_heads, -1).permute(0, 2, 1, 3)[:, selected_heads]
68
+ scale = qh.shape[-1] ** -0.5
69
+ if attn_mask is None:
70
+ mask = None
71
+ elif attn_mask.dtype == torch.bool:
72
+ mask = attn_mask.to(device=q.device)
73
+ else:
74
+ mask = attn_mask.to(device=q.device, dtype=torch.float32)
75
+ for frame in sorted(self.frame_ids):
76
+ if frame < 0 or frame >= frames:
77
+ continue
78
+ query_start = prefix_tokens + frame * height * width
79
+ query_ids = torch.arange(query_start, query_start + height * width, self.query_stride, device=q.device)
80
+ key_start = frame * height * width
81
+ key_ids = torch.arange(key_start, key_start + height * width, device=q.device)
82
+ logits = torch.matmul(qh[:, :, query_ids], kh.transpose(-1, -2)) * scale
83
+ if mask is not None:
84
+ query_mask = mask[:, :, query_ids, :]
85
+ if query_mask.dtype == torch.bool:
86
+ logits = logits.masked_fill(~query_mask, torch.finfo(logits.dtype).min)
87
+ else:
88
+ logits = logits + query_mask
89
+ probs = logits.softmax(dim=-1)[0]
90
+ for local_head, head_id in enumerate(selected_heads):
91
+ # Keep only same-frame reference keys and average selected z queries.
92
+ heat = probs[local_head, :, key_ids].mean(dim=0)
93
+ self.values[(block_id, head_id, frame, call_id)] = heat.cpu().numpy()
94
+
95
+ def save(self, output_dir: Path, reference_frames: list, fps: float) -> None:
96
+ output_dir.mkdir(parents=True, exist_ok=True)
97
+ manifest = []
98
+ assert self.grid is not None
99
+ _, height, width = self.grid
100
+ for (block, head, frame, call_id), values in sorted(self.values.items()):
101
+ npy = output_dir / f"block{block:02d}_head{head:02d}_frame{frame:02d}_call{call_id:02d}.npy"
102
+ np.save(npy, values.reshape(height, width))
103
+ ref = np.asarray(reference_frames[min(frame, len(reference_frames) - 1)].convert("RGB"))
104
+ ref = cv2.resize(ref, (width * 32, height * 32), interpolation=cv2.INTER_LINEAR)
105
+ score = values.reshape(height, width)
106
+ score = score / max(float(score.max()), 1e-12)
107
+ score = cv2.resize(score.astype(np.float32), (ref.shape[1], ref.shape[0]))
108
+ heat = cv2.applyColorMap((score * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
109
+ heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB)
110
+ overlay = np.clip(.42 * ref.astype(np.float32) + .58 * heat.astype(np.float32), 0, 255).astype(np.uint8)
111
+ image_path = output_dir / f"block{block:02d}_head{head:02d}_frame{frame:02d}_call{call_id:02d}.jpg"
112
+ cv2.imwrite(str(image_path), cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 92])
113
+ 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)})
114
+ (output_dir / "attention_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
115
+
116
+
117
+ def install_recorder(pipe, recorder: EditAttentionRecorder) -> list[tuple[object, object]]:
118
+ originals = []
119
+ for block_id in sorted(recorder.block_ids):
120
+ module = pipe.dit.blocks[block_id].self_attn.attn
121
+ original = module.forward
122
+ def wrapped(q, k, v, attn_mask=None, *, _original=original, _block=block_id):
123
+ recorder.capture(_block, q, k, attn_mask)
124
+ return _original(q, k, v, attn_mask=attn_mask)
125
+ module.forward = types.MethodType(lambda self, q, k, v, attn_mask=None, _wrapped=wrapped: _wrapped(q, k, v, attn_mask), module)
126
+ originals.append((module, original))
127
+ return originals
128
+
129
+
130
+ def main() -> None:
131
+ parser = argparse.ArgumentParser()
132
+ parser.add_argument("--checkpoint", required=True)
133
+ parser.add_argument("--input_video", required=True)
134
+ parser.add_argument("--bridge_video", required=True)
135
+ parser.add_argument("--output_dir", required=True)
136
+ parser.add_argument("--steps", type=int, default=12)
137
+ parser.add_argument("--blocks", default="0,14,29")
138
+ parser.add_argument("--heads", default="0,5,11")
139
+ parser.add_argument("--frames", default="0,4,8")
140
+ parser.add_argument("--query_stride", type=int, default=16)
141
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
142
+ parser.add_argument("--model_paths", default=None)
143
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
144
+ parser.add_argument("--height", type=int, default=480)
145
+ parser.add_argument("--width", type=int, default=832)
146
+ parser.add_argument("--num_frames", type=int, default=81)
147
+ parser.add_argument("--sr_scale", type=int, default=4)
148
+ parser.add_argument("--sigma_shift", type=float, default=5.0)
149
+ parser.add_argument("--sampling_noise_scale", type=float, default=1.0)
150
+ parser.add_argument("--device", default="cuda")
151
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
152
+ parser.add_argument("--prompt", default="")
153
+ parser.add_argument("--negative_prompt", default="")
154
+ parser.add_argument("--tile_h", type=int, default=30)
155
+ parser.add_argument("--tile_w", type=int, default=52)
156
+ parser.add_argument("--tile_stride_h", type=int, default=15)
157
+ parser.add_argument("--tile_stride_w", type=int, default=26)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--tiled", action="store_true")
160
+ args = parser.parse_args()
161
+ args.num_frames = normalize_wan_num_frames(args.num_frames)
162
+ random.seed(args.seed)
163
+ torch.manual_seed(args.seed)
164
+ reference, fps = read_video(Path(args.input_video), args.height, args.width, args.num_frames)
165
+ bridge, _ = read_video(Path(args.bridge_video), args.height, args.width, args.num_frames)
166
+ source = [make_lr_source(frame, args.height, args.width, args.sr_scale, upsample_to_hr=False) for frame in bridge]
167
+ pipe = load_pipe(args)
168
+ prepared = prepare(pipe, reference, source, args)
169
+ target_latents = prepared[0]["source_latents"]
170
+ _, _, frames, height, width = target_latents.shape
171
+ # Wan2.1 patchifies latent tensors with patch_size=(1, 2, 2).
172
+ token_grid = (int(frames), int(height // 2), int(width // 2))
173
+ recorder = EditAttentionRecorder(
174
+ parse_ints(args.blocks), parse_ints(args.heads), parse_ints(args.frames),
175
+ args.query_stride, int(pipe.dit.blocks[0].num_heads),
176
+ )
177
+ recorder.grid = token_grid
178
+ originals = install_recorder(pipe, recorder)
179
+ try:
180
+ shared, pos, _ = prepared
181
+ pipe.scheduler.set_timesteps(args.steps, shift=args.sigma_shift)
182
+ latents = shared["source_latents"].clone()
183
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
184
+ pipe.load_models_to_device(pipe.in_iteration_models)
185
+ model_inputs = dict(shared)
186
+ model_inputs.pop("latents", None)
187
+ model_inputs.pop("original_latents", None)
188
+ model_inputs["token_prefix_latents"] = shared["original_latents"].detach()
189
+ model_inputs["token_prefix_block_self_attention"] = True
190
+ for timestep_cpu in pipe.scheduler.timesteps:
191
+ timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype)
192
+ pred = pipe.model_fn(**models, **model_inputs, **pos, latents=latents, timestep=timestep)
193
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, shared["source_latents"])
194
+ video = decode_latents_to_btchw_01(pipe, latents, args.tiled, (30, 52), (15, 26)).cpu()
195
+ 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)
196
+ finally:
197
+ for module, original in originals:
198
+ module.forward = original
199
+ recorder.save(Path(args.output_dir), reference, fps)
200
+ (Path(args.output_dir) / "run_config.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare frozen Wan Bridge SR quality over several inference step counts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import math
8
+ import random
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ from diffsynth.bridge.wan_bridge.model_inference.infer_sr import (
16
+ build_pipeline,
17
+ default_model_paths,
18
+ read_video,
19
+ )
20
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
21
+ decode_latents_to_btchw_01,
22
+ pil_video_to_tensor_01,
23
+ tensor_btchw_01_to_pil,
24
+ wavelet_hf_loss,
25
+ )
26
+ from diffsynth.data.video import save_video
27
+
28
+
29
+ def parse_args():
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument("--checkpoint", required=True)
32
+ parser.add_argument("--input_video", required=True)
33
+ parser.add_argument("--output_dir", required=True)
34
+ parser.add_argument("--steps", default="1,2,4,8,20")
35
+ parser.add_argument("--sigma_shift", type=float, default=5.0)
36
+ parser.add_argument("--sampling_noise_scale", type=float, default=0.0)
37
+ parser.add_argument("--cfg_scale", type=float, default=1.0)
38
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
39
+ parser.add_argument("--prompt", default="a person is speaking")
40
+ parser.add_argument("--negative_prompt", default="")
41
+ parser.add_argument("--height", type=int, default=832)
42
+ parser.add_argument("--width", type=int, default=480)
43
+ parser.add_argument("--num_frames", type=int, default=81)
44
+ parser.add_argument("--fps", type=int, default=16)
45
+ parser.add_argument("--sr_scale", type=int, default=2)
46
+ parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler")
47
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
48
+ parser.add_argument("--model_paths", default=None)
49
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
50
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
51
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
52
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
53
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
54
+ parser.add_argument("--device", default="cuda")
55
+ parser.add_argument("--rand_device", default="cpu")
56
+ parser.add_argument("--seed", type=int, default=42)
57
+ parser.add_argument("--tiled", action="store_true")
58
+ parser.add_argument("--tile_h", type=int, default=30)
59
+ parser.add_argument("--tile_w", type=int, default=52)
60
+ parser.add_argument("--tile_stride_h", type=int, default=15)
61
+ parser.add_argument("--tile_stride_w", type=int, default=26)
62
+ args = parser.parse_args()
63
+ args.num_inference_steps = 1
64
+ args.input_height = args.height // args.sr_scale
65
+ args.input_width = args.width // args.sr_scale
66
+ args.save_input_compare = False
67
+ args.output = None
68
+ args.model_paths = args.model_paths or default_model_paths(args.base_model_dir)
69
+ return args
70
+
71
+
72
+ def prepare_once(pipe, source_video, args):
73
+ pipe.scheduler.set_timesteps(1, shift=args.sigma_shift)
74
+ inputs_posi = {"prompt": args.prompt, "num_inference_steps": max(args.step_values)}
75
+ inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": max(args.step_values)}
76
+ inputs_shared = {
77
+ "input_video": None,
78
+ "source_video": source_video,
79
+ "seed": args.seed,
80
+ "rand_device": args.rand_device,
81
+ "height": args.height,
82
+ "width": args.width,
83
+ "num_frames": args.num_frames,
84
+ "cfg_scale": args.cfg_scale,
85
+ "cfg_merge": False,
86
+ "sigma_shift": args.sigma_shift,
87
+ "tiled": args.tiled,
88
+ "tile_size": (args.tile_h, args.tile_w),
89
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
90
+ }
91
+ for unit in pipe.units:
92
+ inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner(
93
+ unit, pipe, inputs_shared, inputs_posi, inputs_nega
94
+ )
95
+ return inputs_shared, inputs_posi, inputs_nega
96
+
97
+
98
+ @torch.no_grad()
99
+ def sample(pipe, prepared, steps: int, args):
100
+ shared, positive, negative = prepared
101
+ pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift)
102
+ source = shared["source_latents"]
103
+ latents = source.clone()
104
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
105
+ pipe.load_models_to_device(pipe.in_iteration_models)
106
+ model_inputs = dict(shared)
107
+ model_inputs.pop("latents", None)
108
+ torch.cuda.reset_peak_memory_stats()
109
+ torch.cuda.synchronize()
110
+ started = time.perf_counter()
111
+ for timestep_cpu in pipe.scheduler.timesteps:
112
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
113
+ pred = pipe.model_fn(**models, **model_inputs, **positive, latents=latents, timestep=timestep)
114
+ if args.cfg_scale != 1.0:
115
+ pred_negative = pipe.model_fn(
116
+ **models, **model_inputs, **negative, latents=latents, timestep=timestep
117
+ )
118
+ pred = pred_negative + args.cfg_scale * (pred - pred_negative)
119
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, source)
120
+ torch.cuda.synchronize()
121
+ seconds = time.perf_counter() - started
122
+ peak_gib = torch.cuda.max_memory_allocated() / 1024**3
123
+ video = decode_latents_to_btchw_01(
124
+ pipe,
125
+ latents,
126
+ args.tiled,
127
+ (args.tile_h, args.tile_w),
128
+ (args.tile_stride_h, args.tile_stride_w),
129
+ ).cpu()
130
+ return video, seconds, peak_gib, pipe.scheduler.sigmas.tolist()
131
+
132
+
133
+ def center_lpips(model, pred, target, frames=4, crop=224):
134
+ count = min(pred.shape[1], target.shape[1])
135
+ ids = torch.linspace(0, count - 1, steps=min(frames, count)).round().long()
136
+ pred, target = pred[:, ids], target[:, ids]
137
+ crop_h, crop_w = min(crop, pred.shape[-2]), min(crop, pred.shape[-1])
138
+ top, left = (pred.shape[-2] - crop_h) // 2, (pred.shape[-1] - crop_w) // 2
139
+ pred = pred[..., top:top + crop_h, left:left + crop_w]
140
+ target = target[..., top:top + crop_h, left:left + crop_w]
141
+ pred = pred.reshape(-1, 3, crop_h, crop_w).mul(2).sub(1)
142
+ target = target.reshape(-1, 3, crop_h, crop_w).mul(2).sub(1)
143
+ return model(pred, target).mean()
144
+
145
+
146
+ @torch.no_grad()
147
+ def metrics(pred, target, lpips_model):
148
+ count = min(pred.shape[1], target.shape[1])
149
+ pred, target = pred[:, :count].float(), target[:, :count].float()
150
+ mse = F.mse_loss(pred, target)
151
+ delta_pred, delta_target = pred[:, 1:] - pred[:, :-1], target[:, 1:] - target[:, :-1]
152
+ color_error = (pred - target).mean(dim=(-2, -1))
153
+ return {
154
+ "mse": mse.item(),
155
+ "psnr_db": (-10 * torch.log10(mse.clamp_min(1e-12))).item(),
156
+ "mae": F.l1_loss(pred, target).item(),
157
+ "wavelet_hf_l1": wavelet_hf_loss(pred, target, levels=1, loss_type="l1").item(),
158
+ "lpips_vgg": center_lpips(lpips_model, pred, target).item(),
159
+ "temporal_delta_l1": delta_pred.abs().mean().item(),
160
+ "temporal_delta_error": F.l1_loss(delta_pred, delta_target).item(),
161
+ "frame_color_error_std": color_error.std(dim=1).mean().item(),
162
+ }
163
+
164
+
165
+ def main():
166
+ args = parse_args()
167
+ args.step_values = [int(item) for item in args.steps.split(",")]
168
+ random.seed(args.seed)
169
+ torch.manual_seed(args.seed)
170
+ torch.cuda.manual_seed_all(args.seed)
171
+ output_dir = Path(args.output_dir)
172
+ output_dir.mkdir(parents=True, exist_ok=True)
173
+
174
+ source_video, _ = read_video(
175
+ Path(args.input_video), args.input_height, args.input_width, args.num_frames, 0
176
+ )
177
+ original_video, _ = read_video(
178
+ Path(args.input_video), args.height, args.width, args.num_frames, 0
179
+ )
180
+ original = pil_video_to_tensor_01(original_video, torch.device("cpu")).unsqueeze(0)
181
+
182
+ pipe = build_pipeline(args)
183
+ prepared = prepare_once(pipe, source_video, args)
184
+ source_latents = prepared[0]["source_latents"]
185
+ ultraflash_video = decode_latents_to_btchw_01(
186
+ pipe,
187
+ source_latents,
188
+ args.tiled,
189
+ (args.tile_h, args.tile_w),
190
+ (args.tile_stride_h, args.tile_stride_w),
191
+ ).cpu()
192
+ save_video(
193
+ tensor_btchw_01_to_pil(ultraflash_video[0]),
194
+ str(output_dir / "ultraflash_only.mp4"),
195
+ fps=args.fps,
196
+ quality=5,
197
+ )
198
+
199
+ outputs = {}
200
+ runtime = {}
201
+ schedules = {}
202
+ for steps in args.step_values:
203
+ print(f"[StepSweep] running steps={steps} shift={args.sigma_shift}", flush=True)
204
+ video, seconds, peak_gib, sigmas = sample(pipe, prepared, steps, args)
205
+ outputs[steps] = video
206
+ runtime[steps] = {"seconds": seconds, "peak_allocated_gib": peak_gib}
207
+ schedules[steps] = sigmas
208
+ save_video(
209
+ tensor_btchw_01_to_pil(video[0]),
210
+ str(output_dir / f"bridge_steps_{steps:02d}.mp4"),
211
+ fps=args.fps,
212
+ quality=5,
213
+ )
214
+
215
+ pipe.load_models_to_device([])
216
+ import lpips
217
+
218
+ lpips_model = lpips.LPIPS(net="vgg", verbose=False).eval()
219
+ results = {"ultraflash_only": metrics(ultraflash_video, original, lpips_model)}
220
+ for steps, video in outputs.items():
221
+ results[f"steps_{steps}"] = metrics(video, original, lpips_model)
222
+ results[f"steps_{steps}"].update(runtime[steps])
223
+
224
+ comparison = torch.cat(
225
+ [ultraflash_video] + [outputs[step] for step in args.step_values] + [original], dim=-1
226
+ )
227
+ save_video(
228
+ tensor_btchw_01_to_pil(comparison[0]),
229
+ str(output_dir / "comparison_ultraflash_steps1-2-4-8-20_original.mp4"),
230
+ fps=args.fps,
231
+ quality=5,
232
+ )
233
+ payload = {
234
+ "input_video": str(Path(args.input_video).resolve()),
235
+ "checkpoint": args.checkpoint,
236
+ "comparison_order": ["ultraflash_only"] + [f"steps_{s}" for s in args.step_values] + ["original"],
237
+ "settings": {
238
+ "height": args.height,
239
+ "width": args.width,
240
+ "num_frames": args.num_frames,
241
+ "sr_scale": args.sr_scale,
242
+ "sigma_shift": args.sigma_shift,
243
+ "sampling_noise_scale": args.sampling_noise_scale,
244
+ "cfg_scale": args.cfg_scale,
245
+ "target": args.target,
246
+ "prompt": args.prompt,
247
+ "seed": args.seed,
248
+ },
249
+ "sigma_schedules": schedules,
250
+ "metrics": results,
251
+ }
252
+ (output_dir / "metrics.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
253
+ print(json.dumps(results, indent=2), flush=True)
254
+
255
+
256
+ if __name__ == "__main__":
257
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/compare_bridge_steps_firstframe_anchor.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare first-frame-anchor Wan Bridge SR over several inference step counts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import random
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import torch
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[4]
18
+ if str(REPO_ROOT) not in sys.path:
19
+ sys.path.insert(0, str(REPO_ROOT))
20
+
21
+ from PIL import Image # noqa: E402
22
+
23
+ from diffsynth.bridge.wan_bridge.model_inference.infer_sr import ( # noqa: E402
24
+ default_model_paths,
25
+ pick_video,
26
+ read_video,
27
+ )
28
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
29
+ decode_latents_to_btchw_01,
30
+ pil_video_to_tensor_01,
31
+ tensor_btchw_01_to_pil,
32
+ )
33
+ from diffsynth.bridge.wan_bridge.model_training.train_sr_firstframe_anchor import ( # noqa: E402
34
+ FirstFrameAnchorWanVideoSRBridgePipeline,
35
+ replace_first_latent_frame,
36
+ )
37
+ from diffsynth.data.video import save_video # noqa: E402
38
+ from diffsynth.utils import ModelConfig # noqa: E402
39
+ from safetensors.torch import load_file # noqa: E402
40
+
41
+
42
+ def probe_video(path: Path) -> tuple[int, int, int, float]:
43
+ cap = cv2.VideoCapture(str(path))
44
+ if not cap.isOpened():
45
+ raise RuntimeError(f"Failed to open video: {path}")
46
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
47
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
48
+ frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
49
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0)
50
+ cap.release()
51
+ if width <= 0 or height <= 0 or frames <= 0:
52
+ raise RuntimeError(f"Invalid video metadata for {path}: {width}x{height}, frames={frames}")
53
+ return width, height, frames, fps
54
+
55
+
56
+ def fit_reference(image: Image.Image, height: int, width: int, mode: str) -> Image.Image:
57
+ image = image.convert("RGB")
58
+ if mode == "resize":
59
+ return image.resize((width, height), Image.Resampling.BICUBIC)
60
+ src_w, src_h = image.size
61
+ scale = max(width / src_w, height / src_h)
62
+ resized = image.resize(
63
+ (max(width, round(src_w * scale)), max(height, round(src_h * scale))),
64
+ Image.Resampling.BICUBIC,
65
+ )
66
+ left = (resized.width - width) // 2
67
+ top = (resized.height - height) // 2
68
+ return resized.crop((left, top, left + width, top + height))
69
+
70
+
71
+ def load_dit_checkpoint(pipe: FirstFrameAnchorWanVideoSRBridgePipeline, checkpoint: str) -> str:
72
+ state_dict = load_file(checkpoint, device="cpu")
73
+ prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.")
74
+ candidates = [("raw", state_dict)]
75
+ for prefix in prefixes:
76
+ if any(k.startswith(prefix) for k in state_dict):
77
+ candidates.append((
78
+ f"strip:{prefix}",
79
+ {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state_dict.items()},
80
+ ))
81
+ errors = []
82
+ for name, candidate in candidates:
83
+ try:
84
+ pipe.dit.load_state_dict(candidate, strict=True)
85
+ print(f"[FirstFrameAnchorSR] Loaded DiT checkpoint with strategy: {name}", flush=True)
86
+ return name
87
+ except Exception as exc:
88
+ errors.append((name, str(exc).splitlines()[0]))
89
+ msg = "\n".join(f"{name}: {err}" for name, err in errors)
90
+ raise RuntimeError(f"Could not strictly load first-frame-anchor checkpoint:\n{msg}")
91
+
92
+
93
+ def build_pipeline(args) -> FirstFrameAnchorWanVideoSRBridgePipeline:
94
+ model_paths = args.model_paths or default_model_paths(args.base_model_dir)
95
+ model_configs = [ModelConfig(path=path) for path in model_paths.split(",")]
96
+ pipe = FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained(
97
+ torch_dtype=torch.bfloat16,
98
+ device=args.device,
99
+ model_configs=model_configs,
100
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
101
+ )
102
+ load_strategy = load_dit_checkpoint(pipe, args.checkpoint)
103
+ pipe.latent_upsampler = None
104
+ if int(getattr(pipe.vae, "z_dim", 0)) == 48 and not getattr(
105
+ pipe.dit, "fuse_vae_embedding_in_latents", False
106
+ ):
107
+ raise RuntimeError(
108
+ "Wan2.2-TI2V VAE was loaded, but the DiT does not support fused first-frame input"
109
+ )
110
+ pipe.scheduler.noise_scale = args.sampling_noise_scale
111
+ pipe.scheduler.bridge_type = "brownian"
112
+ pipe.scheduler.training_weight_type = "uniform"
113
+ pipe.scheduler.target = args.target
114
+ pipe.eval().requires_grad_(False)
115
+ args.load_strategy = load_strategy
116
+ return pipe
117
+
118
+
119
+ def reset_seed(seed: int) -> None:
120
+ random.seed(seed)
121
+ torch.manual_seed(seed)
122
+ if torch.cuda.is_available():
123
+ torch.cuda.manual_seed_all(seed)
124
+
125
+
126
+ def upscale_and_anchor_source(
127
+ lr_video: list[Image.Image],
128
+ reference_image: Image.Image,
129
+ height: int,
130
+ width: int,
131
+ ) -> list[Image.Image]:
132
+ source = [frame.resize((width, height), Image.Resampling.BICUBIC) for frame in lr_video]
133
+ source[0] = reference_image.copy()
134
+ return source
135
+
136
+
137
+ @torch.no_grad()
138
+ def encode_reference(pipe, reference_image: Image.Image, args) -> torch.Tensor:
139
+ pipe.load_models_to_device(["vae"])
140
+ reference_video = pipe.preprocess_video([reference_image])
141
+ anchor = pipe.vae.encode(
142
+ reference_video,
143
+ device=pipe.device,
144
+ tiled=args.tiled,
145
+ tile_size=(args.tile_h, args.tile_w),
146
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
147
+ ).to(dtype=pipe.torch_dtype, device=pipe.device)
148
+ if anchor.shape[2] != 1:
149
+ raise RuntimeError(f"Expected one reference latent frame, got {tuple(anchor.shape)}")
150
+ return anchor
151
+
152
+
153
+ @torch.no_grad()
154
+ def prepare_once(pipe, source_video: list[Image.Image], reference_image: Image.Image, args):
155
+ pipe.scheduler.set_timesteps(1000, training=True)
156
+ inputs_posi = {"prompt": args.prompt, "num_inference_steps": max(args.step_values)}
157
+ inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": max(args.step_values)}
158
+ inputs_shared = {
159
+ "input_video": None,
160
+ "source_video": source_video,
161
+ "seed": args.seed,
162
+ "rand_device": args.rand_device,
163
+ "height": args.height,
164
+ "width": args.width,
165
+ "num_frames": args.num_frames,
166
+ "cfg_scale": args.cfg_scale,
167
+ "cfg_merge": False,
168
+ "sigma_shift": args.sigma_shift,
169
+ "tiled": args.tiled,
170
+ "tile_size": (args.tile_h, args.tile_w),
171
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
172
+ "fuse_vae_embedding_in_latents": bool(
173
+ getattr(pipe.dit, "fuse_vae_embedding_in_latents", False)
174
+ ),
175
+ }
176
+ for unit in pipe.units:
177
+ inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner(
178
+ unit, pipe, inputs_shared, inputs_posi, inputs_nega
179
+ )
180
+ inputs_shared["first_frame_latents"] = encode_reference(pipe, reference_image, args)
181
+ inputs_shared["source_latents"] = replace_first_latent_frame(
182
+ inputs_shared["source_latents"], inputs_shared["first_frame_latents"]
183
+ )
184
+ return inputs_shared, inputs_posi, inputs_nega
185
+
186
+
187
+ @torch.no_grad()
188
+ def sample(pipe, prepared, steps: int, args):
189
+ shared, positive, negative = prepared
190
+ reset_seed(args.seed)
191
+ pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift)
192
+ source = replace_first_latent_frame(shared["source_latents"], shared["first_frame_latents"])
193
+ latents = source.clone()
194
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
195
+ pipe.load_models_to_device(pipe.in_iteration_models)
196
+ model_inputs = dict(shared)
197
+ model_inputs.pop("latents", None)
198
+ model_inputs.pop("first_frame_latents", None)
199
+ if torch.cuda.is_available():
200
+ torch.cuda.reset_peak_memory_stats()
201
+ torch.cuda.synchronize()
202
+ started = time.perf_counter()
203
+ for timestep_cpu in pipe.scheduler.timesteps:
204
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
205
+ pred = pipe.model_fn(**models, **model_inputs, **positive, latents=latents, timestep=timestep)
206
+ if args.cfg_scale != 1.0:
207
+ pred_neg = pipe.model_fn(
208
+ **models, **model_inputs, **negative, latents=latents, timestep=timestep
209
+ )
210
+ pred = pred_neg + args.cfg_scale * (pred - pred_neg)
211
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, source)
212
+ if args.anchor_each_step:
213
+ latents = replace_first_latent_frame(latents, shared["first_frame_latents"])
214
+ if torch.cuda.is_available():
215
+ torch.cuda.synchronize()
216
+ peak_gib = torch.cuda.max_memory_allocated() / 1024**3
217
+ else:
218
+ peak_gib = 0.0
219
+ seconds = time.perf_counter() - started
220
+ return latents, seconds, peak_gib, [float(s) for s in pipe.scheduler.sigmas]
221
+
222
+
223
+ @torch.no_grad()
224
+ def decode(pipe, latents: torch.Tensor, args) -> torch.Tensor:
225
+ pipe.load_models_to_device(["vae"])
226
+ return decode_latents_to_btchw_01(
227
+ pipe,
228
+ latents,
229
+ tiled=args.tiled,
230
+ tile_size=(args.tile_h, args.tile_w),
231
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
232
+ ).cpu()
233
+
234
+
235
+ def save_with_optional_audio(video: torch.Tensor, output: Path, source_audio_video: Path, fps: int, copy_audio: bool):
236
+ output.parent.mkdir(parents=True, exist_ok=True)
237
+ if not copy_audio:
238
+ save_video(tensor_btchw_01_to_pil(video[0]), str(output), fps=fps, quality=5)
239
+ return
240
+ silent = output.with_name(f".{output.stem}_silent{output.suffix}")
241
+ save_video(tensor_btchw_01_to_pil(video[0]), str(silent), fps=fps, quality=5)
242
+ try:
243
+ subprocess.run(
244
+ [
245
+ "ffmpeg", "-y", "-loglevel", "error",
246
+ "-i", str(silent), "-i", str(source_audio_video),
247
+ "-map", "0:v:0", "-map", "1:a?",
248
+ "-c:v", "copy", "-c:a", "aac", "-shortest", str(output),
249
+ ],
250
+ check=True,
251
+ )
252
+ finally:
253
+ silent.unlink(missing_ok=True)
254
+
255
+
256
+ def save_lr_copy(source_path: Path, output: Path, copy_audio: bool, fps: int, lr_video: list[Image.Image]) -> None:
257
+ output.parent.mkdir(parents=True, exist_ok=True)
258
+ if copy_audio:
259
+ shutil.copy2(source_path, output)
260
+ else:
261
+ save_video(lr_video, str(output), fps=fps, quality=5)
262
+
263
+
264
+ def parse_args():
265
+ parser = argparse.ArgumentParser()
266
+ parser.add_argument("--checkpoint", required=True)
267
+ parser.add_argument("--input_video", required=True)
268
+ parser.add_argument("--reference_image", required=True)
269
+ parser.add_argument("--output_dir", required=True)
270
+ parser.add_argument("--output_stem", default=None)
271
+ parser.add_argument("--steps", default="1,2,4,8,12")
272
+ parser.add_argument("--sigma_shift", type=float, default=5.0)
273
+ parser.add_argument("--sampling_noise_scale", type=float, default=1.0)
274
+ parser.add_argument("--cfg_scale", type=float, default=1.0)
275
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
276
+ parser.add_argument("--prompt", default="a person is speaking")
277
+ parser.add_argument("--negative_prompt", default="")
278
+ parser.add_argument("--height", type=int, default=832)
279
+ parser.add_argument("--width", type=int, default=480)
280
+ parser.add_argument("--input_height", type=int, default=None)
281
+ parser.add_argument("--input_width", type=int, default=None)
282
+ parser.add_argument("--num_frames", type=int, default=81)
283
+ parser.add_argument("--start_frame", type=int, default=0)
284
+ parser.add_argument("--sr_scale", type=int, default=2)
285
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
286
+ parser.add_argument("--model_paths", default=None)
287
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
288
+ parser.add_argument("--device", default="cuda")
289
+ parser.add_argument("--rand_device", default="cpu")
290
+ parser.add_argument("--seed", type=int, default=42)
291
+ parser.add_argument("--fps", type=int, default=None)
292
+ parser.add_argument("--reference_resize_mode", choices=["crop", "resize"], default="resize")
293
+ parser.add_argument("--copy_audio", action=argparse.BooleanOptionalAction, default=True)
294
+ parser.add_argument(
295
+ "--anchor_each_step",
296
+ action=argparse.BooleanOptionalAction,
297
+ default=True,
298
+ help="Re-lock latent frame 0 to the reference after every denoise step. Disable to anchor only at initialization.",
299
+ )
300
+ parser.add_argument("--tiled", action="store_true", default=False)
301
+ parser.add_argument("--tile_h", type=int, default=30)
302
+ parser.add_argument("--tile_w", type=int, default=52)
303
+ parser.add_argument("--tile_stride_h", type=int, default=15)
304
+ parser.add_argument("--tile_stride_w", type=int, default=26)
305
+ args = parser.parse_args()
306
+ args.step_values = [int(item) for item in args.steps.split(",") if item.strip()]
307
+ if not args.step_values:
308
+ raise ValueError("--steps must contain at least one integer")
309
+ args.model_paths = args.model_paths or default_model_paths(args.base_model_dir)
310
+ return args
311
+
312
+
313
+ def main():
314
+ args = parse_args()
315
+ reset_seed(args.seed)
316
+ source_path = pick_video(args.input_video).resolve()
317
+ source_w, source_h, source_frames, source_fps = probe_video(source_path)
318
+ args.num_frames = min(args.num_frames, source_frames)
319
+ args.fps = args.fps or max(1, int(round(source_fps)))
320
+ args.input_height = args.input_height or source_h
321
+ args.input_width = args.input_width or source_w
322
+ output_dir = Path(args.output_dir)
323
+ output_dir.mkdir(parents=True, exist_ok=True)
324
+ stem = args.output_stem or source_path.stem
325
+
326
+ lr_video, _ = read_video(
327
+ source_path,
328
+ args.input_height,
329
+ args.input_width,
330
+ args.num_frames,
331
+ args.start_frame,
332
+ )
333
+ reference_image = fit_reference(
334
+ Image.open(args.reference_image), args.height, args.width, args.reference_resize_mode
335
+ )
336
+ source_video = upscale_and_anchor_source(lr_video, reference_image, args.height, args.width)
337
+
338
+ lr_output = output_dir / f"{stem}_liveact_lr.mp4"
339
+ anchored_source_output = output_dir / f"{stem}_bicubic_anchor_source.mp4"
340
+ save_lr_copy(source_path, lr_output, args.copy_audio, args.fps, lr_video)
341
+ save_video(source_video, str(anchored_source_output), fps=args.fps, quality=5)
342
+
343
+ print(
344
+ f"[FirstFrameAnchorCascade] LR={source_path} {source_w}x{source_h} frames={args.num_frames}; "
345
+ f"target={args.width}x{args.height}; steps={args.step_values}; shift={args.sigma_shift}; noise={args.sampling_noise_scale}",
346
+ flush=True,
347
+ )
348
+ pipe = build_pipeline(args)
349
+ prepared = prepare_once(pipe, source_video, reference_image, args)
350
+ source_preview = decode(pipe, prepared[0]["source_latents"], args)
351
+ source_preview_output = output_dir / f"{stem}_source_latents_decoded.mp4"
352
+ save_with_optional_audio(source_preview, source_preview_output, source_path, args.fps, args.copy_audio)
353
+
354
+ outputs = {}
355
+ runtime = {}
356
+ schedules = {}
357
+ for steps in args.step_values:
358
+ print(f"[FirstFrameAnchorCascade] Running steps={steps}", flush=True)
359
+ latents, seconds, peak_gib, sigmas = sample(pipe, prepared, steps, args)
360
+ video = decode(pipe, latents, args)
361
+ outputs[steps] = video
362
+ runtime[steps] = {"seconds": seconds, "peak_allocated_gib": peak_gib}
363
+ schedules[str(steps)] = sigmas
364
+ save_with_optional_audio(
365
+ video,
366
+ output_dir / f"{stem}_bridge_ffanchor_steps_{steps:02d}.mp4",
367
+ source_path,
368
+ args.fps,
369
+ args.copy_audio,
370
+ )
371
+
372
+ comparison = torch.cat([source_preview] + [outputs[step] for step in args.step_values], dim=-1)
373
+ comparison_name = f"{stem}_comparison_source_{'_'.join(f's{s}' for s in args.step_values)}.mp4"
374
+ comparison_output = output_dir / comparison_name
375
+ save_with_optional_audio(comparison, comparison_output, source_path, args.fps, args.copy_audio)
376
+
377
+ metadata = {
378
+ "input_video": str(source_path),
379
+ "reference_image": str(Path(args.reference_image).resolve()),
380
+ "checkpoint": args.checkpoint,
381
+ "load_strategy": getattr(args, "load_strategy", None),
382
+ "outputs": {
383
+ "liveact_lr": str(lr_output),
384
+ "bicubic_anchor_source": str(anchored_source_output),
385
+ "source_latents_decoded": str(source_preview_output),
386
+ "comparison": str(comparison_output),
387
+ "steps": {
388
+ str(step): str(output_dir / f"{stem}_bridge_ffanchor_steps_{step:02d}.mp4")
389
+ for step in args.step_values
390
+ },
391
+ },
392
+ "runtime": runtime,
393
+ "sigma_schedules": schedules,
394
+ "settings": {
395
+ "input_size_hw": [args.input_height, args.input_width],
396
+ "target_size_hw": [args.height, args.width],
397
+ "num_frames": args.num_frames,
398
+ "fps": args.fps,
399
+ "steps": args.step_values,
400
+ "sigma_shift": args.sigma_shift,
401
+ "sampling_noise_scale": args.sampling_noise_scale,
402
+ "cfg_scale": args.cfg_scale,
403
+ "target": args.target,
404
+ "prompt": args.prompt,
405
+ "seed": args.seed,
406
+ "first_frame_anchor": True,
407
+ "anchor_each_step": args.anchor_each_step,
408
+ "source_mode": "bicubic_upscaled_liveact_lr_with_hr_reference_first_frame",
409
+ },
410
+ }
411
+ (output_dir / f"{stem}_ffanchor_step_sweep.json").write_text(
412
+ json.dumps(metadata, indent=2, ensure_ascii=False),
413
+ encoding="utf-8",
414
+ )
415
+ print(f"[FirstFrameAnchorCascade] Outputs written to: {output_dir}", flush=True)
416
+
417
+
418
+ if __name__ == "__main__":
419
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/diagnose_flicker.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Measure temporal brightness/color/structure jumps and align them to chunks."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+
14
+ def read_frames(path: Path) -> tuple[np.ndarray, float]:
15
+ cap = cv2.VideoCapture(str(path))
16
+ if not cap.isOpened():
17
+ raise RuntimeError(f"Cannot open {path}")
18
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0)
19
+ frames = []
20
+ while True:
21
+ ok, frame = cap.read()
22
+ if not ok:
23
+ break
24
+ frames.append(frame)
25
+ cap.release()
26
+ if not frames:
27
+ raise RuntimeError(f"No frames in {path}")
28
+ return np.stack(frames), fps
29
+
30
+
31
+ def robust_z(x: np.ndarray) -> np.ndarray:
32
+ med = np.median(x)
33
+ mad = np.median(np.abs(x - med)) + 1e-8
34
+ return 0.6745 * (x - med) / mad
35
+
36
+
37
+ def analyze(frames: np.ndarray, fps: float, chunk_latent: int, temporal_stride: int) -> dict:
38
+ rgb = frames[:, :, :, ::-1].astype(np.float32) / 255.0
39
+ gray = np.stack([
40
+ cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for frame in frames
41
+ ]).astype(np.float32) / 255.0
42
+ lab = np.stack([
43
+ cv2.cvtColor(frame, cv2.COLOR_BGR2LAB) for frame in frames
44
+ ]).astype(np.float32)
45
+ # OpenCV LAB is approximately [0,255] for all channels.
46
+ lum = gray.mean(axis=(1, 2))
47
+ lab_mean = lab.mean(axis=(1, 2))
48
+ sat = rgb.max(axis=3).mean(axis=(1, 2)) - rgb.min(axis=3).mean(axis=(1, 2))
49
+ frame_diff = np.abs(gray[1:] - gray[:-1]).mean(axis=(1, 2))
50
+ color_diff = np.abs(lab_mean[1:] - lab_mean[:-1]).mean(axis=1)
51
+ edge = np.stack([
52
+ cv2.Laplacian(gray[i], cv2.CV_32F).var() for i in range(len(gray))
53
+ ])
54
+ edge_diff = np.abs(edge[1:] - edge[:-1])
55
+
56
+ scores = (
57
+ robust_z(frame_diff)
58
+ + robust_z(color_diff)
59
+ + 0.25 * robust_z(edge_diff)
60
+ )
61
+ order = np.argsort(scores)[::-1]
62
+ boundaries = list(range(1 + chunk_latent * temporal_stride, len(frames), chunk_latent * temporal_stride))
63
+
64
+ def around(index: int) -> dict:
65
+ lo = max(0, index - 2)
66
+ hi = min(len(frames) - 1, index + 2)
67
+ return {
68
+ "frame": int(index),
69
+ "time_sec": round(index / fps, 4),
70
+ "lum": round(float(lum[index]), 6),
71
+ "lab": [round(float(v), 4) for v in lab_mean[index]],
72
+ "sat": round(float(sat[index]), 6),
73
+ "window_lum_range": round(float(lum[lo:hi + 1].max() - lum[lo:hi + 1].min()), 6),
74
+ }
75
+
76
+ boundary_stats = []
77
+ for b in boundaries:
78
+ left = max(0, b - 3)
79
+ right = min(len(frames) - 1, b + 2)
80
+ boundary_stats.append({
81
+ "boundary_frame": b,
82
+ "boundary_time_sec": round(b / fps, 4),
83
+ "lum_jump_at_boundary": round(float(abs(lum[b] - lum[b - 1])), 6),
84
+ "color_jump_at_boundary": round(float(color_diff[b - 1]), 6),
85
+ "frame_diff_at_boundary": round(float(frame_diff[b - 1]), 6),
86
+ "left_mean_lum": round(float(lum[left:b].mean()), 6),
87
+ "right_mean_lum": round(float(lum[b:right + 1].mean()), 6),
88
+ })
89
+
90
+ return {
91
+ "frames": int(len(frames)),
92
+ "fps": fps,
93
+ "duration_sec": round(len(frames) / fps, 4),
94
+ "size": [int(frames.shape[2]), int(frames.shape[1])],
95
+ "chunk_latent_frames": chunk_latent,
96
+ "temporal_stride": temporal_stride,
97
+ "predicted_chunk_boundaries": boundaries,
98
+ "top_temporal_jumps": [around(int(i + 1)) | {
99
+ "frame_diff": round(float(frame_diff[i]), 6),
100
+ "color_diff": round(float(color_diff[i]), 6),
101
+ "edge_diff": round(float(edge_diff[i]), 6),
102
+ "combined_robust_score": round(float(scores[i]), 4),
103
+ } for i in order[:12]],
104
+ "boundary_stats": boundary_stats,
105
+ "summary": {
106
+ "lum_min": round(float(lum.min()), 6),
107
+ "lum_max": round(float(lum.max()), 6),
108
+ "lum_std": round(float(lum.std()), 6),
109
+ "max_frame_diff": round(float(frame_diff.max(initial=0)), 6),
110
+ "max_color_diff": round(float(color_diff.max(initial=0)), 6),
111
+ "median_frame_diff": round(float(np.median(frame_diff)), 6),
112
+ },
113
+ "series": {
114
+ "luminance": [round(float(v), 6) for v in lum],
115
+ "lab_mean": [[round(float(v), 4) for v in row] for row in lab_mean],
116
+ "saturation": [round(float(v), 6) for v in sat],
117
+ "frame_diff": [round(float(v), 6) for v in frame_diff],
118
+ "color_diff": [round(float(v), 6) for v in color_diff],
119
+ "edge_variance": [round(float(v), 4) for v in edge],
120
+ },
121
+ }
122
+
123
+
124
+ def save_plot(report: dict, path: Path) -> None:
125
+ import matplotlib.pyplot as plt
126
+
127
+ n = report["frames"]
128
+ x = np.arange(n)
129
+ boundaries = report["predicted_chunk_boundaries"]
130
+ fig, axes = plt.subplots(3, 1, figsize=(15, 9), sharex=True)
131
+ axes[0].plot(x, report["series"]["luminance"], label="mean luminance")
132
+ axes[0].plot(x, report["series"]["saturation"], label="mean saturation", alpha=0.8)
133
+ axes[0].set_ylabel("brightness / sat")
134
+ axes[0].legend(loc="upper right")
135
+ axes[1].plot(x[1:], report["series"]["frame_diff"], label="gray frame diff")
136
+ axes[1].plot(x[1:], report["series"]["color_diff"], label="Lab color diff")
137
+ axes[1].set_ylabel("temporal change")
138
+ axes[1].legend(loc="upper right")
139
+ axes[2].plot(x, report["series"]["edge_variance"], label="Laplacian variance")
140
+ axes[2].set_ylabel("structure")
141
+ axes[2].set_xlabel("pixel frame")
142
+ for ax in axes:
143
+ for b in boundaries:
144
+ ax.axvline(b, color="red", alpha=0.35, linestyle="--")
145
+ fig.suptitle(f"{report['frames']} frames; red lines = predicted chunk boundaries")
146
+ fig.tight_layout()
147
+ fig.savefig(path, dpi=160)
148
+ plt.close(fig)
149
+
150
+
151
+ def main() -> None:
152
+ parser = argparse.ArgumentParser(description=__doc__)
153
+ parser.add_argument("video", type=Path)
154
+ parser.add_argument("--output_dir", type=Path, default=None)
155
+ parser.add_argument("--chunk_latent_frames", type=int, default=4)
156
+ parser.add_argument("--temporal_stride", type=int, default=4)
157
+ args = parser.parse_args()
158
+ out = args.output_dir or args.video.with_suffix("")
159
+ out.mkdir(parents=True, exist_ok=True)
160
+ frames, fps = read_frames(args.video)
161
+ report = analyze(frames, fps, args.chunk_latent_frames, args.temporal_stride)
162
+ (out / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
163
+ save_plot(report, out / "flicker_diagnostic.png")
164
+ print(json.dumps({
165
+ "report": str(out / "report.json"),
166
+ "plot": str(out / "flicker_diagnostic.png"),
167
+ "top_temporal_jumps": report["top_temporal_jumps"][:8],
168
+ "boundary_stats": report["boundary_stats"],
169
+ }, indent=2))
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import random
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import torch
11
+ from PIL import Image
12
+ from safetensors.torch import load_file
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parents[4]
15
+ if str(REPO_ROOT) not in sys.path:
16
+ sys.path.insert(0, str(REPO_ROOT))
17
+
18
+ from diffsynth.data.video import save_video # noqa: E402
19
+ from diffsynth.utils import ModelConfig # noqa: E402
20
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
21
+ WanVideoSRBridgePipeline,
22
+ WanVideoSRUnit_UltraFlashLatentUpsampler,
23
+ center_crop_resize,
24
+ decode_latents_to_btchw_01,
25
+ load_ultraflash_latent_upsampler,
26
+ pil_video_to_tensor_01,
27
+ tensor_btchw_01_to_pil,
28
+ )
29
+
30
+
31
+ def load_dit_checkpoint(pipe: WanVideoSRBridgePipeline, checkpoint: str):
32
+ state_dict = load_file(checkpoint, device="cpu")
33
+ prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.")
34
+ candidates = [("raw", state_dict)]
35
+ for prefix in prefixes:
36
+ if any(k.startswith(prefix) for k in state_dict):
37
+ candidates.append((
38
+ f"strip:{prefix}",
39
+ {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state_dict.items()},
40
+ ))
41
+
42
+ errors = []
43
+ for name, candidate in candidates:
44
+ try:
45
+ pipe.dit.load_state_dict(candidate, strict=True)
46
+ print(f"[WanBridgeSR] Loaded DiT checkpoint with strategy: {name}")
47
+ return
48
+ except Exception as exc:
49
+ errors.append((name, str(exc)))
50
+ msg = "\n".join(f"{name}: {err}" for name, err in errors)
51
+ raise RuntimeError(f"Could not strictly load SR bridge checkpoint:\n{msg}")
52
+
53
+
54
+ def default_model_paths(base_model_dir: str) -> str:
55
+ base = Path(base_model_dir)
56
+ paths = [
57
+ base / "diffusion_pytorch_model.safetensors",
58
+ base / "models_t5_umt5-xxl-enc-bf16.pth",
59
+ base / "Wan2.1_VAE.pth",
60
+ ]
61
+ for path in paths:
62
+ if not path.exists():
63
+ raise FileNotFoundError(f"Missing Wan model file: {path}")
64
+ return ",".join(str(path) for path in paths)
65
+
66
+
67
+ def build_pipeline(args) -> WanVideoSRBridgePipeline:
68
+ model_paths = args.model_paths or default_model_paths(args.base_model_dir)
69
+ model_configs = [ModelConfig(path=path) for path in model_paths.split(",")]
70
+ pipe = WanVideoSRBridgePipeline.from_pretrained(
71
+ torch_dtype=torch.bfloat16,
72
+ device=args.device,
73
+ model_configs=model_configs,
74
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
75
+ )
76
+ load_dit_checkpoint(pipe, args.checkpoint)
77
+ if args.source_mode == "upsampler":
78
+ pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device=args.device)
79
+ pipe.units = pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()]
80
+ print(f"[WanBridgeSR] source_mode=upsampler ckpt={args.latent_upsampler_ckpt}")
81
+ else:
82
+ pipe.latent_upsampler = None
83
+ print("[WanBridgeSR] source_mode=bicubic")
84
+ pipe.scheduler.noise_scale = args.sampling_noise_scale
85
+ pipe.scheduler.bridge_type = "brownian"
86
+ pipe.scheduler.training_weight_type = "uniform"
87
+ pipe.scheduler.target = args.target
88
+ pipe.eval().requires_grad_(False)
89
+ return pipe
90
+
91
+
92
+ def pick_video(path: str | Path) -> Path:
93
+ path = Path(path)
94
+ if path.is_file():
95
+ return path
96
+ if path.is_dir():
97
+ videos = sorted(
98
+ p for p in path.rglob("*")
99
+ if p.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".avi")
100
+ )
101
+ if videos:
102
+ return videos[0]
103
+ raise FileNotFoundError(f"No input video found: {path}")
104
+
105
+
106
+ def read_video(path: Path, height: int, width: int, frames: int, start_frame: int = 0) -> tuple[list[Image.Image], float]:
107
+ cap = cv2.VideoCapture(str(path))
108
+ if not cap.isOpened():
109
+ raise RuntimeError(f"Failed to open video: {path}")
110
+ fps = cap.get(cv2.CAP_PROP_FPS) or 16
111
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
112
+ start_frame = max(int(start_frame), 0)
113
+ if frame_count > 0:
114
+ start_frame = min(start_frame, max(frame_count - 1, 0))
115
+ cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
116
+ out = []
117
+ last = None
118
+ while len(out) < frames:
119
+ ok, frame = cap.read()
120
+ if not ok:
121
+ if last is None:
122
+ break
123
+ frame = last.copy()
124
+ last = frame
125
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
126
+ image = Image.fromarray(frame)
127
+ out.append(center_crop_resize(image, height, width))
128
+ cap.release()
129
+ if not out:
130
+ raise RuntimeError(f"No frames decoded from: {path}")
131
+ while len(out) < frames:
132
+ out.append(out[-1].copy())
133
+ return out, float(fps)
134
+
135
+
136
+ def save_input_pred_video(path: Path, source_video: list[Image.Image], pred_video_btchw_01: torch.Tensor, fps: int):
137
+ source = pil_video_to_tensor_01(source_video, pred_video_btchw_01.device).unsqueeze(0)
138
+ if source.shape[-2:] != pred_video_btchw_01.shape[-2:]:
139
+ b, t, c, h, w = source.shape
140
+ source = torch.nn.functional.interpolate(
141
+ source.reshape(b * t, c, h, w),
142
+ size=pred_video_btchw_01.shape[-2:],
143
+ mode="bicubic",
144
+ align_corners=False,
145
+ antialias=True,
146
+ ).reshape(b, t, c, pred_video_btchw_01.shape[-2], pred_video_btchw_01.shape[-1]).clamp(0, 1)
147
+ min_t = min(source.shape[1], pred_video_btchw_01.shape[1])
148
+ strip = torch.cat([source[:, :min_t], pred_video_btchw_01[:, :min_t]], dim=-1)
149
+ save_video(tensor_btchw_01_to_pil(strip[0]), str(path), fps=fps, quality=5)
150
+
151
+
152
+ @torch.no_grad()
153
+ def run_sr(pipe: WanVideoSRBridgePipeline, source_video: list[Image.Image], prompt: str, args) -> torch.Tensor:
154
+ random.seed(args.seed)
155
+ torch.manual_seed(args.seed)
156
+ if torch.cuda.is_available():
157
+ torch.cuda.manual_seed_all(args.seed)
158
+
159
+ pipe.scheduler.set_timesteps(args.num_inference_steps, shift=args.sigma_shift)
160
+ inputs_posi = {"prompt": prompt, "num_inference_steps": args.num_inference_steps}
161
+ inputs_nega = {"negative_prompt": args.negative_prompt, "num_inference_steps": args.num_inference_steps}
162
+ inputs_shared = {
163
+ "input_video": None,
164
+ "source_video": source_video,
165
+ "seed": args.seed,
166
+ "rand_device": args.rand_device,
167
+ "height": args.height,
168
+ "width": args.width,
169
+ "num_frames": args.num_frames,
170
+ "cfg_scale": args.cfg_scale,
171
+ "cfg_merge": False,
172
+ "sigma_shift": args.sigma_shift,
173
+ "tiled": args.tiled,
174
+ "tile_size": (args.tile_h, args.tile_w),
175
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
176
+ }
177
+
178
+ for unit in pipe.units:
179
+ inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner(unit, pipe, inputs_shared, inputs_posi, inputs_nega)
180
+
181
+ latents = inputs_shared["source_latents"].clone()
182
+ pipe.load_models_to_device(pipe.in_iteration_models)
183
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
184
+ model_inputs = dict(inputs_shared)
185
+ model_inputs.pop("latents", None)
186
+
187
+ for timestep_cpu in pipe.scheduler.timesteps:
188
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
189
+ pred_pos = pipe.model_fn(**models, **model_inputs, **inputs_posi, latents=latents, timestep=timestep)
190
+ if args.cfg_scale != 1.0:
191
+ pred_neg = pipe.model_fn(**models, **model_inputs, **inputs_nega, latents=latents, timestep=timestep)
192
+ pred = pred_neg + args.cfg_scale * (pred_pos - pred_neg)
193
+ else:
194
+ pred = pred_pos
195
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, inputs_shared["source_latents"])
196
+
197
+ pipe.load_models_to_device(["vae"])
198
+ return decode_latents_to_btchw_01(
199
+ pipe,
200
+ latents,
201
+ tiled=args.tiled,
202
+ tile_size=(args.tile_h, args.tile_w),
203
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
204
+ )
205
+
206
+
207
+ def parse_args():
208
+ parser = argparse.ArgumentParser(description="Wan bridge-SR inference for SR checkpoints trained by train_sr.py.")
209
+ parser.add_argument("--checkpoint", required=True, help="SR bridge DiT safetensors checkpoint.")
210
+ parser.add_argument("--input_video", required=True, help="LR/base input video or directory.")
211
+ parser.add_argument("--output", default=None)
212
+ parser.add_argument("--prompt", default="")
213
+ parser.add_argument("--negative_prompt", default="")
214
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
215
+ parser.add_argument("--model_paths", default=None)
216
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
217
+ parser.add_argument("--height", type=int, default=480)
218
+ parser.add_argument("--width", type=int, default=832)
219
+ parser.add_argument("--input_height", type=int, default=None)
220
+ parser.add_argument("--input_width", type=int, default=None)
221
+ parser.add_argument("--num_frames", type=int, default=81)
222
+ parser.add_argument("--start_frame", type=int, default=0)
223
+ parser.add_argument("--sr_scale", type=int, default=2)
224
+ parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler")
225
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
226
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
227
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
228
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
229
+ parser.add_argument("--num_inference_steps", type=int, default=8)
230
+ parser.add_argument("--sampling_noise_scale", type=float, default=0.0)
231
+ parser.add_argument("--sigma_shift", type=float, default=1.0)
232
+ parser.add_argument("--cfg_scale", type=float, default=1.0)
233
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
234
+ parser.add_argument("--seed", type=int, default=42)
235
+ parser.add_argument("--fps", type=int, default=None)
236
+ parser.add_argument("--device", default="cuda")
237
+ parser.add_argument("--rand_device", default="cpu")
238
+ parser.add_argument("--tiled", action="store_true", default=False)
239
+ parser.add_argument("--tile_h", type=int, default=30)
240
+ parser.add_argument("--tile_w", type=int, default=52)
241
+ parser.add_argument("--tile_stride_h", type=int, default=15)
242
+ parser.add_argument("--tile_stride_w", type=int, default=26)
243
+ parser.add_argument("--save_input_compare", action="store_true", default=False)
244
+ return parser.parse_args()
245
+
246
+
247
+ def main():
248
+ args = parse_args()
249
+ source_path = pick_video(args.input_video)
250
+ input_h = args.input_height or (args.height if args.source_mode == "bicubic" else args.height // args.sr_scale)
251
+ input_w = args.input_width or (args.width if args.source_mode == "bicubic" else args.width // args.sr_scale)
252
+ source_video, source_fps = read_video(source_path, input_h, input_w, args.num_frames, args.start_frame)
253
+ fps = args.fps or int(round(source_fps)) or 16
254
+ output = Path(args.output) if args.output else Path(f"{source_path.stem}_wan_bridge_sr.mp4")
255
+ output.parent.mkdir(parents=True, exist_ok=True)
256
+
257
+ print(f"[WanBridgeSR] input={source_path} read={input_h}x{input_w} frames={args.num_frames}")
258
+ print(f"[WanBridgeSR] target={args.height}x{args.width} source_mode={args.source_mode} steps={args.num_inference_steps}")
259
+ pipe = build_pipeline(args)
260
+ pred_video = run_sr(pipe, source_video, args.prompt, args)
261
+ save_video(tensor_btchw_01_to_pil(pred_video[0]), str(output), fps=fps, quality=5)
262
+ print(f"[WanBridgeSR] Saved: {output}")
263
+
264
+ if args.save_input_compare:
265
+ compare = output.with_name(output.stem + "_input_pred.mp4")
266
+ save_input_pred_video(compare, source_video, pred_video, fps)
267
+ print(f"[WanBridgeSR] Saved compare: {compare}")
268
+
269
+ meta = {
270
+ "checkpoint": args.checkpoint,
271
+ "input_video": str(source_path),
272
+ "output": str(output),
273
+ "prompt": args.prompt,
274
+ "height": args.height,
275
+ "width": args.width,
276
+ "input_height": input_h,
277
+ "input_width": input_w,
278
+ "num_frames": args.num_frames,
279
+ "source_mode": args.source_mode,
280
+ "latent_upsampler_ckpt": args.latent_upsampler_ckpt,
281
+ "num_inference_steps": args.num_inference_steps,
282
+ "sampling_noise_scale": args.sampling_noise_scale,
283
+ "sigma_shift": args.sigma_shift,
284
+ "cfg_scale": args.cfg_scale,
285
+ "target": args.target,
286
+ "seed": args.seed,
287
+ "output_shape_btchw": list(pred_video.shape),
288
+ }
289
+ output.with_suffix(".json").write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
290
+
291
+
292
+ if __name__ == "__main__":
293
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_reference.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run frozen Wan Bridge SR and reference-adapted Bridge SR on one LR video.
2
+
3
+ This is the post-processing half of the SoulX-LiveAct cascade. It loads the
4
+ frozen Bridge once, runs the exact same prepared LR source through the base and
5
+ reference paths, and writes LR/base/adapter videos for direct comparison.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import random
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import cv2
19
+ import torch
20
+ from PIL import Image
21
+
22
+ REPO_ROOT = Path(__file__).resolve().parents[4]
23
+ if str(REPO_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(REPO_ROOT))
25
+
26
+ from diffsynth.bridge.wan_bridge.model_inference.infer_sr import ( # noqa: E402
27
+ build_pipeline,
28
+ default_model_paths,
29
+ pick_video,
30
+ read_video,
31
+ )
32
+ from diffsynth.bridge.wan_bridge.model_training.reference_adapter import ( # noqa: E402
33
+ clear_reference_condition,
34
+ install_reference_adapters,
35
+ parse_block_ids,
36
+ prepare_reference_condition,
37
+ reference_blocks,
38
+ set_reference_adapters_enabled,
39
+ )
40
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
41
+ decode_latents_to_btchw_01,
42
+ tensor_btchw_01_to_pil,
43
+ )
44
+ from diffsynth.bridge.wan_bridge.model_training.train_sr_reference import ( # noqa: E402
45
+ load_adapter_checkpoint,
46
+ )
47
+ from diffsynth.data.video import save_video # noqa: E402
48
+ from diffsynth.bridge.wan_bridge.model_inference.attention_heatmap import ( # noqa: E402
49
+ ReferenceAttentionRecorder,
50
+ )
51
+
52
+
53
+ def probe_video(path: Path) -> tuple[int, int, int, float]:
54
+ cap = cv2.VideoCapture(str(path))
55
+ if not cap.isOpened():
56
+ raise RuntimeError(f"Failed to open video: {path}")
57
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
58
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
59
+ frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
60
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0)
61
+ cap.release()
62
+ if width <= 0 or height <= 0 or frames <= 0:
63
+ raise RuntimeError(f"Invalid video metadata for {path}: {width}x{height}, frames={frames}")
64
+ return width, height, frames, fps
65
+
66
+
67
+ def fit_reference(image: Image.Image, height: int, width: int, mode: str) -> Image.Image:
68
+ image = image.convert("RGB")
69
+ if mode == "resize":
70
+ return image.resize((width, height), Image.Resampling.BICUBIC)
71
+ src_w, src_h = image.size
72
+ scale = max(width / src_w, height / src_h)
73
+ resized = image.resize(
74
+ (max(width, round(src_w * scale)), max(height, round(src_h * scale))),
75
+ Image.Resampling.BICUBIC,
76
+ )
77
+ left = (resized.width - width) // 2
78
+ top = (resized.height - height) // 2
79
+ return resized.crop((left, top, left + width, top + height))
80
+
81
+
82
+ @torch.no_grad()
83
+ def encode_reference(pipe, reference_image: Image.Image, args) -> torch.Tensor:
84
+ pipe.load_models_to_device(["vae"])
85
+ reference_video = pipe.preprocess_video([reference_image])
86
+ reference_latents = pipe.vae.encode(
87
+ reference_video,
88
+ device=pipe.device,
89
+ tiled=args.tiled,
90
+ tile_size=(args.tile_h, args.tile_w),
91
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
92
+ ).to(dtype=pipe.torch_dtype, device=pipe.device)
93
+ if reference_latents.shape[2] != 1:
94
+ raise RuntimeError(
95
+ f"A single LiveAct reference image must encode to one latent frame, got {reference_latents.shape[2]}"
96
+ )
97
+ return reference_latents
98
+
99
+
100
+ @torch.no_grad()
101
+ def prepare_inputs(pipe, source_video: list[Image.Image], prompt: str, args):
102
+ inputs_posi = {"prompt": prompt, "num_inference_steps": args.num_inference_steps}
103
+ inputs_nega = {
104
+ "negative_prompt": args.negative_prompt,
105
+ "num_inference_steps": args.num_inference_steps,
106
+ }
107
+ inputs_shared = {
108
+ "input_video": None,
109
+ "source_video": source_video,
110
+ "seed": args.seed,
111
+ "rand_device": args.rand_device,
112
+ "height": args.height,
113
+ "width": args.width,
114
+ "num_frames": args.num_frames,
115
+ "cfg_scale": args.cfg_scale,
116
+ "cfg_merge": False,
117
+ "sigma_shift": args.sigma_shift,
118
+ "tiled": args.tiled,
119
+ "tile_size": (args.tile_h, args.tile_w),
120
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
121
+ }
122
+ for unit in pipe.units:
123
+ inputs_shared, inputs_posi, inputs_nega = pipe.unit_runner(
124
+ unit, pipe, inputs_shared, inputs_posi, inputs_nega
125
+ )
126
+ return inputs_shared, inputs_posi, inputs_nega
127
+
128
+
129
+ def reset_seed(seed: int) -> None:
130
+ random.seed(seed)
131
+ torch.manual_seed(seed)
132
+ if torch.cuda.is_available():
133
+ torch.cuda.manual_seed_all(seed)
134
+
135
+
136
+ @torch.no_grad()
137
+ def predict_latents(pipe, prepared, args, reference_latents: torch.Tensor | None) -> torch.Tensor:
138
+ inputs_shared, inputs_posi, inputs_nega = prepared
139
+ reset_seed(args.seed)
140
+ pipe.scheduler.set_timesteps(args.num_inference_steps, shift=args.sigma_shift)
141
+
142
+ source_latents = inputs_shared["source_latents"]
143
+ latents = source_latents.clone()
144
+ if reference_latents is None:
145
+ clear_reference_condition(pipe.dit)
146
+ set_reference_adapters_enabled(pipe.dit, False)
147
+ else:
148
+ set_reference_adapters_enabled(pipe.dit, True)
149
+ prepare_reference_condition(pipe.dit, source_latents, reference_latents)
150
+
151
+ pipe.load_models_to_device(pipe.in_iteration_models)
152
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
153
+ model_inputs = dict(inputs_shared)
154
+ model_inputs.pop("latents", None)
155
+
156
+ for timestep_cpu in pipe.scheduler.timesteps:
157
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
158
+ pred_pos = pipe.model_fn(
159
+ **models, **model_inputs, **inputs_posi, latents=latents, timestep=timestep
160
+ )
161
+ if args.cfg_scale != 1.0:
162
+ pred_neg = pipe.model_fn(
163
+ **models, **model_inputs, **inputs_nega, latents=latents, timestep=timestep
164
+ )
165
+ prediction = pred_neg + args.cfg_scale * (pred_pos - pred_neg)
166
+ else:
167
+ prediction = pred_pos
168
+ latents = pipe.scheduler.step(prediction, timestep_cpu, latents, source_latents)
169
+
170
+ clear_reference_condition(pipe.dit)
171
+ return latents
172
+
173
+
174
+ @torch.no_grad()
175
+ def decode(pipe, latents: torch.Tensor, args) -> torch.Tensor:
176
+ pipe.load_models_to_device(["vae"])
177
+ return decode_latents_to_btchw_01(
178
+ pipe,
179
+ latents,
180
+ tiled=args.tiled,
181
+ tile_size=(args.tile_h, args.tile_w),
182
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
183
+ ).cpu()
184
+
185
+
186
+ def save_with_optional_audio(video: torch.Tensor, output: Path, source_audio: Path, fps: int, copy_audio: bool):
187
+ output.parent.mkdir(parents=True, exist_ok=True)
188
+ if not copy_audio:
189
+ save_video(tensor_btchw_01_to_pil(video[0]), str(output), fps=fps, quality=5)
190
+ return
191
+
192
+ silent = output.with_name(f".{output.stem}_silent{output.suffix}")
193
+ save_video(tensor_btchw_01_to_pil(video[0]), str(silent), fps=fps, quality=5)
194
+ try:
195
+ subprocess.run(
196
+ [
197
+ "ffmpeg", "-y", "-loglevel", "error",
198
+ "-i", str(silent), "-i", str(source_audio),
199
+ "-map", "0:v:0", "-map", "1:a?",
200
+ "-c:v", "copy", "-c:a", "aac", "-shortest", str(output),
201
+ ],
202
+ check=True,
203
+ )
204
+ finally:
205
+ silent.unlink(missing_ok=True)
206
+
207
+
208
+ def parse_args():
209
+ parser = argparse.ArgumentParser(
210
+ description="Run LR LiveAct video through frozen Bridge and CrossRoPE reference Adapter."
211
+ )
212
+ parser.add_argument("--input_video", required=True)
213
+ parser.add_argument("--reference_image", required=True)
214
+ parser.add_argument("--output_dir", required=True)
215
+ parser.add_argument("--output_stem", default=None)
216
+ parser.add_argument("--bridge_checkpoint", required=True)
217
+ parser.add_argument("--adapter_checkpoint", required=True)
218
+ parser.add_argument("--prompt", default="a person is speaking")
219
+ parser.add_argument("--negative_prompt", default="")
220
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
221
+ parser.add_argument("--model_paths", default=None)
222
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
223
+ parser.add_argument("--height", type=int, default=832)
224
+ parser.add_argument("--width", type=int, default=480)
225
+ parser.add_argument("--input_height", type=int, default=None)
226
+ parser.add_argument("--input_width", type=int, default=None)
227
+ parser.add_argument("--num_frames", type=int, default=0, help="0 uses every LiveAct frame.")
228
+ parser.add_argument("--sr_scale", type=int, default=2)
229
+ parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler")
230
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
231
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
232
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
233
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
234
+ parser.add_argument("--adapter_blocks", default="all")
235
+ parser.add_argument("--adapter_dim", type=int, default=1536)
236
+ parser.add_argument("--adapter_heads", type=int, default=12)
237
+ parser.add_argument(
238
+ "--wavelet_value_mode", choices=["off", "highpass"], default="off",
239
+ help="Use the reference hidden state's reconstructed Haar detail bands as V.",
240
+ )
241
+ parser.add_argument(
242
+ "--wavelet_energy_bias", type=float, default=0.0,
243
+ help="Strength of the normalized Haar-energy additive bias on reference-key logits.",
244
+ )
245
+ parser.add_argument(
246
+ "--wavelet_energy_clip", type=float, default=3.0,
247
+ help="Clamp normalized wavelet energy before applying the attention-bias strength.",
248
+ )
249
+ parser.add_argument(
250
+ "--attention_heatmap_dir", default=None,
251
+ help="Optional directory for exact QK-derived reference attention heatmaps.",
252
+ )
253
+ parser.add_argument(
254
+ "--attention_heatmap_blocks", default="0,6,12,18,24,29",
255
+ help="Wan blocks to visualize when --attention_heatmap_dir is set.",
256
+ )
257
+ parser.add_argument("--attention_query_stride", type=int, default=8)
258
+ parser.add_argument(
259
+ "--diagnostic_active_blocks",
260
+ default="all",
261
+ help="Inference-only ablation: use checkpoint adapters only at these Wan blocks.",
262
+ )
263
+ parser.add_argument("--num_inference_steps", type=int, default=1)
264
+ parser.add_argument("--sampling_noise_scale", type=float, default=0.0)
265
+ parser.add_argument("--sigma_shift", type=float, default=1.0)
266
+ parser.add_argument("--cfg_scale", type=float, default=1.0)
267
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
268
+ parser.add_argument("--seed", type=int, default=42)
269
+ parser.add_argument("--fps", type=int, default=None)
270
+ parser.add_argument("--device", default="cuda")
271
+ parser.add_argument("--rand_device", default="cpu")
272
+ parser.add_argument("--reference_resize_mode", choices=["crop", "resize"], default="resize")
273
+ parser.add_argument("--copy_audio", action=argparse.BooleanOptionalAction, default=True)
274
+ parser.add_argument("--tiled", action="store_true", default=False)
275
+ parser.add_argument("--tile_h", type=int, default=30)
276
+ parser.add_argument("--tile_w", type=int, default=52)
277
+ parser.add_argument("--tile_stride_h", type=int, default=15)
278
+ parser.add_argument("--tile_stride_w", type=int, default=26)
279
+ return parser.parse_args()
280
+
281
+
282
+ def main():
283
+ args = parse_args()
284
+ source_path = pick_video(args.input_video).resolve()
285
+ source_w, source_h, source_frames, source_fps = probe_video(source_path)
286
+ args.num_frames = args.num_frames or source_frames
287
+ args.fps = args.fps or max(1, int(round(source_fps)))
288
+ args.input_height = args.input_height or source_h
289
+ args.input_width = args.input_width or source_w
290
+ args.checkpoint = args.bridge_checkpoint # build_pipeline uses infer_sr's name.
291
+ args.model_paths = args.model_paths or default_model_paths(args.base_model_dir)
292
+
293
+ source_video, _ = read_video(
294
+ source_path,
295
+ args.input_height,
296
+ args.input_width,
297
+ args.num_frames,
298
+ )
299
+ reference_image = fit_reference(
300
+ Image.open(args.reference_image), args.height, args.width, args.reference_resize_mode
301
+ )
302
+
303
+ output_dir = Path(args.output_dir)
304
+ output_dir.mkdir(parents=True, exist_ok=True)
305
+ stem = args.output_stem or source_path.stem
306
+ lr_output = output_dir / f"{stem}_liveact_lr.mp4"
307
+ bridge_output = output_dir / f"{stem}_bridge.mp4"
308
+ adapter_output = output_dir / f"{stem}_bridge_adapter.mp4"
309
+ if source_path != lr_output.resolve():
310
+ shutil.copy2(source_path, lr_output)
311
+
312
+ print(
313
+ f"[LiveActCascade] LR={source_path} {source_w}x{source_h} frames={args.num_frames}; "
314
+ f"target={args.width}x{args.height}"
315
+ )
316
+ pipe = build_pipeline(args)
317
+ block_ids = parse_block_ids(args.adapter_blocks, len(pipe.dit.blocks))
318
+ install_reference_adapters(
319
+ pipe.dit,
320
+ block_ids,
321
+ args.adapter_dim,
322
+ args.adapter_heads,
323
+ wavelet_value_mode=args.wavelet_value_mode,
324
+ wavelet_energy_bias=args.wavelet_energy_bias,
325
+ wavelet_energy_clip=args.wavelet_energy_clip,
326
+ )
327
+ for block in reference_blocks(pipe.dit):
328
+ block.adapter.to(dtype=pipe.torch_dtype, device=pipe.device)
329
+ load_adapter_checkpoint(pipe.dit, args.adapter_checkpoint)
330
+ diagnostic_active = set(parse_block_ids(
331
+ args.diagnostic_active_blocks, len(pipe.dit.blocks)
332
+ ))
333
+ for block_id, block in enumerate(pipe.dit.blocks):
334
+ if hasattr(block, "adapter_active"):
335
+ block.adapter_active = block_id in diagnostic_active
336
+ attention_recorder = None
337
+ if args.attention_heatmap_dir:
338
+ attention_blocks = parse_block_ids(args.attention_heatmap_blocks, len(pipe.dit.blocks))
339
+ attention_recorder = ReferenceAttentionRecorder(
340
+ attention_blocks, args.adapter_heads, args.attention_query_stride
341
+ )
342
+ for block_id in attention_blocks:
343
+ adapter = pipe.dit.blocks[block_id].adapter
344
+ if adapter is None:
345
+ raise ValueError(f"Attention heatmap requested for block {block_id} without Adapter")
346
+ adapter.attention_probe = (
347
+ lambda q, k, delta, grid, bias, block_id=block_id:
348
+ attention_recorder.capture(block_id, q, k, delta, grid, bias)
349
+ )
350
+ pipe.eval().requires_grad_(False)
351
+
352
+ prepared = prepare_inputs(pipe, source_video, args.prompt, args)
353
+ reference_latents = encode_reference(pipe, reference_image, args)
354
+
355
+ print("[LiveActCascade] Running frozen Bridge...")
356
+ base_latents = predict_latents(pipe, prepared, args, reference_latents=None)
357
+ base_video = decode(pipe, base_latents, args)
358
+ save_with_optional_audio(base_video, bridge_output, source_path, args.fps, args.copy_audio)
359
+ del base_latents, base_video
360
+
361
+ print("[LiveActCascade] Running Bridge + reference Adapter...")
362
+ adapter_latents = predict_latents(pipe, prepared, args, reference_latents=reference_latents)
363
+ adapter_video = decode(pipe, adapter_latents, args)
364
+ save_with_optional_audio(adapter_video, adapter_output, source_path, args.fps, args.copy_audio)
365
+ if attention_recorder is not None:
366
+ attention_recorder.save(
367
+ args.attention_heatmap_dir, adapter_video, reference_image, args.fps
368
+ )
369
+
370
+ metadata = {
371
+ "input_video": str(source_path),
372
+ "reference_image": str(Path(args.reference_image).resolve()),
373
+ "bridge_checkpoint": args.bridge_checkpoint,
374
+ "adapter_checkpoint": args.adapter_checkpoint,
375
+ "adapter_architecture": "framewise_target_q_reference_kv_rope2d_residual_zero_scale",
376
+ "wavelet_value_mode": args.wavelet_value_mode,
377
+ "wavelet_energy_bias": args.wavelet_energy_bias,
378
+ "wavelet_energy_clip": args.wavelet_energy_clip,
379
+ "diagnostic_active_blocks": sorted(diagnostic_active),
380
+ "prompt": args.prompt,
381
+ "input_size": [source_h, source_w],
382
+ "output_size": [args.height, args.width],
383
+ "num_frames": args.num_frames,
384
+ "fps": args.fps,
385
+ "outputs": {
386
+ "liveact_lr": str(lr_output),
387
+ "bridge": str(bridge_output),
388
+ "bridge_adapter": str(adapter_output),
389
+ },
390
+ }
391
+ (output_dir / f"{stem}_pipeline.json").write_text(
392
+ json.dumps(metadata, indent=2, ensure_ascii=False), encoding="utf-8"
393
+ )
394
+ print(f"[LiveActCascade] LR: {lr_output}")
395
+ print(f"[LiveActCascade] Bridge: {bridge_output}")
396
+ print(f"[LiveActCascade] Bridge+Adapter: {adapter_output}")
397
+
398
+
399
+ if __name__ == "__main__":
400
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chunked Wan2.2-TI2V Brownian-bridge SR inference with clean history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import random
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import cv2
12
+ import torch
13
+ from PIL import Image
14
+ from safetensors.torch import load_file
15
+
16
+ REPO_ROOT = Path(__file__).resolve().parents[4]
17
+ if str(REPO_ROOT) not in sys.path:
18
+ sys.path.insert(0, str(REPO_ROOT))
19
+
20
+ from diffsynth.bridge.wan_bridge.model_inference.compare_bridge_steps_firstframe_anchor import ( # noqa: E402
21
+ fit_reference,
22
+ load_dit_checkpoint,
23
+ read_video,
24
+ save_with_optional_audio,
25
+ upscale_and_anchor_source,
26
+ )
27
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
28
+ decode_latents_to_btchw_01,
29
+ tensor_btchw_01_to_pil,
30
+ )
31
+ from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v import ( # noqa: E402
32
+ FirstFrameAnchorWanVideoSRBridgePipeline,
33
+ default_model_paths,
34
+ replace_first_latent_frame,
35
+ )
36
+ from diffsynth.data.video import save_video # noqa: E402
37
+ from diffsynth.utils import ModelConfig # noqa: E402
38
+
39
+
40
+ def probe_video(path: Path) -> tuple[int, int, int, float]:
41
+ cap = cv2.VideoCapture(str(path))
42
+ if not cap.isOpened():
43
+ raise RuntimeError(f"Failed to open video: {path}")
44
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
45
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
46
+ frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
47
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0)
48
+ cap.release()
49
+ return width, height, frames, fps
50
+
51
+
52
+ def reset_seed(seed: int) -> None:
53
+ random.seed(seed)
54
+ torch.manual_seed(seed)
55
+ if torch.cuda.is_available():
56
+ torch.cuda.manual_seed_all(seed)
57
+
58
+
59
+ def build_pipeline(args):
60
+ model_paths = args.model_paths or default_model_paths(args.base_model_dir)
61
+ pipe = FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained(
62
+ torch_dtype=torch.bfloat16,
63
+ device=args.device,
64
+ model_configs=[ModelConfig(path=p) for p in model_paths.split(",")],
65
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
66
+ )
67
+ load_dit_checkpoint(pipe, args.checkpoint)
68
+ if not getattr(pipe.dit, "fuse_vae_embedding_in_latents", False):
69
+ raise RuntimeError("Checkpoint base DiT is not Wan2.2-TI2V fused-input compatible")
70
+ pipe.latent_upsampler = None
71
+ pipe.scheduler.noise_scale = args.sampling_noise_scale
72
+ pipe.scheduler.bridge_type = "brownian"
73
+ pipe.scheduler.target = args.target
74
+ pipe.eval().requires_grad_(False)
75
+ return pipe
76
+
77
+
78
+ @torch.no_grad()
79
+ def encode_reference(pipe, image: Image.Image, args):
80
+ pipe.load_models_to_device(["vae"])
81
+ video = pipe.preprocess_video([image])
82
+ anchor = pipe.vae.encode(
83
+ video,
84
+ device=pipe.device,
85
+ tiled=args.tiled,
86
+ tile_size=(args.tile_h, args.tile_w),
87
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
88
+ ).to(device=pipe.device, dtype=pipe.torch_dtype)
89
+ if anchor.shape[2] != 1:
90
+ raise RuntimeError(f"Expected one reference latent frame, got {tuple(anchor.shape)}")
91
+ return anchor
92
+
93
+
94
+ @torch.no_grad()
95
+ def prepare(pipe, source_video, reference_image, args):
96
+ pipe.scheduler.set_timesteps(1000, training=True)
97
+ shared = {
98
+ "input_video": None,
99
+ "source_video": source_video,
100
+ "height": args.height,
101
+ "width": args.width,
102
+ "num_frames": args.num_frames,
103
+ "seed": args.seed,
104
+ "rand_device": args.rand_device,
105
+ "cfg_scale": args.cfg_scale,
106
+ "cfg_merge": False,
107
+ "tiled": args.tiled,
108
+ "tile_size": (args.tile_h, args.tile_w),
109
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
110
+ "fuse_vae_embedding_in_latents": True,
111
+ }
112
+ positive = {"prompt": args.prompt}
113
+ negative = {"negative_prompt": args.negative_prompt}
114
+ for unit in pipe.units:
115
+ shared, positive, negative = pipe.unit_runner(unit, pipe, shared, positive, negative)
116
+ shared["first_frame_latents"] = encode_reference(pipe, reference_image, args)
117
+ shared["source_latents"] = replace_first_latent_frame(
118
+ shared["source_latents"], shared["first_frame_latents"]
119
+ )
120
+ return shared, positive, negative
121
+
122
+
123
+ @torch.no_grad()
124
+ def sample_chunked(pipe, prepared, steps: int, args):
125
+ shared, positive, negative = prepared
126
+ anchor = shared["first_frame_latents"]
127
+ source_full = replace_first_latent_frame(shared["source_latents"], anchor)
128
+ total = source_full.shape[2]
129
+ generated = anchor.clone()
130
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
131
+ pipe.load_models_to_device(pipe.in_iteration_models)
132
+
133
+ for current_start in range(1, total, args.chunk_latent_frames):
134
+ current_end = min(total, current_start + args.chunk_latent_frames)
135
+ history = generated[:, :, max(1, generated.shape[2] - args.history_latent_frames):].detach()
136
+ current_source = source_full[:, :, current_start:current_end]
137
+ chunk_source = torch.cat([anchor, history, current_source], dim=2)
138
+ latents = chunk_source.clone()
139
+ history_len = history.shape[2]
140
+ clean_prefix = torch.cat([anchor, history], dim=2)
141
+
142
+ pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift)
143
+ model_inputs = dict(shared)
144
+ model_inputs.pop("latents", None)
145
+ model_inputs.pop("first_frame_latents", None)
146
+ model_inputs["fuse_vae_embedding_in_latents"] = True
147
+ model_inputs["clean_history_latent_frames"] = history_len
148
+ model_inputs["source_latents"] = chunk_source
149
+
150
+ for timestep_cpu in pipe.scheduler.timesteps:
151
+ timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype)
152
+ pred = pipe.model_fn(
153
+ **models, **model_inputs, **positive, latents=latents, timestep=timestep
154
+ )
155
+ if args.cfg_scale != 1.0:
156
+ pred_negative = pipe.model_fn(
157
+ **models, **model_inputs, **negative, latents=latents, timestep=timestep
158
+ )
159
+ pred = pred_negative + args.cfg_scale * (pred - pred_negative)
160
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, chunk_source)
161
+ latents[:, :, :1 + history_len] = clean_prefix
162
+
163
+ current = latents[:, :, 1 + history_len:].detach()
164
+ generated = torch.cat([generated, current], dim=2)
165
+
166
+ return generated
167
+
168
+
169
+ def parse_args():
170
+ parser = argparse.ArgumentParser(description=__doc__)
171
+ parser.add_argument("--checkpoint", required=True)
172
+ parser.add_argument("--input_video", required=True)
173
+ parser.add_argument("--reference_image", required=True)
174
+ parser.add_argument("--output", required=True)
175
+ parser.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B")
176
+ parser.add_argument("--model_paths", default=None)
177
+ parser.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl")
178
+ parser.add_argument("--prompt", default="a person is speaking")
179
+ parser.add_argument("--negative_prompt", default="")
180
+ parser.add_argument("--height", type=int, default=480)
181
+ parser.add_argument("--width", type=int, default=832)
182
+ parser.add_argument("--input_height", type=int, default=None)
183
+ parser.add_argument("--input_width", type=int, default=None)
184
+ parser.add_argument("--num_frames", type=int, default=81)
185
+ parser.add_argument("--chunk_latent_frames", type=int, default=4)
186
+ parser.add_argument("--history_latent_frames", type=int, default=2)
187
+ parser.add_argument("--steps", type=int, default=4)
188
+ parser.add_argument("--sigma_shift", type=float, default=5.0)
189
+ parser.add_argument("--sampling_noise_scale", type=float, default=1.0)
190
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
191
+ parser.add_argument("--cfg_scale", type=float, default=1.0)
192
+ parser.add_argument("--seed", type=int, default=42)
193
+ parser.add_argument("--device", default="cuda")
194
+ parser.add_argument("--rand_device", default="cpu")
195
+ parser.add_argument("--fps", type=int, default=None)
196
+ parser.add_argument("--tiled", action="store_true")
197
+ parser.add_argument("--tile_h", type=int, default=30)
198
+ parser.add_argument("--tile_w", type=int, default=52)
199
+ parser.add_argument("--tile_stride_h", type=int, default=15)
200
+ parser.add_argument("--tile_stride_w", type=int, default=26)
201
+ return parser.parse_args()
202
+
203
+
204
+ def main():
205
+ args = parse_args()
206
+ if args.chunk_latent_frames < 1 or args.history_latent_frames < 0:
207
+ raise ValueError("chunk_latent_frames must be >=1 and history_latent_frames must be >=0")
208
+ reset_seed(args.seed)
209
+ source_path = Path(args.input_video).resolve()
210
+ source_w, source_h, frame_count, source_fps = probe_video(source_path)
211
+ args.num_frames = min(args.num_frames, frame_count)
212
+ args.fps = args.fps or max(1, int(round(source_fps)))
213
+ lr_video, _ = read_video(
214
+ source_path,
215
+ args.input_height or source_h,
216
+ args.input_width or source_w,
217
+ args.num_frames,
218
+ 0,
219
+ )
220
+ reference = fit_reference(Image.open(args.reference_image), args.height, args.width, "resize")
221
+ source = upscale_and_anchor_source(lr_video, reference, args.height, args.width)
222
+ pipe = build_pipeline(args)
223
+ prepared = prepare(pipe, source, reference, args)
224
+ latents = sample_chunked(pipe, prepared, args.steps, args)
225
+ video = decode_latents_to_btchw_01(
226
+ pipe, latents, args.tiled,
227
+ (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)
228
+ ).cpu()
229
+ output = Path(args.output).resolve()
230
+ save_with_optional_audio(video, output, source_path, args.fps, True)
231
+ output.with_suffix(".json").write_text(json.dumps({
232
+ "input_video": str(source_path),
233
+ "reference_image": str(Path(args.reference_image).resolve()),
234
+ "checkpoint": args.checkpoint,
235
+ "chunk_latent_frames": args.chunk_latent_frames,
236
+ "history_latent_frames": args.history_latent_frames,
237
+ "clean_history": True,
238
+ "first_frame_anchor": True,
239
+ "steps": args.steps,
240
+ }, indent=2), encoding="utf-8")
241
+ print(f"[Wan22TI2VChunked] output={output}", flush=True)
242
+
243
+
244
+ if __name__ == "__main__":
245
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
7
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
8
+ export TOKENIZERS_PARALLELISM="false"
9
+
10
+ : "${CHECKPOINT:?Set CHECKPOINT to the trained Wan2.2 bridge checkpoint}"
11
+ : "${INPUT_VIDEO:?Set INPUT_VIDEO to the LiveAct/LR video}"
12
+ : "${REFERENCE_IMAGE:?Set REFERENCE_IMAGE to the HR first-frame image}"
13
+ : "${OUTPUT:?Set OUTPUT to the output mp4 path}"
14
+
15
+ "${PYTHON_BIN}" diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_chunked.py \
16
+ --checkpoint "${CHECKPOINT}" \
17
+ --input_video "${INPUT_VIDEO}" \
18
+ --reference_image "${REFERENCE_IMAGE}" \
19
+ --output "${OUTPUT}" \
20
+ --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \
21
+ --tokenizer_path "${TOKENIZER_PATH:-/cache/Wan2.2-TI2V-5B/google/umt5-xxl}" \
22
+ --prompt "${PROMPT:-a person is speaking}" \
23
+ --height "${HEIGHT:-480}" \
24
+ --width "${WIDTH:-832}" \
25
+ --chunk_latent_frames "${CHUNK_LATENT_FRAMES:-4}" \
26
+ --history_latent_frames "${HISTORY_LATENT_FRAMES:-2}" \
27
+ --steps "${STEPS:-4}" \
28
+ --sigma_shift "${SIGMA_SHIFT:-5.0}" \
29
+ --sampling_noise_scale "${SAMPLING_NOISE_SCALE:-1.0}" \
30
+ --seed "${SEED:-42}" \
31
+ "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_sr_wan22_ti2v_edit.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the Wan2.1 tiny-ditto edit bridge on a LiveAct video."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import random
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import cv2
12
+ import torch
13
+ from PIL import Image
14
+ from safetensors.torch import load_file
15
+ from tqdm import tqdm
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[4]
18
+ if str(REPO_ROOT) not in sys.path:
19
+ sys.path.insert(0, str(REPO_ROOT))
20
+
21
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
22
+ center_crop_resize,
23
+ decode_latents_to_btchw_01,
24
+ make_lr_source,
25
+ tensor_btchw_01_to_pil,
26
+ )
27
+ from diffsynth.bridge.wan_bridge.model_training.train_sr_wan22_ti2v_edit import ( # noqa: E402
28
+ TinyDittoEditBridgePipeline,
29
+ default_model_paths,
30
+ normalize_wan_num_frames,
31
+ resize_latents_to_match,
32
+ )
33
+ from diffsynth.data.video import save_video # noqa: E402
34
+ from diffsynth.utils import ModelConfig # noqa: E402
35
+
36
+
37
+ def load_checkpoint(pipe, path: str) -> None:
38
+ state = load_file(path, device="cpu")
39
+ candidates = [("raw", state)]
40
+ for prefix in ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit."):
41
+ if any(k.startswith(prefix) for k in state):
42
+ candidates.append((prefix, {k[len(prefix):] if k.startswith(prefix) else k: v for k, v in state.items()}))
43
+ errors = []
44
+ for name, candidate in candidates:
45
+ try:
46
+ pipe.dit.load_state_dict(candidate, strict=True)
47
+ print(f"[EditInfer] loaded checkpoint strategy={name}", flush=True)
48
+ return
49
+ except Exception as exc:
50
+ errors.append(f"{name}: {str(exc).splitlines()[0]}")
51
+ raise RuntimeError("Could not load checkpoint:\n" + "\n".join(errors))
52
+
53
+
54
+ def read_video(path: Path, height: int, width: int, frames: int) -> tuple[list[Image.Image], float]:
55
+ cap = cv2.VideoCapture(str(path))
56
+ if not cap.isOpened():
57
+ raise RuntimeError(f"Failed to open {path}")
58
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 16.0)
59
+ out, last = [], None
60
+ while len(out) < frames:
61
+ ok, frame = cap.read()
62
+ if not ok:
63
+ if last is None:
64
+ break
65
+ frame = last
66
+ last = frame
67
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
68
+ out.append(center_crop_resize(Image.fromarray(frame), height, width))
69
+ cap.release()
70
+ if not out:
71
+ raise RuntimeError(f"No frames decoded from {path}")
72
+ while len(out) < frames:
73
+ out.append(out[-1].copy())
74
+ return out, fps
75
+
76
+
77
+ def make_comparison_video(
78
+ original: list[Image.Image],
79
+ bridge: list[Image.Image],
80
+ ) -> list[Image.Image]:
81
+ frame_count = min(len(original), len(bridge))
82
+ comparison = []
83
+ for index in range(frame_count):
84
+ panels = [original[index].convert("RGB"), bridge[index].convert("RGB")]
85
+ width = panels[0].width
86
+ height = panels[0].height
87
+ canvas = Image.new("RGB", (width * 2, height))
88
+ for column, panel in enumerate(panels):
89
+ canvas.paste(panel.resize((width, height)), (column * width, 0))
90
+ comparison.append(canvas)
91
+ return comparison
92
+
93
+
94
+ def load_pipe(args):
95
+ paths = args.model_paths or default_model_paths(args.base_model_dir)
96
+ pipe = TinyDittoEditBridgePipeline.from_pretrained(
97
+ torch_dtype=torch.bfloat16,
98
+ device=args.device,
99
+ model_configs=[ModelConfig(path=p) for p in paths.split(",")],
100
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
101
+ )
102
+ load_checkpoint(pipe, args.checkpoint)
103
+ pipe.requires_grad_(False).eval()
104
+ pipe.latent_upsampler = None
105
+ dit_in_dim = int(getattr(pipe.dit, "in_dim", 0))
106
+ vae_z_dim = int(getattr(pipe.vae, "z_dim", 0))
107
+ if dit_in_dim != 16 or vae_z_dim != 16:
108
+ raise RuntimeError(
109
+ "Expected Wan2.1-T2V-1.3B with a 16-channel DiT/VAE, "
110
+ f"got dit.in_dim={dit_in_dim}, vae.z_dim={vae_z_dim}"
111
+ )
112
+ pipe.scheduler.noise_scale = args.sampling_noise_scale
113
+ pipe.scheduler.bridge_type = "brownian"
114
+ pipe.scheduler.target = args.target
115
+ return pipe
116
+
117
+
118
+ @torch.no_grad()
119
+ def prepare(pipe, reference_video, source_video, args):
120
+ pipe.scheduler.set_timesteps(1000, training=True)
121
+ shared = {
122
+ "input_video": reference_video,
123
+ "source_video": source_video,
124
+ "height": args.height,
125
+ "width": args.width,
126
+ "num_frames": len(source_video),
127
+ "cfg_scale": 1,
128
+ "cfg_merge": False,
129
+ "tiled": args.tiled,
130
+ "tile_size": (args.tile_h, args.tile_w),
131
+ "tile_stride": (args.tile_stride_h, args.tile_stride_w),
132
+ "rand_device": pipe.device,
133
+ "seed": args.seed,
134
+ "use_gradient_checkpointing": False,
135
+ "use_gradient_checkpointing_offload": False,
136
+ "fuse_vae_embedding_in_latents": False,
137
+ "token_prefix_clean_timestep": True,
138
+ "token_prefix_aligned_rope": True,
139
+ "token_prefix_block_self_attention": True,
140
+ }
141
+ pos = {"prompt": args.prompt}
142
+ neg = {"negative_prompt": args.negative_prompt}
143
+ for unit in pipe.units:
144
+ shared, pos, neg = pipe.unit_runner(unit, pipe, shared, pos, neg)
145
+ pipe.load_models_to_device(["vae"])
146
+ original_video = pipe.preprocess_video(reference_video)
147
+ shared["original_latents"] = pipe.vae.encode(
148
+ original_video,
149
+ device=pipe.device,
150
+ tiled=args.tiled,
151
+ tile_size=(args.tile_h, args.tile_w),
152
+ tile_stride=(args.tile_stride_h, args.tile_stride_w),
153
+ ).to(dtype=pipe.torch_dtype, device=pipe.device)
154
+ shared["source_latents"] = resize_latents_to_match(
155
+ shared["source_latents"], shared["original_latents"]
156
+ )
157
+ return shared, pos, neg
158
+
159
+
160
+ @torch.no_grad()
161
+ def sample(pipe, prepared, steps: int, args):
162
+ shared, pos, neg = prepared
163
+ pipe.scheduler.set_timesteps(steps, shift=args.sigma_shift)
164
+ source = shared["source_latents"]
165
+ latents = source.clone()
166
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
167
+ pipe.load_models_to_device(pipe.in_iteration_models)
168
+ model_inputs = dict(shared)
169
+ model_inputs.pop("latents", None)
170
+ model_inputs["token_prefix_latents"] = shared["original_latents"].detach()
171
+ model_inputs["token_prefix_block_self_attention"] = True
172
+ model_inputs.pop("original_latents", None)
173
+ for timestep_cpu in tqdm(
174
+ pipe.scheduler.timesteps,
175
+ desc=f"Bridge denoise ({steps} steps)",
176
+ leave=False,
177
+ ):
178
+ timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype)
179
+ pred = pipe.model_fn(**models, **model_inputs, **pos, latents=latents, timestep=timestep)
180
+ if args.cfg_scale != 1:
181
+ neg_pred = pipe.model_fn(**models, **model_inputs, **neg, latents=latents, timestep=timestep)
182
+ pred = neg_pred + args.cfg_scale * (pred - neg_pred)
183
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, source)
184
+ return latents
185
+
186
+
187
+ def main():
188
+ p = argparse.ArgumentParser()
189
+ p.add_argument("--checkpoint", required=True)
190
+ p.add_argument("--input_video", required=True)
191
+ p.add_argument("--bridge_video", default=None, help="Optional coarse/edited video used as bridge source.")
192
+ p.add_argument("--target_video", default=None, help="Optional target video saved for comparison only.")
193
+ p.add_argument("--output_dir", required=True)
194
+ p.add_argument("--steps", default="1,2,4,8,20")
195
+ p.add_argument("--base_model_dir", default="/cache/Wan2.1-T2V-1.3B")
196
+ p.add_argument("--model_paths", default=None)
197
+ p.add_argument("--tokenizer_path", default="/cache/Wan2.1-T2V-1.3B/google/umt5-xxl")
198
+ p.add_argument("--height", type=int, default=480)
199
+ p.add_argument("--width", type=int, default=832)
200
+ p.add_argument("--num_frames", type=int, default=81)
201
+ p.add_argument("--sr_scale", type=int, default=4)
202
+ p.add_argument("--sigma_shift", type=float, default=5.0)
203
+ p.add_argument("--sampling_noise_scale", type=float, default=1.0)
204
+ p.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
205
+ p.add_argument("--cfg_scale", type=float, default=1.0)
206
+ p.add_argument("--prompt", default="")
207
+ p.add_argument("--negative_prompt", default="")
208
+ p.add_argument("--seed", type=int, default=42)
209
+ p.add_argument("--device", default="cuda")
210
+ p.add_argument("--tiled", action="store_true")
211
+ p.add_argument("--tile_h", type=int, default=30)
212
+ p.add_argument("--tile_w", type=int, default=52)
213
+ p.add_argument("--tile_stride_h", type=int, default=15)
214
+ p.add_argument("--tile_stride_w", type=int, default=26)
215
+ args = p.parse_args()
216
+ random.seed(args.seed)
217
+ torch.manual_seed(args.seed)
218
+ source_path = Path(args.input_video).resolve()
219
+ bridge_path = Path(args.bridge_video).resolve() if args.bridge_video else source_path
220
+ args.num_frames = normalize_wan_num_frames(args.num_frames)
221
+ reference_video, fps = read_video(source_path, args.height, args.width, args.num_frames)
222
+ bridge_video, bridge_fps = read_video(bridge_path, args.height, args.width, args.num_frames)
223
+ source_video = [make_lr_source(frame, args.height, args.width, args.sr_scale, upsample_to_hr=False) for frame in bridge_video]
224
+ pipe = load_pipe(args)
225
+ prepared = prepare(pipe, reference_video, source_video, args)
226
+ out = Path(args.output_dir)
227
+ out.mkdir(parents=True, exist_ok=True)
228
+ steps_list = [int(x) for x in args.steps.split(",") if x.strip()]
229
+ outputs = {}
230
+ for steps in steps_list:
231
+ print(f"[EditInfer] sampling steps={steps}", flush=True)
232
+ latents = sample(pipe, prepared, steps, args)
233
+ 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()
234
+ generated_frames = tensor_btchw_01_to_pil(video[0])
235
+ path = out / f"{source_path.stem}_edit_x{args.sr_scale}_steps_{steps:02d}.mp4"
236
+ save_video(generated_frames, str(path), fps=fps, quality=5)
237
+ outputs[str(steps)] = str(path)
238
+ comparison = make_comparison_video(reference_video, generated_frames)
239
+ comparison_path = out / f"{source_path.stem}_steps_{steps:02d}_comparison.mp4"
240
+ save_video(comparison, str(comparison_path), fps=fps, quality=5)
241
+ outputs[f"{steps}_comparison"] = str(comparison_path)
242
+ (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")
243
+
244
+
245
+ if __name__ == "__main__":
246
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_inference/infer_vibt.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import random
4
+
5
+ import pandas as pd
6
+ import torch
7
+ from safetensors.torch import load_file
8
+
9
+ from diffsynth.data.video import VideoData, save_video
10
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline
11
+ from diffsynth.pipelines.wan_video_new import ModelConfig
12
+
13
+
14
+ def load_dit_checkpoint(pipe: WanVideoBridgePipeline, checkpoint: str):
15
+ """Load a full single-head DiT checkpoint saved by ViBT training."""
16
+ state_dict = load_file(checkpoint, device="cpu")
17
+ prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.")
18
+
19
+ candidates = [("raw", state_dict)]
20
+ for prefix in prefixes:
21
+ if any(k.startswith(prefix) for k in state_dict):
22
+ stripped = {
23
+ k[len(prefix):] if k.startswith(prefix) else k: v
24
+ for k, v in state_dict.items()
25
+ }
26
+ candidates.append((f"strip:{prefix}", stripped))
27
+
28
+ errors = []
29
+ for name, candidate in candidates:
30
+ try:
31
+ pipe.dit.load_state_dict(candidate, strict=True)
32
+ print(f"[ViBT] Loaded checkpoint with strategy: {name}")
33
+ return
34
+ except Exception as exc:
35
+ errors.append((name, str(exc)))
36
+
37
+ msg = "\n".join(f"{name}: {err}" for name, err in errors)
38
+ raise RuntimeError(f"Could not strictly load ViBT checkpoint:\n{msg}")
39
+
40
+
41
+ def build_pipeline(args):
42
+ model_configs = [
43
+ ModelConfig(
44
+ model_id="Wan-AI/Wan2.1-T2V-1.3B",
45
+ origin_file_pattern="diffusion_pytorch_model*.safetensors",
46
+ offload_device="cpu",
47
+ ),
48
+ ModelConfig(
49
+ model_id="Wan-AI/Wan2.1-T2V-1.3B",
50
+ origin_file_pattern="models_t5_umt5-xxl-enc-bf16.pth",
51
+ offload_device="cpu",
52
+ ),
53
+ ModelConfig(
54
+ model_id="Wan-AI/Wan2.1-T2V-1.3B",
55
+ origin_file_pattern="Wan2.1_VAE.pth",
56
+ offload_device="cpu",
57
+ ),
58
+ ]
59
+
60
+ pipe = WanVideoBridgePipeline.from_pretrained(
61
+ torch_dtype=torch.bfloat16,
62
+ device="cuda",
63
+ model_configs=model_configs,
64
+ )
65
+ load_dit_checkpoint(pipe, args.checkpoint)
66
+
67
+ if args.bridge_type != "brownian" or args.bridge_path_type != "brownian":
68
+ raise ValueError("Final ViBT uses --bridge_type brownian --bridge_path_type brownian")
69
+ if args.target != "stabilized_drift":
70
+ print(f"[ViBT warning] final reported model used target=stabilized_drift, got {args.target}")
71
+
72
+ pipe.scheduler.noise_scale = args.sampling_noise_scale
73
+ pipe.scheduler.bridge_type = args.bridge_type
74
+ pipe.scheduler.training_weight_type = "uniform"
75
+ pipe.scheduler.target = args.target
76
+ return pipe
77
+
78
+
79
+ def infer_one(pipe, source_path, prompt, output_path, args):
80
+ # BridgeScheduler.step() samples stochastic noise with torch.randn_like,
81
+ # so set the global RNG as well as passing the seed into the pipeline.
82
+ random.seed(args.seed)
83
+ torch.manual_seed(args.seed)
84
+ if torch.cuda.is_available():
85
+ torch.cuda.manual_seed_all(args.seed)
86
+
87
+ source_video = VideoData(source_path, height=args.height, width=args.width)
88
+ source_video.set_length(args.num_frames)
89
+
90
+ video = pipe(
91
+ prompt=prompt,
92
+ negative_prompt=args.negative_prompt,
93
+ source_video=source_video,
94
+ seed=args.seed,
95
+ height=args.height,
96
+ width=args.width,
97
+ num_frames=args.num_frames,
98
+ cfg_scale=args.cfg_scale,
99
+ num_inference_steps=args.num_inference_steps,
100
+ sigma_shift=args.sigma_shift,
101
+ tiled=args.tiled,
102
+ )
103
+
104
+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
105
+ save_video(video, output_path, fps=args.fps, quality=5)
106
+ print(f"[ViBT] Saved: {output_path}")
107
+
108
+
109
+ def main():
110
+ parser = argparse.ArgumentParser(description="Final single-head ViBT inference (Wan2.1-T2V-1.3B).")
111
+ parser.add_argument("--checkpoint", required=True)
112
+
113
+ # Single-video mode.
114
+ parser.add_argument("--source_video", default=None)
115
+ parser.add_argument("--prompt", default=None)
116
+ parser.add_argument("--output", default=None)
117
+
118
+ # Metadata/batch mode, compatible with the historical ViBT command.
119
+ parser.add_argument("--dataset_root", default=None)
120
+ parser.add_argument("--metadata", default=None)
121
+ parser.add_argument("--output_dir", default=None)
122
+ parser.add_argument("--num_samples", type=int, default=5)
123
+ parser.add_argument("--row_index", type=int, default=None)
124
+ parser.add_argument("--tag", default="vibt_strict")
125
+
126
+ parser.add_argument("--negative_prompt", default="")
127
+ parser.add_argument("--height", type=int, default=480)
128
+ parser.add_argument("--width", type=int, default=832)
129
+ parser.add_argument("--num_frames", type=int, default=81)
130
+
131
+ # Final ViBT inference settings used in the experiment command.
132
+ parser.add_argument("--num_inference_steps", type=int, default=30)
133
+ parser.add_argument("--cfg_scale", type=float, default=2.0)
134
+ parser.add_argument("--sigma_shift", type=float, default=1.0)
135
+ parser.add_argument("--seed", type=int, default=8888)
136
+ parser.add_argument("--target", default="stabilized_drift", choices=["stabilized_drift", "drift", "x0"])
137
+ parser.add_argument("--bridge_type", default="brownian")
138
+ parser.add_argument("--bridge_path_type", default="brownian")
139
+ parser.add_argument("--sampling_noise_scale", type=float, default=1.0)
140
+ parser.add_argument("--fps", type=int, default=15)
141
+ parser.add_argument("--tiled", action="store_true", default=True)
142
+ parser.add_argument("--no_tiled", dest="tiled", action="store_false")
143
+ args = parser.parse_args()
144
+
145
+ pipe = build_pipeline(args)
146
+
147
+ if args.source_video is not None:
148
+ if args.prompt is None:
149
+ raise ValueError("--prompt is required in single-video mode")
150
+ output = args.output or f"outputs/{args.tag}.mp4"
151
+ infer_one(pipe, args.source_video, args.prompt, output, args)
152
+ return
153
+
154
+ if args.metadata is None or args.dataset_root is None or args.output_dir is None:
155
+ raise ValueError(
156
+ "Use either single-video mode (--source_video --prompt [--output]) or "
157
+ "batch mode (--dataset_root --metadata --output_dir)."
158
+ )
159
+
160
+ df = pd.read_csv(args.metadata)
161
+ if args.row_index is not None:
162
+ indices = [int(args.row_index)]
163
+ else:
164
+ rng = random.Random(args.seed)
165
+ indices = rng.sample(range(len(df)), min(args.num_samples, len(df)))
166
+
167
+ os.makedirs(args.output_dir, exist_ok=True)
168
+ for idx in indices:
169
+ row = df.iloc[idx]
170
+ source = str(row["source_video"])
171
+ if not os.path.isabs(source):
172
+ source = os.path.join(args.dataset_root, source)
173
+ prompt = str(row["prompt"])
174
+ output = os.path.join(args.output_dir, f"{args.tag}_row_{idx:05d}.mp4")
175
+ print(f"[ViBT] row={idx}\n source={source}\n prompt={prompt}")
176
+ infer_one(pipe, source, prompt, output, args)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/full/Wan2.1-T2V-1.3B.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Final single-head ViBT training recipe used in the experiments.
3
+ # Replace dataset/output paths as needed.
4
+
5
+ accelerate launch --num_processes 1 \
6
+ diffsynth/bridge/wan_bridge/model_training/train.py \
7
+ --dataset_base_path /path/to/Ditto-1M \
8
+ --dataset_metadata_path /path/to/style_bridge_2000_random.csv \
9
+ --data_file_keys "video,source_video" \
10
+ --extra_inputs "source_video" \
11
+ --height 480 \
12
+ --width 832 \
13
+ --num_frames 81 \
14
+ --dataset_repeat 10 \
15
+ --dataset_num_workers 2 \
16
+ --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" \
17
+ --trainable_models "dit" \
18
+ --learning_rate 1 \
19
+ --weight_decay 0.01 \
20
+ --d_coef 1.0 \
21
+ --num_epochs 1 \
22
+ --save_steps 1000 \
23
+ --test_steps 1000 \
24
+ --use_gradient_checkpointing \
25
+ --max_timestep_boundary 0.9999 \
26
+ --min_timestep_boundary 0.0001 \
27
+ --noise_sigma 1.0 \
28
+ --bridge_type brownian \
29
+ --bridge_path_type brownian \
30
+ --training_weight_type uniform \
31
+ --target stabilized_drift \
32
+ --remove_prefix_in_ckpt "pipe.dit." \
33
+ --output_path /path/to/output/vibt
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/sobel_utils.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared Sobel operators for adapter training and visualization."""
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ def sobel_rgb_gradients(video_btchw_01: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
8
+ """Return normalized RGB Sobel gradients as [B*T, C, H, W]."""
9
+ video = video_btchw_01.reshape(-1, *video_btchw_01.shape[2:]).float()
10
+ channels = video.shape[1]
11
+ kernel_x = video.new_tensor([
12
+ [-1.0, 0.0, 1.0],
13
+ [-2.0, 0.0, 2.0],
14
+ [-1.0, 0.0, 1.0],
15
+ ]).div(8.0).view(1, 1, 3, 3).repeat(channels, 1, 1, 1)
16
+ kernel_y = kernel_x.transpose(-1, -2).contiguous()
17
+
18
+ video = F.pad(video, (1, 1, 1, 1), mode="reflect")
19
+ return (
20
+ F.conv2d(video, kernel_x, groups=channels),
21
+ F.conv2d(video, kernel_y, groups=channels),
22
+ )
23
+
24
+
25
+ def dilated_sobel_edge_mask(
26
+ gradient_x: torch.Tensor,
27
+ gradient_y: torch.Tensor,
28
+ dilation_radius: int = 2,
29
+ threshold_multiplier: float = 1.0,
30
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
31
+ """Return magnitude, per-frame threshold, thin mask, and dilated mask."""
32
+ magnitude = torch.sqrt(gradient_x.square() + gradient_y.square() + 1e-12).mean(dim=1, keepdim=True)
33
+ threshold = magnitude.mean(dim=(-2, -1), keepdim=True) * float(threshold_multiplier)
34
+ edge_mask = (magnitude >= threshold).to(gradient_x.dtype)
35
+ dilated_mask = edge_mask
36
+ radius = max(int(dilation_radius), 0)
37
+ if radius:
38
+ dilated_mask = F.max_pool2d(
39
+ edge_mask,
40
+ kernel_size=2 * radius + 1,
41
+ stride=1,
42
+ padding=radius,
43
+ )
44
+ return magnitude, threshold, edge_mask, dilated_mask
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, os
2
+ from diffsynth.trainers.utils import (
3
+ DiffusionTrainingModule,
4
+ ModelLogger,
5
+ wan_parser,
6
+ )
7
+ from diffsynth.trainers.unified_dataset import UnifiedDataset
8
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import (
9
+ WanVideoBridgePipeline,
10
+ WanVideoBridgeUnit_InputVideoEmbedder_FSR,
11
+ )
12
+ from accelerate import Accelerator
13
+ from tqdm import tqdm
14
+ from accelerate.utils import DistributedDataParallelKwargs
15
+ from torch.nn.parallel.distributed import DistributedDataParallel
16
+ from prodigyopt import Prodigy
17
+ from diffsynth.data.video import save_video, VideoData
18
+ import wandb
19
+ import copy
20
+ import random
21
+
22
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
23
+
24
+ is_main_process = os.getenv("LOCAL_RANK", "0") == "0"
25
+
26
+
27
+ class WanBridgeTrainingModule(DiffusionTrainingModule):
28
+ def __init__(
29
+ self,
30
+ model_paths=None,
31
+ model_id_with_origin_paths=None,
32
+ trainable_models=None,
33
+ lora_base_model=None,
34
+ lora_target_modules="q,k,v,o,ffn.0,ffn.2",
35
+ lora_rank=32,
36
+ lora_checkpoint=None,
37
+ use_gradient_checkpointing=True,
38
+ use_gradient_checkpointing_offload=False,
39
+ extra_inputs=None,
40
+ max_timestep_boundary=1.0,
41
+ min_timestep_boundary=0.0,
42
+ image_drop_probability=0.0,
43
+ text_drop_probability=0.0,
44
+ ):
45
+ super().__init__()
46
+ # Load models
47
+ model_configs = self.parse_model_configs(
48
+ model_paths, model_id_with_origin_paths, enable_fp8_training=False
49
+ )
50
+ self.pipe: WanVideoBridgePipeline = WanVideoBridgePipeline.from_pretrained(
51
+ torch_dtype=torch.bfloat16, device="cpu", model_configs=model_configs
52
+ )
53
+
54
+ # Training mode
55
+ self.switch_pipe_to_training_mode(
56
+ self.pipe,
57
+ trainable_models,
58
+ lora_base_model,
59
+ lora_target_modules,
60
+ lora_rank,
61
+ lora_checkpoint=lora_checkpoint,
62
+ enable_fp8_training=False,
63
+ )
64
+
65
+ # Store other configs
66
+ self.use_gradient_checkpointing = use_gradient_checkpointing
67
+ self.use_gradient_checkpointing_offload = use_gradient_checkpointing_offload
68
+ self.extra_inputs = extra_inputs.split(",") if extra_inputs is not None else []
69
+ self.max_timestep_boundary = max_timestep_boundary
70
+ self.min_timestep_boundary = min_timestep_boundary
71
+ self.image_drop_probability = image_drop_probability
72
+ self.text_drop_probability = text_drop_probability
73
+
74
+ def forward_preprocess(self, data):
75
+ # CFG-sensitive parameters
76
+ inputs_posi = {"prompt": data["prompt"]}
77
+ if random.random() < self.text_drop_probability:
78
+ inputs_posi["prompt"] = " "
79
+ inputs_nega = {}
80
+
81
+ # CFG-unsensitive parameters
82
+ inputs_shared = {
83
+ # Assume you are using this pipeline for inference,
84
+ # please fill in the input parameters.
85
+ "input_video": data["video"],
86
+ "source_video": data["source_video"],
87
+ "height": data["video"][0].size[1],
88
+ "width": data["video"][0].size[0],
89
+ "num_frames": len(data["video"]),
90
+ # Please do not modify the following parameters
91
+ # unless you clearly know what this will cause.
92
+ "cfg_scale": 1,
93
+ "tiled": False,
94
+ "rand_device": self.pipe.device,
95
+ "use_gradient_checkpointing": self.use_gradient_checkpointing,
96
+ "use_gradient_checkpointing_offload": self.use_gradient_checkpointing_offload,
97
+ "cfg_merge": False,
98
+ "vace_scale": 1,
99
+ "max_timestep_boundary": self.max_timestep_boundary,
100
+ "min_timestep_boundary": self.min_timestep_boundary,
101
+ }
102
+
103
+ # Extra inputs
104
+ for extra_input in self.extra_inputs:
105
+ if extra_input == "input_image":
106
+ inputs_shared["input_image"] = data["video"][0]
107
+ elif extra_input == "end_image":
108
+ inputs_shared["end_image"] = data["video"][-1]
109
+ elif (
110
+ extra_input == "reference_image"
111
+ or extra_input == "vace_reference_image"
112
+ ):
113
+ inputs_shared[extra_input] = data[extra_input][0]
114
+ else:
115
+ inputs_shared[extra_input] = data[extra_input]
116
+
117
+ # Pipeline units will automatically process the input parameters.
118
+ for unit in self.pipe.units:
119
+ inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(
120
+ unit, self.pipe, inputs_shared, inputs_posi, inputs_nega
121
+ )
122
+ if random.random() < self.image_drop_probability:
123
+ inputs_shared["source_latents"] = torch.zeros_like(
124
+ inputs_shared["source_latents"]
125
+ )
126
+ return {**inputs_shared, **inputs_posi}
127
+
128
+ def forward(self, data, inputs=None):
129
+ if inputs is None:
130
+ inputs = self.forward_preprocess(data)
131
+ models = {
132
+ name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models
133
+ }
134
+ loss = self.pipe.training_loss(**models, **inputs)
135
+ return loss
136
+
137
+
138
+ class BridgeLogger(ModelLogger):
139
+ def __init__(
140
+ self, *args, test_video, test_prompt, ema_decay=0.95, log_fps=15, **kwargs
141
+ ):
142
+ super().__init__(*args, **kwargs)
143
+ self.ema_decay = ema_decay
144
+ self.ema_loss = None
145
+ self.test_video = test_video
146
+ self.test_prompt = test_prompt
147
+ self.log_fps = log_fps or 15
148
+ self.wandb_init()
149
+
150
+ def wandb_init(self):
151
+ if not is_main_process:
152
+ return
153
+ wandb.init(project="ViBT-Wan")
154
+
155
+ def on_step_end(
156
+ self, accelerator, model, save_steps=None, test_steps=None, loss=None
157
+ ):
158
+ super().on_step_end(accelerator, model, save_steps)
159
+ if not accelerator.is_main_process:
160
+ return
161
+ # Log loss and ema_loss
162
+ if loss is not None:
163
+ if self.ema_loss is None:
164
+ self.ema_loss = loss
165
+ else:
166
+ self.ema_loss *= self.ema_decay
167
+ self.ema_loss += loss * (1 - self.ema_decay)
168
+ wandb.log({"loss": loss}, step=self.num_steps)
169
+ # Generate video samples
170
+ if test_steps is not None and self.num_steps % test_steps == 0:
171
+ self.generate_video(model)
172
+
173
+ @torch.no_grad()
174
+ def generate_video(self, model):
175
+ if not is_main_process:
176
+ return
177
+ source_video = VideoData(self.test_video, height=480, width=832)
178
+ if isinstance(model, DistributedDataParallel):
179
+ pipe = model.module.pipe
180
+ else:
181
+ pipe = model.pipe
182
+ scheduler_backup = pipe.scheduler
183
+ new_scheduler = copy.deepcopy(scheduler_backup)
184
+ pipe.scheduler = new_scheduler
185
+ video = pipe(
186
+ prompt=self.test_prompt,
187
+ negative_prompt="色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走",
188
+ seed=0,
189
+ tiled=True,
190
+ num_inference_steps=20,
191
+ source_video=source_video,
192
+ cfg_scale=2,
193
+ sigma_shift=5,
194
+ )
195
+ pipe.scheduler = scheduler_backup
196
+ save_path = os.path.join(self.output_path, "generated_videos")
197
+ os.makedirs(save_path, exist_ok=True)
198
+ file_name = os.path.join(save_path, f"step-{self.num_steps}-video.mp4")
199
+ fps = self.log_fps or 15
200
+ save_video(video, file_name, fps=fps, quality=5)
201
+ wandb_video = wandb.Video(file_name, fps=fps, format="mp4")
202
+ wandb.log({"generated_video": wandb_video}, step=self.num_steps)
203
+
204
+
205
+ def launch_prodigy_training_task(
206
+ dataset: torch.utils.data.Dataset,
207
+ model: DiffusionTrainingModule,
208
+ model_logger: ModelLogger,
209
+ learning_rate: float = 1e-5,
210
+ weight_decay: float = 1e-2,
211
+ num_workers: int = 8,
212
+ save_steps: int = None,
213
+ test_steps: int = None,
214
+ num_epochs: int = 1,
215
+ gradient_accumulation_steps: int = 1,
216
+ find_unused_parameters: bool = False,
217
+ args=None,
218
+ ):
219
+ if args is not None:
220
+ learning_rate = args.learning_rate
221
+ weight_decay = args.weight_decay
222
+ num_workers = args.dataset_num_workers
223
+ save_steps = args.save_steps
224
+ test_steps = args.test_steps
225
+ num_epochs = args.num_epochs
226
+ d_coef = args.d_coef
227
+ gradient_accumulation_steps = args.gradient_accumulation_steps
228
+ find_unused_parameters = args.find_unused_parameters
229
+
230
+ optimizer = Prodigy(
231
+ model.trainable_modules(),
232
+ lr=learning_rate,
233
+ weight_decay=weight_decay,
234
+ safeguard_warmup=True,
235
+ d_coef=d_coef,
236
+ )
237
+
238
+ dataloader = torch.utils.data.DataLoader(
239
+ dataset, shuffle=True, collate_fn=lambda x: x[0], num_workers=num_workers
240
+ )
241
+ accelerator = Accelerator(
242
+ gradient_accumulation_steps=gradient_accumulation_steps,
243
+ kwargs_handlers=[
244
+ DistributedDataParallelKwargs(find_unused_parameters=find_unused_parameters)
245
+ ],
246
+ )
247
+ model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
248
+
249
+ for epoch_id in range(num_epochs):
250
+ for data in tqdm(dataloader):
251
+ with accelerator.accumulate(model):
252
+ optimizer.zero_grad()
253
+ if dataset.load_from_cache:
254
+ loss = model({}, inputs=data)
255
+ else:
256
+ loss = model(data)
257
+ accelerator.backward(loss)
258
+ optimizer.step()
259
+ gathered_loss = accelerator.gather(loss.detach())
260
+ gathered_loss = gathered_loss.mean().item()
261
+ model_logger.on_step_end(
262
+ accelerator, model, save_steps, test_steps, gathered_loss
263
+ )
264
+ if save_steps is None:
265
+ model_logger.on_epoch_end(accelerator, model, epoch_id)
266
+ model_logger.on_training_end(accelerator, model, save_steps)
267
+
268
+
269
+ if __name__ == "__main__":
270
+ parser = wan_parser()
271
+ parser.add_argument(
272
+ "--test_steps",
273
+ type=int,
274
+ default=None,
275
+ help="Number of testing intervals. If None, testing will be done every epoch.",
276
+ )
277
+ parser.add_argument(
278
+ "--d_coef",
279
+ type=float,
280
+ default=1.0,
281
+ help="d_coef for Prodigy optimizer.",
282
+ )
283
+ parser.add_argument(
284
+ "--test_video",
285
+ type=str,
286
+ default="assets/test_video_l.mp4",
287
+ help="Path to the test video for logging.",
288
+ )
289
+ parser.add_argument(
290
+ "--test_prompt",
291
+ type=str,
292
+ default="纪实摄影风格画面,一只活泼的小狗在绿茵茵的草地上迅速奔跑。小狗毛色棕黄,两只耳朵立起,神情专注而欢快。阳光洒在它身上,使得毛发看上去格外柔软而闪亮。背景是一片开阔的草地,偶尔点缀着几朵野花,远处隐约可见蓝天和几片白云。透视感鲜明,捕捉小狗奔跑时的动感和四周草地的生机。中景侧面移动视角。",
293
+ help="Prompt used for test video generation.",
294
+ )
295
+ parser.add_argument(
296
+ "--noise_sigma",
297
+ type=float,
298
+ default=1.0,
299
+ help="Noise sigma for video generation.",
300
+ )
301
+ parser.add_argument(
302
+ "--bridge_type",
303
+ type=str,
304
+ default="brownian",
305
+ help="ViBT bridge type. Final ViBT uses 'brownian'.",
306
+ )
307
+ parser.add_argument(
308
+ "--bridge_path_type",
309
+ type=str,
310
+ default="brownian",
311
+ help="Compatibility flag for the released ViBT command. Must be 'brownian'.",
312
+ )
313
+ parser.add_argument(
314
+ "--training_weight_type",
315
+ type=str,
316
+ default="uniform",
317
+ help="Training weight type, one of 'uniform', 'time', ...",
318
+ )
319
+ parser.add_argument(
320
+ "--fsr_factor",
321
+ type=int,
322
+ default=1,
323
+ help="Whether to use FSR input embedder.",
324
+ )
325
+ parser.add_argument(
326
+ "--target",
327
+ type=str,
328
+ default="stabilized_drift",
329
+ choices=["stabilized_drift", "drift", "x0"],
330
+ help="Prediction target. Final ViBT uses stabilized_drift to avoid small-t target explosion.",
331
+ )
332
+ parser.add_argument(
333
+ "--image_drop_probability",
334
+ type=float,
335
+ default=0.0,
336
+ help="Dropout probability for the image condition.",
337
+ )
338
+ parser.add_argument(
339
+ "--text_drop_probability",
340
+ type=float,
341
+ default=0.0,
342
+ help="Dropout probability for the text condition.",
343
+ )
344
+ args = parser.parse_args()
345
+ dataset = UnifiedDataset(
346
+ base_path=args.dataset_base_path,
347
+ metadata_path=args.dataset_metadata_path,
348
+ repeat=args.dataset_repeat,
349
+ data_file_keys=args.data_file_keys.split(","),
350
+ main_data_operator=UnifiedDataset.default_video_operator(
351
+ base_path=args.dataset_base_path,
352
+ max_pixels=args.max_pixels,
353
+ height=args.height,
354
+ width=args.width,
355
+ height_division_factor=16,
356
+ width_division_factor=16,
357
+ num_frames=args.num_frames,
358
+ time_division_factor=4,
359
+ time_division_remainder=1,
360
+ ),
361
+ )
362
+ model = WanBridgeTrainingModule(
363
+ model_paths=args.model_paths,
364
+ model_id_with_origin_paths=args.model_id_with_origin_paths,
365
+ trainable_models=args.trainable_models,
366
+ lora_base_model=args.lora_base_model,
367
+ lora_target_modules=args.lora_target_modules,
368
+ lora_rank=args.lora_rank,
369
+ lora_checkpoint=args.lora_checkpoint,
370
+ use_gradient_checkpointing_offload=args.use_gradient_checkpointing_offload,
371
+ extra_inputs=args.extra_inputs,
372
+ max_timestep_boundary=args.max_timestep_boundary,
373
+ min_timestep_boundary=args.min_timestep_boundary,
374
+ image_drop_probability=args.image_drop_probability,
375
+ text_drop_probability=args.text_drop_probability,
376
+ )
377
+ if args.bridge_type != "brownian" or args.bridge_path_type != "brownian":
378
+ raise ValueError("Final ViBT uses --bridge_type brownian --bridge_path_type brownian")
379
+ model.pipe.scheduler.noise_scale = args.noise_sigma
380
+ model.pipe.scheduler.bridge_type = args.bridge_type
381
+ model.pipe.scheduler.training_weight_type = args.training_weight_type
382
+ model.pipe.scheduler.target = args.target
383
+ print("Scheduler noise scale:", model.pipe.scheduler.noise_scale)
384
+ print("Scheduler bridge type:", model.pipe.scheduler.bridge_type)
385
+ print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type)
386
+ print("Scheduler target:", model.pipe.scheduler.target)
387
+ if args.fsr_factor > 1:
388
+ fps = 15 * args.fsr_factor
389
+ target_frames = 80 * args.fsr_factor + 1
390
+ processor = WanVideoBridgeUnit_InputVideoEmbedder_FSR(
391
+ target_frames=target_frames,
392
+ fsr_factor=args.fsr_factor,
393
+ )
394
+ model.pipe.units = model.pipe.units[:-1] + [processor]
395
+ print("Using FSR input embedder.")
396
+ else:
397
+ fps = 15
398
+ model_logger = BridgeLogger(
399
+ args.output_path,
400
+ remove_prefix_in_ckpt=args.remove_prefix_in_ckpt,
401
+ test_video=args.test_video,
402
+ test_prompt=args.test_prompt,
403
+ log_fps=fps,
404
+ )
405
+ launch_prodigy_training_task(dataset, model, model_logger, args=args)
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import copy
3
+ import csv
4
+ import json
5
+ import math
6
+ import os
7
+ import random
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import imageio
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms.functional as TVF
16
+ from accelerate import Accelerator
17
+ from accelerate.utils import DistributedDataParallelKwargs
18
+ from PIL import Image
19
+ from safetensors.torch import load_file
20
+ from torch.nn.parallel.distributed import DistributedDataParallel
21
+ from torch.utils.data import DataLoader, Dataset
22
+ from tqdm import tqdm
23
+
24
+ REPO_ROOT = Path(__file__).resolve().parents[4]
25
+ if str(REPO_ROOT) not in sys.path:
26
+ sys.path.insert(0, str(REPO_ROOT))
27
+
28
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline # noqa: E402
29
+ from diffsynth.pipelines.wan_video_new import PipelineUnit # noqa: E402
30
+ from diffsynth.data.video import save_video # noqa: E402
31
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger # noqa: E402
32
+ from diffsynth.utils import ModelConfig # noqa: E402
33
+
34
+
35
+ def format_run_value(value: object) -> str:
36
+ text = f"{value:g}" if isinstance(value, float) else str(value)
37
+ return text.replace(".", "p").replace("-", "m").replace("/", "_")
38
+
39
+
40
+ def build_run_name(args) -> str:
41
+ upsampler = Path(args.latent_upsampler_ckpt).stem if args.source_mode == "upsampler" else "none"
42
+ parts = [
43
+ "wan_sr",
44
+ f"x{args.sr_scale}",
45
+ f"{args.height}x{args.width}",
46
+ f"f{args.num_frames}",
47
+ args.source_mode,
48
+ f"up_{upsampler}",
49
+ f"lr{format_run_value(args.learning_rate)}",
50
+ f"noise{format_run_value(args.noise_sigma)}",
51
+ f"bridge{format_run_value(args.bridge_loss_weight)}",
52
+ f"lpips{format_run_value(args.lpips_weight)}",
53
+ f"ssim{format_run_value(args.ssim_weight)}",
54
+ f"wav{format_run_value(args.wavelet_hf_weight)}",
55
+ f"pix{format_run_value(args.pixel_loss_weight)}",
56
+ f"pcrop{args.pixel_loss_crop_size}",
57
+ f"plf{args.pixel_loss_latent_frames}",
58
+ f"seed{args.seed}",
59
+ ]
60
+ return "_".join(parts)
61
+
62
+
63
+ def center_crop_resize(image: Image.Image, height: int, width: int) -> Image.Image:
64
+ image_w, image_h = image.size
65
+ scale = max(width / image_w, height / image_h)
66
+ resized = TVF.resize(
67
+ image,
68
+ (round(image_h * scale), round(image_w * scale)),
69
+ interpolation=TVF.InterpolationMode.BICUBIC,
70
+ )
71
+ return TVF.center_crop(resized, (height, width))
72
+
73
+
74
+ def make_lr_source(image: Image.Image, height: int, width: int, scale: int, upsample_to_hr: bool) -> Image.Image:
75
+ lr_h = max(height // int(scale), 1)
76
+ lr_w = max(width // int(scale), 1)
77
+ lr = image.resize((lr_w, lr_h), Image.Resampling.BICUBIC)
78
+ if upsample_to_hr:
79
+ return lr.resize((width, height), Image.Resampling.BICUBIC)
80
+ return lr
81
+
82
+
83
+ def load_metadata_prompts(prompt_json: str | None, valid_stems: set[str], prompt_field: str) -> dict[str, str]:
84
+ if not prompt_json:
85
+ return {}
86
+ path = Path(prompt_json)
87
+ if not path.exists():
88
+ raise FileNotFoundError(f"prompt metadata not found: {path}")
89
+ if path.suffix.lower() == ".jsonl":
90
+ items = []
91
+ bad_lines = 0
92
+ for line in path.read_text(encoding="utf-8").splitlines():
93
+ if not line.strip():
94
+ continue
95
+ try:
96
+ items.append(json.loads(line))
97
+ except json.JSONDecodeError:
98
+ bad_lines += 1
99
+ if bad_lines:
100
+ print(f"[SRDataset] skipped {bad_lines} malformed metadata jsonl lines from {path}")
101
+ elif path.suffix.lower() == ".json":
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ items = data if isinstance(data, list) else [
104
+ {"video": key, "prompt": value} for key, value in data.items()
105
+ ] if isinstance(data, dict) else []
106
+ else:
107
+ with path.open("r", encoding="utf-8") as f:
108
+ items = list(csv.DictReader(f))
109
+
110
+ prompts = {}
111
+ for item in items:
112
+ if not isinstance(item, dict):
113
+ continue
114
+ video = item.get("video") or item.get("path") or item.get("file") or item.get("file_name") or item.get("id")
115
+ media = item.get("media")
116
+ if isinstance(media, dict):
117
+ video = media.get("v") or video
118
+ if not video:
119
+ continue
120
+ stem = Path(str(video)).stem
121
+ if stem not in valid_stems:
122
+ continue
123
+ prompt = str(item.get("prompt") or item.get("caption") or item.get("raw_p") or "")
124
+ i18n = item.get("i18n")
125
+ if prompt_field != "raw_p" and isinstance(i18n, dict):
126
+ if prompt_field in ("en", "zh"):
127
+ block = i18n.get(prompt_field)
128
+ if isinstance(block, dict):
129
+ prompt = str(block.get("p") or block.get("t") or prompt)
130
+ elif prompt_field in ("en_title", "zh_title"):
131
+ block = i18n.get(prompt_field.split("_", 1)[0])
132
+ if isinstance(block, dict):
133
+ prompt = str(block.get("t") or block.get("p") or prompt)
134
+ if prompt:
135
+ prompts[stem] = prompt
136
+ return prompts
137
+
138
+
139
+ class SeedanceSRDataset(Dataset):
140
+ def __init__(
141
+ self,
142
+ video_dir: str,
143
+ prompt_json: str | None,
144
+ prompt_field: str,
145
+ default_prompt: str,
146
+ height: int,
147
+ width: int,
148
+ num_frames: int,
149
+ sr_scale: int,
150
+ source_mode: str = "upsampler",
151
+ repeat: int = 1,
152
+ limit_videos: int | None = None,
153
+ seed: int = 0,
154
+ ) -> None:
155
+ self.video_dir = Path(video_dir)
156
+ self.height = int(height)
157
+ self.width = int(width)
158
+ self.num_frames = int(num_frames)
159
+ self.sr_scale = int(sr_scale)
160
+ self.source_mode = source_mode
161
+ self.repeat = int(repeat)
162
+ self.default_prompt = default_prompt
163
+ self.rng = random.Random(seed)
164
+ self.videos = sorted(
165
+ p for p in self.video_dir.rglob("*")
166
+ if p.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".avi")
167
+ )
168
+ if limit_videos is not None:
169
+ self.videos = self.videos[: int(limit_videos)]
170
+ if not self.videos:
171
+ raise FileNotFoundError(f"No videos found under {self.video_dir}")
172
+ self.prompts = load_metadata_prompts(prompt_json, {p.stem for p in self.videos}, prompt_field)
173
+ if prompt_json:
174
+ print(f"[SRDataset] matched {len(self.prompts)}/{len(self.videos)} prompts from {prompt_json}")
175
+
176
+ def __len__(self) -> int:
177
+ return len(self.videos) * self.repeat
178
+
179
+ def _read_frames(self, path: Path) -> list[Image.Image]:
180
+ reader = imageio.get_reader(str(path))
181
+ try:
182
+ frame_count = int(reader.count_frames())
183
+ except Exception:
184
+ frame_count = self.num_frames
185
+ max_start = max(frame_count - self.num_frames, 0)
186
+ start = self.rng.randint(0, max_start) if max_start > 0 else 0
187
+ frames = []
188
+ last = None
189
+ for frame_id in range(start, start + self.num_frames):
190
+ try:
191
+ array = reader.get_data(frame_id)
192
+ last = array
193
+ except Exception:
194
+ if last is None:
195
+ break
196
+ array = last
197
+ image = Image.fromarray(np.asarray(array)).convert("RGB")
198
+ frames.append(center_crop_resize(image, self.height, self.width))
199
+ reader.close()
200
+ if not frames:
201
+ raise RuntimeError(f"No frames decoded from {path}")
202
+ while len(frames) < self.num_frames:
203
+ frames.append(frames[-1].copy())
204
+ return frames
205
+
206
+ def __getitem__(self, idx: int) -> dict:
207
+ path = self.videos[idx % len(self.videos)]
208
+ target_video = self._read_frames(path)
209
+ source_video = [
210
+ make_lr_source(frame, self.height, self.width, self.sr_scale, upsample_to_hr=self.source_mode == "bicubic")
211
+ for frame in target_video
212
+ ]
213
+ return {
214
+ "video": target_video,
215
+ "source_video": source_video,
216
+ "prompt": self.prompts.get(path.stem, self.default_prompt),
217
+ "path": str(path),
218
+ }
219
+
220
+
221
+ def pil_video_to_tensor_01(video: list[Image.Image], device: torch.device) -> torch.Tensor:
222
+ frames = [torch.from_numpy(np.asarray(frame).copy()).float().div(255.0) for frame in video]
223
+ return torch.stack(frames, dim=0).permute(0, 3, 1, 2).to(device=device)
224
+
225
+
226
+ def tensor_btchw_01_to_pil(video: torch.Tensor) -> list[Image.Image]:
227
+ video = video.detach().float().clamp(0, 1).cpu()
228
+ frames = video.permute(0, 2, 3, 1).numpy()
229
+ return [Image.fromarray((frame * 255.0).round().astype("uint8")) for frame in frames]
230
+
231
+
232
+ def decode_latents_to_btchw_01(pipe: WanVideoBridgePipeline, latents: torch.Tensor, tiled: bool, tile_size, tile_stride) -> torch.Tensor:
233
+ vae_dtype = next(pipe.vae.parameters()).dtype
234
+ decoded = pipe.vae.decode(
235
+ latents.to(dtype=vae_dtype),
236
+ device=pipe.device,
237
+ tiled=tiled,
238
+ tile_size=tile_size,
239
+ tile_stride=tile_stride,
240
+ )
241
+ return decoded.add(1.0).div(2.0).clamp(0, 1).permute(0, 2, 1, 3, 4).contiguous()
242
+
243
+
244
+ def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor:
245
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
246
+ if min_t <= 0:
247
+ return pred_btchw_01.new_tensor(0.0)
248
+ pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float()
249
+ target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float()
250
+ channels = pred.shape[1]
251
+ window_size = max(1, int(window_size))
252
+ if window_size % 2 == 0:
253
+ window_size += 1
254
+ padding = window_size // 2
255
+ weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size)
256
+
257
+ mu_x = F.conv2d(pred, weight, padding=padding, groups=channels)
258
+ mu_y = F.conv2d(target, weight, padding=padding, groups=channels)
259
+ mu_x_sq = mu_x.square()
260
+ mu_y_sq = mu_y.square()
261
+ mu_xy = mu_x * mu_y
262
+
263
+ sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq
264
+ sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq
265
+ sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy
266
+
267
+ c1 = 0.01 ** 2
268
+ c2 = 0.03 ** 2
269
+ ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / (
270
+ (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8
271
+ )
272
+ return (1.0 - ssim.clamp(-1.0, 1.0)).mean()
273
+
274
+
275
+ def crop_latent_pair_for_pixel_losses(
276
+ pred_latents: torch.Tensor,
277
+ target_latents: torch.Tensor,
278
+ crop_size_pixels: int,
279
+ latent_frames: int,
280
+ vae_factor: int,
281
+ return_crop_info: bool = False,
282
+ ):
283
+ _, _, t, h, w = pred_latents.shape
284
+ if latent_frames > 0 and t > latent_frames:
285
+ crop_t = int(latent_frames)
286
+ start_t = int(torch.randint(t - crop_t + 1, (1,), device=pred_latents.device).item())
287
+ else:
288
+ crop_t = t
289
+ start_t = 0
290
+
291
+ if crop_size_pixels > 0:
292
+ crop_h = max(int(crop_size_pixels) // max(int(vae_factor), 1), 1)
293
+ crop_w = crop_h
294
+ crop_h = min(crop_h, h)
295
+ crop_w = min(crop_w, w)
296
+ start_h = int(torch.randint(h - crop_h + 1, (1,), device=pred_latents.device).item()) if h > crop_h else 0
297
+ start_w = int(torch.randint(w - crop_w + 1, (1,), device=pred_latents.device).item()) if w > crop_w else 0
298
+ else:
299
+ crop_h, crop_w = h, w
300
+ start_h, start_w = 0, 0
301
+
302
+ pred = pred_latents[:, :, start_t:start_t + crop_t, start_h:start_h + crop_h, start_w:start_w + crop_w]
303
+ target = target_latents[:, :, start_t:start_t + crop_t, start_h:start_h + crop_h, start_w:start_w + crop_w]
304
+ if return_crop_info:
305
+ return pred.contiguous(), target.contiguous(), {
306
+ "start_t": start_t,
307
+ "start_h": start_h,
308
+ "start_w": start_w,
309
+ "crop_t": crop_t,
310
+ "crop_h": crop_h,
311
+ "crop_w": crop_w,
312
+ "full_t": t,
313
+ "full_h": h,
314
+ "full_w": w,
315
+ }
316
+ return pred.contiguous(), target.contiguous()
317
+
318
+
319
+ def crop_original_rgb_for_latent_crop(
320
+ original_frames: list[Image.Image],
321
+ crop_info: dict,
322
+ decoded_crop: torch.Tensor,
323
+ device: torch.device,
324
+ ) -> torch.Tensor:
325
+ """Map a decoded latent crop to the same region of the on-disk RGB clip."""
326
+ device = decoded_crop.device if decoded_crop is not None else device
327
+ original = pil_video_to_tensor_01(original_frames, device).unsqueeze(0)
328
+ full_t, full_h, full_w = crop_info["full_t"], crop_info["full_h"], crop_info["full_w"]
329
+ if full_t > 1:
330
+ if (original.shape[1] - 1) % (full_t - 1):
331
+ raise ValueError(f"Cannot align RGB/latent time lengths {original.shape[1]} and {full_t}")
332
+ temporal_stride = (original.shape[1] - 1) // (full_t - 1)
333
+ else:
334
+ temporal_stride = 1
335
+ if original.shape[-2] % full_h or original.shape[-1] % full_w:
336
+ raise ValueError(f"Cannot align RGB size {original.shape[-2:]} with latent grid {(full_h, full_w)}")
337
+ spatial_stride_h = original.shape[-2] // full_h
338
+ spatial_stride_w = original.shape[-1] // full_w
339
+ start_t = crop_info["start_t"] * temporal_stride
340
+ start_h = crop_info["start_h"] * spatial_stride_h
341
+ start_w = crop_info["start_w"] * spatial_stride_w
342
+ target = original[
343
+ :,
344
+ start_t:start_t + decoded_crop.shape[1],
345
+ :,
346
+ start_h:start_h + decoded_crop.shape[-2],
347
+ start_w:start_w + decoded_crop.shape[-1],
348
+ ]
349
+ if target.shape != decoded_crop.shape:
350
+ raise ValueError(
351
+ f"Aligned original crop shape {tuple(target.shape)} != decoded prediction {tuple(decoded_crop.shape)}"
352
+ )
353
+ return target.to(device=decoded_crop.device, dtype=decoded_crop.dtype)
354
+
355
+
356
+ def random_spatial_crop_pair(pred: torch.Tensor, target: torch.Tensor, crop_size: int) -> tuple[torch.Tensor, torch.Tensor]:
357
+ if crop_size <= 0:
358
+ return pred, target
359
+ h, w = pred.shape[-2:]
360
+ crop_h = min(int(crop_size), h)
361
+ crop_w = min(int(crop_size), w)
362
+ if crop_h == h and crop_w == w:
363
+ return pred, target
364
+ top = torch.randint(h - crop_h + 1, (1,), device=pred.device).item() if h > crop_h else 0
365
+ left = torch.randint(w - crop_w + 1, (1,), device=pred.device).item() if w > crop_w else 0
366
+ return pred[..., top:top + crop_h, left:left + crop_w], target[..., top:top + crop_h, left:left + crop_w]
367
+
368
+
369
+ def lpips_video_loss(lpips_model, pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, num_frames: int, crop_size: int) -> torch.Tensor:
370
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
371
+ pred = pred_btchw_01[:, :min_t]
372
+ target = target_btchw_01[:, :min_t]
373
+ pred, target = random_spatial_crop_pair(pred, target, crop_size)
374
+ if num_frames > 0 and pred.shape[1] > num_frames:
375
+ frame_idx = torch.linspace(0, pred.shape[1] - 1, steps=num_frames, device=pred.device).round().long()
376
+ pred = pred.index_select(1, frame_idx)
377
+ target = target.index_select(1, frame_idx)
378
+ pred_frames = pred.reshape(-1, pred.shape[2], pred.shape[3], pred.shape[4]).mul(2).sub(1).clamp(-1, 1)
379
+ target_frames = target.reshape(-1, target.shape[2], target.shape[3], target.shape[4]).mul(2).sub(1).clamp(-1, 1)
380
+ return lpips_model(pred_frames.float(), target_frames.float()).mean()
381
+
382
+
383
+ def haar_highfreq_bands(video_btchw_01: torch.Tensor, levels: int) -> list[torch.Tensor]:
384
+ x = video_btchw_01.reshape(-1, video_btchw_01.shape[2], video_btchw_01.shape[3], video_btchw_01.shape[4]).float()
385
+ bands = []
386
+ for _ in range(max(int(levels), 1)):
387
+ h_even = x.shape[-2] - (x.shape[-2] % 2)
388
+ w_even = x.shape[-1] - (x.shape[-1] % 2)
389
+ if h_even < 2 or w_even < 2:
390
+ break
391
+ x = x[..., :h_even, :w_even]
392
+ a = x[..., 0::2, 0::2]
393
+ b = x[..., 0::2, 1::2]
394
+ c = x[..., 1::2, 0::2]
395
+ d = x[..., 1::2, 1::2]
396
+ ll = (a + b + c + d) * 0.5
397
+ lh = (a - b + c - d) * 0.5
398
+ hl = (a + b - c - d) * 0.5
399
+ hh = (a - b - c + d) * 0.5
400
+ bands.extend([lh, hl, hh])
401
+ x = ll
402
+ return bands
403
+
404
+
405
+ def wavelet_hf_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, levels: int, loss_type: str) -> torch.Tensor:
406
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
407
+ pred_bands = haar_highfreq_bands(pred_btchw_01[:, :min_t], levels)
408
+ target_bands = haar_highfreq_bands(target_btchw_01[:, :min_t], levels)
409
+ if not pred_bands:
410
+ return pred_btchw_01.new_tensor(0.0)
411
+ losses = []
412
+ for pred_band, target_band in zip(pred_bands, target_bands):
413
+ if loss_type == "l2":
414
+ losses.append(F.mse_loss(pred_band, target_band))
415
+ else:
416
+ losses.append(F.l1_loss(pred_band, target_band))
417
+ return torch.stack(losses).mean()
418
+
419
+
420
+ class WanVideoSRBridgePipeline(WanVideoBridgePipeline):
421
+ def training_loss(self, **inputs):
422
+ max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps)
423
+ min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps)
424
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
425
+ timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device)
426
+
427
+ x0 = inputs["input_latents"]
428
+ x1 = inputs["source_latents"]
429
+ noise = inputs["noise"]
430
+ xt = self.scheduler.add_noise(x0, x1, noise, timestep)
431
+ inputs["latents"] = xt
432
+
433
+ target = self.scheduler.training_target(x0, xt, timestep)
434
+ model_output = self.model_fn(**inputs, timestep=timestep)
435
+
436
+ if self.scheduler.target == "stabilized_drift":
437
+ sigma = self.scheduler.get_sigma(timestep)
438
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5
439
+ velocity_target = target / factor
440
+ velocity_for_endpoint = model_output * factor
441
+ elif self.scheduler.target == "drift":
442
+ velocity_target = target
443
+ velocity_for_endpoint = model_output
444
+ else:
445
+ raise ValueError("SR bridge training supports --target stabilized_drift or drift")
446
+
447
+ bridge_loss = F.mse_loss(model_output.float(), velocity_target.float())
448
+ total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss
449
+ metrics = {
450
+ "bridge_loss": float(bridge_loss.detach().cpu()),
451
+ "lpips_loss": 0.0,
452
+ "ssim_loss": 0.0,
453
+ "wavelet_hf_loss": 0.0,
454
+ "pixel_loss": 0.0,
455
+ }
456
+
457
+ lpips_model = inputs.get("lpips_model")
458
+ lpips_weight = float(inputs.get("lpips_weight", 0.0))
459
+ ssim_weight = float(inputs.get("ssim_weight", 0.0))
460
+ wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0))
461
+ pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0))
462
+ if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0:
463
+ sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
464
+ endpoint_pred = xt.float() - sigma * velocity_for_endpoint.float()
465
+ endpoint_pred, target_latents_for_pixel, crop_info = crop_latent_pair_for_pixel_losses(
466
+ endpoint_pred,
467
+ x0.detach(),
468
+ crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 256)),
469
+ latent_frames=int(inputs.get("pixel_loss_latent_frames", 3)),
470
+ vae_factor=int(getattr(self.vae, "upsampling_factor", 8)),
471
+ return_crop_info=True,
472
+ )
473
+ pred_video = decode_latents_to_btchw_01(
474
+ self,
475
+ endpoint_pred,
476
+ tiled=bool(inputs.get("tiled", False)),
477
+ tile_size=inputs.get("tile_size", (30, 52)),
478
+ tile_stride=inputs.get("tile_stride", (15, 26)),
479
+ )
480
+ raw_target_video = inputs.get("raw_target_video")
481
+ if raw_target_video is None:
482
+ raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses")
483
+ target_video = crop_original_rgb_for_latent_crop(
484
+ raw_target_video, crop_info, pred_video, self.device
485
+ )
486
+ if lpips_weight > 0:
487
+ if lpips_model is None:
488
+ raise ValueError("lpips_model is required when lpips_weight > 0")
489
+ loss = lpips_video_loss(
490
+ lpips_model,
491
+ pred_video,
492
+ target_video,
493
+ num_frames=int(inputs.get("lpips_num_frames", 4)),
494
+ crop_size=int(inputs.get("lpips_crop_size", 224)),
495
+ )
496
+ total_loss = total_loss + lpips_weight * loss
497
+ metrics["lpips_loss"] = float(loss.detach().cpu())
498
+ if ssim_weight > 0:
499
+ loss = ssim_video_loss(
500
+ pred_video,
501
+ target_video,
502
+ window_size=int(inputs.get("ssim_window_size", 11)),
503
+ )
504
+ total_loss = total_loss + ssim_weight * loss
505
+ metrics["ssim_loss"] = float(loss.detach().cpu())
506
+ if wavelet_hf_weight > 0:
507
+ loss = wavelet_hf_loss(
508
+ pred_video,
509
+ target_video,
510
+ levels=int(inputs.get("wavelet_hf_levels", 1)),
511
+ loss_type=str(inputs.get("wavelet_hf_loss", "l1")),
512
+ )
513
+ total_loss = total_loss + wavelet_hf_weight * loss
514
+ metrics["wavelet_hf_loss"] = float(loss.detach().cpu())
515
+ if pixel_loss_weight > 0:
516
+ loss = F.mse_loss(pred_video.float(), target_video.float())
517
+ total_loss = total_loss + pixel_loss_weight * loss
518
+ metrics["pixel_loss"] = float(loss.detach().cpu())
519
+
520
+ return total_loss, metrics
521
+
522
+
523
+ class WanVideoSRUnit_UltraFlashLatentUpsampler(PipelineUnit):
524
+ def __init__(self):
525
+ super().__init__(
526
+ input_params=("source_video", "tiled", "tile_size", "tile_stride"),
527
+ onload_model_names=("vae", "latent_upsampler"),
528
+ )
529
+
530
+ def process(self, pipe: WanVideoBridgePipeline, source_video, tiled, tile_size, tile_stride):
531
+ pipe.load_models_to_device(["vae", "latent_upsampler"])
532
+ source_video = pipe.preprocess_video(source_video)
533
+ lr_latents = pipe.vae.encode(
534
+ source_video,
535
+ device=pipe.device,
536
+ tiled=tiled,
537
+ tile_size=tile_size,
538
+ tile_stride=tile_stride,
539
+ ).to(dtype=next(pipe.latent_upsampler.parameters()).dtype, device=pipe.device)
540
+ source_latents, _ = pipe.latent_upsampler(
541
+ lr_latents,
542
+ parallel=True,
543
+ caches=None,
544
+ return_caches=True,
545
+ detach_caches=True,
546
+ )
547
+ return {"source_latents": source_latents.to(dtype=pipe.torch_dtype, device=pipe.device)}
548
+
549
+
550
+ def load_ultraflash_latent_upsampler(args, device: str | torch.device):
551
+ ultraflash_dir = Path(args.ultraflash_dir).resolve()
552
+ if str(ultraflash_dir) not in sys.path:
553
+ sys.path.insert(0, str(ultraflash_dir))
554
+ from sr.config import load_config_class_from_pyfile
555
+ from sr.load_utils import load_latent_upsampler
556
+
557
+ cfg = load_config_class_from_pyfile(str(Path(args.ultraflash_sr_config).resolve()))()
558
+ cfg.latent_upsampler_ckpt = args.latent_upsampler_ckpt
559
+ cfg.latent_upsampler_precision = args.upsampler_dtype
560
+ cfg.latent_upsampler_arch_config["params"]["upsample_scale"] = int(args.sr_scale)
561
+ upsampler = load_latent_upsampler(cfg, torch.device(device))
562
+ upsampler.eval().requires_grad_(False)
563
+ return upsampler
564
+
565
+
566
+ class WanSRTrainingModule(DiffusionTrainingModule):
567
+ def __init__(self, args):
568
+ super().__init__()
569
+ model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
570
+ self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained(
571
+ torch_dtype=torch.bfloat16,
572
+ device="cpu",
573
+ model_configs=model_configs,
574
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
575
+ )
576
+ if args.source_mode == "upsampler":
577
+ self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu")
578
+ self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()]
579
+ print(f"[SRBridge] source_mode=upsampler ckpt={args.latent_upsampler_ckpt}")
580
+ else:
581
+ self.pipe.latent_upsampler = None
582
+ print("[SRBridge] source_mode=bicubic")
583
+ self.switch_pipe_to_training_mode(
584
+ self.pipe,
585
+ args.trainable_models,
586
+ args.lora_base_model,
587
+ args.lora_target_modules,
588
+ args.lora_rank,
589
+ lora_checkpoint=args.lora_checkpoint,
590
+ enable_fp8_training=False,
591
+ )
592
+ self.args = args
593
+ self.extra_loss_inputs = {}
594
+ if args.lpips_weight > 0 or args.val_lpips:
595
+ import lpips
596
+
597
+ self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False)
598
+ else:
599
+ self.lpips_model = None
600
+
601
+ def to(self, *args, **kwargs):
602
+ super().to(*args, **kwargs)
603
+ if self.lpips_model is not None:
604
+ self.lpips_model.to(*args, **kwargs)
605
+ return self
606
+
607
+ def forward_preprocess(self, data):
608
+ prompt = data["prompt"]
609
+ if random.random() < self.args.text_drop_probability:
610
+ prompt = " "
611
+ inputs_posi = {"prompt": prompt}
612
+ inputs_nega = {}
613
+ inputs_shared = {
614
+ "input_video": data["video"],
615
+ "source_video": data["source_video"],
616
+ "height": data["video"][0].size[1],
617
+ "width": data["video"][0].size[0],
618
+ "num_frames": len(data["video"]),
619
+ "cfg_scale": 1,
620
+ "tiled": self.args.tiled,
621
+ "tile_size": (self.args.tile_h, self.args.tile_w),
622
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
623
+ "rand_device": self.pipe.device,
624
+ "seed": None,
625
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
626
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
627
+ "cfg_merge": False,
628
+ "vace_scale": 1,
629
+ "max_timestep_boundary": self.args.max_timestep_boundary,
630
+ "min_timestep_boundary": self.args.min_timestep_boundary,
631
+ "bridge_loss_weight": self.args.bridge_loss_weight,
632
+ "lpips_weight": self.args.lpips_weight,
633
+ "lpips_model": self.lpips_model,
634
+ "lpips_num_frames": self.args.lpips_num_frames,
635
+ "lpips_crop_size": self.args.lpips_crop_size,
636
+ "ssim_weight": self.args.ssim_weight,
637
+ "ssim_window_size": self.args.ssim_window_size,
638
+ "pixel_loss_crop_size": self.args.pixel_loss_crop_size,
639
+ "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames,
640
+ "wavelet_hf_weight": self.args.wavelet_hf_weight,
641
+ "wavelet_hf_levels": self.args.wavelet_hf_levels,
642
+ "wavelet_hf_loss": self.args.wavelet_hf_loss,
643
+ "pixel_loss_weight": self.args.pixel_loss_weight,
644
+ }
645
+ for unit in self.pipe.units:
646
+ inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(
647
+ unit, self.pipe, inputs_shared, inputs_posi, inputs_nega
648
+ )
649
+ # Keep the preprocessed frames loaded from disk as the direct RGB loss target.
650
+ inputs_shared["raw_target_video"] = data["video"]
651
+ return {**inputs_shared, **inputs_posi}
652
+
653
+ def forward(self, data, inputs=None):
654
+ if inputs is None:
655
+ inputs = self.forward_preprocess(data)
656
+ return self.pipe.training_loss(**{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}, **inputs)
657
+
658
+
659
+ class SRModelLogger(ModelLogger):
660
+ def on_step_end(self, accelerator, model, save_steps=None):
661
+ super().on_step_end(accelerator, model, save_steps)
662
+
663
+
664
+ @torch.no_grad()
665
+ def validate(args, accelerator: Accelerator, model: WanSRTrainingModule, dataset: Dataset, step: int) -> dict:
666
+ if not accelerator.is_main_process:
667
+ return {}
668
+ module = accelerator.unwrap_model(model)
669
+ pipe = module.pipe
670
+ pipe.eval()
671
+ backup_scheduler = pipe.scheduler
672
+ pipe.scheduler = copy.deepcopy(backup_scheduler)
673
+ pipe.scheduler.noise_scale = args.val_sampling_noise_scale
674
+ pipe.scheduler.target = args.target
675
+
676
+ rows = []
677
+ out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}"
678
+ out_dir.mkdir(parents=True, exist_ok=True)
679
+ for idx in range(min(args.val_batches, len(dataset))):
680
+ data = dataset[idx]
681
+ pipe.scheduler.set_timesteps(1000, training=True)
682
+ inputs = module.forward_preprocess(data)
683
+ pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift)
684
+ x0 = inputs["input_latents"]
685
+ x1 = inputs["source_latents"]
686
+ latents = x1.clone()
687
+ pipe.load_models_to_device(pipe.in_iteration_models)
688
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
689
+ model_inputs = dict(inputs)
690
+ model_inputs.pop("latents", None)
691
+ for timestep_cpu in pipe.scheduler.timesteps:
692
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
693
+ pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep)
694
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, x1)
695
+
696
+ 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))
697
+ 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))
698
+ source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0)
699
+ target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0)
700
+ if source_tensor.shape[-2:] != target_tensor.shape[-2:]:
701
+ b, t, c, h, w = source_tensor.shape
702
+ source_tensor = F.interpolate(
703
+ source_tensor.reshape(b * t, c, h, w),
704
+ size=target_tensor.shape[-2:],
705
+ mode="bicubic",
706
+ align_corners=False,
707
+ antialias=True,
708
+ ).reshape(b, t, c, target_tensor.shape[-2], target_tensor.shape[-1]).clamp(0, 1)
709
+ min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1])
710
+ strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1)
711
+ save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5)
712
+ 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)
713
+ mse = F.mse_loss(pred_video.float(), target_video.float()).item()
714
+ row = {"idx": idx, "latent_mse": F.mse_loss(latents.float(), x0.float()).item(), "pixel_mse": mse}
715
+ if module.lpips_model is not None and args.val_lpips:
716
+ row["lpips"] = float(lpips_video_loss(module.lpips_model, pred_video, target_video, args.lpips_num_frames, args.lpips_crop_size).detach().cpu())
717
+ if args.val_wavelet_hf_loss:
718
+ row["wavelet_hf"] = float(wavelet_hf_loss(pred_video, target_video, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu())
719
+ if args.val_ssim or args.ssim_weight > 0:
720
+ row["ssim"] = float(ssim_video_loss(pred_video, target_video, args.ssim_window_size).detach().cpu())
721
+ rows.append(row)
722
+
723
+ pipe.scheduler = backup_scheduler
724
+ metrics = {}
725
+ if rows:
726
+ for key in rows[0]:
727
+ if key != "idx":
728
+ 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))
729
+ (out_dir / "metrics.json").write_text(json.dumps({"step": step, "rows": rows, "metrics": metrics}, indent=2), encoding="utf-8")
730
+ print(f"[Validation step {step}] {metrics}")
731
+ pipe.train()
732
+ return metrics
733
+
734
+
735
+ def train(args):
736
+ save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None
737
+ if args.output_path is None:
738
+ args.output_path = str(Path(args.output_root) / build_run_name(args))
739
+ train_set = SeedanceSRDataset(
740
+ args.video_dir,
741
+ args.prompt_json,
742
+ args.prompt_field,
743
+ args.default_prompt,
744
+ args.height,
745
+ args.width,
746
+ args.num_frames,
747
+ args.sr_scale,
748
+ source_mode=args.source_mode,
749
+ repeat=args.dataset_repeat,
750
+ limit_videos=args.limit_videos,
751
+ seed=args.seed,
752
+ )
753
+ val_set = SeedanceSRDataset(
754
+ args.video_dir,
755
+ args.prompt_json,
756
+ args.prompt_field,
757
+ args.default_prompt,
758
+ args.height,
759
+ args.width,
760
+ args.num_frames,
761
+ args.sr_scale,
762
+ source_mode=args.source_mode,
763
+ repeat=1,
764
+ limit_videos=max(args.val_batches, 1),
765
+ seed=args.seed + 1,
766
+ )
767
+ model = WanSRTrainingModule(args)
768
+ model.pipe.scheduler.noise_scale = args.noise_sigma
769
+ model.pipe.scheduler.bridge_type = "brownian"
770
+ model.pipe.scheduler.training_weight_type = args.training_weight_type
771
+ model.pipe.scheduler.target = args.target
772
+ print("Scheduler noise scale:", model.pipe.scheduler.noise_scale)
773
+ print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type)
774
+ print("Scheduler target:", model.pipe.scheduler.target)
775
+
776
+ accelerator = Accelerator(
777
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
778
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
779
+ )
780
+ if accelerator.is_main_process:
781
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
782
+ (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
783
+ print(f"[Output] {args.output_path}")
784
+
785
+ if args.validation_only or args.max_train_steps <= 0:
786
+ model = accelerator.prepare(model)
787
+ validate(args, accelerator, model, val_set, 0)
788
+ return
789
+
790
+ from prodigyopt import Prodigy
791
+
792
+ optimizer = Prodigy(
793
+ model.trainable_modules(),
794
+ lr=args.learning_rate,
795
+ weight_decay=args.weight_decay,
796
+ safeguard_warmup=True,
797
+ d_coef=args.d_coef,
798
+ )
799
+ dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers)
800
+ model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
801
+ logger = SRModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt)
802
+ if args.validate_at_start:
803
+ validate(args, accelerator, model, val_set, 0)
804
+
805
+ global_step = 0
806
+ while global_step < args.max_train_steps:
807
+ for data in tqdm(dataloader, disable=not accelerator.is_local_main_process):
808
+ with accelerator.accumulate(model):
809
+ optimizer.zero_grad()
810
+ loss, metrics = model(data)
811
+ accelerator.backward(loss)
812
+ if args.max_grad_norm > 0:
813
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
814
+ optimizer.step()
815
+ global_step += 1
816
+ gathered_loss = accelerator.gather(loss.detach()).mean().item()
817
+ if accelerator.is_main_process and global_step % args.log_interval == 0:
818
+ print(
819
+ f"[Train step {global_step}] loss={gathered_loss:.6f} "
820
+ f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} "
821
+ f"ssim={metrics['ssim_loss']:.6f} "
822
+ f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}"
823
+ )
824
+ logger.on_step_end(accelerator, model, save_steps)
825
+ if args.val_interval > 0 and global_step % args.val_interval == 0:
826
+ validate(args, accelerator, model, val_set, global_step)
827
+ if global_step >= args.max_train_steps:
828
+ break
829
+ logger.on_training_end(accelerator, model, save_steps)
830
+
831
+
832
+ def default_model_paths(base_model_dir: str) -> str:
833
+ base = Path(base_model_dir)
834
+ paths = [
835
+ base / "diffusion_pytorch_model.safetensors",
836
+ base / "models_t5_umt5-xxl-enc-bf16.pth",
837
+ base / "Wan2.1_VAE.pth",
838
+ ]
839
+ for path in paths:
840
+ if not path.exists():
841
+ raise FileNotFoundError(f"Missing Wan model file: {path}")
842
+ return ",".join(str(path) for path in paths)
843
+
844
+
845
+ def parse_args():
846
+ parser = argparse.ArgumentParser(description="Train a Wan2.1 Brownian-Bridge super-resolution DiT with native Wan VAE.")
847
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
848
+ parser.add_argument("--model_paths", default=None)
849
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
850
+ parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
851
+ parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
852
+ parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p")
853
+ parser.add_argument("--default_prompt", default="")
854
+ parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr")
855
+ parser.add_argument("--output_path", default=None)
856
+ parser.add_argument("--height", type=int, default=480)
857
+ parser.add_argument("--width", type=int, default=832)
858
+ parser.add_argument("--num_frames", type=int, default=81)
859
+ parser.add_argument("--sr_scale", type=int, default=2)
860
+ parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler")
861
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
862
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
863
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
864
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
865
+ parser.add_argument("--fps", type=int, default=16)
866
+ parser.add_argument("--limit_videos", type=int, default=None)
867
+ parser.add_argument("--dataset_repeat", type=int, default=1)
868
+ parser.add_argument("--dataset_num_workers", type=int, default=0)
869
+ parser.add_argument("--trainable_models", default="dit")
870
+ parser.add_argument("--lora_base_model", default=None)
871
+ parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2")
872
+ parser.add_argument("--lora_rank", type=int, default=32)
873
+ parser.add_argument("--lora_checkpoint", default=None)
874
+ parser.add_argument("--learning_rate", type=float, default=1.0)
875
+ parser.add_argument("--weight_decay", type=float, default=0.01)
876
+ parser.add_argument("--d_coef", type=float, default=1.0)
877
+ parser.add_argument("--max_train_steps", type=int, default=5000)
878
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
879
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
880
+ parser.add_argument("--save_steps", type=int, default=500)
881
+ parser.add_argument("--log_interval", type=int, default=1)
882
+ parser.add_argument("--val_interval", type=int, default=100)
883
+ parser.add_argument("--val_batches", type=int, default=1)
884
+ parser.add_argument("--validate_at_start", action="store_true", default=False)
885
+ parser.add_argument("--validation_only", action="store_true", default=False)
886
+ parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.")
887
+ parser.add_argument("--noise_sigma", type=float, default=1.0)
888
+ parser.add_argument("--training_weight_type", default="uniform")
889
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
890
+ parser.add_argument("--bridge_loss_weight", type=float, default=1.0)
891
+ parser.add_argument("--lpips_weight", type=float, default=0.2)
892
+ parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg")
893
+ parser.add_argument("--lpips_num_frames", type=int, default=4)
894
+ parser.add_argument("--lpips_crop_size", type=int, default=224)
895
+ parser.add_argument("--ssim_weight", type=float, default=0.0)
896
+ parser.add_argument("--ssim_window_size", type=int, default=11)
897
+ parser.add_argument("--val_ssim", action="store_true", default=False)
898
+ 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.")
899
+ 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.")
900
+ parser.add_argument("--val_lpips", action="store_true", default=False)
901
+ parser.add_argument("--wavelet_hf_weight", type=float, default=0.1)
902
+ parser.add_argument("--wavelet_hf_levels", type=int, default=1)
903
+ parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1")
904
+ parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False)
905
+ parser.add_argument("--pixel_loss_weight", type=float, default=0.0)
906
+ parser.add_argument("--val_inference_steps", type=int, default=8)
907
+ parser.add_argument("--val_sampling_noise_scale", type=float, default=0.0)
908
+ parser.add_argument("--val_sigma_shift", type=float, default=1.0)
909
+ parser.add_argument("--max_timestep_boundary", type=float, default=0.9999)
910
+ parser.add_argument("--min_timestep_boundary", type=float, default=0.0001)
911
+ parser.add_argument("--text_drop_probability", type=float, default=0.0)
912
+ parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True)
913
+ parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False)
914
+ parser.add_argument("--find_unused_parameters", action="store_true", default=False)
915
+ parser.add_argument("--tiled", action="store_true", default=False)
916
+ parser.add_argument("--tile_h", type=int, default=30)
917
+ parser.add_argument("--tile_w", type=int, default=52)
918
+ parser.add_argument("--tile_stride_h", type=int, default=15)
919
+ parser.add_argument("--tile_stride_w", type=int, default=26)
920
+ parser.add_argument("--seed", type=int, default=42)
921
+ args = parser.parse_args()
922
+ if args.model_paths is None:
923
+ args.model_paths = default_model_paths(args.base_model_dir)
924
+ return args
925
+
926
+
927
+ if __name__ == "__main__":
928
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
929
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ ARGS=(
13
+ diffsynth/bridge/wan_bridge/model_training/train_sr.py
14
+ --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" \
15
+ --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" \
16
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
17
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
18
+ --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr}" \
19
+ --height "${HEIGHT:-480}" \
20
+ --width "${WIDTH:-832}" \
21
+ --num_frames "${NUM_FRAMES:-81}" \
22
+ --sr_scale "${SR_SCALE:-2}" \
23
+ --source_mode "${SOURCE_MODE:-upsampler}" \
24
+ --ultraflash_dir "${ULTRAFLASH_DIR:-/home/ma-user/workspace/rongxiang/UltraFlash/inference}" \
25
+ --ultraflash_sr_config "${ULTRAFLASH_SR_CONFIG:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py}" \
26
+ --latent_upsampler_ckpt "${LATENT_UPSAMPLER_CKPT:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth}" \
27
+ --upsampler_dtype "${UPSAMPLER_DTYPE:-bf16}" \
28
+ --dataset_repeat "${DATASET_REPEAT:-1}" \
29
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \
30
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
31
+ --learning_rate "${LEARNING_RATE:-1.0}" \
32
+ --weight_decay "${WEIGHT_DECAY:-0.01}" \
33
+ --d_coef "${D_COEF:-1.0}" \
34
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \
35
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
36
+ --lpips_net "${LPIPS_NET:-vgg}" \
37
+ --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \
38
+ --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \
39
+ --ssim_weight "${SSIM_WEIGHT:-1.0}" \
40
+ --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \
41
+ --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \
42
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \
43
+ --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-50.0}" \
44
+ --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \
45
+ --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \
46
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-8}" \
47
+ --noise_sigma "${NOISE_SIGMA:-1.0}" \
48
+ --val_interval "${VAL_INTERVAL:-100}" \
49
+ --val_batches "${VAL_BATCHES:-1}" \
50
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-1}" \
51
+ --save_steps "${SAVE_STEPS:-500}" \
52
+ --validate_at_start
53
+ )
54
+
55
+ if [[ -n "${LIMIT_VIDEOS:-}" ]]; then
56
+ ARGS+=(--limit_videos "${LIMIT_VIDEOS}")
57
+ fi
58
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
59
+ ARGS+=(--output_path "${OUTPUT_PATH}")
60
+ fi
61
+
62
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ ARGS=(
13
+ diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py
14
+ --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}" \
15
+ --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}" \
16
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
17
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
18
+ --output_root "${OUTPUT_ROOT:-/cache/outputs2_bridge_wan_srfirst}" \
19
+ --height "${HEIGHT:-480}" \
20
+ --width "${WIDTH:-832}" \
21
+ --num_frames "${NUM_FRAMES:-81}" \
22
+ --sr_scale "${SR_SCALE:-2}" \
23
+ --dataset_repeat "${DATASET_REPEAT:-1}" \
24
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \
25
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
26
+ --learning_rate "${LEARNING_RATE:-1.0}" \
27
+ --weight_decay "${WEIGHT_DECAY:-0.01}" \
28
+ --d_coef "${D_COEF:-1.0}" \
29
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \
30
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
31
+ --lpips_net "${LPIPS_NET:-vgg}" \
32
+ --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \
33
+ --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \
34
+ --ssim_weight "${SSIM_WEIGHT:-1.0}" \
35
+ --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \
36
+ --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \
37
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \
38
+ --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-0.0}" \
39
+ --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \
40
+ --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \
41
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-2}" \
42
+ --noise_sigma "${NOISE_SIGMA:-1.0}" \
43
+ --val_interval "${VAL_INTERVAL:-100}" \
44
+ --val_batches "${VAL_BATCHES:-1}" \
45
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-10}" \
46
+ --save_steps "${SAVE_STEPS:-500}" \
47
+ --validate_at_start \
48
+ --no-anchor_each_step
49
+ )
50
+
51
+ if [[ -n "${LIMIT_VIDEOS:-}" ]]; then
52
+ ARGS+=(--limit_videos "${LIMIT_VIDEOS}")
53
+ fi
54
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
55
+ ARGS+=(--output_path "${OUTPUT_PATH}")
56
+ fi
57
+ if [[ "${ANCHOR_EACH_STEP:-1}" == "0" || "${ANCHOR_EACH_STEP:-1}" == "false" ]]; then
58
+ ARGS+=(--no-anchor_each_step)
59
+ else
60
+ ARGS+=(--anchor_each_step)
61
+ fi
62
+
63
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_1k_firstframe_anchor_flashvsr.sh ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ FLASHVSR_DIT="${FLASHVSR_DIT:-/cache/FlashVSR-v1.1/diffusion_pytorch_model_streaming_dmd.safetensors}"
13
+ WAN_MODEL_DIR="${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}"
14
+ MODEL_PATHS_DEFAULT="${FLASHVSR_DIT},${WAN_MODEL_DIR}/models_t5_umt5-xxl-enc-bf16.pth,${WAN_MODEL_DIR}/Wan2.1_VAE.pth"
15
+
16
+ ARGS=(
17
+ diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py
18
+ --base_model_dir "${WAN_MODEL_DIR}" \
19
+ --model_paths "${MODEL_PATHS:-${MODEL_PATHS_DEFAULT}}" \
20
+ --tokenizer_path "${TOKENIZER_PATH:-${WAN_MODEL_DIR}/google/umt5-xxl}" \
21
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
22
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
23
+ --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_flashvsr_ffanchor}" \
24
+ --height "${HEIGHT:-480}" \
25
+ --width "${WIDTH:-832}" \
26
+ --num_frames "${NUM_FRAMES:-81}" \
27
+ --sr_scale "${SR_SCALE:-2}" \
28
+ --dataset_repeat "${DATASET_REPEAT:-1}" \
29
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \
30
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
31
+ --learning_rate "${LEARNING_RATE:-1.0}" \
32
+ --weight_decay "${WEIGHT_DECAY:-0.01}" \
33
+ --d_coef "${D_COEF:-1.0}" \
34
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \
35
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
36
+ --lpips_net "${LPIPS_NET:-vgg}" \
37
+ --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \
38
+ --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \
39
+ --ssim_weight "${SSIM_WEIGHT:-1.0}" \
40
+ --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \
41
+ --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \
42
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \
43
+ --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-50.0}" \
44
+ --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \
45
+ --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \
46
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-8}" \
47
+ --noise_sigma "${NOISE_SIGMA:-1.0}" \
48
+ --val_interval "${VAL_INTERVAL:-100}" \
49
+ --val_batches "${VAL_BATCHES:-1}" \
50
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-1}" \
51
+ --save_steps "${SAVE_STEPS:-500}" \
52
+ --validate_at_start
53
+ )
54
+
55
+ if [[ -n "${LIMIT_VIDEOS:-}" ]]; then
56
+ ARGS+=(--limit_videos "${LIMIT_VIDEOS}")
57
+ fi
58
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
59
+ ARGS+=(--output_path "${OUTPUT_PATH}")
60
+ fi
61
+ if [[ "${ANCHOR_EACH_STEP:-1}" == "0" || "${ANCHOR_EACH_STEP:-1}" == "false" ]]; then
62
+ ARGS+=(--no-anchor_each_step)
63
+ else
64
+ ARGS+=(--anchor_each_step)
65
+ fi
66
+
67
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_firstframe_anchor.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train Wan Bridge SR with bicubic source video and first-frame latent anchoring.
2
+
3
+ This keeps the Wan text prompt branch enabled, removes the UltraFlash latent
4
+ upsampler source branch, and follows the Wan2.2 TI2V-style strong anchor:
5
+ the first latent temporal index is replaced by the encoded HR reference frame
6
+ during training and after every validation sampling step.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import copy
13
+ import json
14
+ import os
15
+ import random
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from accelerate import Accelerator
21
+ from accelerate.utils import DistributedDataParallelKwargs
22
+ from PIL import Image
23
+ from torch.utils.data import DataLoader, Dataset
24
+ from tqdm import tqdm
25
+
26
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
27
+ SeedanceSRDataset,
28
+ crop_original_rgb_for_latent_crop,
29
+ crop_latent_pair_for_pixel_losses,
30
+ decode_latents_to_btchw_01,
31
+ default_model_paths,
32
+ lpips_video_loss,
33
+ pil_video_to_tensor_01,
34
+ tensor_btchw_01_to_pil,
35
+ wavelet_hf_loss,
36
+ )
37
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline
38
+ from diffsynth.data.video import save_video
39
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger
40
+ from diffsynth.utils import ModelConfig
41
+
42
+
43
+ def format_run_value(value: object) -> str:
44
+ text = f"{value:g}" if isinstance(value, float) else str(value)
45
+ return text.replace(".", "p").replace("-", "m").replace("/", "_")
46
+
47
+
48
+ def build_run_name(args) -> str:
49
+ parts = [
50
+ "wan_sr_ffanchor",
51
+ f"x{args.sr_scale}",
52
+ f"{args.height}x{args.width}",
53
+ f"f{args.num_frames}",
54
+ "bicubic",
55
+ "prompt",
56
+ "relock" if args.anchor_each_step else "initanchor",
57
+ f"lr{format_run_value(args.learning_rate)}",
58
+ f"noise{format_run_value(args.noise_sigma)}",
59
+ f"bridge{format_run_value(args.bridge_loss_weight)}",
60
+ f"lpips{format_run_value(args.lpips_weight)}",
61
+ f"ssim{format_run_value(args.ssim_weight)}",
62
+ f"wav{format_run_value(args.wavelet_hf_weight)}",
63
+ f"pix{format_run_value(args.pixel_loss_weight)}",
64
+ f"pcrop{args.pixel_loss_crop_size}",
65
+ f"plf{args.pixel_loss_latent_frames}",
66
+ f"seed{args.seed}",
67
+ ]
68
+ return "_".join(parts)
69
+
70
+
71
+ class FirstFrameAnchorSRDataset(SeedanceSRDataset):
72
+ """Bicubic-upsampled SR source whose first frame is replaced by HR reference."""
73
+
74
+ def __init__(self, *args, **kwargs) -> None:
75
+ kwargs["source_mode"] = "bicubic"
76
+ super().__init__(*args, **kwargs)
77
+
78
+ def __getitem__(self, idx: int) -> dict:
79
+ item = super().__getitem__(idx)
80
+ reference = item["video"][0].copy()
81
+ item["source_video"][0] = reference.copy()
82
+ item["reference_image"] = reference
83
+ return item
84
+
85
+
86
+ def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor:
87
+ if anchor is None:
88
+ return latents
89
+ if anchor.shape[2] != 1:
90
+ raise ValueError(f"first_frame_latents must have exactly one latent frame, got {tuple(anchor.shape)}")
91
+ if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]:
92
+ raise ValueError(
93
+ f"anchor shape {tuple(anchor.shape)} is incompatible with latents {tuple(latents.shape)}"
94
+ )
95
+ out = latents.clone()
96
+ out[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype)
97
+ return out
98
+
99
+
100
+ def drop_first_time_frame_btchw(video: torch.Tensor) -> torch.Tensor:
101
+ if video.shape[1] <= 1:
102
+ return video[:, :0]
103
+ return video[:, 1:]
104
+
105
+
106
+ def drop_first_time_frame_bcthw(latents: torch.Tensor) -> torch.Tensor:
107
+ if latents.shape[2] <= 1:
108
+ return latents[:, :, :0]
109
+ return latents[:, :, 1:]
110
+
111
+
112
+ def drop_global_first_frame_from_crop_btchw(video: torch.Tensor, crop_info: dict) -> torch.Tensor:
113
+ if int(crop_info.get("start_t", 0)) != 0:
114
+ return video
115
+ return drop_first_time_frame_btchw(video)
116
+
117
+
118
+ def mse_after_first_latent_frame(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
119
+ pred_main = drop_first_time_frame_bcthw(pred)
120
+ target_main = drop_first_time_frame_bcthw(target)
121
+ if pred_main.numel() == 0:
122
+ return pred.new_tensor(0.0)
123
+ return F.mse_loss(pred_main.float(), target_main.float())
124
+
125
+
126
+ def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor:
127
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
128
+ if min_t <= 0:
129
+ return pred_btchw_01.new_tensor(0.0)
130
+ pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float()
131
+ target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float()
132
+ channels = pred.shape[1]
133
+ window_size = max(1, int(window_size))
134
+ if window_size % 2 == 0:
135
+ window_size += 1
136
+ padding = window_size // 2
137
+ weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size)
138
+
139
+ mu_x = F.conv2d(pred, weight, padding=padding, groups=channels)
140
+ mu_y = F.conv2d(target, weight, padding=padding, groups=channels)
141
+ mu_x_sq = mu_x.square()
142
+ mu_y_sq = mu_y.square()
143
+ mu_xy = mu_x * mu_y
144
+
145
+ sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq
146
+ sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq
147
+ sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy
148
+
149
+ c1 = 0.01 ** 2
150
+ c2 = 0.03 ** 2
151
+ ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / (
152
+ (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8
153
+ )
154
+ return (1.0 - ssim.clamp(-1.0, 1.0)).mean()
155
+
156
+
157
+ class FirstFrameAnchorWanVideoSRBridgePipeline(WanVideoBridgePipeline):
158
+ def training_loss(self, **inputs):
159
+ max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps)
160
+ min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps)
161
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
162
+ timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device)
163
+ anchor_each_step = bool(inputs.get("anchor_each_step", True))
164
+
165
+ anchor = inputs.get("first_frame_latents")
166
+ x0 = replace_first_latent_frame(inputs["input_latents"], anchor)
167
+ x1 = replace_first_latent_frame(inputs["source_latents"], anchor)
168
+ noise = inputs["noise"]
169
+
170
+ xt = self.scheduler.add_noise(x0, x1, noise, timestep)
171
+ if anchor_each_step:
172
+ xt = replace_first_latent_frame(xt, anchor)
173
+
174
+ model_inputs = dict(inputs)
175
+ model_inputs["latents"] = xt
176
+ model_inputs["input_latents"] = x0
177
+ model_inputs["source_latents"] = x1
178
+ model_inputs.pop("first_frame_latents", None)
179
+
180
+ target = self.scheduler.training_target(x0, xt, timestep)
181
+ model_output = self.model_fn(**model_inputs, timestep=timestep)
182
+
183
+ if self.scheduler.target == "stabilized_drift":
184
+ sigma = self.scheduler.get_sigma(timestep)
185
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5
186
+ velocity_target = target / factor
187
+ velocity_for_endpoint = model_output * factor
188
+ elif self.scheduler.target == "drift":
189
+ velocity_target = target
190
+ velocity_for_endpoint = model_output
191
+ else:
192
+ raise ValueError("First-frame-anchor SR bridge training supports --target stabilized_drift or drift")
193
+
194
+ bridge_loss = (
195
+ mse_after_first_latent_frame(model_output, velocity_target)
196
+ if anchor_each_step
197
+ else F.mse_loss(model_output.float(), velocity_target.float())
198
+ )
199
+ total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss
200
+ metrics = {
201
+ "bridge_loss": float(bridge_loss.detach().cpu()),
202
+ "lpips_loss": 0.0,
203
+ "ssim_loss": 0.0,
204
+ "wavelet_hf_loss": 0.0,
205
+ "pixel_loss": 0.0,
206
+ }
207
+
208
+ lpips_model = inputs.get("lpips_model")
209
+ lpips_weight = float(inputs.get("lpips_weight", 0.0))
210
+ ssim_weight = float(inputs.get("ssim_weight", 0.0))
211
+ wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0))
212
+ pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0))
213
+ if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0:
214
+ sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
215
+ endpoint_pred = xt.float() - sigma * velocity_for_endpoint.float()
216
+ if bool(inputs.get("anchor_each_step", True)):
217
+ endpoint_pred = replace_first_latent_frame(endpoint_pred, anchor)
218
+ endpoint_pred, _, crop_info = crop_latent_pair_for_pixel_losses(
219
+ endpoint_pred,
220
+ x0.detach(),
221
+ crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 256)),
222
+ latent_frames=int(inputs.get("pixel_loss_latent_frames", 3)),
223
+ vae_factor=int(getattr(self.vae, "upsampling_factor", 8)),
224
+ return_crop_info=True,
225
+ )
226
+ pred_video = decode_latents_to_btchw_01(
227
+ self,
228
+ endpoint_pred,
229
+ tiled=bool(inputs.get("tiled", False)),
230
+ tile_size=inputs.get("tile_size", (30, 52)),
231
+ tile_stride=inputs.get("tile_stride", (15, 26)),
232
+ )
233
+ raw_target_video = inputs.get("raw_target_video")
234
+ if raw_target_video is None:
235
+ raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses")
236
+ target_video = crop_original_rgb_for_latent_crop(raw_target_video, crop_info, pred_video, self.device)
237
+ if anchor_each_step:
238
+ pred_video_main = drop_global_first_frame_from_crop_btchw(pred_video, crop_info)
239
+ target_video_main = drop_global_first_frame_from_crop_btchw(target_video, crop_info)
240
+ else:
241
+ pred_video_main = pred_video
242
+ target_video_main = target_video
243
+ if lpips_weight > 0:
244
+ if lpips_model is None:
245
+ raise ValueError("lpips_model is required when lpips_weight > 0")
246
+ if pred_video_main.shape[1] == 0:
247
+ loss = pred_video.new_tensor(0.0)
248
+ else:
249
+ loss = lpips_video_loss(
250
+ lpips_model,
251
+ pred_video_main,
252
+ target_video_main,
253
+ num_frames=int(inputs.get("lpips_num_frames", 4)),
254
+ crop_size=int(inputs.get("lpips_crop_size", 224)),
255
+ )
256
+ total_loss = total_loss + lpips_weight * loss
257
+ metrics["lpips_loss"] = float(loss.detach().cpu())
258
+ if ssim_weight > 0:
259
+ if pred_video_main.shape[1] == 0:
260
+ loss = pred_video.new_tensor(0.0)
261
+ else:
262
+ loss = ssim_video_loss(
263
+ pred_video_main,
264
+ target_video_main,
265
+ window_size=int(inputs.get("ssim_window_size", 11)),
266
+ )
267
+ total_loss = total_loss + ssim_weight * loss
268
+ metrics["ssim_loss"] = float(loss.detach().cpu())
269
+ if wavelet_hf_weight > 0:
270
+ if pred_video_main.shape[1] == 0:
271
+ loss = pred_video.new_tensor(0.0)
272
+ else:
273
+ loss = wavelet_hf_loss(
274
+ pred_video_main,
275
+ target_video_main,
276
+ levels=int(inputs.get("wavelet_hf_levels", 1)),
277
+ loss_type=str(inputs.get("wavelet_hf_loss", "l1")),
278
+ )
279
+ total_loss = total_loss + wavelet_hf_weight * loss
280
+ metrics["wavelet_hf_loss"] = float(loss.detach().cpu())
281
+ if pixel_loss_weight > 0:
282
+ if pred_video_main.shape[1] == 0:
283
+ loss = pred_video.new_tensor(0.0)
284
+ else:
285
+ loss = F.mse_loss(pred_video_main.float(), target_video_main.float())
286
+ total_loss = total_loss + pixel_loss_weight * loss
287
+ metrics["pixel_loss"] = float(loss.detach().cpu())
288
+
289
+ return total_loss, metrics
290
+
291
+
292
+ class FirstFrameAnchorSRTrainingModule(DiffusionTrainingModule):
293
+ def __init__(self, args):
294
+ super().__init__()
295
+ model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
296
+ self.pipe: FirstFrameAnchorWanVideoSRBridgePipeline = (
297
+ FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained(
298
+ torch_dtype=torch.bfloat16,
299
+ device="cpu",
300
+ model_configs=model_configs,
301
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
302
+ )
303
+ )
304
+ self.pipe.latent_upsampler = None
305
+ print("[FirstFrameAnchorSR] source=bicubic_upscale_with_hr_first_frame text=prompt anchor=strong")
306
+ self.switch_pipe_to_training_mode(
307
+ self.pipe,
308
+ args.trainable_models,
309
+ args.lora_base_model,
310
+ args.lora_target_modules,
311
+ args.lora_rank,
312
+ lora_checkpoint=args.lora_checkpoint,
313
+ enable_fp8_training=False,
314
+ )
315
+ self.args = args
316
+ if args.lpips_weight > 0 or args.val_lpips:
317
+ import lpips
318
+
319
+ self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False)
320
+ else:
321
+ self.lpips_model = None
322
+
323
+ def to(self, *args, **kwargs):
324
+ super().to(*args, **kwargs)
325
+ if self.lpips_model is not None:
326
+ self.lpips_model.to(*args, **kwargs)
327
+ return self
328
+
329
+ def _encode_first_frame_anchor(self, reference_image: Image.Image) -> torch.Tensor:
330
+ self.pipe.load_models_to_device(["vae"])
331
+ reference_video = self.pipe.preprocess_video([reference_image])
332
+ anchor = self.pipe.vae.encode(
333
+ reference_video,
334
+ device=self.pipe.device,
335
+ tiled=self.args.tiled,
336
+ tile_size=(self.args.tile_h, self.args.tile_w),
337
+ tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w),
338
+ ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
339
+ if anchor.shape[2] != 1:
340
+ raise ValueError(f"Expected reference image to encode to one latent frame, got {tuple(anchor.shape)}")
341
+ return anchor
342
+
343
+ def forward_preprocess(self, data):
344
+ prompt = data["prompt"]
345
+ if random.random() < self.args.text_drop_probability:
346
+ prompt = " "
347
+ inputs_posi = {"prompt": prompt}
348
+ inputs_nega = {}
349
+ inputs_shared = {
350
+ "input_video": data["video"],
351
+ "source_video": data["source_video"],
352
+ "height": data["video"][0].size[1],
353
+ "width": data["video"][0].size[0],
354
+ "num_frames": len(data["video"]),
355
+ "cfg_scale": 1,
356
+ "tiled": self.args.tiled,
357
+ "tile_size": (self.args.tile_h, self.args.tile_w),
358
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
359
+ "rand_device": self.pipe.device,
360
+ "seed": None,
361
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
362
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
363
+ "cfg_merge": False,
364
+ "vace_scale": 1,
365
+ "anchor_each_step": self.args.anchor_each_step,
366
+ "max_timestep_boundary": self.args.max_timestep_boundary,
367
+ "min_timestep_boundary": self.args.min_timestep_boundary,
368
+ "bridge_loss_weight": self.args.bridge_loss_weight,
369
+ "lpips_weight": self.args.lpips_weight,
370
+ "lpips_model": self.lpips_model,
371
+ "lpips_num_frames": self.args.lpips_num_frames,
372
+ "lpips_crop_size": self.args.lpips_crop_size,
373
+ "ssim_weight": self.args.ssim_weight,
374
+ "ssim_window_size": self.args.ssim_window_size,
375
+ "pixel_loss_crop_size": self.args.pixel_loss_crop_size,
376
+ "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames,
377
+ "wavelet_hf_weight": self.args.wavelet_hf_weight,
378
+ "wavelet_hf_levels": self.args.wavelet_hf_levels,
379
+ "wavelet_hf_loss": self.args.wavelet_hf_loss,
380
+ "pixel_loss_weight": self.args.pixel_loss_weight,
381
+ }
382
+ for unit in self.pipe.units:
383
+ inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(
384
+ unit, self.pipe, inputs_shared, inputs_posi, inputs_nega
385
+ )
386
+ inputs_shared["first_frame_latents"] = self._encode_first_frame_anchor(data["reference_image"])
387
+ inputs_shared["raw_target_video"] = data["video"]
388
+ return {**inputs_shared, **inputs_posi}
389
+
390
+ def forward(self, data, inputs=None):
391
+ if inputs is None:
392
+ inputs = self.forward_preprocess(data)
393
+ return self.pipe.training_loss(
394
+ **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models},
395
+ **inputs,
396
+ )
397
+
398
+
399
+ class FirstFrameAnchorModelLogger(ModelLogger):
400
+ def on_step_end(self, accelerator, model, save_steps=None):
401
+ super().on_step_end(accelerator, model, save_steps)
402
+
403
+
404
+ @torch.no_grad()
405
+ def validate(args, accelerator: Accelerator, model: FirstFrameAnchorSRTrainingModule, dataset: Dataset, step: int) -> dict:
406
+ if not accelerator.is_main_process:
407
+ return {}
408
+ module = accelerator.unwrap_model(model)
409
+ pipe = module.pipe
410
+ pipe.eval()
411
+ backup_scheduler = pipe.scheduler
412
+ pipe.scheduler = copy.deepcopy(backup_scheduler)
413
+ pipe.scheduler.noise_scale = args.val_sampling_noise_scale
414
+ pipe.scheduler.target = args.target
415
+
416
+ rows = []
417
+ out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}"
418
+ out_dir.mkdir(parents=True, exist_ok=True)
419
+ for idx in range(min(args.val_batches, len(dataset))):
420
+ data = dataset[idx]
421
+ pipe.scheduler.set_timesteps(1000, training=True)
422
+ inputs = module.forward_preprocess(data)
423
+ pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift)
424
+ x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"])
425
+ x1 = replace_first_latent_frame(inputs["source_latents"], inputs["first_frame_latents"])
426
+ latents = x1.clone()
427
+ pipe.load_models_to_device(pipe.in_iteration_models)
428
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
429
+ model_inputs = dict(inputs)
430
+ model_inputs.pop("latents", None)
431
+ model_inputs.pop("first_frame_latents", None)
432
+ model_inputs["input_latents"] = x0
433
+ model_inputs["source_latents"] = x1
434
+ for timestep_cpu in pipe.scheduler.timesteps:
435
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
436
+ pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep)
437
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, x1)
438
+ if args.anchor_each_step:
439
+ latents = replace_first_latent_frame(latents, inputs["first_frame_latents"])
440
+
441
+ pred_video = decode_latents_to_btchw_01(
442
+ pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)
443
+ )
444
+ target_video = decode_latents_to_btchw_01(
445
+ pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)
446
+ )
447
+ if args.anchor_each_step:
448
+ pred_video_main = drop_first_time_frame_btchw(pred_video)
449
+ target_video_main = drop_first_time_frame_btchw(target_video)
450
+ else:
451
+ pred_video_main = pred_video
452
+ target_video_main = target_video
453
+ source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0)
454
+ target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0)
455
+ min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1])
456
+ strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1)
457
+ save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5)
458
+ 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)
459
+ data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png")
460
+
461
+ row = {
462
+ "idx": idx,
463
+ "latent_mse": (
464
+ mse_after_first_latent_frame(latents, x0).item()
465
+ if args.anchor_each_step
466
+ else F.mse_loss(latents.float(), x0.float()).item()
467
+ ),
468
+ "pixel_mse": (
469
+ F.mse_loss(pred_video_main.float(), target_video_main.float()).item()
470
+ if pred_video_main.shape[1] > 0
471
+ else 0.0
472
+ ),
473
+ "anchor_latent_mse": F.mse_loss(
474
+ latents[:, :, :1].float(), inputs["first_frame_latents"].float()
475
+ ).item(),
476
+ }
477
+ if module.lpips_model is not None and args.val_lpips:
478
+ row["lpips"] = float(
479
+ lpips_video_loss(
480
+ module.lpips_model,
481
+ pred_video_main,
482
+ target_video_main,
483
+ args.lpips_num_frames,
484
+ args.lpips_crop_size,
485
+ ).detach().cpu()
486
+ ) if pred_video_main.shape[1] > 0 else 0.0
487
+ if args.val_ssim or args.ssim_weight > 0:
488
+ row["ssim"] = float(
489
+ ssim_video_loss(pred_video_main, target_video_main, args.ssim_window_size).detach().cpu()
490
+ ) if pred_video_main.shape[1] > 0 else 0.0
491
+ if args.val_wavelet_hf_loss:
492
+ row["wavelet_hf"] = float(
493
+ wavelet_hf_loss(pred_video_main, target_video_main, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu()
494
+ ) if pred_video_main.shape[1] > 0 else 0.0
495
+ rows.append(row)
496
+
497
+ pipe.scheduler = backup_scheduler
498
+ metrics = {}
499
+ if rows:
500
+ for key in rows[0]:
501
+ if key != "idx":
502
+ metrics[f"val_{key}"] = float(
503
+ sum(row[key] for row in rows if key in row) / max(sum(1 for row in rows if key in row), 1)
504
+ )
505
+ (out_dir / "metrics.json").write_text(
506
+ json.dumps(
507
+ {
508
+ "step": step,
509
+ "rows": rows,
510
+ "metrics": metrics,
511
+ "pipeline": "bicubic_source_hr_first_frame_strong_latent_anchor_with_prompt",
512
+ "anchor_each_step": args.anchor_each_step,
513
+ },
514
+ indent=2,
515
+ ),
516
+ encoding="utf-8",
517
+ )
518
+ print(f"[Validation step {step}] {metrics}")
519
+ pipe.train()
520
+ return metrics
521
+
522
+
523
+ def build_dataset(args, repeat: int, limit_videos: int | None, seed: int) -> FirstFrameAnchorSRDataset:
524
+ return FirstFrameAnchorSRDataset(
525
+ args.video_dir,
526
+ args.prompt_json,
527
+ args.prompt_field,
528
+ args.default_prompt,
529
+ args.height,
530
+ args.width,
531
+ args.num_frames,
532
+ args.sr_scale,
533
+ repeat=repeat,
534
+ limit_videos=limit_videos,
535
+ seed=seed,
536
+ )
537
+
538
+
539
+ def train(args):
540
+ save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None
541
+ if args.output_path is None:
542
+ args.output_path = str(Path(args.output_root) / build_run_name(args))
543
+ train_set = build_dataset(
544
+ args,
545
+ repeat=args.dataset_repeat,
546
+ limit_videos=args.limit_videos,
547
+ seed=args.seed,
548
+ )
549
+ val_set = build_dataset(
550
+ args,
551
+ repeat=1,
552
+ limit_videos=max(args.val_batches, 1),
553
+ seed=args.seed + 1,
554
+ )
555
+ model = FirstFrameAnchorSRTrainingModule(args)
556
+ model.pipe.scheduler.noise_scale = args.noise_sigma
557
+ model.pipe.scheduler.bridge_type = "brownian"
558
+ model.pipe.scheduler.training_weight_type = args.training_weight_type
559
+ model.pipe.scheduler.target = args.target
560
+ print("Scheduler noise scale:", model.pipe.scheduler.noise_scale)
561
+ print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type)
562
+ print("Scheduler target:", model.pipe.scheduler.target)
563
+
564
+ accelerator = Accelerator(
565
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
566
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
567
+ )
568
+ if accelerator.is_main_process:
569
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
570
+ (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
571
+ print(f"[Output] {args.output_path}")
572
+
573
+ if args.validation_only or args.max_train_steps <= 0:
574
+ model = accelerator.prepare(model)
575
+ validate(args, accelerator, model, val_set, 0)
576
+ return
577
+
578
+ from prodigyopt import Prodigy
579
+
580
+ optimizer = Prodigy(
581
+ model.trainable_modules(),
582
+ lr=args.learning_rate,
583
+ weight_decay=args.weight_decay,
584
+ safeguard_warmup=True,
585
+ d_coef=args.d_coef,
586
+ )
587
+ dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers)
588
+ model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
589
+ logger = FirstFrameAnchorModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt)
590
+ if args.validate_at_start:
591
+ validate(args, accelerator, model, val_set, 0)
592
+
593
+ global_step = 0
594
+ while global_step < args.max_train_steps:
595
+ for data in tqdm(dataloader, disable=not accelerator.is_local_main_process):
596
+ with accelerator.accumulate(model):
597
+ optimizer.zero_grad()
598
+ loss, metrics = model(data)
599
+ accelerator.backward(loss)
600
+ if args.max_grad_norm > 0:
601
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
602
+ optimizer.step()
603
+ global_step += 1
604
+ gathered_loss = accelerator.gather(loss.detach()).mean().item()
605
+ if accelerator.is_main_process and global_step % args.log_interval == 0:
606
+ print(
607
+ f"[Train step {global_step}] loss={gathered_loss:.6f} "
608
+ f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} "
609
+ f"ssim={metrics['ssim_loss']:.6f} "
610
+ f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}"
611
+ )
612
+ logger.on_step_end(accelerator, model, save_steps)
613
+ if args.val_interval > 0 and global_step % args.val_interval == 0:
614
+ validate(args, accelerator, model, val_set, global_step)
615
+ if global_step >= args.max_train_steps:
616
+ break
617
+ logger.on_training_end(accelerator, model, save_steps)
618
+
619
+
620
+ def parse_args():
621
+ parser = argparse.ArgumentParser(
622
+ description="Train Wan2.1 Bridge SR with bicubic source video, prompt text, and strong first-frame latent anchoring."
623
+ )
624
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
625
+ parser.add_argument("--model_paths", default=None)
626
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
627
+ parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
628
+ parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
629
+ parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p")
630
+ parser.add_argument("--default_prompt", default="")
631
+ parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr")
632
+ parser.add_argument("--output_path", default=None)
633
+ parser.add_argument("--height", type=int, default=480)
634
+ parser.add_argument("--width", type=int, default=832)
635
+ parser.add_argument("--num_frames", type=int, default=81)
636
+ parser.add_argument("--sr_scale", type=int, default=2)
637
+ parser.add_argument("--fps", type=int, default=16)
638
+ parser.add_argument("--limit_videos", type=int, default=None)
639
+ parser.add_argument("--dataset_repeat", type=int, default=1)
640
+ parser.add_argument("--dataset_num_workers", type=int, default=0)
641
+ parser.add_argument("--trainable_models", default="dit")
642
+ parser.add_argument("--lora_base_model", default=None)
643
+ parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2")
644
+ parser.add_argument("--lora_rank", type=int, default=32)
645
+ parser.add_argument("--lora_checkpoint", default=None)
646
+ parser.add_argument("--learning_rate", type=float, default=1.0)
647
+ parser.add_argument("--weight_decay", type=float, default=0.01)
648
+ parser.add_argument("--d_coef", type=float, default=1.0)
649
+ parser.add_argument("--max_train_steps", type=int, default=5000)
650
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
651
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
652
+ parser.add_argument("--save_steps", type=int, default=500)
653
+ parser.add_argument("--log_interval", type=int, default=1)
654
+ parser.add_argument("--val_interval", type=int, default=100)
655
+ parser.add_argument("--val_batches", type=int, default=1)
656
+ parser.add_argument("--validate_at_start", action="store_true", default=False)
657
+ parser.add_argument("--validation_only", action="store_true", default=False)
658
+ parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.")
659
+ parser.add_argument("--noise_sigma", type=float, default=1.0)
660
+ parser.add_argument("--training_weight_type", default="uniform")
661
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
662
+ parser.add_argument("--bridge_loss_weight", type=float, default=1.0)
663
+ parser.add_argument("--lpips_weight", type=float, default=1.0)
664
+ parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg")
665
+ parser.add_argument("--lpips_num_frames", type=int, default=4)
666
+ parser.add_argument("--lpips_crop_size", type=int, default=400)
667
+ parser.add_argument("--ssim_weight", type=float, default=0.0)
668
+ parser.add_argument("--ssim_window_size", type=int, default=11)
669
+ parser.add_argument("--val_ssim", action="store_true", default=False)
670
+ parser.add_argument("--pixel_loss_crop_size", type=int, default=400)
671
+ parser.add_argument("--pixel_loss_latent_frames", type=int, default=3)
672
+ parser.add_argument("--val_lpips", action="store_true", default=False)
673
+ parser.add_argument("--wavelet_hf_weight", type=float, default=50.0)
674
+ parser.add_argument("--wavelet_hf_levels", type=int, default=1)
675
+ parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1")
676
+ parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False)
677
+ parser.add_argument("--pixel_loss_weight", type=float, default=8.0)
678
+ parser.add_argument("--val_inference_steps", type=int, default=1)
679
+ parser.add_argument("--val_sampling_noise_scale", type=float, default=1.0)
680
+ parser.add_argument("--val_sigma_shift", type=float, default=5.0)
681
+ parser.add_argument("--max_timestep_boundary", type=float, default=0.9999)
682
+ parser.add_argument("--min_timestep_boundary", type=float, default=0.0001)
683
+ parser.add_argument("--text_drop_probability", type=float, default=0.0)
684
+ parser.add_argument(
685
+ "--anchor_each_step",
686
+ action=argparse.BooleanOptionalAction,
687
+ default=True,
688
+ help="Re-lock latent frame 0 to the reference for RGB endpoint prediction and after validation denoise steps. Disable to anchor only at initialization.",
689
+ )
690
+ parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True)
691
+ parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False)
692
+ parser.add_argument("--find_unused_parameters", action="store_true", default=False)
693
+ parser.add_argument("--tiled", action="store_true", default=False)
694
+ parser.add_argument("--tile_h", type=int, default=30)
695
+ parser.add_argument("--tile_w", type=int, default=52)
696
+ parser.add_argument("--tile_stride_h", type=int, default=15)
697
+ parser.add_argument("--tile_stride_w", type=int, default=26)
698
+ parser.add_argument("--seed", type=int, default=42)
699
+ args = parser.parse_args()
700
+ if args.model_paths is None:
701
+ args.model_paths = default_model_paths(args.base_model_dir)
702
+ return args
703
+
704
+
705
+ if __name__ == "__main__":
706
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
707
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage-2 training for a reference-aware Wan Brownian-Bridge SR adapter.
2
+
3
+ Only the state-aware adapters are optimized. The Wan backbone, the trained
4
+ Brownian-Bridge SR checkpoint, VAE, text encoder, and UltraFlash latent
5
+ upsampler remain frozen.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import copy
12
+ import json
13
+ import os
14
+ import random
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import imageio
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from accelerate import Accelerator
23
+ from accelerate.utils import DistributedDataParallelKwargs
24
+ from safetensors.torch import load_file
25
+ from PIL import Image
26
+ from torch.utils.data import DataLoader, Dataset
27
+ from tqdm import tqdm
28
+
29
+ REPO_ROOT = Path(__file__).resolve().parents[4]
30
+ if str(REPO_ROOT) not in sys.path:
31
+ sys.path.insert(0, str(REPO_ROOT))
32
+
33
+ from diffsynth.bridge.wan_bridge.model_training.reference_adapter import (
34
+ install_reference_adapters,
35
+ parse_block_ids,
36
+ prepare_reference_condition,
37
+ reference_blocks,
38
+ set_reference_adapters_enabled,
39
+ )
40
+ from diffsynth.bridge.wan_bridge.model_training.sobel_utils import (
41
+ dilated_sobel_edge_mask,
42
+ sobel_rgb_gradients,
43
+ )
44
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
45
+ SeedanceSRDataset,
46
+ WanVideoSRBridgePipeline,
47
+ WanVideoSRUnit_UltraFlashLatentUpsampler,
48
+ center_crop_resize,
49
+ crop_original_rgb_for_latent_crop,
50
+ crop_latent_pair_for_pixel_losses,
51
+ decode_latents_to_btchw_01,
52
+ default_model_paths,
53
+ load_ultraflash_latent_upsampler,
54
+ lpips_video_loss,
55
+ pil_video_to_tensor_01,
56
+ tensor_btchw_01_to_pil,
57
+ wavelet_hf_loss,
58
+ )
59
+ from diffsynth.data.video import save_video
60
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger
61
+ from diffsynth.utils import ModelConfig
62
+
63
+
64
+ def _run_value(value: object) -> str:
65
+ text = f"{value:g}" if isinstance(value, float) else str(value)
66
+ return text.replace(".", "p").replace("-", "m").replace("/", "_").replace(",", "-")
67
+
68
+
69
+ def build_reference_run_name(args) -> str:
70
+ """Deterministic experiment directory name from all result-defining knobs."""
71
+ parts = [
72
+ f"ref_{args.reference_mode}",
73
+ "onestep",
74
+ "onewaycross2d_reszero",
75
+ f"wv{args.wavelet_value_mode}",
76
+ f"wb{_run_value(args.wavelet_energy_bias)}-c{_run_value(args.wavelet_energy_clip)}",
77
+ f"x{args.sr_scale}",
78
+ f"{args.height}x{args.width}",
79
+ f"f{args.num_frames}",
80
+ args.source_mode,
81
+ f"blocks{_run_value(args.adapter_blocks)}",
82
+ f"d{args.adapter_dim}",
83
+ f"h{args.adapter_heads}",
84
+ f"l1{_run_value(args.pixel_l1_weight)}",
85
+ f"hf{_run_value(args.hf_weight)}-{args.hf_loss_type}{args.hf_levels}",
86
+ f"sobel{_run_value(args.sobel_edge_weight)}-d{args.sobel_edge_dilation_radius}-thr{_run_value(args.sobel_edge_threshold)}",
87
+ f"lpips{_run_value(args.lpips_weight)}",
88
+ f"crop{args.loss_crop_size}",
89
+ f"lf{args.loss_latent_frames}",
90
+ f"lr{_run_value(args.learning_rate)}",
91
+ f"seed{args.seed}",
92
+ ]
93
+ return "_".join(parts)
94
+
95
+
96
+ class FirstFrameReferenceSRDataset(SeedanceSRDataset):
97
+ """Video SR samples whose identity reference is absolute video frame zero."""
98
+
99
+ def _read_reference_image(self, path: Path) -> Image.Image:
100
+ reader = imageio.get_reader(str(path))
101
+ try:
102
+ frame = reader.get_data(0)
103
+ finally:
104
+ reader.close()
105
+ image = Image.fromarray(np.asarray(frame)).convert("RGB")
106
+ return center_crop_resize(image, self.height, self.width)
107
+
108
+ def __getitem__(self, idx: int) -> dict:
109
+ item = super().__getitem__(idx)
110
+ item["reference_image"] = self._read_reference_image(Path(item["path"]))
111
+ return item
112
+
113
+
114
+ def sobel_edge_loss(
115
+ pred_btchw_01: torch.Tensor,
116
+ target_btchw_01: torch.Tensor,
117
+ dilation_radius: int = 2,
118
+ threshold_multiplier: float = 1.0,
119
+ ) -> torch.Tensor:
120
+ """Sobel-L1 inside a target-edge mask dilated into a learnable band."""
121
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
122
+ pred_x, pred_y = sobel_rgb_gradients(pred_btchw_01[:, :min_t])
123
+ target_x, target_y = sobel_rgb_gradients(target_btchw_01[:, :min_t])
124
+ channels = pred_x.shape[1]
125
+
126
+ with torch.no_grad():
127
+ _, _, _, edge_mask = dilated_sobel_edge_mask(
128
+ target_x, target_y, dilation_radius, threshold_multiplier
129
+ )
130
+ directional_error = (pred_x - target_x).abs() + (pred_y - target_y).abs()
131
+ denominator = edge_mask.sum().clamp_min(1.0) * channels
132
+ return 0.5 * (directional_error * edge_mask).sum() / denominator
133
+
134
+
135
+ def load_bridge_checkpoint(pipe: WanVideoSRBridgePipeline, checkpoint: str) -> None:
136
+ state_dict = load_file(checkpoint, device="cpu")
137
+ prefixes = ("pipe.dit.", "dit.", "module.", "module.dit.", "model.", "model.dit.")
138
+ candidates = [("raw", state_dict)]
139
+ for prefix in prefixes:
140
+ if any(key.startswith(prefix) for key in state_dict):
141
+ candidates.append(
142
+ (f"strip:{prefix}", {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state_dict.items()})
143
+ )
144
+ errors = []
145
+ for name, candidate in candidates:
146
+ try:
147
+ pipe.dit.load_state_dict(candidate, strict=True)
148
+ print(f"[ReferenceSR] loaded frozen Bridge checkpoint ({name}): {checkpoint}")
149
+ return
150
+ except Exception as exc:
151
+ errors.append(f"{name}: {exc}")
152
+ raise RuntimeError("Could not load Bridge checkpoint:\n" + "\n".join(errors))
153
+
154
+
155
+ def load_adapter_checkpoint(dit: torch.nn.Module, checkpoint: str) -> None:
156
+ state_dict = load_file(checkpoint, device="cpu")
157
+ for prefix in ("pipe.dit.", "dit.", "module.pipe.dit."):
158
+ if any(key.startswith(prefix) for key in state_dict):
159
+ state_dict = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state_dict.items()}
160
+ break
161
+ incompatible_markers = (
162
+ ".q_state.", ".q_source.", ".k_reference.", ".v_reference",
163
+ ".adapter.q_proj.", ".adapter.k_proj.", ".adapter.v_proj.",
164
+ ".adapter.target_q_proj.", ".adapter.reference_k_proj.",
165
+ ".adapter.reference_v_proj.", ".adapter.out_proj.",
166
+ ".adapter.pair_norm.", ".adapter.target_stream_embedding",
167
+ ".adapter.reference_stream_embedding",
168
+ )
169
+ if any(marker in key for key in state_dict for marker in incompatible_markers):
170
+ raise RuntimeError(
171
+ "This checkpoint belongs to an older reference-adapter architecture. "
172
+ "The one-way target-Q/reference-KV residual Adapter has different "
173
+ "parameters; start a new run or provide a onewaycross2d_reszero checkpoint."
174
+ )
175
+ result = dit.load_state_dict(state_dict, strict=False)
176
+ unexpected = [key for key in result.unexpected_keys if ".base_block." not in key]
177
+ if unexpected:
178
+ raise RuntimeError(f"Unexpected adapter checkpoint keys: {unexpected[:20]}")
179
+ missing_adapter = [key for key in result.missing_keys if ".adapter." in key]
180
+ if missing_adapter:
181
+ raise RuntimeError(
182
+ "Adapter checkpoint does not cover every configured Wan block. "
183
+ f"Missing {len(missing_adapter)} adapter tensors, for example: {missing_adapter[:10]}. "
184
+ "Use a checkpoint trained with the same --adapter_blocks setting."
185
+ )
186
+ loaded = [key for key in state_dict if ".adapter." in key]
187
+ if not loaded:
188
+ raise RuntimeError(f"No adapter keys found in {checkpoint}")
189
+ print(f"[ReferenceSR] resumed {len(loaded)} adapter tensors from {checkpoint}")
190
+
191
+
192
+ class ReferenceSRTrainingModule(DiffusionTrainingModule):
193
+ def __init__(self, args) -> None:
194
+ super().__init__()
195
+ model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
196
+ self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained(
197
+ torch_dtype=torch.bfloat16,
198
+ device="cpu",
199
+ model_configs=model_configs,
200
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
201
+ )
202
+ load_bridge_checkpoint(self.pipe, args.bridge_checkpoint)
203
+ if args.source_mode == "upsampler":
204
+ self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu")
205
+ self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()]
206
+ else:
207
+ self.pipe.latent_upsampler = None
208
+
209
+ self.pipe.requires_grad_(False)
210
+ block_ids = parse_block_ids(args.adapter_blocks, len(self.pipe.dit.blocks))
211
+ install_reference_adapters(
212
+ self.pipe.dit,
213
+ block_ids,
214
+ adapter_dim=args.adapter_dim,
215
+ adapter_heads=args.adapter_heads,
216
+ wavelet_value_mode=args.wavelet_value_mode,
217
+ wavelet_energy_bias=args.wavelet_energy_bias,
218
+ wavelet_energy_clip=args.wavelet_energy_clip,
219
+ )
220
+ for block in reference_blocks(self.pipe.dit):
221
+ block.adapter.to(dtype=self.pipe.torch_dtype)
222
+ if args.adapter_checkpoint:
223
+ load_adapter_checkpoint(self.pipe.dit, args.adapter_checkpoint)
224
+
225
+ # Strict one-step Bridge: sigma=1 source endpoint to sigma=0 target.
226
+ # The adapter itself has no timestep input.
227
+ self.pipe.scheduler.set_timesteps(1, training=True, shift=args.bridge_sigma_shift)
228
+ self.pipe.scheduler.noise_scale = 0.0
229
+ self.pipe.scheduler.bridge_type = "brownian"
230
+ self.pipe.scheduler.target = args.target
231
+ self.args = args
232
+
233
+ import lpips
234
+
235
+ self.lpips_model = lpips.LPIPS(net="vgg", verbose=False).eval().requires_grad_(False)
236
+ trainable = sum(param.numel() for param in self.parameters() if param.requires_grad)
237
+ total = sum(param.numel() for param in self.pipe.dit.parameters())
238
+ print(
239
+ f"[ReferenceSR] one-way target-Q/reference-KV + 2D RoPE + zero-init residual "
240
+ f"blocks={block_ids}; wavelet_V={args.wavelet_value_mode} "
241
+ f"energy_bias={args.wavelet_energy_bias:g}; "
242
+ f"trainable={trainable / 1e6:.2f}M / DiT={total / 1e9:.3f}B"
243
+ )
244
+
245
+ def to(self, *args, **kwargs):
246
+ super().to(*args, **kwargs)
247
+ self.lpips_model.to(*args, **kwargs)
248
+ return self
249
+
250
+ def forward_preprocess(self, data: dict, apply_text_dropout: bool = True) -> dict:
251
+ if self.args.reference_mode == "image":
252
+ # Temporary fixed conditioning for digital-human image animation.
253
+ prompt = "a person is speaking"
254
+ else:
255
+ prompt = data["prompt"]
256
+ if self.args.reference_mode != "image" and apply_text_dropout and random.random() < self.args.text_drop_probability:
257
+ prompt = " "
258
+ inputs_posi = {"prompt": prompt}
259
+ inputs_nega = {}
260
+ inputs_shared = {
261
+ "input_video": data["video"],
262
+ "source_video": data["source_video"],
263
+ "height": data["video"][0].size[1],
264
+ "width": data["video"][0].size[0],
265
+ "num_frames": len(data["video"]),
266
+ "cfg_scale": 1,
267
+ "tiled": self.args.tiled,
268
+ "tile_size": (self.args.tile_h, self.args.tile_w),
269
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
270
+ "rand_device": self.pipe.device,
271
+ "seed": None,
272
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
273
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
274
+ "cfg_merge": False,
275
+ "vace_scale": 1,
276
+ }
277
+ for unit in self.pipe.units:
278
+ inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(
279
+ unit, self.pipe, inputs_shared, inputs_posi, inputs_nega
280
+ )
281
+ if self.args.reference_mode == "image":
282
+ if "reference_image" not in data:
283
+ raise KeyError("image reference mode requires data['reference_image']")
284
+ self.pipe.load_models_to_device(["vae"])
285
+ reference_video = self.pipe.preprocess_video([data["reference_image"]])
286
+ with torch.no_grad():
287
+ reference_latents = self.pipe.vae.encode(
288
+ reference_video,
289
+ device=self.pipe.device,
290
+ tiled=self.args.tiled,
291
+ tile_size=(self.args.tile_h, self.args.tile_w),
292
+ tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w),
293
+ ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
294
+ if reference_latents.shape[2] != 1:
295
+ raise RuntimeError(
296
+ f"A single reference image must encode to one latent frame, got {reference_latents.shape[2]}"
297
+ )
298
+ inputs_shared["adapter_reference_latents"] = reference_latents
299
+ return {**inputs_shared, **inputs_posi}
300
+
301
+ def _endpoint_prediction(self, inputs: dict) -> tuple[torch.Tensor, torch.Tensor]:
302
+ x0 = inputs["input_latents"]
303
+ x1 = inputs["source_latents"]
304
+ timestep = self.pipe.scheduler.timesteps[0].unsqueeze(0).to(
305
+ dtype=self.pipe.torch_dtype, device=self.pipe.device
306
+ )
307
+ reference_latents = inputs.get("adapter_reference_latents", x0)
308
+ prepare_reference_condition(self.pipe.dit, x1.detach(), reference_latents.detach())
309
+ model_inputs = dict(inputs)
310
+ model_inputs.pop("latents", None)
311
+ model_inputs.pop("input_latents", None)
312
+ model_inputs.pop("adapter_reference_latents", None)
313
+ model_output = self.pipe.model_fn(
314
+ **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models},
315
+ **model_inputs,
316
+ latents=x1,
317
+ timestep=timestep,
318
+ )
319
+ # With one step sigma=1 and the final scheduler endpoint is sigma=0.
320
+ endpoint = self.pipe.scheduler.step(
321
+ model_output,
322
+ self.pipe.scheduler.timesteps[0],
323
+ x1,
324
+ x1,
325
+ )
326
+ return endpoint.float(), x0.detach()
327
+
328
+ def forward(self, data: dict, inputs: dict | None = None):
329
+ inputs = self.forward_preprocess(data) if inputs is None else inputs
330
+ endpoint, target = self._endpoint_prediction(inputs)
331
+ endpoint, target, crop_info = crop_latent_pair_for_pixel_losses(
332
+ endpoint,
333
+ target,
334
+ crop_size_pixels=self.args.loss_crop_size,
335
+ latent_frames=self.args.loss_latent_frames,
336
+ vae_factor=int(getattr(self.pipe.vae, "upsampling_factor", 8)),
337
+ return_crop_info=True,
338
+ )
339
+ pred_video = decode_latents_to_btchw_01(
340
+ self.pipe, endpoint, self.args.tiled, (self.args.tile_h, self.args.tile_w),
341
+ (self.args.tile_stride_h, self.args.tile_stride_w),
342
+ )
343
+ original_rgb = crop_original_rgb_for_latent_crop(
344
+ data["video"], crop_info, pred_video, self.pipe.device
345
+ )
346
+ # Exactly three objectives, all supervised by the on-disk original RGB crop.
347
+ pixel_l1 = F.l1_loss(pred_video.float(), original_rgb.float())
348
+ wavelet = wavelet_hf_loss(
349
+ pred_video, original_rgb, levels=self.args.hf_levels, loss_type=self.args.hf_loss_type
350
+ )
351
+ sobel = sobel_edge_loss(
352
+ pred_video,
353
+ original_rgb,
354
+ dilation_radius=self.args.sobel_edge_dilation_radius,
355
+ threshold_multiplier=self.args.sobel_edge_threshold,
356
+ )
357
+ high_frequency = wavelet + self.args.sobel_edge_weight * sobel
358
+ perceptual = lpips_video_loss(
359
+ self.lpips_model, pred_video, original_rgb,
360
+ num_frames=self.args.lpips_num_frames, crop_size=self.args.lpips_crop_size,
361
+ )
362
+ loss = (
363
+ self.args.pixel_l1_weight * pixel_l1
364
+ + self.args.hf_weight * high_frequency
365
+ + self.args.lpips_weight * perceptual
366
+ )
367
+ metrics = {
368
+ "pixel_l1": float(pixel_l1.detach().cpu()),
369
+ "high_frequency": float(high_frequency.detach().cpu()),
370
+ "wavelet": float(wavelet.detach().cpu()),
371
+ "sobel_edge": float(sobel.detach().cpu()),
372
+ "vgg_lpips": float(perceptual.detach().cpu()),
373
+ }
374
+ return loss, metrics
375
+
376
+
377
+ def _align_video(video: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
378
+ min_t = min(video.shape[1], target.shape[1])
379
+ video = video[:, :min_t]
380
+ if video.shape[-2:] != target.shape[-2:]:
381
+ b, t, c, h, w = video.shape
382
+ video = F.interpolate(
383
+ video.reshape(b * t, c, h, w), size=target.shape[-2:], mode="bicubic",
384
+ align_corners=False, antialias=True,
385
+ ).reshape(b, t, c, target.shape[-2], target.shape[-1])
386
+ return video.clamp(0, 1)
387
+
388
+
389
+ def _quality_metrics(module: ReferenceSRTrainingModule, pred: torch.Tensor, original: torch.Tensor) -> dict:
390
+ min_t = min(pred.shape[1], original.shape[1])
391
+ pred, original = pred[:, :min_t], original[:, :min_t]
392
+ mse = F.mse_loss(pred.float(), original.float())
393
+ return {
394
+ "mse_to_original": float(mse.cpu()),
395
+ "psnr_to_original": float((-10 * torch.log10(mse.clamp_min(1e-12))).cpu()),
396
+ "mean_abs_gap_to_original": float(F.l1_loss(pred.float(), original.float()).cpu()),
397
+ "high_frequency_gap": float(wavelet_hf_loss(pred, original, module.args.hf_levels, module.args.hf_loss_type).cpu()),
398
+ "sobel_edge_gap": float(sobel_edge_loss(
399
+ pred,
400
+ original,
401
+ module.args.sobel_edge_dilation_radius,
402
+ module.args.sobel_edge_threshold,
403
+ ).cpu()),
404
+ "vgg_lpips_gap": float(_deterministic_lpips(
405
+ module.lpips_model, pred, original, module.args.lpips_num_frames, module.args.lpips_crop_size
406
+ ).cpu()),
407
+ }
408
+
409
+
410
+ def _deterministic_lpips(lpips_model, pred: torch.Tensor, target: torch.Tensor, num_frames: int, crop_size: int) -> torch.Tensor:
411
+ """Validation-only LPIPS with the same temporal indices and center crop."""
412
+ min_t = min(pred.shape[1], target.shape[1])
413
+ pred, target = pred[:, :min_t], target[:, :min_t]
414
+ if num_frames > 0 and min_t > num_frames:
415
+ indices = torch.linspace(0, min_t - 1, steps=num_frames, device=pred.device).round().long()
416
+ pred, target = pred.index_select(1, indices), target.index_select(1, indices)
417
+ if crop_size > 0:
418
+ crop_h = min(crop_size, pred.shape[-2])
419
+ crop_w = min(crop_size, pred.shape[-1])
420
+ top = (pred.shape[-2] - crop_h) // 2
421
+ left = (pred.shape[-1] - crop_w) // 2
422
+ pred = pred[..., top:top + crop_h, left:left + crop_w]
423
+ target = target[..., top:top + crop_h, left:left + crop_w]
424
+ pred_frames = pred.reshape(-1, *pred.shape[2:]).mul(2).sub(1).clamp(-1, 1)
425
+ target_frames = target.reshape(-1, *target.shape[2:]).mul(2).sub(1).clamp(-1, 1)
426
+ return lpips_model(pred_frames.float(), target_frames.float()).mean()
427
+
428
+
429
+ @torch.no_grad()
430
+ def _sample(module: ReferenceSRTrainingModule, inputs: dict, enabled: bool) -> torch.Tensor:
431
+ pipe = module.pipe
432
+ x1 = inputs["source_latents"]
433
+ x0 = inputs["input_latents"]
434
+ latents = x1.clone()
435
+ set_reference_adapters_enabled(pipe.dit, enabled)
436
+ if enabled:
437
+ reference_latents = inputs.get("adapter_reference_latents", x0)
438
+ prepare_reference_condition(pipe.dit, x1, reference_latents)
439
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
440
+ model_inputs = dict(inputs)
441
+ model_inputs.pop("latents", None)
442
+ model_inputs.pop("input_latents", None)
443
+ model_inputs.pop("adapter_reference_latents", None)
444
+ model_inputs.pop("use_gradient_checkpointing", None)
445
+ model_inputs.pop("use_gradient_checkpointing_offload", None)
446
+ if len(pipe.scheduler.timesteps) != 1:
447
+ raise RuntimeError(f"Reference SR requires exactly one Bridge step, got {len(pipe.scheduler.timesteps)}")
448
+ timestep_cpu = pipe.scheduler.timesteps[0]
449
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
450
+ pred = pipe.model_fn(
451
+ **models,
452
+ **model_inputs,
453
+ latents=latents,
454
+ timestep=timestep,
455
+ use_gradient_checkpointing=False,
456
+ use_gradient_checkpointing_offload=False,
457
+ )
458
+ return pipe.scheduler.step(pred, timestep_cpu, latents, x1)
459
+
460
+
461
+ @torch.no_grad()
462
+ def validate(args, accelerator: Accelerator, model: ReferenceSRTrainingModule, dataset: Dataset, step: int) -> dict:
463
+ if not accelerator.is_main_process:
464
+ return {}
465
+ module = accelerator.unwrap_model(model)
466
+ pipe = module.pipe
467
+ pipe.eval()
468
+ scheduler_backup = pipe.scheduler
469
+ pipe.scheduler = copy.deepcopy(scheduler_backup)
470
+ pipe.scheduler.noise_scale = 0.0
471
+ pipe.scheduler.target = args.target
472
+ out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}"
473
+ out_dir.mkdir(parents=True, exist_ok=True)
474
+ rows = []
475
+ try:
476
+ for idx in range(min(args.val_batches, len(dataset))):
477
+ data = dataset[idx]
478
+ pipe.scheduler.set_timesteps(1, training=True, shift=args.bridge_sigma_shift)
479
+ inputs = module.forward_preprocess(data, apply_text_dropout=False)
480
+ pipe.load_models_to_device(pipe.in_iteration_models)
481
+ pipe.scheduler.set_timesteps(1, shift=args.bridge_sigma_shift)
482
+ base_latents = _sample(module, inputs, enabled=False)
483
+ pipe.scheduler.set_timesteps(1, shift=args.bridge_sigma_shift)
484
+ ref_latents = _sample(module, inputs, enabled=True)
485
+
486
+ ultraflash_video = decode_latents_to_btchw_01(
487
+ pipe, inputs["source_latents"], args.tiled,
488
+ (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w),
489
+ )
490
+ base_video = decode_latents_to_btchw_01(pipe, base_latents, args.tiled,
491
+ (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w))
492
+ ref_video = decode_latents_to_btchw_01(pipe, ref_latents, args.tiled,
493
+ (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w))
494
+ original = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0)
495
+ source = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0)
496
+ ultraflash_video = _align_video(ultraflash_video, original)
497
+ base_video = _align_video(base_video, original)
498
+ ref_video = _align_video(ref_video, original)
499
+ source = _align_video(source, original)
500
+ min_t = min(source.shape[1], ultraflash_video.shape[1], base_video.shape[1], ref_video.shape[1], original.shape[1])
501
+ original = original[:, :min_t]
502
+ source, ultraflash_video, base_video, ref_video = (
503
+ source[:, :min_t], ultraflash_video[:, :min_t],
504
+ base_video[:, :min_t], ref_video[:, :min_t],
505
+ )
506
+ diff = (ref_video - original).abs().mul(args.val_diff_amplification).clamp(0, 1)
507
+ comparison = torch.cat([source, ultraflash_video, base_video, ref_video, original, diff], dim=-1)
508
+ adapter_video_path = out_dir / f"val_{idx:03d}_adapter_output.mp4"
509
+ comparison_video_path = out_dir / f"val_{idx:03d}_lr_ultraflash_base_ref_original_diff.mp4"
510
+ reference_image_path = None
511
+ if "reference_image" in data:
512
+ reference_image_path = out_dir / f"val_{idx:03d}_input_reference.png"
513
+ data["reference_image"].save(reference_image_path)
514
+ save_video(
515
+ tensor_btchw_01_to_pil(ref_video[0]),
516
+ str(adapter_video_path),
517
+ fps=args.fps,
518
+ quality=5,
519
+ )
520
+ save_video(
521
+ tensor_btchw_01_to_pil(comparison[0]),
522
+ str(comparison_video_path),
523
+ fps=args.fps,
524
+ quality=5,
525
+ )
526
+
527
+ ultraflash_metrics = _quality_metrics(module, ultraflash_video, original)
528
+ base_metrics = _quality_metrics(module, base_video, original)
529
+ ref_metrics = _quality_metrics(module, ref_video, original)
530
+ rows.append({
531
+ "idx": idx,
532
+ "video": data["path"],
533
+ "artifacts": {
534
+ "adapter_output_video": adapter_video_path.name,
535
+ "comparison_video": comparison_video_path.name,
536
+ "input_reference_image": reference_image_path.name if reference_image_path else None,
537
+ },
538
+ "ultraflash": ultraflash_metrics,
539
+ "base": base_metrics,
540
+ "reference": ref_metrics,
541
+ "reference_minus_base": {key: ref_metrics[key] - base_metrics[key] for key in ref_metrics},
542
+ "psnr_gain_db": ref_metrics["psnr_to_original"] - base_metrics["psnr_to_original"],
543
+ })
544
+ finally:
545
+ set_reference_adapters_enabled(pipe.dit, True)
546
+ pipe.scheduler = scheduler_backup
547
+ pipe.train()
548
+
549
+ summary = {}
550
+ if rows:
551
+ for section in ("ultraflash", "base", "reference", "reference_minus_base"):
552
+ for key in rows[0][section]:
553
+ summary[f"{section}/{key}"] = sum(row[section][key] for row in rows) / len(rows)
554
+ summary["reference/psnr_gain_db"] = sum(row["psnr_gain_db"] for row in rows) / len(rows)
555
+ payload = {
556
+ "step": step,
557
+ "bridge_inference_steps": 1,
558
+ "bridge_sigma_shift": args.bridge_sigma_shift,
559
+ "adapter_architecture": "framewise_target_q_reference_kv_rope2d_residual_zero_scale",
560
+ "reference_mode": args.reference_mode,
561
+ "comparison_order": ["LR bicubic", "UltraFlash only", "frozen Bridge", "reference adapter", "original video", f"absolute difference x{args.val_diff_amplification:g}"],
562
+ "rows": rows,
563
+ "summary": summary,
564
+ }
565
+ (out_dir / "metrics.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
566
+ print(f"[Validation step {step}] {summary}")
567
+ return summary
568
+
569
+
570
+ def build_dataset(args, validation: bool = False) -> SeedanceSRDataset:
571
+ dataset_class = FirstFrameReferenceSRDataset if args.reference_mode == "image" else SeedanceSRDataset
572
+ return dataset_class(
573
+ args.video_dir, args.prompt_json, args.prompt_field, args.default_prompt,
574
+ args.height, args.width, args.num_frames, args.sr_scale,
575
+ source_mode=args.source_mode, repeat=1 if validation else args.dataset_repeat,
576
+ limit_videos=max(args.val_batches, 1) if validation else args.limit_videos,
577
+ seed=args.seed + int(validation),
578
+ )
579
+
580
+
581
+ def train(args) -> None:
582
+ random.seed(args.seed)
583
+ torch.manual_seed(args.seed)
584
+ if torch.cuda.is_available():
585
+ torch.cuda.manual_seed_all(args.seed)
586
+ args.output_path = args.output_path or str(Path(args.output_root) / build_reference_run_name(args))
587
+ train_set = build_dataset(args)
588
+ val_dataset = build_dataset(args, validation=True)
589
+ # Materialize once so every validation step uses exactly the same clips.
590
+ val_set = [val_dataset[idx] for idx in range(min(args.val_batches, len(val_dataset)))]
591
+ model = ReferenceSRTrainingModule(args)
592
+ accelerator = Accelerator(
593
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
594
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=False)],
595
+ )
596
+ if accelerator.is_main_process:
597
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
598
+ (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
599
+ print(f"[Output] {args.output_path}")
600
+
601
+ if args.validation_only or args.max_train_steps <= 0:
602
+ model = accelerator.prepare(model)
603
+ validate(args, accelerator, model, val_set, 0)
604
+ return
605
+
606
+ optimizer = torch.optim.AdamW(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay)
607
+ loader = DataLoader(train_set, shuffle=True, collate_fn=lambda batch: batch[0], num_workers=args.dataset_num_workers)
608
+ model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
609
+ logger = ModelLogger(args.output_path, remove_prefix_in_ckpt="pipe.dit.")
610
+ if args.validate_at_start:
611
+ validate(args, accelerator, model, val_set, 0)
612
+
613
+ global_step = 0
614
+ while global_step < args.max_train_steps:
615
+ for data in tqdm(loader, disable=not accelerator.is_local_main_process):
616
+ with accelerator.accumulate(model):
617
+ optimizer.zero_grad(set_to_none=True)
618
+ loss, metrics = model(data)
619
+ accelerator.backward(loss)
620
+ if args.max_grad_norm > 0:
621
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
622
+ optimizer.step()
623
+ global_step += 1
624
+ if accelerator.is_main_process and global_step % args.log_interval == 0:
625
+ print(f"[Train step {global_step}] total={loss.detach().float().item():.6f} "
626
+ f"pixel_l1={metrics['pixel_l1']:.6f} hf={metrics['high_frequency']:.6f} "
627
+ f"wavelet={metrics['wavelet']:.6f} sobel={metrics['sobel_edge']:.6f} "
628
+ f"vgg_lpips={metrics['vgg_lpips']:.6f}")
629
+ logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
630
+ if args.val_interval > 0 and global_step % args.val_interval == 0:
631
+ validate(args, accelerator, model, val_set, global_step)
632
+ if global_step >= args.max_train_steps:
633
+ break
634
+ logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
635
+
636
+
637
+ def parse_args():
638
+ parser = argparse.ArgumentParser(
639
+ description="Train identity-safe target-Q/reference-KV 2D-RoPE attention inside a frozen one-step Wan Bridge SR model."
640
+ )
641
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
642
+ parser.add_argument("--model_paths", default=None)
643
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
644
+ 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")
645
+ parser.add_argument("--adapter_checkpoint", default=None)
646
+ parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
647
+ parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
648
+ parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p")
649
+ parser.add_argument("--default_prompt", default="")
650
+ parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr_reference")
651
+ parser.add_argument("--output_path", default=None)
652
+ parser.add_argument("--height", type=int, default=480)
653
+ parser.add_argument("--width", type=int, default=832)
654
+ parser.add_argument("--num_frames", type=int, default=81)
655
+ parser.add_argument("--sr_scale", type=int, default=2)
656
+ parser.add_argument("--source_mode", choices=["upsampler", "bicubic"], default="upsampler")
657
+ parser.add_argument(
658
+ "--reference_mode",
659
+ choices=["video", "image"],
660
+ default="video",
661
+ help="video uses the target clip as reference; image uses absolute frame 0 of each source video.",
662
+ )
663
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
664
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
665
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
666
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
667
+ parser.add_argument(
668
+ "--adapter_blocks",
669
+ default="all",
670
+ help="Wan blocks preceded by one-way target-Q/reference-KV attention with 2D RoPE and zero-init residual scale.",
671
+ )
672
+ parser.add_argument("--adapter_dim", type=int, default=1536, help="Must equal the Wan hidden width.")
673
+ parser.add_argument("--adapter_heads", type=int, default=12, help="Must equal the Wan head count.")
674
+ parser.add_argument(
675
+ "--wavelet_value_mode", choices=["off", "highpass"], default="off",
676
+ help="highpass uses the reference hidden state's reconstructed Haar detail bands as V.",
677
+ )
678
+ parser.add_argument(
679
+ "--wavelet_energy_bias", type=float, default=0.0,
680
+ help="Strength of the normalized Haar-energy additive reference-key logit bias.",
681
+ )
682
+ parser.add_argument(
683
+ "--wavelet_energy_clip", type=float, default=3.0,
684
+ help="Clamp normalized wavelet energy before multiplying by its bias strength.",
685
+ )
686
+ parser.add_argument(
687
+ "--pixel_l1_weight", "--mse_weight",
688
+ dest="pixel_l1_weight", type=float, default=1.0,
689
+ help="Weight of decoded-RGB pixel L1 loss. --mse_weight is a deprecated compatibility alias.",
690
+ )
691
+ parser.add_argument("--hf_weight", type=float, default=0.1)
692
+ parser.add_argument("--lpips_weight", type=float, default=0.2)
693
+ parser.add_argument("--hf_levels", type=int, default=1)
694
+ parser.add_argument("--hf_loss_type", choices=["l1", "l2"], default="l1")
695
+ parser.add_argument(
696
+ "--sobel_edge_weight",
697
+ type=float,
698
+ default=0.5,
699
+ help="Relative Sobel-L1 weight inside the single high-frequency loss term.",
700
+ )
701
+ parser.add_argument(
702
+ "--sobel_edge_dilation_radius",
703
+ type=int,
704
+ default=2,
705
+ help="Dilate the GT Sobel edge mask by this many decoded RGB pixels.",
706
+ )
707
+ parser.add_argument(
708
+ "--sobel_edge_threshold",
709
+ type=float,
710
+ default=1.0,
711
+ help="Binary edge threshold as a multiple of each frame's mean GT gradient magnitude.",
712
+ )
713
+ parser.add_argument("--lpips_num_frames", type=int, default=4)
714
+ parser.add_argument("--lpips_crop_size", type=int, default=400)
715
+ parser.add_argument("--loss_crop_size", type=int, default=400)
716
+ parser.add_argument("--loss_latent_frames", type=int, default=3)
717
+ parser.add_argument("--learning_rate", type=float, default=5e-5)
718
+ parser.add_argument("--weight_decay", type=float, default=0.01)
719
+ parser.add_argument("--max_train_steps", type=int, default=5000)
720
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
721
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
722
+ parser.add_argument("--save_steps", type=int, default=500)
723
+ parser.add_argument("--log_interval", type=int, default=1)
724
+ parser.add_argument("--val_interval", type=int, default=100)
725
+ parser.add_argument("--val_batches", type=int, default=1)
726
+ parser.add_argument("--bridge_sigma_shift", type=float, default=5.0, help="Fixed scheduler shift for the one-step frozen-Bridge call.")
727
+ parser.add_argument("--val_diff_amplification", type=float, default=4.0)
728
+ parser.add_argument("--validate_at_start", action="store_true")
729
+ parser.add_argument("--validation_only", action="store_true")
730
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
731
+ parser.add_argument("--text_drop_probability", type=float, default=0.0)
732
+ parser.add_argument("--dataset_repeat", type=int, default=1)
733
+ parser.add_argument("--dataset_num_workers", type=int, default=0)
734
+ parser.add_argument("--limit_videos", type=int, default=None)
735
+ parser.add_argument("--fps", type=int, default=16)
736
+ parser.add_argument("--use_gradient_checkpointing", action=argparse.BooleanOptionalAction, default=True)
737
+ parser.add_argument("--use_gradient_checkpointing_offload", action="store_true")
738
+ parser.add_argument("--tiled", action="store_true")
739
+ parser.add_argument("--tile_h", type=int, default=30)
740
+ parser.add_argument("--tile_w", type=int, default=52)
741
+ parser.add_argument("--tile_stride_h", type=int, default=15)
742
+ parser.add_argument("--tile_stride_w", type=int, default=26)
743
+ parser.add_argument("--seed", type=int, default=42)
744
+ args = parser.parse_args()
745
+ if args.model_paths is None:
746
+ args.model_paths = default_model_paths(args.base_model_dir)
747
+ return args
748
+
749
+
750
+ if __name__ == "__main__":
751
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
752
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+
7
+ OUTPUT_ARGS=(--output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_reference}")
8
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
9
+ OUTPUT_ARGS+=(--output_path "${OUTPUT_PATH}")
10
+ fi
11
+
12
+ "${PYTHON_BIN}" "${SCRIPT_DIR}/train_sr_reference.py" \
13
+ --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}" \
14
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
15
+ --prompt_json "${PROMPT_JSON-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
16
+ "${OUTPUT_ARGS[@]}" \
17
+ --height "${HEIGHT:-480}" \
18
+ --width "${WIDTH:-832}" \
19
+ --num_frames "${NUM_FRAMES:-81}" \
20
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
21
+ --val_interval "${VAL_INTERVAL:-100}" \
22
+ --save_steps "${SAVE_STEPS:-500}" \
23
+ --adapter_blocks "${ADAPTER_BLOCKS:-all}" \
24
+ --adapter_dim "${ADAPTER_DIM:-1536}" \
25
+ --adapter_heads "${ADAPTER_HEADS:-12}" \
26
+ --wavelet_value_mode "${WAVELET_VALUE_MODE:-off}" \
27
+ --wavelet_energy_bias "${WAVELET_ENERGY_BIAS:-0.0}" \
28
+ --wavelet_energy_clip "${WAVELET_ENERGY_CLIP:-3.0}" \
29
+ --bridge_sigma_shift "${BRIDGE_SIGMA_SHIFT:-5.0}" \
30
+ --pixel_l1_weight "${PIXEL_L1_WEIGHT:-${MSE_WEIGHT:-1.0}}" \
31
+ --hf_weight "${HF_WEIGHT:-30}" \
32
+ --sobel_edge_weight "${SOBEL_EDGE_WEIGHT:-0.5}" \
33
+ --sobel_edge_dilation_radius "${SOBEL_EDGE_DILATION_RADIUS:-2}" \
34
+ --sobel_edge_threshold "${SOBEL_EDGE_THRESHOLD:-1.0}" \
35
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
36
+ --validate_at_start \
37
+ "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+
6
+ # Digital-human image-reference training: every target clip comes from a video,
7
+ # while absolute frame 0 of that video is encoded once as the reference image.
8
+ # Sobel dilation defaults off; set IMAGE_SOBEL_EDGE_DILATION_RADIUS=1/2 for a
9
+ # 3x3/5x5 edge band.
10
+ VIDEO_DIR="${VIDEO_DIR:-/cache/Human-Image-Animation-Data/videos/000}" \
11
+ PROMPT_JSON="${PROMPT_JSON-}" \
12
+ OUTPUT_ROOT="${OUTPUT_ROOT:-/cache/outputs_wavbridge_wan_sr_reference}" \
13
+ HEIGHT="${HEIGHT:-832}" \
14
+ WIDTH="${WIDTH:-480}" \
15
+ NUM_FRAMES="${NUM_FRAMES:-81}" \
16
+ MAX_TRAIN_STEPS="${MAX_TRAIN_STEPS:-5000}" \
17
+ VAL_INTERVAL="${VAL_INTERVAL:-100}" \
18
+ SAVE_STEPS="${SAVE_STEPS:-200}" \
19
+ PIXEL_L1_WEIGHT="${IMAGE_PIXEL_L1_WEIGHT:-${IMAGE_MSE_WEIGHT:-2.0}}" \
20
+ HF_WEIGHT="${IMAGE_HF_WEIGHT:-0.0}" \
21
+ SOBEL_EDGE_WEIGHT="${IMAGE_SOBEL_EDGE_WEIGHT:-1.0}" \
22
+ SOBEL_EDGE_DILATION_RADIUS="${IMAGE_SOBEL_EDGE_DILATION_RADIUS:-0}" \
23
+ SOBEL_EDGE_THRESHOLD="${IMAGE_SOBEL_EDGE_THRESHOLD:-1.0}" \
24
+ LPIPS_WEIGHT="${IMAGE_LPIPS_WEIGHT:-1.0}" \
25
+ bash "${SCRIPT_DIR}/train_sr_reference.sh" \
26
+ --reference_mode image \
27
+ --default_prompt "a person is speaking" \
28
+ "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_reference_image_wavelet.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+
6
+ # Train a fresh image-reference Adapter whose K remains the full reference
7
+ # hidden state, while V carries reconstructed Haar LH/HL/HH detail features.
8
+ # The modest default bias favors detailed reference patches without letting
9
+ # background edges overwhelm target/reference correspondence.
10
+ WAVELET_VALUE_MODE="${WAVELET_VALUE_MODE:-highpass}" \
11
+ WAVELET_ENERGY_BIAS="${WAVELET_ENERGY_BIAS:-0.50}" \
12
+ WAVELET_ENERGY_CLIP="${WAVELET_ENERGY_CLIP:-3.0}" \
13
+ bash "${SCRIPT_DIR}/train_sr_reference_image.sh" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train a Wan2.2-TI2V Brownian bridge for video super-resolution.
2
+
3
+ This keeps the Wan text prompt branch enabled, removes the UltraFlash latent
4
+ upsampler source branch, and follows the Wan2.2 TI2V-style strong anchor:
5
+ the first latent temporal index is replaced by the encoded HR reference frame
6
+ during training and after every validation sampling step. The TI2V fused
7
+ input path additionally gives the first-frame tokens timestep zero, matching
8
+ the native Wan2.2 TI2V implementation.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import copy
15
+ import json
16
+ import os
17
+ import random
18
+ from pathlib import Path
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from accelerate import Accelerator
23
+ from accelerate.utils import DistributedDataParallelKwargs
24
+ from PIL import Image
25
+ from torch.utils.data import DataLoader, Dataset
26
+ from tqdm import tqdm
27
+
28
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
29
+ SeedanceSRDataset,
30
+ crop_original_rgb_for_latent_crop,
31
+ crop_latent_pair_for_pixel_losses,
32
+ decode_latents_to_btchw_01,
33
+ default_model_paths,
34
+ lpips_video_loss,
35
+ pil_video_to_tensor_01,
36
+ random_spatial_crop_pair,
37
+ tensor_btchw_01_to_pil,
38
+ wavelet_hf_loss,
39
+ )
40
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline
41
+ from diffsynth.data.video import save_video
42
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger
43
+ from diffsynth.utils import ModelConfig
44
+
45
+
46
+ def format_run_value(value: object) -> str:
47
+ text = f"{value:g}" if isinstance(value, float) else str(value)
48
+ return text.replace(".", "p").replace("-", "m").replace("/", "_")
49
+
50
+
51
+ def default_model_paths(base_model_dir: str) -> str:
52
+ """Resolve the three files required by a local Wan2.2-TI2V checkpoint."""
53
+ base = Path(base_model_dir)
54
+ dit = base / "diffusion_pytorch_model.safetensors.index.json"
55
+ if not dit.exists():
56
+ dit = base / "diffusion_pytorch_model.safetensors"
57
+ paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.2_VAE.pth"]
58
+ for path in paths:
59
+ if not path.exists():
60
+ raise FileNotFoundError(f"Missing Wan2.2-TI2V model file: {path}")
61
+ return ",".join(str(path) for path in paths)
62
+
63
+
64
+ def build_run_name(args) -> str:
65
+ parts = [
66
+ "wan22_ti2v_sr_ffanchor",
67
+ f"x{args.sr_scale}",
68
+ f"{args.height}x{args.width}",
69
+ f"f{args.num_frames}",
70
+ "bicubic",
71
+ "prompt",
72
+ "relock" if args.anchor_each_step else "initanchor",
73
+ f"lr{format_run_value(args.learning_rate)}",
74
+ f"noise{format_run_value(args.noise_sigma)}",
75
+ f"bridge{format_run_value(args.bridge_loss_weight)}",
76
+ f"lpips{format_run_value(args.lpips_weight)}",
77
+ f"ssim{format_run_value(args.ssim_weight)}",
78
+ f"wav{format_run_value(args.wavelet_hf_weight)}",
79
+ f"pix{format_run_value(args.pixel_loss_weight)}",
80
+ f"pcrop{args.pixel_loss_crop_size}",
81
+ f"plf{args.pixel_loss_latent_frames}",
82
+ f"seed{args.seed}",
83
+ ]
84
+ return "_".join(parts)
85
+
86
+
87
+ class FirstFrameAnchorSRDataset(SeedanceSRDataset):
88
+ """Bicubic-upsampled SR source whose first frame is replaced by HR reference."""
89
+
90
+ def __init__(self, *args, **kwargs) -> None:
91
+ kwargs["source_mode"] = "bicubic"
92
+ super().__init__(*args, **kwargs)
93
+
94
+ def __getitem__(self, idx: int) -> dict:
95
+ item = super().__getitem__(idx)
96
+ reference = item["video"][0].copy()
97
+ item["source_video"][0] = reference.copy()
98
+ item["reference_image"] = reference
99
+ return item
100
+
101
+
102
+ def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor:
103
+ if anchor is None:
104
+ return latents
105
+ if anchor.shape[2] != 1:
106
+ raise ValueError(f"first_frame_latents must have exactly one latent frame, got {tuple(anchor.shape)}")
107
+ if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]:
108
+ raise ValueError(
109
+ f"anchor shape {tuple(anchor.shape)} is incompatible with latents {tuple(latents.shape)}"
110
+ )
111
+ out = latents.clone()
112
+ out[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype)
113
+ return out
114
+
115
+
116
+ def drop_first_time_frame_btchw(video: torch.Tensor) -> torch.Tensor:
117
+ if video.shape[1] <= 1:
118
+ return video[:, :0]
119
+ return video[:, 1:]
120
+
121
+
122
+ def drop_first_time_frame_bcthw(latents: torch.Tensor) -> torch.Tensor:
123
+ if latents.shape[2] <= 1:
124
+ return latents[:, :, :0]
125
+ return latents[:, :, 1:]
126
+
127
+
128
+ def drop_global_first_frame_from_crop_btchw(video: torch.Tensor, crop_info: dict) -> torch.Tensor:
129
+ if int(crop_info.get("start_t", 0)) != 0:
130
+ return video
131
+ return drop_first_time_frame_btchw(video)
132
+
133
+
134
+ def mse_after_first_latent_frame(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
135
+ pred_main = drop_first_time_frame_bcthw(pred)
136
+ target_main = drop_first_time_frame_bcthw(target)
137
+ if pred_main.numel() == 0:
138
+ return pred.new_tensor(0.0)
139
+ return F.mse_loss(pred_main.float(), target_main.float())
140
+
141
+
142
+ def choose_chunk_bounds(total_latent_frames: int, chunk_latent_frames: int, history_latent_frames: int):
143
+ if total_latent_frames <= 1:
144
+ raise ValueError("A video must contain at least one future latent frame")
145
+ chunk = min(max(int(chunk_latent_frames), 1), total_latent_frames - 1)
146
+ max_start = total_latent_frames - chunk
147
+ start = random.randint(1, max_start) if max_start > 1 else 1
148
+ history_start = max(1, start - max(int(history_latent_frames), 0))
149
+ return history_start, start, start + chunk
150
+
151
+
152
+ def chunk_rgb_target(frames: list[Image.Image], history_start: int, start: int, end: int) -> list[Image.Image]:
153
+ """Map Wan2.2 latent indices back to RGB frames (latent 0 is RGB frame 0)."""
154
+ prefix = [frames[0]]
155
+ if start > history_start:
156
+ prefix.extend(frames[4 * history_start - 3:4 * start - 3])
157
+ current = frames[4 * start - 3:4 * end - 3]
158
+ return prefix + current
159
+
160
+
161
+ def crop_current_rgb_for_latent_region(
162
+ frames: list[Image.Image],
163
+ latent_start: int,
164
+ latent_count: int,
165
+ crop_info: dict,
166
+ device: torch.device,
167
+ ) -> torch.Tensor:
168
+ rgb_start = 4 * latent_start - 3
169
+ rgb_end = rgb_start + 4 * latent_count
170
+ current = pil_video_to_tensor_01(frames[rgb_start:rgb_end], device).unsqueeze(0)
171
+ vae_factor_h = current.shape[-2] // int(crop_info["full_h"])
172
+ vae_factor_w = current.shape[-1] // int(crop_info["full_w"])
173
+ top = int(crop_info["start_h"]) * vae_factor_h
174
+ left = int(crop_info["start_w"]) * vae_factor_w
175
+ height = int(crop_info["crop_h"]) * vae_factor_h
176
+ width = int(crop_info["crop_w"]) * vae_factor_w
177
+ return current[..., top:top + height, left:left + width]
178
+
179
+
180
+ def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor:
181
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
182
+ if min_t <= 0:
183
+ return pred_btchw_01.new_tensor(0.0)
184
+ pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float()
185
+ target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float()
186
+ channels = pred.shape[1]
187
+ window_size = max(1, int(window_size))
188
+ if window_size % 2 == 0:
189
+ window_size += 1
190
+ padding = window_size // 2
191
+ weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size)
192
+
193
+ mu_x = F.conv2d(pred, weight, padding=padding, groups=channels)
194
+ mu_y = F.conv2d(target, weight, padding=padding, groups=channels)
195
+ mu_x_sq = mu_x.square()
196
+ mu_y_sq = mu_y.square()
197
+ mu_xy = mu_x * mu_y
198
+
199
+ sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq
200
+ sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq
201
+ sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy
202
+
203
+ c1 = 0.01 ** 2
204
+ c2 = 0.03 ** 2
205
+ ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / (
206
+ (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8
207
+ )
208
+ return (1.0 - ssim.clamp(-1.0, 1.0)).mean()
209
+
210
+
211
+ class FirstFrameAnchorWanVideoSRBridgePipeline(WanVideoBridgePipeline):
212
+ def training_loss(self, **inputs):
213
+ max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps)
214
+ min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps)
215
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
216
+ timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device)
217
+ anchor_each_step = bool(inputs.get("anchor_each_step", True))
218
+
219
+ anchor = inputs.get("first_frame_latents")
220
+ full_x0 = replace_first_latent_frame(inputs["input_latents"], anchor)
221
+ full_x1 = replace_first_latent_frame(inputs["source_latents"], anchor)
222
+ noise = inputs["noise"]
223
+ history_start, current_start, current_end = choose_chunk_bounds(
224
+ full_x0.shape[2],
225
+ int(inputs.get("chunk_latent_frames", 4)),
226
+ int(inputs.get("history_latent_frames", 2)),
227
+ )
228
+ history = full_x0[:, :, history_start:current_start].detach()
229
+ current_x0 = full_x0[:, :, current_start:current_end]
230
+ current_x1 = full_x1[:, :, current_start:current_end]
231
+ current_noise = noise[:, :, current_start:current_end]
232
+ current_xt = self.scheduler.add_noise(current_x0, current_x1, current_noise, timestep)
233
+ x0 = torch.cat([anchor, history, current_x0], dim=2)
234
+ x1 = torch.cat([anchor, history, current_x1], dim=2)
235
+ xt = torch.cat([anchor, history, current_xt], dim=2)
236
+ prefix_frames = 1 + history.shape[2]
237
+
238
+ model_inputs = dict(inputs)
239
+ model_inputs["latents"] = xt
240
+ model_inputs["input_latents"] = x0
241
+ model_inputs["source_latents"] = x1
242
+ model_inputs.pop("first_frame_latents", None)
243
+ model_inputs["clean_history_latent_frames"] = int(history.shape[2])
244
+
245
+ target = self.scheduler.training_target(current_x0, current_xt, timestep)
246
+ model_output = self.model_fn(**model_inputs, timestep=timestep)
247
+
248
+ if self.scheduler.target == "stabilized_drift":
249
+ sigma = self.scheduler.get_sigma(timestep)
250
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)) ** 0.5
251
+ velocity_target = target / factor
252
+ velocity_for_endpoint = model_output[:, :, prefix_frames:] * factor
253
+ elif self.scheduler.target == "drift":
254
+ velocity_target = target
255
+ velocity_for_endpoint = model_output[:, :, prefix_frames:]
256
+ else:
257
+ raise ValueError("First-frame-anchor SR bridge training supports --target stabilized_drift or drift")
258
+
259
+ bridge_loss = F.mse_loss(
260
+ model_output[:, :, prefix_frames:].float(), velocity_target.float()
261
+ )
262
+ total_loss = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss
263
+ metrics = {
264
+ "bridge_loss": float(bridge_loss.detach().cpu()),
265
+ "lpips_loss": 0.0,
266
+ "ssim_loss": 0.0,
267
+ "wavelet_hf_loss": 0.0,
268
+ "pixel_loss": 0.0,
269
+ }
270
+
271
+ lpips_model = inputs.get("lpips_model")
272
+ lpips_weight = float(inputs.get("lpips_weight", 0.0))
273
+ ssim_weight = float(inputs.get("ssim_weight", 0.0))
274
+ wavelet_hf_weight = float(inputs.get("wavelet_hf_weight", 0.0))
275
+ pixel_loss_weight = float(inputs.get("pixel_loss_weight", 0.0))
276
+ if lpips_weight > 0 or ssim_weight > 0 or wavelet_hf_weight > 0 or pixel_loss_weight > 0:
277
+ sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
278
+ endpoint_current = current_xt.float() - sigma * velocity_for_endpoint.float()
279
+ loss_latent_frames = min(
280
+ max(int(inputs.get("pixel_loss_latent_frames", 3)), 1),
281
+ endpoint_current.shape[2],
282
+ )
283
+ max_loss_start = endpoint_current.shape[2] - loss_latent_frames
284
+ loss_start = (
285
+ int(torch.randint(max_loss_start + 1, (1,), device=endpoint_current.device).item())
286
+ if max_loss_start > 0 else 0
287
+ )
288
+ global_loss_start = current_start + loss_start
289
+ endpoint_loss = endpoint_current[:, :, loss_start:loss_start + loss_latent_frames]
290
+ target_loss = current_x0[:, :, loss_start:loss_start + loss_latent_frames].detach()
291
+ # Prepend one clean GT latent as causal VAE context. It is removed
292
+ # after decoding, while the current region retains all 4 RGB frames
293
+ # per latent index.
294
+ context_latent = full_x0[:, :, global_loss_start - 1:global_loss_start].detach()
295
+ endpoint_decode = torch.cat([context_latent, endpoint_loss], dim=2)
296
+ target_decode = torch.cat([context_latent, target_loss], dim=2)
297
+ endpoint_decode, _, crop_info = crop_latent_pair_for_pixel_losses(
298
+ endpoint_decode,
299
+ target_decode,
300
+ crop_size_pixels=int(inputs.get("pixel_loss_crop_size", 400)),
301
+ latent_frames=0,
302
+ vae_factor=int(getattr(self.vae, "upsampling_factor", 16)),
303
+ return_crop_info=True,
304
+ )
305
+ pred_video = decode_latents_to_btchw_01(
306
+ self,
307
+ endpoint_decode,
308
+ tiled=bool(inputs.get("tiled", False)),
309
+ tile_size=inputs.get("tile_size", (30, 52)),
310
+ tile_stride=inputs.get("tile_stride", (15, 26)),
311
+ )
312
+ raw_target_video = inputs.get("raw_target_video")
313
+ if raw_target_video is None:
314
+ raise ValueError("raw_target_video is required for RGB-space MSE/HF/LPIPS losses")
315
+ pred_video_main = pred_video[:, 1:]
316
+ target_video_main = crop_current_rgb_for_latent_region(
317
+ raw_target_video,
318
+ global_loss_start,
319
+ loss_latent_frames,
320
+ crop_info,
321
+ self.device,
322
+ )
323
+ if lpips_weight > 0:
324
+ if lpips_model is None:
325
+ raise ValueError("lpips_model is required when lpips_weight > 0")
326
+ if pred_video_main.shape[1] == 0:
327
+ loss = pred_video.new_tensor(0.0)
328
+ else:
329
+ loss = lpips_video_loss(
330
+ lpips_model,
331
+ pred_video_main,
332
+ target_video_main,
333
+ num_frames=int(inputs.get("lpips_num_frames", 4)),
334
+ crop_size=int(inputs.get("lpips_crop_size", 224)),
335
+ )
336
+ total_loss = total_loss + lpips_weight * loss
337
+ metrics["lpips_loss"] = float(loss.detach().cpu())
338
+ if ssim_weight > 0:
339
+ if pred_video_main.shape[1] == 0:
340
+ loss = pred_video.new_tensor(0.0)
341
+ else:
342
+ loss = ssim_video_loss(
343
+ pred_video_main,
344
+ target_video_main,
345
+ window_size=int(inputs.get("ssim_window_size", 11)),
346
+ )
347
+ total_loss = total_loss + ssim_weight * loss
348
+ metrics["ssim_loss"] = float(loss.detach().cpu())
349
+ if wavelet_hf_weight > 0:
350
+ if pred_video_main.shape[1] == 0:
351
+ loss = pred_video.new_tensor(0.0)
352
+ else:
353
+ loss = wavelet_hf_loss(
354
+ pred_video_main,
355
+ target_video_main,
356
+ levels=int(inputs.get("wavelet_hf_levels", 1)),
357
+ loss_type=str(inputs.get("wavelet_hf_loss", "l1")),
358
+ )
359
+ total_loss = total_loss + wavelet_hf_weight * loss
360
+ metrics["wavelet_hf_loss"] = float(loss.detach().cpu())
361
+ if pixel_loss_weight > 0:
362
+ if pred_video_main.shape[1] == 0:
363
+ loss = pred_video.new_tensor(0.0)
364
+ else:
365
+ loss = F.mse_loss(pred_video_main.float(), target_video_main.float())
366
+ total_loss = total_loss + pixel_loss_weight * loss
367
+ metrics["pixel_loss"] = float(loss.detach().cpu())
368
+
369
+ return total_loss, metrics
370
+
371
+
372
+ class FirstFrameAnchorSRTrainingModule(DiffusionTrainingModule):
373
+ def __init__(self, args):
374
+ super().__init__()
375
+ model_configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
376
+ self.pipe: FirstFrameAnchorWanVideoSRBridgePipeline = (
377
+ FirstFrameAnchorWanVideoSRBridgePipeline.from_pretrained(
378
+ torch_dtype=torch.bfloat16,
379
+ device="cpu",
380
+ model_configs=model_configs,
381
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
382
+ )
383
+ )
384
+ self.pipe.latent_upsampler = None
385
+ if not getattr(self.pipe.dit, "fuse_vae_embedding_in_latents", False):
386
+ raise RuntimeError(
387
+ "The loaded DiT is not Wan2.2-TI2V fused-input compatible. "
388
+ "Use the Wan2.2-TI2V-5B checkpoint and its 48-channel VAE."
389
+ )
390
+ if int(getattr(self.pipe.vae, "z_dim", 0)) != 48:
391
+ raise RuntimeError(
392
+ f"Expected Wan2.2-TI2V VAE z_dim=48, got {getattr(self.pipe.vae, 'z_dim', None)}"
393
+ )
394
+ print(
395
+ "[Wan22TI2VBridge] source=bicubic_upscale_with_hr_first_frame "
396
+ "text=prompt fused_vae_input=true first_frame_timestep=0 anchor=strong"
397
+ )
398
+ self.switch_pipe_to_training_mode(
399
+ self.pipe,
400
+ args.trainable_models,
401
+ args.lora_base_model,
402
+ args.lora_target_modules,
403
+ args.lora_rank,
404
+ lora_checkpoint=args.lora_checkpoint,
405
+ enable_fp8_training=False,
406
+ )
407
+ self.args = args
408
+ if args.lpips_weight > 0 or args.val_lpips:
409
+ import lpips
410
+
411
+ self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False)
412
+ else:
413
+ self.lpips_model = None
414
+
415
+ def to(self, *args, **kwargs):
416
+ super().to(*args, **kwargs)
417
+ if self.lpips_model is not None:
418
+ self.lpips_model.to(*args, **kwargs)
419
+ return self
420
+
421
+ def _encode_first_frame_anchor(self, reference_image: Image.Image) -> torch.Tensor:
422
+ self.pipe.load_models_to_device(["vae"])
423
+ reference_video = self.pipe.preprocess_video([reference_image])
424
+ anchor = self.pipe.vae.encode(
425
+ reference_video,
426
+ device=self.pipe.device,
427
+ tiled=self.args.tiled,
428
+ tile_size=(self.args.tile_h, self.args.tile_w),
429
+ tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w),
430
+ ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
431
+ if anchor.shape[2] != 1:
432
+ raise ValueError(f"Expected reference image to encode to one latent frame, got {tuple(anchor.shape)}")
433
+ return anchor
434
+
435
+ def forward_preprocess(self, data):
436
+ prompt = data["prompt"]
437
+ if random.random() < self.args.text_drop_probability:
438
+ prompt = " "
439
+ inputs_posi = {"prompt": prompt}
440
+ inputs_nega = {}
441
+ inputs_shared = {
442
+ "input_video": data["video"],
443
+ "source_video": data["source_video"],
444
+ "height": data["video"][0].size[1],
445
+ "width": data["video"][0].size[0],
446
+ "num_frames": len(data["video"]),
447
+ "cfg_scale": 1,
448
+ "tiled": self.args.tiled,
449
+ "tile_size": (self.args.tile_h, self.args.tile_w),
450
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
451
+ "rand_device": self.pipe.device,
452
+ "seed": None,
453
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
454
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
455
+ "cfg_merge": False,
456
+ "vace_scale": 1,
457
+ "anchor_each_step": self.args.anchor_each_step,
458
+ # Wan2.2-TI2V model_fn expands this scalar to per-token timesteps:
459
+ # frame-0 tokens receive zero and future tokens receive t.
460
+ "fuse_vae_embedding_in_latents": True,
461
+ "chunk_latent_frames": self.args.chunk_latent_frames,
462
+ "history_latent_frames": self.args.history_latent_frames,
463
+ "max_timestep_boundary": self.args.max_timestep_boundary,
464
+ "min_timestep_boundary": self.args.min_timestep_boundary,
465
+ "bridge_loss_weight": self.args.bridge_loss_weight,
466
+ "lpips_weight": self.args.lpips_weight,
467
+ "lpips_model": self.lpips_model,
468
+ "lpips_num_frames": self.args.lpips_num_frames,
469
+ "lpips_crop_size": self.args.lpips_crop_size,
470
+ "ssim_weight": self.args.ssim_weight,
471
+ "ssim_window_size": self.args.ssim_window_size,
472
+ "pixel_loss_crop_size": self.args.pixel_loss_crop_size,
473
+ "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames,
474
+ "wavelet_hf_weight": self.args.wavelet_hf_weight,
475
+ "wavelet_hf_levels": self.args.wavelet_hf_levels,
476
+ "wavelet_hf_loss": self.args.wavelet_hf_loss,
477
+ "pixel_loss_weight": self.args.pixel_loss_weight,
478
+ }
479
+ for unit in self.pipe.units:
480
+ inputs_shared, inputs_posi, inputs_nega = self.pipe.unit_runner(
481
+ unit, self.pipe, inputs_shared, inputs_posi, inputs_nega
482
+ )
483
+ inputs_shared["first_frame_latents"] = self._encode_first_frame_anchor(data["reference_image"])
484
+ inputs_shared["raw_target_video"] = data["video"]
485
+ return {**inputs_shared, **inputs_posi}
486
+
487
+ def forward(self, data, inputs=None):
488
+ if inputs is None:
489
+ inputs = self.forward_preprocess(data)
490
+ return self.pipe.training_loss(
491
+ **{name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models},
492
+ **inputs,
493
+ )
494
+
495
+
496
+ class FirstFrameAnchorModelLogger(ModelLogger):
497
+ def on_step_end(self, accelerator, model, save_steps=None):
498
+ super().on_step_end(accelerator, model, save_steps)
499
+
500
+
501
+ @torch.no_grad()
502
+ def sample_chunked_latents(pipe, inputs: dict, args) -> torch.Tensor:
503
+ """Validation sampler matching inference: clean reference/history, noisy current."""
504
+ anchor = inputs["first_frame_latents"]
505
+ source_full = replace_first_latent_frame(inputs["source_latents"], anchor)
506
+ generated = anchor.clone()
507
+ pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift)
508
+ pipe.load_models_to_device(pipe.in_iteration_models)
509
+ models = {name: getattr(pipe, name) for name in pipe.in_iteration_models}
510
+ model_inputs = dict(inputs)
511
+ model_inputs.pop("latents", None)
512
+ model_inputs.pop("first_frame_latents", None)
513
+ model_inputs["fuse_vae_embedding_in_latents"] = True
514
+
515
+ for current_start in range(1, source_full.shape[2], args.chunk_latent_frames):
516
+ current_end = min(source_full.shape[2], current_start + args.chunk_latent_frames)
517
+ history = generated[:, :, max(1, generated.shape[2] - args.history_latent_frames):].detach()
518
+ chunk_source = torch.cat([anchor, history, source_full[:, :, current_start:current_end]], dim=2)
519
+ latents = chunk_source.clone()
520
+ history_len = history.shape[2]
521
+ clean_prefix = torch.cat([anchor, history], dim=2)
522
+ model_inputs["source_latents"] = chunk_source
523
+ model_inputs["clean_history_latent_frames"] = history_len
524
+ for timestep_cpu in pipe.scheduler.timesteps:
525
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
526
+ pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep)
527
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, chunk_source)
528
+ latents[:, :, :1 + history_len] = clean_prefix
529
+ generated = torch.cat([generated, latents[:, :, 1 + history_len:].detach()], dim=2)
530
+ return generated
531
+
532
+
533
+ @torch.no_grad()
534
+ def validate(args, accelerator: Accelerator, model: FirstFrameAnchorSRTrainingModule, dataset: Dataset, step: int) -> dict:
535
+ if not accelerator.is_main_process:
536
+ return {}
537
+ module = accelerator.unwrap_model(model)
538
+ pipe = module.pipe
539
+ pipe.eval()
540
+ backup_scheduler = pipe.scheduler
541
+ pipe.scheduler = copy.deepcopy(backup_scheduler)
542
+ pipe.scheduler.noise_scale = args.val_sampling_noise_scale
543
+ pipe.scheduler.target = args.target
544
+
545
+ rows = []
546
+ out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}"
547
+ out_dir.mkdir(parents=True, exist_ok=True)
548
+ for idx in range(min(args.val_batches, len(dataset))):
549
+ data = dataset[idx]
550
+ pipe.scheduler.set_timesteps(1000, training=True)
551
+ inputs = module.forward_preprocess(data)
552
+ x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"])
553
+ x1 = replace_first_latent_frame(inputs["source_latents"], inputs["first_frame_latents"])
554
+ latents = sample_chunked_latents(pipe, inputs, args)
555
+
556
+ pred_video = decode_latents_to_btchw_01(
557
+ pipe, latents, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)
558
+ )
559
+ target_video = decode_latents_to_btchw_01(
560
+ pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w)
561
+ )
562
+ if args.anchor_each_step:
563
+ pred_video_main = drop_first_time_frame_btchw(pred_video)
564
+ target_video_main = drop_first_time_frame_btchw(target_video)
565
+ else:
566
+ pred_video_main = pred_video
567
+ target_video_main = target_video
568
+ source_tensor = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0)
569
+ target_tensor = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0)
570
+ min_t = min(source_tensor.shape[1], pred_video.shape[1], target_tensor.shape[1])
571
+ strip = torch.cat([source_tensor[:, :min_t], pred_video[:, :min_t], target_tensor[:, :min_t]], dim=-1)
572
+ save_video(tensor_btchw_01_to_pil(pred_video[0]), str(out_dir / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5)
573
+ 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)
574
+ data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png")
575
+
576
+ row = {
577
+ "idx": idx,
578
+ "latent_mse": (
579
+ mse_after_first_latent_frame(latents, x0).item()
580
+ if args.anchor_each_step
581
+ else F.mse_loss(latents.float(), x0.float()).item()
582
+ ),
583
+ "pixel_mse": (
584
+ F.mse_loss(pred_video_main.float(), target_video_main.float()).item()
585
+ if pred_video_main.shape[1] > 0
586
+ else 0.0
587
+ ),
588
+ "anchor_latent_mse": F.mse_loss(
589
+ latents[:, :, :1].float(), inputs["first_frame_latents"].float()
590
+ ).item(),
591
+ }
592
+ if module.lpips_model is not None and args.val_lpips:
593
+ row["lpips"] = float(
594
+ lpips_video_loss(
595
+ module.lpips_model,
596
+ pred_video_main,
597
+ target_video_main,
598
+ args.lpips_num_frames,
599
+ args.lpips_crop_size,
600
+ ).detach().cpu()
601
+ ) if pred_video_main.shape[1] > 0 else 0.0
602
+ if args.val_ssim or args.ssim_weight > 0:
603
+ row["ssim"] = float(
604
+ ssim_video_loss(pred_video_main, target_video_main, args.ssim_window_size).detach().cpu()
605
+ ) if pred_video_main.shape[1] > 0 else 0.0
606
+ if args.val_wavelet_hf_loss:
607
+ row["wavelet_hf"] = float(
608
+ wavelet_hf_loss(pred_video_main, target_video_main, args.wavelet_hf_levels, args.wavelet_hf_loss).detach().cpu()
609
+ ) if pred_video_main.shape[1] > 0 else 0.0
610
+ rows.append(row)
611
+
612
+ pipe.scheduler = backup_scheduler
613
+ metrics = {}
614
+ if rows:
615
+ for key in rows[0]:
616
+ if key != "idx":
617
+ metrics[f"val_{key}"] = float(
618
+ sum(row[key] for row in rows if key in row) / max(sum(1 for row in rows if key in row), 1)
619
+ )
620
+ (out_dir / "metrics.json").write_text(
621
+ json.dumps(
622
+ {
623
+ "step": step,
624
+ "rows": rows,
625
+ "metrics": metrics,
626
+ "pipeline": "bicubic_source_hr_first_frame_strong_latent_anchor_with_prompt",
627
+ "anchor_each_step": args.anchor_each_step,
628
+ },
629
+ indent=2,
630
+ ),
631
+ encoding="utf-8",
632
+ )
633
+ print(f"[Validation step {step}] {metrics}")
634
+ pipe.train()
635
+ return metrics
636
+
637
+
638
+ def build_dataset(args, repeat: int, limit_videos: int | None, seed: int) -> FirstFrameAnchorSRDataset:
639
+ return FirstFrameAnchorSRDataset(
640
+ args.video_dir,
641
+ args.prompt_json,
642
+ args.prompt_field,
643
+ args.default_prompt,
644
+ args.height,
645
+ args.width,
646
+ args.num_frames,
647
+ args.sr_scale,
648
+ repeat=repeat,
649
+ limit_videos=limit_videos,
650
+ seed=seed,
651
+ )
652
+
653
+
654
+ def train(args):
655
+ save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None
656
+ if args.output_path is None:
657
+ args.output_path = str(Path(args.output_root) / build_run_name(args))
658
+ train_set = build_dataset(
659
+ args,
660
+ repeat=args.dataset_repeat,
661
+ limit_videos=args.limit_videos,
662
+ seed=args.seed,
663
+ )
664
+ val_set = build_dataset(
665
+ args,
666
+ repeat=1,
667
+ limit_videos=max(args.val_batches, 1),
668
+ seed=args.seed + 1,
669
+ )
670
+ model = FirstFrameAnchorSRTrainingModule(args)
671
+ model.pipe.scheduler.noise_scale = args.noise_sigma
672
+ model.pipe.scheduler.bridge_type = "brownian"
673
+ model.pipe.scheduler.training_weight_type = args.training_weight_type
674
+ model.pipe.scheduler.target = args.target
675
+ print("Scheduler noise scale:", model.pipe.scheduler.noise_scale)
676
+ print("Scheduler training weight type:", model.pipe.scheduler.training_weight_type)
677
+ print("Scheduler target:", model.pipe.scheduler.target)
678
+
679
+ accelerator = Accelerator(
680
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
681
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
682
+ )
683
+ if accelerator.is_main_process:
684
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
685
+ (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
686
+ print(f"[Output] {args.output_path}")
687
+
688
+ if args.validation_only or args.max_train_steps <= 0:
689
+ model = accelerator.prepare(model)
690
+ validate(args, accelerator, model, val_set, 0)
691
+ return
692
+
693
+ from prodigyopt import Prodigy
694
+
695
+ optimizer = Prodigy(
696
+ model.trainable_modules(),
697
+ lr=args.learning_rate,
698
+ weight_decay=args.weight_decay,
699
+ safeguard_warmup=True,
700
+ d_coef=args.d_coef,
701
+ )
702
+ dataloader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers)
703
+ model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
704
+ logger = FirstFrameAnchorModelLogger(args.output_path, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt)
705
+ if args.validate_at_start:
706
+ validate(args, accelerator, model, val_set, 0)
707
+
708
+ global_step = 0
709
+ while global_step < args.max_train_steps:
710
+ for data in tqdm(dataloader, disable=not accelerator.is_local_main_process):
711
+ with accelerator.accumulate(model):
712
+ optimizer.zero_grad()
713
+ loss, metrics = model(data)
714
+ accelerator.backward(loss)
715
+ if args.max_grad_norm > 0:
716
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
717
+ optimizer.step()
718
+ global_step += 1
719
+ gathered_loss = accelerator.gather(loss.detach()).mean().item()
720
+ if accelerator.is_main_process and global_step % args.log_interval == 0:
721
+ print(
722
+ f"[Train step {global_step}] loss={gathered_loss:.6f} "
723
+ f"bridge={metrics['bridge_loss']:.6f} lpips={metrics['lpips_loss']:.6f} "
724
+ f"ssim={metrics['ssim_loss']:.6f} "
725
+ f"wavelet={metrics['wavelet_hf_loss']:.6f} pixel={metrics['pixel_loss']:.6f}"
726
+ )
727
+ logger.on_step_end(accelerator, model, save_steps)
728
+ if args.val_interval > 0 and global_step % args.val_interval == 0:
729
+ validate(args, accelerator, model, val_set, global_step)
730
+ if global_step >= args.max_train_steps:
731
+ break
732
+ logger.on_training_end(accelerator, model, save_steps)
733
+
734
+
735
+ def parse_args():
736
+ parser = argparse.ArgumentParser(
737
+ description="Train a Wan2.2-TI2V Brownian-Bridge SR model with strong first-frame latent anchoring."
738
+ )
739
+ parser.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B")
740
+ parser.add_argument("--model_paths", default=None)
741
+ parser.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl")
742
+ parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
743
+ parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
744
+ parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p")
745
+ parser.add_argument("--default_prompt", default="")
746
+ parser.add_argument("--output_root", default="/cache/outputs_bridge_wan22_ti2v_sr")
747
+ parser.add_argument("--output_path", default=None)
748
+ parser.add_argument("--height", type=int, default=480)
749
+ parser.add_argument("--width", type=int, default=832)
750
+ parser.add_argument("--num_frames", type=int, default=81)
751
+ parser.add_argument("--chunk_latent_frames", type=int, default=4,
752
+ help="Number of current Wan2.2 latent frames trained per chunk.")
753
+ parser.add_argument("--history_latent_frames", type=int, default=2,
754
+ help="Number of clean GT history latent frames used as teacher-forcing context.")
755
+ parser.add_argument("--sr_scale", type=int, default=2)
756
+ parser.add_argument("--fps", type=int, default=16)
757
+ parser.add_argument("--limit_videos", type=int, default=None)
758
+ parser.add_argument("--dataset_repeat", type=int, default=1)
759
+ parser.add_argument("--dataset_num_workers", type=int, default=0)
760
+ parser.add_argument("--trainable_models", default="dit")
761
+ parser.add_argument("--lora_base_model", default=None)
762
+ parser.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2")
763
+ parser.add_argument("--lora_rank", type=int, default=32)
764
+ parser.add_argument("--lora_checkpoint", default=None)
765
+ parser.add_argument("--learning_rate", type=float, default=1.0)
766
+ parser.add_argument("--weight_decay", type=float, default=0.01)
767
+ parser.add_argument("--d_coef", type=float, default=1.0)
768
+ parser.add_argument("--max_train_steps", type=int, default=5000)
769
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
770
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
771
+ parser.add_argument("--save_steps", type=int, default=500)
772
+ parser.add_argument("--log_interval", type=int, default=1)
773
+ parser.add_argument("--val_interval", type=int, default=100)
774
+ parser.add_argument("--val_batches", type=int, default=1)
775
+ parser.add_argument("--validate_at_start", action="store_true", default=False)
776
+ parser.add_argument("--validation_only", action="store_true", default=False)
777
+ parser.add_argument("--remove_prefix_in_ckpt", default="pipe.dit.")
778
+ parser.add_argument("--noise_sigma", type=float, default=1.0)
779
+ parser.add_argument("--training_weight_type", default="uniform")
780
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
781
+ parser.add_argument("--bridge_loss_weight", type=float, default=1.0)
782
+ parser.add_argument("--lpips_weight", type=float, default=1.0)
783
+ parser.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg")
784
+ parser.add_argument("--lpips_num_frames", type=int, default=4)
785
+ parser.add_argument("--lpips_crop_size", type=int, default=400)
786
+ parser.add_argument("--ssim_weight", type=float, default=0.0)
787
+ parser.add_argument("--ssim_window_size", type=int, default=11)
788
+ parser.add_argument("--val_ssim", action="store_true", default=False)
789
+ parser.add_argument("--pixel_loss_crop_size", type=int, default=400)
790
+ parser.add_argument("--pixel_loss_latent_frames", type=int, default=3)
791
+ parser.add_argument("--val_lpips", action="store_true", default=False)
792
+ parser.add_argument("--wavelet_hf_weight", type=float, default=50.0)
793
+ parser.add_argument("--wavelet_hf_levels", type=int, default=1)
794
+ parser.add_argument("--wavelet_hf_loss", choices=["l1", "l2"], default="l1")
795
+ parser.add_argument("--val_wavelet_hf_loss", action="store_true", default=False)
796
+ parser.add_argument("--pixel_loss_weight", type=float, default=4.0)
797
+ parser.add_argument("--val_inference_steps", type=int, default=1)
798
+ parser.add_argument("--val_sampling_noise_scale", type=float, default=1.0)
799
+ parser.add_argument("--val_sigma_shift", type=float, default=5.0)
800
+ parser.add_argument("--max_timestep_boundary", type=float, default=0.9999)
801
+ parser.add_argument("--min_timestep_boundary", type=float, default=0.0001)
802
+ parser.add_argument("--text_drop_probability", type=float, default=0.0)
803
+ parser.add_argument(
804
+ "--anchor_each_step",
805
+ action=argparse.BooleanOptionalAction,
806
+ default=True,
807
+ help="Compatibility flag. This chunked TI2V trainer always keeps reference/history clean and re-locks them every step.",
808
+ )
809
+ parser.add_argument("--use_gradient_checkpointing", action="store_true", default=True)
810
+ parser.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False)
811
+ parser.add_argument("--find_unused_parameters", action="store_true", default=False)
812
+ parser.add_argument("--tiled", action="store_true", default=False)
813
+ parser.add_argument("--tile_h", type=int, default=30)
814
+ parser.add_argument("--tile_w", type=int, default=52)
815
+ parser.add_argument("--tile_stride_h", type=int, default=15)
816
+ parser.add_argument("--tile_stride_w", type=int, default=26)
817
+ parser.add_argument("--seed", type=int, default=42)
818
+ args = parser.parse_args()
819
+ if not args.anchor_each_step:
820
+ raise ValueError("Wan2.2-TI2V clean-history chunk training requires --anchor_each_step")
821
+ if args.model_paths is None:
822
+ args.model_paths = default_model_paths(args.base_model_dir)
823
+ return args
824
+
825
+
826
+ if __name__ == "__main__":
827
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
828
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ ARGS=(
13
+ diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v.py
14
+ --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \
15
+ --tokenizer_path "${TOKENIZER_PATH:-/cache/Wan2.2-TI2V-5B/google/umt5-xxl}" \
16
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
17
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
18
+ --output_root "${OUTPUT_ROOT:-/cache/rongxiang/outputs_chunkbridge_wan22_ti2v_sr}" \
19
+ --height "${HEIGHT:-480}" \
20
+ --width "${WIDTH:-832}" \
21
+ --num_frames "${NUM_FRAMES:-81}" \
22
+ --chunk_latent_frames "${CHUNK_LATENT_FRAMES:-4}" \
23
+ --history_latent_frames "${HISTORY_LATENT_FRAMES:-2}" \
24
+ --sr_scale "${SR_SCALE:-2}" \
25
+ --dataset_repeat "${DATASET_REPEAT:-1}" \
26
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-0}" \
27
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
28
+ --learning_rate "${LEARNING_RATE:-1.0}" \
29
+ --weight_decay "${WEIGHT_DECAY:-0.01}" \
30
+ --d_coef "${D_COEF:-1.0}" \
31
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \
32
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
33
+ --lpips_net "${LPIPS_NET:-vgg}" \
34
+ --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}" \
35
+ --lpips_crop_size "${LPIPS_CROP_SIZE:-400}" \
36
+ --ssim_weight "${SSIM_WEIGHT:-1.0}" \
37
+ --ssim_window_size "${SSIM_WINDOW_SIZE:-11}" \
38
+ --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \
39
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \
40
+ --wavelet_hf_weight "${WAVELET_HF_WEIGHT:-0.0}" \
41
+ --wavelet_hf_levels "${WAVELET_HF_LEVELS:-1}" \
42
+ --wavelet_hf_loss "${WAVELET_HF_LOSS:-l1}" \
43
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-4.0}" \
44
+ --noise_sigma "${NOISE_SIGMA:-1.0}" \
45
+ --val_interval "${VAL_INTERVAL:-100}" \
46
+ --val_batches "${VAL_BATCHES:-1}" \
47
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-8}" \
48
+ --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}" \
49
+ --save_steps "${SAVE_STEPS:-500}" \
50
+ --validate_at_start
51
+ )
52
+
53
+ if [[ -n "${LIMIT_VIDEOS:-}" ]]; then
54
+ ARGS+=(--limit_videos "${LIMIT_VIDEOS}")
55
+ fi
56
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
57
+ ARGS+=(--output_path "${OUTPUT_PATH}")
58
+ fi
59
+
60
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train a Wan2.1 Brownian bridge for tiny-ditto video editing.
2
+
3
+ The clean edited clip is the bridge target. The coarse edited clip is the
4
+ bridge source. Original reference latents are concatenated with the current
5
+ bridge latents along channels; there is no reference token prefix.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import copy
12
+ import json
13
+ import os
14
+ import random
15
+ import sys
16
+ from collections import Counter
17
+ from pathlib import Path
18
+
19
+ import imageio
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from accelerate import Accelerator
24
+ from accelerate.utils import DistributedDataParallelKwargs
25
+ from PIL import Image
26
+ from torch.utils.data import DataLoader, Dataset
27
+ from tqdm import tqdm
28
+
29
+ REPO_ROOT = Path(__file__).resolve().parents[4]
30
+ if str(REPO_ROOT) not in sys.path:
31
+ sys.path.insert(0, str(REPO_ROOT))
32
+
33
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline
34
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import ( # noqa: E402
35
+ center_crop_resize,
36
+ crop_latent_pair_for_pixel_losses,
37
+ crop_original_rgb_for_latent_crop,
38
+ decode_latents_to_btchw_01,
39
+ lpips_video_loss,
40
+ make_lr_source,
41
+ pil_video_to_tensor_01,
42
+ tensor_btchw_01_to_pil,
43
+ )
44
+ from diffsynth.data.video import save_video # noqa: E402
45
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger # noqa: E402
46
+ from diffsynth.utils import ModelConfig # noqa: E402
47
+
48
+ try:
49
+ import torch_npu # noqa: F401
50
+ except ModuleNotFoundError:
51
+ torch_npu = None
52
+
53
+
54
+ def format_run_value(value: object) -> str:
55
+ text = f"{value:g}" if isinstance(value, float) else str(value)
56
+ return text.replace(".", "p").replace("-", "m").replace("/", "_")
57
+
58
+
59
+ def default_model_paths(base_model_dir: str) -> str:
60
+ base = Path(base_model_dir)
61
+ dit = base / "diffusion_pytorch_model.safetensors.index.json"
62
+ if not dit.exists():
63
+ dit = base / "diffusion_pytorch_model.safetensors"
64
+ paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.1_VAE.pth"]
65
+ missing = [str(p) for p in paths if not p.exists()]
66
+ if missing:
67
+ raise FileNotFoundError("Missing Wan2.1-T2V files: " + ", ".join(missing))
68
+ return ",".join(str(p) for p in paths)
69
+
70
+
71
+ def load_dit_init_state(path: str | os.PathLike) -> dict[str, torch.Tensor]:
72
+ checkpoint = torch.load(path, map_location="cpu", weights_only=False)
73
+ if isinstance(checkpoint, dict) and "model" in checkpoint:
74
+ checkpoint = checkpoint["model"]
75
+ elif isinstance(checkpoint, dict) and "state_dict" in checkpoint:
76
+ checkpoint = checkpoint["state_dict"]
77
+ if not isinstance(checkpoint, dict) or not all(torch.is_tensor(value) for value in checkpoint.values()):
78
+ raise ValueError(f"Unsupported DiT initialization checkpoint: {path}")
79
+ return {
80
+ str(key).removeprefix("module.").removeprefix("model."): value
81
+ for key, value in checkpoint.items()
82
+ }
83
+
84
+
85
+ def configure_dit_channel_concat(pipe, checkpoint_path: str | None) -> None:
86
+ """Load UltraFlash's 32-channel weights for [bridge latent, reference]."""
87
+ dit = pipe.dit
88
+ current_in_dim = int(getattr(dit, "in_dim", 0))
89
+ if current_in_dim != 32:
90
+ if current_in_dim != 16:
91
+ raise RuntimeError(
92
+ f"Expected a 16-channel Wan DiT before adaptation, got in_dim={current_in_dim}"
93
+ )
94
+ old_embedding = dit.patch_embedding
95
+ new_embedding = torch.nn.Conv3d(
96
+ 32,
97
+ old_embedding.out_channels,
98
+ kernel_size=old_embedding.kernel_size,
99
+ stride=old_embedding.stride,
100
+ padding=old_embedding.padding,
101
+ dilation=old_embedding.dilation,
102
+ groups=old_embedding.groups,
103
+ bias=old_embedding.bias is not None,
104
+ ).to(device=old_embedding.weight.device, dtype=old_embedding.weight.dtype)
105
+ with torch.no_grad():
106
+ new_embedding.weight[:, :16].copy_(old_embedding.weight)
107
+ new_embedding.weight[:, 16:].copy_(old_embedding.weight)
108
+ if old_embedding.bias is not None:
109
+ new_embedding.bias.copy_(old_embedding.bias)
110
+ dit.patch_embedding = new_embedding
111
+ dit.in_dim = 32
112
+ if checkpoint_path:
113
+ init_state = load_dit_init_state(checkpoint_path)
114
+ result = dit.load_state_dict(init_state, strict=True)
115
+ if result.missing_keys or result.unexpected_keys:
116
+ raise RuntimeError(
117
+ f"DiT initialization mismatch for {checkpoint_path}: "
118
+ f"missing={result.missing_keys[:8]}, unexpected={result.unexpected_keys[:8]}"
119
+ )
120
+ print(f"[TinyDittoEdit] loaded 32-channel DiT initialization: {checkpoint_path}", flush=True)
121
+
122
+
123
+ def normalize_wan_num_frames(num_frames: int) -> int:
124
+ num_frames = max(int(num_frames), 1)
125
+ if num_frames % 4 == 1:
126
+ return num_frames
127
+ return ((num_frames - 1 + 3) // 4) * 4 + 1
128
+
129
+
130
+ def resolve_media_path(root: Path, rel_path: str, recursive_fallback: bool = True) -> Path:
131
+ path = Path(rel_path)
132
+ if path.is_absolute() and path.exists():
133
+ return path
134
+ candidate = root / path
135
+ if candidate.exists():
136
+ return candidate
137
+ if not recursive_fallback:
138
+ raise FileNotFoundError(f"Missing tiny-ditto media file: {candidate}")
139
+ matches = sorted(root.rglob(path.name))
140
+ if matches:
141
+ preferred = [match for match in matches if path.parts and path.parts[0] in match.parts]
142
+ return preferred[0] if preferred else matches[0]
143
+ raise FileNotFoundError(f"Missing tiny-ditto media file: {candidate}")
144
+
145
+
146
+ def load_tiny_ditto_manifest(
147
+ manifest_path: str,
148
+ limit: int | None = None,
149
+ dataset_root: str | Path | None = None,
150
+ ) -> list[dict]:
151
+ path = Path(manifest_path)
152
+ if not path.exists():
153
+ raise FileNotFoundError(f"Missing tiny-ditto manifest: {path}")
154
+
155
+ if path.is_dir():
156
+ root = Path(dataset_root) if dataset_root is not None else None
157
+ videos_dir = root / "videos" if root is not None else None
158
+ if videos_dir is not None and videos_dir.is_dir():
159
+ # GOKU ships metadata for more cases than may be extracted locally.
160
+ # Build the manifest list from available case directories so missing
161
+ # archives never trigger repeated recursive media searches.
162
+ manifest_files = [
163
+ path / f"{case_dir.name}_all.json"
164
+ for case_dir in sorted(videos_dir.iterdir())
165
+ if case_dir.is_dir()
166
+ and (case_dir / "source.mp4").is_file()
167
+ and (case_dir / "edited.mp4").is_file()
168
+ ]
169
+ manifest_files = [manifest_file for manifest_file in manifest_files if manifest_file.is_file()]
170
+ else:
171
+ manifest_files = sorted(path.rglob("*.json"))
172
+ if not manifest_files:
173
+ raise FileNotFoundError(f"No JSON manifests found under {path}")
174
+ if limit is not None:
175
+ manifest_files = manifest_files[: max(int(limit), 0)]
176
+ items = []
177
+ for manifest_file in manifest_files:
178
+ value = json.loads(manifest_file.read_text(encoding="utf-8"))
179
+ if isinstance(value, list):
180
+ items.extend(value)
181
+ elif isinstance(value, dict):
182
+ items.append(value)
183
+ elif path.suffix.lower() == ".jsonl":
184
+ items = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
185
+ else:
186
+ items = json.loads(path.read_text(encoding="utf-8"))
187
+ if isinstance(items, dict):
188
+ items = [items]
189
+ if not isinstance(items, list):
190
+ raise ValueError(f"tiny-ditto manifest must contain JSON objects or a list: {path}")
191
+ samples = []
192
+ for item in items:
193
+ if not isinstance(item, dict):
194
+ continue
195
+ source_path = item.get("source_path") or item.get("source_video")
196
+ edited_path = item.get("edited_path") or item.get("edited_video")
197
+ instruction = str(
198
+ item.get("instruction")
199
+ or item.get("prompt")
200
+ or item.get("instruction_en")
201
+ or item.get("instruction_cn")
202
+ or ""
203
+ ).strip()
204
+ if source_path and edited_path:
205
+ samples.append(
206
+ {
207
+ "source_path": str(source_path),
208
+ "edited_path": str(edited_path),
209
+ "instruction": instruction,
210
+ "task": str(item.get("task") or item.get("category") or "unknown").strip() or "unknown",
211
+ }
212
+ )
213
+ if not samples:
214
+ raise ValueError(f"No valid source/edited pairs found in {path}")
215
+ return samples
216
+
217
+
218
+ def probe_video_readable(path: Path) -> bool:
219
+ try:
220
+ reader = imageio.get_reader(str(path))
221
+ except (OSError, RuntimeError, ValueError):
222
+ return False
223
+ try:
224
+ reader.get_data(0)
225
+ return True
226
+ except (OSError, RuntimeError, ValueError):
227
+ return False
228
+ finally:
229
+ reader.close()
230
+
231
+
232
+ def read_video_clip(path: Path, height: int, width: int, num_frames: int, start: int) -> list[Image.Image]:
233
+ reader = imageio.get_reader(str(path))
234
+ frames = []
235
+ last = None
236
+ try:
237
+ for frame_id in range(start, start + num_frames):
238
+ try:
239
+ array = reader.get_data(frame_id)
240
+ last = array
241
+ except Exception:
242
+ if last is None:
243
+ break
244
+ array = last
245
+ image = Image.fromarray(np.asarray(array)).convert("RGB")
246
+ frames.append(center_crop_resize(image, height, width))
247
+ finally:
248
+ reader.close()
249
+ if not frames:
250
+ raise RuntimeError(f"No frames decoded from {path}")
251
+ while len(frames) < num_frames:
252
+ frames.append(frames[-1].copy())
253
+ return frames
254
+
255
+
256
+ class TinyDittoEditDataset(Dataset):
257
+ def __init__(
258
+ self,
259
+ dataset_root: str,
260
+ manifest_path: str,
261
+ height: int,
262
+ width: int,
263
+ num_frames: int,
264
+ sr_scale: int,
265
+ default_prompt: str = "",
266
+ repeat: int = 1,
267
+ limit_samples: int | None = None,
268
+ seed: int = 0,
269
+ ) -> None:
270
+ self.dataset_root = Path(dataset_root)
271
+ self.height = int(height)
272
+ self.width = int(width)
273
+ self.num_frames = int(num_frames)
274
+ self.sr_scale = int(sr_scale)
275
+ self.default_prompt = default_prompt
276
+ self.repeat = int(repeat)
277
+ self.rng = random.Random(seed)
278
+ manifest_path_obj = Path(manifest_path)
279
+ samples = load_tiny_ditto_manifest(
280
+ manifest_path,
281
+ limit=limit_samples,
282
+ dataset_root=self.dataset_root,
283
+ )
284
+ self.samples = []
285
+ missing_samples = 0
286
+ task_counts = Counter()
287
+ missing_examples = []
288
+ for sample in samples:
289
+ try:
290
+ # The OpenVE manifest stores paths relative to dataset_root.
291
+ # Keep the fallback for older per-case GOKU manifests.
292
+ source_path = resolve_media_path(self.dataset_root, sample["source_path"])
293
+ edited_path = resolve_media_path(self.dataset_root, sample["edited_path"])
294
+ except FileNotFoundError:
295
+ missing_samples += 1
296
+ if len(missing_examples) < 3:
297
+ missing_examples.append(
298
+ (sample["source_path"], sample["edited_path"])
299
+ )
300
+ continue
301
+ task = sample.get("task", "unknown")
302
+ task_counts[task] += 1
303
+ self.samples.append(
304
+ {
305
+ "source_path": source_path,
306
+ "edited_path": edited_path,
307
+ "instruction": sample["instruction"] or self.default_prompt,
308
+ "task": task,
309
+ }
310
+ )
311
+ if missing_samples:
312
+ print(
313
+ f"[TinyDittoEditDataset] skipped {missing_samples} samples with missing media; "
314
+ f"examples={missing_examples}",
315
+ flush=True,
316
+ )
317
+ self.rng.shuffle(self.samples)
318
+ if limit_samples is not None:
319
+ self.samples = self.samples[: int(limit_samples)]
320
+ if not self.samples:
321
+ raise FileNotFoundError(f"No tiny-ditto pairs found under {self.dataset_root}")
322
+ if manifest_path_obj.name == "metadata.json" and (self.dataset_root / ".complete").is_file():
323
+ summary_path = self.dataset_root / "summary.json"
324
+ if summary_path.is_file():
325
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
326
+ expected = int(summary.get("num_samples", len(samples)))
327
+ if limit_samples is None and expected != len(samples):
328
+ raise ValueError(
329
+ f"Dataset summary expects {expected} samples but manifest has {len(samples)}: "
330
+ f"{manifest_path_obj}"
331
+ )
332
+ print(
333
+ f"[TinyDittoEditDataset] OpenVE tasks={dict(sorted(task_counts.items()))}",
334
+ flush=True,
335
+ )
336
+ else:
337
+ print(
338
+ f"[TinyDittoEditDataset] warning: missing dataset summary {summary_path}",
339
+ flush=True,
340
+ )
341
+ print(
342
+ f"[TinyDittoEditDataset] manifest_entries={len(samples)}, "
343
+ f"usable_pairs={len(self.samples)}, repeat={self.repeat}, "
344
+ f"root={self.dataset_root}, manifest={manifest_path_obj}",
345
+ flush=True,
346
+ )
347
+
348
+ def __len__(self) -> int:
349
+ return len(self.samples) * self.repeat
350
+
351
+ def __getitem__(self, idx: int) -> dict:
352
+ for attempt in range(len(self.samples)):
353
+ sample = self.samples[(idx + attempt) % len(self.samples)]
354
+ # GOKU clips are already short clips. Avoid full-frame-count probing
355
+ # here because imageio's count_frames launches a complete FFmpeg scan.
356
+ start = 0
357
+ try:
358
+ reference_video = read_video_clip(sample["source_path"], self.height, self.width, self.num_frames, start)
359
+ target_video = read_video_clip(sample["edited_path"], self.height, self.width, self.num_frames, start)
360
+ except (OSError, RuntimeError, ValueError):
361
+ continue
362
+ source_video = [
363
+ make_lr_source(frame, self.height, self.width, self.sr_scale, upsample_to_hr=False)
364
+ for frame in target_video
365
+ ]
366
+ return {
367
+ "video": target_video,
368
+ "source_video": source_video,
369
+ "reference_video": reference_video,
370
+ "prompt": sample["instruction"] or self.default_prompt,
371
+ "task": sample.get("task", "unknown"),
372
+ "source_path": str(sample["source_path"]),
373
+ "edited_path": str(sample["edited_path"]),
374
+ }
375
+ raise RuntimeError(f"No readable video pair found while loading dataset index {idx}")
376
+
377
+
378
+ def ssim_video_loss(pred_btchw_01: torch.Tensor, target_btchw_01: torch.Tensor, window_size: int = 11) -> torch.Tensor:
379
+ min_t = min(pred_btchw_01.shape[1], target_btchw_01.shape[1])
380
+ if min_t <= 0:
381
+ return pred_btchw_01.new_tensor(0.0)
382
+ pred = pred_btchw_01[:, :min_t].reshape(-1, *pred_btchw_01.shape[2:]).float()
383
+ target = target_btchw_01[:, :min_t].reshape(-1, *target_btchw_01.shape[2:]).float()
384
+ channels = pred.shape[1]
385
+ window_size = max(1, int(window_size))
386
+ if window_size % 2 == 0:
387
+ window_size += 1
388
+ padding = window_size // 2
389
+ weight = pred.new_ones((channels, 1, window_size, window_size)) / float(window_size * window_size)
390
+ mu_x = F.conv2d(pred, weight, padding=padding, groups=channels)
391
+ mu_y = F.conv2d(target, weight, padding=padding, groups=channels)
392
+ mu_x_sq = mu_x.square()
393
+ mu_y_sq = mu_y.square()
394
+ mu_xy = mu_x * mu_y
395
+ sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x_sq
396
+ sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y_sq
397
+ sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy
398
+ c1 = 0.01**2
399
+ c2 = 0.03**2
400
+ ssim = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / (
401
+ (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + 1e-8
402
+ )
403
+ return (1.0 - ssim.clamp(-1.0, 1.0)).mean()
404
+
405
+
406
+ def align_noise_to_latents(noise: torch.Tensor, latents: torch.Tensor) -> torch.Tensor:
407
+ if noise.shape[:2] != latents.shape[:2] or noise.shape[-2:] != latents.shape[-2:]:
408
+ raise ValueError(
409
+ f"Noise shape {tuple(noise.shape)} is incompatible with latents {tuple(latents.shape)}"
410
+ )
411
+ if noise.shape[2] == latents.shape[2]:
412
+ return noise.to(device=latents.device, dtype=latents.dtype)
413
+ if noise.shape[2] > latents.shape[2]:
414
+ noise = noise[:, :, : latents.shape[2]]
415
+ else:
416
+ tail = torch.randn(
417
+ (*noise.shape[:2], latents.shape[2] - noise.shape[2], *noise.shape[-2:]),
418
+ device=noise.device,
419
+ dtype=noise.dtype,
420
+ )
421
+ noise = torch.cat([noise, tail], dim=2)
422
+ return noise.to(device=latents.device, dtype=latents.dtype)
423
+
424
+
425
+ def resize_latents_to_match(source_latents: torch.Tensor, target_latents: torch.Tensor) -> torch.Tensor:
426
+ if source_latents.shape == target_latents.shape:
427
+ return source_latents
428
+ if source_latents.shape[:2] != target_latents.shape[:2]:
429
+ raise ValueError(
430
+ f"Cannot resize latents with different batch/channel shapes: "
431
+ f"{tuple(source_latents.shape)} vs {tuple(target_latents.shape)}"
432
+ )
433
+ resized = F.interpolate(
434
+ source_latents.float(),
435
+ size=(target_latents.shape[2], target_latents.shape[3], target_latents.shape[4]),
436
+ mode="trilinear",
437
+ align_corners=False,
438
+ )
439
+ return resized.to(device=target_latents.device, dtype=target_latents.dtype)
440
+
441
+
442
+ def ensure_module_device(module: torch.nn.Module | None, device: torch.device) -> torch.nn.Module | None:
443
+ if module is None:
444
+ return None
445
+ param = next(module.parameters(), None)
446
+ buffer = next(module.buffers(), None)
447
+ current_device = param.device if param is not None else buffer.device if buffer is not None else None
448
+ if current_device != device:
449
+ module = module.to(device=device)
450
+ return module
451
+
452
+
453
+ def concat_pil_clips(clips: list[list[Image.Image]]) -> list[Image.Image]:
454
+ if not clips:
455
+ return []
456
+ frame_count = min(len(clip) for clip in clips)
457
+ out = []
458
+ for frame_idx in range(frame_count):
459
+ frames = [clip[frame_idx].convert("RGB") for clip in clips]
460
+ width = sum(frame.width for frame in frames)
461
+ height = max(frame.height for frame in frames)
462
+ canvas = Image.new("RGB", (width, height))
463
+ offset = 0
464
+ for frame in frames:
465
+ canvas.paste(frame, (offset, 0))
466
+ offset += frame.width
467
+ out.append(canvas)
468
+ return out
469
+
470
+
471
+ def build_run_name(args) -> str:
472
+ manifest_name = Path(args.manifest_path).stem
473
+ parts = [
474
+ "wan21_t2v_edit",
475
+ manifest_name,
476
+ f"concat",
477
+ f"x{args.sr_scale}",
478
+ f"{args.height}x{args.width}",
479
+ f"f{args.num_frames}",
480
+ f"lr{format_run_value(args.learning_rate)}",
481
+ f"noise{format_run_value(args.noise_sigma)}",
482
+ f"bridge{format_run_value(args.bridge_loss_weight)}",
483
+ f"lpips{format_run_value(args.lpips_weight)}",
484
+ f"ssim{format_run_value(args.ssim_weight)}",
485
+ f"pix{format_run_value(args.pixel_loss_weight)}",
486
+ f"pcrop{args.pixel_loss_crop_size}",
487
+ f"plf{args.pixel_loss_latent_frames}",
488
+ f"seed{args.seed}",
489
+ ]
490
+ return "_".join(parts)
491
+
492
+
493
+ class TinyDittoEditBridgePipeline(WanVideoBridgePipeline):
494
+ def training_loss(self, **inputs):
495
+ min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0.0) * self.scheduler.num_train_timesteps)
496
+ max_timestep_boundary = int(inputs.get("max_timestep_boundary", 0.9999) * self.scheduler.num_train_timesteps)
497
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
498
+ timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device)
499
+
500
+ x0 = inputs["input_latents"]
501
+ x1 = inputs["source_latents"]
502
+ noise = align_noise_to_latents(inputs["noise"], x0)
503
+ xt = self.scheduler.add_noise(x0, x1, noise, timestep)
504
+ target = self.scheduler.training_target(x0, xt, timestep)
505
+
506
+ model_inputs = dict(inputs)
507
+ model_inputs["latents"] = xt
508
+ model_inputs["input_latents"] = x0
509
+ model_inputs["source_latents"] = x1
510
+ model_inputs.pop("reference_latents", None)
511
+ model_inputs["token_prefix_latents"] = None
512
+ model_inputs["condition_latents"] = inputs["original_latents"].detach()
513
+ model_inputs["channel_concat_condition"] = True
514
+ model_output = self.model_fn(**model_inputs, timestep=timestep)
515
+
516
+ sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
517
+ if self.scheduler.target == "stabilized_drift":
518
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)).sqrt()
519
+ velocity_target = target / factor
520
+ endpoint = xt.float() - sigma * (model_output.float() * factor)
521
+ elif self.scheduler.target == "drift":
522
+ velocity_target = target
523
+ endpoint = xt.float() - sigma * model_output.float()
524
+ else:
525
+ raise ValueError(f"Unsupported target: {self.scheduler.target}")
526
+
527
+ bridge_loss = F.mse_loss(model_output.float(), velocity_target.float())
528
+ total = float(inputs.get("bridge_loss_weight", 1.0)) * bridge_loss
529
+ metrics = {"bridge_loss": float(bridge_loss.detach()), "pixel_loss": 0.0, "lpips_loss": 0.0, "ssim_loss": 0.0}
530
+
531
+ pixel_weight = float(inputs.get("pixel_loss_weight", 0.0))
532
+ lpips_weight = float(inputs.get("lpips_weight", 0.0))
533
+ ssim_weight = float(inputs.get("ssim_weight", 0.0))
534
+ if pixel_weight > 0 or lpips_weight > 0 or ssim_weight > 0:
535
+ pred_cropped, _, crop_info = crop_latent_pair_for_pixel_losses(
536
+ endpoint,
537
+ x0,
538
+ int(inputs.get("pixel_loss_crop_size", 400)),
539
+ int(inputs.get("pixel_loss_latent_frames", 3)),
540
+ int(getattr(self.vae, "upsampling_factor", 16)),
541
+ return_crop_info=True,
542
+ )
543
+ pred_video = decode_latents_to_btchw_01(
544
+ self,
545
+ pred_cropped,
546
+ bool(inputs.get("tiled", False)),
547
+ inputs.get("tile_size", (30, 52)),
548
+ inputs.get("tile_stride", (15, 26)),
549
+ )
550
+ raw_target = inputs.get("raw_target_video")
551
+ if raw_target is None:
552
+ raise ValueError("raw_target_video is required for pixel losses")
553
+ target_video = crop_original_rgb_for_latent_crop(raw_target, crop_info, pred_video, self.device)
554
+ if pred_video.shape != target_video.shape:
555
+ raise RuntimeError(f"Prediction shape {tuple(pred_video.shape)} != target shape {tuple(target_video.shape)}")
556
+ if pixel_weight > 0:
557
+ value = F.mse_loss(pred_video.float(), target_video.float())
558
+ total = total + pixel_weight * value
559
+ metrics["pixel_loss"] = float(value.detach())
560
+ if lpips_weight > 0:
561
+ lpips_model = ensure_module_device(inputs.get("lpips_model"), pred_video.device)
562
+ value = lpips_video_loss(
563
+ lpips_model,
564
+ pred_video,
565
+ target_video,
566
+ int(inputs.get("lpips_num_frames", 4)),
567
+ int(inputs.get("lpips_crop_size", 224)),
568
+ )
569
+ total = total + lpips_weight * value
570
+ metrics["lpips_loss"] = float(value.detach())
571
+ if ssim_weight > 0:
572
+ value = ssim_video_loss(pred_video, target_video, int(inputs.get("ssim_window_size", 11)))
573
+ total = total + ssim_weight * value
574
+ metrics["ssim_loss"] = float(value.detach())
575
+ return total, metrics
576
+
577
+
578
+ class TinyDittoEditTrainingModule(DiffusionTrainingModule):
579
+ def __init__(self, args) -> None:
580
+ super().__init__()
581
+ configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
582
+ self.pipe = TinyDittoEditBridgePipeline.from_pretrained(
583
+ torch_dtype=args.torch_dtype,
584
+ device="cpu",
585
+ model_configs=configs,
586
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
587
+ )
588
+ self.pipe.requires_grad_(False)
589
+ self.pipe.latent_upsampler = None
590
+ configure_dit_channel_concat(self.pipe, args.dit_init_checkpoint)
591
+ dit_in_dim = int(getattr(self.pipe.dit, "in_dim", 0))
592
+ vae_z_dim = int(getattr(self.pipe.vae, "z_dim", 0))
593
+ if dit_in_dim != 32 or vae_z_dim != 16:
594
+ raise RuntimeError(
595
+ "Expected a 32-channel concatenated DiT and 16-channel Wan2.1 VAE, "
596
+ f"got dit.in_dim={dit_in_dim}, vae.z_dim={vae_z_dim}"
597
+ )
598
+ self.pipe.scheduler.noise_scale = args.noise_sigma
599
+ self.pipe.scheduler.bridge_type = "brownian"
600
+ self.pipe.scheduler.training_weight_type = args.training_weight_type
601
+ self.pipe.scheduler.target = args.target
602
+ self.switch_pipe_to_training_mode(
603
+ self.pipe,
604
+ args.trainable_models,
605
+ args.lora_base_model,
606
+ args.lora_target_modules,
607
+ args.lora_rank,
608
+ lora_checkpoint=args.lora_checkpoint,
609
+ enable_fp8_training=False,
610
+ )
611
+ self.args = args
612
+ if args.lpips_weight > 0 or args.val_lpips:
613
+ import lpips
614
+
615
+ self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False)
616
+ else:
617
+ self.lpips_model = None
618
+
619
+ def to(self, *args, **kwargs):
620
+ super().to(*args, **kwargs)
621
+ if self.lpips_model is not None:
622
+ self.lpips_model = self.lpips_model.to(*args, **kwargs)
623
+ return self
624
+
625
+ @torch.no_grad()
626
+ def encode_reference(self, frames: list[Image.Image]) -> torch.Tensor:
627
+ self.pipe.load_models_to_device(["vae"])
628
+ video = self.pipe.preprocess_video(frames)
629
+ latents = self.pipe.vae.encode(
630
+ video,
631
+ device=self.pipe.device,
632
+ tiled=self.args.tiled,
633
+ tile_size=(self.args.tile_h, self.args.tile_w),
634
+ tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w),
635
+ )
636
+ return latents.to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
637
+
638
+ def forward_preprocess(self, data: dict) -> dict:
639
+ self.pipe.scheduler.set_timesteps(1000, training=True)
640
+ shared = {
641
+ "input_video": data["video"],
642
+ "source_video": data["source_video"],
643
+ "height": data["video"][0].height,
644
+ "width": data["video"][0].width,
645
+ "num_frames": len(data["video"]),
646
+ "cfg_scale": 1,
647
+ "cfg_merge": False,
648
+ "tiled": self.args.tiled,
649
+ "tile_size": (self.args.tile_h, self.args.tile_w),
650
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
651
+ "rand_device": "cpu" if str(self.pipe.device).startswith("npu") else self.pipe.device,
652
+ "seed": None,
653
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
654
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
655
+ # All prediction tokens use the bridge timestep. Reference is a
656
+ # channel condition, with no separate token/timestep stream.
657
+ "fuse_vae_embedding_in_latents": False,
658
+ "token_prefix_clean_timestep": False,
659
+ "token_prefix_aligned_rope": False,
660
+ "token_prefix_block_self_attention": False,
661
+ "clean_history_latent_frames": 0,
662
+ "bridge_loss_weight": self.args.bridge_loss_weight,
663
+ "pixel_loss_weight": self.args.pixel_loss_weight,
664
+ "lpips_weight": self.args.lpips_weight,
665
+ "lpips_model": self.lpips_model,
666
+ "lpips_num_frames": self.args.lpips_num_frames,
667
+ "lpips_crop_size": self.args.lpips_crop_size,
668
+ "ssim_weight": self.args.ssim_weight,
669
+ "ssim_window_size": self.args.ssim_window_size,
670
+ "pixel_loss_crop_size": self.args.pixel_loss_crop_size,
671
+ "pixel_loss_latent_frames": self.args.pixel_loss_latent_frames,
672
+ "min_timestep_boundary": self.args.min_timestep_boundary,
673
+ "max_timestep_boundary": self.args.max_timestep_boundary,
674
+ "raw_target_video": data["video"],
675
+ }
676
+ pos, neg = {"prompt": data["prompt"]}, {}
677
+ for unit in self.pipe.units:
678
+ shared, pos, neg = self.pipe.unit_runner(unit, self.pipe, shared, pos, neg)
679
+ # Re-assert channel-only conditioning after all pipeline units.
680
+ shared["fuse_vae_embedding_in_latents"] = False
681
+ shared["token_prefix_clean_timestep"] = False
682
+ shared["token_prefix_aligned_rope"] = False
683
+ shared["token_prefix_block_self_attention"] = False
684
+ shared["original_latents"] = self.encode_reference(data["reference_video"])
685
+ shared["source_latents"] = resize_latents_to_match(
686
+ shared["source_latents"], shared["input_latents"]
687
+ )
688
+ return {**shared, **pos}
689
+
690
+ def forward(self, data: dict, inputs: dict | None = None):
691
+ inputs = self.forward_preprocess(data) if inputs is None else inputs
692
+ return self.pipe.training_loss(**{n: getattr(self.pipe, n) for n in self.pipe.in_iteration_models}, **inputs)
693
+
694
+
695
+ @torch.no_grad()
696
+ def sample_edit(pipe, inputs, args):
697
+ source = inputs["source_latents"]
698
+ latents = source.clone()
699
+ pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift)
700
+ pipe.load_models_to_device(pipe.in_iteration_models)
701
+ models = {n: getattr(pipe, n) for n in pipe.in_iteration_models}
702
+ model_inputs = dict(inputs)
703
+ model_inputs.pop("latents", None)
704
+ model_inputs.pop("original_latents", None)
705
+ model_inputs.pop("reference_latents", None)
706
+ model_inputs["token_prefix_latents"] = None
707
+ model_inputs["token_prefix_block_self_attention"] = False
708
+ model_inputs["condition_latents"] = inputs["original_latents"].detach()
709
+ model_inputs["channel_concat_condition"] = True
710
+ for timestep_cpu in pipe.scheduler.timesteps:
711
+ timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype)
712
+ pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep)
713
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, source)
714
+ return latents
715
+
716
+
717
+ def build_dataset(args, repeat, limit, seed):
718
+ return TinyDittoEditDataset(
719
+ dataset_root=args.dataset_root,
720
+ manifest_path=args.manifest_path,
721
+ height=args.height,
722
+ width=args.width,
723
+ num_frames=args.num_frames,
724
+ sr_scale=args.sr_scale,
725
+ default_prompt=args.default_prompt,
726
+ repeat=repeat,
727
+ limit_samples=limit,
728
+ seed=seed,
729
+ )
730
+
731
+
732
+ def build_validation_dataset(args):
733
+ """Build one deterministic validation subset with equal task coverage."""
734
+ dataset = build_dataset(args, repeat=1, limit=None, seed=args.seed + 1)
735
+ samples_per_task = max(int(args.val_samples_per_task), 1)
736
+ grouped = {}
737
+ for sample in dataset.samples:
738
+ grouped.setdefault(sample.get("task", "unknown"), []).append(sample)
739
+
740
+ selected = []
741
+ for task in sorted(grouped):
742
+ if task not in {"background_change", "camera_edit"}:
743
+ continue
744
+ task_samples = list(grouped[task])
745
+ task_seed = args.seed + 1009 * (sum(ord(char) for char in task) + 1)
746
+ random.Random(task_seed).shuffle(task_samples)
747
+ selected.extend(task_samples[:samples_per_task])
748
+ dataset.samples = selected
749
+ if not dataset.samples:
750
+ raise ValueError("No samples available for task-stratified validation")
751
+ print(
752
+ f"[TinyDittoEdit] validation samples/task={samples_per_task}, "
753
+ f"count={len(dataset.samples)}, "
754
+ f"tasks={dict(sorted(Counter(s.get('task', 'unknown') for s in dataset.samples).items()))}",
755
+ flush=True,
756
+ )
757
+ return dataset
758
+
759
+
760
+ @torch.no_grad()
761
+ def validate(args, accelerator, model, dataset, step):
762
+ if not accelerator.is_main_process:
763
+ return {}
764
+ module = accelerator.unwrap_model(model)
765
+ pipe = module.pipe
766
+ backup = pipe.scheduler
767
+ pipe.scheduler = copy.deepcopy(backup)
768
+ pipe.scheduler.noise_scale = args.val_sampling_noise_scale
769
+ pipe.scheduler.target = args.target
770
+ out = Path(args.output_path) / "validation" / f"step-{step:06d}"
771
+ out.mkdir(parents=True, exist_ok=True)
772
+ rows = []
773
+ for idx in range(len(dataset)):
774
+ data = dataset[idx]
775
+ task_out = out / Path(str(data.get("task", "unknown"))).name
776
+ task_out.mkdir(parents=True, exist_ok=True)
777
+ inputs = module.forward_preprocess(data)
778
+ pred_latent = sample_edit(pipe, inputs, args)
779
+ 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))
780
+ 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))
781
+ 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))
782
+ row = {
783
+ "idx": idx,
784
+ "task": data.get("task", "unknown"),
785
+ "latent_mse": F.mse_loss(pred_latent.float(), inputs["input_latents"].float()).item(),
786
+ "source_latent_mse": F.mse_loss(inputs["source_latents"].float(), inputs["input_latents"].float()).item(),
787
+ "pixel_mse": F.mse_loss(pred.float(), target.float()).item(),
788
+ }
789
+ if args.val_lpips and module.lpips_model is not None:
790
+ module.lpips_model = ensure_module_device(module.lpips_model, pred.device)
791
+ row["lpips"] = float(lpips_video_loss(module.lpips_model, pred, target, args.lpips_num_frames, args.lpips_crop_size))
792
+ if args.val_ssim or args.ssim_weight > 0:
793
+ row["ssim"] = float(ssim_video_loss(pred, target, args.ssim_window_size))
794
+ rows.append(row)
795
+ save_video(data["reference_video"], str(task_out / f"val_{idx:03d}_reference.mp4"), fps=args.fps, quality=5)
796
+ save_video(tensor_btchw_01_to_pil(source[0]), str(task_out / f"val_{idx:03d}_coarse.mp4"), fps=args.fps, quality=5)
797
+ save_video(tensor_btchw_01_to_pil(target[0]), str(task_out / f"val_{idx:03d}_target.mp4"), fps=args.fps, quality=5)
798
+ save_video(tensor_btchw_01_to_pil(pred[0]), str(task_out / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5)
799
+ comparison = concat_pil_clips([data["reference_video"], tensor_btchw_01_to_pil(pred[0])])
800
+ save_video(comparison, str(task_out / f"val_{idx:03d}_comparison.mp4"), fps=args.fps, quality=5)
801
+ metric_names = ["latent_mse", "source_latent_mse", "pixel_mse", "lpips", "ssim"]
802
+ metrics = {
803
+ f"val_{name}": sum(row[name] for row in rows if name in row) / sum(name in row for row in rows)
804
+ for name in metric_names
805
+ if rows and any(name in row for row in rows)
806
+ }
807
+ task_metrics = {}
808
+ for task in sorted({row["task"] for row in rows}):
809
+ task_rows = [row for row in rows if row["task"] == task]
810
+ task_metrics[task] = {
811
+ name: sum(row[name] for row in task_rows if name in row) / sum(name in row for row in task_rows)
812
+ for name in metric_names
813
+ if any(name in row for row in task_rows)
814
+ }
815
+ (out / "metrics.json").write_text(
816
+ json.dumps(
817
+ {
818
+ "step": step,
819
+ "rows": rows,
820
+ "metrics": metrics,
821
+ "task_metrics": task_metrics,
822
+ "pipeline": "tinyditto_edit_reference_concat",
823
+ "reference_concat": True,
824
+ },
825
+ indent=2,
826
+ ensure_ascii=False,
827
+ ),
828
+ encoding="utf-8",
829
+ )
830
+ print(f"[Validation step {step}] {metrics}", flush=True)
831
+ pipe.scheduler = backup
832
+ pipe.train()
833
+ return metrics
834
+
835
+
836
+ class Logger(ModelLogger):
837
+ pass
838
+
839
+
840
+ def parse_args():
841
+ p = argparse.ArgumentParser(description=__doc__)
842
+ p.add_argument("--base_model_dir", default="/cache/Wan2.1-T2V-1.3B")
843
+ p.add_argument("--model_paths", default=None)
844
+ p.add_argument("--lora_checkpoint", default=None)
845
+ p.add_argument("--dit_init_checkpoint", default=None)
846
+ p.add_argument("--tokenizer_path", default="/cache/Wan2.1-T2V-1.3B/google/umt5-xxl")
847
+ p.add_argument("--dataset_root", default="/cache/OpenVE-OneShard-5k")
848
+ p.add_argument("--manifest_path", default="/cache/OpenVE-OneShard-5k/metadata.json")
849
+ p.add_argument("--default_prompt", default="")
850
+ p.add_argument("--output_root", default="/cache/outputs_bridge_wan21_t2v_edit")
851
+ p.add_argument("--output_path", default=None)
852
+ p.add_argument("--height", type=int, default=480)
853
+ p.add_argument("--width", type=int, default=832)
854
+ p.add_argument("--num_frames", type=int, default=81)
855
+ p.add_argument("--sr_scale", type=int, default=2)
856
+ p.add_argument("--fps", type=int, default=20)
857
+ p.add_argument("--dataset_repeat", type=int, default=1)
858
+ p.add_argument("--limit_samples", type=int, default=None)
859
+ p.add_argument("--dataset_num_workers", type=int, default=0)
860
+ p.add_argument("--trainable_models", default="dit")
861
+ p.add_argument("--lora_base_model", default=None)
862
+ p.add_argument("--lora_target_modules", default="q,k,v,o,ffn.0,ffn.2")
863
+ p.add_argument("--lora_rank", type=int, default=32)
864
+ p.add_argument("--learning_rate", type=float, default=1.0)
865
+ p.add_argument("--weight_decay", type=float, default=0.01)
866
+ p.add_argument("--d_coef", type=float, default=1.0)
867
+ p.add_argument("--max_train_steps", type=int, default=5000)
868
+ p.add_argument("--gradient_accumulation_steps", type=int, default=1)
869
+ p.add_argument("--max_grad_norm", type=float, default=1.0)
870
+ p.add_argument("--save_steps", type=int, default=500)
871
+ p.add_argument("--log_interval", type=int, default=1)
872
+ p.add_argument("--val_interval", type=int, default=100)
873
+ p.add_argument("--val_samples_per_task", type=int, default=2)
874
+ p.add_argument("--validate_at_start", action="store_true")
875
+ p.add_argument("--validation_only", action="store_true")
876
+ p.add_argument("--noise_sigma", type=float, default=1.0)
877
+ p.add_argument("--val_sampling_noise_scale", type=float, default=0.0)
878
+ p.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
879
+ p.add_argument("--training_weight_type", default="uniform")
880
+ p.add_argument("--bridge_loss_weight", type=float, default=1.0)
881
+ p.add_argument("--pixel_loss_weight", type=float, default=4.0)
882
+ p.add_argument("--pixel_loss_crop_size", type=int, default=400)
883
+ p.add_argument("--pixel_loss_latent_frames", type=int, default=3)
884
+ p.add_argument("--lpips_weight", type=float, default=1.0)
885
+ p.add_argument("--lpips_net", choices=["alex", "vgg", "squeeze"], default="vgg")
886
+ p.add_argument("--lpips_num_frames", type=int, default=4)
887
+ p.add_argument("--lpips_crop_size", type=int, default=224)
888
+ p.add_argument("--ssim_weight", type=float, default=1.0)
889
+ p.add_argument("--ssim_window_size", type=int, default=11)
890
+ p.add_argument("--torch_dtype", choices=["float16", "bfloat16"], default="float16")
891
+ p.add_argument("--val_lpips", action="store_true")
892
+ p.add_argument("--val_ssim", action="store_true")
893
+ p.add_argument("--val_inference_steps", type=int, default=4)
894
+ p.add_argument("--val_sigma_shift", type=float, default=5.0)
895
+ p.add_argument("--min_timestep_boundary", type=float, default=0.0001)
896
+ p.add_argument("--max_timestep_boundary", type=float, default=0.9999)
897
+ p.add_argument("--use_gradient_checkpointing", action="store_true", default=True)
898
+ p.add_argument("--use_gradient_checkpointing_offload", action="store_true", default=False)
899
+ p.add_argument("--find_unused_parameters", action="store_true", default=False)
900
+ p.add_argument("--tiled", action="store_true")
901
+ p.add_argument("--tile_h", type=int, default=30)
902
+ p.add_argument("--tile_w", type=int, default=52)
903
+ p.add_argument("--tile_stride_h", type=int, default=15)
904
+ p.add_argument("--tile_stride_w", type=int, default=26)
905
+ p.add_argument("--seed", type=int, default=42)
906
+ args = p.parse_args()
907
+ args.requested_num_frames = args.num_frames
908
+ args.num_frames = normalize_wan_num_frames(args.num_frames)
909
+ if args.num_frames != args.requested_num_frames:
910
+ print(
911
+ f"[TinyDittoEdit] num_frames={args.requested_num_frames} is invalid for Wan; "
912
+ f"using {args.num_frames} (required layout: 4n+1).",
913
+ flush=True,
914
+ )
915
+ args.model_paths = args.model_paths or default_model_paths(args.base_model_dir)
916
+ args.torch_dtype = getattr(torch, args.torch_dtype)
917
+ # Persist the effective stream semantics in args.json for reproducibility.
918
+ args.bridge_first_frame_uses_timestep = True
919
+ args.clean_original_prefix_timestep = False
920
+ args.aligned_stream_rope = False
921
+ args.block_prefix_to_bridge_attention = False
922
+ args.conditioning_mode = "channel_concat_reference_no_token_prefix"
923
+ if args.output_path is None:
924
+ args.output_path = str(
925
+ Path(args.output_root)
926
+ / 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}"
927
+ )
928
+ return args
929
+
930
+
931
+ def train(args):
932
+ random.seed(args.seed)
933
+ torch.manual_seed(args.seed)
934
+ if torch_npu is not None and torch.npu.is_available():
935
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
936
+ torch.npu.set_device(local_rank)
937
+ torch.npu.set_compile_mode(jit_compile=False)
938
+ torch.npu.config.allow_internal_format = False
939
+ print(
940
+ f"[TinyDittoEdit] loading dataset root={args.dataset_root} manifest={args.manifest_path}",
941
+ flush=True,
942
+ )
943
+ train_set = build_dataset(args, args.dataset_repeat, args.limit_samples, args.seed)
944
+ val_set = build_validation_dataset(args)
945
+ print(
946
+ f"[TinyDittoEdit] dataset ready: train={len(train_set)}, validation={len(val_set)}",
947
+ flush=True,
948
+ )
949
+ print(
950
+ "[TinyDittoEdit] stream semantics: "
951
+ "bridge_frame0_timestep=sampled, channel_concat=[z_t,reference], "
952
+ "token_prefix=none",
953
+ flush=True,
954
+ )
955
+ model = TinyDittoEditTrainingModule(args)
956
+ accelerator = Accelerator(
957
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
958
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
959
+ )
960
+ if accelerator.is_main_process:
961
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
962
+ (Path(args.output_path) / "args.json").write_text(
963
+ json.dumps(vars(args), indent=2, default=str),
964
+ encoding="utf-8",
965
+ )
966
+ if args.validation_only or args.max_train_steps <= 0:
967
+ validate(args, accelerator, accelerator.prepare(model), val_set, 0)
968
+ return
969
+ from prodigyopt import Prodigy
970
+
971
+ optimizer = Prodigy(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay, safeguard_warmup=True, d_coef=args.d_coef)
972
+ loader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers)
973
+ model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
974
+ 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)
975
+ logger = Logger(args.output_path, remove_prefix_in_ckpt="pipe.dit.")
976
+ if args.validate_at_start:
977
+ validate(args, accelerator, model, val_set, 0)
978
+ accelerator.wait_for_everyone()
979
+ step = 0
980
+ while step < args.max_train_steps:
981
+ for data in tqdm(loader, disable=not accelerator.is_local_main_process):
982
+ with accelerator.accumulate(model):
983
+ optimizer.zero_grad()
984
+ loss, metrics = model(data)
985
+ finite = accelerator.gather(torch.isfinite(loss.detach()).reshape(1))
986
+ if not finite.all():
987
+ raise FloatingPointError(f"Nonfinite loss before update {step + 1}")
988
+ accelerator.backward(loss)
989
+ if args.max_grad_norm > 0:
990
+ grad_norm = accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
991
+ if grad_norm is not None and not torch.isfinite(grad_norm).all():
992
+ raise FloatingPointError(f"Nonfinite gradient before update {step + 1}")
993
+ optimizer.step()
994
+ step += 1
995
+ if step % args.log_interval == 0:
996
+ mean_loss = accelerator.gather(loss.detach().reshape(1)).mean().item()
997
+ if accelerator.is_main_process and step % args.log_interval == 0:
998
+ print(
999
+ f"[Train step {step}] loss={mean_loss:.6f} "
1000
+ f"bridge={metrics['bridge_loss']:.6f} pixel={metrics['pixel_loss']:.6f} "
1001
+ f"lpips={metrics['lpips_loss']:.6f} ssim={metrics['ssim_loss']:.6f}",
1002
+ flush=True,
1003
+ )
1004
+ logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
1005
+ if args.val_interval > 0 and step % args.val_interval == 0:
1006
+ validate(args, accelerator, model, val_set, step)
1007
+ accelerator.wait_for_everyone()
1008
+ if step >= args.max_train_steps:
1009
+ break
1010
+ logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
1011
+
1012
+
1013
+ if __name__ == "__main__":
1014
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
1015
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Compatibility wrapper. The edit pipeline now runs on Wan2.1-T2V-1.3B.
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ exec "${SCRIPT_DIR}/train_wan21_t2v_edit.sh" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-video Wan2.2-TI2V Brownian-bridge SR training.
2
+
3
+ The DiT sees one complete video at a time. Latent frame zero is always the
4
+ encoded HR reference image; all later latent frames are the bicubic-upsampled
5
+ LR video path. There is no chunk/history teacher forcing and no wavelet loss.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import copy
12
+ import json
13
+ import os
14
+ import random
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from accelerate import Accelerator
21
+ from accelerate.utils import DistributedDataParallelKwargs
22
+ from PIL import Image
23
+ from torch.utils.data import DataLoader
24
+ from tqdm import tqdm
25
+
26
+ REPO_ROOT = Path(__file__).resolve().parents[4]
27
+ if str(REPO_ROOT) not in sys.path:
28
+ sys.path.insert(0, str(REPO_ROOT))
29
+
30
+ from diffsynth.bridge.wan_bridge.bridge.wan_bridge_pipeline import WanVideoBridgePipeline
31
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
32
+ SeedanceSRDataset,
33
+ decode_latents_to_btchw_01,
34
+ lpips_video_loss,
35
+ pil_video_to_tensor_01,
36
+ tensor_btchw_01_to_pil,
37
+ )
38
+ from diffsynth.data.video import save_video
39
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger
40
+ from diffsynth.utils import ModelConfig
41
+
42
+
43
+ def default_model_paths(base_model_dir: str) -> str:
44
+ base = Path(base_model_dir)
45
+ dit = base / "diffusion_pytorch_model.safetensors.index.json"
46
+ if not dit.exists():
47
+ dit = base / "diffusion_pytorch_model.safetensors"
48
+ paths = [dit, base / "models_t5_umt5-xxl-enc-bf16.pth", base / "Wan2.2_VAE.pth"]
49
+ missing = [str(p) for p in paths if not p.exists()]
50
+ if missing:
51
+ raise FileNotFoundError("Missing Wan2.2-TI2V files: " + ", ".join(missing))
52
+ return ",".join(str(p) for p in paths)
53
+
54
+
55
+ def normalize_wan_num_frames(num_frames: int) -> int:
56
+ """Round a requested RGB length up to Wan's required 4n+1 layout."""
57
+ num_frames = max(int(num_frames), 1)
58
+ if num_frames % 4 == 1:
59
+ return num_frames
60
+ return ((num_frames - 1 + 3) // 4) * 4 + 1
61
+
62
+
63
+ def align_noise_to_latents(noise: torch.Tensor, latents: torch.Tensor) -> torch.Tensor:
64
+ """Match initializer noise to the VAE output, which is the shape authority."""
65
+ if noise.shape[:2] != latents.shape[:2] or noise.shape[-2:] != latents.shape[-2:]:
66
+ raise ValueError(
67
+ f"Noise shape {tuple(noise.shape)} is spatially incompatible with "
68
+ f"encoded latents {tuple(latents.shape)}"
69
+ )
70
+ if noise.shape[2] == latents.shape[2]:
71
+ return noise.to(device=latents.device, dtype=latents.dtype)
72
+ if noise.shape[2] > latents.shape[2]:
73
+ noise = noise[:, :, :latents.shape[2]]
74
+ else:
75
+ tail = torch.randn(
76
+ (*noise.shape[:2], latents.shape[2] - noise.shape[2], *noise.shape[-2:]),
77
+ device=noise.device,
78
+ dtype=noise.dtype,
79
+ )
80
+ noise = torch.cat([noise, tail], dim=2)
81
+ return noise.to(device=latents.device, dtype=latents.dtype)
82
+
83
+
84
+ def ensure_module_device(module: torch.nn.Module | None, device: torch.device) -> torch.nn.Module | None:
85
+ if module is None:
86
+ return None
87
+ param = next(module.parameters(), None)
88
+ buffer = next(module.buffers(), None)
89
+ current_device = param.device if param is not None else buffer.device if buffer is not None else None
90
+ if current_device != device:
91
+ module = module.to(device=device)
92
+ return module
93
+
94
+
95
+ def replace_first_latent_frame(latents: torch.Tensor, anchor: torch.Tensor | None) -> torch.Tensor:
96
+ if anchor is None:
97
+ return latents
98
+ if anchor.shape[2] != 1:
99
+ raise ValueError(f"Expected one anchor latent frame, got {tuple(anchor.shape)}")
100
+ if latents.shape[:2] != anchor.shape[:2] or latents.shape[-2:] != anchor.shape[-2:]:
101
+ raise ValueError(f"Anchor {tuple(anchor.shape)} incompatible with {tuple(latents.shape)}")
102
+ result = latents.clone()
103
+ result[:, :, :1] = anchor.to(device=latents.device, dtype=latents.dtype)
104
+ return result
105
+
106
+
107
+ def drop_first(video: torch.Tensor) -> torch.Tensor:
108
+ return video[:, 1:] if video.shape[1] > 1 else video[:, :0]
109
+
110
+
111
+ def drop_first_latent(latents: torch.Tensor) -> torch.Tensor:
112
+ return latents[:, :, 1:] if latents.shape[2] > 1 else latents[:, :, :0]
113
+
114
+
115
+ def spatial_crop_latents_for_rgb_loss(
116
+ latents: torch.Tensor,
117
+ crop_size_pixels: int,
118
+ vae_factor: int,
119
+ ) -> tuple[torch.Tensor, dict[str, int]]:
120
+ """Randomly crop latent space before differentiable VAE decoding."""
121
+ _, _, _, height, width = latents.shape
122
+ vae_factor = max(int(vae_factor), 1)
123
+ if crop_size_pixels > 0:
124
+ crop_height = min(max(int(crop_size_pixels) // vae_factor, 1), height)
125
+ crop_width = min(max(int(crop_size_pixels) // vae_factor, 1), width)
126
+ else:
127
+ crop_height, crop_width = height, width
128
+ top = int(torch.randint(height - crop_height + 1, (1,), device=latents.device).item()) if height > crop_height else 0
129
+ left = int(torch.randint(width - crop_width + 1, (1,), device=latents.device).item()) if width > crop_width else 0
130
+ cropped = latents[..., top:top + crop_height, left:left + crop_width].contiguous()
131
+ return cropped, {
132
+ "top": top,
133
+ "left": left,
134
+ "height": crop_height,
135
+ "width": crop_width,
136
+ "full_height": height,
137
+ "full_width": width,
138
+ }
139
+
140
+
141
+ def ssim_video_loss(pred: torch.Tensor, target: torch.Tensor, window_size: int = 11) -> torch.Tensor:
142
+ count = min(pred.shape[1], target.shape[1])
143
+ if count == 0:
144
+ return pred.new_tensor(0.0)
145
+ pred = pred[:, :count].reshape(-1, *pred.shape[2:]).float()
146
+ target = target[:, :count].reshape(-1, *target.shape[2:]).float()
147
+ channels = pred.shape[1]
148
+ window_size = max(1, int(window_size) | 1)
149
+ weight = pred.new_ones((channels, 1, window_size, window_size)) / (window_size**2)
150
+ padding = window_size // 2
151
+ mu_x = F.conv2d(pred, weight, padding=padding, groups=channels)
152
+ mu_y = F.conv2d(target, weight, padding=padding, groups=channels)
153
+ mu_x2, mu_y2, mu_xy = mu_x.square(), mu_y.square(), mu_x * mu_y
154
+ sigma_x = F.conv2d(pred * pred, weight, padding=padding, groups=channels) - mu_x2
155
+ sigma_y = F.conv2d(target * target, weight, padding=padding, groups=channels) - mu_y2
156
+ sigma_xy = F.conv2d(pred * target, weight, padding=padding, groups=channels) - mu_xy
157
+ c1, c2 = 0.01**2, 0.03**2
158
+ value = ((2 * mu_xy + c1) * (2 * sigma_xy + c2)) / (
159
+ (mu_x2 + mu_y2 + c1) * (sigma_x + sigma_y + c2) + 1e-8
160
+ )
161
+ return (1.0 - value.clamp(-1, 1)).mean()
162
+
163
+
164
+ class FirstFrameAnchorSRDataset(SeedanceSRDataset):
165
+ def __init__(self, *args, **kwargs):
166
+ kwargs["source_mode"] = "bicubic"
167
+ super().__init__(*args, **kwargs)
168
+
169
+ def __getitem__(self, idx):
170
+ item = super().__getitem__(idx)
171
+ item["source_video"][0] = item["video"][0].copy()
172
+ item["reference_image"] = item["video"][0].copy()
173
+ return item
174
+
175
+
176
+ class FullVideoWan22BridgePipeline(WanVideoBridgePipeline):
177
+ def training_loss(self, **inputs):
178
+ lo = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps)
179
+ hi = int(inputs.get("max_timestep_boundary", 0.9999) * self.scheduler.num_train_timesteps)
180
+ timestep = self.scheduler.timesteps[torch.randint(lo, hi, (1,))].to(
181
+ device=self.device, dtype=self.torch_dtype
182
+ )
183
+ anchor = inputs["first_frame_latents"]
184
+ x0 = replace_first_latent_frame(inputs["input_latents"], anchor)
185
+ x1 = replace_first_latent_frame(inputs["source_latents"], anchor)
186
+ if x0.shape != x1.shape:
187
+ raise ValueError(
188
+ f"Target latent shape {tuple(x0.shape)} does not match "
189
+ f"source latent shape {tuple(x1.shape)}"
190
+ )
191
+ noise = align_noise_to_latents(inputs["noise"], x0)
192
+ # The anchor is clean and never receives Brownian noise.
193
+ future_xt = self.scheduler.add_noise(x0[:, :, 1:], x1[:, :, 1:], noise[:, :, 1:], timestep)
194
+ xt = torch.cat([anchor, future_xt], dim=2)
195
+ model_inputs = dict(inputs)
196
+ model_inputs.update({"latents": xt, "input_latents": x0, "source_latents": x1})
197
+ model_inputs.pop("first_frame_latents", None)
198
+ output = self.model_fn(**model_inputs, timestep=timestep)
199
+ sigma = torch.as_tensor(self.scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
200
+ target = self.scheduler.training_target(x0[:, :, 1:], future_xt, timestep)
201
+ if self.scheduler.target == "stabilized_drift":
202
+ factor = (1 + (1 - sigma) / (sigma + 1e-5)).sqrt()
203
+ velocity_target = target / factor
204
+ endpoint = future_xt.float() - sigma * (output[:, :, 1:].float() * factor)
205
+ elif self.scheduler.target == "drift":
206
+ velocity_target = target
207
+ endpoint = future_xt.float() - sigma * output[:, :, 1:].float()
208
+ else:
209
+ raise ValueError(f"Unsupported target: {self.scheduler.target}")
210
+
211
+ bridge = F.mse_loss(output[:, :, 1:].float(), velocity_target.float())
212
+ total = float(inputs.get("bridge_loss_weight", 1.0)) * bridge
213
+ metrics = {"bridge_loss": float(bridge.detach()), "pixel_loss": 0.0, "lpips_loss": 0.0, "ssim_loss": 0.0}
214
+ pixel_weight = float(inputs.get("pixel_loss_weight", 0.0))
215
+ lpips_weight = float(inputs.get("lpips_weight", 0.0))
216
+ ssim_weight = float(inputs.get("ssim_weight", 0.0))
217
+ if pixel_weight > 0 or lpips_weight > 0 or ssim_weight > 0:
218
+ # Decode a temporal subset for memory efficiency; frame zero is
219
+ # deliberately absent from both prediction and target losses.
220
+ count = int(inputs.get("pixel_loss_latent_frames", 3))
221
+ if count <= 0 or count >= endpoint.shape[2]:
222
+ start, count = 0, endpoint.shape[2]
223
+ else:
224
+ start = int(torch.randint(endpoint.shape[2] - count + 1, (1,), device=endpoint.device))
225
+ context_index = start
226
+ decode_latent = torch.cat([x0[:, :, context_index:context_index + 1].detach(), endpoint[:, :, start:start + count]], dim=2)
227
+ decode_latent, crop_info = spatial_crop_latents_for_rgb_loss(
228
+ decode_latent,
229
+ int(inputs.get("pixel_loss_crop_size", 400)),
230
+ int(getattr(self.vae, "upsampling_factor", 16)),
231
+ )
232
+ 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)))
233
+ pred_video = pred_video[:, 1:]
234
+ raw_target = inputs.get("raw_target_video")
235
+ if raw_target is None:
236
+ raise ValueError("raw_target_video is required for pixel losses")
237
+ # Under Accelerate, module parameters can be moved without updating
238
+ # BasePipeline.device. The decoded prediction is the authoritative
239
+ # device for all RGB-space losses.
240
+ rgb_start = 1 + 4 * start
241
+ rgb_count = min(pred_video.shape[1], 4 * count, len(raw_target) - rgb_start)
242
+ if rgb_count <= 0:
243
+ raise ValueError(
244
+ f"No RGB frames align with latent range start={start}, count={count}; "
245
+ f"decoded={pred_video.shape[1]}, target={len(raw_target)}"
246
+ )
247
+ spatial_factor_h = raw_target[0].height // crop_info["full_height"]
248
+ spatial_factor_w = raw_target[0].width // crop_info["full_width"]
249
+ top = crop_info["top"] * spatial_factor_h
250
+ left = crop_info["left"] * spatial_factor_w
251
+ crop_height = pred_video.shape[-2]
252
+ crop_width = pred_video.shape[-1]
253
+ target_frames = [
254
+ frame.crop((left, top, left + crop_width, top + crop_height))
255
+ for frame in raw_target[rgb_start:rgb_start + rgb_count]
256
+ ]
257
+ target_video = pil_video_to_tensor_01(target_frames, pred_video.device).unsqueeze(0).to(
258
+ device=pred_video.device, dtype=pred_video.dtype
259
+ )
260
+ pred_video = pred_video[:, :rgb_count]
261
+ if pred_video.shape != target_video.shape:
262
+ raise ValueError(
263
+ f"RGB prediction shape {tuple(pred_video.shape)} does not match "
264
+ f"target shape {tuple(target_video.shape)}"
265
+ )
266
+ if pixel_weight > 0:
267
+ value = F.mse_loss(pred_video.float(), target_video.float())
268
+ total = total + pixel_weight * value
269
+ metrics["pixel_loss"] = float(value.detach())
270
+ if lpips_weight > 0:
271
+ lpips_model = inputs.get("lpips_model")
272
+ if lpips_model is None:
273
+ raise ValueError("lpips_model is required when lpips_weight > 0")
274
+ lpips_model = ensure_module_device(lpips_model, pred_video.device)
275
+ value = lpips_video_loss(lpips_model, pred_video, target_video, int(inputs.get("lpips_num_frames", 4)), int(inputs.get("lpips_crop_size", 224)))
276
+ total = total + lpips_weight * value
277
+ metrics["lpips_loss"] = float(value.detach())
278
+ if ssim_weight > 0:
279
+ value = ssim_video_loss(pred_video, target_video, int(inputs.get("ssim_window_size", 11)))
280
+ total = total + ssim_weight * value
281
+ metrics["ssim_loss"] = float(value.detach())
282
+ return total, metrics
283
+
284
+
285
+ class FullVideoTrainingModule(DiffusionTrainingModule):
286
+ def __init__(self, args):
287
+ super().__init__()
288
+ configs = [ModelConfig(path=p) for p in args.model_paths.split(",")]
289
+ self.pipe = FullVideoWan22BridgePipeline.from_pretrained(torch_dtype=torch.bfloat16, device="cpu", model_configs=configs, tokenizer_config=ModelConfig(path=args.tokenizer_path))
290
+ self.pipe.latent_upsampler = None
291
+ if not getattr(self.pipe.dit, "fuse_vae_embedding_in_latents", False) or int(getattr(self.pipe.vae, "z_dim", 0)) != 48:
292
+ raise RuntimeError("Expected a Wan2.2-TI2V-5B fused-input DiT with 48-channel VAE")
293
+ 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)
294
+ self.args = args
295
+ if args.lpips_weight > 0 or args.val_lpips:
296
+ import lpips
297
+ self.lpips_model = lpips.LPIPS(net=args.lpips_net, verbose=False).eval().requires_grad_(False)
298
+ else:
299
+ self.lpips_model = None
300
+
301
+ def to(self, *args, **kwargs):
302
+ super().to(*args, **kwargs)
303
+ if self.lpips_model is not None:
304
+ self.lpips_model = self.lpips_model.to(*args, **kwargs)
305
+ return self
306
+
307
+ @torch.no_grad()
308
+ def encode_anchor(self, image):
309
+ self.pipe.load_models_to_device(["vae"])
310
+ 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))
311
+ return encoded.to(device=self.pipe.device, dtype=self.pipe.torch_dtype)
312
+
313
+ def forward_preprocess(self, data):
314
+ 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"]}
315
+ pos, neg = {"prompt": data["prompt"]}, {}
316
+ for unit in self.pipe.units:
317
+ shared, pos, neg = self.pipe.unit_runner(unit, self.pipe, shared, pos, neg)
318
+ shared["first_frame_latents"] = self.encode_anchor(data["reference_image"])
319
+ return {**shared, **pos}
320
+
321
+ def forward(self, data, inputs=None):
322
+ inputs = self.forward_preprocess(data) if inputs is None else inputs
323
+ return self.pipe.training_loss(**{n: getattr(self.pipe, n) for n in self.pipe.in_iteration_models}, **inputs)
324
+
325
+
326
+ @torch.no_grad()
327
+ def sample_full(pipe, inputs, args):
328
+ anchor = inputs["first_frame_latents"]
329
+ source = replace_first_latent_frame(inputs["source_latents"], anchor)
330
+ latents = source.clone()
331
+ pipe.scheduler.set_timesteps(args.val_inference_steps, shift=args.val_sigma_shift)
332
+ pipe.load_models_to_device(pipe.in_iteration_models)
333
+ models = {n: getattr(pipe, n) for n in pipe.in_iteration_models}
334
+ model_inputs = dict(inputs)
335
+ model_inputs.pop("latents", None)
336
+ model_inputs.pop("first_frame_latents", None)
337
+ model_inputs["source_latents"] = source
338
+ for timestep_cpu in pipe.scheduler.timesteps:
339
+ timestep = timestep_cpu.unsqueeze(0).to(device=pipe.device, dtype=pipe.torch_dtype)
340
+ pred = pipe.model_fn(**models, **model_inputs, latents=latents, timestep=timestep)
341
+ latents = pipe.scheduler.step(pred, timestep_cpu, latents, source)
342
+ latents[:, :, :1] = anchor
343
+ return latents
344
+
345
+
346
+ def build_dataset(args, repeat, limit, seed):
347
+ 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)
348
+
349
+
350
+ def validate(args, accelerator, model, dataset, step):
351
+ if not accelerator.is_main_process:
352
+ return {}
353
+ module = accelerator.unwrap_model(model)
354
+ pipe = module.pipe
355
+ backup = pipe.scheduler
356
+ pipe.scheduler = copy.deepcopy(backup)
357
+ pipe.scheduler.noise_scale = args.val_sampling_noise_scale
358
+ pipe.scheduler.target = args.target
359
+ out = Path(args.output_path) / "validation" / f"step-{step:06d}"
360
+ out.mkdir(parents=True, exist_ok=True)
361
+ rows = []
362
+ for idx in range(min(args.val_batches, len(dataset))):
363
+ data = dataset[idx]
364
+ inputs = module.forward_preprocess(data)
365
+ x0 = replace_first_latent_frame(inputs["input_latents"], inputs["first_frame_latents"])
366
+ pred_latent = sample_full(pipe, inputs, args)
367
+ 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))
368
+ target = decode_latents_to_btchw_01(pipe, x0, args.tiled, (args.tile_h, args.tile_w), (args.tile_stride_h, args.tile_stride_w))
369
+ pred_main, target_main = drop_first(pred), drop_first(target)
370
+ 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()}
371
+ if args.val_lpips and module.lpips_model is not None:
372
+ module.lpips_model = ensure_module_device(module.lpips_model, pred_main.device)
373
+ row["lpips"] = float(lpips_video_loss(module.lpips_model, pred_main, target_main, args.lpips_num_frames, args.lpips_crop_size))
374
+ if args.val_ssim or args.ssim_weight > 0:
375
+ row["ssim"] = float(ssim_video_loss(pred_main, target_main, args.ssim_window_size))
376
+ rows.append(row)
377
+ save_video(tensor_btchw_01_to_pil(pred[0]), str(out / f"val_{idx:03d}_pred.mp4"), fps=args.fps, quality=5)
378
+ data["reference_image"].save(out / f"val_{idx:03d}_reference.png")
379
+ metrics = {f"val_{k}": sum(r[k] for r in rows) / len(rows) for k in rows[0] if k != "idx"} if rows else {}
380
+ (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")
381
+ print(f"[Validation step {step}] {metrics}", flush=True)
382
+ pipe.scheduler = backup
383
+ pipe.train()
384
+ return metrics
385
+
386
+
387
+ class Logger(ModelLogger):
388
+ pass
389
+
390
+
391
+ def parse_args():
392
+ p = argparse.ArgumentParser(description=__doc__)
393
+ p.add_argument("--base_model_dir", default="/cache/Wan2.2-TI2V-5B")
394
+ p.add_argument("--model_paths", default=None)
395
+ p.add_argument("--tokenizer_path", default="/cache/Wan2.2-TI2V-5B/google/umt5-xxl")
396
+ p.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
397
+ p.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
398
+ p.add_argument("--prompt_field", default="raw_p")
399
+ p.add_argument("--default_prompt", default="")
400
+ p.add_argument("--output_root", default="/cache/outputs_bridge_wan22_ti2v_full")
401
+ p.add_argument("--output_path", default=None)
402
+ 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)
403
+ 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)
404
+ 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)
405
+ 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")
406
+ 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)
407
+ 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)
408
+ args = p.parse_args()
409
+ args.requested_num_frames = args.num_frames
410
+ args.num_frames = normalize_wan_num_frames(args.num_frames)
411
+ if args.num_frames != args.requested_num_frames:
412
+ print(
413
+ f"[Wan22TI2VFull] num_frames={args.requested_num_frames} is invalid for Wan; "
414
+ f"using {args.num_frames} (required layout: 4n+1).",
415
+ flush=True,
416
+ )
417
+ args.model_paths = args.model_paths or default_model_paths(args.base_model_dir)
418
+ if args.output_path is None:
419
+ 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}")
420
+ return args
421
+
422
+
423
+ def train(args):
424
+ random.seed(args.seed); torch.manual_seed(args.seed)
425
+ train_set = build_dataset(args, args.dataset_repeat, args.limit_videos, args.seed)
426
+ val_set = build_dataset(args, 1, max(args.val_batches, 1), args.seed + 1)
427
+ model = FullVideoTrainingModule(args)
428
+ 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
429
+ accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)])
430
+ if accelerator.is_main_process:
431
+ 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")
432
+ if args.validation_only or args.max_train_steps <= 0:
433
+ validate(args, accelerator, accelerator.prepare(model), val_set, 0); return
434
+ from prodigyopt import Prodigy
435
+ optimizer = Prodigy(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay, safeguard_warmup=True, d_coef=args.d_coef)
436
+ loader = DataLoader(train_set, shuffle=True, collate_fn=lambda x: x[0], num_workers=args.dataset_num_workers)
437
+ model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
438
+ logger = Logger(args.output_path, remove_prefix_in_ckpt="pipe.dit.")
439
+ if args.validate_at_start: validate(args, accelerator, model, val_set, 0)
440
+ step = 0
441
+ while step < args.max_train_steps:
442
+ for data in tqdm(loader, disable=not accelerator.is_local_main_process):
443
+ with accelerator.accumulate(model):
444
+ optimizer.zero_grad(); loss, metrics = model(data); accelerator.backward(loss)
445
+ if args.max_grad_norm > 0: accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
446
+ optimizer.step(); step += 1
447
+ if accelerator.is_main_process and step % args.log_interval == 0:
448
+ 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)
449
+ logger.on_step_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
450
+ if args.val_interval > 0 and step % args.val_interval == 0: validate(args, accelerator, model, val_set, step)
451
+ if step >= args.max_train_steps: break
452
+ logger.on_training_end(accelerator, model, args.save_steps if args.save_steps > 0 else None)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
457
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
7
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
8
+ export TOKENIZERS_PARALLELISM=false
9
+
10
+ "${PYTHON_BIN}" diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_full.py \
11
+ --base_model_dir "${BASE_MODEL_DIR:-/cache/Wan2.2-TI2V-5B}" \
12
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}" \
13
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}" \
14
+ --output_root "${OUTPUT_ROOT:-/cache/4xoutputs_bridge_wan22_ti2v_full}" \
15
+ --height "${HEIGHT:-480}" --width "${WIDTH:-832}" --num_frames "${NUM_FRAMES:-33}" \
16
+ --sr_scale "${SR_SCALE:-4}" --fps "${FPS:-16}" \
17
+ --learning_rate "${LEARNING_RATE:-1.0}" --max_train_steps "${MAX_TRAIN_STEPS:-5000}" \
18
+ --save_steps "${SAVE_STEPS:-500}" --val_interval "${VAL_INTERVAL:-100}" \
19
+ --noise_sigma "${NOISE_SIGMA:-1.0}" --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}" \
20
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-4.0}" --lpips_weight "${LPIPS_WEIGHT:-1.0}" \
21
+ --ssim_weight "${SSIM_WEIGHT:-1.0}" --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}" \
22
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}" \
23
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-4}" --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}" \
24
+ --val_lpips --val_ssim --tiled \
25
+ "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train a Brownian bridge directly in latent Haar high-frequency subbands.
2
+
3
+ This is intentionally a separate training entry point. It imports reusable data,
4
+ VAE and UltraFlash helpers from ``train_sr.py`` but does not alter the original SR
5
+ bridge training path.
6
+
7
+ Latent pipeline (one level, orthonormal Haar):
8
+
9
+ LR video -> Wan VAE -> UltraFlash -> z_up -> LL_up
10
+ HD reference frame -> Wan VAE -> (HL_ref, LH_ref, HH_ref) -> repeat in time
11
+ Brownian bridge: reference HF -> target-video HF, conditioned on LL_up
12
+ IDWT(LL_up, predicted HF) -> reconstructed HR video latent
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import copy
19
+ import json
20
+ import math
21
+ import os
22
+ import random
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import imageio
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+ from accelerate import Accelerator
31
+ from accelerate.utils import DistributedDataParallelKwargs
32
+ from PIL import Image, ImageDraw
33
+ from safetensors.torch import load_file
34
+ from torch.utils.data import DataLoader, Dataset
35
+ from tqdm import tqdm
36
+
37
+ REPO_ROOT = Path(__file__).resolve().parents[4]
38
+ if str(REPO_ROOT) not in sys.path:
39
+ sys.path.insert(0, str(REPO_ROOT))
40
+
41
+ from diffsynth.bridge.wan_bridge.model_training.train_sr import (
42
+ SeedanceSRDataset,
43
+ WanVideoSRBridgePipeline,
44
+ WanVideoSRUnit_UltraFlashLatentUpsampler,
45
+ center_crop_resize,
46
+ decode_latents_to_btchw_01,
47
+ default_model_paths,
48
+ load_ultraflash_latent_upsampler,
49
+ pil_video_to_tensor_01,
50
+ tensor_btchw_01_to_pil,
51
+ )
52
+ from diffsynth.data.video import save_video
53
+ from diffsynth.trainers.utils import DiffusionTrainingModule, ModelLogger
54
+ from diffsynth.utils import ModelConfig
55
+
56
+
57
+ BAND_ORDER = ("HL", "LH", "HH")
58
+
59
+
60
+ def haar_dwt2(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
61
+ """Orthonormal 2D Haar DWT over the last two dimensions.
62
+
63
+ Returns LL and high-frequency channels concatenated as [HL, LH, HH]. For an
64
+ input [B, C, T, H, W], the shapes are [B, C, T, H/2, W/2] and
65
+ [B, 3C, T, H/2, W/2].
66
+ """
67
+ if x.ndim != 5:
68
+ raise ValueError(f"Expected BCTHW latent, got {tuple(x.shape)}")
69
+ if x.shape[-2] % 2 or x.shape[-1] % 2:
70
+ raise ValueError(f"Haar DWT requires even H/W, got {tuple(x.shape[-2:])}")
71
+ a = x[..., 0::2, 0::2]
72
+ b = x[..., 0::2, 1::2]
73
+ c = x[..., 1::2, 0::2]
74
+ d = x[..., 1::2, 1::2]
75
+ ll = (a + b + c + d) * 0.5
76
+ hl = (a - b + c - d) * 0.5
77
+ lh = (a + b - c - d) * 0.5
78
+ hh = (a - b - c + d) * 0.5
79
+ return ll, torch.cat((hl, lh, hh), dim=1)
80
+
81
+
82
+ def haar_idwt2(ll: torch.Tensor, hf: torch.Tensor) -> torch.Tensor:
83
+ """Exact inverse of :func:`haar_dwt2`; HF order is [HL, LH, HH]."""
84
+ if ll.ndim != 5 or hf.ndim != 5:
85
+ raise ValueError("LL and HF must both be BCTHW tensors")
86
+ channels = ll.shape[1]
87
+ if hf.shape[1] != channels * 3 or hf.shape[0] != ll.shape[0] or hf.shape[2:] != ll.shape[2:]:
88
+ raise ValueError(f"Incompatible LL/HF shapes: {tuple(ll.shape)}, {tuple(hf.shape)}")
89
+ hl, lh, hh = hf.split(channels, dim=1)
90
+ a = (ll + hl + lh + hh) * 0.5
91
+ b = (ll - hl + lh - hh) * 0.5
92
+ c = (ll + hl - lh - hh) * 0.5
93
+ d = (ll - hl - lh + hh) * 0.5
94
+ out = ll.new_empty((*ll.shape[:-2], ll.shape[-2] * 2, ll.shape[-1] * 2))
95
+ out[..., 0::2, 0::2] = a
96
+ out[..., 0::2, 1::2] = b
97
+ out[..., 1::2, 0::2] = c
98
+ out[..., 1::2, 1::2] = d
99
+ return out
100
+
101
+
102
+ def load_bridge_checkpoint(dit: nn.Module, checkpoint: str) -> None:
103
+ state = load_file(checkpoint, device="cpu")
104
+ prefixes = ("pipe.dit.", "dit.", "module.pipe.dit.", "module.dit.")
105
+ for prefix in prefixes:
106
+ if any(key.startswith(prefix) for key in state):
107
+ state = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state.items()}
108
+ break
109
+ dit.load_state_dict(state, strict=True)
110
+ print(f"[WaveletBridge] initialized Wan DiT from {checkpoint}")
111
+
112
+
113
+ def expand_dit_wavelet_io(dit: nn.Module, latent_channels: int = 16) -> None:
114
+ """Change Wan's input 16->64 and output 16->48 without touching its body."""
115
+ old_patch = dit.patch_embedding
116
+ if old_patch.in_channels != latent_channels:
117
+ raise ValueError(f"Expected {latent_channels}-channel Wan input, got {old_patch.in_channels}")
118
+ new_patch = nn.Conv3d(
119
+ latent_channels * 4,
120
+ old_patch.out_channels,
121
+ kernel_size=old_patch.kernel_size,
122
+ stride=old_patch.stride,
123
+ padding=old_patch.padding,
124
+ dilation=old_patch.dilation,
125
+ bias=old_patch.bias is not None,
126
+ ).to(device=old_patch.weight.device, dtype=old_patch.weight.dtype)
127
+ with torch.no_grad():
128
+ new_patch.weight.zero_()
129
+ # Input order is [LL_up, xt_HL, xt_LH, xt_HH]. Preserve the old
130
+ # Bridge's input behaviour through LL and initially ignore HF state.
131
+ new_patch.weight[:, :latent_channels].copy_(old_patch.weight)
132
+ if old_patch.bias is not None:
133
+ new_patch.bias.copy_(old_patch.bias)
134
+ dit.patch_embedding = new_patch
135
+ dit.in_dim = latent_channels * 4
136
+
137
+ old_linear = dit.head.head
138
+ patch_volume = math.prod(dit.patch_size)
139
+ if old_linear.out_features != latent_channels * patch_volume:
140
+ raise ValueError(f"Unexpected Wan head size {old_linear.out_features}")
141
+ new_linear = nn.Linear(
142
+ old_linear.in_features, latent_channels * 3 * patch_volume, bias=old_linear.bias is not None
143
+ ).to(device=old_linear.weight.device, dtype=old_linear.weight.dtype)
144
+ with torch.no_grad():
145
+ # Each subband starts from the pretrained Bridge head. They immediately
146
+ # separate because each third receives a different subband target.
147
+ for band_id in range(3):
148
+ start = band_id * old_linear.out_features
149
+ stop = start + old_linear.out_features
150
+ new_linear.weight[start:stop].copy_(old_linear.weight)
151
+ if old_linear.bias is not None:
152
+ new_linear.bias[start:stop].copy_(old_linear.bias)
153
+ dit.head.head = new_linear
154
+ print("[WaveletBridge] DiT I/O: 64=[LL,HL,LH,HH] input channels, 48=[HL,LH,HH] output channels")
155
+
156
+
157
+ def load_wavelet_checkpoint(dit: nn.Module, checkpoint: str) -> None:
158
+ state = load_file(checkpoint, device="cpu")
159
+ for prefix in ("pipe.dit.", "dit.", "module.pipe.dit."):
160
+ if any(key.startswith(prefix) for key in state):
161
+ state = {key[len(prefix):] if key.startswith(prefix) else key: value for key, value in state.items()}
162
+ break
163
+ result = dit.load_state_dict(state, strict=False)
164
+ if result.missing_keys or result.unexpected_keys:
165
+ raise RuntimeError(
166
+ f"Wavelet checkpoint mismatch; missing={result.missing_keys[:8]}, unexpected={result.unexpected_keys[:8]}"
167
+ )
168
+ print(f"[WaveletBridge] resumed {checkpoint}")
169
+
170
+
171
+ class SeedanceWaveletBridgeDataset(SeedanceSRDataset):
172
+ """Seedance SR clip plus the actual first frame of the same disk video."""
173
+
174
+ def _read_reference(self, path: Path) -> Image.Image:
175
+ reader = imageio.get_reader(str(path))
176
+ try:
177
+ frame = reader.get_data(0)
178
+ finally:
179
+ reader.close()
180
+ return center_crop_resize(Image.fromarray(frame).convert("RGB"), self.height, self.width)
181
+
182
+ def __getitem__(self, idx: int) -> dict:
183
+ data = super().__getitem__(idx)
184
+ data["reference_image"] = self._read_reference(Path(data["path"]))
185
+ return data
186
+
187
+
188
+ def normalized_band_l1(pred: torch.Tensor, target: torch.Tensor, channels: int) -> tuple[torch.Tensor, dict]:
189
+ losses = []
190
+ metrics = {}
191
+ for band_id, name in enumerate(BAND_ORDER):
192
+ p = pred[:, band_id * channels:(band_id + 1) * channels].float()
193
+ y = target[:, band_id * channels:(band_id + 1) * channels].float()
194
+ scale = y.detach().abs().mean(dim=(1, 2, 3, 4), keepdim=True).clamp_min(1e-3)
195
+ raw = F.l1_loss(p, y)
196
+ losses.append(((p - y).abs() / scale).mean())
197
+ metrics[f"{name.lower()}_l1"] = float(raw.detach().cpu())
198
+ return torch.stack(losses).mean(), metrics
199
+
200
+
201
+ class WaveletBridgeTrainingModule(DiffusionTrainingModule):
202
+ def __init__(self, args) -> None:
203
+ super().__init__()
204
+ configs = [ModelConfig(path=path) for path in args.model_paths.split(",")]
205
+ self.pipe: WanVideoSRBridgePipeline = WanVideoSRBridgePipeline.from_pretrained(
206
+ torch_dtype=torch.bfloat16,
207
+ device="cpu",
208
+ model_configs=configs,
209
+ tokenizer_config=ModelConfig(path=args.tokenizer_path),
210
+ )
211
+ load_bridge_checkpoint(self.pipe.dit, args.bridge_checkpoint)
212
+ expand_dit_wavelet_io(self.pipe.dit, args.latent_channels)
213
+ if args.resume_checkpoint:
214
+ load_wavelet_checkpoint(self.pipe.dit, args.resume_checkpoint)
215
+
216
+ self.pipe.latent_upsampler = load_ultraflash_latent_upsampler(args, device="cpu")
217
+ self.pipe.units = self.pipe.units[:-1] + [WanVideoSRUnit_UltraFlashLatentUpsampler()]
218
+ self.pipe.scheduler.noise_scale = args.noise_sigma
219
+ self.pipe.scheduler.target = args.target
220
+ # We sample this explicit short schedule ourselves. ``training=True``
221
+ # builds an auxiliary timestep-weight table which is undefined for a
222
+ # single point and is not used by this objective.
223
+ self.pipe.scheduler.set_timesteps(args.train_timesteps, shift=args.sigma_shift)
224
+ # The generic Wan input-video unit uses this flag to return the clean
225
+ # encoded target latent. Leaving it False would make that unit call the
226
+ # ordinary diffusion add_noise signature, which is not Bridge-compatible.
227
+ self.pipe.scheduler.training = True
228
+ valid_ids = torch.where(
229
+ (self.pipe.scheduler.sigmas >= args.min_train_sigma)
230
+ & (self.pipe.scheduler.sigmas <= args.max_train_sigma)
231
+ )[0]
232
+ if valid_ids.numel() == 0:
233
+ raise ValueError(
234
+ f"No training sigmas in [{args.min_train_sigma}, {args.max_train_sigma}] "
235
+ f"for a {args.train_timesteps}-point schedule"
236
+ )
237
+ # Keep this CPU-side index table non-persistent: it is schedule metadata,
238
+ # not a learned model tensor and should not enter checkpoints.
239
+ self.train_timestep_ids = valid_ids
240
+ print(
241
+ f"[WaveletBridge] random Brownian training: {valid_ids.numel()} sigmas in "
242
+ f"[{float(self.pipe.scheduler.sigmas[valid_ids].min()):.4f}, "
243
+ f"{float(self.pipe.scheduler.sigmas[valid_ids].max()):.4f}], "
244
+ f"noise_scale={self.pipe.scheduler.noise_scale:g}"
245
+ )
246
+
247
+ self.pipe.requires_grad_(False)
248
+ self.pipe.dit.requires_grad_(True)
249
+ self.args = args
250
+
251
+ @torch.no_grad()
252
+ def _encode_reference(self, reference_image: Image.Image) -> torch.Tensor:
253
+ self.pipe.load_models_to_device(["vae"])
254
+ video = self.pipe.preprocess_video([reference_image])
255
+ return self.pipe.vae.encode(
256
+ video,
257
+ device=self.pipe.device,
258
+ tiled=self.args.tiled,
259
+ tile_size=(self.args.tile_h, self.args.tile_w),
260
+ tile_stride=(self.args.tile_stride_h, self.args.tile_stride_w),
261
+ ).to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
262
+
263
+ def forward_preprocess(self, data: dict, apply_text_dropout: bool = True) -> dict:
264
+ prompt = data["prompt"]
265
+ if apply_text_dropout and random.random() < self.args.text_drop_probability:
266
+ prompt = " "
267
+ positive = {"prompt": prompt}
268
+ negative = {}
269
+ shared = {
270
+ "input_video": data["video"],
271
+ "source_video": data["source_video"],
272
+ "height": data["video"][0].size[1],
273
+ "width": data["video"][0].size[0],
274
+ "num_frames": len(data["video"]),
275
+ "cfg_scale": 1,
276
+ "tiled": self.args.tiled,
277
+ "tile_size": (self.args.tile_h, self.args.tile_w),
278
+ "tile_stride": (self.args.tile_stride_h, self.args.tile_stride_w),
279
+ "rand_device": self.pipe.device,
280
+ "seed": None,
281
+ "use_gradient_checkpointing": self.args.use_gradient_checkpointing,
282
+ "use_gradient_checkpointing_offload": self.args.use_gradient_checkpointing_offload,
283
+ "cfg_merge": False,
284
+ "vace_scale": 1,
285
+ }
286
+ with torch.no_grad():
287
+ for unit in self.pipe.units:
288
+ shared, positive, negative = self.pipe.unit_runner(unit, self.pipe, shared, positive, negative)
289
+ reference_latent = self._encode_reference(data["reference_image"])
290
+
291
+ target_latent = shared["input_latents"]
292
+ upsampled_latent = shared["source_latents"]
293
+ target_ll, target_hf = haar_dwt2(target_latent)
294
+ source_ll, _ = haar_dwt2(upsampled_latent)
295
+ _, reference_hf = haar_dwt2(reference_latent)
296
+ reference_hf = reference_hf.repeat(1, 1, target_hf.shape[2], 1, 1)
297
+
298
+ shared.update({
299
+ "target_latent": target_latent,
300
+ "upsampled_latent": upsampled_latent,
301
+ "target_ll": target_ll,
302
+ "target_hf": target_hf,
303
+ "source_ll": source_ll,
304
+ "reference_hf": reference_hf,
305
+ "noise": torch.randn_like(target_hf),
306
+ })
307
+ return {**shared, **positive}
308
+
309
+ def _predict(self, inputs: dict, xt: torch.Tensor, timestep: torch.Tensor) -> torch.Tensor:
310
+ self.pipe.load_models_to_device(self.pipe.in_iteration_models)
311
+ models = {name: getattr(self.pipe, name) for name in self.pipe.in_iteration_models}
312
+ model_inputs = dict(inputs)
313
+ for key in (
314
+ "target_latent", "upsampled_latent", "target_ll", "target_hf", "source_ll",
315
+ "reference_hf", "source_latents", "input_latents", "noise", "latents",
316
+ ):
317
+ model_inputs.pop(key, None)
318
+ # Conditioning is explicit and spatially aligned. The scheduler never
319
+ # evolves LL; it only evolves the 48 HF channels.
320
+ dit_input = torch.cat((inputs["source_ll"], xt), dim=1)
321
+ return self.pipe.model_fn(**models, **model_inputs, latents=dit_input, timestep=timestep)
322
+
323
+ def forward(self, data: dict, inputs: dict | None = None):
324
+ if inputs is None:
325
+ inputs = self.forward_preprocess(data)
326
+ scheduler = self.pipe.scheduler
327
+ random_id = int(torch.randint(0, self.train_timestep_ids.numel(), (1,)).item())
328
+ timestep_id = self.train_timestep_ids[random_id:random_id + 1]
329
+ timestep = scheduler.timesteps[timestep_id].to(dtype=self.pipe.torch_dtype, device=self.pipe.device)
330
+ x0, x1 = inputs["target_hf"], inputs["reference_hf"]
331
+ xt = scheduler.add_noise(x0, x1, inputs["noise"], timestep)
332
+ target_velocity = scheduler.training_target(x0, xt, timestep)
333
+ output = self._predict(inputs, xt, timestep)
334
+ sigma = torch.as_tensor(scheduler.get_sigma(timestep), device=xt.device, dtype=torch.float32)
335
+
336
+ if self.args.target == "stabilized_drift":
337
+ factor = (1.0 + (1.0 - sigma) / (sigma + 1e-5)).sqrt()
338
+ velocity_target = target_velocity.float() / factor
339
+ velocity = output.float() * factor
340
+ else:
341
+ velocity_target = target_velocity.float()
342
+ velocity = output.float()
343
+ endpoint_hf = xt.float() - sigma * velocity
344
+
345
+ bridge_loss = F.mse_loss(output.float(), velocity_target)
346
+ band_loss, band_metrics = normalized_band_l1(endpoint_hf, x0, self.args.latent_channels)
347
+ pred_latent = haar_idwt2(inputs["source_ll"].float(), endpoint_hf)
348
+ reconstruction_loss = F.l1_loss(pred_latent, inputs["target_latent"].float())
349
+ if endpoint_hf.shape[2] > 1:
350
+ temporal_loss = F.l1_loss(
351
+ endpoint_hf[:, :, 1:] - endpoint_hf[:, :, :-1],
352
+ x0.float()[:, :, 1:] - x0.float()[:, :, :-1],
353
+ )
354
+ else:
355
+ temporal_loss = endpoint_hf.new_zeros(())
356
+ loss = (
357
+ self.args.bridge_loss_weight * bridge_loss
358
+ + self.args.band_loss_weight * band_loss
359
+ + self.args.reconstruction_loss_weight * reconstruction_loss
360
+ + self.args.temporal_loss_weight * temporal_loss
361
+ )
362
+ metrics = {
363
+ "sigma": float(sigma.detach().cpu()),
364
+ "brownian_noise_rms": float(
365
+ (scheduler.get_noise_coeff(sigma.detach().cpu()) * inputs["noise"].float())
366
+ .square().mean().sqrt().detach().cpu()
367
+ ),
368
+ "bridge": float(bridge_loss.detach().cpu()),
369
+ "band": float(band_loss.detach().cpu()),
370
+ "reconstruction": float(reconstruction_loss.detach().cpu()),
371
+ "temporal": float(temporal_loss.detach().cpu()),
372
+ **band_metrics,
373
+ }
374
+ return loss, metrics
375
+
376
+
377
+ def add_label(frame: Image.Image, labels: list[str]) -> Image.Image:
378
+ out = frame.copy()
379
+ draw = ImageDraw.Draw(out)
380
+ cell_w = out.width // len(labels)
381
+ for index, label in enumerate(labels):
382
+ x = index * cell_w + 8
383
+ draw.rectangle((x - 4, 4, x + max(90, len(label) * 8), 28), fill=(0, 0, 0))
384
+ draw.text((x, 8), label, fill=(255, 255, 255))
385
+ return out
386
+
387
+
388
+ @torch.no_grad()
389
+ def validate(args, accelerator: Accelerator, model: WaveletBridgeTrainingModule, dataset: Dataset, step: int) -> dict:
390
+ if not accelerator.is_main_process:
391
+ return {}
392
+ module = accelerator.unwrap_model(model)
393
+ pipe = module.pipe
394
+ pipe.eval()
395
+ out_dir = Path(args.output_path) / "validation" / f"step-{step:06d}"
396
+ out_dir.mkdir(parents=True, exist_ok=True)
397
+ rows = []
398
+ for idx in range(min(args.val_batches, len(dataset))):
399
+ data = dataset[idx]
400
+ inputs = module.forward_preprocess(data, apply_text_dropout=False)
401
+ scheduler = copy.deepcopy(pipe.scheduler)
402
+ scheduler.noise_scale = args.val_noise_sigma
403
+ scheduler.set_timesteps(args.val_inference_steps, shift=args.sigma_shift)
404
+ hf = inputs["reference_hf"].clone()
405
+ for timestep_cpu in scheduler.timesteps:
406
+ timestep = timestep_cpu.unsqueeze(0).to(dtype=pipe.torch_dtype, device=pipe.device)
407
+ output = module._predict(inputs, hf, timestep)
408
+ hf = scheduler.step(output, timestep_cpu, hf, inputs["reference_hf"])
409
+ pred_latent = haar_idwt2(inputs["source_ll"], hf)
410
+
411
+ 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))
412
+ 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))
413
+ target_video = pil_video_to_tensor_01(data["video"], pipe.device).unsqueeze(0)
414
+ lr_video = pil_video_to_tensor_01(data["source_video"], pipe.device).unsqueeze(0)
415
+ b, t, c, h, w = lr_video.shape
416
+ 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)
417
+ ref = pil_video_to_tensor_01([data["reference_image"]], pipe.device).unsqueeze(0).repeat(1, target_video.shape[1], 1, 1, 1)
418
+ min_t = min(lr_video.shape[1], up_video.shape[1], pred_video.shape[1], target_video.shape[1])
419
+ diff = (pred_video[:, :min_t] - target_video[:, :min_t]).abs()
420
+ 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)
421
+ labels = ["LR", "UltraFlash", "Reference", "Wavelet Bridge", "Original", "Abs Difference"]
422
+ strip_frames = [add_label(frame, labels) for frame in tensor_btchw_01_to_pil(strip[0])]
423
+ save_video(strip_frames, str(out_dir / f"val_{idx:03d}_lr_up_ref_bridge_original_diff.mp4"), fps=args.fps, quality=5)
424
+ 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)
425
+ data["reference_image"].save(out_dir / f"val_{idx:03d}_reference.png")
426
+
427
+ pixel_mse = F.mse_loss(pred_video[:, :min_t].float(), target_video[:, :min_t].float()).item()
428
+ row = {
429
+ "idx": idx,
430
+ "pixel_mse": pixel_mse,
431
+ "psnr": -10.0 * math.log10(max(pixel_mse, 1e-12)),
432
+ "latent_l1": F.l1_loss(pred_latent.float(), inputs["target_latent"].float()).item(),
433
+ "hf_l1": F.l1_loss(hf.float(), inputs["target_hf"].float()).item(),
434
+ "source_path": data["path"],
435
+ }
436
+ for band_id, name in enumerate(BAND_ORDER):
437
+ sl = slice(band_id * args.latent_channels, (band_id + 1) * args.latent_channels)
438
+ row[f"{name.lower()}_l1"] = F.l1_loss(hf[:, sl].float(), inputs["target_hf"][:, sl].float()).item()
439
+ rows.append(row)
440
+ numeric_keys = [key for key in rows[0] if key not in ("idx", "source_path")] if rows else []
441
+ metrics = {f"val_{key}": sum(float(row[key]) for row in rows) / len(rows) for key in numeric_keys}
442
+ (out_dir / "metrics.json").write_text(json.dumps({"step": step, "rows": rows, "metrics": metrics}, indent=2), encoding="utf-8")
443
+ print(f"[Validation step {step}] {metrics}")
444
+ pipe.train()
445
+ return metrics
446
+
447
+
448
+ def build_run_name(args) -> str:
449
+ bridge = Path(args.bridge_checkpoint).stem
450
+ return (
451
+ f"wavelet_hf_bridge_x{args.sr_scale}_{args.width}x{args.height}_f{args.num_frames}"
452
+ f"_init-{bridge}_steps{args.train_timesteps}_shift{args.sigma_shift:g}"
453
+ f"_noise{args.noise_sigma:g}_s{args.min_train_sigma:g}-{args.max_train_sigma:g}"
454
+ f"_b{args.bridge_loss_weight:g}_band{args.band_loss_weight:g}"
455
+ f"_rec{args.reconstruction_loss_weight:g}_temp{args.temporal_loss_weight:g}"
456
+ f"_lr{args.learning_rate:g}_seed{args.seed}"
457
+ ).replace(".", "p")
458
+
459
+
460
+ def train(args) -> None:
461
+ random.seed(args.seed)
462
+ torch.manual_seed(args.seed)
463
+ save_steps = args.save_steps if args.save_steps and args.save_steps > 0 else None
464
+ if args.output_path is None:
465
+ args.output_path = str(Path(args.output_root) / build_run_name(args))
466
+ dataset_kwargs = dict(
467
+ video_dir=args.video_dir, prompt_json=args.prompt_json, prompt_field=args.prompt_field,
468
+ default_prompt=args.default_prompt, height=args.height, width=args.width,
469
+ num_frames=args.num_frames, sr_scale=args.sr_scale, source_mode="upsampler",
470
+ )
471
+ train_set = SeedanceWaveletBridgeDataset(**dataset_kwargs, repeat=args.dataset_repeat, limit_videos=args.limit_videos, seed=args.seed)
472
+ val_set = SeedanceWaveletBridgeDataset(**dataset_kwargs, repeat=1, limit_videos=max(args.val_batches, 1), seed=args.seed + 1)
473
+ model = WaveletBridgeTrainingModule(args)
474
+ accelerator = Accelerator(
475
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
476
+ kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
477
+ )
478
+ if accelerator.is_main_process:
479
+ Path(args.output_path).mkdir(parents=True, exist_ok=True)
480
+ (Path(args.output_path) / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
481
+ print(f"[Output] {args.output_path}")
482
+ if args.validation_only or args.max_train_steps <= 0:
483
+ model = accelerator.prepare(model)
484
+ validate(args, accelerator, model, val_set, 0)
485
+ return
486
+
487
+ optimizer = torch.optim.AdamW(model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay)
488
+ loader = DataLoader(train_set, shuffle=True, collate_fn=lambda batch: batch[0], num_workers=args.dataset_num_workers)
489
+ model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
490
+ logger = ModelLogger(args.output_path, remove_prefix_in_ckpt="pipe.dit.")
491
+ if args.validate_at_start:
492
+ validate(args, accelerator, model, val_set, 0)
493
+ step = 0
494
+ while step < args.max_train_steps:
495
+ for data in tqdm(loader, disable=not accelerator.is_local_main_process):
496
+ with accelerator.accumulate(model):
497
+ optimizer.zero_grad()
498
+ loss, metrics = model(data)
499
+ accelerator.backward(loss)
500
+ if args.max_grad_norm > 0:
501
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
502
+ optimizer.step()
503
+ if accelerator.sync_gradients:
504
+ step += 1
505
+ logger.on_step_end(accelerator, model, save_steps)
506
+ if accelerator.is_main_process and step % args.log_interval == 0:
507
+ fields = " ".join(f"{key}={value:.6f}" for key, value in metrics.items())
508
+ print(f"[Train step {step}] total={float(loss.detach().cpu()):.6f} {fields}")
509
+ if args.val_interval > 0 and step % args.val_interval == 0:
510
+ validate(args, accelerator, model, val_set, step)
511
+ if step >= args.max_train_steps:
512
+ break
513
+ logger.on_training_end(accelerator, model, save_steps)
514
+
515
+
516
+ def parse_args():
517
+ parser = argparse.ArgumentParser(description="Train a random Brownian Wan Bridge in latent Haar HF subbands, with optional one-step inference.")
518
+ parser.add_argument("--base_model_dir", default="/temp/Wan2.1-T2V-1.3B")
519
+ parser.add_argument("--model_paths", default=None)
520
+ parser.add_argument("--tokenizer_path", default="/temp/Wan2.1-T2V-1.3B/google/umt5-xxl")
521
+ 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")
522
+ parser.add_argument("--resume_checkpoint", default=None)
523
+ parser.add_argument("--video_dir", default="/temp/seedance-2-prompts-datasets/seedance-2/videos/0")
524
+ parser.add_argument("--prompt_json", default="/temp/seedance-2-prompts-datasets/metadata.jsonl")
525
+ parser.add_argument("--prompt_field", choices=["raw_p", "en", "zh", "en_title", "zh_title"], default="raw_p")
526
+ parser.add_argument("--default_prompt", default="")
527
+ parser.add_argument("--output_root", default="/cache/outputs_bridge_wan_sr_wavelet")
528
+ parser.add_argument("--output_path", default=None)
529
+ parser.add_argument("--height", type=int, default=480)
530
+ parser.add_argument("--width", type=int, default=832)
531
+ parser.add_argument("--num_frames", type=int, default=81)
532
+ parser.add_argument("--sr_scale", type=int, default=2)
533
+ parser.add_argument("--latent_channels", type=int, default=16)
534
+ parser.add_argument("--ultraflash_dir", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference")
535
+ parser.add_argument("--ultraflash_sr_config", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py")
536
+ parser.add_argument("--latent_upsampler_ckpt", default="/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth")
537
+ parser.add_argument("--upsampler_dtype", choices=["bf16", "fp16", "fp32"], default="bf16")
538
+ parser.add_argument("--train_timesteps", type=int, default=1000, help="Resolution of the random Brownian training-sigma schedule; inference can still use one step.")
539
+ parser.add_argument("--sigma_shift", type=float, default=5.0)
540
+ parser.add_argument("--noise_sigma", type=float, default=1.0, help="Brownian noise amplitude multiplying sqrt(sigma*(1-sigma))*epsilon.")
541
+ parser.add_argument("--min_train_sigma", type=float, default=0.02)
542
+ parser.add_argument("--max_train_sigma", type=float, default=0.98)
543
+ parser.add_argument("--target", choices=["stabilized_drift", "drift"], default="stabilized_drift")
544
+ parser.add_argument("--bridge_loss_weight", type=float, default=1.0)
545
+ parser.add_argument("--band_loss_weight", type=float, default=1.0)
546
+ parser.add_argument("--reconstruction_loss_weight", type=float, default=1.0)
547
+ parser.add_argument("--temporal_loss_weight", type=float, default=0.2)
548
+ parser.add_argument("--learning_rate", type=float, default=1e-5)
549
+ parser.add_argument("--weight_decay", type=float, default=0.01)
550
+ parser.add_argument("--max_train_steps", type=int, default=5000)
551
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
552
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
553
+ parser.add_argument("--save_steps", type=int, default=500)
554
+ parser.add_argument("--log_interval", type=int, default=1)
555
+ parser.add_argument("--val_interval", type=int, default=100)
556
+ parser.add_argument("--val_batches", type=int, default=1)
557
+ parser.add_argument("--val_inference_steps", type=int, default=1)
558
+ parser.add_argument("--val_noise_sigma", type=float, default=0.0)
559
+ parser.add_argument("--validate_at_start", action="store_true")
560
+ parser.add_argument("--validation_only", action="store_true")
561
+ parser.add_argument("--limit_videos", type=int, default=None)
562
+ parser.add_argument("--dataset_repeat", type=int, default=1)
563
+ parser.add_argument("--dataset_num_workers", type=int, default=0)
564
+ parser.add_argument("--text_drop_probability", type=float, default=0.0)
565
+ parser.add_argument("--use_gradient_checkpointing", action=argparse.BooleanOptionalAction, default=True)
566
+ parser.add_argument("--use_gradient_checkpointing_offload", action="store_true")
567
+ parser.add_argument("--find_unused_parameters", action="store_true")
568
+ parser.add_argument("--tiled", action="store_true")
569
+ parser.add_argument("--tile_h", type=int, default=30)
570
+ parser.add_argument("--tile_w", type=int, default=52)
571
+ parser.add_argument("--tile_stride_h", type=int, default=15)
572
+ parser.add_argument("--tile_stride_w", type=int, default=26)
573
+ parser.add_argument("--fps", type=int, default=16)
574
+ parser.add_argument("--seed", type=int, default=42)
575
+ args = parser.parse_args()
576
+ if args.model_paths is None:
577
+ args.model_paths = default_model_paths(args.base_model_dir)
578
+ return args
579
+
580
+
581
+ if __name__ == "__main__":
582
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
583
+ train(parse_args())
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ ARGS=(
13
+ diffsynth/bridge/wan_bridge/model_training/train_sr_wavelet_bridge.py
14
+ --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}"
15
+ --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}"
16
+ --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}"
17
+ --video_dir "${VIDEO_DIR:-/temp/seedance-2-prompts-datasets/seedance-2/videos/0}"
18
+ --prompt_json "${PROMPT_JSON:-/temp/seedance-2-prompts-datasets/metadata.jsonl}"
19
+ --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan_sr_wavelet}"
20
+ --height "${HEIGHT:-480}"
21
+ --width "${WIDTH:-832}"
22
+ --num_frames "${NUM_FRAMES:-81}"
23
+ --sr_scale "${SR_SCALE:-2}"
24
+ --ultraflash_dir "${ULTRAFLASH_DIR:-/home/ma-user/workspace/rongxiang/UltraFlash/inference}"
25
+ --ultraflash_sr_config "${ULTRAFLASH_SR_CONFIG:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/configs/sr_sparse_ultraforcing.py}"
26
+ --latent_upsampler_ckpt "${LATENT_UPSAMPLER_CKPT:-/home/ma-user/workspace/rongxiang/UltraFlash/inference/checkpoints/1K-ultraLatentUpsampler-step_19900.pth}"
27
+ --train_timesteps "${TRAIN_TIMESTEPS:-1000}"
28
+ --sigma_shift "${SIGMA_SHIFT:-5}"
29
+ --noise_sigma "${NOISE_SIGMA:-1}"
30
+ --min_train_sigma "${MIN_TRAIN_SIGMA:-0.02}"
31
+ --max_train_sigma "${MAX_TRAIN_SIGMA:-0.98}"
32
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1}"
33
+ --band_loss_weight "${BAND_LOSS_WEIGHT:-1}"
34
+ --reconstruction_loss_weight "${RECONSTRUCTION_LOSS_WEIGHT:-1}"
35
+ --temporal_loss_weight "${TEMPORAL_LOSS_WEIGHT:-0.5}"
36
+ --learning_rate "${LEARNING_RATE:-1e-5}"
37
+ --weight_decay "${WEIGHT_DECAY:-0.01}"
38
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}"
39
+ --gradient_accumulation_steps "${GRADIENT_ACCUMULATION_STEPS:-1}"
40
+ --save_steps "${SAVE_STEPS:-500}"
41
+ --val_interval "${VAL_INTERVAL:-100}"
42
+ --val_batches "${VAL_BATCHES:-1}"
43
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-1}"
44
+ --dataset_repeat "${DATASET_REPEAT:-1}"
45
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-0}"
46
+ --validate_at_start
47
+ )
48
+
49
+ if [[ -n "${LIMIT_VIDEOS:-}" ]]; then ARGS+=(--limit_videos "${LIMIT_VIDEOS}"); fi
50
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then ARGS+=(--output_path "${OUTPUT_PATH}"); fi
51
+ if [[ -n "${RESUME_CHECKPOINT:-}" ]]; then ARGS+=(--resume_checkpoint "${RESUME_CHECKPOINT}"); fi
52
+ if [[ "${TILED:-0}" == "1" ]]; then ARGS+=(--tiled); fi
53
+
54
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ PYTHON_BIN="${PYTHON_BIN:-/cache/rongxiang/conda_envs/la/bin/python}"
8
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
9
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
10
+ export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
11
+
12
+ TRAIN_SCRIPT="diffsynth/bridge/wan_bridge/model_training/train_sr_wan22_ti2v_edit.py"
13
+
14
+ ARGS=(
15
+ "${TRAIN_SCRIPT}"
16
+ --base_model_dir "${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}"
17
+ --dit_init_checkpoint "${DIT_INIT_CHECKPOINT:-/cache/UltraFlash/2K-Causal-Sparse-SR-Dit-fidelity-step_12800.pth}"
18
+ --tokenizer_path "${TOKENIZER_PATH:-/temp/Wan2.1-T2V-1.3B/google/umt5-xxl}"
19
+ --dataset_root "${DATASET_ROOT:-/cache/OpenVE-OneShard-5k}"
20
+ --manifest_path "${MANIFEST_PATH:-/cache/OpenVE-OneShard-5k/metadata.json}"
21
+ --output_root "${OUTPUT_ROOT:-/cache/outputs_bridge_wan21_openve_one_shard_5k}"
22
+ --height "${HEIGHT:-480}"
23
+ --width "${WIDTH:-832}"
24
+ --num_frames "${NUM_FRAMES:-81}"
25
+ --sr_scale "${SR_SCALE:-4}"
26
+ --fps "${FPS:-20}"
27
+ --dataset_repeat "${DATASET_REPEAT:-1}"
28
+ --dataset_num_workers "${DATASET_NUM_WORKERS:-8}"
29
+ --torch_dtype "${TORCH_DTYPE:-float16}"
30
+ --max_train_steps "${MAX_TRAIN_STEPS:-5000}"
31
+ --gradient_accumulation_steps "${GRADIENT_ACCUMULATION_STEPS:-1}"
32
+ --trainable_models "${TRAINABLE_MODELS:-dit}"
33
+ --lora_target_modules "${LORA_TARGET_MODULES:-q,k,v,o,ffn.0,ffn.2}"
34
+ --lora_rank "${LORA_RANK:-32}"
35
+ --learning_rate "${LEARNING_RATE:-1.0}"
36
+ --weight_decay "${WEIGHT_DECAY:-0.01}"
37
+ --d_coef "${D_COEF:-1.0}"
38
+ --bridge_loss_weight "${BRIDGE_LOSS_WEIGHT:-1.0}"
39
+ --pixel_loss_weight "${PIXEL_LOSS_WEIGHT:-2.0}"
40
+ --pixel_loss_crop_size "${PIXEL_LOSS_CROP_SIZE:-400}"
41
+ --pixel_loss_latent_frames "${PIXEL_LOSS_LATENT_FRAMES:-3}"
42
+ --lpips_weight "${LPIPS_WEIGHT:-1.0}"
43
+ --lpips_net "${LPIPS_NET:-vgg}"
44
+ --lpips_num_frames "${LPIPS_NUM_FRAMES:-4}"
45
+ --lpips_crop_size "${LPIPS_CROP_SIZE:-224}"
46
+ --ssim_weight "${SSIM_WEIGHT:-1.0}"
47
+ --ssim_window_size "${SSIM_WINDOW_SIZE:-11}"
48
+ --noise_sigma "${NOISE_SIGMA:-1.0}"
49
+ --val_sampling_noise_scale "${VAL_SAMPLING_NOISE_SCALE:-0.0}"
50
+ --val_interval "${VAL_INTERVAL:-100}"
51
+ --val_samples_per_task "${VAL_SAMPLES_PER_TASK:-2}"
52
+ --val_inference_steps "${VAL_INFERENCE_STEPS:-8}"
53
+ --val_sigma_shift "${VAL_SIGMA_SHIFT:-5.0}"
54
+ --save_steps "${SAVE_STEPS:-400}"
55
+ --seed "${SEED:-42}"
56
+ )
57
+
58
+ if [[ -n "${LORA_CHECKPOINT:-}" ]]; then
59
+ ARGS+=(--lora_checkpoint "${LORA_CHECKPOINT}")
60
+ fi
61
+ if [[ -n "${OUTPUT_PATH:-}" ]]; then
62
+ ARGS+=(--output_path "${OUTPUT_PATH}")
63
+ fi
64
+ if [[ -n "${LIMIT_SAMPLES:-}" ]]; then
65
+ ARGS+=(--limit_samples "${LIMIT_SAMPLES}")
66
+ fi
67
+ if [[ "${VAL_LPIPS:-1}" != "0" ]]; then
68
+ ARGS+=(--val_lpips)
69
+ fi
70
+ if [[ "${VAL_SSIM:-1}" != "0" ]]; then
71
+ ARGS+=(--val_ssim)
72
+ fi
73
+ if [[ "${TILED:-0}" != "0" ]]; then
74
+ ARGS+=(--tiled)
75
+ fi
76
+ if [[ "${VALIDATE_AT_START:-1}" != "0" ]]; then
77
+ ARGS+=(--validate_at_start)
78
+ fi
79
+ if [[ "${USE_GRADIENT_CHECKPOINTING_OFFLOAD:-0}" != "0" ]]; then
80
+ ARGS+=(--use_gradient_checkpointing_offload)
81
+ fi
82
+
83
+ "${PYTHON_BIN}" "${ARGS[@]}" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit_npu.sh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
5
+ cd "${REPO_DIR}"
6
+
7
+ SYSTEM_CANN_ROOT="${SYSTEM_CANN_ROOT:-/usr/local/Ascend/cann-8.5.2}"
8
+ CANN_ROOT="${CANN_ROOT:-/temp/rongxiang/cann-user-8.5.2}"
9
+
10
+ # The ModelArts image has the compiler/runtime but an incomplete 910B OPP
11
+ # directory. Use the persistent user-space CANN archive for OPP kernels and
12
+ # keep the system compiler/runtime as the ABI-compatible base.
13
+ source "${SYSTEM_CANN_ROOT}/set_env.sh" 2>/dev/null || true
14
+ if [[ -d "${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe/kernel/ascend910b" ]]; then
15
+ export ASCEND_HOME_PATH="${SYSTEM_CANN_ROOT}"
16
+ export ASCEND_TOOLKIT_HOME="${SYSTEM_CANN_ROOT}"
17
+ export ASCEND_AICPU_PATH="${SYSTEM_CANN_ROOT}"
18
+ export ASCEND_COMPILER_PATH="${SYSTEM_CANN_ROOT}/compiler"
19
+ export ASCEND_OPP_PATH="${CANN_ROOT}/opp"
20
+ export TBE_IMPL_PATH="${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe"
21
+ export PYTHONPATH="${CANN_ROOT}/python/site-packages:${CANN_ROOT}/opp/built-in/op_impl/ai_core/tbe:${PYTHONPATH:-}"
22
+ 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:-}"
23
+ else
24
+ echo "Warning: complete CANN OPP archive not found at ${CANN_ROOT}; using system CANN." >&2
25
+ fi
26
+
27
+ PYTHON_BIN="${PYTHON_BIN:-/home/ma-user/anaconda3/envs/PyTorch-2.7.1/bin/python}"
28
+ export PYTHON_BIN
29
+ export PYTHONPATH="${REPO_DIR}:${PYTHONPATH:-}"
30
+ export TOKENIZERS_PARALLELISM="${TOKENIZERS_PARALLELISM:-false}"
31
+ export ASCEND_RT_VISIBLE_DEVICES="${ASCEND_RT_VISIBLE_DEVICES:-0,1,2,3,4,5,6,7}"
32
+ export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-1800}"
33
+ export TASK_QUEUE_ENABLE="${TASK_QUEUE_ENABLE:-2}"
34
+ export COMBINED_ENABLE="${COMBINED_ENABLE:-1}"
35
+ export SOC_VERSION="${SOC_VERSION:-Ascend910B3}"
36
+ export ASCEND_SOC_VERSION="${ASCEND_SOC_VERSION:-${SOC_VERSION}}"
37
+
38
+ # Some ModelArts login profiles export stale custom paths. They must not
39
+ # override the selected OPP archive.
40
+ unset ASCEND_CUSTOM_OPP_PATH ME_TBE_PLUGIN_PATH OPTION_EXEC_EXTERN_PLUGIN_PATH
41
+
42
+ # Keep NPU assets and outputs separate from the A100 run.
43
+ export BASE_MODEL_DIR="${BASE_MODEL_DIR:-/temp/Wan2.1-T2V-1.3B}"
44
+ export DATASET_ROOT="${DATASET_ROOT:-/cache/OpenVE-OneShard-5k}"
45
+ export MANIFEST_PATH="${MANIFEST_PATH:-/cache/OpenVE-OneShard-5k/metadata.json}"
46
+ export OUTPUT_ROOT="${OUTPUT_ROOT:-/cache/outputs_bridge_wan21_openve_one_shard_5k_npu}"
47
+ export DATASET_NUM_WORKERS="${DATASET_NUM_WORKERS:-1}"
48
+ export TORCH_DTYPE="${TORCH_DTYPE:-float16}"
49
+ export VAL_LPIPS="${VAL_LPIPS:-0}"
50
+ export VAL_SSIM="${VAL_SSIM:-0}"
51
+ export VALIDATE_AT_START="${VALIDATE_AT_START:-0}"
52
+
53
+ NNODES="${NNODES:-1}"
54
+ NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
55
+ MASTER_ADDR="${MASTER_ADDR:-127.0.0.1}"
56
+ MASTER_PORT="${MASTER_PORT:-29688}"
57
+
58
+ export MASTER_ADDR MASTER_PORT
59
+
60
+ exec "${PYTHON_BIN}" -m torch.distributed.run \
61
+ --no_python \
62
+ --nnodes="${NNODES}" \
63
+ --nproc_per_node="${NPROC_PER_NODE}" \
64
+ --master_addr="${MASTER_ADDR}" \
65
+ --master_port="${MASTER_PORT}" \
66
+ "${REPO_DIR}/diffsynth/bridge/wan_bridge/model_training/train_wan21_t2v_edit.sh" "$@"
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/visualize_sobel_edges.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Visualize the exact Sobel edge mask used by reference-adapter training."""
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import imageio
9
+ import numpy as np
10
+ import torch
11
+ import torchvision.transforms.functional as TVF
12
+ from PIL import Image, ImageDraw
13
+
14
+ from sobel_utils import dilated_sobel_edge_mask, sobel_rgb_gradients
15
+
16
+ REPO_ROOT = Path(__file__).resolve().parents[4]
17
+
18
+
19
+ def center_crop_resize(image: Image.Image, height: int, width: int) -> Image.Image:
20
+ """Match the training pipeline's bicubic resize followed by center crop."""
21
+ image_w, image_h = image.size
22
+ scale = max(width / image_w, height / image_h)
23
+ resized = TVF.resize(
24
+ image,
25
+ (round(image_h * scale), round(image_w * scale)),
26
+ interpolation=TVF.InterpolationMode.BICUBIC,
27
+ )
28
+ return TVF.center_crop(resized, (height, width))
29
+
30
+
31
+ def parse_args() -> argparse.Namespace:
32
+ parser = argparse.ArgumentParser(
33
+ description="Render original/Sobel/thin-mask/dilated-mask/overlay panels for a video."
34
+ )
35
+ parser.add_argument("--input_video", required=True)
36
+ parser.add_argument("--output_video", default=None)
37
+ parser.add_argument("--height", type=int, default=832)
38
+ parser.add_argument("--width", type=int, default=480)
39
+ parser.add_argument(
40
+ "--no_resize",
41
+ action="store_true",
42
+ help="Keep the source resolution instead of applying the training center-crop resize.",
43
+ )
44
+ parser.add_argument("--start_frame", type=int, default=0)
45
+ parser.add_argument("--num_frames", type=int, default=0, help="0 means all remaining frames.")
46
+ parser.add_argument("--fps", type=float, default=None, help="Defaults to the source FPS, then 16.")
47
+ parser.add_argument("--sobel_edge_dilation_radius", type=int, default=0)
48
+ parser.add_argument("--sobel_edge_threshold", type=float, default=1.0)
49
+ parser.add_argument(
50
+ "--magnitude_display_scale",
51
+ type=float,
52
+ default=3.0,
53
+ help="Display white is threshold times this value; this affects visualization only.",
54
+ )
55
+ return parser.parse_args()
56
+
57
+
58
+ def default_output_path(input_path: Path, radius: int, threshold: float) -> Path:
59
+ threshold_text = f"{threshold:g}".replace(".", "p")
60
+ return REPO_ROOT / "outputs" / "sobel_visualizations" / (
61
+ f"{input_path.stem}_sobel_r{radius}_thr{threshold_text}.mp4"
62
+ )
63
+
64
+
65
+ def uint8_rgb(tensor_chw: torch.Tensor) -> np.ndarray:
66
+ return (
67
+ tensor_chw.detach()
68
+ .clamp(0, 1)
69
+ .mul(255)
70
+ .round()
71
+ .byte()
72
+ .permute(1, 2, 0)
73
+ .cpu()
74
+ .numpy()
75
+ )
76
+
77
+
78
+ def add_labels(canvas: np.ndarray, labels: list[str], panel_width: int) -> np.ndarray:
79
+ image = Image.fromarray(canvas)
80
+ draw = ImageDraw.Draw(image)
81
+ bar_height = 30
82
+ for index, label in enumerate(labels):
83
+ left = index * panel_width
84
+ draw.rectangle((left, 0, left + panel_width, bar_height), fill=(0, 0, 0))
85
+ draw.text((left + 8, 8), label, fill=(255, 255, 255))
86
+ return np.asarray(image)
87
+
88
+
89
+ def render_frame(
90
+ frame: np.ndarray,
91
+ height: int,
92
+ width: int,
93
+ no_resize: bool,
94
+ dilation_radius: int,
95
+ threshold_multiplier: float,
96
+ magnitude_display_scale: float,
97
+ ) -> tuple[np.ndarray, dict[str, float]]:
98
+ image = Image.fromarray(np.asarray(frame)).convert("RGB")
99
+ if not no_resize:
100
+ image = center_crop_resize(image, height, width)
101
+
102
+ original = torch.from_numpy(np.asarray(image).copy()).permute(2, 0, 1).float().div(255.0)
103
+ video = original.unsqueeze(0).unsqueeze(0)
104
+ gradient_x, gradient_y = sobel_rgb_gradients(video)
105
+ magnitude, threshold, thin_mask, dilated_mask = dilated_sobel_edge_mask(
106
+ gradient_x,
107
+ gradient_y,
108
+ dilation_radius=dilation_radius,
109
+ threshold_multiplier=threshold_multiplier,
110
+ )
111
+
112
+ display_denominator = threshold * max(float(magnitude_display_scale), 1e-6) + 1e-12
113
+ magnitude_rgb = (magnitude / display_denominator).clamp(0, 1).repeat(1, 3, 1, 1)[0]
114
+ thin_rgb = thin_mask.repeat(1, 3, 1, 1)[0]
115
+ dilated_rgb = dilated_mask.repeat(1, 3, 1, 1)[0]
116
+
117
+ overlay = original.clone()
118
+ dilated = dilated_mask[0]
119
+ thin = thin_mask[0]
120
+ red = original.new_tensor([1.0, 0.0, 0.0]).view(3, 1, 1)
121
+ yellow = original.new_tensor([1.0, 1.0, 0.0]).view(3, 1, 1)
122
+ overlay = overlay * (1.0 - 0.40 * dilated) + red * (0.40 * dilated)
123
+ overlay = overlay * (1.0 - 0.85 * thin) + yellow * (0.85 * thin)
124
+
125
+ panels = [
126
+ uint8_rgb(original),
127
+ uint8_rgb(magnitude_rgb),
128
+ uint8_rgb(thin_rgb),
129
+ uint8_rgb(dilated_rgb),
130
+ uint8_rgb(overlay),
131
+ ]
132
+ labels = [
133
+ "Original",
134
+ "Sobel magnitude",
135
+ "Thin edge mask",
136
+ f"Dilated mask (r={dilation_radius})",
137
+ "Overlay",
138
+ ]
139
+ visualization = add_labels(np.concatenate(panels, axis=1), labels, original.shape[-1])
140
+ metrics = {
141
+ "threshold": float(threshold.item()),
142
+ "thin_edge_ratio": float(thin_mask.mean().item()),
143
+ "dilated_edge_ratio": float(dilated_mask.mean().item()),
144
+ "mean_magnitude": float(magnitude.mean().item()),
145
+ }
146
+ return visualization, metrics
147
+
148
+
149
+ def main() -> None:
150
+ args = parse_args()
151
+ input_path = Path(args.input_video).expanduser().resolve()
152
+ if not input_path.is_file():
153
+ raise FileNotFoundError(f"Input video does not exist: {input_path}")
154
+ if args.start_frame < 0 or args.num_frames < 0:
155
+ raise ValueError("start_frame and num_frames must be non-negative")
156
+
157
+ output_path = (
158
+ Path(args.output_video).expanduser().resolve()
159
+ if args.output_video
160
+ else default_output_path(input_path, args.sobel_edge_dilation_radius, args.sobel_edge_threshold)
161
+ )
162
+ output_path.parent.mkdir(parents=True, exist_ok=True)
163
+
164
+ reader = imageio.get_reader(str(input_path))
165
+ metadata = reader.get_meta_data()
166
+ fps = float(args.fps or metadata.get("fps") or 16.0)
167
+ writer = imageio.get_writer(
168
+ str(output_path), fps=fps, codec="libx264", quality=7, macro_block_size=1
169
+ )
170
+
171
+ frame_metrics: list[dict[str, float | int]] = []
172
+ preview_path = output_path.with_name(f"{output_path.stem}_preview.jpg")
173
+ try:
174
+ frame_index = args.start_frame
175
+ while args.num_frames == 0 or len(frame_metrics) < args.num_frames:
176
+ try:
177
+ frame = reader.get_data(frame_index)
178
+ except (IndexError, EOFError):
179
+ break
180
+ visualization, metrics = render_frame(
181
+ frame=frame,
182
+ height=args.height,
183
+ width=args.width,
184
+ no_resize=args.no_resize,
185
+ dilation_radius=args.sobel_edge_dilation_radius,
186
+ threshold_multiplier=args.sobel_edge_threshold,
187
+ magnitude_display_scale=args.magnitude_display_scale,
188
+ )
189
+ writer.append_data(visualization)
190
+ if not frame_metrics:
191
+ Image.fromarray(visualization).save(preview_path, quality=95)
192
+ frame_metrics.append({"frame_index": frame_index, **metrics})
193
+ frame_index += 1
194
+ finally:
195
+ writer.close()
196
+ reader.close()
197
+
198
+ if not frame_metrics:
199
+ output_path.unlink(missing_ok=True)
200
+ raise RuntimeError(f"No frames were read from {input_path} at start_frame={args.start_frame}")
201
+
202
+ summary = {
203
+ "input_video": str(input_path),
204
+ "output_video": str(output_path),
205
+ "preview_image": str(preview_path),
206
+ "fps": fps,
207
+ "processed_frames": len(frame_metrics),
208
+ "preprocessing": "source resolution" if args.no_resize else "training center-crop resize",
209
+ "height": int(frame_metrics and visualization.shape[0]),
210
+ "panel_width": int(visualization.shape[1] // 5),
211
+ "sobel_kernel_normalization": "1/8",
212
+ "sobel_edge_dilation_radius": args.sobel_edge_dilation_radius,
213
+ "dilation_kernel_size": 2 * args.sobel_edge_dilation_radius + 1,
214
+ "sobel_edge_threshold_multiplier": args.sobel_edge_threshold,
215
+ "threshold_rule": "per-frame mean RGB Sobel magnitude * multiplier",
216
+ "mean_threshold": float(np.mean([row["threshold"] for row in frame_metrics])),
217
+ "mean_thin_edge_ratio": float(np.mean([row["thin_edge_ratio"] for row in frame_metrics])),
218
+ "mean_dilated_edge_ratio": float(np.mean([row["dilated_edge_ratio"] for row in frame_metrics])),
219
+ "frames": frame_metrics,
220
+ }
221
+ json_path = output_path.with_suffix(".json")
222
+ with json_path.open("w", encoding="utf-8") as file:
223
+ json.dump(summary, file, ensure_ascii=False, indent=2)
224
+
225
+ print(f"Saved visualization: {output_path}")
226
+ print(f"Saved preview: {preview_path}")
227
+ print(f"Saved statistics: {json_path}")
228
+ print(
229
+ f"Frames={len(frame_metrics)}, thin={summary['mean_thin_edge_ratio']:.4f}, "
230
+ f"dilated={summary['mean_dilated_edge_ratio']:.4f}"
231
+ )
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
releases/2026-10-20-code/diffsynth/bridge/wan_bridge/model_training/wan_video_new.py ADDED
@@ -0,0 +1,1751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, warnings, glob, os, types
2
+ import numpy as np
3
+ from PIL import Image
4
+ from einops import repeat, reduce
5
+ from typing import Optional, Union
6
+ from dataclasses import dataclass
7
+ try:
8
+ from modelscope import snapshot_download
9
+ except ModuleNotFoundError:
10
+ snapshot_download = None
11
+ from einops import rearrange
12
+ import numpy as np
13
+ from PIL import Image
14
+ from tqdm import tqdm
15
+ from typing import Optional
16
+ from typing_extensions import Literal
17
+
18
+ from ..utils import BasePipeline, ModelConfig, PipelineUnit, PipelineUnitRunner
19
+ from ..models.model_manager import ModelManager
20
+ from ..models.utils import load_state_dict
21
+ from ..models.wan_video_dit import WanModel, RMSNorm, sinusoidal_embedding_1d
22
+ from ..models.wan_video_dit_s2v import rope_precompute
23
+ from ..models.wan_video_text_encoder import WanTextEncoder, T5RelativeEmbedding, T5LayerNorm
24
+ from ..models.wan_video_vae import WanVideoVAE, RMS_norm, CausalConv3d, Upsample
25
+ from ..models.wan_video_image_encoder import WanImageEncoder
26
+ from ..models.wan_video_vace import VaceWanModel
27
+ from ..models.wan_video_motion_controller import WanMotionControllerModel
28
+ from ..models.wan_video_animate_adapter import WanAnimateAdapter
29
+ from ..schedulers.flow_match import FlowMatchScheduler
30
+ from ..prompters.wan_prompter import WanPrompter
31
+ from ..vram_management import enable_vram_management, AutoWrappedModule, AutoWrappedLinear, WanAutoCastLayerNorm
32
+ from ..lora import GeneralLoRALoader
33
+ from .attention_masks import build_token_prefix_attention_spec
34
+
35
+
36
+
37
+ def make_device_tensor(values, device, dtype):
38
+ return torch.as_tensor(values, dtype=torch.float32).to(device=device, dtype=dtype)
39
+
40
+
41
+ class WanVideoPipeline(BasePipeline):
42
+
43
+ def __init__(self, device="npu", torch_dtype=torch.float16, tokenizer_path=None):
44
+ super().__init__(
45
+ device=device, torch_dtype=torch_dtype,
46
+ height_division_factor=16, width_division_factor=16, time_division_factor=4, time_division_remainder=1
47
+ )
48
+ self.scheduler = FlowMatchScheduler(shift=5, sigma_min=0.0, extra_one_step=True)
49
+ self.prompter = WanPrompter(tokenizer_path=tokenizer_path)
50
+ self.text_encoder: WanTextEncoder = None
51
+ self.image_encoder: WanImageEncoder = None
52
+ self.dit: WanModel = None
53
+ self.dit2: WanModel = None
54
+ self.vae: WanVideoVAE = None
55
+ self.motion_controller: WanMotionControllerModel = None
56
+ self.vace: VaceWanModel = None
57
+ self.vace2: VaceWanModel = None
58
+ self.animate_adapter: WanAnimateAdapter = None
59
+ self.in_iteration_models = ("dit", "motion_controller", "vace", "animate_adapter")
60
+ self.in_iteration_models_2 = ("dit2", "motion_controller", "vace2", "animate_adapter")
61
+ self.unit_runner = PipelineUnitRunner()
62
+ self.units = [
63
+ WanVideoUnit_ShapeChecker(),
64
+ WanVideoUnit_NoiseInitializer(),
65
+ WanVideoUnit_PromptEmbedder(),
66
+ WanVideoUnit_S2V(),
67
+ WanVideoUnit_InputVideoEmbedder(),
68
+ WanVideoUnit_ImageEmbedderVAE(),
69
+ WanVideoUnit_ImageEmbedderCLIP(),
70
+ WanVideoUnit_ImageEmbedderFused(),
71
+ WanVideoUnit_FunControl(),
72
+ WanVideoUnit_FunReference(),
73
+ WanVideoUnit_FunCameraControl(),
74
+ WanVideoUnit_SpeedControl(),
75
+ WanVideoUnit_VACE(),
76
+ WanVideoPostUnit_AnimateVideoSplit(),
77
+ WanVideoPostUnit_AnimatePoseLatents(),
78
+ WanVideoPostUnit_AnimateFacePixelValues(),
79
+ WanVideoPostUnit_AnimateInpaint(),
80
+ WanVideoUnit_UnifiedSequenceParallel(),
81
+ WanVideoUnit_TeaCache(),
82
+ WanVideoUnit_CfgMerger(),
83
+ ]
84
+ self.post_units = [
85
+ WanVideoPostUnit_S2V(),
86
+ ]
87
+ self.model_fn = model_fn_wan_video
88
+
89
+ def load_lora(
90
+ self,
91
+ module: torch.nn.Module,
92
+ lora_config: Union[ModelConfig, str] = None,
93
+ alpha=1,
94
+ hotload=False,
95
+ state_dict=None,
96
+ ):
97
+ if state_dict is None:
98
+ if isinstance(lora_config, str):
99
+ lora = load_state_dict(lora_config, torch_dtype=self.torch_dtype, device=self.device)
100
+ else:
101
+ lora_config.download_if_necessary()
102
+ lora = load_state_dict(lora_config.path, torch_dtype=self.torch_dtype, device=self.device)
103
+ else:
104
+ lora = state_dict
105
+ if hotload:
106
+ for name, module in module.named_modules():
107
+ if isinstance(module, AutoWrappedLinear):
108
+ lora_a_name = f'{name}.lora_A.default.weight'
109
+ lora_b_name = f'{name}.lora_B.default.weight'
110
+ if lora_a_name in lora and lora_b_name in lora:
111
+ module.lora_A_weights.append(lora[lora_a_name] * alpha)
112
+ module.lora_B_weights.append(lora[lora_b_name])
113
+ else:
114
+ loader = GeneralLoRALoader(torch_dtype=self.torch_dtype, device=self.device)
115
+ loader.load(module, lora, alpha=alpha)
116
+
117
+ def training_loss(self, **inputs):
118
+ max_timestep_boundary = int(inputs.get("max_timestep_boundary", 1) * self.scheduler.num_train_timesteps)
119
+ min_timestep_boundary = int(inputs.get("min_timestep_boundary", 0) * self.scheduler.num_train_timesteps)
120
+ timestep_id = torch.randint(min_timestep_boundary, max_timestep_boundary, (1,))
121
+ timestep = self.scheduler.timesteps[timestep_id].to(dtype=self.torch_dtype, device=self.device)
122
+
123
+ inputs["latents"] = self.scheduler.add_noise(inputs["input_latents"], inputs["noise"], timestep)
124
+ training_target = self.scheduler.training_target(inputs["input_latents"], inputs["noise"], timestep)
125
+
126
+ noise_pred = self.model_fn(**inputs, timestep=timestep)
127
+
128
+ loss = torch.nn.functional.mse_loss(noise_pred.float(), training_target.float())
129
+ loss = loss * self.scheduler.training_weight(timestep)
130
+ return loss
131
+
132
+
133
+ def enable_vram_management(self, num_persistent_param_in_dit=None, vram_limit=None, vram_buffer=0.5):
134
+ self.vram_management_enabled = True
135
+ if num_persistent_param_in_dit is not None:
136
+ vram_limit = None
137
+ else:
138
+ if vram_limit is None:
139
+ vram_limit = self.get_vram()
140
+ vram_limit = vram_limit - vram_buffer
141
+ if self.text_encoder is not None:
142
+ dtype = next(iter(self.text_encoder.parameters())).dtype
143
+ enable_vram_management(
144
+ self.text_encoder,
145
+ module_map = {
146
+ torch.nn.Linear: AutoWrappedLinear,
147
+ torch.nn.Embedding: AutoWrappedModule,
148
+ T5RelativeEmbedding: AutoWrappedModule,
149
+ T5LayerNorm: AutoWrappedModule,
150
+ },
151
+ module_config = dict(
152
+ offload_dtype=dtype,
153
+ offload_device="cpu",
154
+ onload_dtype=dtype,
155
+ onload_device="cpu",
156
+ computation_dtype=self.torch_dtype,
157
+ computation_device=self.device,
158
+ ),
159
+ vram_limit=vram_limit,
160
+ )
161
+ if self.dit is not None:
162
+ dtype = next(iter(self.dit.parameters())).dtype
163
+ device = "cpu" if vram_limit is not None else self.device
164
+ enable_vram_management(
165
+ self.dit,
166
+ module_map = {
167
+ torch.nn.Linear: AutoWrappedLinear,
168
+ torch.nn.Conv3d: AutoWrappedModule,
169
+ torch.nn.LayerNorm: WanAutoCastLayerNorm,
170
+ RMSNorm: AutoWrappedModule,
171
+ torch.nn.Conv2d: AutoWrappedModule,
172
+ torch.nn.Conv1d: AutoWrappedModule,
173
+ torch.nn.Embedding: AutoWrappedModule,
174
+ },
175
+ module_config = dict(
176
+ offload_dtype=dtype,
177
+ offload_device="cpu",
178
+ onload_dtype=dtype,
179
+ onload_device=device,
180
+ computation_dtype=self.torch_dtype,
181
+ computation_device=self.device,
182
+ ),
183
+ max_num_param=num_persistent_param_in_dit,
184
+ overflow_module_config = dict(
185
+ offload_dtype=dtype,
186
+ offload_device="cpu",
187
+ onload_dtype=dtype,
188
+ onload_device="cpu",
189
+ computation_dtype=self.torch_dtype,
190
+ computation_device=self.device,
191
+ ),
192
+ vram_limit=vram_limit,
193
+ )
194
+ if self.dit2 is not None:
195
+ dtype = next(iter(self.dit2.parameters())).dtype
196
+ device = "cpu" if vram_limit is not None else self.device
197
+ enable_vram_management(
198
+ self.dit2,
199
+ module_map = {
200
+ torch.nn.Linear: AutoWrappedLinear,
201
+ torch.nn.Conv3d: AutoWrappedModule,
202
+ torch.nn.LayerNorm: WanAutoCastLayerNorm,
203
+ RMSNorm: AutoWrappedModule,
204
+ torch.nn.Conv2d: AutoWrappedModule,
205
+ },
206
+ module_config = dict(
207
+ offload_dtype=dtype,
208
+ offload_device="cpu",
209
+ onload_dtype=dtype,
210
+ onload_device=device,
211
+ computation_dtype=self.torch_dtype,
212
+ computation_device=self.device,
213
+ ),
214
+ max_num_param=num_persistent_param_in_dit,
215
+ overflow_module_config = dict(
216
+ offload_dtype=dtype,
217
+ offload_device="cpu",
218
+ onload_dtype=dtype,
219
+ onload_device="cpu",
220
+ computation_dtype=self.torch_dtype,
221
+ computation_device=self.device,
222
+ ),
223
+ vram_limit=vram_limit,
224
+ )
225
+ if self.vae is not None:
226
+ dtype = next(iter(self.vae.parameters())).dtype
227
+ enable_vram_management(
228
+ self.vae,
229
+ module_map = {
230
+ torch.nn.Linear: AutoWrappedLinear,
231
+ torch.nn.Conv2d: AutoWrappedModule,
232
+ RMS_norm: AutoWrappedModule,
233
+ CausalConv3d: AutoWrappedModule,
234
+ Upsample: AutoWrappedModule,
235
+ torch.nn.SiLU: AutoWrappedModule,
236
+ torch.nn.Dropout: AutoWrappedModule,
237
+ },
238
+ module_config = dict(
239
+ offload_dtype=dtype,
240
+ offload_device="cpu",
241
+ onload_dtype=dtype,
242
+ onload_device=self.device,
243
+ computation_dtype=self.torch_dtype,
244
+ computation_device=self.device,
245
+ ),
246
+ )
247
+ if self.image_encoder is not None:
248
+ dtype = next(iter(self.image_encoder.parameters())).dtype
249
+ enable_vram_management(
250
+ self.image_encoder,
251
+ module_map = {
252
+ torch.nn.Linear: AutoWrappedLinear,
253
+ torch.nn.Conv2d: AutoWrappedModule,
254
+ torch.nn.LayerNorm: AutoWrappedModule,
255
+ },
256
+ module_config = dict(
257
+ offload_dtype=dtype,
258
+ offload_device="cpu",
259
+ onload_dtype=dtype,
260
+ onload_device="cpu",
261
+ computation_dtype=dtype,
262
+ computation_device=self.device,
263
+ ),
264
+ )
265
+ if self.motion_controller is not None:
266
+ dtype = next(iter(self.motion_controller.parameters())).dtype
267
+ enable_vram_management(
268
+ self.motion_controller,
269
+ module_map = {
270
+ torch.nn.Linear: AutoWrappedLinear,
271
+ },
272
+ module_config = dict(
273
+ offload_dtype=dtype,
274
+ offload_device="cpu",
275
+ onload_dtype=dtype,
276
+ onload_device="cpu",
277
+ computation_dtype=dtype,
278
+ computation_device=self.device,
279
+ ),
280
+ )
281
+ if self.vace is not None:
282
+ device = "cpu" if vram_limit is not None else self.device
283
+ enable_vram_management(
284
+ self.vace,
285
+ module_map = {
286
+ torch.nn.Linear: AutoWrappedLinear,
287
+ torch.nn.Conv3d: AutoWrappedModule,
288
+ torch.nn.LayerNorm: AutoWrappedModule,
289
+ RMSNorm: AutoWrappedModule,
290
+ },
291
+ module_config = dict(
292
+ offload_dtype=dtype,
293
+ offload_device="cpu",
294
+ onload_dtype=dtype,
295
+ onload_device=device,
296
+ computation_dtype=self.torch_dtype,
297
+ computation_device=self.device,
298
+ ),
299
+ vram_limit=vram_limit,
300
+ )
301
+ if self.audio_encoder is not None:
302
+ # TODO: need check
303
+ dtype = next(iter(self.audio_encoder.parameters())).dtype
304
+ enable_vram_management(
305
+ self.audio_encoder,
306
+ module_map = {
307
+ torch.nn.Linear: AutoWrappedLinear,
308
+ torch.nn.LayerNorm: AutoWrappedModule,
309
+ torch.nn.Conv1d: AutoWrappedModule,
310
+ },
311
+ module_config = dict(
312
+ offload_dtype=dtype,
313
+ offload_device="cpu",
314
+ onload_dtype=dtype,
315
+ onload_device="cpu",
316
+ computation_dtype=self.torch_dtype,
317
+ computation_device=self.device,
318
+ ),
319
+ )
320
+
321
+
322
+ def initialize_usp(self):
323
+ import torch.distributed as dist
324
+ from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment
325
+ backend = "hccl" if getattr(torch, "npu", None) is not None and torch.npu.is_available() else "nccl"
326
+ dist.init_process_group(backend=backend, init_method="env://")
327
+ init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())
328
+ initialize_model_parallel(
329
+ sequence_parallel_degree=dist.get_world_size(),
330
+ ring_degree=1,
331
+ ulysses_degree=dist.get_world_size(),
332
+ )
333
+ if backend == "hccl":
334
+ torch.npu.set_device(dist.get_rank())
335
+ else:
336
+ torch.cuda.set_device(dist.get_rank())
337
+
338
+
339
+ def enable_usp(self):
340
+ from xfuser.core.distributed import get_sequence_parallel_world_size
341
+ from ..distributed.xdit_context_parallel import usp_attn_forward, usp_dit_forward
342
+
343
+ for block in self.dit.blocks:
344
+ block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn)
345
+ self.dit.forward = types.MethodType(usp_dit_forward, self.dit)
346
+ if self.dit2 is not None:
347
+ for block in self.dit2.blocks:
348
+ block.self_attn.forward = types.MethodType(usp_attn_forward, block.self_attn)
349
+ self.dit2.forward = types.MethodType(usp_dit_forward, self.dit2)
350
+ self.sp_size = get_sequence_parallel_world_size()
351
+ self.use_unified_sequence_parallel = True
352
+
353
+
354
+ @classmethod
355
+ def from_pretrained(
356
+ cls,
357
+ torch_dtype: torch.dtype = torch.float16,
358
+ device: Union[str, torch.device] = "npu",
359
+ model_configs: list[ModelConfig] = [],
360
+ tokenizer_config: ModelConfig = ModelConfig(model_id="Wan-AI/Wan2.1-T2V-1.3B", origin_file_pattern="google/*"),
361
+ audio_processor_config: ModelConfig = None,
362
+ redirect_common_files: bool = True,
363
+ use_usp=False,
364
+ ):
365
+ # Redirect model path
366
+ if redirect_common_files:
367
+ redirect_dict = {
368
+ "models_t5_umt5-xxl-enc-bf16.pth": "Wan-AI/Wan2.1-T2V-1.3B",
369
+ "Wan2.1_VAE.pth": "Wan-AI/Wan2.1-T2V-1.3B",
370
+ "models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth": "Wan-AI/Wan2.1-I2V-14B-480P",
371
+ }
372
+ for model_config in model_configs:
373
+ if model_config.origin_file_pattern is None or model_config.model_id is None:
374
+ continue
375
+ if model_config.origin_file_pattern in redirect_dict and model_config.model_id != redirect_dict[model_config.origin_file_pattern]:
376
+ 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.")
377
+ model_config.model_id = redirect_dict[model_config.origin_file_pattern]
378
+
379
+ # Initialize pipeline
380
+ pipe = cls(device=device, torch_dtype=torch_dtype)
381
+ if use_usp: pipe.initialize_usp()
382
+
383
+ # Download and load models
384
+ model_manager = ModelManager()
385
+ for model_config in model_configs:
386
+ model_config.download_if_necessary(use_usp=use_usp)
387
+ model_manager.load_model(
388
+ model_config.path,
389
+ device=model_config.offload_device or device,
390
+ torch_dtype=model_config.offload_dtype or torch_dtype
391
+ )
392
+
393
+ # Load models
394
+ pipe.text_encoder = model_manager.fetch_model("wan_video_text_encoder")
395
+ dit = model_manager.fetch_model("wan_video_dit", index=2)
396
+ if isinstance(dit, list):
397
+ pipe.dit, pipe.dit2 = dit
398
+ else:
399
+ pipe.dit = dit
400
+ pipe.vae = model_manager.fetch_model("wan_video_vae")
401
+ pipe.image_encoder = model_manager.fetch_model("wan_video_image_encoder")
402
+ pipe.motion_controller = model_manager.fetch_model("wan_video_motion_controller")
403
+ vace = model_manager.fetch_model("wan_video_vace", index=2)
404
+ if isinstance(vace, list):
405
+ pipe.vace, pipe.vace2 = vace
406
+ else:
407
+ pipe.vace = vace
408
+ pipe.audio_encoder = model_manager.fetch_model("wans2v_audio_encoder")
409
+ pipe.animate_adapter = model_manager.fetch_model("wan_video_animate_adapter")
410
+
411
+ # Size division factor
412
+ if pipe.vae is not None:
413
+ pipe.height_division_factor = pipe.vae.upsampling_factor * 2
414
+ pipe.width_division_factor = pipe.vae.upsampling_factor * 2
415
+
416
+ # Initialize tokenizer
417
+ tokenizer_config.download_if_necessary(use_usp=use_usp)
418
+ pipe.prompter.fetch_models(pipe.text_encoder)
419
+ pipe.prompter.fetch_tokenizer(tokenizer_config.path)
420
+
421
+ if audio_processor_config is not None:
422
+ audio_processor_config.download_if_necessary(use_usp=use_usp)
423
+ from transformers import Wav2Vec2Processor
424
+ pipe.audio_processor = Wav2Vec2Processor.from_pretrained(audio_processor_config.path)
425
+ # Unified Sequence Parallel
426
+ if use_usp: pipe.enable_usp()
427
+ return pipe
428
+
429
+
430
+ @torch.no_grad()
431
+ def __call__(
432
+ self,
433
+ # Prompt
434
+ prompt: str,
435
+ negative_prompt: Optional[str] = "",
436
+ # Image-to-video
437
+ input_image: Optional[Image.Image] = None,
438
+ # First-last-frame-to-video
439
+ end_image: Optional[Image.Image] = None,
440
+ # Video-to-video
441
+ input_video: Optional[list[Image.Image]] = None,
442
+ denoising_strength: Optional[float] = 1.0,
443
+ # Speech-to-video
444
+ input_audio: Optional[np.array] = None,
445
+ audio_embeds: Optional[torch.Tensor] = None,
446
+ audio_sample_rate: Optional[int] = 16000,
447
+ s2v_pose_video: Optional[list[Image.Image]] = None,
448
+ s2v_pose_latents: Optional[torch.Tensor] = None,
449
+ motion_video: Optional[list[Image.Image]] = None,
450
+ # ControlNet
451
+ control_video: Optional[list[Image.Image]] = None,
452
+ reference_image: Optional[Image.Image] = None,
453
+ # Camera control
454
+ camera_control_direction: Optional[Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown"]] = None,
455
+ camera_control_speed: Optional[float] = 1/54,
456
+ 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),
457
+ # VACE
458
+ vace_video: Optional[list[Image.Image]] = None,
459
+ vace_video_mask: Optional[Image.Image] = None,
460
+ vace_reference_image: Optional[Image.Image] = None,
461
+ vace_scale: Optional[float] = 1.0,
462
+ # Animate
463
+ animate_pose_video: Optional[list[Image.Image]] = None,
464
+ animate_face_video: Optional[list[Image.Image]] = None,
465
+ animate_inpaint_video: Optional[list[Image.Image]] = None,
466
+ animate_mask_video: Optional[list[Image.Image]] = None,
467
+ # Randomness
468
+ seed: Optional[int] = None,
469
+ rand_device: Optional[str] = "cpu",
470
+ # Shape
471
+ height: Optional[int] = 480,
472
+ width: Optional[int] = 832,
473
+ num_frames=81,
474
+ # Classifier-free guidance
475
+ cfg_scale: Optional[float] = 5.0,
476
+ cfg_merge: Optional[bool] = False,
477
+ # Boundary
478
+ switch_DiT_boundary: Optional[float] = 0.875,
479
+ # Scheduler
480
+ num_inference_steps: Optional[int] = 50,
481
+ sigma_shift: Optional[float] = 5.0,
482
+ # Speed control
483
+ motion_bucket_id: Optional[int] = None,
484
+ # VAE tiling
485
+ tiled: Optional[bool] = True,
486
+ tile_size: Optional[tuple[int, int]] = (30, 52),
487
+ tile_stride: Optional[tuple[int, int]] = (15, 26),
488
+ # Sliding window
489
+ sliding_window_size: Optional[int] = None,
490
+ sliding_window_stride: Optional[int] = None,
491
+ # Teacache
492
+ tea_cache_l1_thresh: Optional[float] = None,
493
+ tea_cache_model_id: Optional[str] = "",
494
+ # progress_bar
495
+ progress_bar_cmd=tqdm,
496
+ ):
497
+ # Scheduler
498
+ self.scheduler.set_timesteps(num_inference_steps, denoising_strength=denoising_strength, shift=sigma_shift)
499
+
500
+ # Inputs
501
+ inputs_posi = {
502
+ "prompt": prompt,
503
+ "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps,
504
+ }
505
+ inputs_nega = {
506
+ "negative_prompt": negative_prompt,
507
+ "tea_cache_l1_thresh": tea_cache_l1_thresh, "tea_cache_model_id": tea_cache_model_id, "num_inference_steps": num_inference_steps,
508
+ }
509
+ inputs_shared = {
510
+ "input_image": input_image,
511
+ "end_image": end_image,
512
+ "input_video": input_video, "denoising_strength": denoising_strength,
513
+ "control_video": control_video, "reference_image": reference_image,
514
+ "camera_control_direction": camera_control_direction, "camera_control_speed": camera_control_speed, "camera_control_origin": camera_control_origin,
515
+ "vace_video": vace_video, "vace_video_mask": vace_video_mask, "vace_reference_image": vace_reference_image, "vace_scale": vace_scale,
516
+ "seed": seed, "rand_device": rand_device,
517
+ "height": height, "width": width, "num_frames": num_frames,
518
+ "cfg_scale": cfg_scale, "cfg_merge": cfg_merge,
519
+ "sigma_shift": sigma_shift,
520
+ "motion_bucket_id": motion_bucket_id,
521
+ "tiled": tiled, "tile_size": tile_size, "tile_stride": tile_stride,
522
+ "sliding_window_size": sliding_window_size, "sliding_window_stride": sliding_window_stride,
523
+ "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,
524
+ "animate_pose_video": animate_pose_video, "animate_face_video": animate_face_video, "animate_inpaint_video": animate_inpaint_video, "animate_mask_video": animate_mask_video,
525
+ }
526
+ for unit in self.units:
527
+ inputs_shared, inputs_posi, inputs_nega = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega)
528
+
529
+ # Denoise
530
+ self.load_models_to_device(self.in_iteration_models)
531
+ models = {name: getattr(self, name) for name in self.in_iteration_models}
532
+ for progress_id, timestep in enumerate(progress_bar_cmd(self.scheduler.timesteps)):
533
+ # Switch DiT if necessary
534
+ if timestep.item() < switch_DiT_boundary * self.scheduler.num_train_timesteps and self.dit2 is not None and not models["dit"] is self.dit2:
535
+ self.load_models_to_device(self.in_iteration_models_2)
536
+ models["dit"] = self.dit2
537
+ models["vace"] = self.vace2
538
+
539
+ # Timestep
540
+ timestep = timestep.unsqueeze(0).to(dtype=self.torch_dtype, device=self.device)
541
+
542
+ # Inference
543
+ noise_pred_posi = self.model_fn(**models, **inputs_shared, **inputs_posi, timestep=timestep)
544
+ if cfg_scale != 1.0:
545
+ if cfg_merge:
546
+ noise_pred_posi, noise_pred_nega = noise_pred_posi.chunk(2, dim=0)
547
+ else:
548
+ noise_pred_nega = self.model_fn(**models, **inputs_shared, **inputs_nega, timestep=timestep)
549
+ noise_pred = noise_pred_nega + cfg_scale * (noise_pred_posi - noise_pred_nega)
550
+ else:
551
+ noise_pred = noise_pred_posi
552
+
553
+ # Scheduler
554
+ inputs_shared["latents"] = self.scheduler.step(noise_pred, self.scheduler.timesteps[progress_id], inputs_shared["latents"])
555
+ if "first_frame_latents" in inputs_shared:
556
+ inputs_shared["latents"][:, :, 0:1] = inputs_shared["first_frame_latents"]
557
+
558
+ # VACE (TODO: remove it)
559
+ if vace_reference_image is not None or (animate_pose_video is not None and animate_face_video is not None):
560
+ if vace_reference_image is not None and isinstance(vace_reference_image, list):
561
+ f = len(vace_reference_image)
562
+ else:
563
+ f = 1
564
+ inputs_shared["latents"] = inputs_shared["latents"][:, :, f:]
565
+ # post-denoising, pre-decoding processing logic
566
+ for unit in self.post_units:
567
+ inputs_shared, _, _ = self.unit_runner(unit, self, inputs_shared, inputs_posi, inputs_nega)
568
+ # Decode
569
+ self.load_models_to_device(['vae'])
570
+ video = self.vae.decode(inputs_shared["latents"], device=self.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
571
+ video = self.vae_output_to_video(video)
572
+ self.load_models_to_device([])
573
+
574
+ return video
575
+
576
+
577
+
578
+ class WanVideoUnit_ShapeChecker(PipelineUnit):
579
+ def __init__(self):
580
+ super().__init__(input_params=("height", "width", "num_frames"))
581
+
582
+ def process(self, pipe: WanVideoPipeline, height, width, num_frames):
583
+ height, width, num_frames = pipe.check_resize_height_width(height, width, num_frames)
584
+ return {"height": height, "width": width, "num_frames": num_frames}
585
+
586
+
587
+
588
+ class WanVideoUnit_NoiseInitializer(PipelineUnit):
589
+ def __init__(self):
590
+ super().__init__(input_params=("height", "width", "num_frames", "seed", "rand_device", "vace_reference_image"))
591
+
592
+ def process(self, pipe: WanVideoPipeline, height, width, num_frames, seed, rand_device, vace_reference_image):
593
+ length = (num_frames - 1) // 4 + 1
594
+ if vace_reference_image is not None:
595
+ f = len(vace_reference_image) if isinstance(vace_reference_image, list) else 1
596
+ length += f
597
+ shape = (1, pipe.vae.model.z_dim, length, height // pipe.vae.upsampling_factor, width // pipe.vae.upsampling_factor)
598
+ noise = pipe.generate_noise(shape, seed=seed, rand_device=rand_device)
599
+ if vace_reference_image is not None:
600
+ noise = torch.concat((noise[:, :, -f:], noise[:, :, :-f]), dim=2)
601
+ return {"noise": noise}
602
+
603
+
604
+
605
+ class WanVideoUnit_InputVideoEmbedder(PipelineUnit):
606
+ def __init__(self):
607
+ super().__init__(
608
+ input_params=("input_video", "noise", "tiled", "tile_size", "tile_stride", "vace_reference_image"),
609
+ onload_model_names=("vae",)
610
+ )
611
+
612
+ def process(self, pipe: WanVideoPipeline, input_video, noise, tiled, tile_size, tile_stride, vace_reference_image):
613
+ if input_video is None:
614
+ return {"latents": noise}
615
+ pipe.load_models_to_device(["vae"])
616
+ input_video = pipe.preprocess_video(input_video)
617
+ 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)
618
+ if vace_reference_image is not None:
619
+ if not isinstance(vace_reference_image, list):
620
+ vace_reference_image = [vace_reference_image]
621
+ vace_reference_image = pipe.preprocess_video(vace_reference_image)
622
+ vace_reference_latents = pipe.vae.encode(vace_reference_image, device=pipe.device).to(dtype=pipe.torch_dtype, device=pipe.device)
623
+ input_latents = torch.concat([vace_reference_latents, input_latents], dim=2)
624
+ if pipe.scheduler.training:
625
+ return {"latents": noise, "input_latents": input_latents}
626
+ else:
627
+ latents = pipe.scheduler.add_noise(input_latents, noise, timestep=pipe.scheduler.timesteps[0])
628
+ return {"latents": latents}
629
+
630
+
631
+
632
+ class WanVideoUnit_PromptEmbedder(PipelineUnit):
633
+ def __init__(self):
634
+ super().__init__(
635
+ seperate_cfg=True,
636
+ input_params_posi={"prompt": "prompt", "positive": "positive"},
637
+ input_params_nega={"prompt": "negative_prompt", "positive": "positive"},
638
+ onload_model_names=("text_encoder",)
639
+ )
640
+
641
+ def process(self, pipe: WanVideoPipeline, prompt, positive) -> dict:
642
+ pipe.load_models_to_device(self.onload_model_names)
643
+ prompt_emb = pipe.prompter.encode_prompt(prompt, positive=positive, device=pipe.device)
644
+ return {"context": prompt_emb}
645
+
646
+
647
+
648
+ class WanVideoUnit_ImageEmbedder(PipelineUnit):
649
+ """
650
+ Deprecated
651
+ """
652
+ def __init__(self):
653
+ super().__init__(
654
+ input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"),
655
+ onload_model_names=("image_encoder", "vae")
656
+ )
657
+
658
+ def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride):
659
+ if input_image is None or pipe.image_encoder is None:
660
+ return {}
661
+ pipe.load_models_to_device(self.onload_model_names)
662
+ image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device)
663
+ clip_context = pipe.image_encoder.encode_image([image])
664
+ msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device)
665
+ msk[:, 1:] = 0
666
+ if end_image is not None:
667
+ end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device)
668
+ 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)
669
+ if pipe.dit.has_image_pos_emb:
670
+ clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1)
671
+ msk[:, -1:] = 1
672
+ else:
673
+ vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1)
674
+
675
+ msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
676
+ msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8)
677
+ msk = msk.transpose(1, 2)[0]
678
+
679
+ 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]
680
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
681
+ y = torch.concat([msk, y])
682
+ y = y.unsqueeze(0)
683
+ clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device)
684
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
685
+ return {"clip_feature": clip_context, "y": y}
686
+
687
+
688
+
689
+ class WanVideoUnit_ImageEmbedderCLIP(PipelineUnit):
690
+ def __init__(self):
691
+ super().__init__(
692
+ input_params=("input_image", "end_image", "height", "width"),
693
+ onload_model_names=("image_encoder",)
694
+ )
695
+
696
+ def process(self, pipe: WanVideoPipeline, input_image, end_image, height, width):
697
+ if input_image is None or pipe.image_encoder is None or not pipe.dit.require_clip_embedding:
698
+ return {}
699
+ pipe.load_models_to_device(self.onload_model_names)
700
+ image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device)
701
+ clip_context = pipe.image_encoder.encode_image([image])
702
+ if end_image is not None:
703
+ end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device)
704
+ if pipe.dit.has_image_pos_emb:
705
+ clip_context = torch.concat([clip_context, pipe.image_encoder.encode_image([end_image])], dim=1)
706
+ clip_context = clip_context.to(dtype=pipe.torch_dtype, device=pipe.device)
707
+ return {"clip_feature": clip_context}
708
+
709
+
710
+
711
+ class WanVideoUnit_ImageEmbedderVAE(PipelineUnit):
712
+ def __init__(self):
713
+ super().__init__(
714
+ input_params=("input_image", "end_image", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride"),
715
+ onload_model_names=("vae",)
716
+ )
717
+
718
+ def process(self, pipe: WanVideoPipeline, input_image, end_image, num_frames, height, width, tiled, tile_size, tile_stride):
719
+ if input_image is None or not pipe.dit.require_vae_embedding:
720
+ return {}
721
+ pipe.load_models_to_device(self.onload_model_names)
722
+ image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device)
723
+ msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device)
724
+ msk[:, 1:] = 0
725
+ if end_image is not None:
726
+ end_image = pipe.preprocess_image(end_image.resize((width, height))).to(pipe.device)
727
+ 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)
728
+ msk[:, -1:] = 1
729
+ else:
730
+ vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1)
731
+
732
+ msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
733
+ msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8)
734
+ msk = msk.transpose(1, 2)[0]
735
+
736
+ 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]
737
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
738
+ y = torch.concat([msk, y])
739
+ y = y.unsqueeze(0)
740
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
741
+ return {"y": y}
742
+
743
+
744
+
745
+ class WanVideoUnit_ImageEmbedderFused(PipelineUnit):
746
+ """
747
+ Encode input image to latents using VAE. This unit is for Wan-AI/Wan2.2-TI2V-5B.
748
+ """
749
+ def __init__(self):
750
+ super().__init__(
751
+ input_params=("input_image", "latents", "height", "width", "tiled", "tile_size", "tile_stride"),
752
+ onload_model_names=("vae",)
753
+ )
754
+
755
+ def process(self, pipe: WanVideoPipeline, input_image, latents, height, width, tiled, tile_size, tile_stride):
756
+ if input_image is None or not pipe.dit.fuse_vae_embedding_in_latents:
757
+ return {}
758
+ pipe.load_models_to_device(self.onload_model_names)
759
+ image = pipe.preprocess_image(input_image.resize((width, height))).transpose(0, 1)
760
+ z = pipe.vae.encode([image], device=pipe.device, tiled=tiled, tile_size=tile_size, tile_stride=tile_stride)
761
+ latents[:, :, 0: 1] = z
762
+ return {"latents": latents, "fuse_vae_embedding_in_latents": True, "first_frame_latents": z}
763
+
764
+
765
+
766
+ class WanVideoUnit_FunControl(PipelineUnit):
767
+ def __init__(self):
768
+ super().__init__(
769
+ input_params=("control_video", "num_frames", "height", "width", "tiled", "tile_size", "tile_stride", "clip_feature", "y", "latents"),
770
+ onload_model_names=("vae",)
771
+ )
772
+
773
+ def process(self, pipe: WanVideoPipeline, control_video, num_frames, height, width, tiled, tile_size, tile_stride, clip_feature, y, latents):
774
+ if control_video is None:
775
+ return {}
776
+ pipe.load_models_to_device(self.onload_model_names)
777
+ control_video = pipe.preprocess_video(control_video)
778
+ 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)
779
+ control_latents = control_latents.to(dtype=pipe.torch_dtype, device=pipe.device)
780
+ y_dim = pipe.dit.in_dim-control_latents.shape[1]-latents.shape[1]
781
+ if clip_feature is None or y is None:
782
+ clip_feature = torch.zeros((1, 257, 1280), dtype=pipe.torch_dtype, device=pipe.device)
783
+ y = torch.zeros((1, y_dim, (num_frames - 1) // 4 + 1, height//8, width//8), dtype=pipe.torch_dtype, device=pipe.device)
784
+ else:
785
+ y = y[:, -y_dim:]
786
+ y = torch.concat([control_latents, y], dim=1)
787
+ return {"clip_feature": clip_feature, "y": y}
788
+
789
+
790
+
791
+ class WanVideoUnit_FunReference(PipelineUnit):
792
+ def __init__(self):
793
+ super().__init__(
794
+ input_params=("reference_image", "height", "width", "reference_image"),
795
+ onload_model_names=("vae",)
796
+ )
797
+
798
+ def process(self, pipe: WanVideoPipeline, reference_image, height, width):
799
+ if reference_image is None:
800
+ return {}
801
+ pipe.load_models_to_device(["vae"])
802
+ reference_image = reference_image.resize((width, height))
803
+ reference_latents = pipe.preprocess_video([reference_image])
804
+ reference_latents = pipe.vae.encode(reference_latents, device=pipe.device)
805
+ if pipe.image_encoder is None:
806
+ return {"reference_latents": reference_latents}
807
+ clip_feature = pipe.preprocess_image(reference_image)
808
+ clip_feature = pipe.image_encoder.encode_image([clip_feature])
809
+ return {"reference_latents": reference_latents, "clip_feature": clip_feature}
810
+
811
+
812
+
813
+ class WanVideoUnit_FunCameraControl(PipelineUnit):
814
+ def __init__(self):
815
+ super().__init__(
816
+ input_params=("height", "width", "num_frames", "camera_control_direction", "camera_control_speed", "camera_control_origin", "latents", "input_image", "tiled", "tile_size", "tile_stride"),
817
+ onload_model_names=("vae",)
818
+ )
819
+
820
+ 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):
821
+ if camera_control_direction is None:
822
+ return {}
823
+ pipe.load_models_to_device(self.onload_model_names)
824
+ camera_control_plucker_embedding = pipe.dit.control_adapter.process_camera_coordinates(
825
+ camera_control_direction, num_frames, height, width, camera_control_speed, camera_control_origin)
826
+
827
+ control_camera_video = camera_control_plucker_embedding[:num_frames].permute([3, 0, 1, 2]).unsqueeze(0)
828
+ control_camera_latents = torch.concat(
829
+ [
830
+ torch.repeat_interleave(control_camera_video[:, :, 0:1], repeats=4, dim=2),
831
+ control_camera_video[:, :, 1:]
832
+ ], dim=2
833
+ ).transpose(1, 2)
834
+ b, f, c, h, w = control_camera_latents.shape
835
+ control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, 4, c, h, w).transpose(2, 3)
836
+ control_camera_latents = control_camera_latents.contiguous().view(b, f // 4, c * 4, h, w).transpose(1, 2)
837
+ control_camera_latents_input = control_camera_latents.to(device=pipe.device, dtype=pipe.torch_dtype)
838
+
839
+ input_image = input_image.resize((width, height))
840
+ input_latents = pipe.preprocess_video([input_image])
841
+ input_latents = pipe.vae.encode(input_latents, device=pipe.device)
842
+ y = torch.zeros_like(latents).to(pipe.device)
843
+ y[:, :, :1] = input_latents
844
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
845
+
846
+ if y.shape[1] != pipe.dit.in_dim - latents.shape[1]:
847
+ image = pipe.preprocess_image(input_image.resize((width, height))).to(pipe.device)
848
+ vae_input = torch.concat([image.transpose(0, 1), torch.zeros(3, num_frames-1, height, width).to(image.device)], dim=1)
849
+ 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]
850
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
851
+ msk = torch.ones(1, num_frames, height//8, width//8, device=pipe.device)
852
+ msk[:, 1:] = 0
853
+ msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
854
+ msk = msk.view(1, msk.shape[1] // 4, 4, height//8, width//8)
855
+ msk = msk.transpose(1, 2)[0]
856
+ y = torch.cat([msk,y])
857
+ y = y.unsqueeze(0)
858
+ y = y.to(dtype=pipe.torch_dtype, device=pipe.device)
859
+ return {"control_camera_latents_input": control_camera_latents_input, "y": y}
860
+
861
+
862
+
863
+ class WanVideoUnit_SpeedControl(PipelineUnit):
864
+ def __init__(self):
865
+ super().__init__(input_params=("motion_bucket_id",))
866
+
867
+ def process(self, pipe: WanVideoPipeline, motion_bucket_id):
868
+ if motion_bucket_id is None:
869
+ return {}
870
+ motion_bucket_id = torch.Tensor((motion_bucket_id,)).to(dtype=pipe.torch_dtype, device=pipe.device)
871
+ return {"motion_bucket_id": motion_bucket_id}
872
+
873
+
874
+
875
+ class WanVideoUnit_VACE(PipelineUnit):
876
+ def __init__(self):
877
+ super().__init__(
878
+ input_params=("vace_video", "vace_video_mask", "vace_reference_image", "vace_scale", "height", "width", "num_frames", "tiled", "tile_size", "tile_stride"),
879
+ onload_model_names=("vae",)
880
+ )
881
+
882
+ def process(
883
+ self,
884
+ pipe: WanVideoPipeline,
885
+ vace_video, vace_video_mask, vace_reference_image, vace_scale,
886
+ height, width, num_frames,
887
+ tiled, tile_size, tile_stride
888
+ ):
889
+ if vace_video is not None or vace_video_mask is not None or vace_reference_image is not None:
890
+ pipe.load_models_to_device(["vae"])
891
+ if vace_video is None:
892
+ vace_video = torch.zeros((1, 3, num_frames, height, width), dtype=pipe.torch_dtype, device=pipe.device)
893
+ else:
894
+ vace_video = pipe.preprocess_video(vace_video)
895
+
896
+ if vace_video_mask is None:
897
+ vace_video_mask = torch.ones_like(vace_video)
898
+ else:
899
+ vace_video_mask = pipe.preprocess_video(vace_video_mask, min_value=0, max_value=1)
900
+
901
+ inactive = vace_video * (1 - vace_video_mask) + 0 * vace_video_mask
902
+ reactive = vace_video * vace_video_mask + 0 * (1 - vace_video_mask)
903
+ 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)
904
+ 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)
905
+ vace_video_latents = torch.concat((inactive, reactive), dim=1)
906
+
907
+ vace_mask_latents = rearrange(vace_video_mask[0,0], "T (H P) (W Q) -> 1 (P Q) T H W", P=8, Q=8)
908
+ 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')
909
+
910
+ if vace_reference_image is None:
911
+ pass
912
+ else:
913
+ if not isinstance(vace_reference_image,list):
914
+ vace_reference_image = [vace_reference_image]
915
+
916
+ vace_reference_image = pipe.preprocess_video(vace_reference_image)
917
+
918
+ bs, c, f, h, w = vace_reference_image.shape
919
+ new_vace_ref_images = []
920
+ for j in range(f):
921
+ new_vace_ref_images.append(vace_reference_image[0, :, j:j+1])
922
+ vace_reference_image = new_vace_ref_images
923
+
924
+ 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)
925
+ vace_reference_latents = torch.concat((vace_reference_latents, torch.zeros_like(vace_reference_latents)), dim=1)
926
+ vace_reference_latents = [u.unsqueeze(0) for u in vace_reference_latents]
927
+
928
+ vace_video_latents = torch.concat((*vace_reference_latents, vace_video_latents), dim=2)
929
+ vace_mask_latents = torch.concat((torch.zeros_like(vace_mask_latents[:, :, :f]), vace_mask_latents), dim=2)
930
+
931
+ vace_context = torch.concat((vace_video_latents, vace_mask_latents), dim=1)
932
+ return {"vace_context": vace_context, "vace_scale": vace_scale}
933
+ else:
934
+ return {"vace_context": None, "vace_scale": vace_scale}
935
+
936
+
937
+
938
+ class WanVideoUnit_UnifiedSequenceParallel(PipelineUnit):
939
+ def __init__(self):
940
+ super().__init__(input_params=())
941
+
942
+ def process(self, pipe: WanVideoPipeline):
943
+ if hasattr(pipe, "use_unified_sequence_parallel"):
944
+ if pipe.use_unified_sequence_parallel:
945
+ return {"use_unified_sequence_parallel": True}
946
+ return {}
947
+
948
+
949
+
950
+ class WanVideoUnit_TeaCache(PipelineUnit):
951
+ def __init__(self):
952
+ super().__init__(
953
+ seperate_cfg=True,
954
+ 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"},
955
+ 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"},
956
+ )
957
+
958
+ def process(self, pipe: WanVideoPipeline, num_inference_steps, tea_cache_l1_thresh, tea_cache_model_id):
959
+ if tea_cache_l1_thresh is None:
960
+ return {}
961
+ return {"tea_cache": TeaCache(num_inference_steps, rel_l1_thresh=tea_cache_l1_thresh, model_id=tea_cache_model_id)}
962
+
963
+
964
+
965
+ class WanVideoUnit_CfgMerger(PipelineUnit):
966
+ def __init__(self):
967
+ super().__init__(take_over=True)
968
+ self.concat_tensor_names = ["context", "clip_feature", "y", "reference_latents"]
969
+
970
+ def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega):
971
+ if not inputs_shared["cfg_merge"]:
972
+ return inputs_shared, inputs_posi, inputs_nega
973
+ for name in self.concat_tensor_names:
974
+ tensor_posi = inputs_posi.get(name)
975
+ tensor_nega = inputs_nega.get(name)
976
+ tensor_shared = inputs_shared.get(name)
977
+ if tensor_posi is not None and tensor_nega is not None:
978
+ inputs_shared[name] = torch.concat((tensor_posi, tensor_nega), dim=0)
979
+ elif tensor_shared is not None:
980
+ inputs_shared[name] = torch.concat((tensor_shared, tensor_shared), dim=0)
981
+ inputs_posi.clear()
982
+ inputs_nega.clear()
983
+ return inputs_shared, inputs_posi, inputs_nega
984
+
985
+
986
+ class WanVideoUnit_S2V(PipelineUnit):
987
+ def __init__(self):
988
+ super().__init__(
989
+ take_over=True,
990
+ onload_model_names=("audio_encoder", "vae",)
991
+ )
992
+
993
+ def process_audio(self, pipe: WanVideoPipeline, input_audio, audio_sample_rate, num_frames, fps=16, audio_embeds=None, return_all=False):
994
+ if audio_embeds is not None:
995
+ return {"audio_embeds": audio_embeds}
996
+ pipe.load_models_to_device(["audio_encoder"])
997
+ 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)
998
+ if return_all:
999
+ return audio_embeds
1000
+ else:
1001
+ return {"audio_embeds": audio_embeds[0]}
1002
+
1003
+ def process_motion_latents(self, pipe: WanVideoPipeline, height, width, tiled, tile_size, tile_stride, motion_video=None):
1004
+ pipe.load_models_to_device(["vae"])
1005
+ motion_frames = 73
1006
+ kwargs = {}
1007
+ if motion_video is not None and len(motion_video) > 0:
1008
+ assert len(motion_video) == motion_frames, f"motion video must have {motion_frames} frames, but got {len(motion_video)}"
1009
+ motion_latents = pipe.preprocess_video(motion_video)
1010
+ kwargs["drop_motion_frames"] = False
1011
+ else:
1012
+ motion_latents = torch.zeros([1, 3, motion_frames, height, width], dtype=pipe.torch_dtype, device=pipe.device)
1013
+ kwargs["drop_motion_frames"] = True
1014
+ 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)
1015
+ kwargs.update({"motion_latents": motion_latents})
1016
+ return kwargs
1017
+
1018
+ 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):
1019
+ if s2v_pose_latents is not None:
1020
+ return {"s2v_pose_latents": s2v_pose_latents}
1021
+ if s2v_pose_video is None:
1022
+ return {"s2v_pose_latents": None}
1023
+ pipe.load_models_to_device(["vae"])
1024
+ infer_frames = num_frames - 1
1025
+ input_video = pipe.preprocess_video(s2v_pose_video)[:, :, :infer_frames * num_repeats]
1026
+ # pad if not enough frames
1027
+ padding_frames = infer_frames * num_repeats - input_video.shape[2]
1028
+ input_video = torch.cat([input_video, -torch.ones(1, 3, padding_frames, height, width, device=input_video.device, dtype=input_video.dtype)], dim=2)
1029
+ input_videos = input_video.chunk(num_repeats, dim=2)
1030
+ pose_conds = []
1031
+ for r in range(num_repeats):
1032
+ cond = input_videos[r]
1033
+ cond = torch.cat([cond[:, :, 0:1].repeat(1, 1, 1, 1, 1), cond], dim=2)
1034
+ 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)
1035
+ pose_conds.append(cond_latents[:,:,1:])
1036
+ if return_all:
1037
+ return pose_conds
1038
+ else:
1039
+ return {"s2v_pose_latents": pose_conds[0]}
1040
+
1041
+ def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega):
1042
+ 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:
1043
+ return inputs_shared, inputs_posi, inputs_nega
1044
+ 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")
1045
+ input_audio, audio_embeds, audio_sample_rate = inputs_shared.pop("input_audio"), inputs_shared.pop("audio_embeds"), inputs_shared.get("audio_sample_rate")
1046
+ 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")
1047
+
1048
+ audio_input_positive = self.process_audio(pipe, input_audio, audio_sample_rate, num_frames, audio_embeds=audio_embeds)
1049
+ inputs_posi.update(audio_input_positive)
1050
+ inputs_nega.update({"audio_embeds": 0.0 * audio_input_positive["audio_embeds"]})
1051
+
1052
+ inputs_shared.update(self.process_motion_latents(pipe, height, width, tiled, tile_size, tile_stride, motion_video))
1053
+ 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))
1054
+ return inputs_shared, inputs_posi, inputs_nega
1055
+
1056
+ @staticmethod
1057
+ 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)):
1058
+ assert pipe.audio_encoder is not None and pipe.audio_processor is not None, "Please load audio encoder and audio processor first."
1059
+ shapes = WanVideoUnit_ShapeChecker().process(pipe, height, width, num_frames)
1060
+ height, width, num_frames = shapes["height"], shapes["width"], shapes["num_frames"]
1061
+ unit = WanVideoUnit_S2V()
1062
+ audio_embeds = unit.process_audio(pipe, input_audio, audio_sample_rate, num_frames, fps, return_all=True)
1063
+ 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)
1064
+ pose_latents = None if s2v_pose_video is None else pose_latents
1065
+ return audio_embeds, pose_latents, len(audio_embeds)
1066
+
1067
+
1068
+ class WanVideoPostUnit_S2V(PipelineUnit):
1069
+ def __init__(self):
1070
+ super().__init__(input_params=("latents", "motion_latents", "drop_motion_frames"))
1071
+
1072
+ def process(self, pipe: WanVideoPipeline, latents, motion_latents, drop_motion_frames):
1073
+ if pipe.audio_encoder is None or motion_latents is None or drop_motion_frames:
1074
+ return {}
1075
+ latents = torch.cat([motion_latents, latents[:,:,1:]], dim=2)
1076
+ return {"latents": latents}
1077
+
1078
+
1079
+ class WanVideoPostUnit_AnimateVideoSplit(PipelineUnit):
1080
+ def __init__(self):
1081
+ super().__init__(input_params=("input_video", "animate_pose_video", "animate_face_video", "animate_inpaint_video", "animate_mask_video"))
1082
+
1083
+ def process(self, pipe: WanVideoPipeline, input_video, animate_pose_video, animate_face_video, animate_inpaint_video, animate_mask_video):
1084
+ if input_video is None:
1085
+ return {}
1086
+ if animate_pose_video is not None:
1087
+ animate_pose_video = animate_pose_video[:len(input_video) - 4]
1088
+ if animate_face_video is not None:
1089
+ animate_face_video = animate_face_video[:len(input_video) - 4]
1090
+ if animate_inpaint_video is not None:
1091
+ animate_inpaint_video = animate_inpaint_video[:len(input_video) - 4]
1092
+ if animate_mask_video is not None:
1093
+ animate_mask_video = animate_mask_video[:len(input_video) - 4]
1094
+ 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}
1095
+
1096
+
1097
+ class WanVideoPostUnit_AnimatePoseLatents(PipelineUnit):
1098
+ def __init__(self):
1099
+ super().__init__(
1100
+ input_params=("animate_pose_video", "tiled", "tile_size", "tile_stride"),
1101
+ onload_model_names=("vae",)
1102
+ )
1103
+
1104
+ def process(self, pipe: WanVideoPipeline, animate_pose_video, tiled, tile_size, tile_stride):
1105
+ if animate_pose_video is None:
1106
+ return {}
1107
+ pipe.load_models_to_device(self.onload_model_names)
1108
+ animate_pose_video = pipe.preprocess_video(animate_pose_video)
1109
+ 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)
1110
+ return {"pose_latents": pose_latents}
1111
+
1112
+
1113
+ class WanVideoPostUnit_AnimateFacePixelValues(PipelineUnit):
1114
+ def __init__(self):
1115
+ super().__init__(take_over=True)
1116
+
1117
+ def process(self, pipe: WanVideoPipeline, inputs_shared, inputs_posi, inputs_nega):
1118
+ if inputs_shared.get("animate_face_video", None) is None:
1119
+ return {}
1120
+ inputs_posi["face_pixel_values"] = pipe.preprocess_video(inputs_shared["animate_face_video"])
1121
+ inputs_nega["face_pixel_values"] = torch.zeros_like(inputs_posi["face_pixel_values"]) - 1
1122
+ return inputs_shared, inputs_posi, inputs_nega
1123
+
1124
+
1125
+ class WanVideoPostUnit_AnimateInpaint(PipelineUnit):
1126
+ def __init__(self):
1127
+ super().__init__(
1128
+ input_params=("animate_inpaint_video", "animate_mask_video", "input_image", "tiled", "tile_size", "tile_stride"),
1129
+ onload_model_names=("vae",)
1130
+ )
1131
+
1132
+ def get_i2v_mask(self, lat_t, lat_h, lat_w, mask_len=1, mask_pixel_values=None, device="cuda"):
1133
+ if mask_pixel_values is None:
1134
+ msk = torch.zeros(1, (lat_t-1) * 4 + 1, lat_h, lat_w, device=device)
1135
+ else:
1136
+ msk = mask_pixel_values.clone()
1137
+ msk[:, :mask_len] = 1
1138
+ msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
1139
+ msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w)
1140
+ msk = msk.transpose(1, 2)[0]
1141
+ return msk
1142
+
1143
+ def process(self, pipe: WanVideoPipeline, animate_inpaint_video, animate_mask_video, input_image, tiled, tile_size, tile_stride):
1144
+ if animate_inpaint_video is None or animate_mask_video is None:
1145
+ return {}
1146
+ pipe.load_models_to_device(self.onload_model_names)
1147
+
1148
+ bg_pixel_values = pipe.preprocess_video(animate_inpaint_video)
1149
+ 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)
1150
+ _, lat_t, lat_h, lat_w = y_reft.shape
1151
+
1152
+ ref_pixel_values = pipe.preprocess_video([input_image])
1153
+ 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)
1154
+ mask_ref = self.get_i2v_mask(1, lat_h, lat_w, 1, device=pipe.device)
1155
+ y_ref = torch.concat([mask_ref, ref_latents[0]]).to(dtype=torch.bfloat16, device=pipe.device)
1156
+
1157
+ mask_pixel_values = 1 - pipe.preprocess_video(animate_mask_video, max_value=1, min_value=0)
1158
+ mask_pixel_values = rearrange(mask_pixel_values, "b c t h w -> (b t) c h w")
1159
+ mask_pixel_values = torch.nn.functional.interpolate(mask_pixel_values, size=(lat_h, lat_w), mode='nearest')
1160
+ mask_pixel_values = rearrange(mask_pixel_values, "(b t) c h w -> b t c h w", b=1)[:,:,0]
1161
+ msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, 0, mask_pixel_values=mask_pixel_values, device=pipe.device)
1162
+
1163
+ y_reft = torch.concat([msk_reft, y_reft]).to(dtype=torch.bfloat16, device=pipe.device)
1164
+ y = torch.concat([y_ref, y_reft], dim=1).unsqueeze(0)
1165
+ return {"y": y}
1166
+
1167
+
1168
+ class TeaCache:
1169
+ def __init__(self, num_inference_steps, rel_l1_thresh, model_id):
1170
+ self.num_inference_steps = num_inference_steps
1171
+ self.step = 0
1172
+ self.accumulated_rel_l1_distance = 0
1173
+ self.previous_modulated_input = None
1174
+ self.rel_l1_thresh = rel_l1_thresh
1175
+ self.previous_residual = None
1176
+ self.previous_hidden_states = None
1177
+
1178
+ self.coefficients_dict = {
1179
+ "Wan2.1-T2V-1.3B": [-5.21862437e+04, 9.23041404e+03, -5.28275948e+02, 1.36987616e+01, -4.99875664e-02],
1180
+ "Wan2.1-T2V-14B": [-3.03318725e+05, 4.90537029e+04, -2.65530556e+03, 5.87365115e+01, -3.15583525e-01],
1181
+ "Wan2.1-I2V-14B-480P": [2.57151496e+05, -3.54229917e+04, 1.40286849e+03, -1.35890334e+01, 1.32517977e-01],
1182
+ "Wan2.1-I2V-14B-720P": [ 8.10705460e+03, 2.13393892e+03, -3.72934672e+02, 1.66203073e+01, -4.17769401e-02],
1183
+ }
1184
+ if model_id not in self.coefficients_dict:
1185
+ supported_model_ids = ", ".join([i for i in self.coefficients_dict])
1186
+ raise ValueError(f"{model_id} is not a supported TeaCache model id. Please choose a valid model id in ({supported_model_ids}).")
1187
+ self.coefficients = self.coefficients_dict[model_id]
1188
+
1189
+ def check(self, dit: WanModel, x, t_mod):
1190
+ modulated_inp = t_mod.clone()
1191
+ if self.step == 0 or self.step == self.num_inference_steps - 1:
1192
+ should_calc = True
1193
+ self.accumulated_rel_l1_distance = 0
1194
+ else:
1195
+ coefficients = self.coefficients
1196
+ rescale_func = np.poly1d(coefficients)
1197
+ self.accumulated_rel_l1_distance += rescale_func(((modulated_inp-self.previous_modulated_input).abs().mean() / self.previous_modulated_input.abs().mean()).cpu().item())
1198
+ if self.accumulated_rel_l1_distance < self.rel_l1_thresh:
1199
+ should_calc = False
1200
+ else:
1201
+ should_calc = True
1202
+ self.accumulated_rel_l1_distance = 0
1203
+ self.previous_modulated_input = modulated_inp
1204
+ self.step += 1
1205
+ if self.step == self.num_inference_steps:
1206
+ self.step = 0
1207
+ if should_calc:
1208
+ self.previous_hidden_states = x.clone()
1209
+ return not should_calc
1210
+
1211
+ def store(self, hidden_states):
1212
+ self.previous_residual = hidden_states - self.previous_hidden_states
1213
+ self.previous_hidden_states = None
1214
+
1215
+ def update(self, hidden_states):
1216
+ hidden_states = hidden_states + self.previous_residual
1217
+ return hidden_states
1218
+
1219
+
1220
+
1221
+ class TemporalTiler_BCTHW:
1222
+ def __init__(self):
1223
+ pass
1224
+
1225
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
1226
+ x = torch.ones((length,))
1227
+ if border_width == 0:
1228
+ return x
1229
+
1230
+ shift = 0.5
1231
+ if not left_bound:
1232
+ x[:border_width] = (torch.arange(border_width) + shift) / border_width
1233
+ if not right_bound:
1234
+ x[-border_width:] = torch.flip((torch.arange(border_width) + shift) / border_width, dims=(0,))
1235
+ return x
1236
+
1237
+ def build_mask(self, data, is_bound, border_width):
1238
+ _, _, T, _, _ = data.shape
1239
+ t = self.build_1d_mask(T, is_bound[0], is_bound[1], border_width[0])
1240
+ mask = repeat(t, "T -> 1 1 T 1 1")
1241
+ return mask
1242
+
1243
+ def run(self, model_fn, sliding_window_size, sliding_window_stride, computation_device, computation_dtype, model_kwargs, tensor_names, batch_size=None):
1244
+ tensor_names = [tensor_name for tensor_name in tensor_names if model_kwargs.get(tensor_name) is not None]
1245
+ tensor_dict = {tensor_name: model_kwargs[tensor_name] for tensor_name in tensor_names}
1246
+ B, C, T, H, W = tensor_dict[tensor_names[0]].shape
1247
+ if batch_size is not None:
1248
+ B *= batch_size
1249
+ data_device, data_dtype = tensor_dict[tensor_names[0]].device, tensor_dict[tensor_names[0]].dtype
1250
+ value = torch.zeros((B, C, T, H, W), device=data_device, dtype=data_dtype)
1251
+ weight = torch.zeros((1, 1, T, 1, 1), device=data_device, dtype=data_dtype)
1252
+ for t in range(0, T, sliding_window_stride):
1253
+ if t - sliding_window_stride >= 0 and t - sliding_window_stride + sliding_window_size >= T:
1254
+ continue
1255
+ t_ = min(t + sliding_window_size, T)
1256
+ model_kwargs.update({
1257
+ tensor_name: tensor_dict[tensor_name][:, :, t: t_:, :].to(device=computation_device, dtype=computation_dtype) \
1258
+ for tensor_name in tensor_names
1259
+ })
1260
+ model_output = model_fn(**model_kwargs).to(device=data_device, dtype=data_dtype)
1261
+ mask = self.build_mask(
1262
+ model_output,
1263
+ is_bound=(t == 0, t_ == T),
1264
+ border_width=(sliding_window_size - sliding_window_stride,)
1265
+ ).to(device=data_device, dtype=data_dtype)
1266
+ value[:, :, t: t_, :, :] += model_output * mask
1267
+ weight[:, :, t: t_, :, :] += mask
1268
+ value /= weight
1269
+ model_kwargs.update(tensor_dict)
1270
+ return value
1271
+
1272
+
1273
+
1274
+ def model_fn_wan_video(
1275
+ dit: WanModel,
1276
+ motion_controller: WanMotionControllerModel = None,
1277
+ vace: VaceWanModel = None,
1278
+ animate_adapter: WanAnimateAdapter = None,
1279
+ latents: torch.Tensor = None,
1280
+ token_prefix_latents: Optional[torch.Tensor] = None,
1281
+ timestep: torch.Tensor = None,
1282
+ context: torch.Tensor = None,
1283
+ clip_feature: Optional[torch.Tensor] = None,
1284
+ y: Optional[torch.Tensor] = None,
1285
+ reference_latents = None,
1286
+ vace_context = None,
1287
+ vace_scale = 1.0,
1288
+ audio_embeds: Optional[torch.Tensor] = None,
1289
+ motion_latents: Optional[torch.Tensor] = None,
1290
+ s2v_pose_latents: Optional[torch.Tensor] = None,
1291
+ drop_motion_frames: bool = True,
1292
+ tea_cache: TeaCache = None,
1293
+ use_unified_sequence_parallel: bool = False,
1294
+ motion_bucket_id: Optional[torch.Tensor] = None,
1295
+ pose_latents=None,
1296
+ face_pixel_values=None,
1297
+ sliding_window_size: Optional[int] = None,
1298
+ sliding_window_stride: Optional[int] = None,
1299
+ cfg_merge: bool = False,
1300
+ use_gradient_checkpointing: bool = False,
1301
+ use_gradient_checkpointing_offload: bool = False,
1302
+ control_camera_latents_input = None,
1303
+ fuse_vae_embedding_in_latents: bool = False,
1304
+ token_prefix_clean_timestep: bool = False,
1305
+ token_prefix_aligned_rope: bool = False,
1306
+ token_prefix_block_self_attention: bool = False,
1307
+ clean_history_latent_frames: int = 0,
1308
+ condition_latents: Optional[torch.Tensor] = None,
1309
+ channel_concat_condition: bool = False,
1310
+ **kwargs,
1311
+ ):
1312
+ if sliding_window_size is not None and sliding_window_stride is not None:
1313
+ model_kwargs = dict(
1314
+ dit=dit,
1315
+ motion_controller=motion_controller,
1316
+ vace=vace,
1317
+ latents=latents,
1318
+ token_prefix_latents=token_prefix_latents,
1319
+ timestep=timestep,
1320
+ context=context,
1321
+ clip_feature=clip_feature,
1322
+ y=y,
1323
+ reference_latents=reference_latents,
1324
+ vace_context=vace_context,
1325
+ vace_scale=vace_scale,
1326
+ tea_cache=tea_cache,
1327
+ use_unified_sequence_parallel=use_unified_sequence_parallel,
1328
+ motion_bucket_id=motion_bucket_id,
1329
+ fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents,
1330
+ token_prefix_clean_timestep=token_prefix_clean_timestep,
1331
+ token_prefix_aligned_rope=token_prefix_aligned_rope,
1332
+ token_prefix_block_self_attention=token_prefix_block_self_attention,
1333
+ clean_history_latent_frames=clean_history_latent_frames,
1334
+ condition_latents=condition_latents,
1335
+ channel_concat_condition=channel_concat_condition,
1336
+ )
1337
+ return TemporalTiler_BCTHW().run(
1338
+ model_fn_wan_video,
1339
+ sliding_window_size, sliding_window_stride,
1340
+ latents.device, latents.dtype,
1341
+ model_kwargs=model_kwargs,
1342
+ tensor_names=["latents", "y"],
1343
+ batch_size=2 if cfg_merge else 1
1344
+ )
1345
+ # wan2.2 s2v
1346
+ if audio_embeds is not None:
1347
+ return model_fn_wans2v(
1348
+ dit=dit,
1349
+ latents=latents,
1350
+ timestep=timestep,
1351
+ context=context,
1352
+ audio_embeds=audio_embeds,
1353
+ motion_latents=motion_latents,
1354
+ s2v_pose_latents=s2v_pose_latents,
1355
+ drop_motion_frames=drop_motion_frames,
1356
+ use_gradient_checkpointing_offload=use_gradient_checkpointing_offload,
1357
+ use_gradient_checkpointing=use_gradient_checkpointing,
1358
+ use_unified_sequence_parallel=use_unified_sequence_parallel,
1359
+ )
1360
+
1361
+ if use_unified_sequence_parallel:
1362
+ import torch.distributed as dist
1363
+ from xfuser.core.distributed import (get_sequence_parallel_rank,
1364
+ get_sequence_parallel_world_size,
1365
+ get_sp_group)
1366
+
1367
+ has_reference_latents = reference_latents is not None
1368
+ separated_fused_timestep = bool(dit.seperated_timestep and fuse_vae_embedding_in_latents)
1369
+ separated_prefix_timestep = bool(token_prefix_clean_timestep and token_prefix_latents is not None and not has_reference_latents)
1370
+ if not separated_fused_timestep and not separated_prefix_timestep:
1371
+ t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep))
1372
+ t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim))
1373
+
1374
+ # Motion Controller
1375
+ if motion_bucket_id is not None and motion_controller is not None:
1376
+ t_mod = t_mod + motion_controller(motion_bucket_id).unflatten(1, (6, dit.dim))
1377
+ context = dit.text_embedding(context)
1378
+
1379
+ x = latents
1380
+ # Merged cfg
1381
+ if x.shape[0] != context.shape[0]:
1382
+ x = torch.concat([x] * context.shape[0], dim=0)
1383
+ if timestep.shape[0] != context.shape[0]:
1384
+ timestep = torch.concat([timestep] * context.shape[0], dim=0)
1385
+ if channel_concat_condition:
1386
+ if condition_latents is None:
1387
+ raise ValueError("channel_concat_condition=True requires condition_latents")
1388
+ condition_latents = condition_latents.to(device=x.device, dtype=x.dtype)
1389
+ if condition_latents.shape[0] != x.shape[0]:
1390
+ if x.shape[0] % condition_latents.shape[0] != 0:
1391
+ raise ValueError(
1392
+ f"Cannot expand condition batch {condition_latents.shape[0]} "
1393
+ f"to latent batch {x.shape[0]}"
1394
+ )
1395
+ condition_latents = torch.cat(
1396
+ [condition_latents] * (x.shape[0] // condition_latents.shape[0]), dim=0
1397
+ )
1398
+ if condition_latents.shape[2:] != x.shape[2:]:
1399
+ raise ValueError(
1400
+ f"Condition latent shape {tuple(condition_latents.shape)} does not match "
1401
+ f"bridge latent shape {tuple(x.shape)}"
1402
+ )
1403
+ x = torch.cat([x, condition_latents], dim=1)
1404
+
1405
+ # Image Embedding
1406
+ if y is not None and dit.require_vae_embedding:
1407
+ x = torch.cat([x, y], dim=1)
1408
+ if clip_feature is not None and dit.require_clip_embedding:
1409
+ clip_embdding = dit.img_emb(clip_feature)
1410
+ context = torch.cat([clip_embdding, context], dim=1)
1411
+
1412
+ # Camera control
1413
+ x = dit.patchify(x, control_camera_latents_input)
1414
+
1415
+ # Animate
1416
+ if animate_adapter is not None:
1417
+ x, motion_vec = animate_adapter.after_patch_embedding(x, pose_latents, face_pixel_values)
1418
+ else:
1419
+ motion_vec = None
1420
+
1421
+ # Patchify. For token-concat conditioning, the clean original video is a
1422
+ # prefix stream and the Brownian-bridge video is the prediction stream.
1423
+ f, h, w = x.shape[2:]
1424
+ target_frames = int(f)
1425
+ x = rearrange(x, 'b c f h w -> b (f h w) c').contiguous()
1426
+ prefix_token_count = 0
1427
+ prefix_frames = 0
1428
+ prefix_h = 0
1429
+ prefix_w = 0
1430
+ if token_prefix_latents is not None:
1431
+ prefix_latents = token_prefix_latents.to(device=latents.device, dtype=latents.dtype)
1432
+ if channel_concat_condition and prefix_latents.shape[1] * 2 == int(dit.in_dim):
1433
+ prefix_latents = torch.cat([prefix_latents, torch.zeros_like(prefix_latents)], dim=1)
1434
+ if prefix_latents.shape[0] != latents.shape[0]:
1435
+ if latents.shape[0] % prefix_latents.shape[0] != 0:
1436
+ raise ValueError(
1437
+ f"Cannot expand token prefix batch {prefix_latents.shape[0]} "
1438
+ f"to latent batch {latents.shape[0]}"
1439
+ )
1440
+ prefix_latents = torch.cat(
1441
+ [prefix_latents] * (latents.shape[0] // prefix_latents.shape[0]), dim=0
1442
+ )
1443
+ prefix_grid = dit.patchify(prefix_latents)
1444
+ prefix_frames, prefix_h, prefix_w = prefix_grid.shape[2:]
1445
+ prefix_tokens = rearrange(prefix_grid, 'b c f h w -> b (f h w) c').contiguous()
1446
+ prefix_token_count = int(prefix_tokens.shape[1])
1447
+ x = torch.cat([prefix_tokens, x], dim=1)
1448
+ f += int(prefix_frames)
1449
+
1450
+ if (separated_fused_timestep or separated_prefix_timestep) and not has_reference_latents:
1451
+ target_clean_frames = 1 + max(int(clean_history_latent_frames), 0) if separated_fused_timestep else 0
1452
+ target_clean_frames = min(target_clean_frames, int(latents.shape[2]))
1453
+ prefix_tokens_per_frame = int(prefix_h * prefix_w) if prefix_token_count else 0
1454
+ target_tokens_per_frame = int(h * w)
1455
+ token_timestep_parts = []
1456
+ if prefix_token_count:
1457
+ prefix_time = make_device_tensor([0.0] * int(prefix_frames), latents.device, latents.dtype)
1458
+ token_timestep_parts.append(prefix_time.repeat_interleave(prefix_tokens_per_frame))
1459
+ target_time = make_device_tensor(
1460
+ [0.0] * target_clean_frames
1461
+ + [float(timestep.flatten()[0].item())] * (int(latents.shape[2]) - target_clean_frames),
1462
+ latents.device,
1463
+ latents.dtype,
1464
+ )
1465
+ token_timestep_parts.append(target_time.repeat_interleave(target_tokens_per_frame))
1466
+ token_timestep = torch.cat(token_timestep_parts, dim=0)
1467
+ t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, token_timestep).unsqueeze(0))
1468
+ if t.shape[0] != x.shape[0]:
1469
+ t = torch.cat([t] * x.shape[0], dim=0)
1470
+ t_mod = dit.time_projection(t).unflatten(2, (6, dit.dim))
1471
+
1472
+ # Reference image
1473
+ if reference_latents is not None:
1474
+ if len(reference_latents.shape) == 5:
1475
+ reference_latents = reference_latents[:, :, 0]
1476
+ reference_latents = dit.ref_conv(reference_latents).flatten(2).transpose(1, 2)
1477
+ x = torch.concat([reference_latents, x], dim=1)
1478
+ f += 1
1479
+
1480
+ def build_rope_grid(frame_count: int, grid_h: int, grid_w: int) -> torch.Tensor:
1481
+ rope_freqs = dit.get_rope_freqs(x.device)
1482
+ return torch.cat([
1483
+ rope_freqs[0][:frame_count].view(frame_count, 1, 1, -1).expand(frame_count, grid_h, grid_w, -1),
1484
+ rope_freqs[1][:grid_h].view(1, grid_h, 1, -1).expand(frame_count, grid_h, grid_w, -1),
1485
+ rope_freqs[2][:grid_w].view(1, 1, grid_w, -1).expand(frame_count, grid_h, grid_w, -1),
1486
+ ], dim=-1).reshape(frame_count * grid_h * grid_w, 1, -1)
1487
+
1488
+ if token_prefix_aligned_rope and prefix_frames:
1489
+ # Keep token order [reference, prefix, target], but reset the temporal
1490
+ # RoPE coordinate for each stream. Corresponding prefix/target patches
1491
+ # therefore receive exactly the same (time, height, width) rotation.
1492
+ rope_streams = []
1493
+ if has_reference_latents:
1494
+ rope_streams.append(build_rope_grid(1, h, w))
1495
+ rope_streams.extend([
1496
+ build_rope_grid(int(prefix_frames), int(prefix_h), int(prefix_w)),
1497
+ build_rope_grid(target_frames, h, w),
1498
+ ])
1499
+ freqs = torch.cat(rope_streams, dim=0).to(x.device)
1500
+ else:
1501
+ freqs = build_rope_grid(int(f), h, w).to(x.device)
1502
+
1503
+ attn_mask = None
1504
+ if token_prefix_block_self_attention and prefix_token_count:
1505
+ if has_reference_latents:
1506
+ raise NotImplementedError(
1507
+ "token_prefix_block_self_attention is currently only supported without reference_latents"
1508
+ )
1509
+ attn_mask = build_token_prefix_attention_spec(
1510
+ prefix_token_count=prefix_token_count,
1511
+ target_token_count=int(target_frames * h * w),
1512
+ )
1513
+ if use_unified_sequence_parallel:
1514
+ raise NotImplementedError("Token-prefix attention masks do not support unified sequence parallelism")
1515
+
1516
+ # TeaCache
1517
+ if tea_cache is not None:
1518
+ tea_cache_update = tea_cache.check(dit, x, t_mod)
1519
+ else:
1520
+ tea_cache_update = False
1521
+
1522
+ if vace_context is not None:
1523
+ vace_hints = vace(
1524
+ x, vace_context, context, t_mod, freqs,
1525
+ use_gradient_checkpointing=use_gradient_checkpointing,
1526
+ use_gradient_checkpointing_offload=use_gradient_checkpointing_offload
1527
+ )
1528
+
1529
+ # Optional layer-aligned reference stream. It is kept as an explicit
1530
+ # checkpoint input/output instead of mutable module state, so recomputation
1531
+ # during gradient checkpointing is deterministic.
1532
+ reference_condition = getattr(dit, "_reference_condition", None)
1533
+ reference_x = None
1534
+ if getattr(dit, "_reference_adapters_enabled", False) and reference_condition is not None:
1535
+ reference_x = reference_condition.reference_tokens.to(dtype=x.dtype, device=x.device)
1536
+ if reference_x.shape[0] != x.shape[0]:
1537
+ if x.shape[0] % reference_x.shape[0] != 0:
1538
+ raise ValueError(
1539
+ f"Cannot expand reference batch {reference_x.shape[0]} to target batch {x.shape[0]}"
1540
+ )
1541
+ reference_x = torch.cat([reference_x] * (x.shape[0] // reference_x.shape[0]), dim=0)
1542
+ if use_unified_sequence_parallel:
1543
+ raise NotImplementedError(
1544
+ "Dual-stream frame-wise pair attention does not yet support unified sequence parallelism"
1545
+ )
1546
+ # TeaCache may skip transformer blocks and would therefore skip the
1547
+ # evolving reference stream and frame-wise pair-attention layers.
1548
+ tea_cache_update = False
1549
+ if reference_x is not None and attn_mask is not None:
1550
+ raise NotImplementedError("Dual-stream reference adapters do not support token-prefix attention masks")
1551
+
1552
+ # blocks
1553
+ if use_unified_sequence_parallel:
1554
+ if dist.is_initialized() and dist.get_world_size() > 1:
1555
+ chunks = torch.chunk(x, get_sequence_parallel_world_size(), dim=1)
1556
+ pad_shape = chunks[0].shape[1] - chunks[-1].shape[1]
1557
+ chunks = [torch.nn.functional.pad(chunk, (0, 0, 0, chunks[0].shape[1]-chunk.shape[1]), value=0) for chunk in chunks]
1558
+ x = chunks[get_sequence_parallel_rank()]
1559
+ if tea_cache_update:
1560
+ x = tea_cache.update(x)
1561
+ else:
1562
+ def create_custom_forward(module):
1563
+ def custom_forward(*inputs):
1564
+ return module(*inputs)
1565
+ return custom_forward
1566
+
1567
+ def create_dual_custom_forward(module):
1568
+ def custom_forward(*inputs):
1569
+ return module.forward_dual(*inputs)
1570
+ return custom_forward
1571
+
1572
+ for block_id, block in enumerate(dit.blocks):
1573
+ # Block
1574
+ dual_stream = reference_x is not None and hasattr(block, "forward_dual")
1575
+ if dual_stream and use_gradient_checkpointing_offload:
1576
+ with torch.autograd.graph.save_on_cpu():
1577
+ x, reference_x = torch.utils.checkpoint.checkpoint(
1578
+ create_dual_custom_forward(block),
1579
+ x, reference_x, context, t_mod, freqs,
1580
+ use_reentrant=False,
1581
+ )
1582
+ elif dual_stream and use_gradient_checkpointing:
1583
+ x, reference_x = torch.utils.checkpoint.checkpoint(
1584
+ create_dual_custom_forward(block),
1585
+ x, reference_x, context, t_mod, freqs,
1586
+ use_reentrant=False,
1587
+ )
1588
+ elif dual_stream:
1589
+ x, reference_x = block.forward_dual(x, reference_x, context, t_mod, freqs)
1590
+ elif use_gradient_checkpointing_offload:
1591
+ with torch.autograd.graph.save_on_cpu():
1592
+ if attn_mask is None:
1593
+ x = torch.utils.checkpoint.checkpoint(
1594
+ create_custom_forward(block),
1595
+ x, context, t_mod, freqs,
1596
+ use_reentrant=False,
1597
+ )
1598
+ else:
1599
+ x = torch.utils.checkpoint.checkpoint(
1600
+ create_custom_forward(block),
1601
+ x, context, t_mod, freqs, attn_mask,
1602
+ use_reentrant=False,
1603
+ )
1604
+ elif use_gradient_checkpointing:
1605
+ if attn_mask is None:
1606
+ x = torch.utils.checkpoint.checkpoint(
1607
+ create_custom_forward(block),
1608
+ x, context, t_mod, freqs,
1609
+ use_reentrant=False,
1610
+ )
1611
+ else:
1612
+ x = torch.utils.checkpoint.checkpoint(
1613
+ create_custom_forward(block),
1614
+ x, context, t_mod, freqs, attn_mask,
1615
+ use_reentrant=False,
1616
+ )
1617
+ else:
1618
+ x = block(x, context, t_mod, freqs, attn_mask=attn_mask)
1619
+
1620
+ # VACE
1621
+ if vace_context is not None and block_id in vace.vace_layers_mapping:
1622
+ current_vace_hint = vace_hints[vace.vace_layers_mapping[block_id]]
1623
+ if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1:
1624
+ current_vace_hint = torch.chunk(current_vace_hint, get_sequence_parallel_world_size(), dim=1)[get_sequence_parallel_rank()]
1625
+ current_vace_hint = torch.nn.functional.pad(current_vace_hint, (0, 0, 0, chunks[0].shape[1] - current_vace_hint.shape[1]), value=0)
1626
+ x = x + current_vace_hint * vace_scale
1627
+
1628
+ # Animate
1629
+ if animate_adapter is not None and pose_latents is not None and face_pixel_values is not None:
1630
+ x = animate_adapter.after_transformer_block(block_id, x, motion_vec)
1631
+ if tea_cache is not None:
1632
+ tea_cache.store(x)
1633
+
1634
+ x = dit.head(x, t)
1635
+ if use_unified_sequence_parallel:
1636
+ if dist.is_initialized() and dist.get_world_size() > 1:
1637
+ x = get_sp_group().all_gather(x, dim=1)
1638
+ x = x[:, :-pad_shape] if pad_shape > 0 else x
1639
+ # Remove a token-concat prefix. The model predicts both streams, but only
1640
+ # the edited-video stream is part of the bridge output.
1641
+ if prefix_token_count:
1642
+ x = x[:, prefix_token_count:]
1643
+ f -= prefix_frames
1644
+ # Remove legacy Wan reference-image latents
1645
+ if reference_latents is not None:
1646
+ x = x[:, reference_latents.shape[1]:]
1647
+ f -= 1
1648
+ x = dit.unpatchify(x, (f, h, w))
1649
+ return x
1650
+
1651
+
1652
+ def model_fn_wans2v(
1653
+ dit,
1654
+ latents,
1655
+ timestep,
1656
+ context,
1657
+ audio_embeds,
1658
+ motion_latents,
1659
+ s2v_pose_latents,
1660
+ drop_motion_frames=True,
1661
+ use_gradient_checkpointing_offload=False,
1662
+ use_gradient_checkpointing=False,
1663
+ use_unified_sequence_parallel=False,
1664
+ ):
1665
+ if use_unified_sequence_parallel:
1666
+ import torch.distributed as dist
1667
+ from xfuser.core.distributed import (get_sequence_parallel_rank,
1668
+ get_sequence_parallel_world_size,
1669
+ get_sp_group)
1670
+ origin_ref_latents = latents[:, :, 0:1]
1671
+ x = latents[:, :, 1:]
1672
+
1673
+ # context embedding
1674
+ context = dit.text_embedding(context)
1675
+
1676
+ # audio encode
1677
+ audio_emb_global, merged_audio_emb = dit.cal_audio_emb(audio_embeds)
1678
+
1679
+ # x and s2v_pose_latents
1680
+ s2v_pose_latents = torch.zeros_like(x) if s2v_pose_latents is None else s2v_pose_latents
1681
+ x, (f, h, w) = dit.patchify(dit.patch_embedding(x) + dit.cond_encoder(s2v_pose_latents))
1682
+ seq_len_x = seq_len_x_global = x.shape[1] # global used for unified sequence parallel
1683
+
1684
+ # reference image
1685
+ ref_latents, (rf, rh, rw) = dit.patchify(dit.patch_embedding(origin_ref_latents))
1686
+ grid_sizes = dit.get_grid_sizes((f, h, w), (rf, rh, rw))
1687
+ x = torch.cat([x, ref_latents], dim=1)
1688
+ # mask
1689
+ mask = torch.cat([torch.zeros([1, seq_len_x]), torch.ones([1, ref_latents.shape[1]])], dim=1).to(torch.long).to(x.device)
1690
+ # freqs
1691
+ 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)
1692
+ # motion
1693
+ 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)
1694
+
1695
+ x = x + dit.trainable_cond_mask(mask).to(x.dtype)
1696
+
1697
+ # tmod
1698
+ timestep = torch.cat([timestep, torch.zeros([1], dtype=timestep.dtype, device=timestep.device)])
1699
+ t = dit.time_embedding(sinusoidal_embedding_1d(dit.freq_dim, timestep))
1700
+ t_mod = dit.time_projection(t).unflatten(1, (6, dit.dim)).unsqueeze(2).transpose(0, 2)
1701
+
1702
+ if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1:
1703
+ world_size, sp_rank = get_sequence_parallel_world_size(), get_sequence_parallel_rank()
1704
+ 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()}"
1705
+ x = torch.chunk(x, world_size, dim=1)[sp_rank]
1706
+ seg_idxs = [0] + list(torch.cumsum(torch.tensor([x.shape[1]] * world_size), dim=0).cpu().numpy())
1707
+ seq_len_x_list = [min(max(0, seq_len_x - seg_idxs[i]), x.shape[1]) for i in range(len(seg_idxs)-1)]
1708
+ seq_len_x = seq_len_x_list[sp_rank]
1709
+
1710
+ def create_custom_forward(module):
1711
+ def custom_forward(*inputs):
1712
+ return module(*inputs)
1713
+ return custom_forward
1714
+
1715
+ for block_id, block in enumerate(dit.blocks):
1716
+ if use_gradient_checkpointing_offload:
1717
+ with torch.autograd.graph.save_on_cpu():
1718
+ x = torch.utils.checkpoint.checkpoint(
1719
+ create_custom_forward(block),
1720
+ x, context, t_mod, seq_len_x, pre_compute_freqs[0],
1721
+ use_reentrant=False,
1722
+ )
1723
+ x = torch.utils.checkpoint.checkpoint(
1724
+ create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)),
1725
+ x,
1726
+ use_reentrant=False,
1727
+ )
1728
+ elif use_gradient_checkpointing:
1729
+ x = torch.utils.checkpoint.checkpoint(
1730
+ create_custom_forward(block),
1731
+ x, context, t_mod, seq_len_x, pre_compute_freqs[0],
1732
+ use_reentrant=False,
1733
+ )
1734
+ x = torch.utils.checkpoint.checkpoint(
1735
+ create_custom_forward(lambda x: dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x)),
1736
+ x,
1737
+ use_reentrant=False,
1738
+ )
1739
+ else:
1740
+ x = block(x, context, t_mod, seq_len_x, pre_compute_freqs[0])
1741
+ x = dit.after_transformer_block(block_id, x, audio_emb_global, merged_audio_emb, seq_len_x_global, use_unified_sequence_parallel)
1742
+
1743
+ if use_unified_sequence_parallel and dist.is_initialized() and dist.get_world_size() > 1:
1744
+ x = get_sp_group().all_gather(x, dim=1)
1745
+
1746
+ x = x[:, :seq_len_x_global]
1747
+ x = dit.head(x, t[:-1])
1748
+ x = dit.unpatchify(x, (f, h, w))
1749
+ # make compatible with wan video
1750
+ x = torch.cat([origin_ref_latents, x], dim=2)
1751
+ return x
releases/2026-10-20-code/diffsynth/configs/__init__.py ADDED
File without changes
releases/2026-10-20-code/diffsynth/configs/model_config.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wan-only model detector configuration used by the ViBT release."""
2
+ from typing import TypeAlias
3
+
4
+ # Minimal compatibility definitions required by diffsynth.models.downloader.
5
+ # ViBT loads Wan weights through ModelConfig(model_id=..., origin_file_pattern=...),
6
+ # so the legacy preset-model tables are intentionally left empty.
7
+ preset_models_on_huggingface = {}
8
+ preset_models_on_modelscope = {}
9
+ Preset_model_id: TypeAlias = str
10
+
11
+ from ..models.wan_video_dit import WanModel
12
+ from ..models.wan_video_dit_s2v import WanS2VModel
13
+ from ..models.wan_video_text_encoder import WanTextEncoder
14
+ from ..models.wan_video_image_encoder import WanImageEncoder
15
+ from ..models.wan_video_vae import WanVideoVAE, WanVideoVAE38
16
+ from ..models.wan_video_motion_controller import WanMotionControllerModel
17
+ from ..models.wan_video_vace import VaceWanModel
18
+ from ..models.wav2vec import WanS2VAudioEncoder
19
+ from ..models.wan_video_animate_adapter import WanAnimateAdapter
20
+
21
+ model_loader_configs = [
22
+ (None, "9269f8db9040a9d860eaca435be61814", ["wan_video_dit"], [WanModel], "civitai"),
23
+ (None, "aafcfd9672c3a2456dc46e1cb6e52c70", ["wan_video_dit"], [WanModel], "civitai"),
24
+ (None, "6bfcfb3b342cb286ce886889d519a77e", ["wan_video_dit"], [WanModel], "civitai"),
25
+ (None, "6d6ccde6845b95ad9114ab993d917893", ["wan_video_dit"], [WanModel], "civitai"),
26
+ (None, "349723183fc063b2bfc10bb2835cf677", ["wan_video_dit"], [WanModel], "civitai"),
27
+ (None, "efa44cddf936c70abd0ea28b6cbe946c", ["wan_video_dit"], [WanModel], "civitai"),
28
+ (None, "3ef3b1f8e1dab83d5b71fd7b617f859f", ["wan_video_dit"], [WanModel], "civitai"),
29
+ (None, "70ddad9d3a133785da5ea371aae09504", ["wan_video_dit"], [WanModel], "civitai"),
30
+ (None, "26bde73488a92e64cc20b0a7485b9e5b", ["wan_video_dit"], [WanModel], "civitai"),
31
+ (None, "ac6a5aa74f4a0aab6f64eb9a72f19901", ["wan_video_dit"], [WanModel], "civitai"),
32
+ (None, "b61c605c2adbd23124d152ed28e049ae", ["wan_video_dit"], [WanModel], "civitai"),
33
+ (None, "1f5ab7703c6fc803fdded85ff040c316", ["wan_video_dit"], [WanModel], "civitai"),
34
+ (None, "5b013604280dd715f8457c6ed6d6a626", ["wan_video_dit"], [WanModel], "civitai"),
35
+ (None, "2267d489f0ceb9f21836532952852ee5", ["wan_video_dit"], [WanModel], "civitai"),
36
+ (None, "47dbeab5e560db3180adf51dc0232fb1", ["wan_video_dit"], [WanModel], "civitai"),
37
+ (None, "a61453409b67cd3246cf0c3bebad47ba", ["wan_video_dit", "wan_video_vace"], [WanModel, VaceWanModel], "civitai"),
38
+ (None, "7a513e1f257a861512b1afd387a8ecd9", ["wan_video_dit", "wan_video_vace"], [WanModel, VaceWanModel], "civitai"),
39
+ (None, "cb104773c6c2cb6df4f9529ad5c60d0b", ["wan_video_dit"], [WanModel], "diffusers"),
40
+ (None, "966cffdcc52f9c46c391768b27637614", ["wan_video_dit"], [WanS2VModel], "civitai"),
41
+ (None, "9c8818c2cbea55eca56c7b447df170da", ["wan_video_text_encoder"], [WanTextEncoder], "civitai"),
42
+ (None, "5941c53e207d62f20f9025686193c40b", ["wan_video_image_encoder"], [WanImageEncoder], "civitai"),
43
+ (None, "1378ea763357eea97acdef78e65d6d96", ["wan_video_vae"], [WanVideoVAE], "civitai"),
44
+ (None, "ccc42284ea13e1ad04693284c7a09be6", ["wan_video_vae"], [WanVideoVAE], "civitai"),
45
+ (None, "e1de6c02cdac79f8b739f4d3698cd216", ["wan_video_vae"], [WanVideoVAE38], "civitai"),
46
+ (None, "dbd5ec76bbf977983f972c151d545389", ["wan_video_motion_controller"], [WanMotionControllerModel], "civitai"),
47
+ (None, "06be60f3a4526586d8431cd038a71486", ["wans2v_audio_encoder"], [WanS2VAudioEncoder], "civitai"),
48
+ (None, "31fa352acb8a1b1d33cd8764273d80a2", ["wan_video_dit", "wan_video_animate_adapter"], [WanModel, WanAnimateAdapter], "civitai"),
49
+ ]
50
+
51
+ huggingface_model_loader_configs = []
52
+ patch_model_loader_configs = []
releases/2026-10-20-code/diffsynth/data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .video import VideoData, save_video, save_video_with_audio
releases/2026-10-20-code/diffsynth/data/video.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import imageio, os
2
+ import numpy as np
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import subprocess
6
+ import shutil
7
+
8
+
9
+ class LowMemoryVideo:
10
+ def __init__(self, file_name):
11
+ self.reader = imageio.get_reader(file_name)
12
+
13
+ def __len__(self):
14
+ return self.reader.count_frames()
15
+
16
+ def __getitem__(self, item):
17
+ return Image.fromarray(np.array(self.reader.get_data(item))).convert("RGB")
18
+
19
+ def __del__(self):
20
+ self.reader.close()
21
+
22
+
23
+ def split_file_name(file_name):
24
+ result = []
25
+ number = -1
26
+ for i in file_name:
27
+ if ord(i)>=ord("0") and ord(i)<=ord("9"):
28
+ if number == -1:
29
+ number = 0
30
+ number = number*10 + ord(i) - ord("0")
31
+ else:
32
+ if number != -1:
33
+ result.append(number)
34
+ number = -1
35
+ result.append(i)
36
+ if number != -1:
37
+ result.append(number)
38
+ result = tuple(result)
39
+ return result
40
+
41
+
42
+ def search_for_images(folder):
43
+ file_list = [i for i in os.listdir(folder) if i.endswith(".jpg") or i.endswith(".png")]
44
+ file_list = [(split_file_name(file_name), file_name) for file_name in file_list]
45
+ file_list = [i[1] for i in sorted(file_list)]
46
+ file_list = [os.path.join(folder, i) for i in file_list]
47
+ return file_list
48
+
49
+
50
+ class LowMemoryImageFolder:
51
+ def __init__(self, folder, file_list=None):
52
+ if file_list is None:
53
+ self.file_list = search_for_images(folder)
54
+ else:
55
+ self.file_list = [os.path.join(folder, file_name) for file_name in file_list]
56
+
57
+ def __len__(self):
58
+ return len(self.file_list)
59
+
60
+ def __getitem__(self, item):
61
+ return Image.open(self.file_list[item]).convert("RGB")
62
+
63
+ def __del__(self):
64
+ pass
65
+
66
+
67
+ def crop_and_resize(image, height, width):
68
+ image = np.array(image)
69
+ image_height, image_width, _ = image.shape
70
+ if image_height / image_width < height / width:
71
+ croped_width = int(image_height / height * width)
72
+ left = (image_width - croped_width) // 2
73
+ image = image[:, left: left+croped_width]
74
+ image = Image.fromarray(image).resize((width, height))
75
+ else:
76
+ croped_height = int(image_width / width * height)
77
+ left = (image_height - croped_height) // 2
78
+ image = image[left: left+croped_height, :]
79
+ image = Image.fromarray(image).resize((width, height))
80
+ return image
81
+
82
+
83
+ class VideoData:
84
+ def __init__(self, video_file=None, image_folder=None, height=None, width=None, **kwargs):
85
+ if video_file is not None:
86
+ self.data_type = "video"
87
+ self.data = LowMemoryVideo(video_file, **kwargs)
88
+ elif image_folder is not None:
89
+ self.data_type = "images"
90
+ self.data = LowMemoryImageFolder(image_folder, **kwargs)
91
+ else:
92
+ raise ValueError("Cannot open video or image folder")
93
+ self.length = None
94
+ self.set_shape(height, width)
95
+
96
+ def raw_data(self):
97
+ frames = []
98
+ for i in range(self.__len__()):
99
+ frames.append(self.__getitem__(i))
100
+ return frames
101
+
102
+ def set_length(self, length):
103
+ self.length = length
104
+
105
+ def set_shape(self, height, width):
106
+ self.height = height
107
+ self.width = width
108
+
109
+ def __len__(self):
110
+ if self.length is None:
111
+ return len(self.data)
112
+ else:
113
+ return self.length
114
+
115
+ def shape(self):
116
+ if self.height is not None and self.width is not None:
117
+ return self.height, self.width
118
+ else:
119
+ height, width, _ = self.__getitem__(0).shape
120
+ return height, width
121
+
122
+ def __getitem__(self, item):
123
+ frame = self.data.__getitem__(item)
124
+ width, height = frame.size
125
+ if self.height is not None and self.width is not None:
126
+ if self.height != height or self.width != width:
127
+ frame = crop_and_resize(frame, self.height, self.width)
128
+ return frame
129
+
130
+ def __del__(self):
131
+ pass
132
+
133
+ def save_images(self, folder):
134
+ os.makedirs(folder, exist_ok=True)
135
+ for i in tqdm(range(self.__len__()), desc="Saving images"):
136
+ frame = self.__getitem__(i)
137
+ frame.save(os.path.join(folder, f"{i}.png"))
138
+
139
+
140
+ def save_video(frames, save_path, fps, quality=9, ffmpeg_params=None):
141
+ # quality and ffmpeg_params belong to the legacy FFMPEG backend, not PyAV.
142
+ with imageio.get_writer(save_path, format="FFMPEG", fps=fps,
143
+ quality=quality, ffmpeg_params=ffmpeg_params) as writer:
144
+ for frame in tqdm(frames, desc="Saving video"):
145
+ writer.append_data(np.array(frame))
146
+
147
+ def save_frames(frames, save_path):
148
+ os.makedirs(save_path, exist_ok=True)
149
+ for i, frame in enumerate(tqdm(frames, desc="Saving images")):
150
+ frame.save(os.path.join(save_path, f"{i}.png"))
151
+
152
+
153
+ def merge_video_audio(video_path: str, audio_path: str):
154
+ # TODO: may need a in-python implementation to avoid subprocess dependency
155
+ """
156
+ Merge the video and audio into a new video, with the duration set to the shorter of the two,
157
+ and overwrite the original video file.
158
+
159
+ Parameters:
160
+ video_path (str): Path to the original video file
161
+ audio_path (str): Path to the audio file
162
+ """
163
+
164
+ # check
165
+ if not os.path.exists(video_path):
166
+ raise FileNotFoundError(f"video file {video_path} does not exist")
167
+ if not os.path.exists(audio_path):
168
+ raise FileNotFoundError(f"audio file {audio_path} does not exist")
169
+
170
+ base, ext = os.path.splitext(video_path)
171
+ temp_output = f"{base}_temp{ext}"
172
+
173
+ try:
174
+ # create ffmpeg command
175
+ command = [
176
+ 'ffmpeg',
177
+ '-y', # overwrite
178
+ '-i',
179
+ video_path,
180
+ '-i',
181
+ audio_path,
182
+ '-c:v',
183
+ 'copy', # copy video stream
184
+ '-c:a',
185
+ 'aac', # use AAC audio encoder
186
+ '-b:a',
187
+ '192k', # set audio bitrate (optional)
188
+ '-map',
189
+ '0:v:0', # select the first video stream
190
+ '-map',
191
+ '1:a:0', # select the first audio stream
192
+ '-shortest', # choose the shortest duration
193
+ temp_output
194
+ ]
195
+
196
+ # execute the command
197
+ result = subprocess.run(
198
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
199
+
200
+ # check result
201
+ if result.returncode != 0:
202
+ error_msg = f"FFmpeg execute failed: {result.stderr}"
203
+ print(error_msg)
204
+ raise RuntimeError(error_msg)
205
+
206
+ shutil.move(temp_output, video_path)
207
+ print(f"Merge completed, saved to {video_path}")
208
+
209
+ except Exception as e:
210
+ if os.path.exists(temp_output):
211
+ os.remove(temp_output)
212
+ print(f"merge_video_audio failed with error: {e}")
213
+
214
+
215
+ def save_video_with_audio(frames, save_path, audio_path, fps=16, quality=9, ffmpeg_params=None):
216
+ save_video(frames, save_path, fps, quality, ffmpeg_params)
217
+ merge_video_audio(save_path, audio_path)
releases/2026-10-20-code/diffsynth/lora/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+
5
+ class GeneralLoRALoader:
6
+ def __init__(self, device="cpu", torch_dtype=torch.float32):
7
+ self.device = device
8
+ self.torch_dtype = torch_dtype
9
+
10
+
11
+ def get_name_dict(self, lora_state_dict):
12
+ lora_name_dict = {}
13
+ for key in lora_state_dict:
14
+ if ".lora_B." not in key:
15
+ continue
16
+ keys = key.split(".")
17
+ if len(keys) > keys.index("lora_B") + 2:
18
+ keys.pop(keys.index("lora_B") + 1)
19
+ keys.pop(keys.index("lora_B"))
20
+ if keys[0] == "diffusion_model":
21
+ keys.pop(0)
22
+ keys.pop(-1)
23
+ target_name = ".".join(keys)
24
+ lora_name_dict[target_name] = (key, key.replace(".lora_B.", ".lora_A."))
25
+ return lora_name_dict
26
+
27
+
28
+ def load(self, model: torch.nn.Module, state_dict_lora, alpha=1.0):
29
+ updated_num = 0
30
+ lora_name_dict = self.get_name_dict(state_dict_lora)
31
+ for name, module in model.named_modules():
32
+ if name in lora_name_dict:
33
+ weight_up = state_dict_lora[lora_name_dict[name][0]].to(device=self.device, dtype=self.torch_dtype)
34
+ weight_down = state_dict_lora[lora_name_dict[name][1]].to(device=self.device, dtype=self.torch_dtype)
35
+ if len(weight_up.shape) == 4:
36
+ weight_up = weight_up.squeeze(3).squeeze(2)
37
+ weight_down = weight_down.squeeze(3).squeeze(2)
38
+ weight_lora = alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
39
+ else:
40
+ weight_lora = alpha * torch.mm(weight_up, weight_down)
41
+ state_dict = module.state_dict()
42
+ state_dict["weight"] = state_dict["weight"].to(device=self.device, dtype=self.torch_dtype) + weight_lora
43
+ module.load_state_dict(state_dict)
44
+ updated_num += 1
45
+ print(f"{updated_num} tensors are updated by LoRA.")
releases/2026-10-20-code/diffsynth/models/__init__.py ADDED
File without changes
releases/2026-10-20-code/diffsynth/models/downloader.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+ try:
3
+ from modelscope import snapshot_download
4
+ except ModuleNotFoundError:
5
+ snapshot_download = None
6
+ import os, shutil
7
+ from typing_extensions import Literal, TypeAlias
8
+ from typing import List
9
+ from ..configs.model_config import preset_models_on_huggingface, preset_models_on_modelscope, Preset_model_id
10
+
11
+
12
+ def download_from_modelscope(model_id, origin_file_path, local_dir):
13
+ if snapshot_download is None:
14
+ raise ModuleNotFoundError("modelscope is required to download models from ModelScope.")
15
+ os.makedirs(local_dir, exist_ok=True)
16
+ file_name = os.path.basename(origin_file_path)
17
+ if file_name in os.listdir(local_dir):
18
+ print(f" {file_name} has been already in {local_dir}.")
19
+ else:
20
+ print(f" Start downloading {os.path.join(local_dir, file_name)}")
21
+ snapshot_download(model_id, allow_file_pattern=origin_file_path, local_dir=local_dir)
22
+ downloaded_file_path = os.path.join(local_dir, origin_file_path)
23
+ target_file_path = os.path.join(local_dir, os.path.split(origin_file_path)[-1])
24
+ if downloaded_file_path != target_file_path:
25
+ shutil.move(downloaded_file_path, target_file_path)
26
+ shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0]))
27
+
28
+
29
+ def download_from_huggingface(model_id, origin_file_path, local_dir):
30
+ os.makedirs(local_dir, exist_ok=True)
31
+ file_name = os.path.basename(origin_file_path)
32
+ if file_name in os.listdir(local_dir):
33
+ print(f" {file_name} has been already in {local_dir}.")
34
+ else:
35
+ print(f" Start downloading {os.path.join(local_dir, file_name)}")
36
+ hf_hub_download(model_id, origin_file_path, local_dir=local_dir)
37
+ downloaded_file_path = os.path.join(local_dir, origin_file_path)
38
+ target_file_path = os.path.join(local_dir, file_name)
39
+ if downloaded_file_path != target_file_path:
40
+ shutil.move(downloaded_file_path, target_file_path)
41
+ shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0]))
42
+
43
+
44
+ Preset_model_website: TypeAlias = Literal[
45
+ "HuggingFace",
46
+ "ModelScope",
47
+ ]
48
+ website_to_preset_models = {
49
+ "HuggingFace": preset_models_on_huggingface,
50
+ "ModelScope": preset_models_on_modelscope,
51
+ }
52
+ website_to_download_fn = {
53
+ "HuggingFace": download_from_huggingface,
54
+ "ModelScope": download_from_modelscope,
55
+ }
56
+
57
+
58
+ def download_customized_models(
59
+ model_id,
60
+ origin_file_path,
61
+ local_dir,
62
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
63
+ ):
64
+ downloaded_files = []
65
+ for website in downloading_priority:
66
+ # Check if the file is downloaded.
67
+ file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path))
68
+ if file_to_download in downloaded_files:
69
+ continue
70
+ # Download
71
+ website_to_download_fn[website](model_id, origin_file_path, local_dir)
72
+ if os.path.basename(origin_file_path) in os.listdir(local_dir):
73
+ downloaded_files.append(file_to_download)
74
+ return downloaded_files
75
+
76
+
77
+ def download_models(
78
+ model_id_list: List[Preset_model_id] = [],
79
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
80
+ ):
81
+ print(f"Downloading models: {model_id_list}")
82
+ downloaded_files = []
83
+ load_files = []
84
+
85
+ for model_id in model_id_list:
86
+ for website in downloading_priority:
87
+ if model_id in website_to_preset_models[website]:
88
+
89
+ # Parse model metadata
90
+ model_metadata = website_to_preset_models[website][model_id]
91
+ if isinstance(model_metadata, list):
92
+ file_data = model_metadata
93
+ else:
94
+ file_data = model_metadata.get("file_list", [])
95
+
96
+ # Try downloading the model from this website.
97
+ model_files = []
98
+ for model_id, origin_file_path, local_dir in file_data:
99
+ # Check if the file is downloaded.
100
+ file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path))
101
+ if file_to_download in downloaded_files:
102
+ continue
103
+ # Download
104
+ website_to_download_fn[website](model_id, origin_file_path, local_dir)
105
+ if os.path.basename(origin_file_path) in os.listdir(local_dir):
106
+ downloaded_files.append(file_to_download)
107
+ model_files.append(file_to_download)
108
+
109
+ # If the model is successfully downloaded, break.
110
+ if len(model_files) > 0:
111
+ if isinstance(model_metadata, dict) and "load_path" in model_metadata:
112
+ model_files = model_metadata["load_path"]
113
+ load_files.extend(model_files)
114
+ break
115
+
116
+ return load_files
releases/2026-10-20-code/diffsynth/models/model_manager.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, torch, json, importlib
2
+ from typing import List
3
+
4
+ from .downloader import download_models, download_customized_models, Preset_model_id, Preset_model_website
5
+
6
+
7
+ from ..configs.model_config import model_loader_configs, huggingface_model_loader_configs, patch_model_loader_configs
8
+ from .utils import load_state_dict, init_weights_on_device, hash_state_dict_keys, split_state_dict_with_prefix
9
+
10
+
11
+ def load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device):
12
+ loaded_model_names, loaded_models = [], []
13
+ for model_name, model_class in zip(model_names, model_classes):
14
+ print(f" model_name: {model_name} model_class: {model_class.__name__}")
15
+ state_dict_converter = model_class.state_dict_converter()
16
+ if model_resource == "civitai":
17
+ state_dict_results = state_dict_converter.from_civitai(state_dict)
18
+ elif model_resource == "diffusers":
19
+ state_dict_results = state_dict_converter.from_diffusers(state_dict)
20
+ if isinstance(state_dict_results, tuple):
21
+ model_state_dict, extra_kwargs = state_dict_results
22
+ print(f" This model is initialized with extra kwargs: {extra_kwargs}")
23
+ else:
24
+ model_state_dict, extra_kwargs = state_dict_results, {}
25
+ torch_dtype = torch.float32 if extra_kwargs.get("upcast_to_float32", False) else torch_dtype
26
+ with init_weights_on_device():
27
+ model = model_class(**extra_kwargs)
28
+ if hasattr(model, "eval"):
29
+ model = model.eval()
30
+ model.load_state_dict(model_state_dict, assign=True)
31
+ model = model.to(dtype=torch_dtype, device=device)
32
+ loaded_model_names.append(model_name)
33
+ loaded_models.append(model)
34
+ return loaded_model_names, loaded_models
35
+
36
+
37
+ def load_model_from_huggingface_folder(file_path, model_names, model_classes, torch_dtype, device):
38
+ loaded_model_names, loaded_models = [], []
39
+ for model_name, model_class in zip(model_names, model_classes):
40
+ if torch_dtype in [torch.float32, torch.float16, torch.bfloat16]:
41
+ model = model_class.from_pretrained(file_path, torch_dtype=torch_dtype).eval()
42
+ else:
43
+ model = model_class.from_pretrained(file_path).eval().to(dtype=torch_dtype)
44
+ if torch_dtype == torch.float16 and hasattr(model, "half"):
45
+ model = model.half()
46
+ try:
47
+ model = model.to(device=device)
48
+ except:
49
+ pass
50
+ loaded_model_names.append(model_name)
51
+ loaded_models.append(model)
52
+ return loaded_model_names, loaded_models
53
+
54
+
55
+ def load_single_patch_model_from_single_file(state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device):
56
+ print(f" model_name: {model_name} model_class: {model_class.__name__} extra_kwargs: {extra_kwargs}")
57
+ base_state_dict = base_model.state_dict()
58
+ base_model.to("cpu")
59
+ del base_model
60
+ model = model_class(**extra_kwargs)
61
+ model.load_state_dict(base_state_dict, strict=False)
62
+ model.load_state_dict(state_dict, strict=False)
63
+ model.to(dtype=torch_dtype, device=device)
64
+ return model
65
+
66
+
67
+ def load_patch_model_from_single_file(state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device):
68
+ loaded_model_names, loaded_models = [], []
69
+ for model_name, model_class in zip(model_names, model_classes):
70
+ while True:
71
+ for model_id in range(len(model_manager.model)):
72
+ base_model_name = model_manager.model_name[model_id]
73
+ if base_model_name == model_name:
74
+ base_model_path = model_manager.model_path[model_id]
75
+ base_model = model_manager.model[model_id]
76
+ print(f" Adding patch model to {base_model_name} ({base_model_path})")
77
+ patched_model = load_single_patch_model_from_single_file(
78
+ state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device)
79
+ loaded_model_names.append(base_model_name)
80
+ loaded_models.append(patched_model)
81
+ model_manager.model.pop(model_id)
82
+ model_manager.model_path.pop(model_id)
83
+ model_manager.model_name.pop(model_id)
84
+ break
85
+ else:
86
+ break
87
+ return loaded_model_names, loaded_models
88
+
89
+
90
+
91
+ class ModelDetectorTemplate:
92
+ def __init__(self):
93
+ pass
94
+
95
+ def match(self, file_path="", state_dict={}):
96
+ return False
97
+
98
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
99
+ return [], []
100
+
101
+
102
+
103
+ class ModelDetectorFromSingleFile:
104
+ def __init__(self, model_loader_configs=[]):
105
+ self.keys_hash_with_shape_dict = {}
106
+ self.keys_hash_dict = {}
107
+ for metadata in model_loader_configs:
108
+ self.add_model_metadata(*metadata)
109
+
110
+
111
+ def add_model_metadata(self, keys_hash, keys_hash_with_shape, model_names, model_classes, model_resource):
112
+ self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_names, model_classes, model_resource)
113
+ if keys_hash is not None:
114
+ self.keys_hash_dict[keys_hash] = (model_names, model_classes, model_resource)
115
+
116
+
117
+ def match(self, file_path="", state_dict={}):
118
+ if isinstance(file_path, str) and os.path.isdir(file_path):
119
+ return False
120
+ if len(state_dict) == 0:
121
+ state_dict = load_state_dict(file_path)
122
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
123
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
124
+ return True
125
+ keys_hash = hash_state_dict_keys(state_dict, with_shape=False)
126
+ if keys_hash in self.keys_hash_dict:
127
+ return True
128
+ return False
129
+
130
+
131
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
132
+ if len(state_dict) == 0:
133
+ state_dict = load_state_dict(file_path)
134
+
135
+ # Load models with strict matching
136
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
137
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
138
+ model_names, model_classes, model_resource = self.keys_hash_with_shape_dict[keys_hash_with_shape]
139
+ loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device)
140
+ return loaded_model_names, loaded_models
141
+
142
+ # Load models without strict matching
143
+ # (the shape of parameters may be inconsistent, and the state_dict_converter will modify the model architecture)
144
+ keys_hash = hash_state_dict_keys(state_dict, with_shape=False)
145
+ if keys_hash in self.keys_hash_dict:
146
+ model_names, model_classes, model_resource = self.keys_hash_dict[keys_hash]
147
+ loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device)
148
+ return loaded_model_names, loaded_models
149
+
150
+ return loaded_model_names, loaded_models
151
+
152
+
153
+
154
+ class ModelDetectorFromSplitedSingleFile(ModelDetectorFromSingleFile):
155
+ def __init__(self, model_loader_configs=[]):
156
+ super().__init__(model_loader_configs)
157
+
158
+
159
+ def match(self, file_path="", state_dict={}):
160
+ if isinstance(file_path, str) and os.path.isdir(file_path):
161
+ return False
162
+ if len(state_dict) == 0:
163
+ state_dict = load_state_dict(file_path)
164
+ splited_state_dict = split_state_dict_with_prefix(state_dict)
165
+ for sub_state_dict in splited_state_dict:
166
+ if super().match(file_path, sub_state_dict):
167
+ return True
168
+ return False
169
+
170
+
171
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
172
+ # Split the state_dict and load from each component
173
+ splited_state_dict = split_state_dict_with_prefix(state_dict)
174
+ valid_state_dict = {}
175
+ for sub_state_dict in splited_state_dict:
176
+ if super().match(file_path, sub_state_dict):
177
+ valid_state_dict.update(sub_state_dict)
178
+ if super().match(file_path, valid_state_dict):
179
+ loaded_model_names, loaded_models = super().load(file_path, valid_state_dict, device, torch_dtype)
180
+ else:
181
+ loaded_model_names, loaded_models = [], []
182
+ for sub_state_dict in splited_state_dict:
183
+ if super().match(file_path, sub_state_dict):
184
+ loaded_model_names_, loaded_models_ = super().load(file_path, valid_state_dict, device, torch_dtype)
185
+ loaded_model_names += loaded_model_names_
186
+ loaded_models += loaded_models_
187
+ return loaded_model_names, loaded_models
188
+
189
+
190
+
191
+ class ModelDetectorFromHuggingfaceFolder:
192
+ def __init__(self, model_loader_configs=[]):
193
+ self.architecture_dict = {}
194
+ for metadata in model_loader_configs:
195
+ self.add_model_metadata(*metadata)
196
+
197
+
198
+ def add_model_metadata(self, architecture, huggingface_lib, model_name, redirected_architecture):
199
+ self.architecture_dict[architecture] = (huggingface_lib, model_name, redirected_architecture)
200
+
201
+
202
+ def match(self, file_path="", state_dict={}):
203
+ if not isinstance(file_path, str) or os.path.isfile(file_path):
204
+ return False
205
+ file_list = os.listdir(file_path)
206
+ if "config.json" not in file_list:
207
+ return False
208
+ with open(os.path.join(file_path, "config.json"), "r") as f:
209
+ config = json.load(f)
210
+ if "architectures" not in config and "_class_name" not in config:
211
+ return False
212
+ return True
213
+
214
+
215
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
216
+ with open(os.path.join(file_path, "config.json"), "r") as f:
217
+ config = json.load(f)
218
+ loaded_model_names, loaded_models = [], []
219
+ architectures = config["architectures"] if "architectures" in config else [config["_class_name"]]
220
+ for architecture in architectures:
221
+ huggingface_lib, model_name, redirected_architecture = self.architecture_dict[architecture]
222
+ if redirected_architecture is not None:
223
+ architecture = redirected_architecture
224
+ model_class = importlib.import_module(huggingface_lib).__getattribute__(architecture)
225
+ loaded_model_names_, loaded_models_ = load_model_from_huggingface_folder(file_path, [model_name], [model_class], torch_dtype, device)
226
+ loaded_model_names += loaded_model_names_
227
+ loaded_models += loaded_models_
228
+ return loaded_model_names, loaded_models
229
+
230
+
231
+
232
+ class ModelDetectorFromPatchedSingleFile:
233
+ def __init__(self, model_loader_configs=[]):
234
+ self.keys_hash_with_shape_dict = {}
235
+ for metadata in model_loader_configs:
236
+ self.add_model_metadata(*metadata)
237
+
238
+
239
+ def add_model_metadata(self, keys_hash_with_shape, model_name, model_class, extra_kwargs):
240
+ self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_name, model_class, extra_kwargs)
241
+
242
+
243
+ def match(self, file_path="", state_dict={}):
244
+ if not isinstance(file_path, str) or os.path.isdir(file_path):
245
+ return False
246
+ if len(state_dict) == 0:
247
+ state_dict = load_state_dict(file_path)
248
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
249
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
250
+ return True
251
+ return False
252
+
253
+
254
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, model_manager=None, **kwargs):
255
+ if len(state_dict) == 0:
256
+ state_dict = load_state_dict(file_path)
257
+
258
+ # Load models with strict matching
259
+ loaded_model_names, loaded_models = [], []
260
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
261
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
262
+ model_names, model_classes, extra_kwargs = self.keys_hash_with_shape_dict[keys_hash_with_shape]
263
+ loaded_model_names_, loaded_models_ = load_patch_model_from_single_file(
264
+ state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device)
265
+ loaded_model_names += loaded_model_names_
266
+ loaded_models += loaded_models_
267
+ return loaded_model_names, loaded_models
268
+
269
+
270
+
271
+ class ModelManager:
272
+ def __init__(
273
+ self,
274
+ torch_dtype=torch.float16,
275
+ device="cuda",
276
+ model_id_list: List[Preset_model_id] = [],
277
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
278
+ file_path_list: List[str] = [],
279
+ ):
280
+ self.torch_dtype = torch_dtype
281
+ self.device = device
282
+ self.model = []
283
+ self.model_path = []
284
+ self.model_name = []
285
+ downloaded_files = download_models(model_id_list, downloading_priority) if len(model_id_list) > 0 else []
286
+ self.model_detector = [
287
+ ModelDetectorFromSingleFile(model_loader_configs),
288
+ ModelDetectorFromSplitedSingleFile(model_loader_configs),
289
+ ModelDetectorFromHuggingfaceFolder(huggingface_model_loader_configs),
290
+ ModelDetectorFromPatchedSingleFile(patch_model_loader_configs),
291
+ ]
292
+ self.load_models(downloaded_files + file_path_list)
293
+
294
+
295
+ def load_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], model_resource=None):
296
+ print(f"Loading models from file: {file_path}")
297
+ if len(state_dict) == 0:
298
+ state_dict = load_state_dict(file_path)
299
+ model_names, models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, self.torch_dtype, self.device)
300
+ for model_name, model in zip(model_names, models):
301
+ self.model.append(model)
302
+ self.model_path.append(file_path)
303
+ self.model_name.append(model_name)
304
+ print(f" The following models are loaded: {model_names}.")
305
+
306
+
307
+ def load_model_from_huggingface_folder(self, file_path="", model_names=[], model_classes=[]):
308
+ print(f"Loading models from folder: {file_path}")
309
+ model_names, models = load_model_from_huggingface_folder(file_path, model_names, model_classes, self.torch_dtype, self.device)
310
+ for model_name, model in zip(model_names, models):
311
+ self.model.append(model)
312
+ self.model_path.append(file_path)
313
+ self.model_name.append(model_name)
314
+ print(f" The following models are loaded: {model_names}.")
315
+
316
+
317
+ def load_patch_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], extra_kwargs={}):
318
+ print(f"Loading patch models from file: {file_path}")
319
+ model_names, models = load_patch_model_from_single_file(
320
+ state_dict, model_names, model_classes, extra_kwargs, self, self.torch_dtype, self.device)
321
+ for model_name, model in zip(model_names, models):
322
+ self.model.append(model)
323
+ self.model_path.append(file_path)
324
+ self.model_name.append(model_name)
325
+ print(f" The following patched models are loaded: {model_names}.")
326
+
327
+
328
+ def load_lora(self, *args, **kwargs):
329
+ raise NotImplementedError("LoRA loading is omitted from the Wan-only ViBT release.")
330
+
331
+
332
+ def load_model(self, file_path, model_names=None, device=None, torch_dtype=None):
333
+ print(f"Loading models from: {file_path}")
334
+ if device is None: device = self.device
335
+ if torch_dtype is None: torch_dtype = self.torch_dtype
336
+ if isinstance(file_path, list):
337
+ state_dict = {}
338
+ for path in file_path:
339
+ state_dict.update(load_state_dict(path))
340
+ elif os.path.isfile(file_path):
341
+ state_dict = load_state_dict(file_path)
342
+ else:
343
+ state_dict = None
344
+ for model_detector in self.model_detector:
345
+ if model_detector.match(file_path, state_dict):
346
+ model_names, models = model_detector.load(
347
+ file_path, state_dict,
348
+ device=device, torch_dtype=torch_dtype,
349
+ allowed_model_names=model_names, model_manager=self
350
+ )
351
+ for model_name, model in zip(model_names, models):
352
+ self.model.append(model)
353
+ self.model_path.append(file_path)
354
+ self.model_name.append(model_name)
355
+ print(f" The following models are loaded: {model_names}.")
356
+ break
357
+ else:
358
+ print(f" We cannot detect the model type. No models are loaded.")
359
+
360
+
361
+ def load_models(self, file_path_list, model_names=None, device=None, torch_dtype=None):
362
+ for file_path in file_path_list:
363
+ self.load_model(file_path, model_names, device=device, torch_dtype=torch_dtype)
364
+
365
+
366
+ def fetch_model(self, model_name, file_path=None, require_model_path=False, index=None):
367
+ fetched_models = []
368
+ fetched_model_paths = []
369
+ for model, model_path, model_name_ in zip(self.model, self.model_path, self.model_name):
370
+ if file_path is not None and file_path != model_path:
371
+ continue
372
+ if model_name == model_name_:
373
+ fetched_models.append(model)
374
+ fetched_model_paths.append(model_path)
375
+ if len(fetched_models) == 0:
376
+ print(f"No {model_name} models available.")
377
+ return None
378
+ if len(fetched_models) == 1:
379
+ print(f"Using {model_name} from {fetched_model_paths[0]}.")
380
+ model = fetched_models[0]
381
+ path = fetched_model_paths[0]
382
+ else:
383
+ if index is None:
384
+ model = fetched_models[0]
385
+ path = fetched_model_paths[0]
386
+ print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths[0]}.")
387
+ elif isinstance(index, int):
388
+ model = fetched_models[:index]
389
+ path = fetched_model_paths[:index]
390
+ print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths[:index]}.")
391
+ else:
392
+ model = fetched_models
393
+ path = fetched_model_paths
394
+ print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths}.")
395
+ if require_model_path:
396
+ return model, path
397
+ else:
398
+ return model
399
+
400
+
401
+ def to(self, device):
402
+ for model in self.model:
403
+ model.to(device)
404
+
releases/2026-10-20-code/diffsynth/models/utils.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import torch, os
3
+ from safetensors import safe_open
4
+ from contextlib import contextmanager
5
+ import hashlib
6
+
7
+ @contextmanager
8
+ def init_weights_on_device(device = torch.device("meta"), include_buffers :bool = False):
9
+
10
+ old_register_parameter = torch.nn.Module.register_parameter
11
+ if include_buffers:
12
+ old_register_buffer = torch.nn.Module.register_buffer
13
+
14
+ def register_empty_parameter(module, name, param):
15
+ old_register_parameter(module, name, param)
16
+ if param is not None:
17
+ param_cls = type(module._parameters[name])
18
+ kwargs = module._parameters[name].__dict__
19
+ kwargs["requires_grad"] = param.requires_grad
20
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
21
+
22
+ def register_empty_buffer(module, name, buffer, persistent=True):
23
+ old_register_buffer(module, name, buffer, persistent=persistent)
24
+ if buffer is not None:
25
+ module._buffers[name] = module._buffers[name].to(device)
26
+
27
+ def patch_tensor_constructor(fn):
28
+ def wrapper(*args, **kwargs):
29
+ kwargs["device"] = device
30
+ return fn(*args, **kwargs)
31
+
32
+ return wrapper
33
+
34
+ if include_buffers:
35
+ tensor_constructors_to_patch = {
36
+ torch_function_name: getattr(torch, torch_function_name)
37
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
38
+ }
39
+ else:
40
+ tensor_constructors_to_patch = {}
41
+
42
+ try:
43
+ torch.nn.Module.register_parameter = register_empty_parameter
44
+ if include_buffers:
45
+ torch.nn.Module.register_buffer = register_empty_buffer
46
+ for torch_function_name in tensor_constructors_to_patch.keys():
47
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
48
+ yield
49
+ finally:
50
+ torch.nn.Module.register_parameter = old_register_parameter
51
+ if include_buffers:
52
+ torch.nn.Module.register_buffer = old_register_buffer
53
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
54
+ setattr(torch, torch_function_name, old_torch_function)
55
+
56
+ def load_state_dict_from_folder(file_path, torch_dtype=None):
57
+ state_dict = {}
58
+ for file_name in os.listdir(file_path):
59
+ if "." in file_name and file_name.split(".")[-1] in [
60
+ "safetensors", "bin", "ckpt", "pth", "pt"
61
+ ]:
62
+ state_dict.update(load_state_dict(os.path.join(file_path, file_name), torch_dtype=torch_dtype))
63
+ return state_dict
64
+
65
+
66
+ def load_state_dict(file_path, torch_dtype=None, device="cpu"):
67
+ if file_path.endswith(".safetensors"):
68
+ return load_state_dict_from_safetensors(file_path, torch_dtype=torch_dtype, device=device)
69
+ if file_path.endswith(".safetensors.index.json"):
70
+ with open(file_path, "r", encoding="utf-8") as f:
71
+ index = json.load(f)
72
+ shard_names = sorted(set(index["weight_map"].values()))
73
+ state_dict = {}
74
+ for shard_name in shard_names:
75
+ shard_path = os.path.join(os.path.dirname(file_path), shard_name)
76
+ state_dict.update(
77
+ load_state_dict_from_safetensors(
78
+ shard_path, torch_dtype=torch_dtype, device=device
79
+ )
80
+ )
81
+ return state_dict
82
+ else:
83
+ return load_state_dict_from_bin(file_path, torch_dtype=torch_dtype, device=device)
84
+
85
+
86
+ def load_state_dict_from_safetensors(file_path, torch_dtype=None, device="cpu"):
87
+ state_dict = {}
88
+ with safe_open(file_path, framework="pt", device=str(device)) as f:
89
+ for k in f.keys():
90
+ state_dict[k] = f.get_tensor(k)
91
+ if torch_dtype is not None:
92
+ state_dict[k] = state_dict[k].to(torch_dtype)
93
+ return state_dict
94
+
95
+
96
+ def load_state_dict_from_bin(file_path, torch_dtype=None, device="cpu"):
97
+ state_dict = torch.load(file_path, map_location=device, weights_only=True)
98
+ if torch_dtype is not None:
99
+ for i in state_dict:
100
+ if isinstance(state_dict[i], torch.Tensor):
101
+ state_dict[i] = state_dict[i].to(torch_dtype)
102
+ return state_dict
103
+
104
+
105
+ def search_for_embeddings(state_dict):
106
+ embeddings = []
107
+ for k in state_dict:
108
+ if isinstance(state_dict[k], torch.Tensor):
109
+ embeddings.append(state_dict[k])
110
+ elif isinstance(state_dict[k], dict):
111
+ embeddings += search_for_embeddings(state_dict[k])
112
+ return embeddings
113
+
114
+
115
+ def search_parameter(param, state_dict):
116
+ for name, param_ in state_dict.items():
117
+ if param.numel() == param_.numel():
118
+ if param.shape == param_.shape:
119
+ if torch.dist(param, param_) < 1e-3:
120
+ return name
121
+ else:
122
+ if torch.dist(param.flatten(), param_.flatten()) < 1e-3:
123
+ return name
124
+ return None
125
+
126
+
127
+ def build_rename_dict(source_state_dict, target_state_dict, split_qkv=False):
128
+ matched_keys = set()
129
+ with torch.no_grad():
130
+ for name in source_state_dict:
131
+ rename = search_parameter(source_state_dict[name], target_state_dict)
132
+ if rename is not None:
133
+ print(f'"{name}": "{rename}",')
134
+ matched_keys.add(rename)
135
+ elif split_qkv and len(source_state_dict[name].shape)>=1 and source_state_dict[name].shape[0]%3==0:
136
+ length = source_state_dict[name].shape[0] // 3
137
+ rename = []
138
+ for i in range(3):
139
+ rename.append(search_parameter(source_state_dict[name][i*length: i*length+length], target_state_dict))
140
+ if None not in rename:
141
+ print(f'"{name}": {rename},')
142
+ for rename_ in rename:
143
+ matched_keys.add(rename_)
144
+ for name in target_state_dict:
145
+ if name not in matched_keys:
146
+ print("Cannot find", name, target_state_dict[name].shape)
147
+
148
+
149
+ def search_for_files(folder, extensions):
150
+ files = []
151
+ if os.path.isdir(folder):
152
+ for file in sorted(os.listdir(folder)):
153
+ files += search_for_files(os.path.join(folder, file), extensions)
154
+ elif os.path.isfile(folder):
155
+ for extension in extensions:
156
+ if folder.endswith(extension):
157
+ files.append(folder)
158
+ break
159
+ return files
160
+
161
+
162
+ def convert_state_dict_keys_to_single_str(state_dict, with_shape=True):
163
+ keys = []
164
+ for key, value in state_dict.items():
165
+ if isinstance(key, str):
166
+ if isinstance(value, torch.Tensor):
167
+ if with_shape:
168
+ shape = "_".join(map(str, list(value.shape)))
169
+ keys.append(key + ":" + shape)
170
+ keys.append(key)
171
+ elif isinstance(value, dict):
172
+ keys.append(key + "|" + convert_state_dict_keys_to_single_str(value, with_shape=with_shape))
173
+ keys.sort()
174
+ keys_str = ",".join(keys)
175
+ return keys_str
176
+
177
+
178
+ def split_state_dict_with_prefix(state_dict):
179
+ keys = sorted([key for key in state_dict if isinstance(key, str)])
180
+ prefix_dict = {}
181
+ for key in keys:
182
+ prefix = key if "." not in key else key.split(".")[0]
183
+ if prefix not in prefix_dict:
184
+ prefix_dict[prefix] = []
185
+ prefix_dict[prefix].append(key)
186
+ state_dicts = []
187
+ for prefix, keys in prefix_dict.items():
188
+ sub_state_dict = {key: state_dict[key] for key in keys}
189
+ state_dicts.append(sub_state_dict)
190
+ return state_dicts
191
+
192
+
193
+ def hash_state_dict_keys(state_dict, with_shape=True):
194
+ keys_str = convert_state_dict_keys_to_single_str(state_dict, with_shape=with_shape)
195
+ keys_str = keys_str.encode(encoding="UTF-8")
196
+ return hashlib.md5(keys_str).hexdigest()
releases/2026-10-20-code/diffsynth/models/wan_video_animate_adapter.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+ import math
5
+ from typing import Tuple, Optional, List
6
+ from einops import rearrange
7
+
8
+
9
+
10
+ MEMORY_LAYOUT = {
11
+ "flash": (
12
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
13
+ lambda x: x,
14
+ ),
15
+ "torch": (
16
+ lambda x: x.transpose(1, 2),
17
+ lambda x: x.transpose(1, 2),
18
+ ),
19
+ "vanilla": (
20
+ lambda x: x.transpose(1, 2),
21
+ lambda x: x.transpose(1, 2),
22
+ ),
23
+ }
24
+
25
+
26
+ def attention(
27
+ q,
28
+ k,
29
+ v,
30
+ mode="torch",
31
+ drop_rate=0,
32
+ attn_mask=None,
33
+ causal=False,
34
+ max_seqlen_q=None,
35
+ batch_size=1,
36
+ ):
37
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
38
+
39
+ if mode == "torch":
40
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
41
+ attn_mask = attn_mask.to(q.dtype)
42
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal)
43
+
44
+ x = post_attn_layout(x)
45
+ b, s, a, d = x.shape
46
+ out = x.reshape(b, s, -1)
47
+ return out
48
+
49
+
50
+ class CausalConv1d(nn.Module):
51
+
52
+ def __init__(self, chan_in, chan_out, kernel_size=3, stride=1, dilation=1, pad_mode="replicate", **kwargs):
53
+ super().__init__()
54
+
55
+ self.pad_mode = pad_mode
56
+ padding = (kernel_size - 1, 0) # T
57
+ self.time_causal_padding = padding
58
+
59
+ self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)
60
+
61
+ def forward(self, x):
62
+ x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
63
+ return self.conv(x)
64
+
65
+
66
+
67
+ class FaceEncoder(nn.Module):
68
+ def __init__(self, in_dim: int, hidden_dim: int, num_heads=int, dtype=None, device=None):
69
+ factory_kwargs = {"dtype": dtype, "device": device}
70
+ super().__init__()
71
+
72
+ self.num_heads = num_heads
73
+ self.conv1_local = CausalConv1d(in_dim, 1024 * num_heads, 3, stride=1)
74
+ self.norm1 = nn.LayerNorm(hidden_dim // 8, elementwise_affine=False, eps=1e-6, **factory_kwargs)
75
+ self.act = nn.SiLU()
76
+ self.conv2 = CausalConv1d(1024, 1024, 3, stride=2)
77
+ self.conv3 = CausalConv1d(1024, 1024, 3, stride=2)
78
+
79
+ self.out_proj = nn.Linear(1024, hidden_dim)
80
+ self.norm1 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
81
+
82
+ self.norm2 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
83
+
84
+ self.norm3 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
85
+
86
+ self.padding_tokens = nn.Parameter(torch.zeros(1, 1, 1, hidden_dim))
87
+
88
+ def forward(self, x):
89
+
90
+ x = rearrange(x, "b t c -> b c t")
91
+ b, c, t = x.shape
92
+
93
+ x = self.conv1_local(x)
94
+ x = rearrange(x, "b (n c) t -> (b n) t c", n=self.num_heads)
95
+
96
+ x = self.norm1(x)
97
+ x = self.act(x)
98
+ x = rearrange(x, "b t c -> b c t")
99
+ x = self.conv2(x)
100
+ x = rearrange(x, "b c t -> b t c")
101
+ x = self.norm2(x)
102
+ x = self.act(x)
103
+ x = rearrange(x, "b t c -> b c t")
104
+ x = self.conv3(x)
105
+ x = rearrange(x, "b c t -> b t c")
106
+ x = self.norm3(x)
107
+ x = self.act(x)
108
+ x = self.out_proj(x)
109
+ x = rearrange(x, "(b n) t c -> b t n c", b=b)
110
+ padding = self.padding_tokens.repeat(b, x.shape[1], 1, 1)
111
+ x = torch.cat([x, padding], dim=-2)
112
+ x_local = x.clone()
113
+
114
+ return x_local
115
+
116
+
117
+
118
+ class RMSNorm(nn.Module):
119
+ def __init__(
120
+ self,
121
+ dim: int,
122
+ elementwise_affine=True,
123
+ eps: float = 1e-6,
124
+ device=None,
125
+ dtype=None,
126
+ ):
127
+ """
128
+ Initialize the RMSNorm normalization layer.
129
+
130
+ Args:
131
+ dim (int): The dimension of the input tensor.
132
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
133
+
134
+ Attributes:
135
+ eps (float): A small value added to the denominator for numerical stability.
136
+ weight (nn.Parameter): Learnable scaling parameter.
137
+
138
+ """
139
+ factory_kwargs = {"device": device, "dtype": dtype}
140
+ super().__init__()
141
+ self.eps = eps
142
+ if elementwise_affine:
143
+ self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
144
+
145
+ def _norm(self, x):
146
+ """
147
+ Apply the RMSNorm normalization to the input tensor.
148
+
149
+ Args:
150
+ x (torch.Tensor): The input tensor.
151
+
152
+ Returns:
153
+ torch.Tensor: The normalized tensor.
154
+
155
+ """
156
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
157
+
158
+ def forward(self, x):
159
+ """
160
+ Forward pass through the RMSNorm layer.
161
+
162
+ Args:
163
+ x (torch.Tensor): The input tensor.
164
+
165
+ Returns:
166
+ torch.Tensor: The output tensor after applying RMSNorm.
167
+
168
+ """
169
+ output = self._norm(x.float()).type_as(x)
170
+ if hasattr(self, "weight"):
171
+ output = output * self.weight
172
+ return output
173
+
174
+
175
+ def get_norm_layer(norm_layer):
176
+ """
177
+ Get the normalization layer.
178
+
179
+ Args:
180
+ norm_layer (str): The type of normalization layer.
181
+
182
+ Returns:
183
+ norm_layer (nn.Module): The normalization layer.
184
+ """
185
+ if norm_layer == "layer":
186
+ return nn.LayerNorm
187
+ elif norm_layer == "rms":
188
+ return RMSNorm
189
+ else:
190
+ raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")
191
+
192
+
193
+ class FaceAdapter(nn.Module):
194
+ def __init__(
195
+ self,
196
+ hidden_dim: int,
197
+ heads_num: int,
198
+ qk_norm: bool = True,
199
+ qk_norm_type: str = "rms",
200
+ num_adapter_layers: int = 1,
201
+ dtype=None,
202
+ device=None,
203
+ ):
204
+
205
+ factory_kwargs = {"dtype": dtype, "device": device}
206
+ super().__init__()
207
+ self.hidden_size = hidden_dim
208
+ self.heads_num = heads_num
209
+ self.fuser_blocks = nn.ModuleList(
210
+ [
211
+ FaceBlock(
212
+ self.hidden_size,
213
+ self.heads_num,
214
+ qk_norm=qk_norm,
215
+ qk_norm_type=qk_norm_type,
216
+ **factory_kwargs,
217
+ )
218
+ for _ in range(num_adapter_layers)
219
+ ]
220
+ )
221
+
222
+ def forward(
223
+ self,
224
+ x: torch.Tensor,
225
+ motion_embed: torch.Tensor,
226
+ idx: int,
227
+ freqs_cis_q: Tuple[torch.Tensor, torch.Tensor] = None,
228
+ freqs_cis_k: Tuple[torch.Tensor, torch.Tensor] = None,
229
+ ) -> torch.Tensor:
230
+
231
+ return self.fuser_blocks[idx](x, motion_embed, freqs_cis_q, freqs_cis_k)
232
+
233
+
234
+
235
+ class FaceBlock(nn.Module):
236
+ def __init__(
237
+ self,
238
+ hidden_size: int,
239
+ heads_num: int,
240
+ qk_norm: bool = True,
241
+ qk_norm_type: str = "rms",
242
+ qk_scale: float = None,
243
+ dtype: Optional[torch.dtype] = None,
244
+ device: Optional[torch.device] = None,
245
+ ):
246
+ factory_kwargs = {"device": device, "dtype": dtype}
247
+ super().__init__()
248
+
249
+ self.deterministic = False
250
+ self.hidden_size = hidden_size
251
+ self.heads_num = heads_num
252
+ head_dim = hidden_size // heads_num
253
+ self.scale = qk_scale or head_dim**-0.5
254
+
255
+ self.linear1_kv = nn.Linear(hidden_size, hidden_size * 2, **factory_kwargs)
256
+ self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
257
+
258
+ self.linear2 = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
259
+
260
+ qk_norm_layer = get_norm_layer(qk_norm_type)
261
+ self.q_norm = (
262
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity()
263
+ )
264
+ self.k_norm = (
265
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity()
266
+ )
267
+
268
+ self.pre_norm_feat = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs)
269
+
270
+ self.pre_norm_motion = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs)
271
+
272
+ def forward(
273
+ self,
274
+ x: torch.Tensor,
275
+ motion_vec: torch.Tensor,
276
+ motion_mask: Optional[torch.Tensor] = None,
277
+ use_context_parallel=False,
278
+ ) -> torch.Tensor:
279
+
280
+ B, T, N, C = motion_vec.shape
281
+ T_comp = T
282
+
283
+ x_motion = self.pre_norm_motion(motion_vec)
284
+ x_feat = self.pre_norm_feat(x)
285
+
286
+ kv = self.linear1_kv(x_motion)
287
+ q = self.linear1_q(x_feat)
288
+
289
+ k, v = rearrange(kv, "B L N (K H D) -> K B L N H D", K=2, H=self.heads_num)
290
+ q = rearrange(q, "B S (H D) -> B S H D", H=self.heads_num)
291
+
292
+ # Apply QK-Norm if needed.
293
+ q = self.q_norm(q).to(v)
294
+ k = self.k_norm(k).to(v)
295
+
296
+ k = rearrange(k, "B L N H D -> (B L) H N D")
297
+ v = rearrange(v, "B L N H D -> (B L) H N D")
298
+
299
+ q = rearrange(q, "B (L S) H D -> (B L) H S D", L=T_comp)
300
+ # Compute attention.
301
+ attn = F.scaled_dot_product_attention(q, k, v)
302
+
303
+ attn = rearrange(attn, "(B L) H S D -> B (L S) (H D)", L=T_comp)
304
+
305
+ output = self.linear2(attn)
306
+
307
+ if motion_mask is not None:
308
+ output = output * rearrange(motion_mask, "B T H W -> B (T H W)").unsqueeze(-1)
309
+
310
+ return output
311
+
312
+
313
+
314
+ def custom_qr(input_tensor):
315
+ original_dtype = input_tensor.dtype
316
+ if original_dtype == torch.bfloat16:
317
+ q, r = torch.linalg.qr(input_tensor.to(torch.float32))
318
+ return q.to(original_dtype), r.to(original_dtype)
319
+ return torch.linalg.qr(input_tensor)
320
+
321
+ def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):
322
+ return F.leaky_relu(input + bias, negative_slope) * scale
323
+
324
+
325
+ def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1):
326
+ _, minor, in_h, in_w = input.shape
327
+ kernel_h, kernel_w = kernel.shape
328
+
329
+ out = input.view(-1, minor, in_h, 1, in_w, 1)
330
+ out = F.pad(out, [0, up_x - 1, 0, 0, 0, up_y - 1, 0, 0])
331
+ out = out.view(-1, minor, in_h * up_y, in_w * up_x)
332
+
333
+ out = F.pad(out, [max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)])
334
+ out = out[:, :, max(-pad_y0, 0): out.shape[2] - max(-pad_y1, 0),
335
+ max(-pad_x0, 0): out.shape[3] - max(-pad_x1, 0), ]
336
+
337
+ out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1])
338
+ w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
339
+ out = F.conv2d(out, w)
340
+ out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
341
+ in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, )
342
+ return out[:, :, ::down_y, ::down_x]
343
+
344
+
345
+ def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
346
+ return upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1])
347
+
348
+
349
+ def make_kernel(k):
350
+ k = torch.tensor(k, dtype=torch.float32)
351
+ if k.ndim == 1:
352
+ k = k[None, :] * k[:, None]
353
+ k /= k.sum()
354
+ return k
355
+
356
+
357
+ class FusedLeakyReLU(nn.Module):
358
+ def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
359
+ super().__init__()
360
+ self.bias = nn.Parameter(torch.zeros(1, channel, 1, 1))
361
+ self.negative_slope = negative_slope
362
+ self.scale = scale
363
+
364
+ def forward(self, input):
365
+ out = fused_leaky_relu(input, self.bias, self.negative_slope, self.scale)
366
+ return out
367
+
368
+
369
+ class Blur(nn.Module):
370
+ def __init__(self, kernel, pad, upsample_factor=1):
371
+ super().__init__()
372
+
373
+ kernel = make_kernel(kernel)
374
+
375
+ if upsample_factor > 1:
376
+ kernel = kernel * (upsample_factor ** 2)
377
+
378
+ self.register_buffer('kernel', kernel)
379
+
380
+ self.pad = pad
381
+
382
+ def forward(self, input):
383
+ return upfirdn2d(input, self.kernel, pad=self.pad)
384
+
385
+
386
+ class ScaledLeakyReLU(nn.Module):
387
+ def __init__(self, negative_slope=0.2):
388
+ super().__init__()
389
+
390
+ self.negative_slope = negative_slope
391
+
392
+ def forward(self, input):
393
+ return F.leaky_relu(input, negative_slope=self.negative_slope)
394
+
395
+
396
+ class EqualConv2d(nn.Module):
397
+ def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True):
398
+ super().__init__()
399
+
400
+ self.weight = nn.Parameter(torch.randn(out_channel, in_channel, kernel_size, kernel_size))
401
+ self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
402
+
403
+ self.stride = stride
404
+ self.padding = padding
405
+
406
+ if bias:
407
+ self.bias = nn.Parameter(torch.zeros(out_channel))
408
+ else:
409
+ self.bias = None
410
+
411
+ def forward(self, input):
412
+
413
+ return F.conv2d(input, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding)
414
+
415
+ def __repr__(self):
416
+ return (
417
+ f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},'
418
+ f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
419
+ )
420
+
421
+
422
+ class EqualLinear(nn.Module):
423
+ def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None):
424
+ super().__init__()
425
+
426
+ self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
427
+
428
+ if bias:
429
+ self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
430
+ else:
431
+ self.bias = None
432
+
433
+ self.activation = activation
434
+
435
+ self.scale = (1 / math.sqrt(in_dim)) * lr_mul
436
+ self.lr_mul = lr_mul
437
+
438
+ def forward(self, input):
439
+
440
+ if self.activation:
441
+ out = F.linear(input, self.weight * self.scale)
442
+ out = fused_leaky_relu(out, self.bias * self.lr_mul)
443
+ else:
444
+ out = F.linear(input, self.weight * self.scale, bias=self.bias * self.lr_mul)
445
+
446
+ return out
447
+
448
+ def __repr__(self):
449
+ return (f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})')
450
+
451
+
452
+ class ConvLayer(nn.Sequential):
453
+ def __init__(
454
+ self,
455
+ in_channel,
456
+ out_channel,
457
+ kernel_size,
458
+ downsample=False,
459
+ blur_kernel=[1, 3, 3, 1],
460
+ bias=True,
461
+ activate=True,
462
+ ):
463
+ layers = []
464
+
465
+ if downsample:
466
+ factor = 2
467
+ p = (len(blur_kernel) - factor) + (kernel_size - 1)
468
+ pad0 = (p + 1) // 2
469
+ pad1 = p // 2
470
+
471
+ layers.append(Blur(blur_kernel, pad=(pad0, pad1)))
472
+
473
+ stride = 2
474
+ self.padding = 0
475
+
476
+ else:
477
+ stride = 1
478
+ self.padding = kernel_size // 2
479
+
480
+ layers.append(EqualConv2d(in_channel, out_channel, kernel_size, padding=self.padding, stride=stride,
481
+ bias=bias and not activate))
482
+
483
+ if activate:
484
+ if bias:
485
+ layers.append(FusedLeakyReLU(out_channel))
486
+ else:
487
+ layers.append(ScaledLeakyReLU(0.2))
488
+
489
+ super().__init__(*layers)
490
+
491
+
492
+ class ResBlock(nn.Module):
493
+ def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]):
494
+ super().__init__()
495
+
496
+ self.conv1 = ConvLayer(in_channel, in_channel, 3)
497
+ self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True)
498
+
499
+ self.skip = ConvLayer(in_channel, out_channel, 1, downsample=True, activate=False, bias=False)
500
+
501
+ def forward(self, input):
502
+ out = self.conv1(input)
503
+ out = self.conv2(out)
504
+
505
+ skip = self.skip(input)
506
+ out = (out + skip) / math.sqrt(2)
507
+
508
+ return out
509
+
510
+
511
+ class EncoderApp(nn.Module):
512
+ def __init__(self, size, w_dim=512):
513
+ super(EncoderApp, self).__init__()
514
+
515
+ channels = {
516
+ 4: 512,
517
+ 8: 512,
518
+ 16: 512,
519
+ 32: 512,
520
+ 64: 256,
521
+ 128: 128,
522
+ 256: 64,
523
+ 512: 32,
524
+ 1024: 16
525
+ }
526
+
527
+ self.w_dim = w_dim
528
+ log_size = int(math.log(size, 2))
529
+
530
+ self.convs = nn.ModuleList()
531
+ self.convs.append(ConvLayer(3, channels[size], 1))
532
+
533
+ in_channel = channels[size]
534
+ for i in range(log_size, 2, -1):
535
+ out_channel = channels[2 ** (i - 1)]
536
+ self.convs.append(ResBlock(in_channel, out_channel))
537
+ in_channel = out_channel
538
+
539
+ self.convs.append(EqualConv2d(in_channel, self.w_dim, 4, padding=0, bias=False))
540
+
541
+ def forward(self, x):
542
+
543
+ res = []
544
+ h = x
545
+ for conv in self.convs:
546
+ h = conv(h)
547
+ res.append(h)
548
+
549
+ return res[-1].squeeze(-1).squeeze(-1), res[::-1][2:]
550
+
551
+
552
+ class Encoder(nn.Module):
553
+ def __init__(self, size, dim=512, dim_motion=20):
554
+ super(Encoder, self).__init__()
555
+
556
+ # appearance netmork
557
+ self.net_app = EncoderApp(size, dim)
558
+
559
+ # motion network
560
+ fc = [EqualLinear(dim, dim)]
561
+ for i in range(3):
562
+ fc.append(EqualLinear(dim, dim))
563
+
564
+ fc.append(EqualLinear(dim, dim_motion))
565
+ self.fc = nn.Sequential(*fc)
566
+
567
+ def enc_app(self, x):
568
+ h_source = self.net_app(x)
569
+ return h_source
570
+
571
+ def enc_motion(self, x):
572
+ h, _ = self.net_app(x)
573
+ h_motion = self.fc(h)
574
+ return h_motion
575
+
576
+
577
+ class Direction(nn.Module):
578
+ def __init__(self, motion_dim):
579
+ super(Direction, self).__init__()
580
+ self.weight = nn.Parameter(torch.randn(512, motion_dim))
581
+
582
+ def forward(self, input):
583
+
584
+ weight = self.weight + 1e-8
585
+ Q, R = custom_qr(weight)
586
+ if input is None:
587
+ return Q
588
+ else:
589
+ input_diag = torch.diag_embed(input) # alpha, diagonal matrix
590
+ out = torch.matmul(input_diag, Q.T)
591
+ out = torch.sum(out, dim=1)
592
+ return out
593
+
594
+
595
+ class Synthesis(nn.Module):
596
+ def __init__(self, motion_dim):
597
+ super(Synthesis, self).__init__()
598
+ self.direction = Direction(motion_dim)
599
+
600
+
601
+ class Generator(nn.Module):
602
+ def __init__(self, size, style_dim=512, motion_dim=20):
603
+ super().__init__()
604
+
605
+ self.enc = Encoder(size, style_dim, motion_dim)
606
+ self.dec = Synthesis(motion_dim)
607
+
608
+ def get_motion(self, img):
609
+ #motion_feat = self.enc.enc_motion(img)
610
+ motion_feat = torch.utils.checkpoint.checkpoint((self.enc.enc_motion), img, use_reentrant=True)
611
+ motion = self.dec.direction(motion_feat)
612
+ return motion
613
+
614
+
615
+ class WanAnimateAdapter(torch.nn.Module):
616
+ def __init__(self):
617
+ super().__init__()
618
+ self.pose_patch_embedding = torch.nn.Conv3d(16, 5120, kernel_size=(1, 2, 2), stride=(1, 2, 2))
619
+ self.motion_encoder = Generator(size=512, style_dim=512, motion_dim=20)
620
+ self.face_adapter = FaceAdapter(heads_num=40, hidden_dim=5120, num_adapter_layers=40 // 5)
621
+ self.face_encoder = FaceEncoder(in_dim=512, hidden_dim=5120, num_heads=4)
622
+
623
+ def after_patch_embedding(self, x: List[torch.Tensor], pose_latents, face_pixel_values):
624
+ pose_latents = self.pose_patch_embedding(pose_latents)
625
+ x[:, :, 1:] += pose_latents
626
+
627
+ b,c,T,h,w = face_pixel_values.shape
628
+ face_pixel_values = rearrange(face_pixel_values, "b c t h w -> (b t) c h w")
629
+
630
+ encode_bs = 8
631
+ face_pixel_values_tmp = []
632
+ for i in range(math.ceil(face_pixel_values.shape[0]/encode_bs)):
633
+ face_pixel_values_tmp.append(self.motion_encoder.get_motion(face_pixel_values[i*encode_bs:(i+1)*encode_bs]))
634
+
635
+ motion_vec = torch.cat(face_pixel_values_tmp)
636
+
637
+ motion_vec = rearrange(motion_vec, "(b t) c -> b t c", t=T)
638
+ motion_vec = self.face_encoder(motion_vec)
639
+
640
+ B, L, H, C = motion_vec.shape
641
+ pad_face = torch.zeros(B, 1, H, C).type_as(motion_vec)
642
+ motion_vec = torch.cat([pad_face, motion_vec], dim=1)
643
+ return x, motion_vec
644
+
645
+ def after_transformer_block(self, block_idx, x, motion_vec, motion_masks=None):
646
+ if block_idx % 5 == 0:
647
+ adapter_args = [x, motion_vec, motion_masks, False]
648
+ residual_out = self.face_adapter.fuser_blocks[block_idx // 5](*adapter_args)
649
+ x = residual_out + x
650
+ return x
651
+
652
+ @staticmethod
653
+ def state_dict_converter():
654
+ return WanAnimateAdapterStateDictConverter()
655
+
656
+
657
+ class WanAnimateAdapterStateDictConverter:
658
+ def __init__(self):
659
+ pass
660
+
661
+ def from_diffusers(self, state_dict):
662
+ return state_dict
663
+
664
+ def from_civitai(self, state_dict):
665
+ state_dict_ = {}
666
+ for name, param in state_dict.items():
667
+ if name.startswith("pose_patch_embedding.") or name.startswith("face_adapter") or name.startswith("face_encoder") or name.startswith("motion_encoder"):
668
+ state_dict_[name] = param
669
+ return state_dict_
670
+
releases/2026-10-20-code/diffsynth/models/wan_video_camera_controller.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from einops import rearrange
5
+ import os
6
+ from typing_extensions import Literal
7
+
8
+ class SimpleAdapter(nn.Module):
9
+ def __init__(self, in_dim, out_dim, kernel_size, stride, num_residual_blocks=1):
10
+ super(SimpleAdapter, self).__init__()
11
+
12
+ # Pixel Unshuffle: reduce spatial dimensions by a factor of 8
13
+ self.pixel_unshuffle = nn.PixelUnshuffle(downscale_factor=8)
14
+
15
+ # Convolution: reduce spatial dimensions by a factor
16
+ # of 2 (without overlap)
17
+ self.conv = nn.Conv2d(in_dim * 64, out_dim, kernel_size=kernel_size, stride=stride, padding=0)
18
+
19
+ # Residual blocks for feature extraction
20
+ self.residual_blocks = nn.Sequential(
21
+ *[ResidualBlock(out_dim) for _ in range(num_residual_blocks)]
22
+ )
23
+
24
+ def forward(self, x):
25
+ # Reshape to merge the frame dimension into batch
26
+ bs, c, f, h, w = x.size()
27
+ x = x.permute(0, 2, 1, 3, 4).contiguous().view(bs * f, c, h, w)
28
+
29
+ # Pixel Unshuffle operation
30
+ x_unshuffled = self.pixel_unshuffle(x)
31
+
32
+ # Convolution operation
33
+ x_conv = self.conv(x_unshuffled)
34
+
35
+ # Feature extraction with residual blocks
36
+ out = self.residual_blocks(x_conv)
37
+
38
+ # Reshape to restore original bf dimension
39
+ out = out.view(bs, f, out.size(1), out.size(2), out.size(3))
40
+
41
+ # Permute dimensions to reorder (if needed), e.g., swap channels and feature frames
42
+ out = out.permute(0, 2, 1, 3, 4)
43
+
44
+ return out
45
+
46
+ def process_camera_coordinates(
47
+ self,
48
+ direction: Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown"],
49
+ length: int,
50
+ height: int,
51
+ width: int,
52
+ speed: float = 1/54,
53
+ origin=(0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
54
+ ):
55
+ if origin is None:
56
+ origin = (0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
57
+ coordinates = generate_camera_coordinates(direction, length, speed, origin)
58
+ plucker_embedding = process_pose_file(coordinates, width, height)
59
+ return plucker_embedding
60
+
61
+
62
+
63
+ class ResidualBlock(nn.Module):
64
+ def __init__(self, dim):
65
+ super(ResidualBlock, self).__init__()
66
+ self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
67
+ self.relu = nn.ReLU(inplace=True)
68
+ self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
69
+
70
+ def forward(self, x):
71
+ residual = x
72
+ out = self.relu(self.conv1(x))
73
+ out = self.conv2(out)
74
+ out += residual
75
+ return out
76
+
77
+ class Camera(object):
78
+ """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
79
+ """
80
+ def __init__(self, entry):
81
+ fx, fy, cx, cy = entry[1:5]
82
+ self.fx = fx
83
+ self.fy = fy
84
+ self.cx = cx
85
+ self.cy = cy
86
+ w2c_mat = np.array(entry[7:]).reshape(3, 4)
87
+ w2c_mat_4x4 = np.eye(4)
88
+ w2c_mat_4x4[:3, :] = w2c_mat
89
+ self.w2c_mat = w2c_mat_4x4
90
+ self.c2w_mat = np.linalg.inv(w2c_mat_4x4)
91
+
92
+ def get_relative_pose(cam_params):
93
+ """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
94
+ """
95
+ abs_w2cs = [cam_param.w2c_mat for cam_param in cam_params]
96
+ abs_c2ws = [cam_param.c2w_mat for cam_param in cam_params]
97
+ cam_to_origin = 0
98
+ target_cam_c2w = np.array([
99
+ [1, 0, 0, 0],
100
+ [0, 1, 0, -cam_to_origin],
101
+ [0, 0, 1, 0],
102
+ [0, 0, 0, 1]
103
+ ])
104
+ abs2rel = target_cam_c2w @ abs_w2cs[0]
105
+ ret_poses = [target_cam_c2w, ] + [abs2rel @ abs_c2w for abs_c2w in abs_c2ws[1:]]
106
+ ret_poses = np.array(ret_poses, dtype=np.float32)
107
+ return ret_poses
108
+
109
+ def custom_meshgrid(*args):
110
+ # torch>=2.0.0 only
111
+ return torch.meshgrid(*args, indexing='ij')
112
+
113
+
114
+ def ray_condition(K, c2w, H, W, device):
115
+ """Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py
116
+ """
117
+ # c2w: B, V, 4, 4
118
+ # K: B, V, 4
119
+
120
+ B = K.shape[0]
121
+
122
+ j, i = custom_meshgrid(
123
+ torch.linspace(0, H - 1, H, device=device, dtype=c2w.dtype),
124
+ torch.linspace(0, W - 1, W, device=device, dtype=c2w.dtype),
125
+ )
126
+ i = i.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]
127
+ j = j.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]
128
+
129
+ fx, fy, cx, cy = K.chunk(4, dim=-1) # B,V, 1
130
+
131
+ zs = torch.ones_like(i) # [B, HxW]
132
+ xs = (i - cx) / fx * zs
133
+ ys = (j - cy) / fy * zs
134
+ zs = zs.expand_as(ys)
135
+
136
+ directions = torch.stack((xs, ys, zs), dim=-1) # B, V, HW, 3
137
+ directions = directions / directions.norm(dim=-1, keepdim=True) # B, V, HW, 3
138
+
139
+ rays_d = directions @ c2w[..., :3, :3].transpose(-1, -2) # B, V, 3, HW
140
+ rays_o = c2w[..., :3, 3] # B, V, 3
141
+ rays_o = rays_o[:, :, None].expand_as(rays_d) # B, V, 3, HW
142
+ # c2w @ dirctions
143
+ rays_dxo = torch.linalg.cross(rays_o, rays_d)
144
+ plucker = torch.cat([rays_dxo, rays_d], dim=-1)
145
+ plucker = plucker.reshape(B, c2w.shape[1], H, W, 6) # B, V, H, W, 6
146
+ # plucker = plucker.permute(0, 1, 4, 2, 3)
147
+ return plucker
148
+
149
+
150
+ def process_pose_file(cam_params, width=672, height=384, original_pose_width=1280, original_pose_height=720, device='cpu', return_poses=False):
151
+ if return_poses:
152
+ return cam_params
153
+ else:
154
+ cam_params = [Camera(cam_param) for cam_param in cam_params]
155
+
156
+ sample_wh_ratio = width / height
157
+ pose_wh_ratio = original_pose_width / original_pose_height # Assuming placeholder ratios, change as needed
158
+
159
+ if pose_wh_ratio > sample_wh_ratio:
160
+ resized_ori_w = height * pose_wh_ratio
161
+ for cam_param in cam_params:
162
+ cam_param.fx = resized_ori_w * cam_param.fx / width
163
+ else:
164
+ resized_ori_h = width / pose_wh_ratio
165
+ for cam_param in cam_params:
166
+ cam_param.fy = resized_ori_h * cam_param.fy / height
167
+
168
+ intrinsic = np.asarray([[cam_param.fx * width,
169
+ cam_param.fy * height,
170
+ cam_param.cx * width,
171
+ cam_param.cy * height]
172
+ for cam_param in cam_params], dtype=np.float32)
173
+
174
+ K = torch.as_tensor(intrinsic)[None] # [1, 1, 4]
175
+ c2ws = get_relative_pose(cam_params) # Assuming this function is defined elsewhere
176
+ c2ws = torch.as_tensor(c2ws)[None] # [1, n_frame, 4, 4]
177
+ plucker_embedding = ray_condition(K, c2ws, height, width, device=device)[0].permute(0, 3, 1, 2).contiguous() # V, 6, H, W
178
+ plucker_embedding = plucker_embedding[None]
179
+ plucker_embedding = rearrange(plucker_embedding, "b f c h w -> b f h w c")[0]
180
+ return plucker_embedding
181
+
182
+
183
+
184
+ def generate_camera_coordinates(
185
+ direction: Literal["Left", "Right", "Up", "Down", "LeftUp", "LeftDown", "RightUp", "RightDown", "In", "Out"],
186
+ length: int,
187
+ speed: float = 1/54,
188
+ origin=(0, 0.532139961, 0.946026558, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0)
189
+ ):
190
+ coordinates = [list(origin)]
191
+ while len(coordinates) < length:
192
+ coor = coordinates[-1].copy()
193
+ if "Left" in direction:
194
+ coor[9] += speed
195
+ if "Right" in direction:
196
+ coor[9] -= speed
197
+ if "Up" in direction:
198
+ coor[13] += speed
199
+ if "Down" in direction:
200
+ coor[13] -= speed
201
+ if "In" in direction:
202
+ coor[18] -= speed
203
+ if "Out" in direction:
204
+ coor[18] += speed
205
+ coordinates.append(coor)
206
+ return coordinates
releases/2026-10-20-code/diffsynth/models/wan_video_dit.py ADDED
@@ -0,0 +1,834 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import math
5
+ from typing import Tuple, Optional
6
+ from einops import rearrange
7
+ from .utils import hash_state_dict_keys
8
+ from .wan_video_camera_controller import SimpleAdapter
9
+ from diffsynth.pipelines.attention_masks import TokenPrefixAttentionSpec, ReferenceSequenceAttentionSpec, CausalReferenceSequenceAttentionSpec
10
+ try:
11
+ import torch_npu
12
+ except ModuleNotFoundError:
13
+ torch_npu = None
14
+ try:
15
+ import flash_attn_interface
16
+ FLASH_ATTN_3_AVAILABLE = True
17
+ except ModuleNotFoundError:
18
+ FLASH_ATTN_3_AVAILABLE = False
19
+
20
+ try:
21
+ import flash_attn
22
+ FLASH_ATTN_2_AVAILABLE = True
23
+ except ModuleNotFoundError:
24
+ FLASH_ATTN_2_AVAILABLE = False
25
+
26
+ try:
27
+ from sageattention import sageattn
28
+ SAGE_ATTN_AVAILABLE = True
29
+ except ModuleNotFoundError:
30
+ SAGE_ATTN_AVAILABLE = False
31
+
32
+
33
+ def flash_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, num_heads: int, compatibility_mode=False):
34
+ if compatibility_mode:
35
+ q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
36
+ k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
37
+ v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
38
+ x = F.scaled_dot_product_attention(q, k, v)
39
+ x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
40
+ elif FLASH_ATTN_3_AVAILABLE:
41
+ q = rearrange(q, "b s (n d) -> b s n d", n=num_heads)
42
+ k = rearrange(k, "b s (n d) -> b s n d", n=num_heads)
43
+ v = rearrange(v, "b s (n d) -> b s n d", n=num_heads)
44
+ x = flash_attn_interface.flash_attn_func(q, k, v)
45
+ if isinstance(x,tuple):
46
+ x = x[0]
47
+ x = rearrange(x, "b s n d -> b s (n d)", n=num_heads)
48
+ elif FLASH_ATTN_2_AVAILABLE:
49
+ q = rearrange(q, "b s (n d) -> b s n d", n=num_heads)
50
+ k = rearrange(k, "b s (n d) -> b s n d", n=num_heads)
51
+ v = rearrange(v, "b s (n d) -> b s n d", n=num_heads)
52
+ x = flash_attn.flash_attn_func(q, k, v)
53
+ x = rearrange(x, "b s n d -> b s (n d)", n=num_heads)
54
+ elif SAGE_ATTN_AVAILABLE:
55
+ q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
56
+ k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
57
+ v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
58
+ x = sageattn(q, k, v)
59
+ x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
60
+ else:
61
+ q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
62
+ k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
63
+ v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
64
+ x = F.scaled_dot_product_attention(q, k, v)
65
+ x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
66
+ return x
67
+
68
+
69
+ def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
70
+ return (x * (1 + scale) + shift)
71
+
72
+
73
+ def sinusoidal_embedding_1d(dim, position):
74
+ sinusoid = torch.outer(position.type(torch.float64), torch.pow(
75
+ 10000, -torch.arange(dim//2, dtype=torch.float64, device=position.device).div(dim//2)))
76
+ x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
77
+ return x.to(position.dtype)
78
+
79
+
80
+ def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
81
+ # 3d rope precompute
82
+ f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
83
+ h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
84
+ w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
85
+ return f_freqs_cis, h_freqs_cis, w_freqs_cis
86
+
87
+
88
+ def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
89
+ # 1d rope precompute
90
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)
91
+ [: (dim // 2)].double() / dim))
92
+ freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
93
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
94
+ return freqs_cis.to(torch.complex64)
95
+
96
+
97
+ def rope_apply(x, freqs, num_heads):
98
+ x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
99
+ rope_dtype = torch.float32 if x.device.type == "npu" else torch.float64
100
+ x_out = torch.view_as_complex(x.to(rope_dtype).reshape(
101
+ x.shape[0], x.shape[1], x.shape[2], -1, 2))
102
+ if freqs.device != x.device:
103
+ freqs = freqs.to(device=x.device)
104
+ x_out = torch.view_as_real(x_out * freqs).flatten(2)
105
+ return x_out.to(x.dtype)
106
+
107
+
108
+ class RMSNorm(nn.Module):
109
+ def __init__(self, dim, eps=1e-5):
110
+ super().__init__()
111
+ self.eps = eps
112
+ self.weight = nn.Parameter(torch.ones(dim))
113
+
114
+ def norm(self, x):
115
+ return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
116
+
117
+ def forward(self, x):
118
+ if x.device.type == "npu" and torch_npu is not None:
119
+ out = torch_npu.npu_rms_norm(x, self.weight, epsilon=self.eps)
120
+ return out[0] if isinstance(out, tuple) else out
121
+ dtype = x.dtype
122
+ return self.norm(x.float()).to(dtype) * self.weight
123
+
124
+
125
+ class AttentionModule(nn.Module):
126
+ def __init__(self, num_heads):
127
+ super().__init__()
128
+ self.num_heads = num_heads
129
+
130
+ def forward(self, q, k, v, attn_mask=None):
131
+ if isinstance(attn_mask, CausalReferenceSequenceAttentionSpec):
132
+ b, s, _ = q.shape; l = attn_mask.latent_token_count
133
+ if s != attn_mask.total_token_count: raise ValueError("causal reference attention shape mismatch")
134
+ qh = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads)
135
+ kh = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads)
136
+ vh = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads)
137
+ f, n = int(attn_mask.latent_frames), int(attn_mask.tokens_per_frame)
138
+ frame_ids = torch.arange(l, device=q.device) // n
139
+ causal = frame_ids[:, None] >= frame_ids[None, :]
140
+ latent = F.scaled_dot_product_attention(qh[:, :, :l], kh[:, :, :l], vh[:, :, :l], attn_mask=causal)
141
+ qf = qh[:, :, :l].reshape(b, self.num_heads, f, n, -1)
142
+ kr = kh[:, :, l:].reshape(b, self.num_heads, f, n, -1)
143
+ vr = vh[:, :, l:].reshape(b, self.num_heads, f, n, -1)
144
+ 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)
145
+ ref = torch.zeros_like(qh[:, :, l:])
146
+ return rearrange(torch.cat([latent + cross, ref], dim=2), "b n s d -> b s (n d)", n=self.num_heads)
147
+ if isinstance(attn_mask, ReferenceSequenceAttentionSpec):
148
+ b, s, _ = q.shape; l = attn_mask.latent_token_count
149
+ if s != attn_mask.total_token_count: raise ValueError("reference attention shape mismatch")
150
+ qh = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads)
151
+ kh = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads)
152
+ vh = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads)
153
+ latent = F.scaled_dot_product_attention(qh[:, :, :l], kh[:, :, :l], vh[:, :, :l])
154
+ f, n = int(attn_mask.latent_frames), int(attn_mask.tokens_per_frame)
155
+ qf = qh[:, :, :l].reshape(b, self.num_heads, f, n, -1)
156
+ kr = kh[:, :, l:].reshape(b, self.num_heads, f, n, -1)
157
+ vr = vh[:, :, l:].reshape(b, self.num_heads, f, n, -1)
158
+ 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)
159
+ ref = torch.zeros_like(qh[:, :, l:])
160
+ return rearrange(torch.cat([latent + cross, ref], dim=2), "b n s d -> b s (n d)", n=self.num_heads)
161
+ if isinstance(attn_mask, TokenPrefixAttentionSpec):
162
+ q = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads)
163
+ k = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads)
164
+ v = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads)
165
+ prefix = int(attn_mask.prefix_token_count)
166
+ total = int(attn_mask.total_token_count)
167
+ if q.shape[2] != total or k.shape[2] != total or v.shape[2] != total:
168
+ raise ValueError(
169
+ "Token-prefix attention spec does not match q/k/v sequence length: "
170
+ f"spec={total}, q={q.shape[2]}, k={k.shape[2]}, v={v.shape[2]}"
171
+ )
172
+ # The explicit mask has all-false prefix query rows. Their SDPA
173
+ # output is zero, while target queries attend to every key.
174
+ target_output = F.scaled_dot_product_attention(
175
+ q[:, :, prefix:, :], k, v
176
+ )
177
+ prefix_output = torch.zeros_like(q[:, :, :prefix, :])
178
+ x = torch.cat([prefix_output, target_output], dim=2)
179
+ return rearrange(x, "b n s d -> b s (n d)", n=self.num_heads)
180
+ if attn_mask is not None:
181
+ q = rearrange(q, "b s (n d) -> b n s d", n=self.num_heads)
182
+ k = rearrange(k, "b s (n d) -> b n s d", n=self.num_heads)
183
+ v = rearrange(v, "b s (n d) -> b n s d", n=self.num_heads)
184
+ if attn_mask.dtype != torch.bool:
185
+ attn_mask = attn_mask.to(device=q.device, dtype=q.dtype)
186
+ else:
187
+ attn_mask = attn_mask.to(device=q.device)
188
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
189
+ return rearrange(x, "b n s d -> b s (n d)", n=self.num_heads)
190
+ x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads)
191
+ return x
192
+
193
+
194
+ class SelfAttention(nn.Module):
195
+ def __init__(self, dim: int, num_heads: int, eps: float = 1e-6):
196
+ super().__init__()
197
+ self.dim = dim
198
+ self.num_heads = num_heads
199
+ self.head_dim = dim // num_heads
200
+
201
+ self.q = nn.Linear(dim, dim)
202
+ self.k = nn.Linear(dim, dim)
203
+ self.v = nn.Linear(dim, dim)
204
+ self.o = nn.Linear(dim, dim)
205
+ self.norm_q = RMSNorm(dim, eps=eps)
206
+ self.norm_k = RMSNorm(dim, eps=eps)
207
+
208
+ self.attn = AttentionModule(self.num_heads)
209
+
210
+ def forward(self, x, freqs, attn_mask=None):
211
+ q = self.norm_q(self.q(x))
212
+ k = self.norm_k(self.k(x))
213
+ v = self.v(x)
214
+ q = rope_apply(q, freqs, self.num_heads)
215
+ k = rope_apply(k, freqs, self.num_heads)
216
+ x = self.attn(q, k, v, attn_mask=attn_mask)
217
+ return self.o(x)
218
+
219
+
220
+ class CrossAttention(nn.Module):
221
+ def __init__(self, dim: int, num_heads: int, eps: float = 1e-6, has_image_input: bool = False):
222
+ super().__init__()
223
+ self.dim = dim
224
+ self.num_heads = num_heads
225
+ self.head_dim = dim // num_heads
226
+
227
+ self.q = nn.Linear(dim, dim)
228
+ self.k = nn.Linear(dim, dim)
229
+ self.v = nn.Linear(dim, dim)
230
+ self.o = nn.Linear(dim, dim)
231
+ self.norm_q = RMSNorm(dim, eps=eps)
232
+ self.norm_k = RMSNorm(dim, eps=eps)
233
+ self.has_image_input = has_image_input
234
+ if has_image_input:
235
+ self.k_img = nn.Linear(dim, dim)
236
+ self.v_img = nn.Linear(dim, dim)
237
+ self.norm_k_img = RMSNorm(dim, eps=eps)
238
+
239
+ self.attn = AttentionModule(self.num_heads)
240
+
241
+ def forward(self, x: torch.Tensor, y: torch.Tensor):
242
+ if self.has_image_input:
243
+ img = y[:, :257]
244
+ ctx = y[:, 257:]
245
+ else:
246
+ ctx = y
247
+ q = self.norm_q(self.q(x))
248
+ k = self.norm_k(self.k(ctx))
249
+ v = self.v(ctx)
250
+ x = self.attn(q, k, v)
251
+ if self.has_image_input:
252
+ k_img = self.norm_k_img(self.k_img(img))
253
+ v_img = self.v_img(img)
254
+ y = flash_attention(q, k_img, v_img, num_heads=self.num_heads)
255
+ x = x + y
256
+ return self.o(x)
257
+
258
+
259
+ class GateModule(nn.Module):
260
+ def __init__(self,):
261
+ super().__init__()
262
+
263
+ def forward(self, x, gate, residual):
264
+ return x + gate * residual
265
+
266
+ class DiTBlock(nn.Module):
267
+ def __init__(self, has_image_input: bool, dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6):
268
+ super().__init__()
269
+ self.dim = dim
270
+ self.num_heads = num_heads
271
+ self.ffn_dim = ffn_dim
272
+
273
+ self.self_attn = SelfAttention(dim, num_heads, eps)
274
+ self.cross_attn = CrossAttention(
275
+ dim, num_heads, eps, has_image_input=has_image_input)
276
+ self.norm1 = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
277
+ self.norm2 = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
278
+ self.norm3 = nn.LayerNorm(dim, eps=eps)
279
+ self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.GELU(
280
+ approximate='tanh'), nn.Linear(ffn_dim, dim))
281
+ self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
282
+ self.gate = GateModule()
283
+
284
+ def forward(self, x, context, t_mod, freqs, attn_mask=None):
285
+ has_seq = len(t_mod.shape) == 4
286
+ chunk_dim = 2 if has_seq else 1
287
+ # msa: multi-head self-attention mlp: multi-layer perceptron
288
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
289
+ self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod).chunk(6, dim=chunk_dim)
290
+ if has_seq:
291
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
292
+ shift_msa.squeeze(2), scale_msa.squeeze(2), gate_msa.squeeze(2),
293
+ shift_mlp.squeeze(2), scale_mlp.squeeze(2), gate_mlp.squeeze(2),
294
+ )
295
+ input_x = modulate(self.norm1(x), shift_msa, scale_msa)
296
+ x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, attn_mask=attn_mask))
297
+ x = x + self.cross_attn(self.norm3(x), context)
298
+ input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
299
+ x = self.gate(x, gate_mlp, self.ffn(input_x))
300
+ return x
301
+
302
+
303
+ class MLP(torch.nn.Module):
304
+ def __init__(self, in_dim, out_dim, has_pos_emb=False):
305
+ super().__init__()
306
+ self.proj = torch.nn.Sequential(
307
+ nn.LayerNorm(in_dim),
308
+ nn.Linear(in_dim, in_dim),
309
+ nn.GELU(),
310
+ nn.Linear(in_dim, out_dim),
311
+ nn.LayerNorm(out_dim)
312
+ )
313
+ self.has_pos_emb = has_pos_emb
314
+ if has_pos_emb:
315
+ self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
316
+
317
+ def forward(self, x):
318
+ if self.has_pos_emb:
319
+ x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
320
+ return self.proj(x)
321
+
322
+
323
+ class Head(nn.Module):
324
+ def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
325
+ super().__init__()
326
+ self.dim = dim
327
+ self.patch_size = patch_size
328
+ self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
329
+ self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
330
+ self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
331
+
332
+ def forward(self, x, t_mod):
333
+ if len(t_mod.shape) == 3:
334
+ shift, scale = (self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device) + t_mod.unsqueeze(2)).chunk(2, dim=2)
335
+ x = (self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2)))
336
+ else:
337
+ shift, scale = (self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod).chunk(2, dim=1)
338
+ x = (self.head(self.norm(x) * (1 + scale) + shift))
339
+ return x
340
+
341
+
342
+ class WanModel(torch.nn.Module):
343
+ def __init__(
344
+ self,
345
+ dim: int,
346
+ in_dim: int,
347
+ ffn_dim: int,
348
+ out_dim: int,
349
+ text_dim: int,
350
+ freq_dim: int,
351
+ eps: float,
352
+ patch_size: Tuple[int, int, int],
353
+ num_heads: int,
354
+ num_layers: int,
355
+ has_image_input: bool,
356
+ has_image_pos_emb: bool = False,
357
+ has_ref_conv: bool = False,
358
+ add_control_adapter: bool = False,
359
+ in_dim_control_adapter: int = 24,
360
+ seperated_timestep: bool = False,
361
+ require_vae_embedding: bool = True,
362
+ require_clip_embedding: bool = True,
363
+ fuse_vae_embedding_in_latents: bool = False,
364
+ ):
365
+ super().__init__()
366
+ self.dim = dim
367
+ self.in_dim = in_dim
368
+ self.freq_dim = freq_dim
369
+ self.has_image_input = has_image_input
370
+ self.patch_size = patch_size
371
+ self.seperated_timestep = seperated_timestep
372
+ self.require_vae_embedding = require_vae_embedding
373
+ self.require_clip_embedding = require_clip_embedding
374
+ self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
375
+
376
+ self.patch_embedding = nn.Conv3d(
377
+ in_dim, dim, kernel_size=patch_size, stride=patch_size)
378
+ self.text_embedding = nn.Sequential(
379
+ nn.Linear(text_dim, dim),
380
+ nn.GELU(approximate='tanh'),
381
+ nn.Linear(dim, dim)
382
+ )
383
+ self.time_embedding = nn.Sequential(
384
+ nn.Linear(freq_dim, dim),
385
+ nn.SiLU(),
386
+ nn.Linear(dim, dim)
387
+ )
388
+ self.time_projection = nn.Sequential(
389
+ nn.SiLU(), nn.Linear(dim, dim * 6))
390
+ self.blocks = nn.ModuleList([
391
+ DiTBlock(has_image_input, dim, num_heads, ffn_dim, eps)
392
+ for _ in range(num_layers)
393
+ ])
394
+ self.head = Head(dim, out_dim, patch_size, eps)
395
+ head_dim = dim // num_heads
396
+ self.freqs = precompute_freqs_cis_3d(head_dim)
397
+ self._freqs_device_cache = {}
398
+
399
+ if has_image_input:
400
+ self.img_emb = MLP(1280, dim, has_pos_emb=has_image_pos_emb) # clip_feature_dim = 1280
401
+ if has_ref_conv:
402
+ self.ref_conv = nn.Conv2d(16, dim, kernel_size=(2, 2), stride=(2, 2))
403
+ self.has_image_pos_emb = has_image_pos_emb
404
+ self.has_ref_conv = has_ref_conv
405
+ if add_control_adapter:
406
+ self.control_adapter = SimpleAdapter(in_dim_control_adapter, dim, kernel_size=patch_size[1:], stride=patch_size[1:])
407
+ else:
408
+ self.control_adapter = None
409
+
410
+ def get_rope_freqs(self, device: torch.device | str):
411
+ device = torch.device(device)
412
+ key = str(device)
413
+ if key not in self._freqs_device_cache:
414
+ self._freqs_device_cache[key] = tuple(freq.to(device=device, dtype=torch.complex64) for freq in self.freqs)
415
+ return self._freqs_device_cache[key]
416
+
417
+ def patchify(self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None):
418
+ x = self.patch_embedding(x)
419
+ if self.control_adapter is not None and control_camera_latents_input is not None:
420
+ y_camera = self.control_adapter(control_camera_latents_input)
421
+ x = [u + v for u, v in zip(x, y_camera)]
422
+ x = x[0].unsqueeze(0)
423
+ return x
424
+
425
+ def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
426
+ return rearrange(
427
+ x, 'b (f h w) (x y z c) -> b c (f x) (h y) (w z)',
428
+ f=grid_size[0], h=grid_size[1], w=grid_size[2],
429
+ x=self.patch_size[0], y=self.patch_size[1], z=self.patch_size[2]
430
+ )
431
+
432
+ def forward(self,
433
+ x: torch.Tensor,
434
+ timestep: torch.Tensor,
435
+ context: torch.Tensor,
436
+ clip_feature: Optional[torch.Tensor] = None,
437
+ y: Optional[torch.Tensor] = None,
438
+ use_gradient_checkpointing: bool = False,
439
+ use_gradient_checkpointing_offload: bool = False,
440
+ attn_mask: Optional[torch.Tensor] = None,
441
+ **kwargs,
442
+ ):
443
+ t = self.time_embedding(
444
+ sinusoidal_embedding_1d(self.freq_dim, timestep))
445
+ t_mod = self.time_projection(t).unflatten(1, (6, self.dim))
446
+ context = self.text_embedding(context)
447
+
448
+ if self.has_image_input:
449
+ x = torch.cat([x, y], dim=1) # (b, c_x + c_y, f, h, w)
450
+ clip_embdding = self.img_emb(clip_feature)
451
+ context = torch.cat([clip_embdding, context], dim=1)
452
+
453
+ x, (f, h, w) = self.patchify(x)
454
+
455
+ rope_freqs = self.get_rope_freqs(x.device)
456
+ freqs = torch.cat([
457
+ rope_freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
458
+ rope_freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
459
+ rope_freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
460
+ ], dim=-1).reshape(f * h * w, 1, -1).to(device=x.device, dtype=torch.complex64)
461
+
462
+ def create_custom_forward(module):
463
+ def custom_forward(*inputs):
464
+ return module(*inputs)
465
+ return custom_forward
466
+
467
+ for block in self.blocks:
468
+ if self.training and use_gradient_checkpointing:
469
+ if use_gradient_checkpointing_offload:
470
+ with torch.autograd.graph.save_on_cpu():
471
+ if attn_mask is None:
472
+ x = torch.utils.checkpoint.checkpoint(
473
+ create_custom_forward(block),
474
+ x, context, t_mod, freqs,
475
+ use_reentrant=False,
476
+ )
477
+ else:
478
+ x = torch.utils.checkpoint.checkpoint(
479
+ create_custom_forward(block),
480
+ x, context, t_mod, freqs, attn_mask,
481
+ use_reentrant=False,
482
+ )
483
+ else:
484
+ if attn_mask is None:
485
+ x = torch.utils.checkpoint.checkpoint(
486
+ create_custom_forward(block),
487
+ x, context, t_mod, freqs,
488
+ use_reentrant=False,
489
+ )
490
+ else:
491
+ x = torch.utils.checkpoint.checkpoint(
492
+ create_custom_forward(block),
493
+ x, context, t_mod, freqs, attn_mask,
494
+ use_reentrant=False,
495
+ )
496
+ else:
497
+ x = block(x, context, t_mod, freqs, attn_mask=attn_mask)
498
+
499
+ x = self.head(x, t)
500
+ x = self.unpatchify(x, (f, h, w))
501
+ return x
502
+
503
+ @staticmethod
504
+ def state_dict_converter():
505
+ return WanModelStateDictConverter()
506
+
507
+
508
+ class WanModelStateDictConverter:
509
+ def __init__(self):
510
+ pass
511
+
512
+ def from_diffusers(self, state_dict):
513
+ rename_dict = {
514
+ "blocks.0.attn1.norm_k.weight": "blocks.0.self_attn.norm_k.weight",
515
+ "blocks.0.attn1.norm_q.weight": "blocks.0.self_attn.norm_q.weight",
516
+ "blocks.0.attn1.to_k.bias": "blocks.0.self_attn.k.bias",
517
+ "blocks.0.attn1.to_k.weight": "blocks.0.self_attn.k.weight",
518
+ "blocks.0.attn1.to_out.0.bias": "blocks.0.self_attn.o.bias",
519
+ "blocks.0.attn1.to_out.0.weight": "blocks.0.self_attn.o.weight",
520
+ "blocks.0.attn1.to_q.bias": "blocks.0.self_attn.q.bias",
521
+ "blocks.0.attn1.to_q.weight": "blocks.0.self_attn.q.weight",
522
+ "blocks.0.attn1.to_v.bias": "blocks.0.self_attn.v.bias",
523
+ "blocks.0.attn1.to_v.weight": "blocks.0.self_attn.v.weight",
524
+ "blocks.0.attn2.norm_k.weight": "blocks.0.cross_attn.norm_k.weight",
525
+ "blocks.0.attn2.norm_q.weight": "blocks.0.cross_attn.norm_q.weight",
526
+ "blocks.0.attn2.to_k.bias": "blocks.0.cross_attn.k.bias",
527
+ "blocks.0.attn2.to_k.weight": "blocks.0.cross_attn.k.weight",
528
+ "blocks.0.attn2.to_out.0.bias": "blocks.0.cross_attn.o.bias",
529
+ "blocks.0.attn2.to_out.0.weight": "blocks.0.cross_attn.o.weight",
530
+ "blocks.0.attn2.to_q.bias": "blocks.0.cross_attn.q.bias",
531
+ "blocks.0.attn2.to_q.weight": "blocks.0.cross_attn.q.weight",
532
+ "blocks.0.attn2.to_v.bias": "blocks.0.cross_attn.v.bias",
533
+ "blocks.0.attn2.to_v.weight": "blocks.0.cross_attn.v.weight",
534
+ "blocks.0.ffn.net.0.proj.bias": "blocks.0.ffn.0.bias",
535
+ "blocks.0.ffn.net.0.proj.weight": "blocks.0.ffn.0.weight",
536
+ "blocks.0.ffn.net.2.bias": "blocks.0.ffn.2.bias",
537
+ "blocks.0.ffn.net.2.weight": "blocks.0.ffn.2.weight",
538
+ "blocks.0.norm2.bias": "blocks.0.norm3.bias",
539
+ "blocks.0.norm2.weight": "blocks.0.norm3.weight",
540
+ "blocks.0.scale_shift_table": "blocks.0.modulation",
541
+ "condition_embedder.text_embedder.linear_1.bias": "text_embedding.0.bias",
542
+ "condition_embedder.text_embedder.linear_1.weight": "text_embedding.0.weight",
543
+ "condition_embedder.text_embedder.linear_2.bias": "text_embedding.2.bias",
544
+ "condition_embedder.text_embedder.linear_2.weight": "text_embedding.2.weight",
545
+ "condition_embedder.time_embedder.linear_1.bias": "time_embedding.0.bias",
546
+ "condition_embedder.time_embedder.linear_1.weight": "time_embedding.0.weight",
547
+ "condition_embedder.time_embedder.linear_2.bias": "time_embedding.2.bias",
548
+ "condition_embedder.time_embedder.linear_2.weight": "time_embedding.2.weight",
549
+ "condition_embedder.time_proj.bias": "time_projection.1.bias",
550
+ "condition_embedder.time_proj.weight": "time_projection.1.weight",
551
+ "patch_embedding.bias": "patch_embedding.bias",
552
+ "patch_embedding.weight": "patch_embedding.weight",
553
+ "scale_shift_table": "head.modulation",
554
+ "proj_out.bias": "head.head.bias",
555
+ "proj_out.weight": "head.head.weight",
556
+ }
557
+ state_dict_ = {}
558
+ for name, param in state_dict.items():
559
+ if name in rename_dict:
560
+ state_dict_[rename_dict[name]] = param
561
+ else:
562
+ name_ = ".".join(name.split(".")[:1] + ["0"] + name.split(".")[2:])
563
+ if name_ in rename_dict:
564
+ name_ = rename_dict[name_]
565
+ name_ = ".".join(name_.split(".")[:1] + [name.split(".")[1]] + name_.split(".")[2:])
566
+ state_dict_[name_] = param
567
+ if hash_state_dict_keys(state_dict) == "cb104773c6c2cb6df4f9529ad5c60d0b":
568
+ config = {
569
+ "model_type": "t2v",
570
+ "patch_size": (1, 2, 2),
571
+ "text_len": 512,
572
+ "in_dim": 16,
573
+ "dim": 5120,
574
+ "ffn_dim": 13824,
575
+ "freq_dim": 256,
576
+ "text_dim": 4096,
577
+ "out_dim": 16,
578
+ "num_heads": 40,
579
+ "num_layers": 40,
580
+ "window_size": (-1, -1),
581
+ "qk_norm": True,
582
+ "cross_attn_norm": True,
583
+ "eps": 1e-6,
584
+ }
585
+ else:
586
+ config = {}
587
+ return state_dict_, config
588
+
589
+ def from_civitai(self, state_dict):
590
+ state_dict = {name: param for name, param in state_dict.items() if not name.startswith("vace")}
591
+ 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"]}
592
+ if hash_state_dict_keys(state_dict) == "9269f8db9040a9d860eaca435be61814":
593
+ config = {
594
+ "has_image_input": False,
595
+ "patch_size": [1, 2, 2],
596
+ "in_dim": 16,
597
+ "dim": 1536,
598
+ "ffn_dim": 8960,
599
+ "freq_dim": 256,
600
+ "text_dim": 4096,
601
+ "out_dim": 16,
602
+ "num_heads": 12,
603
+ "num_layers": 30,
604
+ "eps": 1e-6
605
+ }
606
+ elif hash_state_dict_keys(state_dict) == "aafcfd9672c3a2456dc46e1cb6e52c70":
607
+ config = {
608
+ "has_image_input": False,
609
+ "patch_size": [1, 2, 2],
610
+ "in_dim": 16,
611
+ "dim": 5120,
612
+ "ffn_dim": 13824,
613
+ "freq_dim": 256,
614
+ "text_dim": 4096,
615
+ "out_dim": 16,
616
+ "num_heads": 40,
617
+ "num_layers": 40,
618
+ "eps": 1e-6
619
+ }
620
+ elif hash_state_dict_keys(state_dict) == "6bfcfb3b342cb286ce886889d519a77e":
621
+ config = {
622
+ "has_image_input": True,
623
+ "patch_size": [1, 2, 2],
624
+ "in_dim": 36,
625
+ "dim": 5120,
626
+ "ffn_dim": 13824,
627
+ "freq_dim": 256,
628
+ "text_dim": 4096,
629
+ "out_dim": 16,
630
+ "num_heads": 40,
631
+ "num_layers": 40,
632
+ "eps": 1e-6
633
+ }
634
+ elif hash_state_dict_keys(state_dict) == "6d6ccde6845b95ad9114ab993d917893":
635
+ config = {
636
+ "has_image_input": True,
637
+ "patch_size": [1, 2, 2],
638
+ "in_dim": 36,
639
+ "dim": 1536,
640
+ "ffn_dim": 8960,
641
+ "freq_dim": 256,
642
+ "text_dim": 4096,
643
+ "out_dim": 16,
644
+ "num_heads": 12,
645
+ "num_layers": 30,
646
+ "eps": 1e-6
647
+ }
648
+ elif hash_state_dict_keys(state_dict) == "349723183fc063b2bfc10bb2835cf677":
649
+ # 1.3B PAI control
650
+ config = {
651
+ "has_image_input": True,
652
+ "patch_size": [1, 2, 2],
653
+ "in_dim": 48,
654
+ "dim": 1536,
655
+ "ffn_dim": 8960,
656
+ "freq_dim": 256,
657
+ "text_dim": 4096,
658
+ "out_dim": 16,
659
+ "num_heads": 12,
660
+ "num_layers": 30,
661
+ "eps": 1e-6
662
+ }
663
+ elif hash_state_dict_keys(state_dict) == "efa44cddf936c70abd0ea28b6cbe946c":
664
+ # 14B PAI control
665
+ config = {
666
+ "has_image_input": True,
667
+ "patch_size": [1, 2, 2],
668
+ "in_dim": 48,
669
+ "dim": 5120,
670
+ "ffn_dim": 13824,
671
+ "freq_dim": 256,
672
+ "text_dim": 4096,
673
+ "out_dim": 16,
674
+ "num_heads": 40,
675
+ "num_layers": 40,
676
+ "eps": 1e-6
677
+ }
678
+ elif hash_state_dict_keys(state_dict) == "3ef3b1f8e1dab83d5b71fd7b617f859f":
679
+ config = {
680
+ "has_image_input": True,
681
+ "patch_size": [1, 2, 2],
682
+ "in_dim": 36,
683
+ "dim": 5120,
684
+ "ffn_dim": 13824,
685
+ "freq_dim": 256,
686
+ "text_dim": 4096,
687
+ "out_dim": 16,
688
+ "num_heads": 40,
689
+ "num_layers": 40,
690
+ "eps": 1e-6,
691
+ "has_image_pos_emb": True
692
+ }
693
+ elif hash_state_dict_keys(state_dict) == "70ddad9d3a133785da5ea371aae09504":
694
+ # 1.3B PAI control v1.1
695
+ config = {
696
+ "has_image_input": True,
697
+ "patch_size": [1, 2, 2],
698
+ "in_dim": 48,
699
+ "dim": 1536,
700
+ "ffn_dim": 8960,
701
+ "freq_dim": 256,
702
+ "text_dim": 4096,
703
+ "out_dim": 16,
704
+ "num_heads": 12,
705
+ "num_layers": 30,
706
+ "eps": 1e-6,
707
+ "has_ref_conv": True
708
+ }
709
+ elif hash_state_dict_keys(state_dict) == "26bde73488a92e64cc20b0a7485b9e5b":
710
+ # 14B PAI control v1.1
711
+ config = {
712
+ "has_image_input": True,
713
+ "patch_size": [1, 2, 2],
714
+ "in_dim": 48,
715
+ "dim": 5120,
716
+ "ffn_dim": 13824,
717
+ "freq_dim": 256,
718
+ "text_dim": 4096,
719
+ "out_dim": 16,
720
+ "num_heads": 40,
721
+ "num_layers": 40,
722
+ "eps": 1e-6,
723
+ "has_ref_conv": True
724
+ }
725
+ elif hash_state_dict_keys(state_dict) == "ac6a5aa74f4a0aab6f64eb9a72f19901":
726
+ # 1.3B PAI control-camera v1.1
727
+ config = {
728
+ "has_image_input": True,
729
+ "patch_size": [1, 2, 2],
730
+ "in_dim": 32,
731
+ "dim": 1536,
732
+ "ffn_dim": 8960,
733
+ "freq_dim": 256,
734
+ "text_dim": 4096,
735
+ "out_dim": 16,
736
+ "num_heads": 12,
737
+ "num_layers": 30,
738
+ "eps": 1e-6,
739
+ "has_ref_conv": False,
740
+ "add_control_adapter": True,
741
+ "in_dim_control_adapter": 24,
742
+ }
743
+ elif hash_state_dict_keys(state_dict) == "b61c605c2adbd23124d152ed28e049ae":
744
+ # 14B PAI control-camera v1.1
745
+ config = {
746
+ "has_image_input": True,
747
+ "patch_size": [1, 2, 2],
748
+ "in_dim": 32,
749
+ "dim": 5120,
750
+ "ffn_dim": 13824,
751
+ "freq_dim": 256,
752
+ "text_dim": 4096,
753
+ "out_dim": 16,
754
+ "num_heads": 40,
755
+ "num_layers": 40,
756
+ "eps": 1e-6,
757
+ "has_ref_conv": False,
758
+ "add_control_adapter": True,
759
+ "in_dim_control_adapter": 24,
760
+ }
761
+ elif hash_state_dict_keys(state_dict) == "1f5ab7703c6fc803fdded85ff040c316":
762
+ # Wan-AI/Wan2.2-TI2V-5B
763
+ config = {
764
+ "has_image_input": False,
765
+ "patch_size": [1, 2, 2],
766
+ "in_dim": 48,
767
+ "dim": 3072,
768
+ "ffn_dim": 14336,
769
+ "freq_dim": 256,
770
+ "text_dim": 4096,
771
+ "out_dim": 48,
772
+ "num_heads": 24,
773
+ "num_layers": 30,
774
+ "eps": 1e-6,
775
+ "seperated_timestep": True,
776
+ "require_clip_embedding": False,
777
+ "require_vae_embedding": False,
778
+ "fuse_vae_embedding_in_latents": True,
779
+ }
780
+ elif hash_state_dict_keys(state_dict) == "5b013604280dd715f8457c6ed6d6a626":
781
+ # Wan-AI/Wan2.2-I2V-A14B
782
+ config = {
783
+ "has_image_input": False,
784
+ "patch_size": [1, 2, 2],
785
+ "in_dim": 36,
786
+ "dim": 5120,
787
+ "ffn_dim": 13824,
788
+ "freq_dim": 256,
789
+ "text_dim": 4096,
790
+ "out_dim": 16,
791
+ "num_heads": 40,
792
+ "num_layers": 40,
793
+ "eps": 1e-6,
794
+ "require_clip_embedding": False,
795
+ }
796
+ elif hash_state_dict_keys(state_dict) == "2267d489f0ceb9f21836532952852ee5":
797
+ # Wan2.2-Fun-A14B-Control
798
+ config = {
799
+ "has_image_input": False,
800
+ "patch_size": [1, 2, 2],
801
+ "in_dim": 52,
802
+ "dim": 5120,
803
+ "ffn_dim": 13824,
804
+ "freq_dim": 256,
805
+ "text_dim": 4096,
806
+ "out_dim": 16,
807
+ "num_heads": 40,
808
+ "num_layers": 40,
809
+ "eps": 1e-6,
810
+ "has_ref_conv": True,
811
+ "require_clip_embedding": False,
812
+ }
813
+ elif hash_state_dict_keys(state_dict) == "47dbeab5e560db3180adf51dc0232fb1":
814
+ # Wan2.2-Fun-A14B-Control-Camera
815
+ config = {
816
+ "has_image_input": False,
817
+ "patch_size": [1, 2, 2],
818
+ "in_dim": 36,
819
+ "dim": 5120,
820
+ "ffn_dim": 13824,
821
+ "freq_dim": 256,
822
+ "text_dim": 4096,
823
+ "out_dim": 16,
824
+ "num_heads": 40,
825
+ "num_layers": 40,
826
+ "eps": 1e-6,
827
+ "has_ref_conv": False,
828
+ "add_control_adapter": True,
829
+ "in_dim_control_adapter": 24,
830
+ "require_clip_embedding": False,
831
+ }
832
+ else:
833
+ config = {}
834
+ return state_dict, config