EuuIia commited on
Commit
4734a8f
·
verified ·
1 Parent(s): d44dfca

Upload pipeline_ltx_video.py

Browse files
Files changed (1) hide show
  1. pipeline_ltx_video.py +1902 -0
pipeline_ltx_video.py ADDED
@@ -0,0 +1,1902 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py
2
+ import copy
3
+ import inspect
4
+ import math
5
+ import re
6
+ from contextlib import nullcontext
7
+ from dataclasses import dataclass
8
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from diffusers.image_processor import VaeImageProcessor
13
+ from diffusers.models import AutoencoderKL
14
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
15
+ from diffusers.schedulers import DPMSolverMultistepScheduler
16
+ from diffusers.utils import deprecate, logging
17
+ from diffusers.utils.torch_utils import randn_tensor
18
+ from einops import rearrange
19
+ from transformers import (
20
+ T5EncoderModel,
21
+ T5Tokenizer,
22
+ AutoModelForCausalLM,
23
+ AutoProcessor,
24
+ AutoTokenizer,
25
+ )
26
+
27
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
28
+ CausalVideoAutoencoder,
29
+ )
30
+ from ltx_video.models.autoencoders.vae_encode import (
31
+ get_vae_size_scale_factor,
32
+ latent_to_pixel_coords,
33
+ vae_decode,
34
+ vae_encode,
35
+ )
36
+ from ltx_video.models.transformers.symmetric_patchifier import Patchifier
37
+ from ltx_video.models.transformers.transformer3d import Transformer3DModel
38
+ from ltx_video.schedulers.rf import TimestepShifter
39
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
40
+ from ltx_video.utils.prompt_enhance_utils import generate_cinematic_prompt
41
+ from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
42
+ from ltx_video.models.autoencoders.vae_encode import (
43
+ un_normalize_latents,
44
+ normalize_latents,
45
+ )
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+
51
+ ASPECT_RATIO_1024_BIN = {
52
+ "0.25": [512.0, 2048.0],
53
+ "0.28": [512.0, 1856.0],
54
+ "0.32": [576.0, 1792.0],
55
+ "0.33": [576.0, 1728.0],
56
+ "0.35": [576.0, 1664.0],
57
+ "0.4": [640.0, 1600.0],
58
+ "0.42": [640.0, 1536.0],
59
+ "0.48": [704.0, 1472.0],
60
+ "0.5": [704.0, 1408.0],
61
+ "0.52": [704.0, 1344.0],
62
+ "0.57": [768.0, 1344.0],
63
+ "0.6": [768.0, 1280.0],
64
+ "0.68": [832.0, 1216.0],
65
+ "0.72": [832.0, 1152.0],
66
+ "0.78": [896.0, 1152.0],
67
+ "0.82": [896.0, 1088.0],
68
+ "0.88": [960.0, 1088.0],
69
+ "0.94": [960.0, 1024.0],
70
+ "1.0": [1024.0, 1024.0],
71
+ "1.07": [1024.0, 960.0],
72
+ "1.13": [1088.0, 960.0],
73
+ "1.21": [1088.0, 896.0],
74
+ "1.29": [1152.0, 896.0],
75
+ "1.38": [1152.0, 832.0],
76
+ "1.46": [1216.0, 832.0],
77
+ "1.67": [1280.0, 768.0],
78
+ "1.75": [1344.0, 768.0],
79
+ "2.0": [1408.0, 704.0],
80
+ "2.09": [1472.0, 704.0],
81
+ "2.4": [1536.0, 640.0],
82
+ "2.5": [1600.0, 640.0],
83
+ "3.0": [1728.0, 576.0],
84
+ "4.0": [2048.0, 512.0],
85
+ }
86
+
87
+ ASPECT_RATIO_512_BIN = {
88
+ "0.25": [256.0, 1024.0],
89
+ "0.28": [256.0, 928.0],
90
+ "0.32": [288.0, 896.0],
91
+ "0.33": [288.0, 864.0],
92
+ "0.35": [288.0, 832.0],
93
+ "0.4": [320.0, 800.0],
94
+ "0.42": [320.0, 768.0],
95
+ "0.48": [352.0, 736.0],
96
+ "0.5": [352.0, 704.0],
97
+ "0.52": [352.0, 672.0],
98
+ "0.57": [384.0, 672.0],
99
+ "0.6": [384.0, 640.0],
100
+ "0.68": [416.0, 608.0],
101
+ "0.72": [416.0, 576.0],
102
+ "0.78": [448.0, 576.0],
103
+ "0.82": [448.0, 544.0],
104
+ "0.88": [480.0, 544.0],
105
+ "0.94": [480.0, 512.0],
106
+ "1.0": [512.0, 512.0],
107
+ "1.07": [512.0, 480.0],
108
+ "1.13": [544.0, 480.0],
109
+ "1.21": [544.0, 448.0],
110
+ "1.29": [576.0, 448.0],
111
+ "1.38": [576.0, 416.0],
112
+ "1.46": [608.0, 416.0],
113
+ "1.67": [640.0, 384.0],
114
+ "1.75": [672.0, 384.0],
115
+ "2.0": [704.0, 352.0],
116
+ "2.09": [736.0, 352.0],
117
+ "2.4": [768.0, 320.0],
118
+ "2.5": [800.0, 320.0],
119
+ "3.0": [864.0, 288.0],
120
+ "4.0": [1024.0, 256.0],
121
+ }
122
+
123
+
124
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
125
+ def retrieve_timesteps(
126
+ scheduler,
127
+ num_inference_steps: Optional[int] = None,
128
+ device: Optional[Union[str, torch.device]] = None,
129
+ timesteps: Optional[List[int]] = None,
130
+ skip_initial_inference_steps: int = 0,
131
+ skip_final_inference_steps: int = 0,
132
+ **kwargs,
133
+ ):
134
+ """
135
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
136
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
137
+
138
+ Args:
139
+ scheduler (`SchedulerMixin`):
140
+ The scheduler to get timesteps from.
141
+ num_inference_steps (`int`):
142
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
143
+ `timesteps` must be `None`.
144
+ device (`str` or `torch.device`, *optional*):
145
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
146
+ timesteps (`List[int]`, *optional*):
147
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
148
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
149
+ must be `None`.
150
+ max_timestep ('float', *optional*, defaults to 1.0):
151
+ The initial noising level for image-to-image/video-to-video. The list if timestamps will be
152
+ truncated to start with a timestamp greater or equal to this.
153
+
154
+ Returns:
155
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
156
+ second element is the number of inference steps.
157
+ """
158
+ if timesteps is not None:
159
+ accepts_timesteps = "timesteps" in set(
160
+ inspect.signature(scheduler.set_timesteps).parameters.keys()
161
+ )
162
+ if not accepts_timesteps:
163
+ raise ValueError(
164
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
165
+ f" timestep schedules. Please check whether you are using the correct scheduler."
166
+ )
167
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
168
+ timesteps = scheduler.timesteps
169
+ num_inference_steps = len(timesteps)
170
+ else:
171
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
172
+ timesteps = scheduler.timesteps
173
+
174
+ if (
175
+ skip_initial_inference_steps < 0
176
+ or skip_final_inference_steps < 0
177
+ or skip_initial_inference_steps + skip_final_inference_steps
178
+ >= num_inference_steps
179
+ ):
180
+ raise ValueError(
181
+ "invalid skip inference step values: must be non-negative and the sum of skip_initial_inference_steps and skip_final_inference_steps must be less than the number of inference steps"
182
+ )
183
+
184
+ timesteps = timesteps[
185
+ skip_initial_inference_steps : len(timesteps) - skip_final_inference_steps
186
+ ]
187
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
188
+ num_inference_steps = len(timesteps)
189
+
190
+ return timesteps, num_inference_steps
191
+
192
+
193
+ @dataclass
194
+ class ConditioningItem:
195
+ """
196
+ Defines a single frame-conditioning item - a single frame or a sequence of frames.
197
+
198
+ Attributes:
199
+ media_item (torch.Tensor): shape=(b, 3, f, h, w). The media item to condition on.
200
+ media_frame_number (int): The start-frame number of the media item in the generated video.
201
+ conditioning_strength (float): The strength of the conditioning (1.0 = full conditioning).
202
+ media_x (Optional[int]): Optional left x coordinate of the media item in the generated frame.
203
+ media_y (Optional[int]): Optional top y coordinate of the media item in the generated frame.
204
+ """
205
+
206
+ media_item: torch.Tensor
207
+ media_frame_number: int
208
+ conditioning_strength: float
209
+ media_x: Optional[int] = None
210
+ media_y: Optional[int] = None
211
+
212
+
213
+ class LTXVideoPipeline(DiffusionPipeline):
214
+ r"""
215
+ Pipeline for text-to-image generation using LTX-Video.
216
+
217
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
218
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
219
+
220
+ Args:
221
+ vae ([`AutoencoderKL`]):
222
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
223
+ text_encoder ([`T5EncoderModel`]):
224
+ Frozen text-encoder. This uses
225
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
226
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
227
+ tokenizer (`T5Tokenizer`):
228
+ Tokenizer of class
229
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
230
+ transformer ([`Transformer2DModel`]):
231
+ A text conditioned `Transformer2DModel` to denoise the encoded image latents.
232
+ scheduler ([`SchedulerMixin`]):
233
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
234
+ """
235
+
236
+ bad_punct_regex = re.compile(
237
+ r"["
238
+ + "#®•©™&@·º½¾¿¡§~"
239
+ + r"\)"
240
+ + r"\("
241
+ + r"\]"
242
+ + r"\["
243
+ + r"\}"
244
+ + r"\{"
245
+ + r"\|"
246
+ + "\\"
247
+ + r"\/"
248
+ + r"\*"
249
+ + r"]{1,}"
250
+ ) # noqa
251
+
252
+ _optional_components = [
253
+ "tokenizer",
254
+ "text_encoder",
255
+ "prompt_enhancer_image_caption_model",
256
+ "prompt_enhancer_image_caption_processor",
257
+ "prompt_enhancer_llm_model",
258
+ "prompt_enhancer_llm_tokenizer",
259
+ ]
260
+ model_cpu_offload_seq = "prompt_enhancer_image_caption_model->prompt_enhancer_llm_model->text_encoder->transformer->vae"
261
+
262
+ def __init__(
263
+ self,
264
+ tokenizer: T5Tokenizer,
265
+ text_encoder: T5EncoderModel,
266
+ vae: AutoencoderKL,
267
+ transformer: Transformer3DModel,
268
+ scheduler: DPMSolverMultistepScheduler,
269
+ patchifier: Patchifier,
270
+ prompt_enhancer_image_caption_model: AutoModelForCausalLM,
271
+ prompt_enhancer_image_caption_processor: AutoProcessor,
272
+ prompt_enhancer_llm_model: AutoModelForCausalLM,
273
+ prompt_enhancer_llm_tokenizer: AutoTokenizer,
274
+ allowed_inference_steps: Optional[List[float]] = None,
275
+ ):
276
+ super().__init__()
277
+
278
+ self.register_modules(
279
+ tokenizer=tokenizer,
280
+ text_encoder=text_encoder,
281
+ vae=vae,
282
+ transformer=transformer,
283
+ scheduler=scheduler,
284
+ patchifier=patchifier,
285
+ prompt_enhancer_image_caption_model=prompt_enhancer_image_caption_model,
286
+ prompt_enhancer_image_caption_processor=prompt_enhancer_image_caption_processor,
287
+ prompt_enhancer_llm_model=prompt_enhancer_llm_model,
288
+ prompt_enhancer_llm_tokenizer=prompt_enhancer_llm_tokenizer,
289
+ )
290
+
291
+ self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(
292
+ self.vae
293
+ )
294
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
295
+
296
+ self.allowed_inference_steps = allowed_inference_steps
297
+
298
+ def mask_text_embeddings(self, emb, mask):
299
+ if emb.shape[0] == 1:
300
+ keep_index = mask.sum().item()
301
+ return emb[:, :, :keep_index, :], keep_index
302
+ else:
303
+ masked_feature = emb * mask[:, None, :, None]
304
+ return masked_feature, emb.shape[2]
305
+
306
+ # Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
307
+ def encode_prompt(
308
+ self,
309
+ prompt: Union[str, List[str]],
310
+ do_classifier_free_guidance: bool = True,
311
+ negative_prompt: str = "",
312
+ num_images_per_prompt: int = 1,
313
+ device: Optional[torch.device] = None,
314
+ prompt_embeds: Optional[torch.FloatTensor] = None,
315
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
316
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
317
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
318
+ text_encoder_max_tokens: int = 256,
319
+ **kwargs,
320
+ ):
321
+ r"""
322
+ Encodes the prompt into text encoder hidden states.
323
+
324
+ Args:
325
+ prompt (`str` or `List[str]`, *optional*):
326
+ prompt to be encoded
327
+ negative_prompt (`str` or `List[str]`, *optional*):
328
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
329
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
330
+ This should be "".
331
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
332
+ whether to use classifier free guidance or not
333
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
334
+ number of images that should be generated per prompt
335
+ device: (`torch.device`, *optional*):
336
+ torch device to place the resulting embeddings on
337
+ prompt_embeds (`torch.FloatTensor`, *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.FloatTensor`, *optional*):
341
+ Pre-generated negative text embeddings.
342
+ """
343
+
344
+ if "mask_feature" in kwargs:
345
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
346
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
347
+
348
+ if device is None:
349
+ device = self._execution_device
350
+
351
+ if prompt is not None and isinstance(prompt, str):
352
+ batch_size = 1
353
+ elif prompt is not None and isinstance(prompt, list):
354
+ batch_size = len(prompt)
355
+ else:
356
+ batch_size = prompt_embeds.shape[0]
357
+
358
+ # See Section 3.1. of the paper.
359
+ max_length = (
360
+ text_encoder_max_tokens # TPU supports only lengths multiple of 128
361
+ )
362
+ if prompt_embeds is None:
363
+ assert (
364
+ self.text_encoder is not None
365
+ ), "You should provide either prompt_embeds or self.text_encoder should not be None,"
366
+ text_enc_device = next(self.text_encoder.parameters()).device
367
+ prompt = self._text_preprocessing(prompt)
368
+ text_inputs = self.tokenizer(
369
+ prompt,
370
+ padding="max_length",
371
+ max_length=max_length,
372
+ truncation=True,
373
+ add_special_tokens=True,
374
+ return_tensors="pt",
375
+ )
376
+ text_input_ids = text_inputs.input_ids
377
+ untruncated_ids = self.tokenizer(
378
+ prompt, padding="longest", return_tensors="pt"
379
+ ).input_ids
380
+
381
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[
382
+ -1
383
+ ] and not torch.equal(text_input_ids, untruncated_ids):
384
+ removed_text = self.tokenizer.batch_decode(
385
+ untruncated_ids[:, max_length - 1 : -1]
386
+ )
387
+ logger.warning(
388
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
389
+ f" {max_length} tokens: {removed_text}"
390
+ )
391
+
392
+ prompt_attention_mask = text_inputs.attention_mask
393
+ prompt_attention_mask = prompt_attention_mask.to(text_enc_device)
394
+ prompt_attention_mask = prompt_attention_mask.to(device)
395
+
396
+ prompt_embeds = self.text_encoder(
397
+ text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask
398
+ )
399
+ prompt_embeds = prompt_embeds[0]
400
+
401
+ if self.text_encoder is not None:
402
+ dtype = self.text_encoder.dtype
403
+ elif self.transformer is not None:
404
+ dtype = self.transformer.dtype
405
+ else:
406
+ dtype = None
407
+
408
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
409
+
410
+ bs_embed, seq_len, _ = prompt_embeds.shape
411
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
412
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
413
+ prompt_embeds = prompt_embeds.view(
414
+ bs_embed * num_images_per_prompt, seq_len, -1
415
+ )
416
+ prompt_attention_mask = prompt_attention_mask.repeat(1, num_images_per_prompt)
417
+ prompt_attention_mask = prompt_attention_mask.view(
418
+ bs_embed * num_images_per_prompt, -1
419
+ )
420
+
421
+ # get unconditional embeddings for classifier free guidance
422
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
423
+ uncond_tokens = self._text_preprocessing(negative_prompt)
424
+ uncond_tokens = uncond_tokens * batch_size
425
+ max_length = prompt_embeds.shape[1]
426
+ uncond_input = self.tokenizer(
427
+ uncond_tokens,
428
+ padding="max_length",
429
+ max_length=max_length,
430
+ truncation=True,
431
+ return_attention_mask=True,
432
+ add_special_tokens=True,
433
+ return_tensors="pt",
434
+ )
435
+ negative_prompt_attention_mask = uncond_input.attention_mask
436
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(
437
+ text_enc_device
438
+ )
439
+
440
+ negative_prompt_embeds = self.text_encoder(
441
+ uncond_input.input_ids.to(text_enc_device),
442
+ attention_mask=negative_prompt_attention_mask,
443
+ )
444
+ negative_prompt_embeds = negative_prompt_embeds[0]
445
+
446
+ if do_classifier_free_guidance:
447
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
448
+ seq_len = negative_prompt_embeds.shape[1]
449
+
450
+ negative_prompt_embeds = negative_prompt_embeds.to(
451
+ dtype=dtype, device=device
452
+ )
453
+
454
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
455
+ 1, num_images_per_prompt, 1
456
+ )
457
+ negative_prompt_embeds = negative_prompt_embeds.view(
458
+ batch_size * num_images_per_prompt, seq_len, -1
459
+ )
460
+
461
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(
462
+ 1, num_images_per_prompt
463
+ )
464
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(
465
+ bs_embed * num_images_per_prompt, -1
466
+ )
467
+ else:
468
+ negative_prompt_embeds = None
469
+ negative_prompt_attention_mask = None
470
+
471
+ return (
472
+ prompt_embeds,
473
+ prompt_attention_mask,
474
+ negative_prompt_embeds,
475
+ negative_prompt_attention_mask,
476
+ )
477
+
478
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
479
+ def prepare_extra_step_kwargs(self, generator, eta):
480
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
481
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
482
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
483
+ # and should be between [0, 1]
484
+
485
+ accepts_eta = "eta" in set(
486
+ inspect.signature(self.scheduler.step).parameters.keys()
487
+ )
488
+ extra_step_kwargs = {}
489
+ if accepts_eta:
490
+ extra_step_kwargs["eta"] = eta
491
+
492
+ # check if the scheduler accepts generator
493
+ accepts_generator = "generator" in set(
494
+ inspect.signature(self.scheduler.step).parameters.keys()
495
+ )
496
+ if accepts_generator:
497
+ extra_step_kwargs["generator"] = generator
498
+ return extra_step_kwargs
499
+
500
+ def check_inputs(
501
+ self,
502
+ prompt,
503
+ height,
504
+ width,
505
+ negative_prompt,
506
+ prompt_embeds=None,
507
+ negative_prompt_embeds=None,
508
+ prompt_attention_mask=None,
509
+ negative_prompt_attention_mask=None,
510
+ enhance_prompt=False,
511
+ ):
512
+ if height % 8 != 0 or width % 8 != 0:
513
+ raise ValueError(
514
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
515
+ )
516
+
517
+ if prompt is not None and prompt_embeds is not None:
518
+ raise ValueError(
519
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
520
+ " only forward one of the two."
521
+ )
522
+ elif prompt is None and prompt_embeds is None:
523
+ raise ValueError(
524
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
525
+ )
526
+ elif prompt is not None and (
527
+ not isinstance(prompt, str) and not isinstance(prompt, list)
528
+ ):
529
+ raise ValueError(
530
+ f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
531
+ )
532
+
533
+ if prompt is not None and negative_prompt_embeds is not None:
534
+ raise ValueError(
535
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
536
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
537
+ )
538
+
539
+ if negative_prompt is not None and negative_prompt_embeds is not None:
540
+ raise ValueError(
541
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
542
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
543
+ )
544
+
545
+ if prompt_embeds is not None and prompt_attention_mask is None:
546
+ raise ValueError(
547
+ "Must provide `prompt_attention_mask` when specifying `prompt_embeds`."
548
+ )
549
+
550
+ if (
551
+ negative_prompt_embeds is not None
552
+ and negative_prompt_attention_mask is None
553
+ ):
554
+ raise ValueError(
555
+ "Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`."
556
+ )
557
+
558
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
559
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
560
+ raise ValueError(
561
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
562
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
563
+ f" {negative_prompt_embeds.shape}."
564
+ )
565
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
566
+ raise ValueError(
567
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
568
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
569
+ f" {negative_prompt_attention_mask.shape}."
570
+ )
571
+
572
+ if enhance_prompt:
573
+ assert (
574
+ self.prompt_enhancer_image_caption_model is not None
575
+ ), "Image caption model must be initialized if enhance_prompt is True"
576
+ assert (
577
+ self.prompt_enhancer_image_caption_processor is not None
578
+ ), "Image caption processor must be initialized if enhance_prompt is True"
579
+ assert (
580
+ self.prompt_enhancer_llm_model is not None
581
+ ), "Text prompt enhancer model must be initialized if enhance_prompt is True"
582
+ assert (
583
+ self.prompt_enhancer_llm_tokenizer is not None
584
+ ), "Text prompt enhancer tokenizer must be initialized if enhance_prompt is True"
585
+
586
+ def _text_preprocessing(self, text):
587
+ if not isinstance(text, (tuple, list)):
588
+ text = [text]
589
+
590
+ def process(text: str):
591
+ text = text.strip()
592
+ return text
593
+
594
+ return [process(t) for t in text]
595
+
596
+ @staticmethod
597
+ def add_noise_to_image_conditioning_latents(
598
+ t: float,
599
+ init_latents: torch.Tensor,
600
+ latents: torch.Tensor,
601
+ noise_scale: float,
602
+ conditioning_mask: torch.Tensor,
603
+ generator,
604
+ eps=1e-6,
605
+ ):
606
+ """
607
+ Add timestep-dependent noise to the hard-conditioning latents.
608
+ This helps with motion continuity, especially when conditioned on a single frame.
609
+ """
610
+ noise = randn_tensor(
611
+ latents.shape,
612
+ generator=generator,
613
+ device=latents.device,
614
+ dtype=latents.dtype,
615
+ )
616
+ # Add noise only to hard-conditioning latents (conditioning_mask = 1.0)
617
+ need_to_noise = (conditioning_mask > 1.0 - eps).unsqueeze(-1)
618
+ noised_latents = init_latents + noise_scale * noise * (t**2)
619
+ latents = torch.where(need_to_noise, noised_latents, latents)
620
+ return latents
621
+
622
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
623
+ def prepare_latents(
624
+ self,
625
+ latents: torch.Tensor | None,
626
+ media_items: torch.Tensor | None,
627
+ timestep: float,
628
+ latent_shape: torch.Size | Tuple[Any, ...],
629
+ dtype: torch.dtype,
630
+ device: torch.device,
631
+ generator: torch.Generator | List[torch.Generator],
632
+ vae_per_channel_normalize: bool = True,
633
+ ):
634
+ """
635
+ Prepare the initial latent tensor to be denoised.
636
+ The latents are either pure noise or a noised version of the encoded media items.
637
+ Args:
638
+ latents (`torch.FloatTensor` or `None`):
639
+ The latents to use (provided by the user) or `None` to create new latents.
640
+ media_items (`torch.FloatTensor` or `None`):
641
+ An image or video to be updated using img2img or vid2vid. The media item is encoded and noised.
642
+ timestep (`float`):
643
+ The timestep to noise the encoded media_items to.
644
+ latent_shape (`torch.Size`):
645
+ The target latent shape.
646
+ dtype (`torch.dtype`):
647
+ The target dtype.
648
+ device (`torch.device`):
649
+ The target device.
650
+ generator (`torch.Generator` or `List[torch.Generator]`):
651
+ Generator(s) to be used for the noising process.
652
+ vae_per_channel_normalize ('bool'):
653
+ When encoding the media_items, whether to normalize the latents per-channel.
654
+ Returns:
655
+ `torch.FloatTensor`: The latents to be used for the denoising process. This is a tensor of shape
656
+ (batch_size, num_channels, height, width).
657
+ """
658
+ if isinstance(generator, list) and len(generator) != latent_shape[0]:
659
+ raise ValueError(
660
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
661
+ f" size of {latent_shape[0]}. Make sure the batch size matches the length of the generators."
662
+ )
663
+
664
+ # Initialize the latents with the given latents or encoded media item, if provided
665
+ assert (
666
+ latents is None or media_items is None
667
+ ), "Cannot provide both latents and media_items. Please provide only one of the two."
668
+
669
+ assert (
670
+ latents is None and media_items is None or timestep < 1.0
671
+ ), "Input media_item or latents are provided, but they will be replaced with noise."
672
+
673
+ if media_items is not None:
674
+ latents = vae_encode(
675
+ media_items.to(dtype=self.vae.dtype, device=self.vae.device),
676
+ self.vae,
677
+ vae_per_channel_normalize=vae_per_channel_normalize,
678
+ )
679
+ if latents is not None:
680
+ assert (
681
+ latents.shape == latent_shape
682
+ ), f"Latents have to be of shape {latent_shape} but are {latents.shape}."
683
+ latents = latents.to(device=device, dtype=dtype)
684
+
685
+ # For backward compatibility, generate in the "patchified" shape and rearrange
686
+ b, c, f, h, w = latent_shape
687
+ noise = randn_tensor(
688
+ (b, f * h * w, c), generator=generator, device=device, dtype=dtype
689
+ )
690
+ noise = rearrange(noise, "b (f h w) c -> b c f h w", f=f, h=h, w=w)
691
+
692
+ # scale the initial noise by the standard deviation required by the scheduler
693
+ noise = noise * self.scheduler.init_noise_sigma
694
+
695
+ if latents is None:
696
+ latents = noise
697
+ else:
698
+ # Noise the latents to the required (first) timestep
699
+ latents = timestep * noise + (1 - timestep) * latents
700
+
701
+ return latents
702
+
703
+ @staticmethod
704
+ def classify_height_width_bin(
705
+ height: int, width: int, ratios: dict
706
+ ) -> Tuple[int, int]:
707
+ """Returns binned height and width."""
708
+ ar = float(height / width)
709
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
710
+ default_hw = ratios[closest_ratio]
711
+ return int(default_hw[0]), int(default_hw[1])
712
+
713
+ @staticmethod
714
+ def resize_and_crop_tensor(
715
+ samples: torch.Tensor, new_width: int, new_height: int
716
+ ) -> torch.Tensor:
717
+ n_frames, orig_height, orig_width = samples.shape[-3:]
718
+
719
+ # Check if resizing is needed
720
+ if orig_height != new_height or orig_width != new_width:
721
+ ratio = max(new_height / orig_height, new_width / orig_width)
722
+ resized_width = int(orig_width * ratio)
723
+ resized_height = int(orig_height * ratio)
724
+
725
+ # Resize
726
+ samples = LTXVideoPipeline.resize_tensor(
727
+ samples, resized_height, resized_width
728
+ )
729
+
730
+ # Center Crop
731
+ start_x = (resized_width - new_width) // 2
732
+ end_x = start_x + new_width
733
+ start_y = (resized_height - new_height) // 2
734
+ end_y = start_y + new_height
735
+ samples = samples[..., start_y:end_y, start_x:end_x]
736
+
737
+ return samples
738
+
739
+ @staticmethod
740
+ def resize_tensor(media_items, height, width):
741
+ n_frames = media_items.shape[2]
742
+ if media_items.shape[-2:] != (height, width):
743
+ media_items = rearrange(media_items, "b c n h w -> (b n) c h w")
744
+ media_items = F.interpolate(
745
+ media_items,
746
+ size=(height, width),
747
+ mode="bilinear",
748
+ align_corners=False,
749
+ )
750
+ media_items = rearrange(media_items, "(b n) c h w -> b c n h w", n=n_frames)
751
+ return media_items
752
+
753
+ @torch.no_grad()
754
+ def __call__(
755
+ self,
756
+ height: int,
757
+ width: int,
758
+ num_frames: int,
759
+ frame_rate: float,
760
+ prompt: Union[str, List[str]] = None,
761
+ negative_prompt: str = "",
762
+ num_inference_steps: int = 20,
763
+ skip_initial_inference_steps: int = 0,
764
+ skip_final_inference_steps: int = 0,
765
+ timesteps: List[int] = None,
766
+ guidance_scale: Union[float, List[float]] = 4.5,
767
+ cfg_star_rescale: bool = False,
768
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
769
+ skip_block_list: Optional[Union[List[List[int]], List[int]]] = None,
770
+ stg_scale: Union[float, List[float]] = 1.0,
771
+ rescaling_scale: Union[float, List[float]] = 0.7,
772
+ guidance_timesteps: Optional[List[int]] = None,
773
+ num_images_per_prompt: Optional[int] = 1,
774
+ eta: float = 0.0,
775
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
776
+ latents: Optional[torch.FloatTensor] = None,
777
+ prompt_embeds: Optional[torch.FloatTensor] = None,
778
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
779
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
780
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
781
+ output_type: Optional[str] = "pil",
782
+ return_dict: bool = True,
783
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
784
+ conditioning_items: Optional[List[ConditioningItem]] = None,
785
+ decode_timestep: Union[List[float], float] = 0.0,
786
+ decode_noise_scale: Optional[List[float]] = None,
787
+ mixed_precision: bool = False,
788
+ offload_to_cpu: bool = False,
789
+ enhance_prompt: bool = False,
790
+ text_encoder_max_tokens: int = 256,
791
+ stochastic_sampling: bool = False,
792
+ media_items: Optional[torch.Tensor] = None,
793
+ tone_map_compression_ratio: float = 0.0,
794
+ **kwargs,
795
+ ) -> Union[ImagePipelineOutput, Tuple]:
796
+ """
797
+ Function invoked when calling the pipeline for generation.
798
+
799
+ Args:
800
+ prompt (`str` or `List[str]`, *optional*):
801
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
802
+ instead.
803
+ negative_prompt (`str` or `List[str]`, *optional*):
804
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
805
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
806
+ less than `1`).
807
+ num_inference_steps (`int`, *optional*, defaults to 100):
808
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
809
+ expense of slower inference. If `timesteps` is provided, this parameter is ignored.
810
+ skip_initial_inference_steps (`int`, *optional*, defaults to 0):
811
+ The number of initial timesteps to skip. After calculating the timesteps, this number of timesteps will
812
+ be removed from the beginning of the timesteps list. Meaning the highest-timesteps values will not run.
813
+ skip_final_inference_steps (`int`, *optional*, defaults to 0):
814
+ The number of final timesteps to skip. After calculating the timesteps, this number of timesteps will
815
+ be removed from the end of the timesteps list. Meaning the lowest-timesteps values will not run.
816
+ timesteps (`List[int]`, *optional*):
817
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
818
+ timesteps are used. Must be in descending order.
819
+ guidance_scale (`float`, *optional*, defaults to 4.5):
820
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
821
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
822
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
823
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
824
+ usually at the expense of lower image quality.
825
+ cfg_star_rescale (`bool`, *optional*, defaults to `False`):
826
+ If set to `True`, applies the CFG star rescale. Scales the negative prediction according to dot
827
+ product between positive and negative.
828
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
829
+ The number of images to generate per prompt.
830
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
831
+ The height in pixels of the generated image.
832
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
833
+ The width in pixels of the generated image.
834
+ eta (`float`, *optional*, defaults to 0.0):
835
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
836
+ [`schedulers.DDIMScheduler`], will be ignored for others.
837
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
838
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
839
+ to make generation deterministic.
840
+ latents (`torch.FloatTensor`, *optional*):
841
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
842
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
843
+ tensor will ge generated by sampling using the supplied random `generator`.
844
+ prompt_embeds (`torch.FloatTensor`, *optional*):
845
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
846
+ provided, text embeddings will be generated from `prompt` input argument.
847
+ prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
848
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
849
+ Pre-generated negative text embeddings. This negative prompt should be "". If not
850
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
851
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
852
+ Pre-generated attention mask for negative text embeddings.
853
+ output_type (`str`, *optional*, defaults to `"pil"`):
854
+ The output format of the generate image. Choose between
855
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
856
+ return_dict (`bool`, *optional*, defaults to `True`):
857
+ Whether to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
858
+ callback_on_step_end (`Callable`, *optional*):
859
+ A function that calls at the end of each denoising steps during the inference. The function is called
860
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
861
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
862
+ `callback_on_step_end_tensor_inputs`.
863
+ use_resolution_binning (`bool` defaults to `True`):
864
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
865
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
866
+ the requested resolution. Useful for generating non-square images.
867
+ enhance_prompt (`bool`, *optional*, defaults to `False`):
868
+ If set to `True`, the prompt is enhanced using a LLM model.
869
+ text_encoder_max_tokens (`int`, *optional*, defaults to `256`):
870
+ The maximum number of tokens to use for the text encoder.
871
+ stochastic_sampling (`bool`, *optional*, defaults to `False`):
872
+ If set to `True`, the sampling is stochastic. If set to `False`, the sampling is deterministic.
873
+ media_items ('torch.Tensor', *optional*):
874
+ The input media item used for image-to-image / video-to-video.
875
+ tone_map_compression_ratio: compression ratio for tone mapping, defaults to 0.0.
876
+ If set to 0.0, no tone mapping is applied. If set to 1.0 - full compression is applied.
877
+ Examples:
878
+
879
+ Returns:
880
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
881
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
882
+ returned where the first element is a list with the generated images
883
+ """
884
+ if "mask_feature" in kwargs:
885
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
886
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
887
+
888
+ is_video = kwargs.get("is_video", False)
889
+ self.check_inputs(
890
+ prompt,
891
+ height,
892
+ width,
893
+ negative_prompt,
894
+ prompt_embeds,
895
+ negative_prompt_embeds,
896
+ prompt_attention_mask,
897
+ negative_prompt_attention_mask,
898
+ )
899
+
900
+ # 2. Default height and width to transformer
901
+ if prompt is not None and isinstance(prompt, str):
902
+ batch_size = 1
903
+ elif prompt is not None and isinstance(prompt, list):
904
+ batch_size = len(prompt)
905
+ else:
906
+ batch_size = prompt_embeds.shape[0]
907
+
908
+ device = self._execution_device
909
+
910
+ self.video_scale_factor = self.video_scale_factor if is_video else 1
911
+ vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", True)
912
+ image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)
913
+
914
+ latent_height = height // self.vae_scale_factor
915
+ latent_width = width // self.vae_scale_factor
916
+ latent_num_frames = num_frames // self.video_scale_factor
917
+ if isinstance(self.vae, CausalVideoAutoencoder) and is_video:
918
+ latent_num_frames += 1
919
+ latent_shape = (
920
+ batch_size * num_images_per_prompt,
921
+ self.transformer.config.in_channels,
922
+ latent_num_frames,
923
+ latent_height,
924
+ latent_width,
925
+ )
926
+
927
+ # Prepare the list of denoising time-steps
928
+
929
+ retrieve_timesteps_kwargs = {}
930
+ if isinstance(self.scheduler, TimestepShifter):
931
+ retrieve_timesteps_kwargs["samples_shape"] = latent_shape
932
+
933
+ assert (
934
+ skip_initial_inference_steps == 0
935
+ or latents is not None
936
+ or media_items is not None
937
+ ), (
938
+ f"skip_initial_inference_steps ({skip_initial_inference_steps}) is used for image-to-image/video-to-video - "
939
+ "media_item or latents should be provided."
940
+ )
941
+
942
+ timesteps, num_inference_steps = retrieve_timesteps(
943
+ self.scheduler,
944
+ num_inference_steps,
945
+ device,
946
+ timesteps,
947
+ skip_initial_inference_steps=skip_initial_inference_steps,
948
+ skip_final_inference_steps=skip_final_inference_steps,
949
+ **retrieve_timesteps_kwargs,
950
+ )
951
+
952
+ if self.allowed_inference_steps is not None:
953
+ for timestep in [round(x, 4) for x in timesteps.tolist()]:
954
+ assert (
955
+ timestep in self.allowed_inference_steps
956
+ ), f"Invalid inference timestep {timestep}. Allowed timesteps are {self.allowed_inference_steps}."
957
+
958
+
959
+ # Versão Corrigida em pipeline_ltx_video.py
960
+ if guidance_timesteps:
961
+ guidance_mapping = []
962
+ for timestep in timesteps:
963
+ indices = [
964
+ i for i, val in enumerate(guidance_timesteps) if val <= timestep
965
+ ]
966
+ guidance_mapping.append(
967
+ indices[0] if len(indices) > 0 else (len(guidance_timesteps) - 1)
968
+ )
969
+ else:
970
+ # CORREÇÃO: Garante que guidance_mapping exista mesmo se guidance_timesteps não for fornecido.
971
+ # Cria um mapeamento de identidade seguro.
972
+ guidance_mapping = list(range(len(timesteps)))
973
+
974
+
975
+
976
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
977
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
978
+ # corresponds to doing no classifier free guidance.
979
+ if not isinstance(guidance_scale, List):
980
+ guidance_scale = [guidance_scale] * len(timesteps)
981
+ else:
982
+ guidance_scale = [
983
+ guidance_scale[guidance_mapping[i]] for i in range(len(timesteps))
984
+ ]
985
+
986
+ if not isinstance(stg_scale, List):
987
+ stg_scale = [stg_scale] * len(timesteps)
988
+ else:
989
+ stg_scale = [stg_scale[guidance_mapping[i]] for i in range(len(timesteps))]
990
+
991
+ if not isinstance(rescaling_scale, List):
992
+ rescaling_scale = [rescaling_scale] * len(timesteps)
993
+ else:
994
+ rescaling_scale = [
995
+ rescaling_scale[guidance_mapping[i]] for i in range(len(timesteps))
996
+ ]
997
+
998
+ # Normalize skip_block_list to always be None or a list of lists matching timesteps
999
+ if skip_block_list is not None:
1000
+ # Convert single list to list of lists if needed
1001
+ if len(skip_block_list) == 0 or not isinstance(skip_block_list[0], list):
1002
+ skip_block_list = [skip_block_list] * len(timesteps)
1003
+ else:
1004
+ new_skip_block_list = []
1005
+ for i, timestep in enumerate(timesteps):
1006
+ new_skip_block_list.append(skip_block_list[guidance_mapping[i]])
1007
+ skip_block_list = new_skip_block_list
1008
+
1009
+ if enhance_prompt:
1010
+ self.prompt_enhancer_image_caption_model = (
1011
+ self.prompt_enhancer_image_caption_model.to(self._execution_device)
1012
+ )
1013
+ self.prompt_enhancer_llm_model = self.prompt_enhancer_llm_model.to(
1014
+ self._execution_device
1015
+ )
1016
+
1017
+ prompt = generate_cinematic_prompt(
1018
+ self.prompt_enhancer_image_caption_model,
1019
+ self.prompt_enhancer_image_caption_processor,
1020
+ self.prompt_enhancer_llm_model,
1021
+ self.prompt_enhancer_llm_tokenizer,
1022
+ prompt,
1023
+ conditioning_items,
1024
+ max_new_tokens=text_encoder_max_tokens,
1025
+ )
1026
+
1027
+ # 3. Encode input prompt
1028
+ if self.text_encoder is not None:
1029
+ self.text_encoder = self.text_encoder.to(self._execution_device)
1030
+
1031
+ (
1032
+ prompt_embeds,
1033
+ prompt_attention_mask,
1034
+ negative_prompt_embeds,
1035
+ negative_prompt_attention_mask,
1036
+ ) = self.encode_prompt(
1037
+ prompt,
1038
+ True,
1039
+ negative_prompt=negative_prompt,
1040
+ num_images_per_prompt=num_images_per_prompt,
1041
+ device=device,
1042
+ prompt_embeds=prompt_embeds,
1043
+ negative_prompt_embeds=negative_prompt_embeds,
1044
+ prompt_attention_mask=prompt_attention_mask,
1045
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
1046
+ text_encoder_max_tokens=text_encoder_max_tokens,
1047
+ )
1048
+
1049
+ if offload_to_cpu and self.text_encoder is not None:
1050
+ self.text_encoder = self.text_encoder.cpu()
1051
+
1052
+ self.transformer = self.transformer.to(self._execution_device)
1053
+
1054
+ prompt_embeds_batch = prompt_embeds
1055
+ prompt_attention_mask_batch = prompt_attention_mask
1056
+ negative_prompt_embeds = (
1057
+ torch.zeros_like(prompt_embeds)
1058
+ if negative_prompt_embeds is None
1059
+ else negative_prompt_embeds
1060
+ )
1061
+ negative_prompt_attention_mask = (
1062
+ torch.zeros_like(prompt_attention_mask)
1063
+ if negative_prompt_attention_mask is None
1064
+ else negative_prompt_attention_mask
1065
+ )
1066
+
1067
+ prompt_embeds_batch = torch.cat(
1068
+ [negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0
1069
+ )
1070
+ prompt_attention_mask_batch = torch.cat(
1071
+ [
1072
+ negative_prompt_attention_mask,
1073
+ prompt_attention_mask,
1074
+ prompt_attention_mask,
1075
+ ],
1076
+ dim=0,
1077
+ )
1078
+ # 4. Prepare the initial latents using the provided media and conditioning items
1079
+
1080
+ # Prepare the initial latents tensor, shape = (b, c, f, h, w)
1081
+ latents = self.prepare_latents(
1082
+ latents=latents,
1083
+ media_items=media_items,
1084
+ timestep=timesteps[0],
1085
+ latent_shape=latent_shape,
1086
+ dtype=prompt_embeds.dtype,
1087
+ device=device,
1088
+ generator=generator,
1089
+ vae_per_channel_normalize=vae_per_channel_normalize,
1090
+ )
1091
+
1092
+ # Update the latents with the conditioning items and patchify them into (b, n, c)
1093
+ latents, pixel_coords, conditioning_mask, num_cond_latents = (
1094
+ self.prepare_conditioning(
1095
+ conditioning_items=conditioning_items,
1096
+ init_latents=latents,
1097
+ num_frames=num_frames,
1098
+ height=height,
1099
+ width=width,
1100
+ vae_per_channel_normalize=vae_per_channel_normalize,
1101
+ generator=generator,
1102
+ )
1103
+ )
1104
+ init_latents = latents.clone() # Used for image_cond_noise_update
1105
+
1106
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1107
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1108
+
1109
+ # 7. Denoising loop
1110
+ num_warmup_steps = max(
1111
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
1112
+ )
1113
+
1114
+ orig_conditioning_mask = conditioning_mask
1115
+
1116
+ # Befor compiling this code please be aware:
1117
+ # This code might generate different input shapes if some timesteps have no STG or CFG.
1118
+ # This means that the codes might need to be compiled mutliple times.
1119
+ # To avoid that, use the same STG and CFG values for all timesteps.
1120
+
1121
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1122
+ for i, t in enumerate(timesteps):
1123
+ do_classifier_free_guidance = guidance_scale[i] > 1.0
1124
+ do_spatio_temporal_guidance = stg_scale[i] > 0
1125
+ do_rescaling = rescaling_scale[i] != 1.0
1126
+
1127
+ num_conds = 1
1128
+ if do_classifier_free_guidance:
1129
+ num_conds += 1
1130
+ if do_spatio_temporal_guidance:
1131
+ num_conds += 1
1132
+
1133
+ if do_classifier_free_guidance and do_spatio_temporal_guidance:
1134
+ indices = slice(batch_size * 0, batch_size * 3)
1135
+ elif do_classifier_free_guidance:
1136
+ indices = slice(batch_size * 0, batch_size * 2)
1137
+ elif do_spatio_temporal_guidance:
1138
+ indices = slice(batch_size * 1, batch_size * 3)
1139
+ else:
1140
+ indices = slice(batch_size * 1, batch_size * 2)
1141
+
1142
+ # Prepare skip layer masks
1143
+ skip_layer_mask: Optional[torch.Tensor] = None
1144
+ if do_spatio_temporal_guidance:
1145
+ if skip_block_list is not None:
1146
+ skip_layer_mask = self.transformer.create_skip_layer_mask(
1147
+ batch_size, num_conds, num_conds - 1, skip_block_list[i]
1148
+ )
1149
+
1150
+ batch_pixel_coords = torch.cat([pixel_coords] * num_conds)
1151
+ conditioning_mask = orig_conditioning_mask
1152
+ if conditioning_mask is not None and is_video:
1153
+ assert num_images_per_prompt == 1
1154
+ conditioning_mask = torch.cat([conditioning_mask] * num_conds)
1155
+ fractional_coords = batch_pixel_coords.to(torch.float32)
1156
+ fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)
1157
+
1158
+ if conditioning_mask is not None and image_cond_noise_scale > 0.0:
1159
+ latents = self.add_noise_to_image_conditioning_latents(
1160
+ t,
1161
+ init_latents,
1162
+ latents,
1163
+ image_cond_noise_scale,
1164
+ orig_conditioning_mask,
1165
+ generator,
1166
+ )
1167
+
1168
+ latent_model_input = (
1169
+ torch.cat([latents] * num_conds) if num_conds > 1 else latents
1170
+ )
1171
+ latent_model_input = self.scheduler.scale_model_input(
1172
+ latent_model_input, t
1173
+ )
1174
+
1175
+ current_timestep = t
1176
+ if not torch.is_tensor(current_timestep):
1177
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1178
+ # This would be a good case for the `match` statement (Python 3.10+)
1179
+ is_mps = latent_model_input.device.type == "mps"
1180
+ if isinstance(current_timestep, float):
1181
+ dtype = torch.float32 if is_mps else torch.float64
1182
+ else:
1183
+ dtype = torch.int32 if is_mps else torch.int64
1184
+ current_timestep = torch.tensor(
1185
+ [current_timestep],
1186
+ dtype=dtype,
1187
+ device=latent_model_input.device,
1188
+ )
1189
+ elif len(current_timestep.shape) == 0:
1190
+ current_timestep = current_timestep[None].to(
1191
+ latent_model_input.device
1192
+ )
1193
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1194
+ current_timestep = current_timestep.expand(
1195
+ latent_model_input.shape[0]
1196
+ ).unsqueeze(-1)
1197
+
1198
+ if conditioning_mask is not None:
1199
+ # Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
1200
+ # and will start to be denoised when the current timestep is lower than their conditioning timestep.
1201
+ current_timestep = torch.min(
1202
+ current_timestep, 1.0 - conditioning_mask
1203
+ )
1204
+
1205
+ # Choose the appropriate context manager based on `mixed_precision`
1206
+ if mixed_precision:
1207
+ context_manager = torch.autocast(device.type, dtype=torch.bfloat16)
1208
+ else:
1209
+ context_manager = nullcontext() # Dummy context manager
1210
+
1211
+ # predict noise model_output
1212
+ with context_manager:
1213
+ noise_pred = self.transformer(
1214
+ latent_model_input.to(self.transformer.dtype),
1215
+ indices_grid=fractional_coords,
1216
+ encoder_hidden_states=prompt_embeds_batch[indices].to(
1217
+ self.transformer.dtype
1218
+ ),
1219
+ encoder_attention_mask=prompt_attention_mask_batch[indices],
1220
+ timestep=current_timestep,
1221
+ skip_layer_mask=skip_layer_mask,
1222
+ skip_layer_strategy=skip_layer_strategy,
1223
+ return_dict=False,
1224
+ )[0]
1225
+
1226
+ # perform guidance
1227
+ if do_spatio_temporal_guidance:
1228
+ noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(
1229
+ num_conds
1230
+ )[-2:]
1231
+ if do_classifier_free_guidance:
1232
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(num_conds)[:2]
1233
+
1234
+ if cfg_star_rescale:
1235
+ # Rescales the unconditional noise prediction using the projection of the conditional prediction onto it:
1236
+ # α = (⟨ε_text, ε_uncond⟩ / ||ε_uncond||²), then ε_uncond ← α * ε_uncond
1237
+ # where ε_text is the conditional noise prediction and ε_uncond is the unconditional one.
1238
+ positive_flat = noise_pred_text.view(batch_size, -1)
1239
+ negative_flat = noise_pred_uncond.view(batch_size, -1)
1240
+ dot_product = torch.sum(
1241
+ positive_flat * negative_flat, dim=1, keepdim=True
1242
+ )
1243
+ squared_norm = (
1244
+ torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
1245
+ )
1246
+ alpha = dot_product / squared_norm
1247
+ noise_pred_uncond = alpha * noise_pred_uncond
1248
+
1249
+ noise_pred = noise_pred_uncond + guidance_scale[i] * (
1250
+ noise_pred_text - noise_pred_uncond
1251
+ )
1252
+ elif do_spatio_temporal_guidance:
1253
+ noise_pred = noise_pred_text
1254
+ if do_spatio_temporal_guidance:
1255
+ noise_pred = noise_pred + stg_scale[i] * (
1256
+ noise_pred_text - noise_pred_text_perturb
1257
+ )
1258
+ if do_rescaling and stg_scale[i] > 0.0:
1259
+ noise_pred_text_std = noise_pred_text.view(batch_size, -1).std(
1260
+ dim=1, keepdim=True
1261
+ )
1262
+ noise_pred_std = noise_pred.view(batch_size, -1).std(
1263
+ dim=1, keepdim=True
1264
+ )
1265
+
1266
+ factor = noise_pred_text_std / noise_pred_std
1267
+ factor = rescaling_scale[i] * factor + (1 - rescaling_scale[i])
1268
+
1269
+ noise_pred = noise_pred * factor.view(batch_size, 1, 1)
1270
+
1271
+ current_timestep = current_timestep[:1]
1272
+ # learned sigma
1273
+ if (
1274
+ self.transformer.config.out_channels // 2
1275
+ == self.transformer.config.in_channels
1276
+ ):
1277
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1278
+
1279
+ # compute previous image: x_t -> x_t-1
1280
+ latents = self.denoising_step(
1281
+ latents,
1282
+ noise_pred,
1283
+ current_timestep,
1284
+ orig_conditioning_mask,
1285
+ t,
1286
+ extra_step_kwargs,
1287
+ stochastic_sampling=stochastic_sampling,
1288
+ )
1289
+
1290
+ # call the callback, if provided
1291
+ if i == len(timesteps) - 1 or (
1292
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1293
+ ):
1294
+ progress_bar.update()
1295
+
1296
+ if callback_on_step_end is not None:
1297
+ callback_on_step_end(self, i, t, {})
1298
+
1299
+ if offload_to_cpu:
1300
+ self.transformer = self.transformer.cpu()
1301
+ if self._execution_device == "cuda":
1302
+ torch.cuda.empty_cache()
1303
+
1304
+ # Remove the added conditioning latents
1305
+ latents = latents[:, num_cond_latents:]
1306
+
1307
+ latents = self.patchifier.unpatchify(
1308
+ latents=latents,
1309
+ output_height=latent_height,
1310
+ output_width=latent_width,
1311
+ out_channels=self.transformer.in_channels
1312
+ // math.prod(self.patchifier.patch_size),
1313
+ )
1314
+ if output_type != "latent":
1315
+ if self.vae.decoder.timestep_conditioning:
1316
+ noise = torch.randn_like(latents)
1317
+ if not isinstance(decode_timestep, list):
1318
+ decode_timestep = [decode_timestep] * latents.shape[0]
1319
+ if decode_noise_scale is None:
1320
+ decode_noise_scale = decode_timestep
1321
+ elif not isinstance(decode_noise_scale, list):
1322
+ decode_noise_scale = [decode_noise_scale] * latents.shape[0]
1323
+
1324
+ decode_timestep = torch.tensor(decode_timestep).to(latents.device)
1325
+ decode_noise_scale = torch.tensor(decode_noise_scale).to(
1326
+ latents.device
1327
+ )[:, None, None, None, None]
1328
+ latents = (
1329
+ latents * (1 - decode_noise_scale) + noise * decode_noise_scale
1330
+ )
1331
+ else:
1332
+ decode_timestep = None
1333
+ latents = self.tone_map_latents(latents, tone_map_compression_ratio)
1334
+ image = vae_decode(
1335
+ latents,
1336
+ self.vae,
1337
+ is_video,
1338
+ vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],
1339
+ timestep=decode_timestep,
1340
+ )
1341
+
1342
+ image = self.image_processor.postprocess(image, output_type=output_type)
1343
+
1344
+ else:
1345
+ image = latents
1346
+
1347
+ # Offload all models
1348
+ self.maybe_free_model_hooks()
1349
+
1350
+ if not return_dict:
1351
+ return (image,)
1352
+
1353
+ return ImagePipelineOutput(images=image)
1354
+
1355
+ def denoising_step(
1356
+ self,
1357
+ latents: torch.Tensor,
1358
+ noise_pred: torch.Tensor,
1359
+ current_timestep: torch.Tensor,
1360
+ conditioning_mask: torch.Tensor,
1361
+ t: float,
1362
+ extra_step_kwargs,
1363
+ t_eps=1e-6,
1364
+ stochastic_sampling=False,
1365
+ ):
1366
+ """
1367
+ Perform the denoising step for the required tokens, based on the current timestep and
1368
+ conditioning mask:
1369
+ Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
1370
+ and will start to be denoised when the current timestep is equal or lower than their
1371
+ conditioning timestep.
1372
+ (hard-conditioning latents with conditioning_mask = 1.0 are never denoised)
1373
+ """
1374
+ # Denoise the latents using the scheduler
1375
+ denoised_latents = self.scheduler.step(
1376
+ noise_pred,
1377
+ t if current_timestep is None else current_timestep,
1378
+ latents,
1379
+ **extra_step_kwargs,
1380
+ return_dict=False,
1381
+ stochastic_sampling=stochastic_sampling,
1382
+ )[0]
1383
+
1384
+ if conditioning_mask is None:
1385
+ return denoised_latents
1386
+
1387
+ tokens_to_denoise_mask = (t - t_eps < (1.0 - conditioning_mask)).unsqueeze(-1)
1388
+ return torch.where(tokens_to_denoise_mask, denoised_latents, latents)
1389
+
1390
+ def prepare_conditioning(
1391
+ self,
1392
+ conditioning_items: Optional[List[ConditioningItem]],
1393
+ init_latents: torch.Tensor,
1394
+ num_frames: int,
1395
+ height: int,
1396
+ width: int,
1397
+ vae_per_channel_normalize: bool = False,
1398
+ generator=None,
1399
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
1400
+ """
1401
+ Prepare conditioning tokens based on the provided conditioning items.
1402
+
1403
+ This method encodes provided conditioning items (video frames or single frames) into latents
1404
+ and integrates them with the initial latent tensor. It also calculates corresponding pixel
1405
+ coordinates, a mask indicating the influence of conditioning latents, and the total number of
1406
+ conditioning latents.
1407
+
1408
+ Args:
1409
+ conditioning_items (Optional[List[ConditioningItem]]): A list of ConditioningItem objects.
1410
+ init_latents (torch.Tensor): The initial latent tensor of shape (b, c, f_l, h_l, w_l), where
1411
+ `f_l` is the number of latent frames, and `h_l` and `w_l` are latent spatial dimensions.
1412
+ num_frames, height, width: The dimensions of the generated video.
1413
+ vae_per_channel_normalize (bool, optional): Whether to normalize channels during VAE encoding.
1414
+ Defaults to `False`.
1415
+ generator: The random generator
1416
+
1417
+ Returns:
1418
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
1419
+ - `init_latents` (torch.Tensor): The updated latent tensor including conditioning latents,
1420
+ patchified into (b, n, c) shape.
1421
+ - `init_pixel_coords` (torch.Tensor): The pixel coordinates corresponding to the updated
1422
+ latent tensor.
1423
+ - `conditioning_mask` (torch.Tensor): A mask indicating the conditioning-strength of each
1424
+ latent token.
1425
+ - `num_cond_latents` (int): The total number of latent tokens added from conditioning items.
1426
+
1427
+ Raises:
1428
+ AssertionError: If input shapes, dimensions, or conditions for applying conditioning are invalid.
1429
+ """
1430
+ assert isinstance(self.vae, CausalVideoAutoencoder)
1431
+
1432
+ if conditioning_items:
1433
+ batch_size, _, num_latent_frames = init_latents.shape[:3]
1434
+
1435
+ init_conditioning_mask = torch.zeros(
1436
+ init_latents[:, 0, :, :, :].shape,
1437
+ dtype=torch.float32,
1438
+ device=init_latents.device,
1439
+ )
1440
+
1441
+ extra_conditioning_latents = []
1442
+ extra_conditioning_pixel_coords = []
1443
+ extra_conditioning_mask = []
1444
+ extra_conditioning_num_latents = 0 # Number of extra conditioning latents added (should be removed before decoding)
1445
+
1446
+ # Process each conditioning item
1447
+ for conditioning_item in conditioning_items:
1448
+ conditioning_item = self._resize_conditioning_item(
1449
+ conditioning_item, height, width
1450
+ )
1451
+ media_item = conditioning_item.media_item
1452
+ media_frame_number = conditioning_item.media_frame_number
1453
+ strength = conditioning_item.conditioning_strength
1454
+ assert media_item.ndim == 5 # (b, c, f, h, w)
1455
+ b, c, n_frames, h, w = media_item.shape
1456
+ assert (
1457
+ height == h and width == w
1458
+ ) or media_frame_number == 0, f"Dimensions do not match: {height}x{width} != {h}x{w} - allowed only when media_frame_number == 0"
1459
+ assert n_frames % 8 == 1
1460
+ assert (
1461
+ media_frame_number >= 0
1462
+ and media_frame_number + n_frames <= num_frames
1463
+ )
1464
+
1465
+ # Encode the provided conditioning media item
1466
+ media_item_latents = vae_encode(
1467
+ media_item.to(dtype=self.vae.dtype, device=self.vae.device),
1468
+ self.vae,
1469
+ vae_per_channel_normalize=vae_per_channel_normalize,
1470
+ ).to(dtype=init_latents.dtype)
1471
+
1472
+ # Handle the different conditioning cases
1473
+ if media_frame_number == 0:
1474
+ # Get the target spatial position of the latent conditioning item
1475
+ media_item_latents, l_x, l_y = self._get_latent_spatial_position(
1476
+ media_item_latents,
1477
+ conditioning_item,
1478
+ height,
1479
+ width,
1480
+ strip_latent_border=True,
1481
+ )
1482
+ b, c_l, f_l, h_l, w_l = media_item_latents.shape
1483
+
1484
+ # First frame or sequence - just update the initial noise latents and the mask
1485
+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l] = (
1486
+ torch.lerp(
1487
+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l],
1488
+ media_item_latents,
1489
+ strength,
1490
+ )
1491
+ )
1492
+ init_conditioning_mask[
1493
+ :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l
1494
+ ] = strength
1495
+ else:
1496
+ # Non-first frame or sequence
1497
+ if n_frames > 1:
1498
+ # Handle non-first sequence.
1499
+ # Encoded latents are either fully consumed, or the prefix is handled separately below.
1500
+ (
1501
+ init_latents,
1502
+ init_conditioning_mask,
1503
+ media_item_latents,
1504
+ ) = self._handle_non_first_conditioning_sequence(
1505
+ init_latents,
1506
+ init_conditioning_mask,
1507
+ media_item_latents,
1508
+ media_frame_number,
1509
+ strength,
1510
+ )
1511
+
1512
+ # Single frame or sequence-prefix latents
1513
+ if media_item_latents is not None:
1514
+ noise = randn_tensor(
1515
+ media_item_latents.shape,
1516
+ generator=generator,
1517
+ device=media_item_latents.device,
1518
+ dtype=media_item_latents.dtype,
1519
+ )
1520
+
1521
+ media_item_latents = torch.lerp(
1522
+ noise, media_item_latents, strength
1523
+ )
1524
+
1525
+ # Patchify the extra conditioning latents and calculate their pixel coordinates
1526
+ media_item_latents, latent_coords = self.patchifier.patchify(
1527
+ latents=media_item_latents
1528
+ )
1529
+ pixel_coords = latent_to_pixel_coords(
1530
+ latent_coords,
1531
+ self.vae,
1532
+ causal_fix=self.transformer.config.causal_temporal_positioning,
1533
+ )
1534
+
1535
+ # Update the frame numbers to match the target frame number
1536
+ pixel_coords[:, 0] += media_frame_number
1537
+ extra_conditioning_num_latents += media_item_latents.shape[1]
1538
+
1539
+ conditioning_mask = torch.full(
1540
+ media_item_latents.shape[:2],
1541
+ strength,
1542
+ dtype=torch.float32,
1543
+ device=init_latents.device,
1544
+ )
1545
+
1546
+ extra_conditioning_latents.append(media_item_latents)
1547
+ extra_conditioning_pixel_coords.append(pixel_coords)
1548
+ extra_conditioning_mask.append(conditioning_mask)
1549
+
1550
+ # Patchify the updated latents and calculate their pixel coordinates
1551
+ init_latents, init_latent_coords = self.patchifier.patchify(
1552
+ latents=init_latents
1553
+ )
1554
+ init_pixel_coords = latent_to_pixel_coords(
1555
+ init_latent_coords,
1556
+ self.vae,
1557
+ causal_fix=self.transformer.config.causal_temporal_positioning,
1558
+ )
1559
+
1560
+ if not conditioning_items:
1561
+ return init_latents, init_pixel_coords, None, 0
1562
+
1563
+ init_conditioning_mask, _ = self.patchifier.patchify(
1564
+ latents=init_conditioning_mask.unsqueeze(1)
1565
+ )
1566
+ init_conditioning_mask = init_conditioning_mask.squeeze(-1)
1567
+
1568
+ if extra_conditioning_latents:
1569
+ # Stack the extra conditioning latents, pixel coordinates and mask
1570
+ init_latents = torch.cat([*extra_conditioning_latents, init_latents], dim=1)
1571
+ init_pixel_coords = torch.cat(
1572
+ [*extra_conditioning_pixel_coords, init_pixel_coords], dim=2
1573
+ )
1574
+ init_conditioning_mask = torch.cat(
1575
+ [*extra_conditioning_mask, init_conditioning_mask], dim=1
1576
+ )
1577
+
1578
+ if self.transformer.use_tpu_flash_attention:
1579
+ # When flash attention is used, keep the original number of tokens by removing
1580
+ # tokens from the end.
1581
+ init_latents = init_latents[:, :-extra_conditioning_num_latents]
1582
+ init_pixel_coords = init_pixel_coords[
1583
+ :, :, :-extra_conditioning_num_latents
1584
+ ]
1585
+ init_conditioning_mask = init_conditioning_mask[
1586
+ :, :-extra_conditioning_num_latents
1587
+ ]
1588
+
1589
+ return (
1590
+ init_latents,
1591
+ init_pixel_coords,
1592
+ init_conditioning_mask,
1593
+ extra_conditioning_num_latents,
1594
+ )
1595
+
1596
+ @staticmethod
1597
+ def _resize_conditioning_item(
1598
+ conditioning_item: ConditioningItem,
1599
+ height: int,
1600
+ width: int,
1601
+ ):
1602
+ if conditioning_item.media_x or conditioning_item.media_y:
1603
+ raise ValueError(
1604
+ "Provide media_item in the target size for spatial conditioning."
1605
+ )
1606
+ new_conditioning_item = copy.copy(conditioning_item)
1607
+ new_conditioning_item.media_item = LTXVideoPipeline.resize_tensor(
1608
+ conditioning_item.media_item, height, width
1609
+ )
1610
+ return new_conditioning_item
1611
+
1612
+ def _get_latent_spatial_position(
1613
+ self,
1614
+ latents: torch.Tensor,
1615
+ conditioning_item: ConditioningItem,
1616
+ height: int,
1617
+ width: int,
1618
+ strip_latent_border,
1619
+ ):
1620
+ """
1621
+ Get the spatial position of the conditioning item in the latent space.
1622
+ If requested, strip the conditioning latent borders that do not align with target borders.
1623
+ (border latents look different then other latents and might confuse the model)
1624
+ """
1625
+ scale = self.vae_scale_factor
1626
+ h, w = conditioning_item.media_item.shape[-2:]
1627
+ assert (
1628
+ h <= height and w <= width
1629
+ ), f"Conditioning item size {h}x{w} is larger than target size {height}x{width}"
1630
+ assert h % scale == 0 and w % scale == 0
1631
+
1632
+ # Compute the start and end spatial positions of the media item
1633
+ x_start, y_start = conditioning_item.media_x, conditioning_item.media_y
1634
+ x_start = (width - w) // 2 if x_start is None else x_start
1635
+ y_start = (height - h) // 2 if y_start is None else y_start
1636
+ x_end, y_end = x_start + w, y_start + h
1637
+ assert (
1638
+ x_end <= width and y_end <= height
1639
+ ), f"Conditioning item {x_start}:{x_end}x{y_start}:{y_end} is out of bounds for target size {width}x{height}"
1640
+
1641
+ if strip_latent_border:
1642
+ # Strip one latent from left/right and/or top/bottom, update x, y accordingly
1643
+ if x_start > 0:
1644
+ x_start += scale
1645
+ latents = latents[:, :, :, :, 1:]
1646
+
1647
+ if y_start > 0:
1648
+ y_start += scale
1649
+ latents = latents[:, :, :, 1:, :]
1650
+
1651
+ if x_end < width:
1652
+ latents = latents[:, :, :, :, :-1]
1653
+
1654
+ if y_end < height:
1655
+ latents = latents[:, :, :, :-1, :]
1656
+
1657
+ return latents, x_start // scale, y_start // scale
1658
+
1659
+ @staticmethod
1660
+ def _handle_non_first_conditioning_sequence(
1661
+ init_latents: torch.Tensor,
1662
+ init_conditioning_mask: torch.Tensor,
1663
+ latents: torch.Tensor,
1664
+ media_frame_number: int,
1665
+ strength: float,
1666
+ num_prefix_latent_frames: int = 2,
1667
+ prefix_latents_mode: str = "concat",
1668
+ prefix_soft_conditioning_strength: float = 0.15,
1669
+ ):
1670
+ """
1671
+ Special handling for a conditioning sequence that does not start on the first frame.
1672
+ The special handling is required to allow a short encoded video to be used as middle
1673
+ (or last) sequence in a longer video.
1674
+ Args:
1675
+ init_latents (torch.Tensor): The initial noise latents to be updated.
1676
+ init_conditioning_mask (torch.Tensor): The initial conditioning mask to be updated.
1677
+ latents (torch.Tensor): The encoded conditioning item.
1678
+ media_frame_number (int): The target frame number of the first frame in the conditioning sequence.
1679
+ strength (float): The conditioning strength for the conditioning latents.
1680
+ num_prefix_latent_frames (int, optional): The length of the sequence prefix, to be handled
1681
+ separately. Defaults to 2.
1682
+ prefix_latents_mode (str, optional): Special treatment for prefix (boundary) latents.
1683
+ - "drop": Drop the prefix latents.
1684
+ - "soft": Use the prefix latents, but with soft-conditioning
1685
+ - "concat": Add the prefix latents as extra tokens (like single frames)
1686
+ prefix_soft_conditioning_strength (float, optional): The strength of the soft-conditioning for
1687
+ the prefix latents, relevant if `prefix_latents_mode` is "soft". Defaults to 0.1.
1688
+
1689
+ """
1690
+ f_l = latents.shape[2]
1691
+ f_l_p = num_prefix_latent_frames
1692
+ assert f_l >= f_l_p
1693
+ assert media_frame_number % 8 == 0
1694
+ if f_l > f_l_p:
1695
+ # Insert the conditioning latents **excluding the prefix** into the sequence
1696
+ f_l_start = media_frame_number // 8 + f_l_p
1697
+ f_l_end = f_l_start + f_l - f_l_p
1698
+ init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
1699
+ init_latents[:, :, f_l_start:f_l_end],
1700
+ latents[:, :, f_l_p:],
1701
+ strength,
1702
+ )
1703
+ # Mark these latent frames as conditioning latents
1704
+ init_conditioning_mask[:, f_l_start:f_l_end] = strength
1705
+
1706
+ # Handle the prefix-latents
1707
+ if prefix_latents_mode == "soft":
1708
+ if f_l_p > 1:
1709
+ # Drop the first (single-frame) latent and soft-condition the remaining prefix
1710
+ f_l_start = media_frame_number // 8 + 1
1711
+ f_l_end = f_l_start + f_l_p - 1
1712
+ strength = min(prefix_soft_conditioning_strength, strength)
1713
+ init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
1714
+ init_latents[:, :, f_l_start:f_l_end],
1715
+ latents[:, :, 1:f_l_p],
1716
+ strength,
1717
+ )
1718
+ # Mark these latent frames as conditioning latents
1719
+ init_conditioning_mask[:, f_l_start:f_l_end] = strength
1720
+ latents = None # No more latents to handle
1721
+ elif prefix_latents_mode == "drop":
1722
+ # Drop the prefix latents
1723
+ latents = None
1724
+ elif prefix_latents_mode == "concat":
1725
+ # Pass-on the prefix latents to be handled as extra conditioning frames
1726
+ latents = latents[:, :, :f_l_p]
1727
+ else:
1728
+ raise ValueError(f"Invalid prefix_latents_mode: {prefix_latents_mode}")
1729
+ return (
1730
+ init_latents,
1731
+ init_conditioning_mask,
1732
+ latents,
1733
+ )
1734
+
1735
+ def trim_conditioning_sequence(
1736
+ self, start_frame: int, sequence_num_frames: int, target_num_frames: int
1737
+ ):
1738
+ """
1739
+ Trim a conditioning sequence to the allowed number of frames.
1740
+
1741
+ Args:
1742
+ start_frame (int): The target frame number of the first frame in the sequence.
1743
+ sequence_num_frames (int): The number of frames in the sequence.
1744
+ target_num_frames (int): The target number of frames in the generated video.
1745
+
1746
+ Returns:
1747
+ int: updated sequence length
1748
+ """
1749
+ scale_factor = self.video_scale_factor
1750
+ num_frames = min(sequence_num_frames, target_num_frames - start_frame)
1751
+ # Trim down to a multiple of temporal_scale_factor frames plus 1
1752
+ num_frames = (num_frames - 1) // scale_factor * scale_factor + 1
1753
+ return num_frames
1754
+
1755
+ @staticmethod
1756
+ def tone_map_latents(
1757
+ latents: torch.Tensor,
1758
+ compression: float,
1759
+ ) -> torch.Tensor:
1760
+ """
1761
+ Applies a non-linear tone-mapping function to latent values to reduce their dynamic range
1762
+ in a perceptually smooth way using a sigmoid-based compression.
1763
+
1764
+ This is useful for regularizing high-variance latents or for conditioning outputs
1765
+ during generation, especially when controlling dynamic behavior with a `compression` factor.
1766
+
1767
+ Parameters:
1768
+ ----------
1769
+ latents : torch.Tensor
1770
+ Input latent tensor with arbitrary shape. Expected to be roughly in [-1, 1] or [0, 1] range.
1771
+ compression : float
1772
+ Compression strength in the range [0, 1].
1773
+ - 0.0: No tone-mapping (identity transform)
1774
+ - 1.0: Full compression effect
1775
+
1776
+ Returns:
1777
+ -------
1778
+ torch.Tensor
1779
+ The tone-mapped latent tensor of the same shape as input.
1780
+ """
1781
+ if not (0 <= compression <= 1):
1782
+ raise ValueError("Compression must be in the range [0, 1]")
1783
+
1784
+ # Remap [0-1] to [0-0.75] and apply sigmoid compression in one shot
1785
+ scale_factor = compression * 0.75
1786
+ abs_latents = torch.abs(latents)
1787
+
1788
+ # Sigmoid compression: sigmoid shifts large values toward 0.2, small values stay ~1.0
1789
+ # When scale_factor=0, sigmoid term vanishes, when scale_factor=0.75, full effect
1790
+ sigmoid_term = torch.sigmoid(4.0 * scale_factor * (abs_latents - 1.0))
1791
+ scales = 1.0 - 0.8 * scale_factor * sigmoid_term
1792
+
1793
+ filtered = latents * scales
1794
+ return filtered
1795
+
1796
+
1797
+ def adain_filter_latent(
1798
+ latents: torch.Tensor, reference_latents: torch.Tensor, factor=1.0
1799
+ ):
1800
+ """
1801
+ Applies Adaptive Instance Normalization (AdaIN) to a latent tensor based on
1802
+ statistics from a reference latent tensor.
1803
+
1804
+ Args:
1805
+ latent (torch.Tensor): Input latents to normalize
1806
+ reference_latent (torch.Tensor): The reference latents providing style statistics.
1807
+ factor (float): Blending factor between original and transformed latent.
1808
+ Range: -10.0 to 10.0, Default: 1.0
1809
+
1810
+ Returns:
1811
+ torch.Tensor: The transformed latent tensor
1812
+ """
1813
+ result = latents.clone()
1814
+
1815
+ for i in range(latents.size(0)):
1816
+ for c in range(latents.size(1)):
1817
+ r_sd, r_mean = torch.std_mean(
1818
+ reference_latents[i, c], dim=None
1819
+ ) # index by original dim order
1820
+ i_sd, i_mean = torch.std_mean(result[i, c], dim=None)
1821
+
1822
+ result[i, c] = ((result[i, c] - i_mean) / i_sd) * r_sd + r_mean
1823
+
1824
+ result = torch.lerp(latents, result, factor)
1825
+ return result
1826
+
1827
+
1828
+ class LTXMultiScalePipeline:
1829
+ def _upsample_latents(
1830
+ self, latest_upsampler: LatentUpsampler, latents: torch.Tensor
1831
+ ):
1832
+ assert latents.device == latest_upsampler.device
1833
+
1834
+ latents = un_normalize_latents(
1835
+ latents, self.vae, vae_per_channel_normalize=True
1836
+ )
1837
+ upsampled_latents = latest_upsampler(latents)
1838
+ upsampled_latents = normalize_latents(
1839
+ upsampled_latents, self.vae, vae_per_channel_normalize=True
1840
+ )
1841
+ return upsampled_latents
1842
+
1843
+ def __init__(
1844
+ self, video_pipeline: LTXVideoPipeline, latent_upsampler: LatentUpsampler
1845
+ ):
1846
+ self.video_pipeline = video_pipeline
1847
+ self.vae = video_pipeline.vae
1848
+ self.latent_upsampler = latent_upsampler
1849
+
1850
+ def __call__(
1851
+ self,
1852
+ downscale_factor: float,
1853
+ first_pass: dict,
1854
+ second_pass: dict,
1855
+ *args: Any,
1856
+ **kwargs: Any,
1857
+ ) -> Any:
1858
+ original_kwargs = kwargs.copy()
1859
+ original_output_type = kwargs["output_type"]
1860
+ original_width = kwargs["width"]
1861
+ original_height = kwargs["height"]
1862
+
1863
+ x_width = int(kwargs["width"] * downscale_factor)
1864
+ downscaled_width = x_width - (x_width % self.video_pipeline.vae_scale_factor)
1865
+ x_height = int(kwargs["height"] * downscale_factor)
1866
+ downscaled_height = x_height - (x_height % self.video_pipeline.vae_scale_factor)
1867
+
1868
+ kwargs["output_type"] = "latent"
1869
+ kwargs["width"] = downscaled_width
1870
+ kwargs["height"] = downscaled_height
1871
+ kwargs.update(**first_pass)
1872
+ result = self.video_pipeline(*args, **kwargs)
1873
+ latents = result.images
1874
+
1875
+ upsampled_latents = self._upsample_latents(self.latent_upsampler, latents)
1876
+ upsampled_latents = adain_filter_latent(
1877
+ latents=upsampled_latents, reference_latents=latents
1878
+ )
1879
+
1880
+ kwargs = original_kwargs
1881
+
1882
+ kwargs["latents"] = upsampled_latents
1883
+ kwargs["output_type"] = original_output_type
1884
+ kwargs["width"] = downscaled_width * 2
1885
+ kwargs["height"] = downscaled_height * 2
1886
+ kwargs.update(**second_pass)
1887
+
1888
+ result = self.video_pipeline(*args, **kwargs)
1889
+ if original_output_type != "latent":
1890
+ num_frames = result.images.shape[2]
1891
+ videos = rearrange(result.images, "b c f h w -> (b f) c h w")
1892
+
1893
+ videos = F.interpolate(
1894
+ videos,
1895
+ size=(original_height, original_width),
1896
+ mode="bilinear",
1897
+ align_corners=False,
1898
+ )
1899
+ videos = rearrange(videos, "(b f) c h w -> b c f h w", f=num_frames)
1900
+ result.images = videos
1901
+
1902
+ return result