abreza commited on
Commit
6445a3f
·
1 Parent(s): 89a10ef

add ttm pipelines

Browse files
pipelines/cog_pipeline.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Noam Rotstein
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ #
14
+ # Adapted from Hugging Face Diffusers (Apache-2.0):
15
+ # https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py
16
+
17
+ try:
18
+ from dataclasses import dataclass
19
+ import math
20
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21
+ import torch
22
+ from transformers import T5EncoderModel, T5Tokenizer
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.image_processor import PipelineImageInput
25
+ from diffusers.models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
26
+ from diffusers.schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
27
+ from diffusers.utils import (
28
+ is_torch_xla_available,
29
+ logging,
30
+ replace_example_docstring,
31
+ )
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+ from diffusers.video_processor import VideoProcessor
34
+ from diffusers.pipelines.cogvideo.pipeline_output import CogVideoXPipelineOutput
35
+ from diffusers.pipelines.cogvideo.pipeline_cogvideox_image2video import retrieve_timesteps
36
+ from diffusers import CogVideoXImageToVideoPipeline
37
+
38
+ import torch.nn.functional as F
39
+ from pipelines.utils import load_video_to_tensor
40
+
41
+ except ImportError as e:
42
+ raise ImportError(f"Required module not found: {e}. Please install it before running this script. "
43
+ f"For installation instructions, see: https://github.com/zai-org/CogVideo")
44
+
45
+
46
+ try:
47
+ if is_torch_xla_available():
48
+ import torch_xla.core.xla_model as xm
49
+ XLA_AVAILABLE = True
50
+ else:
51
+ XLA_AVAILABLE = False
52
+ except ImportError:
53
+ XLA_AVAILABLE = False
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+
58
+ EXAMPLE_DOC_STRING = """
59
+ """
60
+
61
+
62
+ class CogVideoXImageToVideoTTMPipeline(CogVideoXImageToVideoPipeline):
63
+ r"""
64
+ Pipeline for image-to-video generation using CogVideoX combined with Time to Move (TTM).
65
+ This model inherits from [`CogVideoXImageToVideoPipeline`].
66
+ """
67
+ _optional_components = []
68
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
69
+
70
+ _callback_tensor_inputs = [
71
+ "latents",
72
+ "prompt_embeds",
73
+ "negative_prompt_embeds",
74
+ ]
75
+
76
+ def __init__(
77
+ self,
78
+ tokenizer: T5Tokenizer,
79
+ text_encoder: T5EncoderModel,
80
+ vae: AutoencoderKLCogVideoX,
81
+ transformer: CogVideoXTransformer3DModel,
82
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
83
+ ):
84
+ super().__init__(
85
+ tokenizer=tokenizer,
86
+ text_encoder=text_encoder,
87
+ vae=vae,
88
+ transformer=transformer,
89
+ scheduler=scheduler,
90
+ )
91
+
92
+ self.register_modules(
93
+ tokenizer=tokenizer,
94
+ text_encoder=text_encoder,
95
+ vae=vae,
96
+ transformer=transformer,
97
+ scheduler=scheduler,
98
+ )
99
+ self.vae_scale_factor_spatial = (
100
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
101
+ )
102
+ self.vae_scale_factor_temporal = (
103
+ self.vae.config.temporal_compression_ratio if getattr(self, "vae", None) else 4
104
+ )
105
+ self.vae_scaling_factor_image = self.vae.config.scaling_factor if getattr(self, "vae", None) else 0.7
106
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
107
+
108
+
109
+ @torch.no_grad()
110
+ def encode_frames(self, frames: torch.Tensor, vae_scale_factor: float = None) -> torch.Tensor:
111
+ """Encode video frames into latent space with shape (B, F, C, H, W). Input shape (B, C, F, H, W), expected range [-1, 1]."""
112
+ latents = self.vae.encode(frames)[0].sample()
113
+ # latents = self.vae.encode(frames)[0].mode()
114
+ vae_scale_factor = vae_scale_factor or self.vae_scaling_factor_image
115
+ latents = latents * vae_scale_factor
116
+ return latents.permute(0, 2, 1, 3, 4).contiguous() # shape (B, C, F, H, W) -> (B, F, C, H, W)
117
+
118
+
119
+ def convert_rgb_mask_to_latent_mask(self, mask: torch.Tensor) -> torch.Tensor:
120
+ """
121
+ Convert a per-frame mask [T, 1, H, W] to latent resolution [1, T_latent, 1, H', W'].
122
+ T_latent groups frames by the temporal VAE downsample factor k = vae_scale_factor_temporal:
123
+ [0], [1..k], [k+1..2k], ...
124
+ """
125
+ k = self.vae_scale_factor_temporal
126
+
127
+ mask0 = mask[0:1] # [1,1,H,W]
128
+ mask1 = mask[1::k] # [T'-1,1,H,W]
129
+ sampled = torch.cat([mask0, mask1], dim=0) # [T',1,H,W]
130
+ pooled = sampled.permute(1, 0, 2, 3).unsqueeze(0)
131
+
132
+ # Up-sample spatially to match latent spatial resolution
133
+ s = self.vae_scale_factor_spatial
134
+ H_latent = pooled.shape[-2] // s
135
+ W_latent = pooled.shape[-1] // s
136
+ pooled = F.interpolate(pooled, size=(pooled.shape[2], H_latent, W_latent), mode="nearest")
137
+
138
+ # Back to [1, T_latent, 1, H, W]
139
+ latent_mask = pooled.permute(0, 2, 1, 3, 4)
140
+
141
+ return latent_mask
142
+
143
+
144
+ @torch.no_grad()
145
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
146
+ def __call__(
147
+ self,
148
+ image: PipelineImageInput,
149
+ prompt: Optional[Union[str, List[str]]] = None,
150
+ negative_prompt: Optional[Union[str, List[str]]] = None,
151
+ height: Optional[int] = None,
152
+ width: Optional[int] = None,
153
+ num_frames: int = 49,
154
+ num_inference_steps: int = 50,
155
+ timesteps: Optional[List[int]] = None,
156
+ guidance_scale: float = 6,
157
+ use_dynamic_cfg: bool = False,
158
+ num_videos_per_prompt: int = 1,
159
+ eta: float = 0.0,
160
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
161
+ latents: Optional[torch.FloatTensor] = None,
162
+ prompt_embeds: Optional[torch.FloatTensor] = None,
163
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
164
+ output_type: str = "pil",
165
+ return_dict: bool = True,
166
+ attention_kwargs: Optional[Dict[str, Any]] = None,
167
+ callback_on_step_end: Optional[
168
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
169
+ ] = None,
170
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
171
+ max_sequence_length: int = 226,
172
+ motion_signal_video_path: Optional[str] = None,
173
+ motion_signal_mask_path: Optional[str] = None,
174
+ tweak_index: int = 0,
175
+ tstrong_index: int = 0
176
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
177
+ """
178
+ Function invoked when calling the pipeline for generation.
179
+
180
+ Args:
181
+ image (`PipelineImageInput`):
182
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
183
+ prompt (`str` or `List[str]`, *optional*):
184
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
185
+ instead.
186
+ negative_prompt (`str` or `List[str]`, *optional*):
187
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
188
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
189
+ less than `1`).
190
+ height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
191
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
192
+ width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
193
+ The width in pixels of the generated image. This is set to 720 by default for the best results.
194
+ num_frames (`int`, defaults to `48`):
195
+ Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
196
+ contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
197
+ num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that
198
+ needs to be satisfied is that of divisibility mentioned above.
199
+ num_inference_steps (`int`, *optional*, defaults to 50):
200
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
201
+ expense of slower inference.
202
+ timesteps (`List[int]`, *optional*):
203
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
204
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
205
+ passed will be used. Must be in descending order.
206
+ guidance_scale (`float`, *optional*, defaults to 7.0):
207
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
208
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
209
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
210
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
211
+ usually at the expense of lower image quality.
212
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
213
+ The number of videos to generate per prompt.
214
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
215
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
216
+ to make generation deterministic.
217
+ latents (`torch.FloatTensor`, *optional*):
218
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
219
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
220
+ tensor will be generated by sampling using the supplied random `generator`.
221
+ prompt_embeds (`torch.FloatTensor`, *optional*):
222
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
223
+ provided, text embeddings will be generated from `prompt` input argument.
224
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
225
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
226
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
227
+ argument.
228
+ output_type (`str`, *optional*, defaults to `"pil"`):
229
+ The output format of the generate image. Choose between
230
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
231
+ return_dict (`bool`, *optional*, defaults to `True`):
232
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
233
+ of a plain tuple.
234
+ attention_kwargs (`dict`, *optional*):
235
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
236
+ `self.processor` in
237
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
238
+ callback_on_step_end (`Callable`, *optional*):
239
+ A function that calls at the end of each denoising steps during the inference. The function is called
240
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
241
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
242
+ `callback_on_step_end_tensor_inputs`.
243
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
244
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
245
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
246
+ `._callback_tensor_inputs` attribute of your pipeline class.
247
+ max_sequence_length (`int`, defaults to `226`):
248
+ Maximum sequence length in encoded prompt. Must be consistent with
249
+ `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
250
+ motion_signal_video_path (`str`):
251
+ Path to the video file containing the motion signal to guide the motion of the generated video.
252
+ It should be a crude version of the reference video, with pixels with motion dragged to their target.
253
+ motion_signal_mask_path (`str`):
254
+ Path to the mask video file containing the motion mask of TTM.
255
+ The mask should be a binary with the conditioning motion pixels being 1 and the rest being 0.
256
+ tweak_index (`int`):
257
+ The index of the tweak, from which the denoising process starts.
258
+ tstrong_index (`int`):
259
+ The index of the tweak, from which the denoising process starts in the motion conditioned region.
260
+ Examples:
261
+
262
+ Returns:
263
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] or `tuple`:
264
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
265
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
266
+ """
267
+
268
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
269
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
270
+
271
+ height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
272
+ width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
273
+ num_frames = num_frames or self.transformer.config.sample_frames
274
+
275
+ # 1. Check inputs. Raise error if not correct
276
+ self.check_inputs(
277
+ image=image,
278
+ prompt=prompt,
279
+ height=height,
280
+ width=width,
281
+ negative_prompt=negative_prompt,
282
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
283
+ latents=latents,
284
+ prompt_embeds=prompt_embeds,
285
+ negative_prompt_embeds=negative_prompt_embeds,
286
+ )
287
+ self._guidance_scale = guidance_scale
288
+ self._attention_kwargs = attention_kwargs
289
+ self._current_timestep = None
290
+ self._interrupt = False
291
+
292
+ if motion_signal_mask_path is None:
293
+ raise ValueError("`motion_signal_mask_path` is required for TTM.")
294
+ if motion_signal_video_path is None:
295
+ raise ValueError("`motion_signal_video_path` is required for TTM.")
296
+
297
+ # 2. Default call parameters
298
+ if prompt is not None and isinstance(prompt, str):
299
+ batch_size = 1
300
+ elif prompt is not None and isinstance(prompt, list):
301
+ batch_size = len(prompt)
302
+ else:
303
+ batch_size = prompt_embeds.shape[0]
304
+
305
+ device = self._execution_device
306
+
307
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
308
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
309
+ # corresponds to doing no classifier free guidance.
310
+ do_classifier_free_guidance = guidance_scale > 1.0
311
+
312
+ # 3. Encode input prompt
313
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
314
+ prompt=prompt,
315
+ negative_prompt=negative_prompt,
316
+ do_classifier_free_guidance=do_classifier_free_guidance,
317
+ num_videos_per_prompt=num_videos_per_prompt,
318
+ prompt_embeds=prompt_embeds,
319
+ negative_prompt_embeds=negative_prompt_embeds,
320
+ max_sequence_length=max_sequence_length,
321
+ device=device,
322
+ )
323
+ if do_classifier_free_guidance:
324
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
325
+
326
+ # 4. Prepare timesteps
327
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
328
+ self._num_timesteps = len(timesteps)
329
+
330
+ # 5. Prepare latents
331
+ latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
332
+
333
+ # For CogVideoX 1.5, the latent frames should be padded to make it divisible by patch_size_t
334
+ patch_size_t = self.transformer.config.patch_size_t
335
+ additional_frames = 0
336
+ if patch_size_t is not None and latent_frames % patch_size_t != 0:
337
+ additional_frames = patch_size_t - latent_frames % patch_size_t
338
+ num_frames += additional_frames * self.vae_scale_factor_temporal
339
+
340
+ image = self.video_processor.preprocess(image, height=height, width=width).to(
341
+ device, dtype=prompt_embeds.dtype
342
+ )
343
+
344
+ latent_channels = self.transformer.config.in_channels // 2
345
+ latents, image_latents = self.prepare_latents(
346
+ image,
347
+ batch_size * num_videos_per_prompt,
348
+ latent_channels,
349
+ num_frames,
350
+ height,
351
+ width,
352
+ prompt_embeds.dtype,
353
+ device,
354
+ generator,
355
+ latents,
356
+ )
357
+
358
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
359
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
360
+
361
+ # 7. Create rotary embeds if required
362
+ image_rotary_emb = (
363
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
364
+ if self.transformer.config.use_rotary_positional_embeddings
365
+ else None
366
+ )
367
+
368
+ # 8. Create ofs embeds if required
369
+ ofs_emb = None if self.transformer.config.ofs_embed_dim is None else latents.new_full((1,), fill_value=2.0)
370
+
371
+ # 9. Initialize for TTM
372
+ ref_vid = load_video_to_tensor(motion_signal_video_path).to(device=device) # shape [1, C, T, H, W]
373
+ refB, refC, refT, refH, refW = ref_vid.shape
374
+ ref_vid = F.interpolate(
375
+ ref_vid.permute(0, 2, 1, 3, 4).reshape(refB*refT, refC, refH, refW),
376
+ size=(height, width), mode="bicubic", align_corners=True,
377
+ ).reshape(refB, refT, refC, height, width).permute(0, 2, 1, 3, 4)
378
+
379
+ ref_vid = self.video_processor.normalize(ref_vid.to(dtype=self.vae.dtype)) # Normalize and convert dtype for VAE encoding
380
+ ref_latents = self.encode_frames(ref_vid).float().detach() # shape [1, T, C, H, W]
381
+
382
+ ref_mask = load_video_to_tensor(motion_signal_mask_path).to(device=device) # shape [1, C, T, H, W]
383
+ mB, mC, mT, mH, mW = ref_mask.shape
384
+
385
+ ref_mask = F.interpolate(
386
+ ref_mask.permute(0, 2, 1, 3, 4).reshape(mB*mT, mC, mH, mW),
387
+ size=(height, width), mode="nearest",
388
+ ).reshape(mB, mT, mC, height, width).permute(0, 2, 1, 3, 4)
389
+ ref_mask = ref_mask[0].permute(1, 0, 2, 3).contiguous() # (1, C, T, H, W) -> (T, H, W, 1)
390
+
391
+ if len(ref_mask.shape) == 4:
392
+ ref_mask = ref_mask.unsqueeze(0)
393
+
394
+ ref_mask = ref_mask[0,:,:1].contiguous() # (1, T, C, H, W) -> (T, 1, H, W)
395
+ ref_mask = (ref_mask > 0.5).float().max(dim=1, keepdim=True)[0] # [T, 1, H, W]
396
+ motion_mask = self.convert_rgb_mask_to_latent_mask(ref_mask) # [1, T, 1, H, W]
397
+ background_mask = 1.0 - motion_mask
398
+
399
+ if tweak_index >= 0:
400
+ tweak = self.scheduler.timesteps[tweak_index]
401
+ fixed_noise = randn_tensor(
402
+ ref_latents.shape,
403
+ generator=generator,
404
+ device=ref_latents.device,
405
+ dtype=ref_latents.dtype,
406
+ )
407
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, tweak.long())
408
+ latents = noisy_latents.to(dtype=latents.dtype, device=latents.device)
409
+ else:
410
+ tweak = torch.tensor(-1)
411
+ fixed_noise = randn_tensor(
412
+ ref_latents.shape,
413
+ generator=generator,
414
+ device=ref_latents.device,
415
+ dtype=ref_latents.dtype,
416
+ )
417
+ tweak_index = 0
418
+
419
+ # 10. Denoising loop
420
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
421
+
422
+ # logging
423
+ # ------------------------------------------------------------------
424
+ with self.progress_bar(total=len(timesteps) - tweak_index) as progress_bar:
425
+ # for DPM-solver++
426
+ old_pred_original_sample = None
427
+ for i, t in enumerate(timesteps[tweak_index:]):
428
+ if self.interrupt:
429
+ continue
430
+
431
+ self._current_timestep = t
432
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
433
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
434
+
435
+ latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents
436
+ latent_model_input = torch.cat([latent_model_input, latent_image_input], dim=2)
437
+
438
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
439
+ timestep = t.expand(latent_model_input.shape[0])
440
+
441
+ # predict noise model_output
442
+ noise_pred = self.transformer(
443
+ hidden_states=latent_model_input,
444
+ encoder_hidden_states=prompt_embeds,
445
+ timestep=timestep,
446
+ ofs=ofs_emb,
447
+ image_rotary_emb=image_rotary_emb,
448
+ attention_kwargs=attention_kwargs,
449
+ return_dict=False,
450
+ )[0]
451
+ noise_pred = noise_pred.float()
452
+
453
+ # perform guidance
454
+ if use_dynamic_cfg:
455
+ self._guidance_scale = 1 + guidance_scale * (
456
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
457
+ )
458
+ if do_classifier_free_guidance:
459
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
460
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
461
+
462
+ # compute the previous noisy sample x_t -> x_t-1
463
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
464
+ latents, old_pred_original_sample = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)
465
+ else:
466
+ latents, old_pred_original_sample = self.scheduler.step(
467
+ noise_pred,
468
+ old_pred_original_sample,
469
+ t,
470
+ timesteps[i - 1] if i > 0 else None,
471
+ latents,
472
+ **extra_step_kwargs,
473
+ return_dict=False,
474
+ )
475
+
476
+ # In between tweak and tstrong, replace mask with noisy reference latents
477
+ in_between_tweak_tstrong = (i+tweak_index) < tstrong_index
478
+
479
+ if in_between_tweak_tstrong:
480
+ if i+tweak_index+1 < len(timesteps):
481
+ prev_t = timesteps[i+tweak_index+1]
482
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, prev_t.long()).to(dtype=latents.dtype, device=latents.device)
483
+ latents = latents * background_mask + noisy_latents * motion_mask
484
+ else:
485
+ latents = latents * background_mask + ref_latents * motion_mask
486
+
487
+ latents = latents.to(prompt_embeds.dtype)
488
+
489
+ # call the callback, if provided
490
+ if callback_on_step_end is not None:
491
+ callback_kwargs = {}
492
+ for k in callback_on_step_end_tensor_inputs:
493
+ callback_kwargs[k] = locals()[k]
494
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
495
+
496
+ latents = callback_outputs.pop("latents", latents)
497
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
498
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
499
+
500
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
501
+ progress_bar.update()
502
+
503
+ if XLA_AVAILABLE:
504
+ xm.mark_step()
505
+
506
+ self._current_timestep = None
507
+
508
+ if not output_type == "latent":
509
+ # Discard any padding frames that were added for CogVideoX 1.5
510
+ latents = latents[:, additional_frames:]
511
+ frames = self.decode_latents(latents)
512
+ video = self.video_processor.postprocess_video(video=frames, output_type=output_type)
513
+ else:
514
+ video = latents
515
+
516
+ # Offload all models
517
+ self.maybe_free_model_hooks()
518
+
519
+ if not return_dict:
520
+ return (video,)
521
+
522
+ return CogVideoXPipelineOutput(
523
+ frames=video,
524
+ )
pipelines/svd_pipeline.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Noam Rotstein
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ #
14
+ # Adapted from Hugging Face Diffusers (Apache-2.0):
15
+ # https://github.com/huggingface/diffusers/blob/8abc7aeb715c0149ee0a9982b2d608ce97f55215/src/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py#L147
16
+
17
+ try:
18
+ import inspect
19
+ from dataclasses import dataclass
20
+ from typing import Callable, Dict, List, Optional, Union
21
+ import numpy as np
22
+ import PIL.Image
23
+ import torch
24
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
25
+ from diffusers.models import AutoencoderKLTemporalDecoder, UNetSpatioTemporalConditionModel
26
+ from diffusers.schedulers import EulerDiscreteScheduler
27
+ from diffusers.utils import BaseOutput, is_torch_xla_available, logging, replace_example_docstring
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+ from diffusers.video_processor import VideoProcessor
30
+ import torch.nn.functional as F
31
+ from diffusers.pipelines.stable_video_diffusion import StableVideoDiffusionPipeline
32
+ from pipelines.utils import load_video_to_tensor
33
+
34
+ except ImportError as e:
35
+ raise ImportError(f"Required module not found: {e}. Please install it before running this script. "
36
+ f"For installation instructions, see:https://github.com/Stability-AI/generative-models")
37
+
38
+ if is_torch_xla_available():
39
+ import torch_xla.core.xla_model as xm
40
+
41
+ XLA_AVAILABLE = True
42
+ else:
43
+ XLA_AVAILABLE = False
44
+
45
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
46
+
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ """
50
+
51
+
52
+ def _append_dims(x, target_dims):
53
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
54
+ dims_to_append = target_dims - x.ndim
55
+ if dims_to_append < 0:
56
+ raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
57
+ return x[(...,) + (None,) * dims_to_append]
58
+
59
+
60
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
61
+ def retrieve_timesteps(
62
+ scheduler,
63
+ num_inference_steps: Optional[int] = None,
64
+ device: Optional[Union[str, torch.device]] = None,
65
+ timesteps: Optional[List[int]] = None,
66
+ sigmas: Optional[List[float]] = None,
67
+ **kwargs,
68
+ ):
69
+ r"""
70
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
71
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
72
+
73
+ Args:
74
+ scheduler (`SchedulerMixin`):
75
+ The scheduler to get timesteps from.
76
+ num_inference_steps (`int`):
77
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
78
+ must be `None`.
79
+ device (`str` or `torch.device`, *optional*):
80
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
81
+ timesteps (`List[int]`, *optional*):
82
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
83
+ `num_inference_steps` and `sigmas` must be `None`.
84
+ sigmas (`List[float]`, *optional*):
85
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
86
+ `num_inference_steps` and `timesteps` must be `None`.
87
+
88
+ Returns:
89
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
90
+ second element is the number of inference steps.
91
+ """
92
+ if timesteps is not None and sigmas is not None:
93
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
94
+ if timesteps is not None:
95
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
96
+ if not accepts_timesteps:
97
+ raise ValueError(
98
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
99
+ f" timestep schedules. Please check whether you are using the correct scheduler."
100
+ )
101
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
102
+ timesteps = scheduler.timesteps
103
+ num_inference_steps = len(timesteps)
104
+ elif sigmas is not None:
105
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
106
+ if not accept_sigmas:
107
+ raise ValueError(
108
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
109
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
110
+ )
111
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
112
+ timesteps = scheduler.timesteps
113
+ num_inference_steps = len(timesteps)
114
+ else:
115
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
116
+ timesteps = scheduler.timesteps
117
+ return timesteps, num_inference_steps
118
+
119
+
120
+ @dataclass
121
+ class StableVideoDiffusionPipelineOutput(BaseOutput):
122
+ r"""
123
+ Output class for Stable Video Diffusion pipeline.
124
+
125
+ Args:
126
+ frames (`[List[List[PIL.Image.Image]]`, `np.ndarray`, `torch.Tensor`]):
127
+ List of denoised PIL images of length `batch_size` or numpy array or torch tensor of shape `(batch_size,
128
+ num_frames, height, width, num_channels)`.
129
+ """
130
+
131
+ frames: Union[List[List[PIL.Image.Image]], np.ndarray, torch.Tensor]
132
+
133
+
134
+ class StableVideoDiffusionTTMPipeline(StableVideoDiffusionPipeline):
135
+ r"""
136
+ Pipeline to generate video from an input image using Stable Video Diffusion combined with Time to Move (TTM).
137
+ This model inherits from [`StableVideoDiffusionPipeline`].
138
+ """
139
+
140
+ model_cpu_offload_seq = "image_encoder->unet->vae"
141
+ _callback_tensor_inputs = ["latents"]
142
+
143
+ def __init__(
144
+ self,
145
+ vae: AutoencoderKLTemporalDecoder,
146
+ image_encoder: CLIPVisionModelWithProjection,
147
+ unet: UNetSpatioTemporalConditionModel,
148
+ scheduler: EulerDiscreteScheduler,
149
+ feature_extractor: CLIPImageProcessor,
150
+ ):
151
+ super().__init__(
152
+ vae=vae,
153
+ image_encoder=image_encoder,
154
+ unet=unet,
155
+ scheduler=scheduler,
156
+ feature_extractor=feature_extractor,
157
+ )
158
+
159
+ self.register_modules(
160
+ vae=vae,
161
+ image_encoder=image_encoder,
162
+ unet=unet,
163
+ scheduler=scheduler,
164
+ feature_extractor=feature_extractor,
165
+ )
166
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
167
+ self.video_processor = VideoProcessor(do_resize=True, vae_scale_factor=self.vae_scale_factor)
168
+
169
+
170
+ def encode_frames(self, frames: torch.Tensor, num_frames: int, encode_chunk_size: int = 14):
171
+ """
172
+ Args:
173
+ frames: [B, C, T, H, W] tensor, preprocessed to VAE's expected range (e.g., [-1, 1]).
174
+ num_frames: T (used for reshaping back).
175
+ encode_chunk_size: process at most this many frames at a time to avoid OOM.
176
+
177
+ Returns:
178
+ latents: [B, T, C_latent, h, w], multiplied by self.vae.config.scaling_factor.
179
+
180
+ Notes:
181
+ - Stochastic: samples from posterior (latent_dist.sample()).
182
+ - If the VAE's compiled module hides the signature, we inspect the original .forward
183
+ and pass num_frames only if it's accepted (same pattern as decode).
184
+ """
185
+ if frames.dim() != 5:
186
+ raise ValueError(f"Expected frames with shape [B, C, T, H, W], got {list(frames.shape)}")
187
+ B, C, T, H, W = frames.shape
188
+
189
+ # [B, C, T, H, W] -> [B, T, C, H, W] -> [B*T, C, H, W]
190
+ frames_bt = frames.permute(0, 2, 1, 3, 4).reshape(-1, C, H, W)
191
+
192
+ # Use the *encode* signature (decoder may accept num_frames, encoder usually doesn't)
193
+ encode_fn = self.vae._orig_mod.encode if hasattr(self.vae, "_orig_mod") else self.vae.encode
194
+ try:
195
+ accepts_num_frames = ("num_frames" in inspect.signature(encode_fn).parameters)
196
+ except (TypeError, ValueError):
197
+ # Signature might be obscured by wrappers/compilation; be conservative
198
+ accepts_num_frames = False
199
+
200
+ latents_chunks = []
201
+ for i in range(0, frames_bt.shape[0], encode_chunk_size):
202
+ chunk = frames_bt[i : i + encode_chunk_size]
203
+
204
+ # match VAE device/dtype to avoid implicit casts
205
+ chunk = chunk.to(device=self.vae.device, dtype=self.vae.dtype)
206
+
207
+ encode_kwargs = {}
208
+ if accepts_num_frames:
209
+ # This will normally be False for AutoencoderKLTemporalDecoder.encode()
210
+ encode_kwargs["num_frames"] = chunk.shape[0]
211
+
212
+ # Be robust to unexpected wrappers hiding the signature
213
+ try:
214
+ enc_out = self.vae.encode(chunk, **encode_kwargs)
215
+ except TypeError as e:
216
+ if "unexpected keyword argument 'num_frames'" in str(e):
217
+ enc_out = self.vae.encode(chunk)
218
+ else:
219
+ raise
220
+
221
+ posterior = enc_out.latent_dist # DiagonalGaussianDistribution
222
+ latents_chunks.append(posterior.sample())
223
+
224
+ latents = torch.cat(latents_chunks, dim=0) # [B*T, C_lat, h, w]
225
+ latents = latents * self.vae.config.scaling_factor
226
+
227
+ # [B*T, C_lat, h, w] -> [B, T, C_lat, h, w]
228
+ latents = latents.reshape(B, num_frames, *latents.shape[1:])
229
+
230
+ return latents
231
+
232
+ def convert_rgb_mask_to_latent_mask(self, mask: torch.Tensor, first_different=True) -> torch.Tensor:
233
+ """
234
+ Args:
235
+ mask: [T, 1, H, W] tensor (0/1 or any float in [0,1]).
236
+ Returns:
237
+ latent_mask: [1, T_latent, 1, H, W], where
238
+ T_latent = ceil(T / self.vae_scale_factor_temporal)
239
+ For CogVideoX-style VAE (k=4), groups are [0], [1-4], [5-8], ..., achieved by
240
+ pre-padding zeros at the start before max-pooling with stride=k.
241
+ """
242
+ T, _, H, W = mask.shape
243
+
244
+ k = self.vae_scale_factor_temporal
245
+ # Pre-pad zeros along time so that the first pooled window corresponds to frame 0 alone
246
+ if first_different:
247
+ num_pad = (k - (T % k)) % k
248
+ pad = torch.zeros((num_pad, 1, H, W), device=mask.device, dtype=mask.dtype)
249
+ mask = torch.cat([pad, mask], dim=0)
250
+
251
+
252
+ # [T,1,H,W] -> [1,1,T,H,W]
253
+ x = mask.permute(1, 0, 2, 3).unsqueeze(0)
254
+ if k > 1:
255
+ # Max-pool over time with kernel=stride=k (no spatial pooling)
256
+ pooled = F.max_pool3d(x, kernel_size=(k, 1, 1), stride=(k, 1, 1))
257
+ else:
258
+ pooled = x
259
+
260
+ # Up-sample spatially to match latent spatial resolution
261
+ s = self.vae_scale_factor_spatial
262
+ H_latent = pooled.shape[-2] // s
263
+ W_latent = pooled.shape[-1] // s
264
+ pooled = F.interpolate(pooled, size=(pooled.shape[2], H_latent, W_latent), mode="nearest")
265
+
266
+ # Back to [1, T_latent, 1, H, W]
267
+ latent_mask = pooled.permute(0, 2, 1, 3, 4)
268
+
269
+ return latent_mask
270
+
271
+
272
+ @torch.no_grad()
273
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
274
+ def __call__(
275
+ self,
276
+ image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.Tensor],
277
+ height: int = 576,
278
+ width: int = 1024,
279
+ num_frames: Optional[int] = None,
280
+ num_inference_steps: int = 25,
281
+ sigmas: Optional[List[float]] = None,
282
+ min_guidance_scale: float = 1.0,
283
+ max_guidance_scale: float = 3.0,
284
+ fps: int = 7,
285
+ motion_bucket_id: int = 127,
286
+ noise_aug_strength: float = 0.02,
287
+ decode_chunk_size: Optional[int] = None,
288
+ num_videos_per_prompt: Optional[int] = 1,
289
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
290
+ latents: Optional[torch.Tensor] = None,
291
+ output_type: Optional[str] = "pil",
292
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
293
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
294
+ return_dict: bool = True,
295
+ motion_signal_video_path: Optional[str] = None,
296
+ motion_signal_mask_path: Optional[str] = None,
297
+ tweak_index: int = 0,
298
+ tstrong_index: int = 0
299
+ ):
300
+ r"""
301
+ The call function to the pipeline for generation.
302
+
303
+ Args:
304
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.Tensor`):
305
+ Image(s) to guide image generation. If you provide a tensor, the expected value range is between `[0,
306
+ 1]`.
307
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
308
+ The height in pixels of the generated image.
309
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
310
+ The width in pixels of the generated image.
311
+ num_frames (`int`, *optional*):
312
+ The number of video frames to generate. Defaults to `self.unet.config.num_frames` (14 for
313
+ `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt`).
314
+ num_inference_steps (`int`, *optional*, defaults to 25):
315
+ The number of denoising steps. More denoising steps usually lead to a higher quality video at the
316
+ expense of slower inference. This parameter is modulated by `strength`.
317
+ sigmas (`List[float]`, *optional*):
318
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
319
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
320
+ will be used.
321
+ min_guidance_scale (`float`, *optional*, defaults to 1.0):
322
+ The minimum guidance scale. Used for the classifier free guidance with first frame.
323
+ max_guidance_scale (`float`, *optional*, defaults to 3.0):
324
+ The maximum guidance scale. Used for the classifier free guidance with last frame.
325
+ fps (`int`, *optional*, defaults to 7):
326
+ Frames per second. The rate at which the generated images shall be exported to a video after
327
+ generation. Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training.
328
+ motion_bucket_id (`int`, *optional*, defaults to 127):
329
+ Used for conditioning the amount of motion for the generation. The higher the number the more motion
330
+ will be in the video.
331
+ noise_aug_strength (`float`, *optional*, defaults to 0.02):
332
+ The amount of noise added to the init image, the higher it is the less the video will look like the
333
+ init image. Increase it for more motion.
334
+ decode_chunk_size (`int`, *optional*):
335
+ The number of frames to decode at a time. Higher chunk size leads to better temporal consistency at the
336
+ expense of more memory usage. By default, the decoder decodes all frames at once for maximal quality.
337
+ For lower memory usage, reduce `decode_chunk_size`.
338
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
339
+ The number of videos to generate per prompt.
340
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
341
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
342
+ generation deterministic.
343
+ motion_signal_video_path (`str`):
344
+ Path to the video file containing the motion signal to guide the motion of the generated video.
345
+ It should be a crude version of the reference video, with pixels with motion dragged to their target.
346
+ motion_signal_mask_path (`str`):
347
+ Path to the mask video file containing the motion mask of TTM.
348
+ The mask should be a binary with the conditioning motion pixels being 1 and the rest being 0.
349
+ tweak_index (`int`):
350
+ The index of the tweak, from which the denoising process starts.
351
+ tstrong_index (`int`):
352
+ The index of the tweak, from which the denoising process starts in the motion conditioned region.
353
+ latents (`torch.Tensor`, *optional*):
354
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
355
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
356
+ tensor is generated by sampling using the supplied random `generator`.
357
+ output_type (`str`, *optional*, defaults to `"pil"`):
358
+ The output format of the generated image. Choose between `pil`, `np` or `pt`.
359
+ callback_on_step_end (`Callable`, *optional*):
360
+ A function that is called at the end of each denoising step during inference. The function is called
361
+ with the following arguments:
362
+ `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`.
363
+ `callback_kwargs` will include a list of all tensors as specified by
364
+ `callback_on_step_end_tensor_inputs`.
365
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
366
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
367
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
368
+ `._callback_tensor_inputs` attribute of your pipeline class.
369
+ return_dict (`bool`, *optional*, defaults to `True`):
370
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
371
+ plain tuple.
372
+
373
+ Examples:
374
+
375
+ Returns:
376
+ [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`:
377
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is
378
+ returned, otherwise a `tuple` of (`List[List[PIL.Image.Image]]` or `np.ndarray` or `torch.Tensor`) is
379
+ returned.
380
+ """
381
+ # 0. Default height and width to unet
382
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
383
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
384
+
385
+ num_frames = num_frames if num_frames is not None else self.unet.config.num_frames
386
+ decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames
387
+
388
+ # 1. Check inputs. Raise error if not correct
389
+ self.check_inputs(image, height, width)
390
+
391
+ if motion_signal_mask_path is None:
392
+ raise ValueError("`motion_signal_mask_path` is required for TTM.")
393
+ if motion_signal_video_path is None:
394
+ raise ValueError("`motion_signal_video_path` is required for TTM.")
395
+
396
+ # 2. Define call parameters
397
+ if isinstance(image, PIL.Image.Image):
398
+ batch_size = 1
399
+ elif isinstance(image, list):
400
+ batch_size = len(image)
401
+ else:
402
+ batch_size = image.shape[0]
403
+ device = self._execution_device
404
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
405
+ # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
406
+ # corresponds to doing no classifier free guidance.
407
+ self._guidance_scale = max_guidance_scale
408
+
409
+ # 3. Encode input image
410
+ image_embeddings = self._encode_image(image, device, num_videos_per_prompt, self.do_classifier_free_guidance)
411
+
412
+ # NOTE: Stable Video Diffusion was conditioned on fps - 1, which is why it is reduced here.
413
+ # See: https://github.com/Stability-AI/generative-models/blob/ed0997173f98eaf8f4edf7ba5fe8f15c6b877fd3/scripts/sampling/simple_video_sample.py#L188
414
+ fps = fps - 1
415
+
416
+ # 4. Encode input image using VAE
417
+ image = self.video_processor.preprocess(image, height=height, width=width).to(device)
418
+ noise = randn_tensor(image.shape, generator=generator, device=device, dtype=image.dtype)
419
+ image = image + noise_aug_strength * noise
420
+
421
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
422
+ if needs_upcasting:
423
+ self.vae.to(dtype=torch.float32)
424
+
425
+ image_latents = self._encode_vae_image(
426
+ image,
427
+ device=device,
428
+ num_videos_per_prompt=num_videos_per_prompt,
429
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
430
+ )
431
+ image_latents = image_latents.to(image_embeddings.dtype)
432
+
433
+ # cast back to fp16 if needed
434
+ if needs_upcasting:
435
+ self.vae.to(dtype=torch.float16)
436
+
437
+ # Repeat the image latents for each frame so we can concatenate them with the noise
438
+ # image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width]
439
+ image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)
440
+
441
+ # 5. Get Added Time IDs
442
+ added_time_ids = self._get_add_time_ids(
443
+ fps,
444
+ motion_bucket_id,
445
+ noise_aug_strength,
446
+ image_embeddings.dtype,
447
+ batch_size,
448
+ num_videos_per_prompt,
449
+ self.do_classifier_free_guidance,
450
+ )
451
+ added_time_ids = added_time_ids.to(device)
452
+
453
+ # 6. Prepare timesteps
454
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, None, sigmas)
455
+
456
+ # ---- Sanity checks for TTM indices (0 ≤ tstrong < tweak < num_steps) ----
457
+ if not (0 <= tstrong_index < num_inference_steps):
458
+ raise ValueError(f"tstrong_index must be in [0, {num_inference_steps-1}], got {tstrong_index}.")
459
+ if not (0 <= tweak_index < num_inference_steps):
460
+ raise ValueError(f"tweak_index must be in [0, {num_inference_steps-1}], got {tweak_index}.")
461
+ if not (tstrong_index > tweak_index):
462
+ raise ValueError(f"Require tweak_index < tstrong_index, got {tweak_index} >= {tstrong_index}.")
463
+
464
+ # 7. Prepare latent variables
465
+ num_channels_latents = self.unet.config.in_channels
466
+ latents = self.prepare_latents(
467
+ batch_size * num_videos_per_prompt,
468
+ num_frames,
469
+ num_channels_latents,
470
+ height,
471
+ width,
472
+ image_embeddings.dtype,
473
+ device,
474
+ generator,
475
+ latents,
476
+ )
477
+
478
+ # 8. Prepare guidance scale
479
+ guidance_scale = torch.linspace(min_guidance_scale, max_guidance_scale, num_frames).unsqueeze(0)
480
+ guidance_scale = guidance_scale.to(device, latents.dtype)
481
+ guidance_scale = guidance_scale.repeat(batch_size * num_videos_per_prompt, 1)
482
+ guidance_scale = _append_dims(guidance_scale, latents.ndim)
483
+
484
+ self._guidance_scale = guidance_scale
485
+
486
+ # 9. Initialize for TTM
487
+ ref_vid = load_video_to_tensor(motion_signal_video_path).to(device=device) # shape [1, C, T, H, W]
488
+ refB, refC, refT, refH, refW = ref_vid.shape
489
+
490
+ ref_vid = F.interpolate(
491
+ ref_vid.permute(0, 2, 1, 3, 4).reshape(refB*refT, refC, refH, refW),
492
+ size=(height, width), mode="bicubic", align_corners=True,
493
+ ).reshape(refB, refT, refC, height, width).permute(0, 2, 1, 3, 4)
494
+
495
+ ref_vid = self.video_processor.normalize(ref_vid.to(dtype=self.vae.dtype)) # Normalize and convert dtype for VAE encoding
496
+
497
+ if num_frames < refT:
498
+ logger.warning(f"num_frames ({num_frames}) < input frames ({refT}); trimming reference video.")
499
+ ref_vid = ref_vid[:, :, :num_frames]
500
+ elif num_frames > refT:
501
+ raise ValueError(f"num_frames ({num_frames}) is greater than input frames ({refT}). This is not supported.")
502
+
503
+ ref_latents = self.encode_frames(ref_vid, num_frames, decode_chunk_size).detach()
504
+ ref_latents = ref_latents.to(dtype=latents.dtype, device=device)
505
+
506
+ if not hasattr(self, "vae_scale_factor_temporal"): # encode ref video to latents
507
+ if hasattr(self.vae, "scale_factor_temporal"):
508
+ self.vae_scale_factor_temporal = self.vae.scale_factor_temporal
509
+ else:
510
+ if ref_latents.shape[1] == num_frames:
511
+ self.vae_scale_factor_temporal = 1
512
+ else:
513
+ raise ValueError("Please configure the temporal scale factor of the VAE.")
514
+
515
+ self.vae_scale_factor_spatial = self.vae_scale_factor
516
+
517
+ ref_mask = load_video_to_tensor(motion_signal_mask_path).to(device=device) # shape [1, C, T, H, W]
518
+
519
+ mB, mC, mT, mH, mW = ref_mask.shape # do resizing with nearest neighbor to avoid interpolation artifacts
520
+ ref_mask = F.interpolate(
521
+ ref_mask.permute(0, 2, 1, 3, 4).reshape(mB*mT, mC, mH, mW),
522
+ size=(height, width), mode="nearest",
523
+ ).reshape(mB, mT, mC, height, width).permute(0, 2, 1, 3, 4)
524
+ ref_mask = ref_mask[0].permute(1, 0, 2, 3).contiguous() # (1, C, T, H, W) -> (T, H, W, 1)
525
+ if ref_mask.shape[0] > num_frames:
526
+ print(f"Warning: num_frames ({num_frames}) is less than input mask frames ({mT}). Trimming to {num_frames}.")
527
+ ref_mask = ref_mask[:num_frames]
528
+ elif ref_mask.shape[0] < num_frames:
529
+ raise ValueError(f"num_frames ({num_frames}) is greater than input mask frames ({mT}). This is not supported.")
530
+ ref_mask = (ref_mask > 0.5).float().max(dim=1, keepdim=True)[0] # [T, 1, H, W]
531
+ motion_mask = self.convert_rgb_mask_to_latent_mask(ref_mask, False) # [1, T, 1, H, W]
532
+ motion_mask = motion_mask.to(dtype=latents.dtype)
533
+ background_mask = 1.0 - motion_mask
534
+
535
+ if tweak_index >= 0:
536
+ tweak = self.scheduler.timesteps[tweak_index]
537
+ tweak = torch.tensor([tweak], device=device)
538
+ fixed_noise = randn_tensor(ref_latents.shape,
539
+ generator=generator,
540
+ device=ref_latents.device,
541
+ dtype=ref_latents.dtype)
542
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, tweak)
543
+ latents = noisy_latents.to(dtype=latents.dtype, device=latents.device)
544
+ else:
545
+ tweak = torch.tensor(-1)
546
+ fixed_noise = randn_tensor(ref_latents.shape,
547
+ generator=generator,
548
+ device=ref_latents.device,
549
+ dtype=ref_latents.dtype)
550
+ tweak_index = 0
551
+
552
+
553
+ # 10. Denoising loop
554
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
555
+ self._num_timesteps = len(timesteps)
556
+ with self.progress_bar(total=len(timesteps) - tweak_index) as progress_bar:
557
+ for i, t in enumerate(timesteps[tweak_index:]):
558
+ # expand the latents if we are doing classifier free guidance
559
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
560
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
561
+
562
+ # Concatenate image_latents over channels dimension
563
+ latent_model_input = torch.cat([latent_model_input, image_latents], dim=2)
564
+
565
+ # predict the noise residual
566
+ noise_pred = self.unet(
567
+ latent_model_input,
568
+ t,
569
+ encoder_hidden_states=image_embeddings,
570
+ added_time_ids=added_time_ids,
571
+ return_dict=False,
572
+ )[0]
573
+
574
+ # perform guidance
575
+ if self.do_classifier_free_guidance:
576
+ noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
577
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
578
+
579
+ # compute the previous noisy sample x_t -> x_t-1
580
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
581
+
582
+ # In between tweak and tstrong, replace mask with noisy reference latents
583
+ in_between_tweak_tstrong = (i+tweak_index) < tstrong_index
584
+
585
+ if in_between_tweak_tstrong:
586
+ if i+tweak_index+1 < len(timesteps):
587
+ prev_t = torch.tensor([timesteps[i+tweak_index+1]], device=device)
588
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, prev_t).to(dtype=latents.dtype, device=latents.device)
589
+ latents = latents * background_mask + noisy_latents * motion_mask
590
+ elif i+tweak_index+1 == len(timesteps):
591
+ latents = latents * background_mask + ref_latents * motion_mask
592
+ else:
593
+ raise ValueError(f"Unexpected timestep index {i+tweak_index+1} >= {len(timesteps)}")
594
+
595
+ if callback_on_step_end is not None:
596
+ callback_kwargs = {}
597
+ for k in callback_on_step_end_tensor_inputs:
598
+ callback_kwargs[k] = locals()[k]
599
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
600
+
601
+ latents = callback_outputs.pop("latents", latents)
602
+
603
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
604
+ progress_bar.update()
605
+
606
+ if XLA_AVAILABLE:
607
+ xm.mark_step()
608
+
609
+ if not output_type == "latent":
610
+ # cast back to fp16 if needed
611
+ if needs_upcasting:
612
+ self.vae.to(dtype=torch.float16)
613
+ frames = self.decode_latents(latents, num_frames, decode_chunk_size)
614
+ frames = self.video_processor.postprocess_video(video=frames, output_type=output_type)
615
+ else:
616
+ frames = latents
617
+
618
+ self.maybe_free_model_hooks()
619
+
620
+ if not return_dict:
621
+ return frames
622
+
623
+ return StableVideoDiffusionPipelineOutput(
624
+ frames=frames)
pipelines/utils.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Tuple
5
+ import numpy as np
6
+ import cv2
7
+ import torch
8
+
9
+ def validate_inputs(image_path: str, mask_path: str, motion_path: str) -> None:
10
+ for p in [image_path, mask_path, motion_path]:
11
+ if not Path(p).exists():
12
+ raise FileNotFoundError(f"Required file not found: {p}")
13
+
14
+ def compute_hw_from_area(
15
+ image_height: int,
16
+ image_width: int,
17
+ max_area: int,
18
+ mod_value: int,
19
+ ) -> Tuple[int, int]:
20
+ """Compute (height, width) with same math and rounding as original."""
21
+ aspect_ratio = image_height / image_width
22
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
23
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
24
+ return int(height), int(width)
25
+
26
+
27
+ def load_video_to_tensor(video_path):
28
+ """Returns a video tensor from a video file. shape [1, T, C, H, W], [0, 1] range."""
29
+ # load video
30
+ cap = cv2.VideoCapture(video_path)
31
+ frames = []
32
+ while 1:
33
+ ret, frame = cap.read()
34
+ if not ret:
35
+ break
36
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
37
+ frames.append(frame)
38
+ cap.release()
39
+ # Convert frames to tensor, shape [T, H, W, C], [0, 1] range
40
+ frames = np.array(frames)
41
+
42
+ video_tensor = torch.tensor(frames)
43
+ video_tensor = video_tensor.permute(0, 3, 1, 2).float() / 255.0
44
+ video_tensor = video_tensor.unsqueeze(0).permute(0, 2, 1, 3, 4)
45
+ return video_tensor
pipelines/wan_pipeline.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Noam Rotstein
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ #
14
+ # Adapted from Hugging Face Diffusers (Apache-2.0):
15
+ # https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_i2v.py
16
+
17
+
18
+ try:
19
+ import html
20
+ from typing import Any, Callable, Dict, List, Optional, Union
21
+ import torch
22
+ from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.image_processor import PipelineImageInput
25
+ from diffusers.models import AutoencoderKLWan, WanTransformer3DModel
26
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
27
+ from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+ from diffusers.video_processor import VideoProcessor
30
+ from diffusers.pipelines.wan.pipeline_output import WanPipelineOutput
31
+ from diffusers.pipelines.wan.pipeline_wan_i2v import retrieve_latents, WanImageToVideoPipeline
32
+
33
+ import torch.nn.functional as F
34
+ from pipelines.utils import load_video_to_tensor
35
+
36
+ if is_torch_xla_available():
37
+ import torch_xla.core.xla_model as xm
38
+
39
+ XLA_AVAILABLE = True
40
+ else:
41
+ XLA_AVAILABLE = False
42
+ except ImportError as e:
43
+ raise ImportError(f"Required module not found: {e}. Please install it before running this script. "
44
+ f"For installation instructions, see: https://github.com/Wan-Video/Wan2.2")
45
+
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+ # after logger/is_ftfy_available
50
+ _ftfy = None
51
+ if is_ftfy_available():
52
+ import ftfy as _ftfy
53
+
54
+
55
+ EXAMPLE_DOC_STRING = """
56
+ """
57
+
58
+
59
+ class WanImageToVideoTTMPipeline(WanImageToVideoPipeline):
60
+ r"""
61
+ Pipeline for image-to-video generation using Wan with Time-To-Move (TTM) conditioning.
62
+ This model inherits from [`WanImageToVideoPipeline`].
63
+ """
64
+
65
+ model_cpu_offload_seq = "text_encoder->image_encoder->transformer->transformer_2->vae"
66
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
67
+ _optional_components = ["transformer", "transformer_2", "image_encoder", "image_processor"]
68
+
69
+ def __init__(
70
+ self,
71
+ tokenizer: AutoTokenizer,
72
+ text_encoder: UMT5EncoderModel,
73
+ vae: AutoencoderKLWan,
74
+ scheduler: FlowMatchEulerDiscreteScheduler,
75
+ image_processor: CLIPImageProcessor = None,
76
+ image_encoder: CLIPVisionModel = None,
77
+ transformer: WanTransformer3DModel = None,
78
+ transformer_2: WanTransformer3DModel = None,
79
+ boundary_ratio: Optional[float] = None,
80
+ expand_timesteps: bool = False,
81
+ ):
82
+ super().__init__(
83
+ tokenizer=tokenizer,
84
+ text_encoder=text_encoder,
85
+ vae=vae,
86
+ scheduler=scheduler,
87
+ image_processor=image_processor,
88
+ image_encoder=image_encoder,
89
+ transformer=transformer,
90
+ transformer_2=transformer_2,
91
+ boundary_ratio=boundary_ratio,
92
+ expand_timesteps=expand_timesteps,
93
+ )
94
+
95
+ self.register_modules(
96
+ vae=vae,
97
+ text_encoder=text_encoder,
98
+ tokenizer=tokenizer,
99
+ image_encoder=image_encoder,
100
+ transformer=transformer,
101
+ scheduler=scheduler,
102
+ image_processor=image_processor,
103
+ transformer_2=transformer_2,
104
+ )
105
+ self.register_to_config(boundary_ratio=boundary_ratio, expand_timesteps=expand_timesteps)
106
+
107
+ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
108
+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
109
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
110
+ self.image_processor = image_processor
111
+
112
+
113
+ def convert_rgb_mask_to_latent_mask(self, mask: torch.Tensor) -> torch.Tensor:
114
+ """
115
+ Convert a per-frame mask [T, 1, H, W] to latent resolution [1, T_latent, 1, H', W'].
116
+ T_latent groups frames by the temporal VAE downsample factor k = vae_scale_factor_temporal:
117
+ [0], [1..k], [k+1..2k], ...
118
+ """
119
+
120
+ k = self.vae_scale_factor_temporal
121
+ mask0 = mask[0:1] # [1,1,H,W]
122
+ mask1 = mask[1::k] # [T'-1,1,H,W]
123
+ sampled = torch.cat([mask0, mask1], dim=0) # [T',1,H,W]
124
+ pooled = sampled.permute(1, 0, 2, 3).unsqueeze(0)
125
+
126
+ # Up-sample spatially to match latent spatial resolution
127
+ spatial_downsample = self.vae_scale_factor_spatial
128
+ H_latent = pooled.shape[-2] // spatial_downsample
129
+ W_latent = pooled.shape[-1] // spatial_downsample
130
+ pooled = F.interpolate(pooled, size=(pooled.shape[2], H_latent, W_latent), mode="nearest")
131
+
132
+ # Back to [1, T_latent, 1, H, W]
133
+ latent_mask = pooled.permute(0, 2, 1, 3, 4)
134
+
135
+ return latent_mask
136
+
137
+
138
+ @torch.no_grad()
139
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
140
+ def __call__(
141
+ self,
142
+ image: PipelineImageInput,
143
+ prompt: Union[str, List[str]] = None,
144
+ negative_prompt: Union[str, List[str]] = None,
145
+ height: int = 480,
146
+ width: int = 832,
147
+ num_frames: int = 81,
148
+ num_inference_steps: int = 50,
149
+ guidance_scale: float = 5.0,
150
+ guidance_scale_2: Optional[float] = None,
151
+ num_videos_per_prompt: Optional[int] = 1,
152
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
153
+ latents: Optional[torch.Tensor] = None,
154
+ prompt_embeds: Optional[torch.Tensor] = None,
155
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
156
+ image_embeds: Optional[torch.Tensor] = None,
157
+ last_image: Optional[torch.Tensor] = None,
158
+ output_type: Optional[str] = "np",
159
+ return_dict: bool = True,
160
+ attention_kwargs: Optional[Dict[str, Any]] = None,
161
+ callback_on_step_end: Optional[
162
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
163
+ ] = None,
164
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
165
+ max_sequence_length: int = 512,
166
+ motion_signal_video_path: Optional[str] = None,
167
+ motion_signal_mask_path: Optional[str] = None,
168
+ tweak_index: int = 0,
169
+ tstrong_index: int = 0
170
+ ):
171
+ r"""
172
+ The call function to the pipeline for generation.
173
+
174
+ Args:
175
+ image (`PipelineImageInput`):
176
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
177
+ prompt (`str` or `List[str]`, *optional*):
178
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
179
+ instead.
180
+ negative_prompt (`str` or `List[str]`, *optional*):
181
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
182
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
183
+ less than `1`).
184
+ height (`int`, defaults to `480`):
185
+ The height of the generated video.
186
+ width (`int`, defaults to `832`):
187
+ The width of the generated video.
188
+ num_frames (`int`, defaults to `81`):
189
+ The number of frames in the generated video.
190
+ num_inference_steps (`int`, defaults to `50`):
191
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
192
+ expense of slower inference.
193
+ guidance_scale (`float`, defaults to `5.0`):
194
+ Guidance scale as defined in [Classifier-Free Diffusion
195
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
196
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
197
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
198
+ the text `prompt`, usually at the expense of lower image quality.
199
+ guidance_scale_2 (`float`, *optional*, defaults to `None`):
200
+ Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
201
+ `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
202
+ and the pipeline's `boundary_ratio` are not None.
203
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
204
+ The number of images to generate per prompt.
205
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
206
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
207
+ generation deterministic.
208
+ latents (`torch.Tensor`, *optional*):
209
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
210
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
211
+ tensor is generated by sampling using the supplied random `generator`.
212
+ prompt_embeds (`torch.Tensor`, *optional*):
213
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
214
+ provided, text embeddings are generated from the `prompt` input argument.
215
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
216
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
217
+ provided, text embeddings are generated from the `negative_prompt` input argument.
218
+ image_embeds (`torch.Tensor`, *optional*):
219
+ Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
220
+ image embeddings are generated from the `image` input argument.
221
+ output_type (`str`, *optional*, defaults to `"np"`):
222
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
223
+ return_dict (`bool`, *optional*, defaults to `True`):
224
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
225
+ attention_kwargs (`dict`, *optional*):
226
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
227
+ `self.processor` in
228
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
229
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
230
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
231
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
232
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
233
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
234
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
235
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
236
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
237
+ `._callback_tensor_inputs` attribute of your pipeline class.
238
+ max_sequence_length (`int`, defaults to `512`):
239
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
240
+ truncated. If the prompt is shorter, it will be padded to this length.
241
+ motion_signal_video_path (`str`):
242
+ Path to the video file containing the motion signal to guide the motion of the generated video.
243
+ It should be a crude version of the reference video, with pixels with motion dragged to their target.
244
+ motion_signal_mask_path (`str`):
245
+ Path to the mask video file containing the motion mask of TTM.
246
+ The mask should be a binary with the conditioning motion pixels being 1 and the rest being 0.
247
+ tweak_index (`int`):
248
+ The index of the tweak, from which the denoising process starts.
249
+ tstrong_index (`int`):
250
+ The index of the tweak, from which the denoising process starts in the motion conditioned region.
251
+ Examples:
252
+
253
+ Returns:
254
+ [`~WanPipelineOutput`] or `tuple`:
255
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
256
+ the first element is a list with the generated images and the second element is a list of `bool`s
257
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
258
+ """
259
+
260
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
261
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
262
+
263
+
264
+ # 1. Check inputs. Raise error if not correct
265
+ self.check_inputs(
266
+ prompt,
267
+ negative_prompt,
268
+ image,
269
+ height,
270
+ width,
271
+ prompt_embeds,
272
+ negative_prompt_embeds,
273
+ image_embeds,
274
+ callback_on_step_end_tensor_inputs,
275
+ guidance_scale_2,
276
+ )
277
+
278
+ if motion_signal_video_path is None:
279
+ raise ValueError("`motion_signal_video_path` must be provided for TTM.")
280
+ if motion_signal_mask_path is None:
281
+ raise ValueError("`motion_signal_mask_path` must be provided for TTM.")
282
+
283
+ if num_frames % self.vae_scale_factor_temporal != 1:
284
+ logger.warning(
285
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
286
+ )
287
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
288
+ num_frames = max(num_frames, 1)
289
+
290
+ if self.config.boundary_ratio is not None and guidance_scale_2 is None:
291
+ guidance_scale_2 = guidance_scale
292
+
293
+ self._guidance_scale = guidance_scale
294
+ self._attention_kwargs = attention_kwargs
295
+ self._current_timestep = None
296
+ self._interrupt = False
297
+
298
+ device = self._execution_device
299
+
300
+ # 2. Define call parameters
301
+ if prompt is not None and isinstance(prompt, str):
302
+ batch_size = 1
303
+ elif prompt is not None and isinstance(prompt, list):
304
+ batch_size = len(prompt)
305
+ else:
306
+ batch_size = prompt_embeds.shape[0]
307
+
308
+ # 3. Encode input prompt
309
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
310
+ prompt=prompt,
311
+ negative_prompt=negative_prompt,
312
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
313
+ num_videos_per_prompt=num_videos_per_prompt,
314
+ prompt_embeds=prompt_embeds,
315
+ negative_prompt_embeds=negative_prompt_embeds,
316
+ max_sequence_length=max_sequence_length,
317
+ device=device,
318
+ )
319
+
320
+ # Encode image embedding
321
+ transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
322
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
323
+ if negative_prompt_embeds is not None:
324
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
325
+
326
+ # only wan 2.1 i2v transformer accepts image_embeds
327
+ if self.transformer is not None and self.transformer.config.image_dim is not None:
328
+ if image_embeds is None:
329
+ if last_image is None:
330
+ image_embeds = self.encode_image(image, device)
331
+ else:
332
+ image_embeds = self.encode_image([image, last_image], device)
333
+ image_embeds = image_embeds.repeat(batch_size, 1, 1)
334
+ image_embeds = image_embeds.to(transformer_dtype)
335
+
336
+ # 4. Prepare timesteps
337
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
338
+ timesteps = self.scheduler.timesteps
339
+
340
+ tweak_index = int(tweak_index)
341
+ tstrong_index = int(tstrong_index)
342
+
343
+ if tweak_index < -1:
344
+ raise ValueError(f"`tweak_index` ({tweak_index}) must be >= -1.")
345
+ if tweak_index >= len(timesteps):
346
+ raise ValueError(f"`tweak_index` ({tweak_index}) must be < {len(timesteps)}.")
347
+
348
+ if tstrong_index < 0:
349
+ raise ValueError(f"`tstrong_index` ({tstrong_index}) must be >= 0.")
350
+ if tstrong_index >= len(timesteps):
351
+ raise ValueError(f"`tstrong_index` ({tstrong_index}) must be < {len(timesteps)}.")
352
+ if tstrong_index < max(0, tweak_index):
353
+ raise ValueError(f"`tstrong_index` ({tstrong_index}) must be >= `tweak_index` ({tweak_index}).")
354
+
355
+ # 5. Prepare latent variables
356
+ num_channels_latents = self.vae.config.z_dim
357
+ image = self.video_processor.preprocess(image, height=height, width=width).to(device, dtype=torch.float32)
358
+ if last_image is not None:
359
+ last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(
360
+ device, dtype=torch.float32
361
+ )
362
+
363
+ latents_outputs = self.prepare_latents(
364
+ image,
365
+ batch_size * num_videos_per_prompt,
366
+ num_channels_latents,
367
+ height,
368
+ width,
369
+ num_frames,
370
+ torch.float32,
371
+ device,
372
+ generator,
373
+ latents,
374
+ last_image,
375
+ )
376
+ if self.config.expand_timesteps:
377
+ latents, condition, first_frame_mask = latents_outputs
378
+ else:
379
+ latents, condition = latents_outputs
380
+
381
+ # 6. Initialize for TTM
382
+ ref_vid = load_video_to_tensor(motion_signal_video_path).to(device=device) # shape [1, C, T, H, W]
383
+ refB, refC, refT, refH, refW = ref_vid.shape
384
+
385
+ ref_vid = F.interpolate(
386
+ ref_vid.permute(0, 2, 1, 3, 4).reshape(refB*refT, refC, refH, refW),
387
+ size=(height, width), mode="bicubic", align_corners=True,
388
+ ).reshape(refB, refT, refC, height, width).permute(0, 2, 1, 3, 4)
389
+
390
+ ref_vid = self.video_processor.normalize(ref_vid.to(dtype=self.vae.dtype)) # [1, C, T, H, W]
391
+ ref_latents = retrieve_latents(self.vae.encode(ref_vid), sample_mode="argmax") # [1, z, T', H', W']
392
+ latents_mean = torch.tensor(self.vae.config.latents_mean)\
393
+ .view(1, self.vae.config.z_dim, 1, 1, 1).to(ref_latents.device, ref_latents.dtype)
394
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std)\
395
+ .view(1, self.vae.config.z_dim, 1, 1, 1).to(ref_latents.device, ref_latents.dtype)
396
+ ref_latents = (ref_latents - latents_mean) * latents_std
397
+
398
+
399
+ ref_mask = load_video_to_tensor(motion_signal_mask_path).to(device=device) # shape [1, C, T, H, W]
400
+ mB, mC, mT, mH, mW = ref_mask.shape
401
+ ref_mask = F.interpolate(
402
+ ref_mask.permute(0, 2, 1, 3, 4).reshape(mB*mT, mC, mH, mW),
403
+ size=(height, width), mode="nearest",
404
+ ).reshape(mB, mT, mC, height, width).permute(0, 2, 1, 3, 4) # [1, C, T, H, W] -> [T, C, H, W]
405
+ mask_tc_hw = ref_mask[0].permute(1, 0, 2, 3).contiguous()
406
+
407
+ if mask_tc_hw.shape[0] > num_frames: # Align time dimension to num_frames
408
+ logger.warning("Mask has %d frames but num_frames=%d; trimming.", mask_tc_hw.shape[0], num_frames)
409
+ mask_tc_hw = mask_tc_hw[:num_frames]
410
+ elif mask_tc_hw.shape[0] < num_frames:
411
+ raise ValueError(f"num_frames ({num_frames}) is greater than mask frames ({mask_tc_hw.shape[0]}). "
412
+ "Please pad/extend your mask or lower num_frames.")
413
+
414
+ if mask_tc_hw.shape[1] > 1: # Reduce channels if needed -> [T,1,H,W], binarize once
415
+ mask_t1_hw = (mask_tc_hw > 0.5).any(dim=1, keepdim=True).float()
416
+ else:
417
+ mask_t1_hw = (mask_tc_hw > 0.5).float()
418
+
419
+ motion_mask = self.convert_rgb_mask_to_latent_mask(mask_t1_hw).permute(0, 2, 1, 3, 4).contiguous()
420
+ background_mask = 1.0 - motion_mask
421
+
422
+ if tweak_index >= 0:
423
+ tweak = timesteps[tweak_index]
424
+ fixed_noise = randn_tensor(
425
+ ref_latents.shape,
426
+ generator=generator,
427
+ device=ref_latents.device,
428
+ dtype=ref_latents.dtype,
429
+ )
430
+ tweak = torch.as_tensor(tweak, device=ref_latents.device, dtype=torch.long).view(1)
431
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, tweak.long())
432
+ latents = noisy_latents.to(dtype=latents.dtype, device=latents.device)
433
+ else:
434
+ tweak = torch.tensor(-1)
435
+ fixed_noise = randn_tensor(
436
+ ref_latents.shape,
437
+ generator=generator,
438
+ device=ref_latents.device,
439
+ dtype=ref_latents.dtype,
440
+ )
441
+ tweak_index = 0
442
+
443
+ # 7. Denoising loop
444
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
445
+ self._num_timesteps = len(timesteps)
446
+
447
+ if self.config.boundary_ratio is not None:
448
+ boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
449
+ else:
450
+ boundary_timestep = None
451
+
452
+ with self.progress_bar(total=len(timesteps) - tweak_index) as progress_bar:
453
+ for i, t in enumerate(timesteps[tweak_index:]):
454
+ if self.interrupt:
455
+ continue
456
+
457
+ self._current_timestep = t
458
+
459
+ if boundary_timestep is None or t >= boundary_timestep:
460
+ # wan2.1 or high-noise stage in wan2.2
461
+ current_model = self.transformer
462
+ current_guidance_scale = guidance_scale
463
+ else:
464
+ # low-noise stage in wan2.2
465
+ current_model = self.transformer_2
466
+ current_guidance_scale = guidance_scale_2
467
+
468
+ if self.config.expand_timesteps:
469
+ latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents
470
+ latent_model_input = latent_model_input.to(transformer_dtype)
471
+
472
+ temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
473
+ timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
474
+ else:
475
+ latent_model_input = torch.cat([latents, condition], dim=1).to(transformer_dtype)
476
+ timestep = t.expand(latents.shape[0])
477
+
478
+ with current_model.cache_context("cond"):
479
+ noise_pred = current_model(
480
+ hidden_states=latent_model_input,
481
+ timestep=timestep,
482
+ encoder_hidden_states=prompt_embeds,
483
+ encoder_hidden_states_image=image_embeds,
484
+ attention_kwargs=attention_kwargs,
485
+ return_dict=False,
486
+ )[0]
487
+
488
+ if self.do_classifier_free_guidance:
489
+ with current_model.cache_context("uncond"):
490
+ noise_uncond = current_model(
491
+ hidden_states=latent_model_input,
492
+ timestep=timestep,
493
+ encoder_hidden_states=negative_prompt_embeds,
494
+ encoder_hidden_states_image=image_embeds,
495
+ attention_kwargs=attention_kwargs,
496
+ return_dict=False,
497
+ )[0]
498
+ noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
499
+
500
+ # In between tweak and tstrong, replace mask with noisy reference latents
501
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
502
+ in_between_tweak_tstrong = (i+tweak_index) < tstrong_index
503
+
504
+ if in_between_tweak_tstrong:
505
+ if i+tweak_index+1 < len(timesteps):
506
+ prev_t = timesteps[i+tweak_index+1]
507
+ prev_t = torch.as_tensor(prev_t, device=ref_latents.device, dtype=torch.long).view(1)
508
+ noisy_latents = self.scheduler.add_noise(ref_latents, fixed_noise, prev_t.long()).to(dtype=latents.dtype, device=latents.device)
509
+ latents = latents * background_mask + noisy_latents * motion_mask
510
+ else:
511
+ latents = latents * background_mask + ref_latents.to(dtype=latents.dtype, device=latents.device) * motion_mask
512
+
513
+
514
+ if callback_on_step_end is not None:
515
+ callback_kwargs = {}
516
+ for k in callback_on_step_end_tensor_inputs:
517
+ callback_kwargs[k] = locals()[k]
518
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
519
+
520
+ latents = callback_outputs.pop("latents", latents)
521
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
522
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
523
+
524
+ # call the callback, if provided
525
+ if i == len(timesteps) - tweak_index - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
526
+ progress_bar.update()
527
+
528
+ if XLA_AVAILABLE:
529
+ xm.mark_step()
530
+
531
+ self._current_timestep = None
532
+
533
+ if self.config.expand_timesteps:
534
+ latents = (1 - first_frame_mask) * condition + first_frame_mask * latents
535
+
536
+ if not output_type == "latent":
537
+ latents = latents.to(self.vae.dtype)
538
+ latents_mean = (
539
+ torch.tensor(self.vae.config.latents_mean)
540
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
541
+ .to(latents.device, latents.dtype)
542
+ )
543
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
544
+ latents.device, latents.dtype
545
+ )
546
+ latents = latents / latents_std + latents_mean
547
+ video = self.vae.decode(latents, return_dict=False)[0]
548
+
549
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
550
+ else:
551
+ video = latents
552
+
553
+ # Offload all models
554
+ self.maybe_free_model_hooks()
555
+
556
+ if not return_dict:
557
+ return (video,)
558
+
559
+ return WanPipelineOutput(frames=video)