Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
759ec77
·
verified ·
1 Parent(s): d913a15

Upload folder using huggingface_hub

Browse files
main/README.md CHANGED
@@ -10,6 +10,7 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
10
 
11
  | Example | Description | Code Example | Colab | Author |
12
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
 
13
  |Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
14
  |Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/flux_with_cfg.ipynb)|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
15
  |Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/exx8/differential-diffusion) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
@@ -93,6 +94,55 @@ pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion
93
 
94
  ## Example usages
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  ### Adaptive Mask Inpainting
97
 
98
  **Hyeonwoo Kim\*, Sookwan Han\*, Patrick Kwon, Hanbyul Joo**
 
10
 
11
  | Example | Description | Code Example | Colab | Author |
12
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
13
+ |Spatiotemporal Skip Guidance (STG)|[Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) (CVPR 2025) enhances video diffusion models by generating a weaker model through layer skipping and using it as guidance, improving fidelity in models like HunyuanVideo, LTXVideo, and Mochi.|[Spatiotemporal Skip Guidance](#spatiotemporal-skip-guidance)|-|[Junha Hyung](https://junhahyung.github.io/), [Kinam Kim](https://kinam0252.github.io/)|
14
  |Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
15
  |Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/flux_with_cfg.ipynb)|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
16
  |Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/exx8/differential-diffusion) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
 
94
 
95
  ## Example usages
96
 
