linyq commited on
Commit
ca5da2f
Β·
verified Β·
1 Parent(s): 805afc8

Add files using upload-large-folder tool

Browse files
__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from pipeline_kiwi_edit import KiwiEditPipeline
2
+ from mllm_encoder import MLLMEncoder
3
+ from conditional_embedder import ConditionalEmbedder
4
+ from wan_video_vae import VAE
conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
mllm_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
mllm_encoder/mllm_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
pipeline_kiwi_edit.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import numpy as np
4
+ from typing import Optional, List, Union, Callable, Tuple
5
+ from PIL import Image, ImageOps
6
+ from einops import rearrange
7
+ from tqdm import tqdm
8
+ from diffusers import DiffusionPipeline
9
+
10
+
11
+ def sinusoidal_embedding_1d(dim, position):
12
+ """1D sinusoidal positional embedding for timesteps."""
13
+ sinusoid = torch.outer(
14
+ position.type(torch.float64),
15
+ torch.pow(
16
+ 10000,
17
+ -torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(
18
+ dim // 2
19
+ ),
20
+ ),
21
+ )
22
+ x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
23
+ return x.to(position.dtype)
24
+
25
+
26
+ def _build_rope_3d(rope_module, f, h, w, device):
27
+ """
28
+ Build 3D RoPE (cos, sin) for a given (f, h, w) grid using the
29
+ WanRotaryPosEmbed module's precomputed buffers.
30
+
31
+ Returns:
32
+ (freqs_cos, freqs_sin) each of shape [1, f*h*w, 1, head_dim]
33
+ """
34
+ split_sizes = [rope_module.t_dim, rope_module.h_dim, rope_module.w_dim]
35
+ cos_parts = rope_module.freqs_cos.split(split_sizes, dim=1)
36
+ sin_parts = rope_module.freqs_sin.split(split_sizes, dim=1)
37
+
38
+ cos_f = cos_parts[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1)
39
+ cos_h = cos_parts[1][:h].view(1, h, 1, -1).expand(f, h, w, -1)
40
+ cos_w = cos_parts[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
41
+
42
+ sin_f = sin_parts[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1)
43
+ sin_h = sin_parts[1][:h].view(1, h, 1, -1).expand(f, h, w, -1)
44
+ sin_w = sin_parts[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
45
+
46
+ freqs_cos = torch.cat([cos_f, cos_h, cos_w], dim=-1).reshape(1, f * h * w, 1, -1).to(device)
47
+ freqs_sin = torch.cat([sin_f, sin_h, sin_w], dim=-1).reshape(1, f * h * w, 1, -1).to(device)
48
+ return freqs_cos, freqs_sin
49
+
50
+
51
+ class KiwiEditPipeline(DiffusionPipeline):
52
+ """
53
+ Pipeline for reference-guided video and image editing using KiwiEdit.
54
+
55
+ This pipeline uses a Qwen2.5-VL multimodal LLM encoder for understanding
56
+ editing instructions with source visual context, a WanTransformer3DModel
57
+ for diffusion, and AutoencoderKLWan for VAE encoding/decoding.
58
+
59
+ Args:
60
+ transformer: WanTransformer3DModel - DiT backbone for denoising.
61
+ vae: AutoencoderKLWan - 3D causal VAE.
62
+ scheduler: FlowMatchEulerDiscreteScheduler or compatible scheduler.
63
+ mllm_encoder: MLLMEncoder - Qwen2.5-VL MLLM with learnable queries.
64
+ processor: AutoProcessor - Qwen2.5-VL processor/tokenizer bundle.
65
+ source_embedder: ConditionalEmbedder - VAE source conditioning.
66
+ ref_embedder: ConditionalEmbedder - VAE reference conditioning.
67
+ """
68
+
69
+ model_cpu_offload_seq = "mllm_encoder->source_embedder->ref_embedder->transformer->vae"
70
+
71
+ def __init__(
72
+ self,
73
+ transformer,
74
+ vae,
75
+ scheduler,
76
+ mllm_encoder,
77
+ source_embedder,
78
+ ref_embedder,
79
+ processor=None,
80
+ ):
81
+ super().__init__()
82
+ if isinstance(processor, (list, tuple)):
83
+ # Diffusers may pass the raw model_index spec; let MLLMEncoder resolve it later.
84
+ processor = None
85
+ self.register_modules(
86
+ transformer=transformer,
87
+ vae=vae,
88
+ scheduler=scheduler,
89
+ mllm_encoder=mllm_encoder,
90
+ processor=processor,
91
+ source_embedder=source_embedder,
92
+ ref_embedder=ref_embedder,
93
+ )
94
+ if processor is not None:
95
+ self.mllm_encoder.processor = processor
96
+
97
+ # ------------------------------------------------------------------ #
98
+ # Helper utilities #
99
+ # ------------------------------------------------------------------ #
100
+
101
+ @staticmethod
102
+ def _check_resize(height, width, num_frames, h_div=16, w_div=16, t_div=4, t_rem=1):
103
+ """Round height/width/num_frames to valid values."""
104
+ if height % h_div != 0:
105
+ height = (height + h_div - 1) // h_div * h_div
106
+ if width % w_div != 0:
107
+ width = (width + w_div - 1) // w_div * w_div
108
+ if num_frames % t_div != t_rem:
109
+ num_frames = (num_frames + t_div - 1) // t_div * t_div + t_rem
110
+ return height, width, num_frames
111
+
112
+ @staticmethod
113
+ def _preprocess_image(image: Image.Image, dtype, device):
114
+ """Convert PIL Image to tensor in [-1, 1]."""
115
+ arr = np.array(image, dtype=np.float32)
116
+ tensor = torch.from_numpy(arr).to(dtype=dtype, device=device)
117
+ tensor = tensor / 127.5 - 1.0 # [0, 255] -> [-1, 1]
118
+ tensor = tensor.permute(2, 0, 1) # H W C -> C H W
119
+ return tensor
120
+
121
+ def _preprocess_video(self, frames: List[Image.Image], dtype, device):
122
+ """Convert list of PIL Images to tensor [1, C, T, H, W] in [-1, 1]."""
123
+ tensors = [self._preprocess_image(f, dtype, device) for f in frames]
124
+ video = torch.stack(tensors, dim=1) # C T H W
125
+ return video.unsqueeze(0) # 1 C T H W
126
+
127
+ @staticmethod
128
+ def _vae_output_to_video(vae_output):
129
+ """Convert VAE output tensor to list of PIL Images."""
130
+ # vae_output shape: [B, C, T, H, W] or [T, H, W, C]
131
+ if vae_output.dim() == 5:
132
+ vae_output = vae_output.squeeze(0).permute(1, 2, 3, 0) # T H W C
133
+ frames = []
134
+ for t in range(vae_output.shape[0]):
135
+ frame = ((vae_output[t] + 1.0) * 127.5).clamp(0, 255)
136
+ frame = frame.to(device="cpu", dtype=torch.uint8).numpy()
137
+ frames.append(Image.fromarray(frame))
138
+ return frames
139
+
140
+ # ------------------------------------------------------------------ #
141
+ # Custom Flow Match Scheduler #
142
+ # ------------------------------------------------------------------ #
143
+
144
+ def _setup_scheduler(self, num_inference_steps, denoising_strength=1.0, shift=5.0):
145
+ """
146
+ Set up flow-match sigmas and timesteps matching the original diffsynth
147
+ FlowMatchScheduler with extra_one_step=True and shift.
148
+ """
149
+ sigma_min = 0.003 / 1.002
150
+ sigma_max = 1.0
151
+ sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength
152
+ # extra_one_step: generate N+1 points, drop last
153
+ sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1]
154
+ # Apply shift
155
+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
156
+ timesteps = sigmas * 1000 # num_train_timesteps = 1000
157
+ return sigmas, timesteps
158
+
159
+ def _scheduler_step(self, model_output, sigmas, step_index, sample):
160
+ """Euler step for flow matching."""
161
+ sigma = sigmas[step_index]
162
+ if step_index + 1 >= len(sigmas):
163
+ sigma_next = 0.0
164
+ else:
165
+ sigma_next = sigmas[step_index + 1]
166
+ return sample + model_output * (sigma_next - sigma)
167
+
168
+ def _scheduler_add_noise(self, original_samples, noise, sigmas, step_index):
169
+ """Add noise at given timestep for img2img / video2video."""
170
+ sigma = sigmas[step_index]
171
+ return (1 - sigma) * original_samples + sigma * noise
172
+
173
+ def _scheduler_get_sigma(self, timestep, sigmas, timesteps):
174
+ """Get sigma for a given timestep."""
175
+ timestep_id = torch.argmin((timesteps - timestep).abs())
176
+ return sigmas[timestep_id]
177
+
178
+ # ------------------------------------------------------------------ #
179
+ # Transformer forward helpers #
180
+ # ------------------------------------------------------------------ #
181
+
182
+ def _model_forward(
183
+ self,
184
+ latents,
185
+ timestep,
186
+ context,
187
+ vae_source_input=None,
188
+ vae_ref_image=None,
189
+ sigmas=None,
190
+ timesteps_schedule=None,
191
+ ):
192
+ """
193
+ Custom DiT forward pass that handles source/ref conditioning.
194
+ Mirrors model_fn_wan_video from the original diffsynth pipeline.
195
+ """
196
+ device = latents.device
197
+ dtype = latents.dtype
198
+ t = self.transformer
199
+
200
+ # --- Timestep embedding ---
201
+ timestep_emb = sinusoidal_embedding_1d(
202
+ t.config.freq_dim, timestep
203
+ ).to(dtype)
204
+ time_emb = t.condition_embedder.time_embedder(timestep_emb)
205
+ # diffusers time_proj = Linear only (SiLU is applied separately)
206
+ t_mod = t.condition_embedder.time_proj(F.silu(time_emb)).unflatten(
207
+ 1, (6, t.config.num_attention_heads * t.config.attention_head_dim)
208
+ )
209
+
210
+ # --- Text/context embedding ---
211
+ # NOTE: Do NOT apply text_embedder here. The MLLM encoder's connector
212
+ # already projects to dit_dim. text_embedder is for raw text encoder
213
+ # output (text_dim β†’ dim), which doesn't apply to MLLM output.
214
+
215
+ # --- Patchify latents ---
216
+ x = latents
217
+ if vae_source_input is not None:
218
+ vae_source_cond = self.source_embedder(vae_source_input)
219
+ x = t.patch_embedding(x)
220
+ # Get sigma for this timestep
221
+ sigma = self._scheduler_get_sigma(timestep, sigmas, timesteps_schedule)
222
+ x = x + vae_source_cond * sigma
223
+ else:
224
+ x = t.patch_embedding(x)
225
+
226
+ f, h, w = x.shape[2:]
227
+ x = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
228
+
229
+ # --- 3D RoPE frequencies (real-valued cos/sin format) ---
230
+ rotary_emb = _build_rope_3d(t.rope, f, h, w, device)
231
+
232
+ # --- Reference image conditioning ---
233
+ vae_ref_input_length = 0
234
+ if vae_ref_image is not None:
235
+ if len(vae_ref_image) > 1:
236
+ vae_ref = torch.cat(vae_ref_image, dim=2) # concat along temporal
237
+ else:
238
+ vae_ref = vae_ref_image[0]
239
+
240
+ vae_ref = self.ref_embedder(vae_ref)
241
+ ref_f, ref_h, ref_w = vae_ref.shape[2:]
242
+ vae_ref = rearrange(vae_ref, "b c f h w -> b (f h w) c").contiguous()
243
+
244
+ # Recompute RoPE for extended sequence (main + ref tokens)
245
+ total_f = f + ref_f
246
+ rotary_emb = _build_rope_3d(t.rope, total_f, h, w, device)
247
+
248
+ vae_ref_input_length = vae_ref.shape[1]
249
+
250
+ if self.ref_embedder.config.ref_pad_first:
251
+ x = torch.cat([vae_ref, x], dim=1)
252
+ else:
253
+ x = torch.cat([x, vae_ref], dim=1)
254
+
255
+ # --- Transformer blocks ---
256
+ for block in t.blocks:
257
+ x = block(x, context, t_mod, rotary_emb)
258
+
259
+ # --- Output head ---
260
+ # Match diffusers' FP32 norm + modulation + projection
261
+ table = t.scale_shift_table
262
+ shift, scale = (
263
+ table.to(device=device) + time_emb.unsqueeze(1)
264
+ ).chunk(2, dim=1)
265
+ shift = shift.to(device=x.device)
266
+ scale = scale.to(device=x.device)
267
+ x = (t.norm_out(x.float()) * (1 + scale) + shift).type_as(x)
268
+ x = t.proj_out(x)
269
+
270
+ # --- Remove ref tokens from output ---
271
+ if vae_ref_image is not None and vae_ref_input_length > 0:
272
+ if self.ref_embedder.config.ref_pad_first:
273
+ x = x[:, vae_ref_input_length:, :]
274
+ else:
275
+ x = x[:, :-vae_ref_input_length, :]
276
+
277
+ # --- Unpatchify ---
278
+ patch_size = t.config.patch_size
279
+ x = rearrange(
280
+ x,
281
+ "b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
282
+ f=f, h=h, w=w,
283
+ x=patch_size[0], y=patch_size[1], z=patch_size[2],
284
+ )
285
+ return x
286
+
287
+ # ------------------------------------------------------------------ #
288
+ # Main __call__ #
289
+ # ------------------------------------------------------------------ #
290
+
291
+ @torch.no_grad()
292
+ def __call__(
293
+ self,
294
+ prompt: str,
295
+ source_video: Optional[List[Image.Image]] = None,
296
+ source_input: Optional[List[Image.Image]] = None,
297
+ ref_image: Optional[List[Image.Image]] = None,
298
+ negative_prompt: Optional[str] = "",
299
+ input_video: Optional[List[Image.Image]] = None,
300
+ height: int = 480,
301
+ width: int = 832,
302
+ num_frames: int = 81,
303
+ num_inference_steps: int = 50,
304
+ guidance_scale: float = 1.0,
305
+ sigma_shift: float = 5.0,
306
+ denoising_strength: float = 1.0,
307
+ seed: Optional[int] = None,
308
+ tiled: bool = True,
309
+ tile_size: Tuple[int, int] = (30, 52),
310
+ tile_stride: Tuple[int, int] = (15, 26),
311
+ output_type: str = "pil",
312
+ progress_bar: Callable = tqdm,
313
+ ) -> List[Image.Image]:
314
+ """
315
+ Run KiwiEdit inference.
316
+
317
+ Args:
318
+ prompt: Editing instruction text.
319
+ source_video: Source video/image frames for MLLM context (also used as
320
+ source_input if source_input is not provided).
321
+ source_input: Source frames for VAE conditioning. If None but source_video
322
+ is provided, source_video is used.
323
+ ref_image: Optional reference image(s) for guided editing.
324
+ negative_prompt: Negative prompt for CFG.
325
+ input_video: Optional input video for video-to-video (adds noise then denoises).
326
+ height: Output height in pixels.
327
+ width: Output width in pixels.
328
+ num_frames: Number of output frames (1 for image editing).
329
+ num_inference_steps: Number of denoising steps.
330
+ guidance_scale: Classifier-free guidance scale.
331
+ sigma_shift: Flow matching shift parameter.
332
+ denoising_strength: How much noise to add (1.0 = full noise).
333
+ seed: Random seed for reproducibility.
334
+ tiled: Whether to use tiled VAE encoding/decoding.
335
+ tile_size: VAE tile size.
336
+ tile_stride: VAE tile stride.
337
+ output_type: "pil" for PIL Images, "latent" for raw latents.
338
+ progress_bar: Progress bar callable (e.g., tqdm).
339
+
340
+ Returns:
341
+ List of PIL Images (video frames).
342
+ """
343
+ device = self._execution_device
344
+ dtype = torch.bfloat16
345
+ # --- 1. Shape check ---
346
+ # VAE spatial factor is 16, transformer patch spatial is 2,
347
+ # so pixel dims must be multiples of 32.
348
+ height, width, num_frames = self._check_resize(
349
+ height, width, num_frames, h_div=32, w_div=32
350
+ )
351
+
352
+ # --- 2. Determine VAE parameters ---
353
+ z_dim = self.vae.config.z_dim
354
+ # Compute upsampling factor from VAE config
355
+ dim_mult = self.vae.config.get("dim_mult", [1, 2, 4, 4])
356
+ temporal_downsample = self.vae.config.get("temperal_downsample", [False, True, True])
357
+ # Wan VideoVAE spatial factor is 2^(len(dim_mult)) due to extra
358
+ # downsampling in the encoder beyond the level transitions.
359
+ spatial_factor = 2 ** len(dim_mult) # 16 for 4 levels
360
+ temporal_factor = 2 ** sum(temporal_downsample) # 4 for [F, T, T]
361
+
362
+ # --- 3. MLLM encoding ---
363
+ context = None
364
+ src_video_for_mllm = source_video
365
+ if src_video_for_mllm is not None:
366
+ self.mllm_encoder._ensure_qwen_loaded()
367
+ if ref_image is not None:
368
+ # Ref mode always uses the video path (even for a single frame)
369
+ context = self.mllm_encoder(
370
+ prompt, src_video=src_video_for_mllm, ref_image=ref_image
371
+ )
372
+ elif len(src_video_for_mllm) == 1:
373
+ context = self.mllm_encoder(
374
+ prompt, src_image=src_video_for_mllm
375
+ )
376
+ else:
377
+ context = self.mllm_encoder(
378
+ prompt, src_video=src_video_for_mllm
379
+ )
380
+ # For negative prompt: use zero context
381
+ context_nega = None
382
+
383
+ # --- 4. Setup scheduler ---
384
+ sigmas, timesteps = self._setup_scheduler(
385
+ num_inference_steps, denoising_strength, sigma_shift
386
+ )
387
+ sigmas = sigmas.to(device)
388
+ timesteps = timesteps.to(device)
389
+
390
+ # --- 5. Initialize noise ---
391
+ latent_length = (num_frames - 1) // temporal_factor + 1
392
+ latent_h = height // spatial_factor
393
+ latent_w = width // spatial_factor
394
+ shape = (1, z_dim, latent_length, latent_h, latent_w)
395
+
396
+ generator = None if seed is None else torch.Generator("cpu").manual_seed(seed)
397
+ noise = torch.randn(shape, generator=generator, device="cpu", dtype=torch.float32)
398
+ noise = noise.to(dtype=dtype, device=device)
399
+
400
+ # --- 6. Encode source input ---
401
+ vae_source_input = None
402
+ # Fall back to source_video if source_input not provided
403
+ src_for_vae = source_input if source_input is not None else source_video
404
+ if src_for_vae is not None:
405
+ src_frames = [src_for_vae[i] for i in range(min(num_frames, len(src_for_vae)))]
406
+ # Resize source frames to match the (possibly adjusted) target dimensions
407
+ src_frames = [f.resize((width, height), Image.LANCZOS) for f in src_frames]
408
+ src_tensor = self._preprocess_video(src_frames, dtype=torch.float32, device=device)
409
+ vae_source_input = self.vae.encode(src_tensor).latent_dist.sample()
410
+ vae_source_input = vae_source_input.to(dtype=dtype)
411
+
412
+ # --- 7. Encode reference images ---
413
+ vae_ref_image = None
414
+ if ref_image is not None:
415
+ vae_ref_image = []
416
+ for item in ref_image:
417
+ target_size = (width, height)
418
+ item = ImageOps.pad(item, target_size, color="white", centering=(0.5, 0.5))
419
+ ref_tensor = self._preprocess_video([item], dtype=torch.float32, device=device)
420
+ ref_latent = self.vae.encode(ref_tensor).latent_dist.sample()
421
+ vae_ref_image.append(ref_latent.to(dtype=dtype))
422
+
423
+ # --- 8. Handle input_video (video-to-video) ---
424
+ if input_video is not None:
425
+ input_tensor = self._preprocess_video(input_video, dtype=torch.float32, device=device)
426
+ input_latents = self.vae.encode(input_tensor).latent_dist.sample()
427
+ input_latents = input_latents.to(dtype=dtype)
428
+ latents = self._scheduler_add_noise(input_latents, noise, sigmas, 0)
429
+ else:
430
+ latents = noise
431
+
432
+ # --- 9. Denoising loop ---
433
+ for step_idx, timestep_val in enumerate(progress_bar(timesteps)):
434
+ timestep = timestep_val.unsqueeze(0).to(dtype=dtype, device=device)
435
+
436
+ # Positive prediction
437
+ noise_pred = self._model_forward(
438
+ latents=latents,
439
+ timestep=timestep,
440
+ context=context,
441
+ vae_source_input=vae_source_input,
442
+ vae_ref_image=vae_ref_image,
443
+ sigmas=sigmas,
444
+ timesteps_schedule=timesteps,
445
+ )
446
+
447
+ # CFG
448
+ # if guidance_scale != 1.0:
449
+ # noise_pred_nega = self._model_forward(
450
+ # latents=latents,
451
+ # timestep=timestep,
452
+ # context=context_nega,
453
+ # vae_source_input=vae_source_input,
454
+ # vae_ref_image=vae_ref_image,
455
+ # sigmas=sigmas,
456
+ # timesteps_schedule=timesteps,
457
+ # )
458
+ # noise_pred = noise_pred_nega + guidance_scale * (
459
+ # noise_pred_posi - noise_pred_nega
460
+ # )
461
+ # else:
462
+ # noise_pred = noise_pred_posi
463
+
464
+ # Scheduler step
465
+ latents = self._scheduler_step(noise_pred, sigmas, step_idx, latents)
466
+
467
+ # --- 10. Decode ---
468
+ if output_type == "latent":
469
+ return latents
470
+
471
+ video = self.vae.decode(latents).sample
472
+ video = self._vae_output_to_video(video)
473
+ return video
ref_embedder/conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
source_embedder/conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
vae/wan_video_vae.py ADDED
@@ -0,0 +1,1486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+
4
+ from einops import rearrange, repeat
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from tqdm import tqdm
10
+ from diffusers import ModelMixin, ConfigMixin
11
+ from diffusers.configuration_utils import register_to_config
12
+
13
+ CACHE_T = 2
14
+
15
+
16
+ def check_is_instance(model, module_class):
17
+ if isinstance(model, module_class):
18
+ return True
19
+ if hasattr(model, "module") and isinstance(model.module, module_class):
20
+ return True
21
+ return False
22
+
23
+
24
+ def block_causal_mask(x, block_size):
25
+ # params
26
+ b, n, s, _, device = *x.size(), x.device
27
+ assert s % block_size == 0
28
+ num_blocks = s // block_size
29
+
30
+ # build mask
31
+ mask = torch.zeros(b, n, s, s, dtype=torch.bool, device=device)
32
+ for i in range(num_blocks):
33
+ mask[:, :,
34
+ i * block_size:(i + 1) * block_size, :(i + 1) * block_size] = 1
35
+ return mask
36
+
37
+
38
+ class CausalConv3d(nn.Conv3d):
39
+ """
40
+ Causal 3d convolusion.
41
+ """
42
+
43
+ def __init__(self, *args, **kwargs):
44
+ super().__init__(*args, **kwargs)
45
+ self._padding = (self.padding[2], self.padding[2], self.padding[1],
46
+ self.padding[1], 2 * self.padding[0], 0)
47
+ self.padding = (0, 0, 0)
48
+
49
+ def forward(self, x, cache_x=None):
50
+ padding = list(self._padding)
51
+ if cache_x is not None and self._padding[4] > 0:
52
+ cache_x = cache_x.to(x.device)
53
+ x = torch.cat([cache_x, x], dim=2)
54
+ padding[4] -= cache_x.shape[2]
55
+ x = F.pad(x, padding)
56
+
57
+ return super().forward(x)
58
+
59
+
60
+ class RMS_norm(nn.Module):
61
+
62
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
63
+ super().__init__()
64
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
65
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
66
+
67
+ self.channel_first = channel_first
68
+ self.scale = dim**0.5
69
+ self.gamma = nn.Parameter(torch.ones(shape))
70
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
71
+
72
+ def forward(self, x):
73
+ return F.normalize(
74
+ x, dim=(1 if self.channel_first else
75
+ -1)) * self.scale * self.gamma + self.bias
76
+
77
+
78
+ class Upsample(nn.Upsample):
79
+
80
+ def forward(self, x):
81
+ """
82
+ Fix bfloat16 support for nearest neighbor interpolation.
83
+ """
84
+ return super().forward(x.float()).type_as(x)
85
+
86
+
87
+ class Resample(nn.Module):
88
+
89
+ def __init__(self, dim, mode):
90
+ assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d',
91
+ 'downsample3d')
92
+ super().__init__()
93
+ self.dim = dim
94
+ self.mode = mode
95
+
96
+ # layers
97
+ if mode == 'upsample2d':
98
+ self.resample = nn.Sequential(
99
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
100
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
101
+ elif mode == 'upsample3d':
102
+ self.resample = nn.Sequential(
103
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
104
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
105
+ self.time_conv = CausalConv3d(dim,
106
+ dim * 2, (3, 1, 1),
107
+ padding=(1, 0, 0))
108
+
109
+ elif mode == 'downsample2d':
110
+ self.resample = nn.Sequential(
111
+ nn.ZeroPad2d((0, 1, 0, 1)),
112
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
113
+ elif mode == 'downsample3d':
114
+ self.resample = nn.Sequential(
115
+ nn.ZeroPad2d((0, 1, 0, 1)),
116
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
117
+ self.time_conv = CausalConv3d(dim,
118
+ dim, (3, 1, 1),
119
+ stride=(2, 1, 1),
120
+ padding=(0, 0, 0))
121
+
122
+ else:
123
+ self.resample = nn.Identity()
124
+
125
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
126
+ b, c, t, h, w = x.size()
127
+ if self.mode == 'upsample3d':
128
+ if feat_cache is not None:
129
+ idx = feat_idx[0]
130
+ if feat_cache[idx] is None:
131
+ feat_cache[idx] = 'Rep'
132
+ feat_idx[0] += 1
133
+ else:
134
+
135
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
136
+ if cache_x.shape[2] < 2 and feat_cache[
137
+ idx] is not None and feat_cache[idx] != 'Rep':
138
+ # cache last frame of last two chunk
139
+ cache_x = torch.cat([
140
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
141
+ cache_x.device), cache_x
142
+ ],
143
+ dim=2)
144
+ if cache_x.shape[2] < 2 and feat_cache[
145
+ idx] is not None and feat_cache[idx] == 'Rep':
146
+ cache_x = torch.cat([
147
+ torch.zeros_like(cache_x).to(cache_x.device),
148
+ cache_x
149
+ ],
150
+ dim=2)
151
+ if feat_cache[idx] == 'Rep':
152
+ x = self.time_conv(x)
153
+ else:
154
+ x = self.time_conv(x, feat_cache[idx])
155
+ feat_cache[idx] = cache_x
156
+ feat_idx[0] += 1
157
+
158
+ x = x.reshape(b, 2, c, t, h, w)
159
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
160
+ 3)
161
+ x = x.reshape(b, c, t * 2, h, w)
162
+ t = x.shape[2]
163
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
164
+ x = self.resample(x)
165
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
166
+
167
+ if self.mode == 'downsample3d':
168
+ if feat_cache is not None:
169
+ idx = feat_idx[0]
170
+ if feat_cache[idx] is None:
171
+ feat_cache[idx] = x.clone()
172
+ feat_idx[0] += 1
173
+ else:
174
+ cache_x = x[:, :, -1:, :, :].clone()
175
+ x = self.time_conv(
176
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
177
+ feat_cache[idx] = cache_x
178
+ feat_idx[0] += 1
179
+ return x
180
+
181
+ def init_weight(self, conv):
182
+ conv_weight = conv.weight
183
+ nn.init.zeros_(conv_weight)
184
+ c1, c2, t, h, w = conv_weight.size()
185
+ one_matrix = torch.eye(c1, c2)
186
+ init_matrix = one_matrix
187
+ nn.init.zeros_(conv_weight)
188
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix
189
+ conv.weight.data.copy_(conv_weight)
190
+ nn.init.zeros_(conv.bias.data)
191
+
192
+ def init_weight2(self, conv):
193
+ conv_weight = conv.weight.data
194
+ nn.init.zeros_(conv_weight)
195
+ c1, c2, t, h, w = conv_weight.size()
196
+ init_matrix = torch.eye(c1 // 2, c2)
197
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
198
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
199
+ conv.weight.data.copy_(conv_weight)
200
+ nn.init.zeros_(conv.bias.data)
201
+
202
+
203
+
204
+ def patchify(x, patch_size):
205
+ if patch_size == 1:
206
+ return x
207
+ if x.dim() == 4:
208
+ x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
209
+ elif x.dim() == 5:
210
+ x = rearrange(x,
211
+ "b c f (h q) (w r) -> b (c r q) f h w",
212
+ q=patch_size,
213
+ r=patch_size)
214
+ else:
215
+ raise ValueError(f"Invalid input shape: {x.shape}")
216
+ return x
217
+
218
+
219
+ def unpatchify(x, patch_size):
220
+ if patch_size == 1:
221
+ return x
222
+ if x.dim() == 4:
223
+ x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
224
+ elif x.dim() == 5:
225
+ x = rearrange(x,
226
+ "b (c r q) f h w -> b c f (h q) (w r)",
227
+ q=patch_size,
228
+ r=patch_size)
229
+ return x
230
+
231
+
232
+ class Resample38(Resample):
233
+
234
+ def __init__(self, dim, mode):
235
+ assert mode in (
236
+ "none",
237
+ "upsample2d",
238
+ "upsample3d",
239
+ "downsample2d",
240
+ "downsample3d",
241
+ )
242
+ super(Resample, self).__init__()
243
+ self.dim = dim
244
+ self.mode = mode
245
+
246
+ # layers
247
+ if mode == "upsample2d":
248
+ self.resample = nn.Sequential(
249
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
250
+ nn.Conv2d(dim, dim, 3, padding=1),
251
+ )
252
+ elif mode == "upsample3d":
253
+ self.resample = nn.Sequential(
254
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
255
+ nn.Conv2d(dim, dim, 3, padding=1),
256
+ )
257
+ self.time_conv = CausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
258
+ elif mode == "downsample2d":
259
+ self.resample = nn.Sequential(
260
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
261
+ )
262
+ elif mode == "downsample3d":
263
+ self.resample = nn.Sequential(
264
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
265
+ )
266
+ self.time_conv = CausalConv3d(
267
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)
268
+ )
269
+ else:
270
+ self.resample = nn.Identity()
271
+
272
+ class ResidualBlock(nn.Module):
273
+
274
+ def __init__(self, in_dim, out_dim, dropout=0.0):
275
+ super().__init__()
276
+ self.in_dim = in_dim
277
+ self.out_dim = out_dim
278
+
279
+ # layers
280
+ self.residual = nn.Sequential(
281
+ RMS_norm(in_dim, images=False), nn.SiLU(),
282
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
283
+ RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout),
284
+ CausalConv3d(out_dim, out_dim, 3, padding=1))
285
+ self.shortcut = CausalConv3d(in_dim, out_dim, 1) \
286
+ if in_dim != out_dim else nn.Identity()
287
+
288
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
289
+ h = self.shortcut(x)
290
+ for layer in self.residual:
291
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
292
+ idx = feat_idx[0]
293
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
294
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
295
+ # cache last frame of last two chunk
296
+ cache_x = torch.cat([
297
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
298
+ cache_x.device), cache_x
299
+ ],
300
+ dim=2)
301
+ x = layer(x, feat_cache[idx])
302
+ feat_cache[idx] = cache_x
303
+ feat_idx[0] += 1
304
+ else:
305
+ x = layer(x)
306
+ return x + h
307
+
308
+
309
+ class AttentionBlock(nn.Module):
310
+ """
311
+ Causal self-attention with a single head.
312
+ """
313
+
314
+ def __init__(self, dim):
315
+ super().__init__()
316
+ self.dim = dim
317
+
318
+ # layers
319
+ self.norm = RMS_norm(dim)
320
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
321
+ self.proj = nn.Conv2d(dim, dim, 1)
322
+
323
+ # zero out the last layer params
324
+ nn.init.zeros_(self.proj.weight)
325
+
326
+ def forward(self, x):
327
+ identity = x
328
+ b, c, t, h, w = x.size()
329
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
330
+ x = self.norm(x)
331
+ # compute query, key, value
332
+ q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, -1).permute(
333
+ 0, 1, 3, 2).contiguous().chunk(3, dim=-1)
334
+
335
+ # apply attention
336
+ x = F.scaled_dot_product_attention(
337
+ q,
338
+ k,
339
+ v,
340
+ #attn_mask=block_causal_mask(q, block_size=h * w)
341
+ )
342
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
343
+
344
+ # output
345
+ x = self.proj(x)
346
+ x = rearrange(x, '(b t) c h w-> b c t h w', t=t)
347
+ return x + identity
348
+
349
+
350
+ class AvgDown3D(nn.Module):
351
+ def __init__(
352
+ self,
353
+ in_channels,
354
+ out_channels,
355
+ factor_t,
356
+ factor_s=1,
357
+ ):
358
+ super().__init__()
359
+ self.in_channels = in_channels
360
+ self.out_channels = out_channels
361
+ self.factor_t = factor_t
362
+ self.factor_s = factor_s
363
+ self.factor = self.factor_t * self.factor_s * self.factor_s
364
+
365
+ assert in_channels * self.factor % out_channels == 0
366
+ self.group_size = in_channels * self.factor // out_channels
367
+
368
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
369
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
370
+ pad = (0, 0, 0, 0, pad_t, 0)
371
+ x = F.pad(x, pad)
372
+ B, C, T, H, W = x.shape
373
+ x = x.view(
374
+ B,
375
+ C,
376
+ T // self.factor_t,
377
+ self.factor_t,
378
+ H // self.factor_s,
379
+ self.factor_s,
380
+ W // self.factor_s,
381
+ self.factor_s,
382
+ )
383
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
384
+ x = x.view(
385
+ B,
386
+ C * self.factor,
387
+ T // self.factor_t,
388
+ H // self.factor_s,
389
+ W // self.factor_s,
390
+ )
391
+ x = x.view(
392
+ B,
393
+ self.out_channels,
394
+ self.group_size,
395
+ T // self.factor_t,
396
+ H // self.factor_s,
397
+ W // self.factor_s,
398
+ )
399
+ x = x.mean(dim=2)
400
+ return x
401
+
402
+
403
+ class DupUp3D(nn.Module):
404
+ def __init__(
405
+ self,
406
+ in_channels: int,
407
+ out_channels: int,
408
+ factor_t,
409
+ factor_s=1,
410
+ ):
411
+ super().__init__()
412
+ self.in_channels = in_channels
413
+ self.out_channels = out_channels
414
+
415
+ self.factor_t = factor_t
416
+ self.factor_s = factor_s
417
+ self.factor = self.factor_t * self.factor_s * self.factor_s
418
+
419
+ assert out_channels * self.factor % in_channels == 0
420
+ self.repeats = out_channels * self.factor // in_channels
421
+
422
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
423
+ x = x.repeat_interleave(self.repeats, dim=1)
424
+ x = x.view(
425
+ x.size(0),
426
+ self.out_channels,
427
+ self.factor_t,
428
+ self.factor_s,
429
+ self.factor_s,
430
+ x.size(2),
431
+ x.size(3),
432
+ x.size(4),
433
+ )
434
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
435
+ x = x.view(
436
+ x.size(0),
437
+ self.out_channels,
438
+ x.size(2) * self.factor_t,
439
+ x.size(4) * self.factor_s,
440
+ x.size(6) * self.factor_s,
441
+ )
442
+ if first_chunk:
443
+ x = x[:, :, self.factor_t - 1 :, :, :]
444
+ return x
445
+
446
+
447
+ class Down_ResidualBlock(nn.Module):
448
+ def __init__(
449
+ self, in_dim, out_dim, dropout, mult, temperal_downsample=False, down_flag=False
450
+ ):
451
+ super().__init__()
452
+
453
+ # Shortcut path with downsample
454
+ self.avg_shortcut = AvgDown3D(
455
+ in_dim,
456
+ out_dim,
457
+ factor_t=2 if temperal_downsample else 1,
458
+ factor_s=2 if down_flag else 1,
459
+ )
460
+
461
+ # Main path with residual blocks and downsample
462
+ downsamples = []
463
+ for _ in range(mult):
464
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
465
+ in_dim = out_dim
466
+
467
+ # Add the final downsample block
468
+ if down_flag:
469
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
470
+ downsamples.append(Resample38(out_dim, mode=mode))
471
+
472
+ self.downsamples = nn.Sequential(*downsamples)
473
+
474
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
475
+ x_copy = x.clone()
476
+ for module in self.downsamples:
477
+ x = module(x, feat_cache, feat_idx)
478
+
479
+ return x + self.avg_shortcut(x_copy)
480
+
481
+
482
+ class Up_ResidualBlock(nn.Module):
483
+ def __init__(
484
+ self, in_dim, out_dim, dropout, mult, temperal_upsample=False, up_flag=False
485
+ ):
486
+ super().__init__()
487
+ # Shortcut path with upsample
488
+ if up_flag:
489
+ self.avg_shortcut = DupUp3D(
490
+ in_dim,
491
+ out_dim,
492
+ factor_t=2 if temperal_upsample else 1,
493
+ factor_s=2 if up_flag else 1,
494
+ )
495
+ else:
496
+ self.avg_shortcut = None
497
+
498
+ # Main path with residual blocks and upsample
499
+ upsamples = []
500
+ for _ in range(mult):
501
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
502
+ in_dim = out_dim
503
+
504
+ # Add the final upsample block
505
+ if up_flag:
506
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
507
+ upsamples.append(Resample38(out_dim, mode=mode))
508
+
509
+ self.upsamples = nn.Sequential(*upsamples)
510
+
511
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
512
+ x_main = x.clone()
513
+ for module in self.upsamples:
514
+ x_main = module(x_main, feat_cache, feat_idx)
515
+ if self.avg_shortcut is not None:
516
+ x_shortcut = self.avg_shortcut(x, first_chunk)
517
+ return x_main + x_shortcut
518
+ else:
519
+ return x_main
520
+
521
+
522
+ class Encoder3d(nn.Module):
523
+
524
+ def __init__(self,
525
+ dim=128,
526
+ z_dim=4,
527
+ dim_mult=[1, 2, 4, 4],
528
+ num_res_blocks=2,
529
+ attn_scales=[],
530
+ temperal_downsample=[True, True, False],
531
+ dropout=0.0):
532
+ super().__init__()
533
+ self.dim = dim
534
+ self.z_dim = z_dim
535
+ self.dim_mult = dim_mult
536
+ self.num_res_blocks = num_res_blocks
537
+ self.attn_scales = attn_scales
538
+ self.temperal_downsample = temperal_downsample
539
+
540
+ # dimensions
541
+ dims = [dim * u for u in [1] + dim_mult]
542
+ scale = 1.0
543
+
544
+ # init block
545
+ self.conv1 = CausalConv3d(3, dims[0], 3, padding=1)
546
+
547
+ # downsample blocks
548
+ downsamples = []
549
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
550
+ # residual (+attention) blocks
551
+ for _ in range(num_res_blocks):
552
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
553
+ if scale in attn_scales:
554
+ downsamples.append(AttentionBlock(out_dim))
555
+ in_dim = out_dim
556
+
557
+ # downsample block
558
+ if i != len(dim_mult) - 1:
559
+ mode = 'downsample3d' if temperal_downsample[
560
+ i] else 'downsample2d'
561
+ downsamples.append(Resample(out_dim, mode=mode))
562
+ scale /= 2.0
563
+ self.downsamples = nn.Sequential(*downsamples)
564
+
565
+ # middle blocks
566
+ self.middle = nn.Sequential(ResidualBlock(out_dim, out_dim, dropout),
567
+ AttentionBlock(out_dim),
568
+ ResidualBlock(out_dim, out_dim, dropout))
569
+
570
+ # output blocks
571
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
572
+ CausalConv3d(out_dim, z_dim, 3, padding=1))
573
+
574
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
575
+ if feat_cache is not None:
576
+ idx = feat_idx[0]
577
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
578
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
579
+ # cache last frame of last two chunk
580
+ cache_x = torch.cat([
581
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
582
+ cache_x.device), cache_x
583
+ ],
584
+ dim=2)
585
+ x = self.conv1(x, feat_cache[idx])
586
+ feat_cache[idx] = cache_x
587
+ feat_idx[0] += 1
588
+ else:
589
+ x = self.conv1(x)
590
+
591
+ ## downsamples
592
+ for layer in self.downsamples:
593
+ if feat_cache is not None:
594
+ x = layer(x, feat_cache, feat_idx)
595
+ else:
596
+ x = layer(x)
597
+
598
+ ## middle
599
+ for layer in self.middle:
600
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
601
+ x = layer(x, feat_cache, feat_idx)
602
+ else:
603
+ x = layer(x)
604
+
605
+ ## head
606
+ for layer in self.head:
607
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
608
+ idx = feat_idx[0]
609
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
610
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
611
+ # cache last frame of last two chunk
612
+ cache_x = torch.cat([
613
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
614
+ cache_x.device), cache_x
615
+ ],
616
+ dim=2)
617
+ x = layer(x, feat_cache[idx])
618
+ feat_cache[idx] = cache_x
619
+ feat_idx[0] += 1
620
+ else:
621
+ x = layer(x)
622
+ return x
623
+
624
+
625
+ class Encoder3d_38(nn.Module):
626
+
627
+ def __init__(self,
628
+ dim=128,
629
+ z_dim=4,
630
+ dim_mult=[1, 2, 4, 4],
631
+ num_res_blocks=2,
632
+ attn_scales=[],
633
+ temperal_downsample=[False, True, True],
634
+ dropout=0.0):
635
+ super().__init__()
636
+ self.dim = dim
637
+ self.z_dim = z_dim
638
+ self.dim_mult = dim_mult
639
+ self.num_res_blocks = num_res_blocks
640
+ self.attn_scales = attn_scales
641
+ self.temperal_downsample = temperal_downsample
642
+
643
+ # dimensions
644
+ dims = [dim * u for u in [1] + dim_mult]
645
+ scale = 1.0
646
+
647
+ # init block
648
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
649
+
650
+ # downsample blocks
651
+ downsamples = []
652
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
653
+ t_down_flag = (
654
+ temperal_downsample[i] if i < len(temperal_downsample) else False
655
+ )
656
+ downsamples.append(
657
+ Down_ResidualBlock(
658
+ in_dim=in_dim,
659
+ out_dim=out_dim,
660
+ dropout=dropout,
661
+ mult=num_res_blocks,
662
+ temperal_downsample=t_down_flag,
663
+ down_flag=i != len(dim_mult) - 1,
664
+ )
665
+ )
666
+ scale /= 2.0
667
+ self.downsamples = nn.Sequential(*downsamples)
668
+
669
+ # middle blocks
670
+ self.middle = nn.Sequential(
671
+ ResidualBlock(out_dim, out_dim, dropout),
672
+ AttentionBlock(out_dim),
673
+ ResidualBlock(out_dim, out_dim, dropout),
674
+ )
675
+
676
+ # # output blocks
677
+ self.head = nn.Sequential(
678
+ RMS_norm(out_dim, images=False),
679
+ nn.SiLU(),
680
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
681
+ )
682
+
683
+
684
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
685
+
686
+ if feat_cache is not None:
687
+ idx = feat_idx[0]
688
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
689
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
690
+ cache_x = torch.cat(
691
+ [
692
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
693
+ cache_x,
694
+ ],
695
+ dim=2,
696
+ )
697
+ x = self.conv1(x, feat_cache[idx])
698
+ feat_cache[idx] = cache_x
699
+ feat_idx[0] += 1
700
+ else:
701
+ x = self.conv1(x)
702
+
703
+ ## downsamples
704
+ for layer in self.downsamples:
705
+ if feat_cache is not None:
706
+ x = layer(x, feat_cache, feat_idx)
707
+ else:
708
+ x = layer(x)
709
+
710
+ ## middle
711
+ for layer in self.middle:
712
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
713
+ x = layer(x, feat_cache, feat_idx)
714
+ else:
715
+ x = layer(x)
716
+
717
+ ## head
718
+ for layer in self.head:
719
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
720
+ idx = feat_idx[0]
721
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
722
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
723
+ cache_x = torch.cat(
724
+ [
725
+ feat_cache[idx][:, :, -1, :, :]
726
+ .unsqueeze(2)
727
+ .to(cache_x.device),
728
+ cache_x,
729
+ ],
730
+ dim=2,
731
+ )
732
+ x = layer(x, feat_cache[idx])
733
+ feat_cache[idx] = cache_x
734
+ feat_idx[0] += 1
735
+ else:
736
+ x = layer(x)
737
+
738
+ return x
739
+
740
+
741
+ class Decoder3d(nn.Module):
742
+
743
+ def __init__(self,
744
+ dim=128,
745
+ z_dim=4,
746
+ dim_mult=[1, 2, 4, 4],
747
+ num_res_blocks=2,
748
+ attn_scales=[],
749
+ temperal_upsample=[False, True, True],
750
+ dropout=0.0):
751
+ super().__init__()
752
+ self.dim = dim
753
+ self.z_dim = z_dim
754
+ self.dim_mult = dim_mult
755
+ self.num_res_blocks = num_res_blocks
756
+ self.attn_scales = attn_scales
757
+ self.temperal_upsample = temperal_upsample
758
+
759
+ # dimensions
760
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
761
+ scale = 1.0 / 2**(len(dim_mult) - 2)
762
+
763
+ # init block
764
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
765
+
766
+ # middle blocks
767
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
768
+ AttentionBlock(dims[0]),
769
+ ResidualBlock(dims[0], dims[0], dropout))
770
+
771
+ # upsample blocks
772
+ upsamples = []
773
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
774
+ # residual (+attention) blocks
775
+ if i == 1 or i == 2 or i == 3:
776
+ in_dim = in_dim // 2
777
+ for _ in range(num_res_blocks + 1):
778
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
779
+ if scale in attn_scales:
780
+ upsamples.append(AttentionBlock(out_dim))
781
+ in_dim = out_dim
782
+
783
+ # upsample block
784
+ if i != len(dim_mult) - 1:
785
+ mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d'
786
+ upsamples.append(Resample(out_dim, mode=mode))
787
+ scale *= 2.0
788
+ self.upsamples = nn.Sequential(*upsamples)
789
+
790
+ # output blocks
791
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
792
+ CausalConv3d(out_dim, 3, 3, padding=1))
793
+
794
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
795
+ ## conv1
796
+ if feat_cache is not None:
797
+ idx = feat_idx[0]
798
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
799
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
800
+ # cache last frame of last two chunk
801
+ cache_x = torch.cat([
802
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
803
+ cache_x.device), cache_x
804
+ ],
805
+ dim=2)
806
+ x = self.conv1(x, feat_cache[idx])
807
+ feat_cache[idx] = cache_x
808
+ feat_idx[0] += 1
809
+ else:
810
+ x = self.conv1(x)
811
+
812
+ ## middle
813
+ for layer in self.middle:
814
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
815
+ x = layer(x, feat_cache, feat_idx)
816
+ else:
817
+ x = layer(x)
818
+
819
+ ## upsamples
820
+ for layer in self.upsamples:
821
+ if feat_cache is not None:
822
+ x = layer(x, feat_cache, feat_idx)
823
+ else:
824
+ x = layer(x)
825
+
826
+ ## head
827
+ for layer in self.head:
828
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
829
+ idx = feat_idx[0]
830
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
831
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
832
+ # cache last frame of last two chunk
833
+ cache_x = torch.cat([
834
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
835
+ cache_x.device), cache_x
836
+ ],
837
+ dim=2)
838
+ x = layer(x, feat_cache[idx])
839
+ feat_cache[idx] = cache_x
840
+ feat_idx[0] += 1
841
+ else:
842
+ x = layer(x)
843
+ return x
844
+
845
+
846
+
847
+ class Decoder3d_38(nn.Module):
848
+
849
+ def __init__(self,
850
+ dim=128,
851
+ z_dim=4,
852
+ dim_mult=[1, 2, 4, 4],
853
+ num_res_blocks=2,
854
+ attn_scales=[],
855
+ temperal_upsample=[False, True, True],
856
+ dropout=0.0):
857
+ super().__init__()
858
+ self.dim = dim
859
+ self.z_dim = z_dim
860
+ self.dim_mult = dim_mult
861
+ self.num_res_blocks = num_res_blocks
862
+ self.attn_scales = attn_scales
863
+ self.temperal_upsample = temperal_upsample
864
+
865
+ # dimensions
866
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
867
+ scale = 1.0 / 2 ** (len(dim_mult) - 2)
868
+ # init block
869
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
870
+
871
+ # middle blocks
872
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
873
+ AttentionBlock(dims[0]),
874
+ ResidualBlock(dims[0], dims[0], dropout))
875
+
876
+ # upsample blocks
877
+ upsamples = []
878
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
879
+ t_up_flag = temperal_upsample[i] if i < len(temperal_upsample) else False
880
+ upsamples.append(
881
+ Up_ResidualBlock(in_dim=in_dim,
882
+ out_dim=out_dim,
883
+ dropout=dropout,
884
+ mult=num_res_blocks + 1,
885
+ temperal_upsample=t_up_flag,
886
+ up_flag=i != len(dim_mult) - 1))
887
+ self.upsamples = nn.Sequential(*upsamples)
888
+
889
+ # output blocks
890
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
891
+ CausalConv3d(out_dim, 12, 3, padding=1))
892
+
893
+
894
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
895
+ if feat_cache is not None:
896
+ idx = feat_idx[0]
897
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
898
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
899
+ cache_x = torch.cat(
900
+ [
901
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
902
+ cache_x,
903
+ ],
904
+ dim=2,
905
+ )
906
+ x = self.conv1(x, feat_cache[idx])
907
+ feat_cache[idx] = cache_x
908
+ feat_idx[0] += 1
909
+ else:
910
+ x = self.conv1(x)
911
+
912
+ for layer in self.middle:
913
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
914
+ x = layer(x, feat_cache, feat_idx)
915
+ else:
916
+ x = layer(x)
917
+
918
+ ## upsamples
919
+ for layer in self.upsamples:
920
+ if feat_cache is not None:
921
+ x = layer(x, feat_cache, feat_idx, first_chunk)
922
+ else:
923
+ x = layer(x)
924
+
925
+ ## head
926
+ for layer in self.head:
927
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
928
+ idx = feat_idx[0]
929
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
930
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
931
+ cache_x = torch.cat(
932
+ [
933
+ feat_cache[idx][:, :, -1, :, :]
934
+ .unsqueeze(2)
935
+ .to(cache_x.device),
936
+ cache_x,
937
+ ],
938
+ dim=2,
939
+ )
940
+ x = layer(x, feat_cache[idx])
941
+ feat_cache[idx] = cache_x
942
+ feat_idx[0] += 1
943
+ else:
944
+ x = layer(x)
945
+ return x
946
+
947
+
948
+ def count_conv3d(model):
949
+ count = 0
950
+ for m in model.modules():
951
+ if isinstance(m, CausalConv3d):
952
+ count += 1
953
+ return count
954
+
955
+
956
+ class VideoVAE_(nn.Module):
957
+
958
+ def __init__(self,
959
+ dim=96,
960
+ z_dim=16,
961
+ dim_mult=[1, 2, 4, 4],
962
+ num_res_blocks=2,
963
+ attn_scales=[],
964
+ temperal_downsample=[False, True, True],
965
+ dropout=0.0):
966
+ super().__init__()
967
+ self.dim = dim
968
+ self.z_dim = z_dim
969
+ self.dim_mult = dim_mult
970
+ self.num_res_blocks = num_res_blocks
971
+ self.attn_scales = attn_scales
972
+ self.temperal_downsample = temperal_downsample
973
+ self.temperal_upsample = temperal_downsample[::-1]
974
+
975
+ # modules
976
+ self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,
977
+ attn_scales, self.temperal_downsample, dropout)
978
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
979
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
980
+ self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,
981
+ attn_scales, self.temperal_upsample, dropout)
982
+
983
+ def forward(self, x):
984
+ mu, log_var = self.encode(x)
985
+ z = self.reparameterize(mu, log_var)
986
+ x_recon = self.decode(z)
987
+ return x_recon, mu, log_var
988
+
989
+ def encode(self, x, scale):
990
+ self.clear_cache()
991
+ ## cache
992
+ t = x.shape[2]
993
+ iter_ = 1 + (t - 1) // 4
994
+
995
+ for i in range(iter_):
996
+ self._enc_conv_idx = [0]
997
+ if i == 0:
998
+ out = self.encoder(x[:, :, :1, :, :],
999
+ feat_cache=self._enc_feat_map,
1000
+ feat_idx=self._enc_conv_idx)
1001
+ else:
1002
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1003
+ feat_cache=self._enc_feat_map,
1004
+ feat_idx=self._enc_conv_idx)
1005
+ out = torch.cat([out, out_], 2)
1006
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1007
+ if isinstance(scale[0], torch.Tensor):
1008
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1009
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1010
+ 1, self.z_dim, 1, 1, 1)
1011
+ else:
1012
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1013
+ mu = (mu - scale[0]) * scale[1]
1014
+ return mu
1015
+
1016
+ def decode(self, z, scale):
1017
+ self.clear_cache()
1018
+ # z: [b,c,t,h,w]
1019
+ if isinstance(scale[0], torch.Tensor):
1020
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1021
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1022
+ 1, self.z_dim, 1, 1, 1)
1023
+ else:
1024
+ scale = scale.to(dtype=z.dtype, device=z.device)
1025
+ z = z / scale[1] + scale[0]
1026
+ iter_ = z.shape[2]
1027
+ x = self.conv2(z)
1028
+ for i in range(iter_):
1029
+ self._conv_idx = [0]
1030
+ if i == 0:
1031
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1032
+ feat_cache=self._feat_map,
1033
+ feat_idx=self._conv_idx)
1034
+ else:
1035
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1036
+ feat_cache=self._feat_map,
1037
+ feat_idx=self._conv_idx)
1038
+ out = torch.cat([out, out_], 2) # may add tensor offload
1039
+ return out
1040
+
1041
+ def reparameterize(self, mu, log_var):
1042
+ std = torch.exp(0.5 * log_var)
1043
+ eps = torch.randn_like(std)
1044
+ return eps * std + mu
1045
+
1046
+ def sample(self, imgs, deterministic=False):
1047
+ mu, log_var = self.encode(imgs)
1048
+ if deterministic:
1049
+ return mu
1050
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
1051
+ return mu + std * torch.randn_like(std)
1052
+
1053
+ def clear_cache(self):
1054
+ self._conv_num = count_conv3d(self.decoder)
1055
+ self._conv_idx = [0]
1056
+ self._feat_map = [None] * self._conv_num
1057
+ # cache encode
1058
+ self._enc_conv_num = count_conv3d(self.encoder)
1059
+ self._enc_conv_idx = [0]
1060
+ self._enc_feat_map = [None] * self._enc_conv_num
1061
+
1062
+
1063
+ class WanVideoVAE(nn.Module):
1064
+
1065
+ def __init__(self, z_dim=16):
1066
+ super().__init__()
1067
+
1068
+ mean = [
1069
+ -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
1070
+ 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
1071
+ ]
1072
+ std = [
1073
+ 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
1074
+ 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
1075
+ ]
1076
+ self.mean = torch.tensor(mean)
1077
+ self.std = torch.tensor(std)
1078
+ self.scale = [self.mean, 1.0 / self.std]
1079
+
1080
+ # init model
1081
+ self.model = VideoVAE_(z_dim=z_dim).eval().requires_grad_(False)
1082
+ self.upsampling_factor = 8
1083
+ self.z_dim = z_dim
1084
+
1085
+
1086
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
1087
+ x = torch.ones((length,))
1088
+ if not left_bound:
1089
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
1090
+ if not right_bound:
1091
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
1092
+ return x
1093
+
1094
+
1095
+ def build_mask(self, data, is_bound, border_width):
1096
+ _, _, _, H, W = data.shape
1097
+ h = self.build_1d_mask(H, is_bound[0], is_bound[1], border_width[0])
1098
+ w = self.build_1d_mask(W, is_bound[2], is_bound[3], border_width[1])
1099
+
1100
+ h = repeat(h, "H -> H W", H=H, W=W)
1101
+ w = repeat(w, "W -> H W", H=H, W=W)
1102
+
1103
+ mask = torch.stack([h, w]).min(dim=0).values
1104
+ mask = rearrange(mask, "H W -> 1 1 1 H W")
1105
+ return mask
1106
+
1107
+
1108
+ def tiled_decode(self, hidden_states, device, tile_size, tile_stride):
1109
+ _, _, T, H, W = hidden_states.shape
1110
+ size_h, size_w = tile_size
1111
+ stride_h, stride_w = tile_stride
1112
+
1113
+ # Split tasks
1114
+ tasks = []
1115
+ for h in range(0, H, stride_h):
1116
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1117
+ for w in range(0, W, stride_w):
1118
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1119
+ h_, w_ = h + size_h, w + size_w
1120
+ tasks.append((h, h_, w, w_))
1121
+
1122
+ data_device = "cpu"
1123
+ computation_device = device
1124
+
1125
+ out_T = T * 4 - 3
1126
+ weight = torch.zeros((1, 1, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1127
+ values = torch.zeros((1, 3, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1128
+
1129
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"):
1130
+ hidden_states_batch = hidden_states[:, :, :, h:h_, w:w_].to(computation_device)
1131
+ hidden_states_batch = self.model.decode(hidden_states_batch, self.scale).to(data_device)
1132
+
1133
+ mask = self.build_mask(
1134
+ hidden_states_batch,
1135
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1136
+ border_width=((size_h - stride_h) * self.upsampling_factor, (size_w - stride_w) * self.upsampling_factor)
1137
+ ).to(dtype=hidden_states.dtype, device=data_device)
1138
+
1139
+ target_h = h * self.upsampling_factor
1140
+ target_w = w * self.upsampling_factor
1141
+ values[
1142
+ :,
1143
+ :,
1144
+ :,
1145
+ target_h:target_h + hidden_states_batch.shape[3],
1146
+ target_w:target_w + hidden_states_batch.shape[4],
1147
+ ] += hidden_states_batch * mask
1148
+ weight[
1149
+ :,
1150
+ :,
1151
+ :,
1152
+ target_h: target_h + hidden_states_batch.shape[3],
1153
+ target_w: target_w + hidden_states_batch.shape[4],
1154
+ ] += mask
1155
+ values = values / weight
1156
+ values = values.clamp_(-1, 1)
1157
+ return values
1158
+
1159
+
1160
+ def tiled_encode(self, video, device, tile_size, tile_stride):
1161
+ _, _, T, H, W = video.shape
1162
+ size_h, size_w = tile_size
1163
+ stride_h, stride_w = tile_stride
1164
+
1165
+ # Split tasks
1166
+ tasks = []
1167
+ for h in range(0, H, stride_h):
1168
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1169
+ for w in range(0, W, stride_w):
1170
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1171
+ h_, w_ = h + size_h, w + size_w
1172
+ tasks.append((h, h_, w, w_))
1173
+
1174
+ data_device = "cpu"
1175
+ computation_device = device
1176
+
1177
+ out_T = (T + 3) // 4
1178
+ weight = torch.zeros((1, 1, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1179
+ values = torch.zeros((1, self.z_dim, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1180
+
1181
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"):
1182
+ hidden_states_batch = video[:, :, :, h:h_, w:w_].to(computation_device)
1183
+ hidden_states_batch = self.model.encode(hidden_states_batch, self.scale).to(data_device)
1184
+
1185
+ mask = self.build_mask(
1186
+ hidden_states_batch,
1187
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1188
+ border_width=((size_h - stride_h) // self.upsampling_factor, (size_w - stride_w) // self.upsampling_factor)
1189
+ ).to(dtype=video.dtype, device=data_device)
1190
+
1191
+ target_h = h // self.upsampling_factor
1192
+ target_w = w // self.upsampling_factor
1193
+ values[
1194
+ :,
1195
+ :,
1196
+ :,
1197
+ target_h:target_h + hidden_states_batch.shape[3],
1198
+ target_w:target_w + hidden_states_batch.shape[4],
1199
+ ] += hidden_states_batch * mask
1200
+ weight[
1201
+ :,
1202
+ :,
1203
+ :,
1204
+ target_h: target_h + hidden_states_batch.shape[3],
1205
+ target_w: target_w + hidden_states_batch.shape[4],
1206
+ ] += mask
1207
+ values = values / weight
1208
+ return values
1209
+
1210
+
1211
+ def single_encode(self, video, device):
1212
+ video = video.to(device)
1213
+ x = self.model.encode(video, self.scale)
1214
+ return x
1215
+
1216
+
1217
+ def single_decode(self, hidden_state, device):
1218
+ hidden_state = hidden_state.to(device)
1219
+ video = self.model.decode(hidden_state, self.scale)
1220
+ return video.clamp_(-1, 1)
1221
+
1222
+
1223
+ def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1224
+ videos = [video.to("cpu") for video in videos]
1225
+ hidden_states = []
1226
+ for video in videos:
1227
+ video = video.unsqueeze(0)
1228
+ if tiled:
1229
+ tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor)
1230
+ tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor)
1231
+ hidden_state = self.tiled_encode(video, device, tile_size, tile_stride)
1232
+ else:
1233
+ hidden_state = self.single_encode(video, device)
1234
+ hidden_state = hidden_state.squeeze(0)
1235
+ hidden_states.append(hidden_state)
1236
+ hidden_states = torch.stack(hidden_states)
1237
+ return hidden_states
1238
+
1239
+
1240
+ def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1241
+ hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states]
1242
+ videos = []
1243
+ for hidden_state in hidden_states:
1244
+ hidden_state = hidden_state.unsqueeze(0)
1245
+ if tiled:
1246
+ video = self.tiled_decode(hidden_state, device, tile_size, tile_stride)
1247
+ else:
1248
+ video = self.single_decode(hidden_state, device)
1249
+ video = video.squeeze(0)
1250
+ videos.append(video)
1251
+ videos = torch.stack(videos)
1252
+ return videos
1253
+
1254
+
1255
+ @staticmethod
1256
+ def state_dict_converter():
1257
+ return WanVideoVAEStateDictConverter()
1258
+
1259
+
1260
+ class WanVideoVAEStateDictConverter:
1261
+
1262
+ def __init__(self):
1263
+ pass
1264
+
1265
+ def from_civitai(self, state_dict):
1266
+ state_dict_ = {}
1267
+ if 'model_state' in state_dict:
1268
+ state_dict = state_dict['model_state']
1269
+ for name in state_dict:
1270
+ state_dict_['model.' + name] = state_dict[name]
1271
+ return state_dict_
1272
+
1273
+
1274
+ class VideoVAE38_(VideoVAE_):
1275
+
1276
+ def __init__(self,
1277
+ dim=160,
1278
+ z_dim=48,
1279
+ dec_dim=256,
1280
+ dim_mult=[1, 2, 4, 4],
1281
+ num_res_blocks=2,
1282
+ attn_scales=[],
1283
+ temperal_downsample=[False, True, True],
1284
+ dropout=0.0):
1285
+ super(VideoVAE_, self).__init__()
1286
+ self.dim = dim
1287
+ self.z_dim = z_dim
1288
+ self.dim_mult = dim_mult
1289
+ self.num_res_blocks = num_res_blocks
1290
+ self.attn_scales = attn_scales
1291
+ self.temperal_downsample = temperal_downsample
1292
+ self.temperal_upsample = temperal_downsample[::-1]
1293
+
1294
+ # modules
1295
+ self.encoder = Encoder3d_38(dim, z_dim * 2, dim_mult, num_res_blocks,
1296
+ attn_scales, self.temperal_downsample, dropout)
1297
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
1298
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
1299
+ self.decoder = Decoder3d_38(dec_dim, z_dim, dim_mult, num_res_blocks,
1300
+ attn_scales, self.temperal_upsample, dropout)
1301
+
1302
+
1303
+ def encode(self, x, scale):
1304
+ self.clear_cache()
1305
+ x = patchify(x, patch_size=2)
1306
+ t = x.shape[2]
1307
+ iter_ = 1 + (t - 1) // 4
1308
+ for i in range(iter_):
1309
+ self._enc_conv_idx = [0]
1310
+ if i == 0:
1311
+ out = self.encoder(x[:, :, :1, :, :],
1312
+ feat_cache=self._enc_feat_map,
1313
+ feat_idx=self._enc_conv_idx)
1314
+ else:
1315
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1316
+ feat_cache=self._enc_feat_map,
1317
+ feat_idx=self._enc_conv_idx)
1318
+ out = torch.cat([out, out_], 2)
1319
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1320
+ if isinstance(scale[0], torch.Tensor):
1321
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1322
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1323
+ 1, self.z_dim, 1, 1, 1)
1324
+ else:
1325
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1326
+ mu = (mu - scale[0]) * scale[1]
1327
+ self.clear_cache()
1328
+ return mu
1329
+
1330
+
1331
+ def decode(self, z, scale):
1332
+ self.clear_cache()
1333
+ if isinstance(scale[0], torch.Tensor):
1334
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1335
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1336
+ 1, self.z_dim, 1, 1, 1)
1337
+ else:
1338
+ scale = scale.to(dtype=z.dtype, device=z.device)
1339
+ z = z / scale[1] + scale[0]
1340
+ iter_ = z.shape[2]
1341
+ x = self.conv2(z)
1342
+ for i in range(iter_):
1343
+ self._conv_idx = [0]
1344
+ if i == 0:
1345
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1346
+ feat_cache=self._feat_map,
1347
+ feat_idx=self._conv_idx,
1348
+ first_chunk=True)
1349
+ else:
1350
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1351
+ feat_cache=self._feat_map,
1352
+ feat_idx=self._conv_idx)
1353
+ out = torch.cat([out, out_], 2)
1354
+ out = unpatchify(out, patch_size=2)
1355
+ self.clear_cache()
1356
+ return out
1357
+
1358
+
1359
+ class WanVideoVAE38(WanVideoVAE):
1360
+
1361
+ def __init__(self, z_dim=48, dim=160):
1362
+ super(WanVideoVAE, self).__init__()
1363
+
1364
+ mean = [
1365
+ -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
1366
+ -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
1367
+ -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
1368
+ -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
1369
+ -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
1370
+ 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667
1371
+ ]
1372
+ std = [
1373
+ 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
1374
+ 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
1375
+ 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
1376
+ 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
1377
+ 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
1378
+ 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744
1379
+ ]
1380
+ self.mean = torch.tensor(mean)
1381
+ self.std = torch.tensor(std)
1382
+ self.scale = [self.mean, 1.0 / self.std]
1383
+
1384
+ # init model
1385
+ self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False)
1386
+ self.upsampling_factor = 16
1387
+ self.z_dim = z_dim
1388
+
1389
+
1390
+ # ─────────────────────────────────────────────────────────────────────────────
1391
+ # Diffusers-compatible wrapper (formerly kiwi_vae.py)
1392
+ # ─────────────────────────────────��───────────────────────────────────────────
1393
+
1394
+ @dataclass
1395
+ class LatentDist:
1396
+ mu: torch.Tensor
1397
+
1398
+ def sample(self):
1399
+ return self.mu
1400
+
1401
+
1402
+ @dataclass
1403
+ class EncoderOutput:
1404
+ latent_dist: LatentDist
1405
+
1406
+
1407
+ @dataclass
1408
+ class DecoderOutput:
1409
+ sample: torch.Tensor
1410
+
1411
+
1412
+ class VAE(VideoVAE_, ModelMixin, ConfigMixin):
1413
+ """
1414
+ Diffusers-compatible VAE wrapper around the original Wan VideoVAE.
1415
+ Loads weights directly from diffusion_pytorch_model.safetensors.
1416
+ """
1417
+
1418
+ @register_to_config
1419
+ def __init__(
1420
+ self,
1421
+ z_dim: int = 48,
1422
+ dim: int = 160,
1423
+ dim_mult: List[int] = [1, 2, 4, 4],
1424
+ num_res_blocks: int = 2,
1425
+ attn_scales: List[float] = [],
1426
+ temperal_downsample: List[bool] = [False, True, True],
1427
+ dropout: float = 0.0,
1428
+ vae_pth: str = "wan_vae.pth",
1429
+ latents_mean: Optional[List[float]] = None,
1430
+ latents_std: Optional[List[float]] = None,
1431
+ ):
1432
+ # Build the actual VAE backbone so diffusers can load weights without mismatch.
1433
+ if z_dim == 48:
1434
+ VideoVAE38_.__init__(
1435
+ self,
1436
+ dim=dim,
1437
+ z_dim=z_dim,
1438
+ dim_mult=dim_mult,
1439
+ num_res_blocks=num_res_blocks,
1440
+ attn_scales=attn_scales,
1441
+ temperal_downsample=temperal_downsample,
1442
+ dropout=dropout,
1443
+ )
1444
+ self._use_38 = True
1445
+ self.upsampling_factor = 16
1446
+ else:
1447
+ VideoVAE_.__init__(
1448
+ self,
1449
+ dim=dim,
1450
+ z_dim=z_dim,
1451
+ dim_mult=dim_mult,
1452
+ num_res_blocks=num_res_blocks,
1453
+ attn_scales=attn_scales,
1454
+ temperal_downsample=temperal_downsample,
1455
+ dropout=dropout,
1456
+ )
1457
+ self._use_38 = False
1458
+ self.upsampling_factor = 8
1459
+
1460
+ # Keep for config compatibility; weights are loaded by diffusers.
1461
+ self._vae_pth = vae_pth
1462
+ self.z_dim = z_dim
1463
+
1464
+ # Build latent normalization scale: [mean, 1/std]
1465
+ if latents_mean is not None and latents_std is not None:
1466
+ mean = torch.tensor(latents_mean)
1467
+ std = torch.tensor(latents_std)
1468
+ self._scale = [mean, 1.0 / std]
1469
+ else:
1470
+ self._scale = [torch.zeros(z_dim), torch.ones(z_dim)]
1471
+
1472
+ def encode(self, x):
1473
+ x = x.to(dtype=next(self.parameters()).dtype)
1474
+ if self._use_38:
1475
+ mu = VideoVAE38_.encode(self, x, self._scale)
1476
+ else:
1477
+ mu = VideoVAE_.encode(self, x, self._scale)
1478
+ return EncoderOutput(latent_dist=LatentDist(mu=mu))
1479
+
1480
+ def decode(self, z):
1481
+ z = z.to(dtype=next(self.parameters()).dtype)
1482
+ if self._use_38:
1483
+ out = VideoVAE38_.decode(self, z, self._scale)
1484
+ else:
1485
+ out = VideoVAE_.decode(self, z, self._scale)
1486
+ return DecoderOutput(sample=out)
wan_video_vae.py ADDED
@@ -0,0 +1,1486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+
4
+ from einops import rearrange, repeat
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from tqdm import tqdm
10
+ from diffusers import ModelMixin, ConfigMixin
11
+ from diffusers.configuration_utils import register_to_config
12
+
13
+ CACHE_T = 2
14
+
15
+
16
+ def check_is_instance(model, module_class):
17
+ if isinstance(model, module_class):
18
+ return True
19
+ if hasattr(model, "module") and isinstance(model.module, module_class):
20
+ return True
21
+ return False
22
+
23
+
24
+ def block_causal_mask(x, block_size):
25
+ # params
26
+ b, n, s, _, device = *x.size(), x.device
27
+ assert s % block_size == 0
28
+ num_blocks = s // block_size
29
+
30
+ # build mask
31
+ mask = torch.zeros(b, n, s, s, dtype=torch.bool, device=device)
32
+ for i in range(num_blocks):
33
+ mask[:, :,
34
+ i * block_size:(i + 1) * block_size, :(i + 1) * block_size] = 1
35
+ return mask
36
+
37
+
38
+ class CausalConv3d(nn.Conv3d):
39
+ """
40
+ Causal 3d convolusion.
41
+ """
42
+
43
+ def __init__(self, *args, **kwargs):
44
+ super().__init__(*args, **kwargs)
45
+ self._padding = (self.padding[2], self.padding[2], self.padding[1],
46
+ self.padding[1], 2 * self.padding[0], 0)
47
+ self.padding = (0, 0, 0)
48
+
49
+ def forward(self, x, cache_x=None):
50
+ padding = list(self._padding)
51
+ if cache_x is not None and self._padding[4] > 0:
52
+ cache_x = cache_x.to(x.device)
53
+ x = torch.cat([cache_x, x], dim=2)
54
+ padding[4] -= cache_x.shape[2]
55
+ x = F.pad(x, padding)
56
+
57
+ return super().forward(x)
58
+
59
+
60
+ class RMS_norm(nn.Module):
61
+
62
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
63
+ super().__init__()
64
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
65
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
66
+
67
+ self.channel_first = channel_first
68
+ self.scale = dim**0.5
69
+ self.gamma = nn.Parameter(torch.ones(shape))
70
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
71
+
72
+ def forward(self, x):
73
+ return F.normalize(
74
+ x, dim=(1 if self.channel_first else
75
+ -1)) * self.scale * self.gamma + self.bias
76
+
77
+
78
+ class Upsample(nn.Upsample):
79
+
80
+ def forward(self, x):
81
+ """
82
+ Fix bfloat16 support for nearest neighbor interpolation.
83
+ """
84
+ return super().forward(x.float()).type_as(x)
85
+
86
+
87
+ class Resample(nn.Module):
88
+
89
+ def __init__(self, dim, mode):
90
+ assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d',
91
+ 'downsample3d')
92
+ super().__init__()
93
+ self.dim = dim
94
+ self.mode = mode
95
+
96
+ # layers
97
+ if mode == 'upsample2d':
98
+ self.resample = nn.Sequential(
99
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
100
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
101
+ elif mode == 'upsample3d':
102
+ self.resample = nn.Sequential(
103
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
104
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
105
+ self.time_conv = CausalConv3d(dim,
106
+ dim * 2, (3, 1, 1),
107
+ padding=(1, 0, 0))
108
+
109
+ elif mode == 'downsample2d':
110
+ self.resample = nn.Sequential(
111
+ nn.ZeroPad2d((0, 1, 0, 1)),
112
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
113
+ elif mode == 'downsample3d':
114
+ self.resample = nn.Sequential(
115
+ nn.ZeroPad2d((0, 1, 0, 1)),
116
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
117
+ self.time_conv = CausalConv3d(dim,
118
+ dim, (3, 1, 1),
119
+ stride=(2, 1, 1),
120
+ padding=(0, 0, 0))
121
+
122
+ else:
123
+ self.resample = nn.Identity()
124
+
125
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
126
+ b, c, t, h, w = x.size()
127
+ if self.mode == 'upsample3d':
128
+ if feat_cache is not None:
129
+ idx = feat_idx[0]
130
+ if feat_cache[idx] is None:
131
+ feat_cache[idx] = 'Rep'
132
+ feat_idx[0] += 1
133
+ else:
134
+
135
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
136
+ if cache_x.shape[2] < 2 and feat_cache[
137
+ idx] is not None and feat_cache[idx] != 'Rep':
138
+ # cache last frame of last two chunk
139
+ cache_x = torch.cat([
140
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
141
+ cache_x.device), cache_x
142
+ ],
143
+ dim=2)
144
+ if cache_x.shape[2] < 2 and feat_cache[
145
+ idx] is not None and feat_cache[idx] == 'Rep':
146
+ cache_x = torch.cat([
147
+ torch.zeros_like(cache_x).to(cache_x.device),
148
+ cache_x
149
+ ],
150
+ dim=2)
151
+ if feat_cache[idx] == 'Rep':
152
+ x = self.time_conv(x)
153
+ else:
154
+ x = self.time_conv(x, feat_cache[idx])
155
+ feat_cache[idx] = cache_x
156
+ feat_idx[0] += 1
157
+
158
+ x = x.reshape(b, 2, c, t, h, w)
159
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
160
+ 3)
161
+ x = x.reshape(b, c, t * 2, h, w)
162
+ t = x.shape[2]
163
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
164
+ x = self.resample(x)
165
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
166
+
167
+ if self.mode == 'downsample3d':
168
+ if feat_cache is not None:
169
+ idx = feat_idx[0]
170
+ if feat_cache[idx] is None:
171
+ feat_cache[idx] = x.clone()
172
+ feat_idx[0] += 1
173
+ else:
174
+ cache_x = x[:, :, -1:, :, :].clone()
175
+ x = self.time_conv(
176
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
177
+ feat_cache[idx] = cache_x
178
+ feat_idx[0] += 1
179
+ return x
180
+
181
+ def init_weight(self, conv):
182
+ conv_weight = conv.weight
183
+ nn.init.zeros_(conv_weight)
184
+ c1, c2, t, h, w = conv_weight.size()
185
+ one_matrix = torch.eye(c1, c2)
186
+ init_matrix = one_matrix
187
+ nn.init.zeros_(conv_weight)
188
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix
189
+ conv.weight.data.copy_(conv_weight)
190
+ nn.init.zeros_(conv.bias.data)
191
+
192
+ def init_weight2(self, conv):
193
+ conv_weight = conv.weight.data
194
+ nn.init.zeros_(conv_weight)
195
+ c1, c2, t, h, w = conv_weight.size()
196
+ init_matrix = torch.eye(c1 // 2, c2)
197
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
198
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
199
+ conv.weight.data.copy_(conv_weight)
200
+ nn.init.zeros_(conv.bias.data)
201
+
202
+
203
+
204
+ def patchify(x, patch_size):
205
+ if patch_size == 1:
206
+ return x
207
+ if x.dim() == 4:
208
+ x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
209
+ elif x.dim() == 5:
210
+ x = rearrange(x,
211
+ "b c f (h q) (w r) -> b (c r q) f h w",
212
+ q=patch_size,
213
+ r=patch_size)
214
+ else:
215
+ raise ValueError(f"Invalid input shape: {x.shape}")
216
+ return x
217
+
218
+
219
+ def unpatchify(x, patch_size):
220
+ if patch_size == 1:
221
+ return x
222
+ if x.dim() == 4:
223
+ x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
224
+ elif x.dim() == 5:
225
+ x = rearrange(x,
226
+ "b (c r q) f h w -> b c f (h q) (w r)",
227
+ q=patch_size,
228
+ r=patch_size)
229
+ return x
230
+
231
+
232
+ class Resample38(Resample):
233
+
234
+ def __init__(self, dim, mode):
235
+ assert mode in (
236
+ "none",
237
+ "upsample2d",
238
+ "upsample3d",
239
+ "downsample2d",
240
+ "downsample3d",
241
+ )
242
+ super(Resample, self).__init__()
243
+ self.dim = dim
244
+ self.mode = mode
245
+
246
+ # layers
247
+ if mode == "upsample2d":
248
+ self.resample = nn.Sequential(
249
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
250
+ nn.Conv2d(dim, dim, 3, padding=1),
251
+ )
252
+ elif mode == "upsample3d":
253
+ self.resample = nn.Sequential(
254
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
255
+ nn.Conv2d(dim, dim, 3, padding=1),
256
+ )
257
+ self.time_conv = CausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
258
+ elif mode == "downsample2d":
259
+ self.resample = nn.Sequential(
260
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
261
+ )
262
+ elif mode == "downsample3d":
263
+ self.resample = nn.Sequential(
264
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
265
+ )
266
+ self.time_conv = CausalConv3d(
267
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)
268
+ )
269
+ else:
270
+ self.resample = nn.Identity()
271
+
272
+ class ResidualBlock(nn.Module):
273
+
274
+ def __init__(self, in_dim, out_dim, dropout=0.0):
275
+ super().__init__()
276
+ self.in_dim = in_dim
277
+ self.out_dim = out_dim
278
+
279
+ # layers
280
+ self.residual = nn.Sequential(
281
+ RMS_norm(in_dim, images=False), nn.SiLU(),
282
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
283
+ RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout),
284
+ CausalConv3d(out_dim, out_dim, 3, padding=1))
285
+ self.shortcut = CausalConv3d(in_dim, out_dim, 1) \
286
+ if in_dim != out_dim else nn.Identity()
287
+
288
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
289
+ h = self.shortcut(x)
290
+ for layer in self.residual:
291
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
292
+ idx = feat_idx[0]
293
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
294
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
295
+ # cache last frame of last two chunk
296
+ cache_x = torch.cat([
297
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
298
+ cache_x.device), cache_x
299
+ ],
300
+ dim=2)
301
+ x = layer(x, feat_cache[idx])
302
+ feat_cache[idx] = cache_x
303
+ feat_idx[0] += 1
304
+ else:
305
+ x = layer(x)
306
+ return x + h
307
+
308
+
309
+ class AttentionBlock(nn.Module):
310
+ """
311
+ Causal self-attention with a single head.
312
+ """
313
+
314
+ def __init__(self, dim):
315
+ super().__init__()
316
+ self.dim = dim
317
+
318
+ # layers
319
+ self.norm = RMS_norm(dim)
320
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
321
+ self.proj = nn.Conv2d(dim, dim, 1)
322
+
323
+ # zero out the last layer params
324
+ nn.init.zeros_(self.proj.weight)
325
+
326
+ def forward(self, x):
327
+ identity = x
328
+ b, c, t, h, w = x.size()
329
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
330
+ x = self.norm(x)
331
+ # compute query, key, value
332
+ q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, -1).permute(
333
+ 0, 1, 3, 2).contiguous().chunk(3, dim=-1)
334
+
335
+ # apply attention
336
+ x = F.scaled_dot_product_attention(
337
+ q,
338
+ k,
339
+ v,
340
+ #attn_mask=block_causal_mask(q, block_size=h * w)
341
+ )
342
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
343
+
344
+ # output
345
+ x = self.proj(x)
346
+ x = rearrange(x, '(b t) c h w-> b c t h w', t=t)
347
+ return x + identity
348
+
349
+
350
+ class AvgDown3D(nn.Module):
351
+ def __init__(
352
+ self,
353
+ in_channels,
354
+ out_channels,
355
+ factor_t,
356
+ factor_s=1,
357
+ ):
358
+ super().__init__()
359
+ self.in_channels = in_channels
360
+ self.out_channels = out_channels
361
+ self.factor_t = factor_t
362
+ self.factor_s = factor_s
363
+ self.factor = self.factor_t * self.factor_s * self.factor_s
364
+
365
+ assert in_channels * self.factor % out_channels == 0
366
+ self.group_size = in_channels * self.factor // out_channels
367
+
368
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
369
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
370
+ pad = (0, 0, 0, 0, pad_t, 0)
371
+ x = F.pad(x, pad)
372
+ B, C, T, H, W = x.shape
373
+ x = x.view(
374
+ B,
375
+ C,
376
+ T // self.factor_t,
377
+ self.factor_t,
378
+ H // self.factor_s,
379
+ self.factor_s,
380
+ W // self.factor_s,
381
+ self.factor_s,
382
+ )
383
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
384
+ x = x.view(
385
+ B,
386
+ C * self.factor,
387
+ T // self.factor_t,
388
+ H // self.factor_s,
389
+ W // self.factor_s,
390
+ )
391
+ x = x.view(
392
+ B,
393
+ self.out_channels,
394
+ self.group_size,
395
+ T // self.factor_t,
396
+ H // self.factor_s,
397
+ W // self.factor_s,
398
+ )
399
+ x = x.mean(dim=2)
400
+ return x
401
+
402
+
403
+ class DupUp3D(nn.Module):
404
+ def __init__(
405
+ self,
406
+ in_channels: int,
407
+ out_channels: int,
408
+ factor_t,
409
+ factor_s=1,
410
+ ):
411
+ super().__init__()
412
+ self.in_channels = in_channels
413
+ self.out_channels = out_channels
414
+
415
+ self.factor_t = factor_t
416
+ self.factor_s = factor_s
417
+ self.factor = self.factor_t * self.factor_s * self.factor_s
418
+
419
+ assert out_channels * self.factor % in_channels == 0
420
+ self.repeats = out_channels * self.factor // in_channels
421
+
422
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
423
+ x = x.repeat_interleave(self.repeats, dim=1)
424
+ x = x.view(
425
+ x.size(0),
426
+ self.out_channels,
427
+ self.factor_t,
428
+ self.factor_s,
429
+ self.factor_s,
430
+ x.size(2),
431
+ x.size(3),
432
+ x.size(4),
433
+ )
434
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
435
+ x = x.view(
436
+ x.size(0),
437
+ self.out_channels,
438
+ x.size(2) * self.factor_t,
439
+ x.size(4) * self.factor_s,
440
+ x.size(6) * self.factor_s,
441
+ )
442
+ if first_chunk:
443
+ x = x[:, :, self.factor_t - 1 :, :, :]
444
+ return x
445
+
446
+
447
+ class Down_ResidualBlock(nn.Module):
448
+ def __init__(
449
+ self, in_dim, out_dim, dropout, mult, temperal_downsample=False, down_flag=False
450
+ ):
451
+ super().__init__()
452
+
453
+ # Shortcut path with downsample
454
+ self.avg_shortcut = AvgDown3D(
455
+ in_dim,
456
+ out_dim,
457
+ factor_t=2 if temperal_downsample else 1,
458
+ factor_s=2 if down_flag else 1,
459
+ )
460
+
461
+ # Main path with residual blocks and downsample
462
+ downsamples = []
463
+ for _ in range(mult):
464
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
465
+ in_dim = out_dim
466
+
467
+ # Add the final downsample block
468
+ if down_flag:
469
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
470
+ downsamples.append(Resample38(out_dim, mode=mode))
471
+
472
+ self.downsamples = nn.Sequential(*downsamples)
473
+
474
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
475
+ x_copy = x.clone()
476
+ for module in self.downsamples:
477
+ x = module(x, feat_cache, feat_idx)
478
+
479
+ return x + self.avg_shortcut(x_copy)
480
+
481
+
482
+ class Up_ResidualBlock(nn.Module):
483
+ def __init__(
484
+ self, in_dim, out_dim, dropout, mult, temperal_upsample=False, up_flag=False
485
+ ):
486
+ super().__init__()
487
+ # Shortcut path with upsample
488
+ if up_flag:
489
+ self.avg_shortcut = DupUp3D(
490
+ in_dim,
491
+ out_dim,
492
+ factor_t=2 if temperal_upsample else 1,
493
+ factor_s=2 if up_flag else 1,
494
+ )
495
+ else:
496
+ self.avg_shortcut = None
497
+
498
+ # Main path with residual blocks and upsample
499
+ upsamples = []
500
+ for _ in range(mult):
501
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
502
+ in_dim = out_dim
503
+
504
+ # Add the final upsample block
505
+ if up_flag:
506
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
507
+ upsamples.append(Resample38(out_dim, mode=mode))
508
+
509
+ self.upsamples = nn.Sequential(*upsamples)
510
+
511
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
512
+ x_main = x.clone()
513
+ for module in self.upsamples:
514
+ x_main = module(x_main, feat_cache, feat_idx)
515
+ if self.avg_shortcut is not None:
516
+ x_shortcut = self.avg_shortcut(x, first_chunk)
517
+ return x_main + x_shortcut
518
+ else:
519
+ return x_main
520
+
521
+
522
+ class Encoder3d(nn.Module):
523
+
524
+ def __init__(self,
525
+ dim=128,
526
+ z_dim=4,
527
+ dim_mult=[1, 2, 4, 4],
528
+ num_res_blocks=2,
529
+ attn_scales=[],
530
+ temperal_downsample=[True, True, False],
531
+ dropout=0.0):
532
+ super().__init__()
533
+ self.dim = dim
534
+ self.z_dim = z_dim
535
+ self.dim_mult = dim_mult
536
+ self.num_res_blocks = num_res_blocks
537
+ self.attn_scales = attn_scales
538
+ self.temperal_downsample = temperal_downsample
539
+
540
+ # dimensions
541
+ dims = [dim * u for u in [1] + dim_mult]
542
+ scale = 1.0
543
+
544
+ # init block
545
+ self.conv1 = CausalConv3d(3, dims[0], 3, padding=1)
546
+
547
+ # downsample blocks
548
+ downsamples = []
549
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
550
+ # residual (+attention) blocks
551
+ for _ in range(num_res_blocks):
552
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
553
+ if scale in attn_scales:
554
+ downsamples.append(AttentionBlock(out_dim))
555
+ in_dim = out_dim
556
+
557
+ # downsample block
558
+ if i != len(dim_mult) - 1:
559
+ mode = 'downsample3d' if temperal_downsample[
560
+ i] else 'downsample2d'
561
+ downsamples.append(Resample(out_dim, mode=mode))
562
+ scale /= 2.0
563
+ self.downsamples = nn.Sequential(*downsamples)
564
+
565
+ # middle blocks
566
+ self.middle = nn.Sequential(ResidualBlock(out_dim, out_dim, dropout),
567
+ AttentionBlock(out_dim),
568
+ ResidualBlock(out_dim, out_dim, dropout))
569
+
570
+ # output blocks
571
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
572
+ CausalConv3d(out_dim, z_dim, 3, padding=1))
573
+
574
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
575
+ if feat_cache is not None:
576
+ idx = feat_idx[0]
577
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
578
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
579
+ # cache last frame of last two chunk
580
+ cache_x = torch.cat([
581
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
582
+ cache_x.device), cache_x
583
+ ],
584
+ dim=2)
585
+ x = self.conv1(x, feat_cache[idx])
586
+ feat_cache[idx] = cache_x
587
+ feat_idx[0] += 1
588
+ else:
589
+ x = self.conv1(x)
590
+
591
+ ## downsamples
592
+ for layer in self.downsamples:
593
+ if feat_cache is not None:
594
+ x = layer(x, feat_cache, feat_idx)
595
+ else:
596
+ x = layer(x)
597
+
598
+ ## middle
599
+ for layer in self.middle:
600
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
601
+ x = layer(x, feat_cache, feat_idx)
602
+ else:
603
+ x = layer(x)
604
+
605
+ ## head
606
+ for layer in self.head:
607
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
608
+ idx = feat_idx[0]
609
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
610
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
611
+ # cache last frame of last two chunk
612
+ cache_x = torch.cat([
613
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
614
+ cache_x.device), cache_x
615
+ ],
616
+ dim=2)
617
+ x = layer(x, feat_cache[idx])
618
+ feat_cache[idx] = cache_x
619
+ feat_idx[0] += 1
620
+ else:
621
+ x = layer(x)
622
+ return x
623
+
624
+
625
+ class Encoder3d_38(nn.Module):
626
+
627
+ def __init__(self,
628
+ dim=128,
629
+ z_dim=4,
630
+ dim_mult=[1, 2, 4, 4],
631
+ num_res_blocks=2,
632
+ attn_scales=[],
633
+ temperal_downsample=[False, True, True],
634
+ dropout=0.0):
635
+ super().__init__()
636
+ self.dim = dim
637
+ self.z_dim = z_dim
638
+ self.dim_mult = dim_mult
639
+ self.num_res_blocks = num_res_blocks
640
+ self.attn_scales = attn_scales
641
+ self.temperal_downsample = temperal_downsample
642
+
643
+ # dimensions
644
+ dims = [dim * u for u in [1] + dim_mult]
645
+ scale = 1.0
646
+
647
+ # init block
648
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
649
+
650
+ # downsample blocks
651
+ downsamples = []
652
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
653
+ t_down_flag = (
654
+ temperal_downsample[i] if i < len(temperal_downsample) else False
655
+ )
656
+ downsamples.append(
657
+ Down_ResidualBlock(
658
+ in_dim=in_dim,
659
+ out_dim=out_dim,
660
+ dropout=dropout,
661
+ mult=num_res_blocks,
662
+ temperal_downsample=t_down_flag,
663
+ down_flag=i != len(dim_mult) - 1,
664
+ )
665
+ )
666
+ scale /= 2.0
667
+ self.downsamples = nn.Sequential(*downsamples)
668
+
669
+ # middle blocks
670
+ self.middle = nn.Sequential(
671
+ ResidualBlock(out_dim, out_dim, dropout),
672
+ AttentionBlock(out_dim),
673
+ ResidualBlock(out_dim, out_dim, dropout),
674
+ )
675
+
676
+ # # output blocks
677
+ self.head = nn.Sequential(
678
+ RMS_norm(out_dim, images=False),
679
+ nn.SiLU(),
680
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
681
+ )
682
+
683
+
684
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
685
+
686
+ if feat_cache is not None:
687
+ idx = feat_idx[0]
688
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
689
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
690
+ cache_x = torch.cat(
691
+ [
692
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
693
+ cache_x,
694
+ ],
695
+ dim=2,
696
+ )
697
+ x = self.conv1(x, feat_cache[idx])
698
+ feat_cache[idx] = cache_x
699
+ feat_idx[0] += 1
700
+ else:
701
+ x = self.conv1(x)
702
+
703
+ ## downsamples
704
+ for layer in self.downsamples:
705
+ if feat_cache is not None:
706
+ x = layer(x, feat_cache, feat_idx)
707
+ else:
708
+ x = layer(x)
709
+
710
+ ## middle
711
+ for layer in self.middle:
712
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
713
+ x = layer(x, feat_cache, feat_idx)
714
+ else:
715
+ x = layer(x)
716
+
717
+ ## head
718
+ for layer in self.head:
719
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
720
+ idx = feat_idx[0]
721
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
722
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
723
+ cache_x = torch.cat(
724
+ [
725
+ feat_cache[idx][:, :, -1, :, :]
726
+ .unsqueeze(2)
727
+ .to(cache_x.device),
728
+ cache_x,
729
+ ],
730
+ dim=2,
731
+ )
732
+ x = layer(x, feat_cache[idx])
733
+ feat_cache[idx] = cache_x
734
+ feat_idx[0] += 1
735
+ else:
736
+ x = layer(x)
737
+
738
+ return x
739
+
740
+
741
+ class Decoder3d(nn.Module):
742
+
743
+ def __init__(self,
744
+ dim=128,
745
+ z_dim=4,
746
+ dim_mult=[1, 2, 4, 4],
747
+ num_res_blocks=2,
748
+ attn_scales=[],
749
+ temperal_upsample=[False, True, True],
750
+ dropout=0.0):
751
+ super().__init__()
752
+ self.dim = dim
753
+ self.z_dim = z_dim
754
+ self.dim_mult = dim_mult
755
+ self.num_res_blocks = num_res_blocks
756
+ self.attn_scales = attn_scales
757
+ self.temperal_upsample = temperal_upsample
758
+
759
+ # dimensions
760
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
761
+ scale = 1.0 / 2**(len(dim_mult) - 2)
762
+
763
+ # init block
764
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
765
+
766
+ # middle blocks
767
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
768
+ AttentionBlock(dims[0]),
769
+ ResidualBlock(dims[0], dims[0], dropout))
770
+
771
+ # upsample blocks
772
+ upsamples = []
773
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
774
+ # residual (+attention) blocks
775
+ if i == 1 or i == 2 or i == 3:
776
+ in_dim = in_dim // 2
777
+ for _ in range(num_res_blocks + 1):
778
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
779
+ if scale in attn_scales:
780
+ upsamples.append(AttentionBlock(out_dim))
781
+ in_dim = out_dim
782
+
783
+ # upsample block
784
+ if i != len(dim_mult) - 1:
785
+ mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d'
786
+ upsamples.append(Resample(out_dim, mode=mode))
787
+ scale *= 2.0
788
+ self.upsamples = nn.Sequential(*upsamples)
789
+
790
+ # output blocks
791
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
792
+ CausalConv3d(out_dim, 3, 3, padding=1))
793
+
794
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
795
+ ## conv1
796
+ if feat_cache is not None:
797
+ idx = feat_idx[0]
798
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
799
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
800
+ # cache last frame of last two chunk
801
+ cache_x = torch.cat([
802
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
803
+ cache_x.device), cache_x
804
+ ],
805
+ dim=2)
806
+ x = self.conv1(x, feat_cache[idx])
807
+ feat_cache[idx] = cache_x
808
+ feat_idx[0] += 1
809
+ else:
810
+ x = self.conv1(x)
811
+
812
+ ## middle
813
+ for layer in self.middle:
814
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
815
+ x = layer(x, feat_cache, feat_idx)
816
+ else:
817
+ x = layer(x)
818
+
819
+ ## upsamples
820
+ for layer in self.upsamples:
821
+ if feat_cache is not None:
822
+ x = layer(x, feat_cache, feat_idx)
823
+ else:
824
+ x = layer(x)
825
+
826
+ ## head
827
+ for layer in self.head:
828
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
829
+ idx = feat_idx[0]
830
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
831
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
832
+ # cache last frame of last two chunk
833
+ cache_x = torch.cat([
834
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
835
+ cache_x.device), cache_x
836
+ ],
837
+ dim=2)
838
+ x = layer(x, feat_cache[idx])
839
+ feat_cache[idx] = cache_x
840
+ feat_idx[0] += 1
841
+ else:
842
+ x = layer(x)
843
+ return x
844
+
845
+
846
+
847
+ class Decoder3d_38(nn.Module):
848
+
849
+ def __init__(self,
850
+ dim=128,
851
+ z_dim=4,
852
+ dim_mult=[1, 2, 4, 4],
853
+ num_res_blocks=2,
854
+ attn_scales=[],
855
+ temperal_upsample=[False, True, True],
856
+ dropout=0.0):
857
+ super().__init__()
858
+ self.dim = dim
859
+ self.z_dim = z_dim
860
+ self.dim_mult = dim_mult
861
+ self.num_res_blocks = num_res_blocks
862
+ self.attn_scales = attn_scales
863
+ self.temperal_upsample = temperal_upsample
864
+
865
+ # dimensions
866
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
867
+ scale = 1.0 / 2 ** (len(dim_mult) - 2)
868
+ # init block
869
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
870
+
871
+ # middle blocks
872
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
873
+ AttentionBlock(dims[0]),
874
+ ResidualBlock(dims[0], dims[0], dropout))
875
+
876
+ # upsample blocks
877
+ upsamples = []
878
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
879
+ t_up_flag = temperal_upsample[i] if i < len(temperal_upsample) else False
880
+ upsamples.append(
881
+ Up_ResidualBlock(in_dim=in_dim,
882
+ out_dim=out_dim,
883
+ dropout=dropout,
884
+ mult=num_res_blocks + 1,
885
+ temperal_upsample=t_up_flag,
886
+ up_flag=i != len(dim_mult) - 1))
887
+ self.upsamples = nn.Sequential(*upsamples)
888
+
889
+ # output blocks
890
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
891
+ CausalConv3d(out_dim, 12, 3, padding=1))
892
+
893
+
894
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
895
+ if feat_cache is not None:
896
+ idx = feat_idx[0]
897
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
898
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
899
+ cache_x = torch.cat(
900
+ [
901
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
902
+ cache_x,
903
+ ],
904
+ dim=2,
905
+ )
906
+ x = self.conv1(x, feat_cache[idx])
907
+ feat_cache[idx] = cache_x
908
+ feat_idx[0] += 1
909
+ else:
910
+ x = self.conv1(x)
911
+
912
+ for layer in self.middle:
913
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
914
+ x = layer(x, feat_cache, feat_idx)
915
+ else:
916
+ x = layer(x)
917
+
918
+ ## upsamples
919
+ for layer in self.upsamples:
920
+ if feat_cache is not None:
921
+ x = layer(x, feat_cache, feat_idx, first_chunk)
922
+ else:
923
+ x = layer(x)
924
+
925
+ ## head
926
+ for layer in self.head:
927
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
928
+ idx = feat_idx[0]
929
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
930
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
931
+ cache_x = torch.cat(
932
+ [
933
+ feat_cache[idx][:, :, -1, :, :]
934
+ .unsqueeze(2)
935
+ .to(cache_x.device),
936
+ cache_x,
937
+ ],
938
+ dim=2,
939
+ )
940
+ x = layer(x, feat_cache[idx])
941
+ feat_cache[idx] = cache_x
942
+ feat_idx[0] += 1
943
+ else:
944
+ x = layer(x)
945
+ return x
946
+
947
+
948
+ def count_conv3d(model):
949
+ count = 0
950
+ for m in model.modules():
951
+ if isinstance(m, CausalConv3d):
952
+ count += 1
953
+ return count
954
+
955
+
956
+ class VideoVAE_(nn.Module):
957
+
958
+ def __init__(self,
959
+ dim=96,
960
+ z_dim=16,
961
+ dim_mult=[1, 2, 4, 4],
962
+ num_res_blocks=2,
963
+ attn_scales=[],
964
+ temperal_downsample=[False, True, True],
965
+ dropout=0.0):
966
+ super().__init__()
967
+ self.dim = dim
968
+ self.z_dim = z_dim
969
+ self.dim_mult = dim_mult
970
+ self.num_res_blocks = num_res_blocks
971
+ self.attn_scales = attn_scales
972
+ self.temperal_downsample = temperal_downsample
973
+ self.temperal_upsample = temperal_downsample[::-1]
974
+
975
+ # modules
976
+ self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,
977
+ attn_scales, self.temperal_downsample, dropout)
978
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
979
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
980
+ self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,
981
+ attn_scales, self.temperal_upsample, dropout)
982
+
983
+ def forward(self, x):
984
+ mu, log_var = self.encode(x)
985
+ z = self.reparameterize(mu, log_var)
986
+ x_recon = self.decode(z)
987
+ return x_recon, mu, log_var
988
+
989
+ def encode(self, x, scale):
990
+ self.clear_cache()
991
+ ## cache
992
+ t = x.shape[2]
993
+ iter_ = 1 + (t - 1) // 4
994
+
995
+ for i in range(iter_):
996
+ self._enc_conv_idx = [0]
997
+ if i == 0:
998
+ out = self.encoder(x[:, :, :1, :, :],
999
+ feat_cache=self._enc_feat_map,
1000
+ feat_idx=self._enc_conv_idx)
1001
+ else:
1002
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1003
+ feat_cache=self._enc_feat_map,
1004
+ feat_idx=self._enc_conv_idx)
1005
+ out = torch.cat([out, out_], 2)
1006
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1007
+ if isinstance(scale[0], torch.Tensor):
1008
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1009
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1010
+ 1, self.z_dim, 1, 1, 1)
1011
+ else:
1012
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1013
+ mu = (mu - scale[0]) * scale[1]
1014
+ return mu
1015
+
1016
+ def decode(self, z, scale):
1017
+ self.clear_cache()
1018
+ # z: [b,c,t,h,w]
1019
+ if isinstance(scale[0], torch.Tensor):
1020
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1021
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1022
+ 1, self.z_dim, 1, 1, 1)
1023
+ else:
1024
+ scale = scale.to(dtype=z.dtype, device=z.device)
1025
+ z = z / scale[1] + scale[0]
1026
+ iter_ = z.shape[2]
1027
+ x = self.conv2(z)
1028
+ for i in range(iter_):
1029
+ self._conv_idx = [0]
1030
+ if i == 0:
1031
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1032
+ feat_cache=self._feat_map,
1033
+ feat_idx=self._conv_idx)
1034
+ else:
1035
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1036
+ feat_cache=self._feat_map,
1037
+ feat_idx=self._conv_idx)
1038
+ out = torch.cat([out, out_], 2) # may add tensor offload
1039
+ return out
1040
+
1041
+ def reparameterize(self, mu, log_var):
1042
+ std = torch.exp(0.5 * log_var)
1043
+ eps = torch.randn_like(std)
1044
+ return eps * std + mu
1045
+
1046
+ def sample(self, imgs, deterministic=False):
1047
+ mu, log_var = self.encode(imgs)
1048
+ if deterministic:
1049
+ return mu
1050
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
1051
+ return mu + std * torch.randn_like(std)
1052
+
1053
+ def clear_cache(self):
1054
+ self._conv_num = count_conv3d(self.decoder)
1055
+ self._conv_idx = [0]
1056
+ self._feat_map = [None] * self._conv_num
1057
+ # cache encode
1058
+ self._enc_conv_num = count_conv3d(self.encoder)
1059
+ self._enc_conv_idx = [0]
1060
+ self._enc_feat_map = [None] * self._enc_conv_num
1061
+
1062
+
1063
+ class WanVideoVAE(nn.Module):
1064
+
1065
+ def __init__(self, z_dim=16):
1066
+ super().__init__()
1067
+
1068
+ mean = [
1069
+ -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
1070
+ 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
1071
+ ]
1072
+ std = [
1073
+ 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
1074
+ 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
1075
+ ]
1076
+ self.mean = torch.tensor(mean)
1077
+ self.std = torch.tensor(std)
1078
+ self.scale = [self.mean, 1.0 / self.std]
1079
+
1080
+ # init model
1081
+ self.model = VideoVAE_(z_dim=z_dim).eval().requires_grad_(False)
1082
+ self.upsampling_factor = 8
1083
+ self.z_dim = z_dim
1084
+
1085
+
1086
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
1087
+ x = torch.ones((length,))
1088
+ if not left_bound:
1089
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
1090
+ if not right_bound:
1091
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
1092
+ return x
1093
+
1094
+
1095
+ def build_mask(self, data, is_bound, border_width):
1096
+ _, _, _, H, W = data.shape
1097
+ h = self.build_1d_mask(H, is_bound[0], is_bound[1], border_width[0])
1098
+ w = self.build_1d_mask(W, is_bound[2], is_bound[3], border_width[1])
1099
+
1100
+ h = repeat(h, "H -> H W", H=H, W=W)
1101
+ w = repeat(w, "W -> H W", H=H, W=W)
1102
+
1103
+ mask = torch.stack([h, w]).min(dim=0).values
1104
+ mask = rearrange(mask, "H W -> 1 1 1 H W")
1105
+ return mask
1106
+
1107
+
1108
+ def tiled_decode(self, hidden_states, device, tile_size, tile_stride):
1109
+ _, _, T, H, W = hidden_states.shape
1110
+ size_h, size_w = tile_size
1111
+ stride_h, stride_w = tile_stride
1112
+
1113
+ # Split tasks
1114
+ tasks = []
1115
+ for h in range(0, H, stride_h):
1116
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1117
+ for w in range(0, W, stride_w):
1118
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1119
+ h_, w_ = h + size_h, w + size_w
1120
+ tasks.append((h, h_, w, w_))
1121
+
1122
+ data_device = "cpu"
1123
+ computation_device = device
1124
+
1125
+ out_T = T * 4 - 3
1126
+ weight = torch.zeros((1, 1, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1127
+ values = torch.zeros((1, 3, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1128
+
1129
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"):
1130
+ hidden_states_batch = hidden_states[:, :, :, h:h_, w:w_].to(computation_device)
1131
+ hidden_states_batch = self.model.decode(hidden_states_batch, self.scale).to(data_device)
1132
+
1133
+ mask = self.build_mask(
1134
+ hidden_states_batch,
1135
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1136
+ border_width=((size_h - stride_h) * self.upsampling_factor, (size_w - stride_w) * self.upsampling_factor)
1137
+ ).to(dtype=hidden_states.dtype, device=data_device)
1138
+
1139
+ target_h = h * self.upsampling_factor
1140
+ target_w = w * self.upsampling_factor
1141
+ values[
1142
+ :,
1143
+ :,
1144
+ :,
1145
+ target_h:target_h + hidden_states_batch.shape[3],
1146
+ target_w:target_w + hidden_states_batch.shape[4],
1147
+ ] += hidden_states_batch * mask
1148
+ weight[
1149
+ :,
1150
+ :,
1151
+ :,
1152
+ target_h: target_h + hidden_states_batch.shape[3],
1153
+ target_w: target_w + hidden_states_batch.shape[4],
1154
+ ] += mask
1155
+ values = values / weight
1156
+ values = values.clamp_(-1, 1)
1157
+ return values
1158
+
1159
+
1160
+ def tiled_encode(self, video, device, tile_size, tile_stride):
1161
+ _, _, T, H, W = video.shape
1162
+ size_h, size_w = tile_size
1163
+ stride_h, stride_w = tile_stride
1164
+
1165
+ # Split tasks
1166
+ tasks = []
1167
+ for h in range(0, H, stride_h):
1168
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1169
+ for w in range(0, W, stride_w):
1170
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1171
+ h_, w_ = h + size_h, w + size_w
1172
+ tasks.append((h, h_, w, w_))
1173
+
1174
+ data_device = "cpu"
1175
+ computation_device = device
1176
+
1177
+ out_T = (T + 3) // 4
1178
+ weight = torch.zeros((1, 1, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1179
+ values = torch.zeros((1, self.z_dim, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1180
+
1181
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"):
1182
+ hidden_states_batch = video[:, :, :, h:h_, w:w_].to(computation_device)
1183
+ hidden_states_batch = self.model.encode(hidden_states_batch, self.scale).to(data_device)
1184
+
1185
+ mask = self.build_mask(
1186
+ hidden_states_batch,
1187
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1188
+ border_width=((size_h - stride_h) // self.upsampling_factor, (size_w - stride_w) // self.upsampling_factor)
1189
+ ).to(dtype=video.dtype, device=data_device)
1190
+
1191
+ target_h = h // self.upsampling_factor
1192
+ target_w = w // self.upsampling_factor
1193
+ values[
1194
+ :,
1195
+ :,
1196
+ :,
1197
+ target_h:target_h + hidden_states_batch.shape[3],
1198
+ target_w:target_w + hidden_states_batch.shape[4],
1199
+ ] += hidden_states_batch * mask
1200
+ weight[
1201
+ :,
1202
+ :,
1203
+ :,
1204
+ target_h: target_h + hidden_states_batch.shape[3],
1205
+ target_w: target_w + hidden_states_batch.shape[4],
1206
+ ] += mask
1207
+ values = values / weight
1208
+ return values
1209
+
1210
+
1211
+ def single_encode(self, video, device):
1212
+ video = video.to(device)
1213
+ x = self.model.encode(video, self.scale)
1214
+ return x
1215
+
1216
+
1217
+ def single_decode(self, hidden_state, device):
1218
+ hidden_state = hidden_state.to(device)
1219
+ video = self.model.decode(hidden_state, self.scale)
1220
+ return video.clamp_(-1, 1)
1221
+
1222
+
1223
+ def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1224
+ videos = [video.to("cpu") for video in videos]
1225
+ hidden_states = []
1226
+ for video in videos:
1227
+ video = video.unsqueeze(0)
1228
+ if tiled:
1229
+ tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor)
1230
+ tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor)
1231
+ hidden_state = self.tiled_encode(video, device, tile_size, tile_stride)
1232
+ else:
1233
+ hidden_state = self.single_encode(video, device)
1234
+ hidden_state = hidden_state.squeeze(0)
1235
+ hidden_states.append(hidden_state)
1236
+ hidden_states = torch.stack(hidden_states)
1237
+ return hidden_states
1238
+
1239
+
1240
+ def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1241
+ hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states]
1242
+ videos = []
1243
+ for hidden_state in hidden_states:
1244
+ hidden_state = hidden_state.unsqueeze(0)
1245
+ if tiled:
1246
+ video = self.tiled_decode(hidden_state, device, tile_size, tile_stride)
1247
+ else:
1248
+ video = self.single_decode(hidden_state, device)
1249
+ video = video.squeeze(0)
1250
+ videos.append(video)
1251
+ videos = torch.stack(videos)
1252
+ return videos
1253
+
1254
+
1255
+ @staticmethod
1256
+ def state_dict_converter():
1257
+ return WanVideoVAEStateDictConverter()
1258
+
1259
+
1260
+ class WanVideoVAEStateDictConverter:
1261
+
1262
+ def __init__(self):
1263
+ pass
1264
+
1265
+ def from_civitai(self, state_dict):
1266
+ state_dict_ = {}
1267
+ if 'model_state' in state_dict:
1268
+ state_dict = state_dict['model_state']
1269
+ for name in state_dict:
1270
+ state_dict_['model.' + name] = state_dict[name]
1271
+ return state_dict_
1272
+
1273
+
1274
+ class VideoVAE38_(VideoVAE_):
1275
+
1276
+ def __init__(self,
1277
+ dim=160,
1278
+ z_dim=48,
1279
+ dec_dim=256,
1280
+ dim_mult=[1, 2, 4, 4],
1281
+ num_res_blocks=2,
1282
+ attn_scales=[],
1283
+ temperal_downsample=[False, True, True],
1284
+ dropout=0.0):
1285
+ super(VideoVAE_, self).__init__()
1286
+ self.dim = dim
1287
+ self.z_dim = z_dim
1288
+ self.dim_mult = dim_mult
1289
+ self.num_res_blocks = num_res_blocks
1290
+ self.attn_scales = attn_scales
1291
+ self.temperal_downsample = temperal_downsample
1292
+ self.temperal_upsample = temperal_downsample[::-1]
1293
+
1294
+ # modules
1295
+ self.encoder = Encoder3d_38(dim, z_dim * 2, dim_mult, num_res_blocks,
1296
+ attn_scales, self.temperal_downsample, dropout)
1297
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
1298
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
1299
+ self.decoder = Decoder3d_38(dec_dim, z_dim, dim_mult, num_res_blocks,
1300
+ attn_scales, self.temperal_upsample, dropout)
1301
+
1302
+
1303
+ def encode(self, x, scale):
1304
+ self.clear_cache()
1305
+ x = patchify(x, patch_size=2)
1306
+ t = x.shape[2]
1307
+ iter_ = 1 + (t - 1) // 4
1308
+ for i in range(iter_):
1309
+ self._enc_conv_idx = [0]
1310
+ if i == 0:
1311
+ out = self.encoder(x[:, :, :1, :, :],
1312
+ feat_cache=self._enc_feat_map,
1313
+ feat_idx=self._enc_conv_idx)
1314
+ else:
1315
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1316
+ feat_cache=self._enc_feat_map,
1317
+ feat_idx=self._enc_conv_idx)
1318
+ out = torch.cat([out, out_], 2)
1319
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1320
+ if isinstance(scale[0], torch.Tensor):
1321
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1322
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1323
+ 1, self.z_dim, 1, 1, 1)
1324
+ else:
1325
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1326
+ mu = (mu - scale[0]) * scale[1]
1327
+ self.clear_cache()
1328
+ return mu
1329
+
1330
+
1331
+ def decode(self, z, scale):
1332
+ self.clear_cache()
1333
+ if isinstance(scale[0], torch.Tensor):
1334
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1335
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1336
+ 1, self.z_dim, 1, 1, 1)
1337
+ else:
1338
+ scale = scale.to(dtype=z.dtype, device=z.device)
1339
+ z = z / scale[1] + scale[0]
1340
+ iter_ = z.shape[2]
1341
+ x = self.conv2(z)
1342
+ for i in range(iter_):
1343
+ self._conv_idx = [0]
1344
+ if i == 0:
1345
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1346
+ feat_cache=self._feat_map,
1347
+ feat_idx=self._conv_idx,
1348
+ first_chunk=True)
1349
+ else:
1350
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1351
+ feat_cache=self._feat_map,
1352
+ feat_idx=self._conv_idx)
1353
+ out = torch.cat([out, out_], 2)
1354
+ out = unpatchify(out, patch_size=2)
1355
+ self.clear_cache()
1356
+ return out
1357
+
1358
+
1359
+ class WanVideoVAE38(WanVideoVAE):
1360
+
1361
+ def __init__(self, z_dim=48, dim=160):
1362
+ super(WanVideoVAE, self).__init__()
1363
+
1364
+ mean = [
1365
+ -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
1366
+ -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
1367
+ -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
1368
+ -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
1369
+ -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
1370
+ 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667
1371
+ ]
1372
+ std = [
1373
+ 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
1374
+ 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
1375
+ 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
1376
+ 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
1377
+ 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
1378
+ 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744
1379
+ ]
1380
+ self.mean = torch.tensor(mean)
1381
+ self.std = torch.tensor(std)
1382
+ self.scale = [self.mean, 1.0 / self.std]
1383
+
1384
+ # init model
1385
+ self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False)
1386
+ self.upsampling_factor = 16
1387
+ self.z_dim = z_dim
1388
+
1389
+
1390
+ # ─────────────────────────────────────────────────────────────────────────────
1391
+ # Diffusers-compatible wrapper (formerly kiwi_vae.py)
1392
+ # ─────────────────────────────────��───────────────────────────────────────────
1393
+
1394
+ @dataclass
1395
+ class LatentDist:
1396
+ mu: torch.Tensor
1397
+
1398
+ def sample(self):
1399
+ return self.mu
1400
+
1401
+
1402
+ @dataclass
1403
+ class EncoderOutput:
1404
+ latent_dist: LatentDist
1405
+
1406
+
1407
+ @dataclass
1408
+ class DecoderOutput:
1409
+ sample: torch.Tensor
1410
+
1411
+
1412
+ class VAE(VideoVAE_, ModelMixin, ConfigMixin):
1413
+ """
1414
+ Diffusers-compatible VAE wrapper around the original Wan VideoVAE.
1415
+ Loads weights directly from diffusion_pytorch_model.safetensors.
1416
+ """
1417
+
1418
+ @register_to_config
1419
+ def __init__(
1420
+ self,
1421
+ z_dim: int = 48,
1422
+ dim: int = 160,
1423
+ dim_mult: List[int] = [1, 2, 4, 4],
1424
+ num_res_blocks: int = 2,
1425
+ attn_scales: List[float] = [],
1426
+ temperal_downsample: List[bool] = [False, True, True],
1427
+ dropout: float = 0.0,
1428
+ vae_pth: str = "wan_vae.pth",
1429
+ latents_mean: Optional[List[float]] = None,
1430
+ latents_std: Optional[List[float]] = None,
1431
+ ):
1432
+ # Build the actual VAE backbone so diffusers can load weights without mismatch.
1433
+ if z_dim == 48:
1434
+ VideoVAE38_.__init__(
1435
+ self,
1436
+ dim=dim,
1437
+ z_dim=z_dim,
1438
+ dim_mult=dim_mult,
1439
+ num_res_blocks=num_res_blocks,
1440
+ attn_scales=attn_scales,
1441
+ temperal_downsample=temperal_downsample,
1442
+ dropout=dropout,
1443
+ )
1444
+ self._use_38 = True
1445
+ self.upsampling_factor = 16
1446
+ else:
1447
+ VideoVAE_.__init__(
1448
+ self,
1449
+ dim=dim,
1450
+ z_dim=z_dim,
1451
+ dim_mult=dim_mult,
1452
+ num_res_blocks=num_res_blocks,
1453
+ attn_scales=attn_scales,
1454
+ temperal_downsample=temperal_downsample,
1455
+ dropout=dropout,
1456
+ )
1457
+ self._use_38 = False
1458
+ self.upsampling_factor = 8
1459
+
1460
+ # Keep for config compatibility; weights are loaded by diffusers.
1461
+ self._vae_pth = vae_pth
1462
+ self.z_dim = z_dim
1463
+
1464
+ # Build latent normalization scale: [mean, 1/std]
1465
+ if latents_mean is not None and latents_std is not None:
1466
+ mean = torch.tensor(latents_mean)
1467
+ std = torch.tensor(latents_std)
1468
+ self._scale = [mean, 1.0 / std]
1469
+ else:
1470
+ self._scale = [torch.zeros(z_dim), torch.ones(z_dim)]
1471
+
1472
+ def encode(self, x):
1473
+ x = x.to(dtype=next(self.parameters()).dtype)
1474
+ if self._use_38:
1475
+ mu = VideoVAE38_.encode(self, x, self._scale)
1476
+ else:
1477
+ mu = VideoVAE_.encode(self, x, self._scale)
1478
+ return EncoderOutput(latent_dist=LatentDist(mu=mu))
1479
+
1480
+ def decode(self, z):
1481
+ z = z.to(dtype=next(self.parameters()).dtype)
1482
+ if self._use_38:
1483
+ out = VideoVAE38_.decode(self, z, self._scale)
1484
+ else:
1485
+ out = VideoVAE_.decode(self, z, self._scale)
1486
+ return DecoderOutput(sample=out)