97
+ ### Spatiotemporal Skip Guidance
98
+
99
+ **Junha Hyung\*, Kinam Kim\*, Susung Hong, Min-Jung Kim, Jaegul Choo**
100
+
101
+ **KAIST AI, University of Washington**
102
+
103
+ [*Spatiotemporal Skip Guidance (STG) for Enhanced Video Diffusion Sampling*](https://arxiv.org/abs/2411.18664) (CVPR 2025) is a simple training-free sampling guidance method for enhancing transformer-based video diffusion models. STG employs an implicit weak model via self-perturbation, avoiding the need for external models or additional training. By selectively skipping spatiotemporal layers, STG produces an aligned, degraded version of the original model to boost sample quality without compromising diversity or dynamic degree.
104
+
105
+ Following is the example video of STG applied to Mochi.
106
+
107
+
108
+ https://github.com/user-attachments/assets/148adb59-da61-4c50-9dfa-425dcb5c23b3
109
+
110
+ More examples and information can be found on the [GitHub repository](https://github.com/junhahyung/STGuidance) and the [Project website](https://junhahyung.github.io/STGuidance/).
111
+
112
+ #### Usage example
113
+ ```python
114
+ import torch
115
+ from pipeline_stg_mochi import MochiSTGPipeline
116
+ from diffusers.utils import export_to_video
117
+
118
+ # Load the pipeline
119
+ pipe = MochiSTGPipeline.from_pretrained("genmo/mochi-1-preview", variant="bf16", torch_dtype=torch.bfloat16)
120
+
121
+ # Enable memory savings
122
+ pipe = pipe.to("cuda")
123
+
124
+ #--------Option--------#
125
+ prompt = "A close-up of a beautiful woman's face with colored powder exploding around her, creating an abstract splash of vibrant hues, realistic style."
126
+ stg_applied_layers_idx = [34]
127
+ stg_mode = "STG"
128
+ stg_scale = 1.0 # 0.0 for CFG
129
+ #----------------------#
130
+
131
+ # Generate video frames
132
+ frames = pipe(
133
+ prompt,
134
+ height=480,
135
+ width=480,
136
+ num_frames=81,
137
+ stg_applied_layers_idx=stg_applied_layers_idx,
138
+ stg_scale=stg_scale,
139
+ generator = torch.Generator().manual_seed(42),
140
+ do_rescaling=do_rescaling,
141
+ ).frames[0]
142
+
143
+ export_to_video(frames, "output.mp4", fps=30)
144
+ ```
145
+
146
  ### Adaptive Mask Inpainting
147
 
148
  **Hyeonwoo Kim\*, Sookwan Han\*, Patrick Kwon, Hanbyul Joo**
main/pipeline_stg_cogvideox.py ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ import math
18
+ import types
19
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ from transformers import T5EncoderModel, T5Tokenizer
23
+
24
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from diffusers.loaders import CogVideoXLoraLoaderMixin
26
+ from diffusers.models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
27
+ from diffusers.models.embeddings import get_3d_rotary_pos_embed
28
+ from diffusers.pipelines.cogvideo.pipeline_output import CogVideoXPipelineOutput
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
31
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+ from diffusers.video_processor import VideoProcessor
34
+
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
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```python
49
+ >>> import torch
50
+ >>> from diffusers.utils import export_to_video
51
+ >>> from examples.community.pipeline_stg_cogvideox import CogVideoXSTGPipeline
52
+
53
+ >>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
54
+ >>> pipe = CogVideoXSTGPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.float16).to("cuda")
55
+ >>> prompt = (
56
+ ... "A father and son building a treehouse together, their hands covered in sawdust and smiles on their faces, realistic style."
57
+ ... )
58
+ >>> pipe.transformer.to(memory_format=torch.channels_last)
59
+
60
+ >>> # Configure STG mode options
61
+ >>> stg_applied_layers_idx = [11] # Layer indices from 0 to 41
62
+ >>> stg_scale = 1.0 # Set to 0.0 for CFG
63
+ >>> do_rescaling = False
64
+
65
+ >>> # Generate video frames with STG parameters
66
+ >>> frames = pipe(
67
+ ... prompt=prompt,
68
+ ... stg_applied_layers_idx=stg_applied_layers_idx,
69
+ ... stg_scale=stg_scale,
70
+ ... do_rescaling=do_rescaling,
71
+ >>> ).frames[0]
72
+ >>> export_to_video(frames, "output.mp4", fps=8)
73
+ ```
74
+ """
75
+
76
+
77
+ def forward_with_stg(
78
+ self,
79
+ hidden_states: torch.Tensor,
80
+ encoder_hidden_states: torch.Tensor,
81
+ temb: torch.Tensor,
82
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
83
+ ) -> torch.Tensor:
84
+ hidden_states_ptb = hidden_states[2:]
85
+ encoder_hidden_states_ptb = encoder_hidden_states[2:]
86
+
87
+ text_seq_length = encoder_hidden_states.size(1)
88
+
89
+ # norm & modulate
90
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
91
+ hidden_states, encoder_hidden_states, temb
92
+ )
93
+
94
+ # attention
95
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
96
+ hidden_states=norm_hidden_states,
97
+ encoder_hidden_states=norm_encoder_hidden_states,
98
+ image_rotary_emb=image_rotary_emb,
99
+ )
100
+
101
+ hidden_states = hidden_states + gate_msa * attn_hidden_states
102
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states
103
+
104
+ # norm & modulate
105
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
106
+ hidden_states, encoder_hidden_states, temb
107
+ )
108
+
109
+ # feed-forward
110
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
111
+ ff_output = self.ff(norm_hidden_states)
112
+
113
+ hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:]
114
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length]
115
+
116
+ hidden_states[2:] = hidden_states_ptb
117
+ encoder_hidden_states[2:] = encoder_hidden_states_ptb
118
+
119
+ return hidden_states, encoder_hidden_states
120
+
121
+
122
+ # Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
123
+ def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
124
+ tw = tgt_width
125
+ th = tgt_height
126
+ h, w = src
127
+ r = h / w
128
+ if r > (th / tw):
129
+ resize_height = th
130
+ resize_width = int(round(th / h * w))
131
+ else:
132
+ resize_width = tw
133
+ resize_height = int(round(tw / w * h))
134
+
135
+ crop_top = int(round((th - resize_height) / 2.0))
136
+ crop_left = int(round((tw - resize_width) / 2.0))
137
+
138
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
139
+
140
+
141
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
142
+ def retrieve_timesteps(
143
+ scheduler,
144
+ num_inference_steps: Optional[int] = None,
145
+ device: Optional[Union[str, torch.device]] = None,
146
+ timesteps: Optional[List[int]] = None,
147
+ sigmas: Optional[List[float]] = None,
148
+ **kwargs,
149
+ ):
150
+ r"""
151
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
152
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
153
+
154
+ Args:
155
+ scheduler (`SchedulerMixin`):
156
+ The scheduler to get timesteps from.
157
+ num_inference_steps (`int`):
158
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
159
+ must be `None`.
160
+ device (`str` or `torch.device`, *optional*):
161
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
162
+ timesteps (`List[int]`, *optional*):
163
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
164
+ `num_inference_steps` and `sigmas` must be `None`.
165
+ sigmas (`List[float]`, *optional*):
166
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
167
+ `num_inference_steps` and `timesteps` must be `None`.
168
+
169
+ Returns:
170
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
171
+ second element is the number of inference steps.
172
+ """
173
+ if timesteps is not None and sigmas is not None:
174
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
175
+ if timesteps is not None:
176
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
177
+ if not accepts_timesteps:
178
+ raise ValueError(
179
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
180
+ f" timestep schedules. Please check whether you are using the correct scheduler."
181
+ )
182
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
183
+ timesteps = scheduler.timesteps
184
+ num_inference_steps = len(timesteps)
185
+ elif sigmas is not None:
186
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
187
+ if not accept_sigmas:
188
+ raise ValueError(
189
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
190
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
191
+ )
192
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
193
+ timesteps = scheduler.timesteps
194
+ num_inference_steps = len(timesteps)
195
+ else:
196
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
197
+ timesteps = scheduler.timesteps
198
+ return timesteps, num_inference_steps
199
+
200
+
201
+ class CogVideoXSTGPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin):
202
+ r"""
203
+ Pipeline for text-to-video generation using CogVideoX.
204
+
205
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
206
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
207
+
208
+ Args:
209
+ vae ([`AutoencoderKL`]):
210
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
211
+ text_encoder ([`T5EncoderModel`]):
212
+ Frozen text-encoder. CogVideoX uses
213
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
214
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
215
+ tokenizer (`T5Tokenizer`):
216
+ Tokenizer of class
217
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
218
+ transformer ([`CogVideoXTransformer3DModel`]):
219
+ A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
220
+ scheduler ([`SchedulerMixin`]):
221
+ A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
222
+ """
223
+
224
+ _optional_components = []
225
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
226
+
227
+ _callback_tensor_inputs = [
228
+ "latents",
229
+ "prompt_embeds",
230
+ "negative_prompt_embeds",
231
+ ]
232
+
233
+ def __init__(
234
+ self,
235
+ tokenizer: T5Tokenizer,
236
+ text_encoder: T5EncoderModel,
237
+ vae: AutoencoderKLCogVideoX,
238
+ transformer: CogVideoXTransformer3DModel,
239
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
240
+ ):
241
+ super().__init__()
242
+
243
+ self.register_modules(
244
+ tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
245
+ )
246
+ self.vae_scale_factor_spatial = (
247
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
248
+ )
249
+ self.vae_scale_factor_temporal = (
250
+ self.vae.config.temporal_compression_ratio if getattr(self, "vae", None) else 4
251
+ )
252
+ self.vae_scaling_factor_image = self.vae.config.scaling_factor if getattr(self, "vae", None) else 0.7
253
+
254
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
255
+
256
+ def _get_t5_prompt_embeds(
257
+ self,
258
+ prompt: Union[str, List[str]] = None,
259
+ num_videos_per_prompt: int = 1,
260
+ max_sequence_length: int = 226,
261
+ device: Optional[torch.device] = None,
262
+ dtype: Optional[torch.dtype] = None,
263
+ ):
264
+ device = device or self._execution_device
265
+ dtype = dtype or self.text_encoder.dtype
266
+
267
+ prompt = [prompt] if isinstance(prompt, str) else prompt
268
+ batch_size = len(prompt)
269
+
270
+ text_inputs = self.tokenizer(
271
+ prompt,
272
+ padding="max_length",
273
+ max_length=max_sequence_length,
274
+ truncation=True,
275
+ add_special_tokens=True,
276
+ return_tensors="pt",
277
+ )
278
+ text_input_ids = text_inputs.input_ids
279
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
280
+
281
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
282
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
283
+ logger.warning(
284
+ "The following part of your input was truncated because `max_sequence_length` is set to "
285
+ f" {max_sequence_length} tokens: {removed_text}"
286
+ )
287
+
288
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
289
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
290
+
291
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
292
+ _, seq_len, _ = prompt_embeds.shape
293
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
294
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
295
+
296
+ return prompt_embeds
297
+
298
+ def encode_prompt(
299
+ self,
300
+ prompt: Union[str, List[str]],
301
+ negative_prompt: Optional[Union[str, List[str]]] = None,
302
+ do_classifier_free_guidance: bool = True,
303
+ num_videos_per_prompt: int = 1,
304
+ prompt_embeds: Optional[torch.Tensor] = None,
305
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
306
+ max_sequence_length: int = 226,
307
+ device: Optional[torch.device] = None,
308
+ dtype: Optional[torch.dtype] = None,
309
+ ):
310
+ r"""
311
+ Encodes the prompt into text encoder hidden states.
312
+
313
+ Args:
314
+ prompt (`str` or `List[str]`, *optional*):
315
+ prompt to be encoded
316
+ negative_prompt (`str` or `List[str]`, *optional*):
317
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
318
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
319
+ less than `1`).
320
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
321
+ Whether to use classifier free guidance or not.
322
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
323
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
324
+ prompt_embeds (`torch.Tensor`, *optional*):
325
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
326
+ provided, text embeddings will be generated from `prompt` input argument.
327
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
328
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
329
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
330
+ argument.
331
+ device: (`torch.device`, *optional*):
332
+ torch device
333
+ dtype: (`torch.dtype`, *optional*):
334
+ torch dtype
335
+ """
336
+ device = device or self._execution_device
337
+
338
+ prompt = [prompt] if isinstance(prompt, str) else prompt
339
+ if prompt is not None:
340
+ batch_size = len(prompt)
341
+ else:
342
+ batch_size = prompt_embeds.shape[0]
343
+
344
+ if prompt_embeds is None:
345
+ prompt_embeds = self._get_t5_prompt_embeds(
346
+ prompt=prompt,
347
+ num_videos_per_prompt=num_videos_per_prompt,
348
+ max_sequence_length=max_sequence_length,
349
+ device=device,
350
+ dtype=dtype,
351
+ )
352
+
353
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
354
+ negative_prompt = negative_prompt or ""
355
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
356
+
357
+ if prompt is not None and type(prompt) is not type(negative_prompt):
358
+ raise TypeError(
359
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
360
+ f" {type(prompt)}."
361
+ )
362
+ elif batch_size != len(negative_prompt):
363
+ raise ValueError(
364
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
365
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
366
+ " the batch size of `prompt`."
367
+ )
368
+
369
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
370
+ prompt=negative_prompt,
371
+ num_videos_per_prompt=num_videos_per_prompt,
372
+ max_sequence_length=max_sequence_length,
373
+ device=device,
374
+ dtype=dtype,
375
+ )
376
+
377
+ return prompt_embeds, negative_prompt_embeds
378
+
379
+ def prepare_latents(
380
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
381
+ ):
382
+ if isinstance(generator, list) and len(generator) != batch_size:
383
+ raise ValueError(
384
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
385
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
386
+ )
387
+
388
+ shape = (
389
+ batch_size,
390
+ (num_frames - 1) // self.vae_scale_factor_temporal + 1,
391
+ num_channels_latents,
392
+ height // self.vae_scale_factor_spatial,
393
+ width // self.vae_scale_factor_spatial,
394
+ )
395
+
396
+ if latents is None:
397
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
398
+ else:
399
+ latents = latents.to(device)
400
+
401
+ # scale the initial noise by the standard deviation required by the scheduler
402
+ latents = latents * self.scheduler.init_noise_sigma
403
+ return latents
404
+
405
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
406
+ latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
407
+ latents = 1 / self.vae_scaling_factor_image * latents
408
+
409
+ frames = self.vae.decode(latents).sample
410
+ return frames
411
+
412
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
413
+ def prepare_extra_step_kwargs(self, generator, eta):
414
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
415
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
416
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
417
+ # and should be between [0, 1]
418
+
419
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
420
+ extra_step_kwargs = {}
421
+ if accepts_eta:
422
+ extra_step_kwargs["eta"] = eta
423
+
424
+ # check if the scheduler accepts generator
425
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
426
+ if accepts_generator:
427
+ extra_step_kwargs["generator"] = generator
428
+ return extra_step_kwargs
429
+
430
+ # Copied from diffusers.pipelines.latte.pipeline_latte.LattePipeline.check_inputs
431
+ def check_inputs(
432
+ self,
433
+ prompt,
434
+ height,
435
+ width,
436
+ negative_prompt,
437
+ callback_on_step_end_tensor_inputs,
438
+ prompt_embeds=None,
439
+ negative_prompt_embeds=None,
440
+ ):
441
+ if height % 8 != 0 or width % 8 != 0:
442
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
443
+
444
+ if callback_on_step_end_tensor_inputs is not None and not all(
445
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
446
+ ):
447
+ raise ValueError(
448
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
449
+ )
450
+ if prompt is not None and prompt_embeds is not None:
451
+ raise ValueError(
452
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
453
+ " only forward one of the two."
454
+ )
455
+ elif prompt is None and prompt_embeds is None:
456
+ raise ValueError(
457
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
458
+ )
459
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
460
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
461
+
462
+ if prompt is not None and negative_prompt_embeds is not None:
463
+ raise ValueError(
464
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
465
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
466
+ )
467
+
468
+ if negative_prompt is not None and negative_prompt_embeds is not None:
469
+ raise ValueError(
470
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
471
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
472
+ )
473
+
474
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
475
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
476
+ raise ValueError(
477
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
478
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
479
+ f" {negative_prompt_embeds.shape}."
480
+ )
481
+
482
+ def fuse_qkv_projections(self) -> None:
483
+ r"""Enables fused QKV projections."""
484
+ self.fusing_transformer = True
485
+ self.transformer.fuse_qkv_projections()
486
+
487
+ def unfuse_qkv_projections(self) -> None:
488
+ r"""Disable QKV projection fusion if enabled."""
489
+ if not self.fusing_transformer:
490
+ logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
491
+ else:
492
+ self.transformer.unfuse_qkv_projections()
493
+ self.fusing_transformer = False
494
+
495
+ def _prepare_rotary_positional_embeddings(
496
+ self,
497
+ height: int,
498
+ width: int,
499
+ num_frames: int,
500
+ device: torch.device,
501
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
502
+ grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
503
+ grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
504
+
505
+ p = self.transformer.config.patch_size
506
+ p_t = self.transformer.config.patch_size_t
507
+
508
+ base_size_width = self.transformer.config.sample_width // p
509
+ base_size_height = self.transformer.config.sample_height // p
510
+
511
+ if p_t is None:
512
+ # CogVideoX 1.0
513
+ grid_crops_coords = get_resize_crop_region_for_grid(
514
+ (grid_height, grid_width), base_size_width, base_size_height
515
+ )
516
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
517
+ embed_dim=self.transformer.config.attention_head_dim,
518
+ crops_coords=grid_crops_coords,
519
+ grid_size=(grid_height, grid_width),
520
+ temporal_size=num_frames,
521
+ device=device,
522
+ )
523
+ else:
524
+ # CogVideoX 1.5
525
+ base_num_frames = (num_frames + p_t - 1) // p_t
526
+
527
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
528
+ embed_dim=self.transformer.config.attention_head_dim,
529
+ crops_coords=None,
530
+ grid_size=(grid_height, grid_width),
531
+ temporal_size=base_num_frames,
532
+ grid_type="slice",
533
+ max_size=(base_size_height, base_size_width),
534
+ device=device,
535
+ )
536
+
537
+ return freqs_cos, freqs_sin
538
+
539
+ @property
540
+ def guidance_scale(self):
541
+ return self._guidance_scale
542
+
543
+ @property
544
+ def do_spatio_temporal_guidance(self):
545
+ return self._stg_scale > 0.0
546
+
547
+ @property
548
+ def num_timesteps(self):
549
+ return self._num_timesteps
550
+
551
+ @property
552
+ def attention_kwargs(self):
553
+ return self._attention_kwargs
554
+
555
+ @property
556
+ def current_timestep(self):
557
+ return self._current_timestep
558
+
559
+ @property
560
+ def interrupt(self):
561
+ return self._interrupt
562
+
563
+ @torch.no_grad()
564
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
565
+ def __call__(
566
+ self,
567
+ prompt: Optional[Union[str, List[str]]] = None,
568
+ negative_prompt: Optional[Union[str, List[str]]] = None,
569
+ height: Optional[int] = None,
570
+ width: Optional[int] = None,
571
+ num_frames: Optional[int] = None,
572
+ num_inference_steps: int = 50,
573
+ timesteps: Optional[List[int]] = None,
574
+ guidance_scale: float = 6,
575
+ use_dynamic_cfg: bool = False,
576
+ num_videos_per_prompt: int = 1,
577
+ eta: float = 0.0,
578
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
579
+ latents: Optional[torch.FloatTensor] = None,
580
+ prompt_embeds: Optional[torch.FloatTensor] = None,
581
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
582
+ output_type: str = "pil",
583
+ return_dict: bool = True,
584
+ attention_kwargs: Optional[Dict[str, Any]] = None,
585
+ callback_on_step_end: Optional[
586
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
587
+ ] = None,
588
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
589
+ max_sequence_length: int = 226,
590
+ stg_applied_layers_idx: Optional[List[int]] = [11],
591
+ stg_scale: Optional[float] = 0.0,
592
+ do_rescaling: Optional[bool] = False,
593
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
594
+ """
595
+ Function invoked when calling the pipeline for generation.
596
+
597
+ Args:
598
+ prompt (`str` or `List[str]`, *optional*):
599
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
600
+ instead.
601
+ negative_prompt (`str` or `List[str]`, *optional*):
602
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
603
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
604
+ less than `1`).
605
+ height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
606
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
607
+ width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
608
+ The width in pixels of the generated image. This is set to 720 by default for the best results.
609
+ num_frames (`int`, defaults to `48`):
610
+ Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
611
+ contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
612
+ num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that
613
+ needs to be satisfied is that of divisibility mentioned above.
614
+ num_inference_steps (`int`, *optional*, defaults to 50):
615
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
616
+ expense of slower inference.
617
+ timesteps (`List[int]`, *optional*):
618
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
619
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
620
+ passed will be used. Must be in descending order.
621
+ guidance_scale (`float`, *optional*, defaults to 7.0):
622
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
623
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
624
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
625
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
626
+ usually at the expense of lower image quality.
627
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
628
+ The number of videos to generate per prompt.
629
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
630
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
631
+ to make generation deterministic.
632
+ latents (`torch.FloatTensor`, *optional*):
633
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
634
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
635
+ tensor will ge generated by sampling using the supplied random `generator`.
636
+ prompt_embeds (`torch.FloatTensor`, *optional*):
637
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
638
+ provided, text embeddings will be generated from `prompt` input argument.
639
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
640
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
641
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
642
+ argument.
643
+ output_type (`str`, *optional*, defaults to `"pil"`):
644
+ The output format of the generate image. Choose between
645
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
646
+ return_dict (`bool`, *optional*, defaults to `True`):
647
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
648
+ of a plain tuple.
649
+ attention_kwargs (`dict`, *optional*):
650
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
651
+ `self.processor` in
652
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
653
+ callback_on_step_end (`Callable`, *optional*):
654
+ A function that calls at the end of each denoising steps during the inference. The function is called
655
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
656
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
657
+ `callback_on_step_end_tensor_inputs`.
658
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
659
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
660
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
661
+ `._callback_tensor_inputs` attribute of your pipeline class.
662
+ max_sequence_length (`int`, defaults to `226`):
663
+ Maximum sequence length in encoded prompt. Must be consistent with
664
+ `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
665
+
666
+ Examples:
667
+
668
+ Returns:
669
+ [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] or `tuple`:
670
+ [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
671
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
672
+ """
673
+
674
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
675
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
676
+
677
+ height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
678
+ width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
679
+ num_frames = num_frames or self.transformer.config.sample_frames
680
+
681
+ num_videos_per_prompt = 1
682
+
683
+ # 1. Check inputs. Raise error if not correct
684
+ self.check_inputs(
685
+ prompt,
686
+ height,
687
+ width,
688
+ negative_prompt,
689
+ callback_on_step_end_tensor_inputs,
690
+ prompt_embeds,
691
+ negative_prompt_embeds,
692
+ )
693
+ self._stg_scale = stg_scale
694
+ self._guidance_scale = guidance_scale
695
+ self._attention_kwargs = attention_kwargs
696
+ self._current_timestep = None
697
+ self._interrupt = False
698
+
699
+ if self.do_spatio_temporal_guidance:
700
+ for i in stg_applied_layers_idx:
701
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
702
+ forward_with_stg, self.transformer.transformer_blocks[i]
703
+ )
704
+
705
+ # 2. Default call parameters
706
+ if prompt is not None and isinstance(prompt, str):
707
+ batch_size = 1
708
+ elif prompt is not None and isinstance(prompt, list):
709
+ batch_size = len(prompt)
710
+ else:
711
+ batch_size = prompt_embeds.shape[0]
712
+
713
+ device = self._execution_device
714
+
715
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
716
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
717
+ # corresponds to doing no classifier free guidance.
718
+ do_classifier_free_guidance = guidance_scale > 1.0
719
+
720
+ # 3. Encode input prompt
721
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
722
+ prompt,
723
+ negative_prompt,
724
+ do_classifier_free_guidance,
725
+ num_videos_per_prompt=num_videos_per_prompt,
726
+ prompt_embeds=prompt_embeds,
727
+ negative_prompt_embeds=negative_prompt_embeds,
728
+ max_sequence_length=max_sequence_length,
729
+ device=device,
730
+ )
731
+ if do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
732
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
733
+ elif do_classifier_free_guidance and self.do_spatio_temporal_guidance:
734
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0)
735
+
736
+ # 4. Prepare timesteps
737
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
738
+ self._num_timesteps = len(timesteps)
739
+
740
+ # 5. Prepare latents
741
+ latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
742
+
743
+ # For CogVideoX 1.5, the latent frames should be padded to make it divisible by patch_size_t
744
+ patch_size_t = self.transformer.config.patch_size_t
745
+ additional_frames = 0
746
+ if patch_size_t is not None and latent_frames % patch_size_t != 0:
747
+ additional_frames = patch_size_t - latent_frames % patch_size_t
748
+ num_frames += additional_frames * self.vae_scale_factor_temporal
749
+
750
+ latent_channels = self.transformer.config.in_channels
751
+ latents = self.prepare_latents(
752
+ batch_size * num_videos_per_prompt,
753
+ latent_channels,
754
+ num_frames,
755
+ height,
756
+ width,
757
+ prompt_embeds.dtype,
758
+ device,
759
+ generator,
760
+ latents,
761
+ )
762
+
763
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
764
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
765
+
766
+ # 7. Create rotary embeds if required
767
+ image_rotary_emb = (
768
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
769
+ if self.transformer.config.use_rotary_positional_embeddings
770
+ else None
771
+ )
772
+
773
+ # 8. Denoising loop
774
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
775
+
776
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
777
+ # for DPM-solver++
778
+ old_pred_original_sample = None
779
+ for i, t in enumerate(timesteps):
780
+ if self.interrupt:
781
+ continue
782
+
783
+ self._current_timestep = t
784
+ if do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
785
+ latent_model_input = torch.cat([latents] * 2)
786
+ elif do_classifier_free_guidance and self.do_spatio_temporal_guidance:
787
+ latent_model_input = torch.cat([latents] * 3)
788
+ else:
789
+ latent_model_input = latents
790
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
791
+
792
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
793
+ timestep = t.expand(latent_model_input.shape[0])
794
+
795
+ # predict noise model_output
796
+ noise_pred = self.transformer(
797
+ hidden_states=latent_model_input,
798
+ encoder_hidden_states=prompt_embeds,
799
+ timestep=timestep,
800
+ image_rotary_emb=image_rotary_emb,
801
+ attention_kwargs=attention_kwargs,
802
+ return_dict=False,
803
+ )[0]
804
+ noise_pred = noise_pred.float()
805
+
806
+ # perform guidance
807
+ if use_dynamic_cfg:
808
+ self._guidance_scale = 1 + guidance_scale * (
809
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
810
+ )
811
+ if do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
812
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
813
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
814
+ elif do_classifier_free_guidance and self.do_spatio_temporal_guidance:
815
+ noise_pred_uncond, noise_pred_text, noise_pred_perturb = noise_pred.chunk(3)
816
+ noise_pred = (
817
+ noise_pred_uncond
818
+ + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
819
+ + self._stg_scale * (noise_pred_text - noise_pred_perturb)
820
+ )
821
+
822
+ if do_rescaling:
823
+ rescaling_scale = 0.7
824
+ factor = noise_pred_text.std() / noise_pred.std()
825
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
826
+ noise_pred = noise_pred * factor
827
+
828
+ # compute the previous noisy sample x_t -> x_t-1
829
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
830
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
831
+ else:
832
+ latents, old_pred_original_sample = self.scheduler.step(
833
+ noise_pred,
834
+ old_pred_original_sample,
835
+ t,
836
+ timesteps[i - 1] if i > 0 else None,
837
+ latents,
838
+ **extra_step_kwargs,
839
+ return_dict=False,
840
+ )
841
+ latents = latents.to(prompt_embeds.dtype)
842
+
843
+ # call the callback, if provided
844
+ if callback_on_step_end is not None:
845
+ callback_kwargs = {}
846
+ for k in callback_on_step_end_tensor_inputs:
847
+ callback_kwargs[k] = locals()[k]
848
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
849
+
850
+ latents = callback_outputs.pop("latents", latents)
851
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
852
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
853
+
854
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
855
+ progress_bar.update()
856
+
857
+ if XLA_AVAILABLE:
858
+ xm.mark_step()
859
+
860
+ self._current_timestep = None
861
+
862
+ if not output_type == "latent":
863
+ # Discard any padding frames that were added for CogVideoX 1.5
864
+ latents = latents[:, additional_frames:]
865
+ video = self.decode_latents(latents)
866
+ video = self.video_processor.postprocess_video(video=video, output_type=output_type)
867
+ else:
868
+ video = latents
869
+
870
+ # Offload all models
871
+ self.maybe_free_model_hooks()
872
+
873
+ if not return_dict:
874
+ return (video,)
875
+
876
+ return CogVideoXPipelineOutput(frames=video)
main/pipeline_stg_hunyuan_video.py ADDED
@@ -0,0 +1,794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HunyuanVideo Team and The HuggingFace Team. All rights reserved.
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
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import types
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPTextModel, CLIPTokenizer, LlamaModel, LlamaTokenizerFast
22
+
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.loaders import HunyuanVideoLoraLoaderMixin
25
+ from diffusers.models import AutoencoderKLHunyuanVideo, HunyuanVideoTransformer3DModel
26
+ from diffusers.pipelines.hunyuan_video.pipeline_output import HunyuanVideoPipelineOutput
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
29
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
30
+ from diffusers.utils.torch_utils import randn_tensor
31
+ from diffusers.video_processor import VideoProcessor
32
+
33
+
34
+ if is_torch_xla_available():
35
+ import torch_xla.core.xla_model as xm
36
+
37
+ XLA_AVAILABLE = True
38
+ else:
39
+ XLA_AVAILABLE = False
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+
44
+ EXAMPLE_DOC_STRING = """
45
+ Examples:
46
+ ```python
47
+ >>> import torch
48
+ >>> from diffusers.utils import export_to_video
49
+ >>> from diffusers import HunyuanVideoTransformer3DModel
50
+ >>> from examples.community.pipeline_stg_hunyuan_video import HunyuanVideoSTGPipeline
51
+
52
+ >>> model_id = "hunyuanvideo-community/HunyuanVideo"
53
+ >>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
54
+ ... model_id, subfolder="transformer", torch_dtype=torch.bfloat16
55
+ ... )
56
+ >>> pipe = HunyuanVideoSTGPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
57
+ >>> pipe.vae.enable_tiling()
58
+ >>> pipe.to("cuda")
59
+
60
+ >>> # Configure STG mode options
61
+ >>> stg_applied_layers_idx = [2] # Layer indices from 0 to 41
62
+ >>> stg_scale = 1.0 # Set 0.0 for CFG
63
+
64
+ >>> output = pipe(
65
+ ... prompt="A wolf howling at the moon, with the moon subtly resembling a giant clock face, realistic style.",
66
+ ... height=320,
67
+ ... width=512,
68
+ ... num_frames=61,
69
+ ... num_inference_steps=30,
70
+ ... stg_applied_layers_idx=stg_applied_layers_idx,
71
+ ... stg_scale=stg_scale,
72
+ >>> ).frames[0]
73
+ >>> export_to_video(output, "output.mp4", fps=15)
74
+ ```
75
+ """
76
+
77
+
78
+ DEFAULT_PROMPT_TEMPLATE = {
79
+ "template": (
80
+ "<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: "
81
+ "1. The main content and theme of the video."
82
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
83
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
84
+ "4. background environment, light, style and atmosphere."
85
+ "5. camera angles, movements, and transitions used in the video:<|eot_id|>"
86
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
87
+ ),
88
+ "crop_start": 95,
89
+ }
90
+
91
+
92
+ def forward_with_stg(
93
+ self,
94
+ hidden_states: torch.Tensor,
95
+ encoder_hidden_states: torch.Tensor,
96
+ temb: torch.Tensor,
97
+ attention_mask: Optional[torch.Tensor] = None,
98
+ freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
99
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
100
+ return hidden_states, encoder_hidden_states
101
+
102
+
103
+ def forward_without_stg(
104
+ self,
105
+ hidden_states: torch.Tensor,
106
+ encoder_hidden_states: torch.Tensor,
107
+ temb: torch.Tensor,
108
+ attention_mask: Optional[torch.Tensor] = None,
109
+ freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
110
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
111
+ # 1. Input normalization
112
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
113
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
114
+ encoder_hidden_states, emb=temb
115
+ )
116
+
117
+ # 2. Joint attention
118
+ attn_output, context_attn_output = self.attn(
119
+ hidden_states=norm_hidden_states,
120
+ encoder_hidden_states=norm_encoder_hidden_states,
121
+ attention_mask=attention_mask,
122
+ image_rotary_emb=freqs_cis,
123
+ )
124
+
125
+ # 3. Modulation and residual connection
126
+ hidden_states = hidden_states + attn_output * gate_msa.unsqueeze(1)
127
+ encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
128
+
129
+ norm_hidden_states = self.norm2(hidden_states)
130
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
131
+
132
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
133
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
134
+
135
+ # 4. Feed-forward
136
+ ff_output = self.ff(norm_hidden_states)
137
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
138
+
139
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1) * ff_output
140
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
141
+
142
+ return hidden_states, encoder_hidden_states
143
+
144
+
145
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
146
+ def retrieve_timesteps(
147
+ scheduler,
148
+ num_inference_steps: Optional[int] = None,
149
+ device: Optional[Union[str, torch.device]] = None,
150
+ timesteps: Optional[List[int]] = None,
151
+ sigmas: Optional[List[float]] = None,
152
+ **kwargs,
153
+ ):
154
+ r"""
155
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
156
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
157
+
158
+ Args:
159
+ scheduler (`SchedulerMixin`):
160
+ The scheduler to get timesteps from.
161
+ num_inference_steps (`int`):
162
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
163
+ must be `None`.
164
+ device (`str` or `torch.device`, *optional*):
165
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
166
+ timesteps (`List[int]`, *optional*):
167
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
168
+ `num_inference_steps` and `sigmas` must be `None`.
169
+ sigmas (`List[float]`, *optional*):
170
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
171
+ `num_inference_steps` and `timesteps` must be `None`.
172
+
173
+ Returns:
174
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
175
+ second element is the number of inference steps.
176
+ """
177
+ if timesteps is not None and sigmas is not None:
178
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
179
+ if timesteps is not None:
180
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
181
+ if not accepts_timesteps:
182
+ raise ValueError(
183
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
184
+ f" timestep schedules. Please check whether you are using the correct scheduler."
185
+ )
186
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
187
+ timesteps = scheduler.timesteps
188
+ num_inference_steps = len(timesteps)
189
+ elif sigmas is not None:
190
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
191
+ if not accept_sigmas:
192
+ raise ValueError(
193
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
194
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
195
+ )
196
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
197
+ timesteps = scheduler.timesteps
198
+ num_inference_steps = len(timesteps)
199
+ else:
200
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
201
+ timesteps = scheduler.timesteps
202
+ return timesteps, num_inference_steps
203
+
204
+
205
+ class HunyuanVideoSTGPipeline(DiffusionPipeline, HunyuanVideoLoraLoaderMixin):
206
+ r"""
207
+ Pipeline for text-to-video generation using HunyuanVideo.
208
+
209
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
210
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
211
+
212
+ Args:
213
+ text_encoder ([`LlamaModel`]):
214
+ [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
215
+ tokenizer (`LlamaTokenizer`):
216
+ Tokenizer from [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
217
+ transformer ([`HunyuanVideoTransformer3DModel`]):
218
+ Conditional Transformer to denoise the encoded image latents.
219
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
220
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
221
+ vae ([`AutoencoderKLHunyuanVideo`]):
222
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
223
+ text_encoder_2 ([`CLIPTextModel`]):
224
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
225
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
226
+ tokenizer_2 (`CLIPTokenizer`):
227
+ Tokenizer of class
228
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
229
+ """
230
+
231
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
232
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
233
+
234
+ def __init__(
235
+ self,
236
+ text_encoder: LlamaModel,
237
+ tokenizer: LlamaTokenizerFast,
238
+ transformer: HunyuanVideoTransformer3DModel,
239
+ vae: AutoencoderKLHunyuanVideo,
240
+ scheduler: FlowMatchEulerDiscreteScheduler,
241
+ text_encoder_2: CLIPTextModel,
242
+ tokenizer_2: CLIPTokenizer,
243
+ ):
244
+ super().__init__()
245
+
246
+ self.register_modules(
247
+ vae=vae,
248
+ text_encoder=text_encoder,
249
+ tokenizer=tokenizer,
250
+ transformer=transformer,
251
+ scheduler=scheduler,
252
+ text_encoder_2=text_encoder_2,
253
+ tokenizer_2=tokenizer_2,
254
+ )
255
+
256
+ self.vae_scale_factor_temporal = self.vae.temporal_compression_ratio if getattr(self, "vae", None) else 4
257
+ self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio if getattr(self, "vae", None) else 8
258
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
259
+
260
+ def _get_llama_prompt_embeds(
261
+ self,
262
+ prompt: Union[str, List[str]],
263
+ prompt_template: Dict[str, Any],
264
+ num_videos_per_prompt: int = 1,
265
+ device: Optional[torch.device] = None,
266
+ dtype: Optional[torch.dtype] = None,
267
+ max_sequence_length: int = 256,
268
+ num_hidden_layers_to_skip: int = 2,
269
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
270
+ device = device or self._execution_device
271
+ dtype = dtype or self.text_encoder.dtype
272
+
273
+ prompt = [prompt] if isinstance(prompt, str) else prompt
274
+ batch_size = len(prompt)
275
+
276
+ prompt = [prompt_template["template"].format(p) for p in prompt]
277
+
278
+ crop_start = prompt_template.get("crop_start", None)
279
+ if crop_start is None:
280
+ prompt_template_input = self.tokenizer(
281
+ prompt_template["template"],
282
+ padding="max_length",
283
+ return_tensors="pt",
284
+ return_length=False,
285
+ return_overflowing_tokens=False,
286
+ return_attention_mask=False,
287
+ )
288
+ crop_start = prompt_template_input["input_ids"].shape[-1]
289
+ # Remove <|eot_id|> token and placeholder {}
290
+ crop_start -= 2
291
+
292
+ max_sequence_length += crop_start
293
+ text_inputs = self.tokenizer(
294
+ prompt,
295
+ max_length=max_sequence_length,
296
+ padding="max_length",
297
+ truncation=True,
298
+ return_tensors="pt",
299
+ return_length=False,
300
+ return_overflowing_tokens=False,
301
+ return_attention_mask=True,
302
+ )
303
+ text_input_ids = text_inputs.input_ids.to(device=device)
304
+ prompt_attention_mask = text_inputs.attention_mask.to(device=device)
305
+
306
+ prompt_embeds = self.text_encoder(
307
+ input_ids=text_input_ids,
308
+ attention_mask=prompt_attention_mask,
309
+ output_hidden_states=True,
310
+ ).hidden_states[-(num_hidden_layers_to_skip + 1)]
311
+ prompt_embeds = prompt_embeds.to(dtype=dtype)
312
+
313
+ if crop_start is not None and crop_start > 0:
314
+ prompt_embeds = prompt_embeds[:, crop_start:]
315
+ prompt_attention_mask = prompt_attention_mask[:, crop_start:]
316
+
317
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
318
+ _, seq_len, _ = prompt_embeds.shape
319
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
320
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
321
+ prompt_attention_mask = prompt_attention_mask.repeat(1, num_videos_per_prompt)
322
+ prompt_attention_mask = prompt_attention_mask.view(batch_size * num_videos_per_prompt, seq_len)
323
+
324
+ return prompt_embeds, prompt_attention_mask
325
+
326
+ def _get_clip_prompt_embeds(
327
+ self,
328
+ prompt: Union[str, List[str]],
329
+ num_videos_per_prompt: int = 1,
330
+ device: Optional[torch.device] = None,
331
+ dtype: Optional[torch.dtype] = None,
332
+ max_sequence_length: int = 77,
333
+ ) -> torch.Tensor:
334
+ device = device or self._execution_device
335
+ dtype = dtype or self.text_encoder_2.dtype
336
+
337
+ prompt = [prompt] if isinstance(prompt, str) else prompt
338
+ batch_size = len(prompt)
339
+
340
+ text_inputs = self.tokenizer_2(
341
+ prompt,
342
+ padding="max_length",
343
+ max_length=max_sequence_length,
344
+ truncation=True,
345
+ return_tensors="pt",
346
+ )
347
+
348
+ text_input_ids = text_inputs.input_ids
349
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
350
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
351
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
352
+ logger.warning(
353
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
354
+ f" {max_sequence_length} tokens: {removed_text}"
355
+ )
356
+
357
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False).pooler_output
358
+
359
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
360
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
361
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, -1)
362
+
363
+ return prompt_embeds
364
+
365
+ def encode_prompt(
366
+ self,
367
+ prompt: Union[str, List[str]],
368
+ prompt_2: Union[str, List[str]] = None,
369
+ prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
370
+ num_videos_per_prompt: int = 1,
371
+ prompt_embeds: Optional[torch.Tensor] = None,
372
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
373
+ prompt_attention_mask: Optional[torch.Tensor] = None,
374
+ device: Optional[torch.device] = None,
375
+ dtype: Optional[torch.dtype] = None,
376
+ max_sequence_length: int = 256,
377
+ ):
378
+ if prompt_embeds is None:
379
+ prompt_embeds, prompt_attention_mask = self._get_llama_prompt_embeds(
380
+ prompt,
381
+ prompt_template,
382
+ num_videos_per_prompt,
383
+ device=device,
384
+ dtype=dtype,
385
+ max_sequence_length=max_sequence_length,
386
+ )
387
+
388
+ if pooled_prompt_embeds is None:
389
+ if prompt_2 is None and pooled_prompt_embeds is None:
390
+ prompt_2 = prompt
391
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
392
+ prompt,
393
+ num_videos_per_prompt,
394
+ device=device,
395
+ dtype=dtype,
396
+ max_sequence_length=77,
397
+ )
398
+
399
+ return prompt_embeds, pooled_prompt_embeds, prompt_attention_mask
400
+
401
+ def check_inputs(
402
+ self,
403
+ prompt,
404
+ prompt_2,
405
+ height,
406
+ width,
407
+ prompt_embeds=None,
408
+ callback_on_step_end_tensor_inputs=None,
409
+ prompt_template=None,
410
+ ):
411
+ if height % 16 != 0 or width % 16 != 0:
412
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
413
+
414
+ if callback_on_step_end_tensor_inputs is not None and not all(
415
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
416
+ ):
417
+ raise ValueError(
418
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
419
+ )
420
+
421
+ if prompt is not None and prompt_embeds is not None:
422
+ raise ValueError(
423
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
424
+ " only forward one of the two."
425
+ )
426
+ elif prompt_2 is not None and prompt_embeds is not None:
427
+ raise ValueError(
428
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
429
+ " only forward one of the two."
430
+ )
431
+ elif prompt is None and prompt_embeds is None:
432
+ raise ValueError(
433
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
434
+ )
435
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
436
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
437
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
438
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
439
+
440
+ if prompt_template is not None:
441
+ if not isinstance(prompt_template, dict):
442
+ raise ValueError(f"`prompt_template` has to be of type `dict` but is {type(prompt_template)}")
443
+ if "template" not in prompt_template:
444
+ raise ValueError(
445
+ f"`prompt_template` has to contain a key `template` but only found {prompt_template.keys()}"
446
+ )
447
+
448
+ def prepare_latents(
449
+ self,
450
+ batch_size: int,
451
+ num_channels_latents: 32,
452
+ height: int = 720,
453
+ width: int = 1280,
454
+ num_frames: int = 129,
455
+ dtype: Optional[torch.dtype] = None,
456
+ device: Optional[torch.device] = None,
457
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
458
+ latents: Optional[torch.Tensor] = None,
459
+ ) -> torch.Tensor:
460
+ if latents is not None:
461
+ return latents.to(device=device, dtype=dtype)
462
+
463
+ shape = (
464
+ batch_size,
465
+ num_channels_latents,
466
+ num_frames,
467
+ int(height) // self.vae_scale_factor_spatial,
468
+ int(width) // self.vae_scale_factor_spatial,
469
+ )
470
+ if isinstance(generator, list) and len(generator) != batch_size:
471
+ raise ValueError(
472
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
473
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
474
+ )
475
+
476
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
477
+ return latents
478
+
479
+ def enable_vae_slicing(self):
480
+ r"""
481
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
482
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
483
+ """
484
+ self.vae.enable_slicing()
485
+
486
+ def disable_vae_slicing(self):
487
+ r"""
488
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
489
+ computing decoding in one step.
490
+ """
491
+ self.vae.disable_slicing()
492
+
493
+ def enable_vae_tiling(self):
494
+ r"""
495
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
496
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
497
+ processing larger images.
498
+ """
499
+ self.vae.enable_tiling()
500
+
501
+ def disable_vae_tiling(self):
502
+ r"""
503
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
504
+ computing decoding in one step.
505
+ """
506
+ self.vae.disable_tiling()
507
+
508
+ @property
509
+ def guidance_scale(self):
510
+ return self._guidance_scale
511
+
512
+ @property
513
+ def do_spatio_temporal_guidance(self):
514
+ return self._stg_scale > 0.0
515
+
516
+ @property
517
+ def num_timesteps(self):
518
+ return self._num_timesteps
519
+
520
+ @property
521
+ def attention_kwargs(self):
522
+ return self._attention_kwargs
523
+
524
+ @property
525
+ def current_timestep(self):
526
+ return self._current_timestep
527
+
528
+ @property
529
+ def interrupt(self):
530
+ return self._interrupt
531
+
532
+ @torch.no_grad()
533
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
534
+ def __call__(
535
+ self,
536
+ prompt: Union[str, List[str]] = None,
537
+ prompt_2: Union[str, List[str]] = None,
538
+ height: int = 720,
539
+ width: int = 1280,
540
+ num_frames: int = 129,
541
+ num_inference_steps: int = 50,
542
+ sigmas: List[float] = None,
543
+ guidance_scale: float = 6.0,
544
+ num_videos_per_prompt: Optional[int] = 1,
545
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
546
+ latents: Optional[torch.Tensor] = None,
547
+ prompt_embeds: Optional[torch.Tensor] = None,
548
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
549
+ prompt_attention_mask: Optional[torch.Tensor] = None,
550
+ output_type: Optional[str] = "pil",
551
+ return_dict: bool = True,
552
+ attention_kwargs: Optional[Dict[str, Any]] = None,
553
+ callback_on_step_end: Optional[
554
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
555
+ ] = None,
556
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
557
+ prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
558
+ max_sequence_length: int = 256,
559
+ stg_applied_layers_idx: Optional[List[int]] = [2],
560
+ stg_scale: Optional[float] = 0.0,
561
+ ):
562
+ r"""
563
+ The call function to the pipeline for generation.
564
+
565
+ Args:
566
+ prompt (`str` or `List[str]`, *optional*):
567
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
568
+ instead.
569
+ prompt_2 (`str` or `List[str]`, *optional*):
570
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
571
+ will be used instead.
572
+ height (`int`, defaults to `720`):
573
+ The height in pixels of the generated image.
574
+ width (`int`, defaults to `1280`):
575
+ The width in pixels of the generated image.
576
+ num_frames (`int`, defaults to `129`):
577
+ The number of frames in the generated video.
578
+ num_inference_steps (`int`, defaults to `50`):
579
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
580
+ expense of slower inference.
581
+ sigmas (`List[float]`, *optional*):
582
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
583
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
584
+ will be used.
585
+ guidance_scale (`float`, defaults to `6.0`):
586
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
587
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
588
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
589
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
590
+ usually at the expense of lower image quality. Note that the only available HunyuanVideo model is
591
+ CFG-distilled, which means that traditional guidance between unconditional and conditional latent is
592
+ not applied.
593
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
594
+ The number of images to generate per prompt.
595
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
596
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
597
+ generation deterministic.
598
+ latents (`torch.Tensor`, *optional*):
599
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
600
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
601
+ tensor is generated by sampling using the supplied random `generator`.
602
+ prompt_embeds (`torch.Tensor`, *optional*):
603
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
604
+ provided, text embeddings are generated from the `prompt` input argument.
605
+ output_type (`str`, *optional*, defaults to `"pil"`):
606
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
607
+ return_dict (`bool`, *optional*, defaults to `True`):
608
+ Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a plain tuple.
609
+ attention_kwargs (`dict`, *optional*):
610
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
611
+ `self.processor` in
612
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
613
+ clip_skip (`int`, *optional*):
614
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
615
+ the output of the pre-final layer will be used for computing the prompt embeddings.
616
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
617
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
618
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
619
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
620
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
621
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
622
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
623
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
624
+ `._callback_tensor_inputs` attribute of your pipeline class.
625
+
626
+ Examples:
627
+
628
+ Returns:
629
+ [`~HunyuanVideoPipelineOutput`] or `tuple`:
630
+ If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned, otherwise a `tuple` is returned
631
+ where the first element is a list with the generated images and the second element is a list of `bool`s
632
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
633
+ """
634
+
635
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
636
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
637
+
638
+ # 1. Check inputs. Raise error if not correct
639
+ self.check_inputs(
640
+ prompt,
641
+ prompt_2,
642
+ height,
643
+ width,
644
+ prompt_embeds,
645
+ callback_on_step_end_tensor_inputs,
646
+ prompt_template,
647
+ )
648
+
649
+ self._stg_scale = stg_scale
650
+ self._guidance_scale = guidance_scale
651
+ self._attention_kwargs = attention_kwargs
652
+ self._current_timestep = None
653
+ self._interrupt = False
654
+
655
+ device = self._execution_device
656
+
657
+ # 2. Define call parameters
658
+ if prompt is not None and isinstance(prompt, str):
659
+ batch_size = 1
660
+ elif prompt is not None and isinstance(prompt, list):
661
+ batch_size = len(prompt)
662
+ else:
663
+ batch_size = prompt_embeds.shape[0]
664
+
665
+ # 3. Encode input prompt
666
+ prompt_embeds, pooled_prompt_embeds, prompt_attention_mask = self.encode_prompt(
667
+ prompt=prompt,
668
+ prompt_2=prompt_2,
669
+ prompt_template=prompt_template,
670
+ num_videos_per_prompt=num_videos_per_prompt,
671
+ prompt_embeds=prompt_embeds,
672
+ pooled_prompt_embeds=pooled_prompt_embeds,
673
+ prompt_attention_mask=prompt_attention_mask,
674
+ device=device,
675
+ max_sequence_length=max_sequence_length,
676
+ )
677
+
678
+ transformer_dtype = self.transformer.dtype
679
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
680
+ prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
681
+ if pooled_prompt_embeds is not None:
682
+ pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
683
+
684
+ # 4. Prepare timesteps
685
+ sigmas = np.linspace(1.0, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
686
+ timesteps, num_inference_steps = retrieve_timesteps(
687
+ self.scheduler,
688
+ num_inference_steps,
689
+ device,
690
+ sigmas=sigmas,
691
+ )
692
+
693
+ # 5. Prepare latent variables
694
+ num_channels_latents = self.transformer.config.in_channels
695
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
696
+ latents = self.prepare_latents(
697
+ batch_size * num_videos_per_prompt,
698
+ num_channels_latents,
699
+ height,
700
+ width,
701
+ num_latent_frames,
702
+ torch.float32,
703
+ device,
704
+ generator,
705
+ latents,
706
+ )
707
+
708
+ # 6. Prepare guidance condition
709
+ guidance = torch.tensor([guidance_scale] * latents.shape[0], dtype=transformer_dtype, device=device) * 1000.0
710
+
711
+ # 7. Denoising loop
712
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
713
+ self._num_timesteps = len(timesteps)
714
+
715
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
716
+ for i, t in enumerate(timesteps):
717
+ if self.interrupt:
718
+ continue
719
+
720
+ self._current_timestep = t
721
+ latent_model_input = latents.to(transformer_dtype)
722
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
723
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
724
+
725
+ if self.do_spatio_temporal_guidance:
726
+ for i in stg_applied_layers_idx:
727
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
728
+ forward_without_stg, self.transformer.transformer_blocks[i]
729
+ )
730
+
731
+ noise_pred = self.transformer(
732
+ hidden_states=latent_model_input,
733
+ timestep=timestep,
734
+ encoder_hidden_states=prompt_embeds,
735
+ encoder_attention_mask=prompt_attention_mask,
736
+ pooled_projections=pooled_prompt_embeds,
737
+ guidance=guidance,
738
+ attention_kwargs=attention_kwargs,
739
+ return_dict=False,
740
+ )[0]
741
+
742
+ if self.do_spatio_temporal_guidance:
743
+ for i in stg_applied_layers_idx:
744
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
745
+ forward_with_stg, self.transformer.transformer_blocks[i]
746
+ )
747
+
748
+ noise_pred_perturb = self.transformer(
749
+ hidden_states=latent_model_input,
750
+ timestep=timestep,
751
+ encoder_hidden_states=prompt_embeds,
752
+ encoder_attention_mask=prompt_attention_mask,
753
+ pooled_projections=pooled_prompt_embeds,
754
+ guidance=guidance,
755
+ attention_kwargs=attention_kwargs,
756
+ return_dict=False,
757
+ )[0]
758
+ noise_pred = noise_pred + self._stg_scale * (noise_pred - noise_pred_perturb)
759
+
760
+ # compute the previous noisy sample x_t -> x_t-1
761
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
762
+
763
+ if callback_on_step_end is not None:
764
+ callback_kwargs = {}
765
+ for k in callback_on_step_end_tensor_inputs:
766
+ callback_kwargs[k] = locals()[k]
767
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
768
+
769
+ latents = callback_outputs.pop("latents", latents)
770
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
771
+
772
+ # call the callback, if provided
773
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
774
+ progress_bar.update()
775
+
776
+ if XLA_AVAILABLE:
777
+ xm.mark_step()
778
+
779
+ self._current_timestep = None
780
+
781
+ if not output_type == "latent":
782
+ latents = latents.to(self.vae.dtype) / self.vae.config.scaling_factor
783
+ video = self.vae.decode(latents, return_dict=False)[0]
784
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
785
+ else:
786
+ video = latents
787
+
788
+ # Offload all models
789
+ self.maybe_free_model_hooks()
790
+
791
+ if not return_dict:
792
+ return (video,)
793
+
794
+ return HunyuanVideoPipelineOutput(frames=video)
main/pipeline_stg_ltx.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Lightricks and The HuggingFace Team. All rights reserved.
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
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import types
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import T5EncoderModel, T5TokenizerFast
22
+
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.loaders import FromSingleFileMixin, LTXVideoLoraLoaderMixin
25
+ from diffusers.models.autoencoders import AutoencoderKLLTXVideo
26
+ from diffusers.models.transformers import LTXVideoTransformer3DModel
27
+ from diffusers.pipelines.ltx.pipeline_output import LTXPipelineOutput
28
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
29
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
30
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
31
+ from diffusers.utils.torch_utils import randn_tensor
32
+ from diffusers.video_processor import VideoProcessor
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ EXAMPLE_DOC_STRING = """
45
+ Examples:
46
+ ```py
47
+ >>> import torch
48
+ >>> from diffusers.utils import export_to_video
49
+ >>> from examples.community.pipeline_stg_ltx import LTXSTGPipeline
50
+
51
+ >>> pipe = LTXSTGPipeline.from_pretrained("Lightricks/LTX-Video", torch_dtype=torch.bfloat16)
52
+ >>> pipe.to("cuda")
53
+
54
+ >>> prompt = "A woman with light skin, wearing a blue jacket and a black hat with a veil, looks down and to her right, then back up as she speaks; she has brown hair styled in an updo, light brown eyebrows, and is wearing a white collared shirt under her jacket; the camera remains stationary on her face as she speaks; the background is out of focus, but shows trees and people in period clothing; the scene is captured in real-life footage."
55
+ >>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
56
+
57
+ >>> # Configure STG mode options
58
+ >>> stg_applied_layers_idx = [19] # Layer indices from 0 to 41
59
+ >>> stg_scale = 1.0 # Set 0.0 for CFG
60
+ >>> do_rescaling = False
61
+
62
+ >>> video = pipe(
63
+ ... prompt=prompt,
64
+ ... negative_prompt=negative_prompt,
65
+ ... width=704,
66
+ ... height=480,
67
+ ... num_frames=161,
68
+ ... num_inference_steps=50,
69
+ ... stg_applied_layers_idx=stg_applied_layers_idx,
70
+ ... stg_scale=stg_scale,
71
+ ... do_rescaling=do_rescaling,
72
+ >>> ).frames[0]
73
+ >>> export_to_video(video, "output.mp4", fps=24)
74
+ ```
75
+ """
76
+
77
+
78
+ def forward_with_stg(
79
+ self,
80
+ hidden_states: torch.Tensor,
81
+ encoder_hidden_states: torch.Tensor,
82
+ temb: torch.Tensor,
83
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
84
+ encoder_attention_mask: Optional[torch.Tensor] = None,
85
+ ) -> torch.Tensor:
86
+ hidden_states_ptb = hidden_states[2:]
87
+ encoder_hidden_states_ptb = encoder_hidden_states[2:]
88
+
89
+ batch_size = hidden_states.size(0)
90
+ norm_hidden_states = self.norm1(hidden_states)
91
+
92
+ num_ada_params = self.scale_shift_table.shape[0]
93
+ ada_values = self.scale_shift_table[None, None] + temb.reshape(batch_size, temb.size(1), num_ada_params, -1)
94
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ada_values.unbind(dim=2)
95
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
96
+
97
+ attn_hidden_states = self.attn1(
98
+ hidden_states=norm_hidden_states,
99
+ encoder_hidden_states=None,
100
+ image_rotary_emb=image_rotary_emb,
101
+ )
102
+ hidden_states = hidden_states + attn_hidden_states * gate_msa
103
+
104
+ attn_hidden_states = self.attn2(
105
+ hidden_states,
106
+ encoder_hidden_states=encoder_hidden_states,
107
+ image_rotary_emb=None,
108
+ attention_mask=encoder_attention_mask,
109
+ )
110
+ hidden_states = hidden_states + attn_hidden_states
111
+ norm_hidden_states = self.norm2(hidden_states) * (1 + scale_mlp) + shift_mlp
112
+
113
+ ff_output = self.ff(norm_hidden_states)
114
+ hidden_states = hidden_states + ff_output * gate_mlp
115
+
116
+ hidden_states[2:] = hidden_states_ptb
117
+ encoder_hidden_states[2:] = encoder_hidden_states_ptb
118
+
119
+ return hidden_states
120
+
121
+
122
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
123
+ def calculate_shift(
124
+ image_seq_len,
125
+ base_seq_len: int = 256,
126
+ max_seq_len: int = 4096,
127
+ base_shift: float = 0.5,
128
+ max_shift: float = 1.16,
129
+ ):
130
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
131
+ b = base_shift - m * base_seq_len
132
+ mu = image_seq_len * m + b
133
+ return mu
134
+
135
+
136
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
137
+ def retrieve_timesteps(
138
+ scheduler,
139
+ num_inference_steps: Optional[int] = None,
140
+ device: Optional[Union[str, torch.device]] = None,
141
+ timesteps: Optional[List[int]] = None,
142
+ sigmas: Optional[List[float]] = None,
143
+ **kwargs,
144
+ ):
145
+ r"""
146
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
147
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
148
+
149
+ Args:
150
+ scheduler (`SchedulerMixin`):
151
+ The scheduler to get timesteps from.
152
+ num_inference_steps (`int`):
153
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
154
+ must be `None`.
155
+ device (`str` or `torch.device`, *optional*):
156
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
157
+ timesteps (`List[int]`, *optional*):
158
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
159
+ `num_inference_steps` and `sigmas` must be `None`.
160
+ sigmas (`List[float]`, *optional*):
161
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
162
+ `num_inference_steps` and `timesteps` must be `None`.
163
+
164
+ Returns:
165
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
166
+ second element is the number of inference steps.
167
+ """
168
+ if timesteps is not None and sigmas is not None:
169
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
170
+ if timesteps is not None:
171
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
172
+ if not accepts_timesteps:
173
+ raise ValueError(
174
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
175
+ f" timestep schedules. Please check whether you are using the correct scheduler."
176
+ )
177
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
178
+ timesteps = scheduler.timesteps
179
+ num_inference_steps = len(timesteps)
180
+ elif sigmas is not None:
181
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
182
+ if not accept_sigmas:
183
+ raise ValueError(
184
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
185
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
186
+ )
187
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
188
+ timesteps = scheduler.timesteps
189
+ num_inference_steps = len(timesteps)
190
+ else:
191
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
192
+ timesteps = scheduler.timesteps
193
+ return timesteps, num_inference_steps
194
+
195
+
196
+ class LTXSTGPipeline(DiffusionPipeline, FromSingleFileMixin, LTXVideoLoraLoaderMixin):
197
+ r"""
198
+ Pipeline for text-to-video generation.
199
+
200
+ Reference: https://github.com/Lightricks/LTX-Video
201
+
202
+ Args:
203
+ transformer ([`LTXVideoTransformer3DModel`]):
204
+ Conditional Transformer architecture to denoise the encoded video latents.
205
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
206
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
207
+ vae ([`AutoencoderKLLTXVideo`]):
208
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
209
+ text_encoder ([`T5EncoderModel`]):
210
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
211
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
212
+ tokenizer (`CLIPTokenizer`):
213
+ Tokenizer of class
214
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
215
+ tokenizer (`T5TokenizerFast`):
216
+ Second Tokenizer of class
217
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
218
+ """
219
+
220
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
221
+ _optional_components = []
222
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
223
+
224
+ def __init__(
225
+ self,
226
+ scheduler: FlowMatchEulerDiscreteScheduler,
227
+ vae: AutoencoderKLLTXVideo,
228
+ text_encoder: T5EncoderModel,
229
+ tokenizer: T5TokenizerFast,
230
+ transformer: LTXVideoTransformer3DModel,
231
+ ):
232
+ super().__init__()
233
+
234
+ self.register_modules(
235
+ vae=vae,
236
+ text_encoder=text_encoder,
237
+ tokenizer=tokenizer,
238
+ transformer=transformer,
239
+ scheduler=scheduler,
240
+ )
241
+
242
+ self.vae_spatial_compression_ratio = (
243
+ self.vae.spatial_compression_ratio if getattr(self, "vae", None) is not None else 32
244
+ )
245
+ self.vae_temporal_compression_ratio = (
246
+ self.vae.temporal_compression_ratio if getattr(self, "vae", None) is not None else 8
247
+ )
248
+ self.transformer_spatial_patch_size = (
249
+ self.transformer.config.patch_size if getattr(self, "transformer", None) is not None else 1
250
+ )
251
+ self.transformer_temporal_patch_size = (
252
+ self.transformer.config.patch_size_t if getattr(self, "transformer") is not None else 1
253
+ )
254
+
255
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
256
+ self.tokenizer_max_length = (
257
+ self.tokenizer.model_max_length if getattr(self, "tokenizer", None) is not None else 128
258
+ )
259
+
260
+ def _get_t5_prompt_embeds(
261
+ self,
262
+ prompt: Union[str, List[str]] = None,
263
+ num_videos_per_prompt: int = 1,
264
+ max_sequence_length: int = 128,
265
+ device: Optional[torch.device] = None,
266
+ dtype: Optional[torch.dtype] = None,
267
+ ):
268
+ device = device or self._execution_device
269
+ dtype = dtype or self.text_encoder.dtype
270
+
271
+ prompt = [prompt] if isinstance(prompt, str) else prompt
272
+ batch_size = len(prompt)
273
+
274
+ text_inputs = self.tokenizer(
275
+ prompt,
276
+ padding="max_length",
277
+ max_length=max_sequence_length,
278
+ truncation=True,
279
+ add_special_tokens=True,
280
+ return_tensors="pt",
281
+ )
282
+ text_input_ids = text_inputs.input_ids
283
+ prompt_attention_mask = text_inputs.attention_mask
284
+ prompt_attention_mask = prompt_attention_mask.bool().to(device)
285
+
286
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
287
+
288
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
289
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
290
+ logger.warning(
291
+ "The following part of your input was truncated because `max_sequence_length` is set to "
292
+ f" {max_sequence_length} tokens: {removed_text}"
293
+ )
294
+
295
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
296
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
297
+
298
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
299
+ _, seq_len, _ = prompt_embeds.shape
300
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
301
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
302
+
303
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
304
+ prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1)
305
+
306
+ return prompt_embeds, prompt_attention_mask
307
+
308
+ # Copied from diffusers.pipelines.mochi.pipeline_mochi.MochiPipeline.encode_prompt with 256->128
309
+ def encode_prompt(
310
+ self,
311
+ prompt: Union[str, List[str]],
312
+ negative_prompt: Optional[Union[str, List[str]]] = None,
313
+ do_classifier_free_guidance: bool = True,
314
+ num_videos_per_prompt: int = 1,
315
+ prompt_embeds: Optional[torch.Tensor] = None,
316
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
317
+ prompt_attention_mask: Optional[torch.Tensor] = None,
318
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
319
+ max_sequence_length: int = 128,
320
+ device: Optional[torch.device] = None,
321
+ dtype: Optional[torch.dtype] = None,
322
+ ):
323
+ r"""
324
+ Encodes the prompt into text encoder hidden states.
325
+
326
+ Args:
327
+ prompt (`str` or `List[str]`, *optional*):
328
+ prompt to be encoded
329
+ negative_prompt (`str` or `List[str]`, *optional*):
330
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
331
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
332
+ less than `1`).
333
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
334
+ Whether to use classifier free guidance or not.
335
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
336
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
337
+ prompt_embeds (`torch.Tensor`, *optional*):
338
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
339
+ provided, text embeddings will be generated from `prompt` input argument.
340
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
341
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
342
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
343
+ argument.
344
+ device: (`torch.device`, *optional*):
345
+ torch device
346
+ dtype: (`torch.dtype`, *optional*):
347
+ torch dtype
348
+ """
349
+ device = device or self._execution_device
350
+
351
+ prompt = [prompt] if isinstance(prompt, str) else prompt
352
+ if prompt is not None:
353
+ batch_size = len(prompt)
354
+ else:
355
+ batch_size = prompt_embeds.shape[0]
356
+
357
+ if prompt_embeds is None:
358
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
359
+ prompt=prompt,
360
+ num_videos_per_prompt=num_videos_per_prompt,
361
+ max_sequence_length=max_sequence_length,
362
+ device=device,
363
+ dtype=dtype,
364
+ )
365
+
366
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
367
+ negative_prompt = negative_prompt or ""
368
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
369
+
370
+ if prompt is not None and type(prompt) is not type(negative_prompt):
371
+ raise TypeError(
372
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
373
+ f" {type(prompt)}."
374
+ )
375
+ elif batch_size != len(negative_prompt):
376
+ raise ValueError(
377
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
378
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
379
+ " the batch size of `prompt`."
380
+ )
381
+
382
+ negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
383
+ prompt=negative_prompt,
384
+ num_videos_per_prompt=num_videos_per_prompt,
385
+ max_sequence_length=max_sequence_length,
386
+ device=device,
387
+ dtype=dtype,
388
+ )
389
+
390
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
391
+
392
+ def check_inputs(
393
+ self,
394
+ prompt,
395
+ height,
396
+ width,
397
+ callback_on_step_end_tensor_inputs=None,
398
+ prompt_embeds=None,
399
+ negative_prompt_embeds=None,
400
+ prompt_attention_mask=None,
401
+ negative_prompt_attention_mask=None,
402
+ ):
403
+ if height % 32 != 0 or width % 32 != 0:
404
+ raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
405
+
406
+ if callback_on_step_end_tensor_inputs is not None and not all(
407
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
408
+ ):
409
+ raise ValueError(
410
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
411
+ )
412
+
413
+ if prompt is not None and prompt_embeds is not None:
414
+ raise ValueError(
415
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
416
+ " only forward one of the two."
417
+ )
418
+ elif prompt is None and prompt_embeds is None:
419
+ raise ValueError(
420
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
421
+ )
422
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
423
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
424
+
425
+ if prompt_embeds is not None and prompt_attention_mask is None:
426
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
427
+
428
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
429
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
430
+
431
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
432
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
433
+ raise ValueError(
434
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
435
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
436
+ f" {negative_prompt_embeds.shape}."
437
+ )
438
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
439
+ raise ValueError(
440
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
441
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
442
+ f" {negative_prompt_attention_mask.shape}."
443
+ )
444
+
445
+ @staticmethod
446
+ def _pack_latents(latents: torch.Tensor, patch_size: int = 1, patch_size_t: int = 1) -> torch.Tensor:
447
+ # Unpacked latents of shape are [B, C, F, H, W] are patched into tokens of shape [B, C, F // p_t, p_t, H // p, p, W // p, p].
448
+ # The patch dimensions are then permuted and collapsed into the channel dimension of shape:
449
+ # [B, F // p_t * H // p * W // p, C * p_t * p * p] (an ndim=3 tensor).
450
+ # dim=0 is the batch size, dim=1 is the effective video sequence length, dim=2 is the effective number of input features
451
+ batch_size, num_channels, num_frames, height, width = latents.shape
452
+ post_patch_num_frames = num_frames // patch_size_t
453
+ post_patch_height = height // patch_size
454
+ post_patch_width = width // patch_size
455
+ latents = latents.reshape(
456
+ batch_size,
457
+ -1,
458
+ post_patch_num_frames,
459
+ patch_size_t,
460
+ post_patch_height,
461
+ patch_size,
462
+ post_patch_width,
463
+ patch_size,
464
+ )
465
+ latents = latents.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7).flatten(1, 3)
466
+ return latents
467
+
468
+ @staticmethod
469
+ def _unpack_latents(
470
+ latents: torch.Tensor, num_frames: int, height: int, width: int, patch_size: int = 1, patch_size_t: int = 1
471
+ ) -> torch.Tensor:
472
+ # Packed latents of shape [B, S, D] (S is the effective video sequence length, D is the effective feature dimensions)
473
+ # are unpacked and reshaped into a video tensor of shape [B, C, F, H, W]. This is the inverse operation of
474
+ # what happens in the `_pack_latents` method.
475
+ batch_size = latents.size(0)
476
+ latents = latents.reshape(batch_size, num_frames, height, width, -1, patch_size_t, patch_size, patch_size)
477
+ latents = latents.permute(0, 4, 1, 5, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(2, 3)
478
+ return latents
479
+
480
+ @staticmethod
481
+ def _normalize_latents(
482
+ latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
483
+ ) -> torch.Tensor:
484
+ # Normalize latents across the channel dimension [B, C, F, H, W]
485
+ latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
486
+ latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
487
+ latents = (latents - latents_mean) * scaling_factor / latents_std
488
+ return latents
489
+
490
+ @staticmethod
491
+ def _denormalize_latents(
492
+ latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
493
+ ) -> torch.Tensor:
494
+ # Denormalize latents across the channel dimension [B, C, F, H, W]
495
+ latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
496
+ latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
497
+ latents = latents * latents_std / scaling_factor + latents_mean
498
+ return latents
499
+
500
+ def prepare_latents(
501
+ self,
502
+ batch_size: int = 1,
503
+ num_channels_latents: int = 128,
504
+ height: int = 512,
505
+ width: int = 704,
506
+ num_frames: int = 161,
507
+ dtype: Optional[torch.dtype] = None,
508
+ device: Optional[torch.device] = None,
509
+ generator: Optional[torch.Generator] = None,
510
+ latents: Optional[torch.Tensor] = None,
511
+ ) -> torch.Tensor:
512
+ if latents is not None:
513
+ return latents.to(device=device, dtype=dtype)
514
+
515
+ height = height // self.vae_spatial_compression_ratio
516
+ width = width // self.vae_spatial_compression_ratio
517
+ num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
518
+
519
+ shape = (batch_size, num_channels_latents, num_frames, height, width)
520
+
521
+ if isinstance(generator, list) and len(generator) != batch_size:
522
+ raise ValueError(
523
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
524
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
525
+ )
526
+
527
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
528
+ latents = self._pack_latents(
529
+ latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
530
+ )
531
+ return latents
532
+
533
+ @property
534
+ def guidance_scale(self):
535
+ return self._guidance_scale
536
+
537
+ @property
538
+ def do_classifier_free_guidance(self):
539
+ return self._guidance_scale > 1.0
540
+
541
+ @property
542
+ def do_spatio_temporal_guidance(self):
543
+ return self._stg_scale > 0.0
544
+
545
+ @property
546
+ def num_timesteps(self):
547
+ return self._num_timesteps
548
+
549
+ @property
550
+ def attention_kwargs(self):
551
+ return self._attention_kwargs
552
+
553
+ @property
554
+ def interrupt(self):
555
+ return self._interrupt
556
+
557
+ @torch.no_grad()
558
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
559
+ def __call__(
560
+ self,
561
+ prompt: Union[str, List[str]] = None,
562
+ negative_prompt: Optional[Union[str, List[str]]] = None,
563
+ height: int = 512,
564
+ width: int = 704,
565
+ num_frames: int = 161,
566
+ frame_rate: int = 25,
567
+ num_inference_steps: int = 50,
568
+ timesteps: List[int] = None,
569
+ guidance_scale: float = 3,
570
+ num_videos_per_prompt: Optional[int] = 1,
571
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
572
+ latents: Optional[torch.Tensor] = None,
573
+ prompt_embeds: Optional[torch.Tensor] = None,
574
+ prompt_attention_mask: Optional[torch.Tensor] = None,
575
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
576
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
577
+ decode_timestep: Union[float, List[float]] = 0.0,
578
+ decode_noise_scale: Optional[Union[float, List[float]]] = None,
579
+ output_type: Optional[str] = "pil",
580
+ return_dict: bool = True,
581
+ attention_kwargs: Optional[Dict[str, Any]] = None,
582
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
583
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
584
+ max_sequence_length: int = 128,
585
+ stg_applied_layers_idx: Optional[List[int]] = [19],
586
+ stg_scale: Optional[float] = 1.0,
587
+ do_rescaling: Optional[bool] = False,
588
+ ):
589
+ r"""
590
+ Function invoked when calling the pipeline for generation.
591
+
592
+ Args:
593
+ prompt (`str` or `List[str]`, *optional*):
594
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
595
+ instead.
596
+ height (`int`, defaults to `512`):
597
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
598
+ width (`int`, defaults to `704`):
599
+ The width in pixels of the generated image. This is set to 848 by default for the best results.
600
+ num_frames (`int`, defaults to `161`):
601
+ The number of video frames to generate
602
+ num_inference_steps (`int`, *optional*, defaults to 50):
603
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
604
+ expense of slower inference.
605
+ timesteps (`List[int]`, *optional*):
606
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
607
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
608
+ passed will be used. Must be in descending order.
609
+ guidance_scale (`float`, defaults to `3 `):
610
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
611
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
612
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
613
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
614
+ usually at the expense of lower image quality.
615
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
616
+ The number of videos to generate per prompt.
617
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
618
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
619
+ to make generation deterministic.
620
+ latents (`torch.Tensor`, *optional*):
621
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
622
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
623
+ tensor will ge generated by sampling using the supplied random `generator`.
624
+ prompt_embeds (`torch.Tensor`, *optional*):
625
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
626
+ provided, text embeddings will be generated from `prompt` input argument.
627
+ prompt_attention_mask (`torch.Tensor`, *optional*):
628
+ Pre-generated attention mask for text embeddings.
629
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
630
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
631
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
632
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
633
+ Pre-generated attention mask for negative text embeddings.
634
+ decode_timestep (`float`, defaults to `0.0`):
635
+ The timestep at which generated video is decoded.
636
+ decode_noise_scale (`float`, defaults to `None`):
637
+ The interpolation factor between random noise and denoised latents at the decode timestep.
638
+ output_type (`str`, *optional*, defaults to `"pil"`):
639
+ The output format of the generate image. Choose between
640
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
641
+ return_dict (`bool`, *optional*, defaults to `True`):
642
+ Whether or not to return a [`~pipelines.ltx.LTXPipelineOutput`] instead of a plain tuple.
643
+ attention_kwargs (`dict`, *optional*):
644
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
645
+ `self.processor` in
646
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
647
+ callback_on_step_end (`Callable`, *optional*):
648
+ A function that calls at the end of each denoising steps during the inference. The function is called
649
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
650
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
651
+ `callback_on_step_end_tensor_inputs`.
652
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
653
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
654
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
655
+ `._callback_tensor_inputs` attribute of your pipeline class.
656
+ max_sequence_length (`int` defaults to `128 `):
657
+ Maximum sequence length to use with the `prompt`.
658
+
659
+ Examples:
660
+
661
+ Returns:
662
+ [`~pipelines.ltx.LTXPipelineOutput`] or `tuple`:
663
+ If `return_dict` is `True`, [`~pipelines.ltx.LTXPipelineOutput`] is returned, otherwise a `tuple` is
664
+ returned where the first element is a list with the generated images.
665
+ """
666
+
667
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
668
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
669
+
670
+ # 1. Check inputs. Raise error if not correct
671
+ self.check_inputs(
672
+ prompt=prompt,
673
+ height=height,
674
+ width=width,
675
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
676
+ prompt_embeds=prompt_embeds,
677
+ negative_prompt_embeds=negative_prompt_embeds,
678
+ prompt_attention_mask=prompt_attention_mask,
679
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
680
+ )
681
+
682
+ self._stg_scale = stg_scale
683
+ self._guidance_scale = guidance_scale
684
+ self._attention_kwargs = attention_kwargs
685
+ self._interrupt = False
686
+
687
+ if self.do_spatio_temporal_guidance:
688
+ for i in stg_applied_layers_idx:
689
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
690
+ forward_with_stg, self.transformer.transformer_blocks[i]
691
+ )
692
+
693
+ # 2. Define call parameters
694
+ if prompt is not None and isinstance(prompt, str):
695
+ batch_size = 1
696
+ elif prompt is not None and isinstance(prompt, list):
697
+ batch_size = len(prompt)
698
+ else:
699
+ batch_size = prompt_embeds.shape[0]
700
+
701
+ device = self._execution_device
702
+
703
+ # 3. Prepare text embeddings
704
+ (
705
+ prompt_embeds,
706
+ prompt_attention_mask,
707
+ negative_prompt_embeds,
708
+ negative_prompt_attention_mask,
709
+ ) = self.encode_prompt(
710
+ prompt=prompt,
711
+ negative_prompt=negative_prompt,
712
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
713
+ num_videos_per_prompt=num_videos_per_prompt,
714
+ prompt_embeds=prompt_embeds,
715
+ negative_prompt_embeds=negative_prompt_embeds,
716
+ prompt_attention_mask=prompt_attention_mask,
717
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
718
+ max_sequence_length=max_sequence_length,
719
+ device=device,
720
+ )
721
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
722
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
723
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
724
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
725
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0)
726
+ prompt_attention_mask = torch.cat(
727
+ [negative_prompt_attention_mask, prompt_attention_mask, prompt_attention_mask], dim=0
728
+ )
729
+
730
+ # 4. Prepare latent variables
731
+ num_channels_latents = self.transformer.config.in_channels
732
+ latents = self.prepare_latents(
733
+ batch_size * num_videos_per_prompt,
734
+ num_channels_latents,
735
+ height,
736
+ width,
737
+ num_frames,
738
+ torch.float32,
739
+ device,
740
+ generator,
741
+ latents,
742
+ )
743
+
744
+ # 5. Prepare timesteps
745
+ latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
746
+ latent_height = height // self.vae_spatial_compression_ratio
747
+ latent_width = width // self.vae_spatial_compression_ratio
748
+ video_sequence_length = latent_num_frames * latent_height * latent_width
749
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
750
+ mu = calculate_shift(
751
+ video_sequence_length,
752
+ self.scheduler.config.get("base_image_seq_len", 256),
753
+ self.scheduler.config.get("max_image_seq_len", 4096),
754
+ self.scheduler.config.get("base_shift", 0.5),
755
+ self.scheduler.config.get("max_shift", 1.16),
756
+ )
757
+ timesteps, num_inference_steps = retrieve_timesteps(
758
+ self.scheduler,
759
+ num_inference_steps,
760
+ device,
761
+ timesteps,
762
+ sigmas=sigmas,
763
+ mu=mu,
764
+ )
765
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
766
+ self._num_timesteps = len(timesteps)
767
+
768
+ # 6. Prepare micro-conditions
769
+ latent_frame_rate = frame_rate / self.vae_temporal_compression_ratio
770
+ rope_interpolation_scale = (
771
+ 1 / latent_frame_rate,
772
+ self.vae_spatial_compression_ratio,
773
+ self.vae_spatial_compression_ratio,
774
+ )
775
+
776
+ # 7. Denoising loop
777
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
778
+ for i, t in enumerate(timesteps):
779
+ if self.interrupt:
780
+ continue
781
+
782
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
783
+ latent_model_input = torch.cat([latents] * 2)
784
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
785
+ latent_model_input = torch.cat([latents] * 3)
786
+ else:
787
+ latent_model_input = latents
788
+
789
+ latent_model_input = latent_model_input.to(prompt_embeds.dtype)
790
+
791
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
792
+ timestep = t.expand(latent_model_input.shape[0])
793
+
794
+ noise_pred = self.transformer(
795
+ hidden_states=latent_model_input,
796
+ encoder_hidden_states=prompt_embeds,
797
+ timestep=timestep,
798
+ encoder_attention_mask=prompt_attention_mask,
799
+ num_frames=latent_num_frames,
800
+ height=latent_height,
801
+ width=latent_width,
802
+ rope_interpolation_scale=rope_interpolation_scale,
803
+ attention_kwargs=attention_kwargs,
804
+ return_dict=False,
805
+ )[0]
806
+ noise_pred = noise_pred.float()
807
+
808
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
809
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
810
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
811
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
812
+ noise_pred_uncond, noise_pred_text, noise_pred_perturb = noise_pred.chunk(3)
813
+ noise_pred = (
814
+ noise_pred_uncond
815
+ + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
816
+ + self._stg_scale * (noise_pred_text - noise_pred_perturb)
817
+ )
818
+
819
+ if do_rescaling:
820
+ rescaling_scale = 0.7
821
+ factor = noise_pred_text.std() / noise_pred.std()
822
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
823
+ noise_pred = noise_pred * factor
824
+
825
+ # compute the previous noisy sample x_t -> x_t-1
826
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
827
+
828
+ if callback_on_step_end is not None:
829
+ callback_kwargs = {}
830
+ for k in callback_on_step_end_tensor_inputs:
831
+ callback_kwargs[k] = locals()[k]
832
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
833
+
834
+ latents = callback_outputs.pop("latents", latents)
835
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
836
+
837
+ # call the callback, if provided
838
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
839
+ progress_bar.update()
840
+
841
+ if XLA_AVAILABLE:
842
+ xm.mark_step()
843
+
844
+ if output_type == "latent":
845
+ video = latents
846
+ else:
847
+ latents = self._unpack_latents(
848
+ latents,
849
+ latent_num_frames,
850
+ latent_height,
851
+ latent_width,
852
+ self.transformer_spatial_patch_size,
853
+ self.transformer_temporal_patch_size,
854
+ )
855
+ latents = self._denormalize_latents(
856
+ latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor
857
+ )
858
+ latents = latents.to(prompt_embeds.dtype)
859
+
860
+ if not self.vae.config.timestep_conditioning:
861
+ timestep = None
862
+ else:
863
+ noise = randn_tensor(latents.shape, generator=generator, device=device, dtype=latents.dtype)
864
+ if not isinstance(decode_timestep, list):
865
+ decode_timestep = [decode_timestep] * batch_size
866
+ if decode_noise_scale is None:
867
+ decode_noise_scale = decode_timestep
868
+ elif not isinstance(decode_noise_scale, list):
869
+ decode_noise_scale = [decode_noise_scale] * batch_size
870
+
871
+ timestep = torch.tensor(decode_timestep, device=device, dtype=latents.dtype)
872
+ decode_noise_scale = torch.tensor(decode_noise_scale, device=device, dtype=latents.dtype)[
873
+ :, None, None, None, None
874
+ ]
875
+ latents = (1 - decode_noise_scale) * latents + decode_noise_scale * noise
876
+
877
+ video = self.vae.decode(latents, timestep, return_dict=False)[0]
878
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
879
+
880
+ # Offload all models
881
+ self.maybe_free_model_hooks()
882
+
883
+ if not return_dict:
884
+ return (video,)
885
+
886
+ return LTXPipelineOutput(frames=video)
main/pipeline_stg_ltx_image2video.py ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Lightricks and The HuggingFace Team. All rights reserved.
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
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import types
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import T5EncoderModel, T5TokenizerFast
22
+
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.image_processor import PipelineImageInput
25
+ from diffusers.loaders import FromSingleFileMixin, LTXVideoLoraLoaderMixin
26
+ from diffusers.models.autoencoders import AutoencoderKLLTXVideo
27
+ from diffusers.models.transformers import LTXVideoTransformer3DModel
28
+ from diffusers.pipelines.ltx.pipeline_output import LTXPipelineOutput
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
31
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+ from diffusers.video_processor import VideoProcessor
34
+
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
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+ EXAMPLE_DOC_STRING = """
46
+ Examples:
47
+ ```py
48
+ >>> import torch
49
+ >>> from diffusers.utils import export_to_video, load_image
50
+ >>> from examples.community.pipeline_stg_ltx_image2video import LTXImageToVideoSTGPipeline
51
+
52
+ >>> pipe = LTXImageToVideoSTGPipeline.from_pretrained("Lightricks/LTX-Video", torch_dtype=torch.bfloat16)
53
+ >>> pipe.to("cuda")
54
+
55
+ >>> image = load_image(
56
+ ... "https://huggingface.co/datasets/a-r-r-o-w/tiny-meme-dataset-captioned/resolve/main/images/11.png"
57
+ >>> )
58
+ >>> prompt = "A medieval fantasy scene featuring a rugged man with shoulder-length brown hair and a beard. He wears a dark leather tunic over a maroon shirt with intricate metal details. His facial expression is serious and intense, and he is making a gesture with his right hand, forming a small circle with his thumb and index finger. The warm golden lighting casts dramatic shadows on his face. The background includes an ornate stone arch and blurred medieval-style decor, creating an epic atmosphere."
59
+ >>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
60
+
61
+ >>> # Configure STG mode options
62
+ >>> stg_applied_layers_idx = [19] # Layer indices from 0 to 41
63
+ >>> stg_scale = 1.0 # Set 0.0 for CFG
64
+ >>> do_rescaling = False
65
+
66
+ >>> video = pipe(
67
+ ... image=image,
68
+ ... prompt=prompt,
69
+ ... negative_prompt=negative_prompt,
70
+ ... width=704,
71
+ ... height=480,
72
+ ... num_frames=161,
73
+ ... num_inference_steps=50,
74
+ ... stg_applied_layers_idx=stg_applied_layers_idx,
75
+ ... stg_scale=stg_scale,
76
+ ... do_rescaling=do_rescaling,
77
+ >>> ).frames[0]
78
+ >>> export_to_video(video, "output.mp4", fps=24)
79
+ ```
80
+ """
81
+
82
+
83
+ def forward_with_stg(
84
+ self,
85
+ hidden_states: torch.Tensor,
86
+ encoder_hidden_states: torch.Tensor,
87
+ temb: torch.Tensor,
88
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
89
+ encoder_attention_mask: Optional[torch.Tensor] = None,
90
+ ) -> torch.Tensor:
91
+ hidden_states_ptb = hidden_states[2:]
92
+ encoder_hidden_states_ptb = encoder_hidden_states[2:]
93
+
94
+ batch_size = hidden_states.size(0)
95
+ norm_hidden_states = self.norm1(hidden_states)
96
+
97
+ num_ada_params = self.scale_shift_table.shape[0]
98
+ ada_values = self.scale_shift_table[None, None] + temb.reshape(batch_size, temb.size(1), num_ada_params, -1)
99
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ada_values.unbind(dim=2)
100
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
101
+
102
+ attn_hidden_states = self.attn1(
103
+ hidden_states=norm_hidden_states,
104
+ encoder_hidden_states=None,
105
+ image_rotary_emb=image_rotary_emb,
106
+ )
107
+ hidden_states = hidden_states + attn_hidden_states * gate_msa
108
+
109
+ attn_hidden_states = self.attn2(
110
+ hidden_states,
111
+ encoder_hidden_states=encoder_hidden_states,
112
+ image_rotary_emb=None,
113
+ attention_mask=encoder_attention_mask,
114
+ )
115
+ hidden_states = hidden_states + attn_hidden_states
116
+ norm_hidden_states = self.norm2(hidden_states) * (1 + scale_mlp) + shift_mlp
117
+
118
+ ff_output = self.ff(norm_hidden_states)
119
+ hidden_states = hidden_states + ff_output * gate_mlp
120
+
121
+ hidden_states[2:] = hidden_states_ptb
122
+ encoder_hidden_states[2:] = encoder_hidden_states_ptb
123
+
124
+ return hidden_states
125
+
126
+
127
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
128
+ def calculate_shift(
129
+ image_seq_len,
130
+ base_seq_len: int = 256,
131
+ max_seq_len: int = 4096,
132
+ base_shift: float = 0.5,
133
+ max_shift: float = 1.16,
134
+ ):
135
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
136
+ b = base_shift - m * base_seq_len
137
+ mu = image_seq_len * m + b
138
+ return mu
139
+
140
+
141
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
142
+ def retrieve_timesteps(
143
+ scheduler,
144
+ num_inference_steps: Optional[int] = None,
145
+ device: Optional[Union[str, torch.device]] = None,
146
+ timesteps: Optional[List[int]] = None,
147
+ sigmas: Optional[List[float]] = None,
148
+ **kwargs,
149
+ ):
150
+ r"""
151
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
152
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
153
+
154
+ Args:
155
+ scheduler (`SchedulerMixin`):
156
+ The scheduler to get timesteps from.
157
+ num_inference_steps (`int`):
158
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
159
+ must be `None`.
160
+ device (`str` or `torch.device`, *optional*):
161
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
162
+ timesteps (`List[int]`, *optional*):
163
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
164
+ `num_inference_steps` and `sigmas` must be `None`.
165
+ sigmas (`List[float]`, *optional*):
166
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
167
+ `num_inference_steps` and `timesteps` must be `None`.
168
+
169
+ Returns:
170
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
171
+ second element is the number of inference steps.
172
+ """
173
+ if timesteps is not None and sigmas is not None:
174
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
175
+ if timesteps is not None:
176
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
177
+ if not accepts_timesteps:
178
+ raise ValueError(
179
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
180
+ f" timestep schedules. Please check whether you are using the correct scheduler."
181
+ )
182
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
183
+ timesteps = scheduler.timesteps
184
+ num_inference_steps = len(timesteps)
185
+ elif sigmas is not None:
186
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
187
+ if not accept_sigmas:
188
+ raise ValueError(
189
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
190
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
191
+ )
192
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
193
+ timesteps = scheduler.timesteps
194
+ num_inference_steps = len(timesteps)
195
+ else:
196
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
197
+ timesteps = scheduler.timesteps
198
+ return timesteps, num_inference_steps
199
+
200
+
201
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
202
+ def retrieve_latents(
203
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
204
+ ):
205
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
206
+ return encoder_output.latent_dist.sample(generator)
207
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
208
+ return encoder_output.latent_dist.mode()
209
+ elif hasattr(encoder_output, "latents"):
210
+ return encoder_output.latents
211
+ else:
212
+ raise AttributeError("Could not access latents of provided encoder_output")
213
+
214
+
215
+ class LTXImageToVideoSTGPipeline(DiffusionPipeline, FromSingleFileMixin, LTXVideoLoraLoaderMixin):
216
+ r"""
217
+ Pipeline for image-to-video generation.
218
+
219
+ Reference: https://github.com/Lightricks/LTX-Video
220
+
221
+ Args:
222
+ transformer ([`LTXVideoTransformer3DModel`]):
223
+ Conditional Transformer architecture to denoise the encoded video latents.
224
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
225
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
226
+ vae ([`AutoencoderKLLTXVideo`]):
227
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
228
+ text_encoder ([`T5EncoderModel`]):
229
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
230
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
231
+ tokenizer (`CLIPTokenizer`):
232
+ Tokenizer of class
233
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
234
+ tokenizer (`T5TokenizerFast`):
235
+ Second Tokenizer of class
236
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
237
+ """
238
+
239
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
240
+ _optional_components = []
241
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
242
+
243
+ def __init__(
244
+ self,
245
+ scheduler: FlowMatchEulerDiscreteScheduler,
246
+ vae: AutoencoderKLLTXVideo,
247
+ text_encoder: T5EncoderModel,
248
+ tokenizer: T5TokenizerFast,
249
+ transformer: LTXVideoTransformer3DModel,
250
+ ):
251
+ super().__init__()
252
+
253
+ self.register_modules(
254
+ vae=vae,
255
+ text_encoder=text_encoder,
256
+ tokenizer=tokenizer,
257
+ transformer=transformer,
258
+ scheduler=scheduler,
259
+ )
260
+
261
+ self.vae_spatial_compression_ratio = (
262
+ self.vae.spatial_compression_ratio if getattr(self, "vae", None) is not None else 32
263
+ )
264
+ self.vae_temporal_compression_ratio = (
265
+ self.vae.temporal_compression_ratio if getattr(self, "vae", None) is not None else 8
266
+ )
267
+ self.transformer_spatial_patch_size = (
268
+ self.transformer.config.patch_size if getattr(self, "transformer", None) is not None else 1
269
+ )
270
+ self.transformer_temporal_patch_size = (
271
+ self.transformer.config.patch_size_t if getattr(self, "transformer") is not None else 1
272
+ )
273
+
274
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
275
+ self.tokenizer_max_length = (
276
+ self.tokenizer.model_max_length if getattr(self, "tokenizer", None) is not None else 128
277
+ )
278
+
279
+ self.default_height = 512
280
+ self.default_width = 704
281
+ self.default_frames = 121
282
+
283
+ def _get_t5_prompt_embeds(
284
+ self,
285
+ prompt: Union[str, List[str]] = None,
286
+ num_videos_per_prompt: int = 1,
287
+ max_sequence_length: int = 128,
288
+ device: Optional[torch.device] = None,
289
+ dtype: Optional[torch.dtype] = None,
290
+ ):
291
+ device = device or self._execution_device
292
+ dtype = dtype or self.text_encoder.dtype
293
+
294
+ prompt = [prompt] if isinstance(prompt, str) else prompt
295
+ batch_size = len(prompt)
296
+
297
+ text_inputs = self.tokenizer(
298
+ prompt,
299
+ padding="max_length",
300
+ max_length=max_sequence_length,
301
+ truncation=True,
302
+ add_special_tokens=True,
303
+ return_tensors="pt",
304
+ )
305
+ text_input_ids = text_inputs.input_ids
306
+ prompt_attention_mask = text_inputs.attention_mask
307
+ prompt_attention_mask = prompt_attention_mask.bool().to(device)
308
+
309
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
310
+
311
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
312
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
313
+ logger.warning(
314
+ "The following part of your input was truncated because `max_sequence_length` is set to "
315
+ f" {max_sequence_length} tokens: {removed_text}"
316
+ )
317
+
318
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
319
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
320
+
321
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
322
+ _, seq_len, _ = prompt_embeds.shape
323
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
324
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
325
+
326
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
327
+ prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1)
328
+
329
+ return prompt_embeds, prompt_attention_mask
330
+
331
+ # Copied from diffusers.pipelines.mochi.pipeline_mochi.MochiPipeline.encode_prompt with 256->128
332
+ def encode_prompt(
333
+ self,
334
+ prompt: Union[str, List[str]],
335
+ negative_prompt: Optional[Union[str, List[str]]] = None,
336
+ do_classifier_free_guidance: bool = True,
337
+ num_videos_per_prompt: int = 1,
338
+ prompt_embeds: Optional[torch.Tensor] = None,
339
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
340
+ prompt_attention_mask: Optional[torch.Tensor] = None,
341
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
342
+ max_sequence_length: int = 128,
343
+ device: Optional[torch.device] = None,
344
+ dtype: Optional[torch.dtype] = None,
345
+ ):
346
+ r"""
347
+ Encodes the prompt into text encoder hidden states.
348
+
349
+ Args:
350
+ prompt (`str` or `List[str]`, *optional*):
351
+ prompt to be encoded
352
+ negative_prompt (`str` or `List[str]`, *optional*):
353
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
354
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
355
+ less than `1`).
356
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
357
+ Whether to use classifier free guidance or not.
358
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
359
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
360
+ prompt_embeds (`torch.Tensor`, *optional*):
361
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
362
+ provided, text embeddings will be generated from `prompt` input argument.
363
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
364
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
365
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
366
+ argument.
367
+ device: (`torch.device`, *optional*):
368
+ torch device
369
+ dtype: (`torch.dtype`, *optional*):
370
+ torch dtype
371
+ """
372
+ device = device or self._execution_device
373
+
374
+ prompt = [prompt] if isinstance(prompt, str) else prompt
375
+ if prompt is not None:
376
+ batch_size = len(prompt)
377
+ else:
378
+ batch_size = prompt_embeds.shape[0]
379
+
380
+ if prompt_embeds is None:
381
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
382
+ prompt=prompt,
383
+ num_videos_per_prompt=num_videos_per_prompt,
384
+ max_sequence_length=max_sequence_length,
385
+ device=device,
386
+ dtype=dtype,
387
+ )
388
+
389
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
390
+ negative_prompt = negative_prompt or ""
391
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
392
+
393
+ if prompt is not None and type(prompt) is not type(negative_prompt):
394
+ raise TypeError(
395
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
396
+ f" {type(prompt)}."
397
+ )
398
+ elif batch_size != len(negative_prompt):
399
+ raise ValueError(
400
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
401
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
402
+ " the batch size of `prompt`."
403
+ )
404
+
405
+ negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
406
+ prompt=negative_prompt,
407
+ num_videos_per_prompt=num_videos_per_prompt,
408
+ max_sequence_length=max_sequence_length,
409
+ device=device,
410
+ dtype=dtype,
411
+ )
412
+
413
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
414
+
415
+ # Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline.check_inputs
416
+ def check_inputs(
417
+ self,
418
+ prompt,
419
+ height,
420
+ width,
421
+ callback_on_step_end_tensor_inputs=None,
422
+ prompt_embeds=None,
423
+ negative_prompt_embeds=None,
424
+ prompt_attention_mask=None,
425
+ negative_prompt_attention_mask=None,
426
+ ):
427
+ if height % 32 != 0 or width % 32 != 0:
428
+ raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
429
+
430
+ if callback_on_step_end_tensor_inputs is not None and not all(
431
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
432
+ ):
433
+ raise ValueError(
434
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
435
+ )
436
+
437
+ if prompt is not None and prompt_embeds is not None:
438
+ raise ValueError(
439
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
440
+ " only forward one of the two."
441
+ )
442
+ elif prompt is None and prompt_embeds is None:
443
+ raise ValueError(
444
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
445
+ )
446
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
447
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
448
+
449
+ if prompt_embeds is not None and prompt_attention_mask is None:
450
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
451
+
452
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
453
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
454
+
455
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
456
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
457
+ raise ValueError(
458
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
459
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
460
+ f" {negative_prompt_embeds.shape}."
461
+ )
462
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
463
+ raise ValueError(
464
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
465
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
466
+ f" {negative_prompt_attention_mask.shape}."
467
+ )
468
+
469
+ @staticmethod
470
+ # Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._pack_latents
471
+ def _pack_latents(latents: torch.Tensor, patch_size: int = 1, patch_size_t: int = 1) -> torch.Tensor:
472
+ # Unpacked latents of shape are [B, C, F, H, W] are patched into tokens of shape [B, C, F // p_t, p_t, H // p, p, W // p, p].
473
+ # The patch dimensions are then permuted and collapsed into the channel dimension of shape:
474
+ # [B, F // p_t * H // p * W // p, C * p_t * p * p] (an ndim=3 tensor).
475
+ # dim=0 is the batch size, dim=1 is the effective video sequence length, dim=2 is the effective number of input features
476
+ batch_size, num_channels, num_frames, height, width = latents.shape
477
+ post_patch_num_frames = num_frames // patch_size_t
478
+ post_patch_height = height // patch_size
479
+ post_patch_width = width // patch_size
480
+ latents = latents.reshape(
481
+ batch_size,
482
+ -1,
483
+ post_patch_num_frames,
484
+ patch_size_t,
485
+ post_patch_height,
486
+ patch_size,
487
+ post_patch_width,
488
+ patch_size,
489
+ )
490
+ latents = latents.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7).flatten(1, 3)
491
+ return latents
492
+
493
+ @staticmethod
494
+ # Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._unpack_latents
495
+ def _unpack_latents(
496
+ latents: torch.Tensor, num_frames: int, height: int, width: int, patch_size: int = 1, patch_size_t: int = 1
497
+ ) -> torch.Tensor:
498
+ # Packed latents of shape [B, S, D] (S is the effective video sequence length, D is the effective feature dimensions)
499
+ # are unpacked and reshaped into a video tensor of shape [B, C, F, H, W]. This is the inverse operation of
500
+ # what happens in the `_pack_latents` method.
501
+ batch_size = latents.size(0)
502
+ latents = latents.reshape(batch_size, num_frames, height, width, -1, patch_size_t, patch_size, patch_size)
503
+ latents = latents.permute(0, 4, 1, 5, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(2, 3)
504
+ return latents
505
+
506
+ @staticmethod
507
+ # Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._normalize_latents
508
+ def _normalize_latents(
509
+ latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
510
+ ) -> torch.Tensor:
511
+ # Normalize latents across the channel dimension [B, C, F, H, W]
512
+ latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
513
+ latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
514
+ latents = (latents - latents_mean) * scaling_factor / latents_std
515
+ return latents
516
+
517
+ @staticmethod
518
+ # Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._denormalize_latents
519
+ def _denormalize_latents(
520
+ latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
521
+ ) -> torch.Tensor:
522
+ # Denormalize latents across the channel dimension [B, C, F, H, W]
523
+ latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
524
+ latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
525
+ latents = latents * latents_std / scaling_factor + latents_mean
526
+ return latents
527
+
528
+ def prepare_latents(
529
+ self,
530
+ image: Optional[torch.Tensor] = None,
531
+ batch_size: int = 1,
532
+ num_channels_latents: int = 128,
533
+ height: int = 512,
534
+ width: int = 704,
535
+ num_frames: int = 161,
536
+ dtype: Optional[torch.dtype] = None,
537
+ device: Optional[torch.device] = None,
538
+ generator: Optional[torch.Generator] = None,
539
+ latents: Optional[torch.Tensor] = None,
540
+ ) -> torch.Tensor:
541
+ height = height // self.vae_spatial_compression_ratio
542
+ width = width // self.vae_spatial_compression_ratio
543
+ num_frames = (
544
+ (num_frames - 1) // self.vae_temporal_compression_ratio + 1 if latents is None else latents.size(2)
545
+ )
546
+
547
+ shape = (batch_size, num_channels_latents, num_frames, height, width)
548
+ mask_shape = (batch_size, 1, num_frames, height, width)
549
+
550
+ if latents is not None:
551
+ conditioning_mask = latents.new_zeros(shape)
552
+ conditioning_mask[:, :, 0] = 1.0
553
+ conditioning_mask = self._pack_latents(
554
+ conditioning_mask, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
555
+ )
556
+ return latents.to(device=device, dtype=dtype), conditioning_mask
557
+
558
+ if isinstance(generator, list):
559
+ if len(generator) != batch_size:
560
+ raise ValueError(
561
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
562
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
563
+ )
564
+
565
+ init_latents = [
566
+ retrieve_latents(self.vae.encode(image[i].unsqueeze(0).unsqueeze(2)), generator[i])
567
+ for i in range(batch_size)
568
+ ]
569
+ else:
570
+ init_latents = [
571
+ retrieve_latents(self.vae.encode(img.unsqueeze(0).unsqueeze(2)), generator) for img in image
572
+ ]
573
+
574
+ init_latents = torch.cat(init_latents, dim=0).to(dtype)
575
+ init_latents = self._normalize_latents(init_latents, self.vae.latents_mean, self.vae.latents_std)
576
+ init_latents = init_latents.repeat(1, 1, num_frames, 1, 1)
577
+ conditioning_mask = torch.zeros(mask_shape, device=device, dtype=dtype)
578
+ conditioning_mask[:, :, 0] = 1.0
579
+
580
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
581
+ latents = init_latents * conditioning_mask + noise * (1 - conditioning_mask)
582
+
583
+ conditioning_mask = self._pack_latents(
584
+ conditioning_mask, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
585
+ ).squeeze(-1)
586
+ latents = self._pack_latents(
587
+ latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
588
+ )
589
+
590
+ return latents, conditioning_mask
591
+
592
+ @property
593
+ def guidance_scale(self):
594
+ return self._guidance_scale
595
+
596
+ @property
597
+ def do_classifier_free_guidance(self):
598
+ return self._guidance_scale > 1.0
599
+
600
+ @property
601
+ def do_spatio_temporal_guidance(self):
602
+ return self._stg_scale > 0.0
603
+
604
+ @property
605
+ def num_timesteps(self):
606
+ return self._num_timesteps
607
+
608
+ @property
609
+ def attention_kwargs(self):
610
+ return self._attention_kwargs
611
+
612
+ @property
613
+ def interrupt(self):
614
+ return self._interrupt
615
+
616
+ @torch.no_grad()
617
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
618
+ def __call__(
619
+ self,
620
+ image: PipelineImageInput = None,
621
+ prompt: Union[str, List[str]] = None,
622
+ negative_prompt: Optional[Union[str, List[str]]] = None,
623
+ height: int = 512,
624
+ width: int = 704,
625
+ num_frames: int = 161,
626
+ frame_rate: int = 25,
627
+ num_inference_steps: int = 50,
628
+ timesteps: List[int] = None,
629
+ guidance_scale: float = 3,
630
+ num_videos_per_prompt: Optional[int] = 1,
631
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
632
+ latents: Optional[torch.Tensor] = None,
633
+ prompt_embeds: Optional[torch.Tensor] = None,
634
+ prompt_attention_mask: Optional[torch.Tensor] = None,
635
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
636
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
637
+ decode_timestep: Union[float, List[float]] = 0.0,
638
+ decode_noise_scale: Optional[Union[float, List[float]]] = None,
639
+ output_type: Optional[str] = "pil",
640
+ return_dict: bool = True,
641
+ attention_kwargs: Optional[Dict[str, Any]] = None,
642
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
643
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
644
+ max_sequence_length: int = 128,
645
+ stg_applied_layers_idx: Optional[List[int]] = [19],
646
+ stg_scale: Optional[float] = 1.0,
647
+ do_rescaling: Optional[bool] = False,
648
+ ):
649
+ r"""
650
+ Function invoked when calling the pipeline for generation.
651
+
652
+ Args:
653
+ image (`PipelineImageInput`):
654
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
655
+ prompt (`str` or `List[str]`, *optional*):
656
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
657
+ instead.
658
+ height (`int`, defaults to `512`):
659
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
660
+ width (`int`, defaults to `704`):
661
+ The width in pixels of the generated image. This is set to 848 by default for the best results.
662
+ num_frames (`int`, defaults to `161`):
663
+ The number of video frames to generate
664
+ num_inference_steps (`int`, *optional*, defaults to 50):
665
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
666
+ expense of slower inference.
667
+ timesteps (`List[int]`, *optional*):
668
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
669
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
670
+ passed will be used. Must be in descending order.
671
+ guidance_scale (`float`, defaults to `3 `):
672
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
673
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
674
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
675
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
676
+ usually at the expense of lower image quality.
677
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
678
+ The number of videos to generate per prompt.
679
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
680
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
681
+ to make generation deterministic.
682
+ latents (`torch.Tensor`, *optional*):
683
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
684
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
685
+ tensor will ge generated by sampling using the supplied random `generator`.
686
+ prompt_embeds (`torch.Tensor`, *optional*):
687
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
688
+ provided, text embeddings will be generated from `prompt` input argument.
689
+ prompt_attention_mask (`torch.Tensor`, *optional*):
690
+ Pre-generated attention mask for text embeddings.
691
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
692
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
693
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
694
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
695
+ Pre-generated attention mask for negative text embeddings.
696
+ decode_timestep (`float`, defaults to `0.0`):
697
+ The timestep at which generated video is decoded.
698
+ decode_noise_scale (`float`, defaults to `None`):
699
+ The interpolation factor between random noise and denoised latents at the decode timestep.
700
+ output_type (`str`, *optional*, defaults to `"pil"`):
701
+ The output format of the generate image. Choose between
702
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
703
+ return_dict (`bool`, *optional*, defaults to `True`):
704
+ Whether or not to return a [`~pipelines.ltx.LTXPipelineOutput`] instead of a plain tuple.
705
+ attention_kwargs (`dict`, *optional*):
706
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
707
+ `self.processor` in
708
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
709
+ callback_on_step_end (`Callable`, *optional*):
710
+ A function that calls at the end of each denoising steps during the inference. The function is called
711
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
712
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
713
+ `callback_on_step_end_tensor_inputs`.
714
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
715
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
716
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
717
+ `._callback_tensor_inputs` attribute of your pipeline class.
718
+ max_sequence_length (`int` defaults to `128 `):
719
+ Maximum sequence length to use with the `prompt`.
720
+
721
+ Examples:
722
+
723
+ Returns:
724
+ [`~pipelines.ltx.LTXPipelineOutput`] or `tuple`:
725
+ If `return_dict` is `True`, [`~pipelines.ltx.LTXPipelineOutput`] is returned, otherwise a `tuple` is
726
+ returned where the first element is a list with the generated images.
727
+ """
728
+
729
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
730
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
731
+
732
+ # 1. Check inputs. Raise error if not correct
733
+ self.check_inputs(
734
+ prompt=prompt,
735
+ height=height,
736
+ width=width,
737
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
738
+ prompt_embeds=prompt_embeds,
739
+ negative_prompt_embeds=negative_prompt_embeds,
740
+ prompt_attention_mask=prompt_attention_mask,
741
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
742
+ )
743
+
744
+ self._stg_scale = stg_scale
745
+ self._guidance_scale = guidance_scale
746
+ self._attention_kwargs = attention_kwargs
747
+ self._interrupt = False
748
+
749
+ if self.do_spatio_temporal_guidance:
750
+ for i in stg_applied_layers_idx:
751
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
752
+ forward_with_stg, self.transformer.transformer_blocks[i]
753
+ )
754
+
755
+ # 2. Define call parameters
756
+ if prompt is not None and isinstance(prompt, str):
757
+ batch_size = 1
758
+ elif prompt is not None and isinstance(prompt, list):
759
+ batch_size = len(prompt)
760
+ else:
761
+ batch_size = prompt_embeds.shape[0]
762
+
763
+ device = self._execution_device
764
+
765
+ # 3. Prepare text embeddings
766
+ (
767
+ prompt_embeds,
768
+ prompt_attention_mask,
769
+ negative_prompt_embeds,
770
+ negative_prompt_attention_mask,
771
+ ) = self.encode_prompt(
772
+ prompt=prompt,
773
+ negative_prompt=negative_prompt,
774
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
775
+ num_videos_per_prompt=num_videos_per_prompt,
776
+ prompt_embeds=prompt_embeds,
777
+ negative_prompt_embeds=negative_prompt_embeds,
778
+ prompt_attention_mask=prompt_attention_mask,
779
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
780
+ max_sequence_length=max_sequence_length,
781
+ device=device,
782
+ )
783
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
784
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
785
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
786
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
787
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0)
788
+ prompt_attention_mask = torch.cat(
789
+ [negative_prompt_attention_mask, prompt_attention_mask, prompt_attention_mask], dim=0
790
+ )
791
+
792
+ # 4. Prepare latent variables
793
+ if latents is None:
794
+ image = self.video_processor.preprocess(image, height=height, width=width)
795
+ image = image.to(device=device, dtype=prompt_embeds.dtype)
796
+
797
+ num_channels_latents = self.transformer.config.in_channels
798
+ latents, conditioning_mask = self.prepare_latents(
799
+ image,
800
+ batch_size * num_videos_per_prompt,
801
+ num_channels_latents,
802
+ height,
803
+ width,
804
+ num_frames,
805
+ torch.float32,
806
+ device,
807
+ generator,
808
+ latents,
809
+ )
810
+
811
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
812
+ conditioning_mask = torch.cat([conditioning_mask, conditioning_mask])
813
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
814
+ conditioning_mask = torch.cat([conditioning_mask, conditioning_mask, conditioning_mask])
815
+
816
+ # 5. Prepare timesteps
817
+ latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
818
+ latent_height = height // self.vae_spatial_compression_ratio
819
+ latent_width = width // self.vae_spatial_compression_ratio
820
+ video_sequence_length = latent_num_frames * latent_height * latent_width
821
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
822
+ mu = calculate_shift(
823
+ video_sequence_length,
824
+ self.scheduler.config.get("base_image_seq_len", 256),
825
+ self.scheduler.config.get("max_image_seq_len", 4096),
826
+ self.scheduler.config.get("base_shift", 0.5),
827
+ self.scheduler.config.get("max_shift", 1.16),
828
+ )
829
+ timesteps, num_inference_steps = retrieve_timesteps(
830
+ self.scheduler,
831
+ num_inference_steps,
832
+ device,
833
+ timesteps,
834
+ sigmas=sigmas,
835
+ mu=mu,
836
+ )
837
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
838
+ self._num_timesteps = len(timesteps)
839
+
840
+ # 6. Prepare micro-conditions
841
+ latent_frame_rate = frame_rate / self.vae_temporal_compression_ratio
842
+ rope_interpolation_scale = (
843
+ 1 / latent_frame_rate,
844
+ self.vae_spatial_compression_ratio,
845
+ self.vae_spatial_compression_ratio,
846
+ )
847
+
848
+ # 7. Denoising loop
849
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
850
+ for i, t in enumerate(timesteps):
851
+ if self.interrupt:
852
+ continue
853
+
854
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
855
+ latent_model_input = torch.cat([latents] * 2)
856
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
857
+ latent_model_input = torch.cat([latents] * 3)
858
+ else:
859
+ latent_model_input = latents
860
+
861
+ latent_model_input = latent_model_input.to(prompt_embeds.dtype)
862
+
863
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
864
+ timestep = t.expand(latent_model_input.shape[0])
865
+ timestep = timestep.unsqueeze(-1) * (1 - conditioning_mask)
866
+
867
+ noise_pred = self.transformer(
868
+ hidden_states=latent_model_input,
869
+ encoder_hidden_states=prompt_embeds,
870
+ timestep=timestep,
871
+ encoder_attention_mask=prompt_attention_mask,
872
+ num_frames=latent_num_frames,
873
+ height=latent_height,
874
+ width=latent_width,
875
+ rope_interpolation_scale=rope_interpolation_scale,
876
+ attention_kwargs=attention_kwargs,
877
+ return_dict=False,
878
+ )[0]
879
+ noise_pred = noise_pred.float()
880
+
881
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
882
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
883
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
884
+ timestep, _ = timestep.chunk(2)
885
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
886
+ noise_pred_uncond, noise_pred_text, noise_pred_perturb = noise_pred.chunk(3)
887
+ noise_pred = (
888
+ noise_pred_uncond
889
+ + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
890
+ + self._stg_scale * (noise_pred_text - noise_pred_perturb)
891
+ )
892
+ timestep, _, _ = timestep.chunk(3)
893
+
894
+ if do_rescaling:
895
+ rescaling_scale = 0.7
896
+ factor = noise_pred_text.std() / noise_pred.std()
897
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
898
+ noise_pred = noise_pred * factor
899
+
900
+ # compute the previous noisy sample x_t -> x_t-1
901
+ noise_pred = self._unpack_latents(
902
+ noise_pred,
903
+ latent_num_frames,
904
+ latent_height,
905
+ latent_width,
906
+ self.transformer_spatial_patch_size,
907
+ self.transformer_temporal_patch_size,
908
+ )
909
+ latents = self._unpack_latents(
910
+ latents,
911
+ latent_num_frames,
912
+ latent_height,
913
+ latent_width,
914
+ self.transformer_spatial_patch_size,
915
+ self.transformer_temporal_patch_size,
916
+ )
917
+
918
+ noise_pred = noise_pred[:, :, 1:]
919
+ noise_latents = latents[:, :, 1:]
920
+ pred_latents = self.scheduler.step(noise_pred, t, noise_latents, return_dict=False)[0]
921
+
922
+ latents = torch.cat([latents[:, :, :1], pred_latents], dim=2)
923
+ latents = self._pack_latents(
924
+ latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
925
+ )
926
+
927
+ if callback_on_step_end is not None:
928
+ callback_kwargs = {}
929
+ for k in callback_on_step_end_tensor_inputs:
930
+ callback_kwargs[k] = locals()[k]
931
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
932
+
933
+ latents = callback_outputs.pop("latents", latents)
934
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
935
+
936
+ # call the callback, if provided
937
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
938
+ progress_bar.update()
939
+
940
+ if XLA_AVAILABLE:
941
+ xm.mark_step()
942
+
943
+ if output_type == "latent":
944
+ video = latents
945
+ else:
946
+ latents = self._unpack_latents(
947
+ latents,
948
+ latent_num_frames,
949
+ latent_height,
950
+ latent_width,
951
+ self.transformer_spatial_patch_size,
952
+ self.transformer_temporal_patch_size,
953
+ )
954
+ latents = self._denormalize_latents(
955
+ latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor
956
+ )
957
+ latents = latents.to(prompt_embeds.dtype)
958
+
959
+ if not self.vae.config.timestep_conditioning:
960
+ timestep = None
961
+ else:
962
+ noise = torch.randn(latents.shape, generator=generator, device=device, dtype=latents.dtype)
963
+ if not isinstance(decode_timestep, list):
964
+ decode_timestep = [decode_timestep] * batch_size
965
+ if decode_noise_scale is None:
966
+ decode_noise_scale = decode_timestep
967
+ elif not isinstance(decode_noise_scale, list):
968
+ decode_noise_scale = [decode_noise_scale] * batch_size
969
+
970
+ timestep = torch.tensor(decode_timestep, device=device, dtype=latents.dtype)
971
+ decode_noise_scale = torch.tensor(decode_noise_scale, device=device, dtype=latents.dtype)[
972
+ :, None, None, None, None
973
+ ]
974
+ latents = (1 - decode_noise_scale) * latents + decode_noise_scale * noise
975
+
976
+ video = self.vae.decode(latents, timestep, return_dict=False)[0]
977
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
978
+
979
+ # Offload all models
980
+ self.maybe_free_model_hooks()
981
+
982
+ if not return_dict:
983
+ return (video,)
984
+
985
+ return LTXPipelineOutput(frames=video)
main/pipeline_stg_mochi.py ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Genmo and The HuggingFace Team. All rights reserved.
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
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import types
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import T5EncoderModel, T5TokenizerFast
22
+
23
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
24
+ from diffusers.loaders import Mochi1LoraLoaderMixin
25
+ from diffusers.models import AutoencoderKLMochi, MochiTransformer3DModel
26
+ from diffusers.pipelines.mochi.pipeline_output import MochiPipelineOutput
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
29
+ from diffusers.utils import (
30
+ is_torch_xla_available,
31
+ logging,
32
+ replace_example_docstring,
33
+ )
34
+ from diffusers.utils.torch_utils import randn_tensor
35
+ from diffusers.video_processor import VideoProcessor
36
+
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
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```py
51
+ >>> import torch
52
+ >>> from diffusers.utils import export_to_video
53
+ >>> from examples.community.pipeline_stg_mochi import MochiSTGPipeline
54
+
55
+ >>> pipe = MochiSTGPipeline.from_pretrained("genmo/mochi-1-preview", torch_dtype=torch.bfloat16)
56
+ >>> pipe.enable_model_cpu_offload()
57
+ >>> pipe.enable_vae_tiling()
58
+ >>> prompt = "A close-up of a beautiful woman's face with colored powder exploding around her, creating an abstract splash of vibrant hues, realistic style."
59
+
60
+ >>> # Configure STG mode options
61
+ >>> stg_applied_layers_idx = [34] # Layer indices from 0 to 41
62
+ >>> stg_scale = 1.0 # Set 0.0 for CFG
63
+ >>> do_rescaling = False
64
+
65
+ >>> frames = pipe(
66
+ ... prompt=prompt,
67
+ ... num_inference_steps=28,
68
+ ... guidance_scale=3.5,
69
+ ... stg_applied_layers_idx=stg_applied_layers_idx,
70
+ ... stg_scale=stg_scale,
71
+ ... do_rescaling=do_rescaling).frames[0]
72
+ >>> export_to_video(frames, "mochi.mp4")
73
+ ```
74
+ """
75
+
76
+
77
+ def forward_with_stg(
78
+ self,
79
+ hidden_states: torch.Tensor,
80
+ encoder_hidden_states: torch.Tensor,
81
+ temb: torch.Tensor,
82
+ encoder_attention_mask: torch.Tensor,
83
+ image_rotary_emb: Optional[torch.Tensor] = None,
84
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
85
+ hidden_states_ptb = hidden_states[2:]
86
+ encoder_hidden_states_ptb = encoder_hidden_states[2:]
87
+ norm_hidden_states, gate_msa, scale_mlp, gate_mlp = self.norm1(hidden_states, temb)
88
+
89
+ if not self.context_pre_only:
90
+ norm_encoder_hidden_states, enc_gate_msa, enc_scale_mlp, enc_gate_mlp = self.norm1_context(
91
+ encoder_hidden_states, temb
92
+ )
93
+ else:
94
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states, temb)
95
+
96
+ attn_hidden_states, context_attn_hidden_states = self.attn1(
97
+ hidden_states=norm_hidden_states,
98
+ encoder_hidden_states=norm_encoder_hidden_states,
99
+ image_rotary_emb=image_rotary_emb,
100
+ attention_mask=encoder_attention_mask,
101
+ )
102
+
103
+ hidden_states = hidden_states + self.norm2(attn_hidden_states, torch.tanh(gate_msa).unsqueeze(1))
104
+ norm_hidden_states = self.norm3(hidden_states, (1 + scale_mlp.unsqueeze(1).to(torch.float32)))
105
+ ff_output = self.ff(norm_hidden_states)
106
+ hidden_states = hidden_states + self.norm4(ff_output, torch.tanh(gate_mlp).unsqueeze(1))
107
+
108
+ if not self.context_pre_only:
109
+ encoder_hidden_states = encoder_hidden_states + self.norm2_context(
110
+ context_attn_hidden_states, torch.tanh(enc_gate_msa).unsqueeze(1)
111
+ )
112
+ norm_encoder_hidden_states = self.norm3_context(
113
+ encoder_hidden_states, (1 + enc_scale_mlp.unsqueeze(1).to(torch.float32))
114
+ )
115
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
116
+ encoder_hidden_states = encoder_hidden_states + self.norm4_context(
117
+ context_ff_output, torch.tanh(enc_gate_mlp).unsqueeze(1)
118
+ )
119
+
120
+ hidden_states[2:] = hidden_states_ptb
121
+ encoder_hidden_states[2:] = encoder_hidden_states_ptb
122
+
123
+ return hidden_states, encoder_hidden_states
124
+
125
+
126
+ # from: https://github.com/genmoai/models/blob/075b6e36db58f1242921deff83a1066887b9c9e1/src/mochi_preview/infer.py#L77
127
+ def linear_quadratic_schedule(num_steps, threshold_noise, linear_steps=None):
128
+ if linear_steps is None:
129
+ linear_steps = num_steps // 2
130
+ linear_sigma_schedule = [i * threshold_noise / linear_steps for i in range(linear_steps)]
131
+ threshold_noise_step_diff = linear_steps - threshold_noise * num_steps
132
+ quadratic_steps = num_steps - linear_steps
133
+ quadratic_coef = threshold_noise_step_diff / (linear_steps * quadratic_steps**2)
134
+ linear_coef = threshold_noise / linear_steps - 2 * threshold_noise_step_diff / (quadratic_steps**2)
135
+ const = quadratic_coef * (linear_steps**2)
136
+ quadratic_sigma_schedule = [
137
+ quadratic_coef * (i**2) + linear_coef * i + const for i in range(linear_steps, num_steps)
138
+ ]
139
+ sigma_schedule = linear_sigma_schedule + quadratic_sigma_schedule
140
+ sigma_schedule = [1.0 - x for x in sigma_schedule]
141
+ return sigma_schedule
142
+
143
+
144
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
145
+ def retrieve_timesteps(
146
+ scheduler,
147
+ num_inference_steps: Optional[int] = None,
148
+ device: Optional[Union[str, torch.device]] = None,
149
+ timesteps: Optional[List[int]] = None,
150
+ sigmas: Optional[List[float]] = None,
151
+ **kwargs,
152
+ ):
153
+ r"""
154
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
155
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
156
+
157
+ Args:
158
+ scheduler (`SchedulerMixin`):
159
+ The scheduler to get timesteps from.
160
+ num_inference_steps (`int`):
161
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
162
+ must be `None`.
163
+ device (`str` or `torch.device`, *optional*):
164
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
165
+ timesteps (`List[int]`, *optional*):
166
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
167
+ `num_inference_steps` and `sigmas` must be `None`.
168
+ sigmas (`List[float]`, *optional*):
169
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
170
+ `num_inference_steps` and `timesteps` must be `None`.
171
+
172
+ Returns:
173
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
174
+ second element is the number of inference steps.
175
+ """
176
+ if timesteps is not None and sigmas is not None:
177
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom value")
178
+ if timesteps is not None:
179
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
180
+ if not accepts_timesteps:
181
+ raise ValueError(
182
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
183
+ f" timestep schedules. Please check whether you are using the correct scheduler."
184
+ )
185
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
186
+ timesteps = scheduler.timesteps
187
+ num_inference_steps = len(timesteps)
188
+ elif sigmas is not None:
189
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
190
+ if not accept_sigmas:
191
+ raise ValueError(
192
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
193
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
194
+ )
195
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
196
+ timesteps = scheduler.timesteps
197
+ num_inference_steps = len(timesteps)
198
+ else:
199
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
200
+ timesteps = scheduler.timesteps
201
+ return timesteps, num_inference_steps
202
+
203
+
204
+ class MochiSTGPipeline(DiffusionPipeline, Mochi1LoraLoaderMixin):
205
+ r"""
206
+ The mochi pipeline for text-to-video generation.
207
+
208
+ Reference: https://github.com/genmoai/models
209
+
210
+ Args:
211
+ transformer ([`MochiTransformer3DModel`]):
212
+ Conditional Transformer architecture to denoise the encoded video latents.
213
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
214
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
215
+ vae ([`AutoencoderKLMochi`]):
216
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
217
+ text_encoder ([`T5EncoderModel`]):
218
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
219
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
220
+ tokenizer (`CLIPTokenizer`):
221
+ Tokenizer of class
222
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
223
+ tokenizer (`T5TokenizerFast`):
224
+ Second Tokenizer of class
225
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
226
+ """
227
+
228
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
229
+ _optional_components = []
230
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
231
+
232
+ def __init__(
233
+ self,
234
+ scheduler: FlowMatchEulerDiscreteScheduler,
235
+ vae: AutoencoderKLMochi,
236
+ text_encoder: T5EncoderModel,
237
+ tokenizer: T5TokenizerFast,
238
+ transformer: MochiTransformer3DModel,
239
+ force_zeros_for_empty_prompt: bool = False,
240
+ ):
241
+ super().__init__()
242
+
243
+ self.register_modules(
244
+ vae=vae,
245
+ text_encoder=text_encoder,
246
+ tokenizer=tokenizer,
247
+ transformer=transformer,
248
+ scheduler=scheduler,
249
+ )
250
+ # TODO: determine these scaling factors from model parameters
251
+ self.vae_spatial_scale_factor = 8
252
+ self.vae_temporal_scale_factor = 6
253
+ self.patch_size = 2
254
+
255
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_scale_factor)
256
+ self.tokenizer_max_length = (
257
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 256
258
+ )
259
+ self.default_height = 480
260
+ self.default_width = 848
261
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
262
+
263
+ def _get_t5_prompt_embeds(
264
+ self,
265
+ prompt: Union[str, List[str]] = None,
266
+ num_videos_per_prompt: int = 1,
267
+ max_sequence_length: int = 256,
268
+ device: Optional[torch.device] = None,
269
+ dtype: Optional[torch.dtype] = None,
270
+ ):
271
+ device = device or self._execution_device
272
+ dtype = dtype or self.text_encoder.dtype
273
+
274
+ prompt = [prompt] if isinstance(prompt, str) else prompt
275
+ batch_size = len(prompt)
276
+
277
+ text_inputs = self.tokenizer(
278
+ prompt,
279
+ padding="max_length",
280
+ max_length=max_sequence_length,
281
+ truncation=True,
282
+ add_special_tokens=True,
283
+ return_tensors="pt",
284
+ )
285
+
286
+ text_input_ids = text_inputs.input_ids
287
+ prompt_attention_mask = text_inputs.attention_mask
288
+ prompt_attention_mask = prompt_attention_mask.bool().to(device)
289
+
290
+ # The original Mochi implementation zeros out empty negative prompts
291
+ # but this can lead to overflow when placing the entire pipeline under the autocast context
292
+ # adding this here so that we can enable zeroing prompts if necessary
293
+ if self.config.force_zeros_for_empty_prompt and (prompt == "" or prompt[-1] == ""):
294
+ text_input_ids = torch.zeros_like(text_input_ids, device=device)
295
+ prompt_attention_mask = torch.zeros_like(prompt_attention_mask, dtype=torch.bool, device=device)
296
+
297
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
298
+
299
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
300
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
301
+ logger.warning(
302
+ "The following part of your input was truncated because `max_sequence_length` is set to "
303
+ f" {max_sequence_length} tokens: {removed_text}"
304
+ )
305
+
306
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)[0]
307
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
308
+
309
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
310
+ _, seq_len, _ = prompt_embeds.shape
311
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
312
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
313
+
314
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
315
+ prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1)
316
+
317
+ return prompt_embeds, prompt_attention_mask
318
+
319
+ # Adapted from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt
320
+ def encode_prompt(
321
+ self,
322
+ prompt: Union[str, List[str]],
323
+ negative_prompt: Optional[Union[str, List[str]]] = None,
324
+ do_classifier_free_guidance: bool = True,
325
+ num_videos_per_prompt: int = 1,
326
+ prompt_embeds: Optional[torch.Tensor] = None,
327
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
328
+ prompt_attention_mask: Optional[torch.Tensor] = None,
329
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
330
+ max_sequence_length: int = 256,
331
+ device: Optional[torch.device] = None,
332
+ dtype: Optional[torch.dtype] = None,
333
+ ):
334
+ r"""
335
+ Encodes the prompt into text encoder hidden states.
336
+
337
+ Args:
338
+ prompt (`str` or `List[str]`, *optional*):
339
+ prompt to be encoded
340
+ negative_prompt (`str` or `List[str]`, *optional*):
341
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
342
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
343
+ less than `1`).
344
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
345
+ Whether to use classifier free guidance or not.
346
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
347
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
348
+ prompt_embeds (`torch.Tensor`, *optional*):
349
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
350
+ provided, text embeddings will be generated from `prompt` input argument.
351
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
352
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
353
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
354
+ argument.
355
+ device: (`torch.device`, *optional*):
356
+ torch device
357
+ dtype: (`torch.dtype`, *optional*):
358
+ torch dtype
359
+ """
360
+ device = device or self._execution_device
361
+
362
+ prompt = [prompt] if isinstance(prompt, str) else prompt
363
+ if prompt is not None:
364
+ batch_size = len(prompt)
365
+ else:
366
+ batch_size = prompt_embeds.shape[0]
367
+
368
+ if prompt_embeds is None:
369
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
370
+ prompt=prompt,
371
+ num_videos_per_prompt=num_videos_per_prompt,
372
+ max_sequence_length=max_sequence_length,
373
+ device=device,
374
+ dtype=dtype,
375
+ )
376
+
377
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
378
+ negative_prompt = negative_prompt or ""
379
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
380
+
381
+ if prompt is not None and type(prompt) is not type(negative_prompt):
382
+ raise TypeError(
383
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
384
+ f" {type(prompt)}."
385
+ )
386
+ elif batch_size != len(negative_prompt):
387
+ raise ValueError(
388
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
389
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
390
+ " the batch size of `prompt`."
391
+ )
392
+
393
+ negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
394
+ prompt=negative_prompt,
395
+ num_videos_per_prompt=num_videos_per_prompt,
396
+ max_sequence_length=max_sequence_length,
397
+ device=device,
398
+ dtype=dtype,
399
+ )
400
+
401
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
402
+
403
+ def check_inputs(
404
+ self,
405
+ prompt,
406
+ height,
407
+ width,
408
+ callback_on_step_end_tensor_inputs=None,
409
+ prompt_embeds=None,
410
+ negative_prompt_embeds=None,
411
+ prompt_attention_mask=None,
412
+ negative_prompt_attention_mask=None,
413
+ ):
414
+ if height % 8 != 0 or width % 8 != 0:
415
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
416
+
417
+ if callback_on_step_end_tensor_inputs is not None and not all(
418
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
419
+ ):
420
+ raise ValueError(
421
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
422
+ )
423
+
424
+ if prompt is not None and prompt_embeds is not None:
425
+ raise ValueError(
426
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
427
+ " only forward one of the two."
428
+ )
429
+ elif prompt is None and prompt_embeds is None:
430
+ raise ValueError(
431
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
432
+ )
433
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
434
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
435
+
436
+ if prompt_embeds is not None and prompt_attention_mask is None:
437
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
438
+
439
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
440
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
441
+
442
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
443
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
444
+ raise ValueError(
445
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
446
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
447
+ f" {negative_prompt_embeds.shape}."
448
+ )
449
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
450
+ raise ValueError(
451
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
452
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
453
+ f" {negative_prompt_attention_mask.shape}."
454
+ )
455
+
456
+ def enable_vae_slicing(self):
457
+ r"""
458
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
459
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
460
+ """
461
+ self.vae.enable_slicing()
462
+
463
+ def disable_vae_slicing(self):
464
+ r"""
465
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
466
+ computing decoding in one step.
467
+ """
468
+ self.vae.disable_slicing()
469
+
470
+ def enable_vae_tiling(self):
471
+ r"""
472
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
473
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
474
+ processing larger images.
475
+ """
476
+ self.vae.enable_tiling()
477
+
478
+ def disable_vae_tiling(self):
479
+ r"""
480
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
481
+ computing decoding in one step.
482
+ """
483
+ self.vae.disable_tiling()
484
+
485
+ def prepare_latents(
486
+ self,
487
+ batch_size,
488
+ num_channels_latents,
489
+ height,
490
+ width,
491
+ num_frames,
492
+ dtype,
493
+ device,
494
+ generator,
495
+ latents=None,
496
+ ):
497
+ height = height // self.vae_spatial_scale_factor
498
+ width = width // self.vae_spatial_scale_factor
499
+ num_frames = (num_frames - 1) // self.vae_temporal_scale_factor + 1
500
+
501
+ shape = (batch_size, num_channels_latents, num_frames, height, width)
502
+
503
+ if latents is not None:
504
+ return latents.to(device=device, dtype=dtype)
505
+ if isinstance(generator, list) and len(generator) != batch_size:
506
+ raise ValueError(
507
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
508
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
509
+ )
510
+
511
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
512
+ latents = latents.to(dtype)
513
+ return latents
514
+
515
+ @property
516
+ def guidance_scale(self):
517
+ return self._guidance_scale
518
+
519
+ @property
520
+ def do_classifier_free_guidance(self):
521
+ return self._guidance_scale > 1.0
522
+
523
+ @property
524
+ def do_spatio_temporal_guidance(self):
525
+ return self._stg_scale > 0.0
526
+
527
+ @property
528
+ def num_timesteps(self):
529
+ return self._num_timesteps
530
+
531
+ @property
532
+ def attention_kwargs(self):
533
+ return self._attention_kwargs
534
+
535
+ @property
536
+ def current_timestep(self):
537
+ return self._current_timestep
538
+
539
+ @property
540
+ def interrupt(self):
541
+ return self._interrupt
542
+
543
+ @torch.no_grad()
544
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
545
+ def __call__(
546
+ self,
547
+ prompt: Union[str, List[str]] = None,
548
+ negative_prompt: Optional[Union[str, List[str]]] = None,
549
+ height: Optional[int] = None,
550
+ width: Optional[int] = None,
551
+ num_frames: int = 19,
552
+ num_inference_steps: int = 64,
553
+ timesteps: List[int] = None,
554
+ guidance_scale: float = 4.5,
555
+ num_videos_per_prompt: Optional[int] = 1,
556
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
557
+ latents: Optional[torch.Tensor] = None,
558
+ prompt_embeds: Optional[torch.Tensor] = None,
559
+ prompt_attention_mask: Optional[torch.Tensor] = None,
560
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
561
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
562
+ output_type: Optional[str] = "pil",
563
+ return_dict: bool = True,
564
+ attention_kwargs: Optional[Dict[str, Any]] = None,
565
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
566
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
567
+ max_sequence_length: int = 256,
568
+ stg_applied_layers_idx: Optional[List[int]] = [34],
569
+ stg_scale: Optional[float] = 0.0,
570
+ do_rescaling: Optional[bool] = False,
571
+ ):
572
+ r"""
573
+ Function invoked when calling the pipeline for generation.
574
+
575
+ Args:
576
+ prompt (`str` or `List[str]`, *optional*):
577
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
578
+ instead.
579
+ height (`int`, *optional*, defaults to `self.default_height`):
580
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
581
+ width (`int`, *optional*, defaults to `self.default_width`):
582
+ The width in pixels of the generated image. This is set to 848 by default for the best results.
583
+ num_frames (`int`, defaults to `19`):
584
+ The number of video frames to generate
585
+ num_inference_steps (`int`, *optional*, defaults to 50):
586
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
587
+ expense of slower inference.
588
+ timesteps (`List[int]`, *optional*):
589
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
590
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
591
+ passed will be used. Must be in descending order.
592
+ guidance_scale (`float`, defaults to `4.5`):
593
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
594
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
595
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
596
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
597
+ usually at the expense of lower image quality.
598
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
599
+ The number of videos to generate per prompt.
600
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
601
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
602
+ to make generation deterministic.
603
+ latents (`torch.Tensor`, *optional*):
604
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
605
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
606
+ tensor will ge generated by sampling using the supplied random `generator`.
607
+ prompt_embeds (`torch.Tensor`, *optional*):
608
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
609
+ provided, text embeddings will be generated from `prompt` input argument.
610
+ prompt_attention_mask (`torch.Tensor`, *optional*):
611
+ Pre-generated attention mask for text embeddings.
612
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
613
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
614
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
615
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
616
+ Pre-generated attention mask for negative text embeddings.
617
+ output_type (`str`, *optional*, defaults to `"pil"`):
618
+ The output format of the generate image. Choose between
619
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
620
+ return_dict (`bool`, *optional*, defaults to `True`):
621
+ Whether or not to return a [`~pipelines.mochi.MochiPipelineOutput`] instead of a plain tuple.
622
+ attention_kwargs (`dict`, *optional*):
623
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
624
+ `self.processor` in
625
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
626
+ callback_on_step_end (`Callable`, *optional*):
627
+ A function that calls at the end of each denoising steps during the inference. The function is called
628
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
629
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
630
+ `callback_on_step_end_tensor_inputs`.
631
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
632
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
633
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
634
+ `._callback_tensor_inputs` attribute of your pipeline class.
635
+ max_sequence_length (`int` defaults to `256`):
636
+ Maximum sequence length to use with the `prompt`.
637
+
638
+ Examples:
639
+
640
+ Returns:
641
+ [`~pipelines.mochi.MochiPipelineOutput`] or `tuple`:
642
+ If `return_dict` is `True`, [`~pipelines.mochi.MochiPipelineOutput`] is returned, otherwise a `tuple`
643
+ is returned where the first element is a list with the generated images.
644
+ """
645
+
646
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
647
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
648
+
649
+ height = height or self.default_height
650
+ width = width or self.default_width
651
+
652
+ # 1. Check inputs. Raise error if not correct
653
+ self.check_inputs(
654
+ prompt=prompt,
655
+ height=height,
656
+ width=width,
657
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
658
+ prompt_embeds=prompt_embeds,
659
+ negative_prompt_embeds=negative_prompt_embeds,
660
+ prompt_attention_mask=prompt_attention_mask,
661
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
662
+ )
663
+
664
+ self._guidance_scale = guidance_scale
665
+ self._stg_scale = stg_scale
666
+ self._attention_kwargs = attention_kwargs
667
+ self._current_timestep = None
668
+ self._interrupt = False
669
+
670
+ if self.do_spatio_temporal_guidance:
671
+ for i in stg_applied_layers_idx:
672
+ self.transformer.transformer_blocks[i].forward = types.MethodType(
673
+ forward_with_stg, self.transformer.transformer_blocks[i]
674
+ )
675
+
676
+ # 2. Define call parameters
677
+ if prompt is not None and isinstance(prompt, str):
678
+ batch_size = 1
679
+ elif prompt is not None and isinstance(prompt, list):
680
+ batch_size = len(prompt)
681
+ else:
682
+ batch_size = prompt_embeds.shape[0]
683
+
684
+ device = self._execution_device
685
+ # 3. Prepare text embeddings
686
+ (
687
+ prompt_embeds,
688
+ prompt_attention_mask,
689
+ negative_prompt_embeds,
690
+ negative_prompt_attention_mask,
691
+ ) = self.encode_prompt(
692
+ prompt=prompt,
693
+ negative_prompt=negative_prompt,
694
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
695
+ num_videos_per_prompt=num_videos_per_prompt,
696
+ prompt_embeds=prompt_embeds,
697
+ negative_prompt_embeds=negative_prompt_embeds,
698
+ prompt_attention_mask=prompt_attention_mask,
699
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
700
+ max_sequence_length=max_sequence_length,
701
+ device=device,
702
+ )
703
+ # 4. Prepare latent variables
704
+ num_channels_latents = self.transformer.config.in_channels
705
+ latents = self.prepare_latents(
706
+ batch_size * num_videos_per_prompt,
707
+ num_channels_latents,
708
+ height,
709
+ width,
710
+ num_frames,
711
+ prompt_embeds.dtype,
712
+ device,
713
+ generator,
714
+ latents,
715
+ )
716
+
717
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
718
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
719
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
720
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
721
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0)
722
+ prompt_attention_mask = torch.cat(
723
+ [negative_prompt_attention_mask, prompt_attention_mask, prompt_attention_mask], dim=0
724
+ )
725
+
726
+ # 5. Prepare timestep
727
+ # from https://github.com/genmoai/models/blob/075b6e36db58f1242921deff83a1066887b9c9e1/src/mochi_preview/infer.py#L77
728
+ threshold_noise = 0.025
729
+ sigmas = linear_quadratic_schedule(num_inference_steps, threshold_noise)
730
+ sigmas = np.array(sigmas)
731
+
732
+ timesteps, num_inference_steps = retrieve_timesteps(
733
+ self.scheduler,
734
+ num_inference_steps,
735
+ device,
736
+ timesteps,
737
+ sigmas,
738
+ )
739
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
740
+ self._num_timesteps = len(timesteps)
741
+
742
+ # 6. Denoising loop
743
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
744
+ for i, t in enumerate(timesteps):
745
+ if self.interrupt:
746
+ continue
747
+
748
+ # Note: Mochi uses reversed timesteps. To ensure compatibility with methods like FasterCache, we need
749
+ # to make sure we're using the correct non-reversed timestep value.
750
+ self._current_timestep = 1000 - t
751
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
752
+ latent_model_input = torch.cat([latents] * 2)
753
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
754
+ latent_model_input = torch.cat([latents] * 3)
755
+ else:
756
+ latent_model_input = latents
757
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
758
+ timestep = t.expand(latent_model_input.shape[0]).to(latents.dtype)
759
+
760
+ noise_pred = self.transformer(
761
+ hidden_states=latent_model_input,
762
+ encoder_hidden_states=prompt_embeds,
763
+ timestep=timestep,
764
+ encoder_attention_mask=prompt_attention_mask,
765
+ attention_kwargs=attention_kwargs,
766
+ return_dict=False,
767
+ )[0]
768
+ # Mochi CFG + Sampling runs in FP32
769
+ noise_pred = noise_pred.to(torch.float32)
770
+
771
+ if self.do_classifier_free_guidance and not self.do_spatio_temporal_guidance:
772
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
773
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
774
+ elif self.do_classifier_free_guidance and self.do_spatio_temporal_guidance:
775
+ noise_pred_uncond, noise_pred_text, noise_pred_perturb = noise_pred.chunk(3)
776
+ noise_pred = (
777
+ noise_pred_uncond
778
+ + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
779
+ + self._stg_scale * (noise_pred_text - noise_pred_perturb)
780
+ )
781
+
782
+ if do_rescaling:
783
+ rescaling_scale = 0.7
784
+ factor = noise_pred_text.std() / noise_pred.std()
785
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
786
+ noise_pred = noise_pred * factor
787
+
788
+ # compute the previous noisy sample x_t -> x_t-1
789
+ latents_dtype = latents.dtype
790
+ latents = self.scheduler.step(noise_pred, t, latents.to(torch.float32), return_dict=False)[0]
791
+ latents = latents.to(latents_dtype)
792
+
793
+ if latents.dtype != latents_dtype:
794
+ if torch.backends.mps.is_available():
795
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
796
+ latents = latents.to(latents_dtype)
797
+
798
+ if callback_on_step_end is not None:
799
+ callback_kwargs = {}
800
+ for k in callback_on_step_end_tensor_inputs:
801
+ callback_kwargs[k] = locals()[k]
802
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
803
+
804
+ latents = callback_outputs.pop("latents", latents)
805
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
806
+
807
+ # call the callback, if provided
808
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
809
+ progress_bar.update()
810
+
811
+ if XLA_AVAILABLE:
812
+ xm.mark_step()
813
+
814
+ self._current_timestep = None
815
+
816
+ if output_type == "latent":
817
+ video = latents
818
+ else:
819
+ # unscale/denormalize the latents
820
+ # denormalize with the mean and std if available and not None
821
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
822
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
823
+ if has_latents_mean and has_latents_std:
824
+ latents_mean = (
825
+ torch.tensor(self.vae.config.latents_mean).view(1, 12, 1, 1, 1).to(latents.device, latents.dtype)
826
+ )
827
+ latents_std = (
828
+ torch.tensor(self.vae.config.latents_std).view(1, 12, 1, 1, 1).to(latents.device, latents.dtype)
829
+ )
830
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
831
+ else:
832
+ latents = latents / self.vae.config.scaling_factor
833
+
834
+ video = self.vae.decode(latents, return_dict=False)[0]
835
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
836
+
837
+ # Offload all models
838
+ self.maybe_free_model_hooks()
839
+
840
+ if not return_dict:
841
+ return (video,)
842
+
843
+ return MochiPipelineOutput(frames=video)