eeuuia commited on
Commit
eff5895
·
verified ·
1 Parent(s): 4300db6

Upload pipeline_ltx_video (2).py

Browse files
LTX-Video/ltx_video/pipelines/pipeline_ltx_video (2).py ADDED
@@ -0,0 +1,1895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if guidance_timesteps:
959
+ guidance_mapping = []
960
+ for timestep in timesteps:
961
+ indices = [
962
+ i for i, val in enumerate(guidance_timesteps) if val <= timestep
963
+ ]
964
+ # assert len(indices) > 0, f"No guidance timestep found for {timestep}"
965
+ guidance_mapping.append(
966
+ indices[0] if len(indices) > 0 else (len(guidance_timesteps) - 1)
967
+ )
968
+
969
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
970
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
971
+ # corresponds to doing no classifier free guidance.
972
+ if not isinstance(guidance_scale, List):
973
+ guidance_scale = [guidance_scale] * len(timesteps)
974
+ else:
975
+ guidance_scale = [
976
+ guidance_scale[guidance_mapping[i]] for i in range(len(timesteps))
977
+ ]
978
+
979
+ if not isinstance(stg_scale, List):
980
+ stg_scale = [stg_scale] * len(timesteps)
981
+ else:
982
+ stg_scale = [stg_scale[guidance_mapping[i]] for i in range(len(timesteps))]
983
+
984
+ if not isinstance(rescaling_scale, List):
985
+ rescaling_scale = [rescaling_scale] * len(timesteps)
986
+ else:
987
+ rescaling_scale = [
988
+ rescaling_scale[guidance_mapping[i]] for i in range(len(timesteps))
989
+ ]
990
+
991
+ # Normalize skip_block_list to always be None or a list of lists matching timesteps
992
+ if skip_block_list is not None:
993
+ # Convert single list to list of lists if needed
994
+ if len(skip_block_list) == 0 or not isinstance(skip_block_list[0], list):
995
+ skip_block_list = [skip_block_list] * len(timesteps)
996
+ else:
997
+ new_skip_block_list = []
998
+ for i, timestep in enumerate(timesteps):
999
+ new_skip_block_list.append(skip_block_list[guidance_mapping[i]])
1000
+ skip_block_list = new_skip_block_list
1001
+
1002
+ if enhance_prompt:
1003
+ self.prompt_enhancer_image_caption_model = (
1004
+ self.prompt_enhancer_image_caption_model.to(self._execution_device)
1005
+ )
1006
+ self.prompt_enhancer_llm_model = self.prompt_enhancer_llm_model.to(
1007
+ self._execution_device
1008
+ )
1009
+
1010
+ prompt = generate_cinematic_prompt(
1011
+ self.prompt_enhancer_image_caption_model,
1012
+ self.prompt_enhancer_image_caption_processor,
1013
+ self.prompt_enhancer_llm_model,
1014
+ self.prompt_enhancer_llm_tokenizer,
1015
+ prompt,
1016
+ conditioning_items,
1017
+ max_new_tokens=text_encoder_max_tokens,
1018
+ )
1019
+
1020
+ # 3. Encode input prompt
1021
+ if self.text_encoder is not None:
1022
+ self.text_encoder = self.text_encoder.to(self._execution_device)
1023
+
1024
+ (
1025
+ prompt_embeds,
1026
+ prompt_attention_mask,
1027
+ negative_prompt_embeds,
1028
+ negative_prompt_attention_mask,
1029
+ ) = self.encode_prompt(
1030
+ prompt,
1031
+ True,
1032
+ negative_prompt=negative_prompt,
1033
+ num_images_per_prompt=num_images_per_prompt,
1034
+ device=device,
1035
+ prompt_embeds=prompt_embeds,
1036
+ negative_prompt_embeds=negative_prompt_embeds,
1037
+ prompt_attention_mask=prompt_attention_mask,
1038
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
1039
+ text_encoder_max_tokens=text_encoder_max_tokens,
1040
+ )
1041
+
1042
+ if offload_to_cpu and self.text_encoder is not None:
1043
+ self.text_encoder = self.text_encoder.cpu()
1044
+
1045
+ self.transformer = self.transformer.to(self._execution_device)
1046
+
1047
+ prompt_embeds_batch = prompt_embeds
1048
+ prompt_attention_mask_batch = prompt_attention_mask
1049
+ negative_prompt_embeds = (
1050
+ torch.zeros_like(prompt_embeds)
1051
+ if negative_prompt_embeds is None
1052
+ else negative_prompt_embeds
1053
+ )
1054
+ negative_prompt_attention_mask = (
1055
+ torch.zeros_like(prompt_attention_mask)
1056
+ if negative_prompt_attention_mask is None
1057
+ else negative_prompt_attention_mask
1058
+ )
1059
+
1060
+ prompt_embeds_batch = torch.cat(
1061
+ [negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0
1062
+ )
1063
+ prompt_attention_mask_batch = torch.cat(
1064
+ [
1065
+ negative_prompt_attention_mask,
1066
+ prompt_attention_mask,
1067
+ prompt_attention_mask,
1068
+ ],
1069
+ dim=0,
1070
+ )
1071
+ # 4. Prepare the initial latents using the provided media and conditioning items
1072
+
1073
+ # Prepare the initial latents tensor, shape = (b, c, f, h, w)
1074
+ latents = self.prepare_latents(
1075
+ latents=latents,
1076
+ media_items=media_items,
1077
+ timestep=timesteps[0],
1078
+ latent_shape=latent_shape,
1079
+ dtype=prompt_embeds.dtype,
1080
+ device=device,
1081
+ generator=generator,
1082
+ vae_per_channel_normalize=vae_per_channel_normalize,
1083
+ )
1084
+
1085
+ # Update the latents with the conditioning items and patchify them into (b, n, c)
1086
+ latents, pixel_coords, conditioning_mask, num_cond_latents = (
1087
+ self.prepare_conditioning(
1088
+ conditioning_items=conditioning_items,
1089
+ init_latents=latents,
1090
+ num_frames=num_frames,
1091
+ height=height,
1092
+ width=width,
1093
+ vae_per_channel_normalize=vae_per_channel_normalize,
1094
+ generator=generator,
1095
+ )
1096
+ )
1097
+ init_latents = latents.clone() # Used for image_cond_noise_update
1098
+
1099
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1100
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1101
+
1102
+ # 7. Denoising loop
1103
+ num_warmup_steps = max(
1104
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
1105
+ )
1106
+
1107
+ orig_conditioning_mask = conditioning_mask
1108
+
1109
+ # Befor compiling this code please be aware:
1110
+ # This code might generate different input shapes if some timesteps have no STG or CFG.
1111
+ # This means that the codes might need to be compiled mutliple times.
1112
+ # To avoid that, use the same STG and CFG values for all timesteps.
1113
+
1114
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1115
+ for i, t in enumerate(timesteps):
1116
+ do_classifier_free_guidance = guidance_scale[i] > 1.0
1117
+ do_spatio_temporal_guidance = stg_scale[i] > 0
1118
+ do_rescaling = rescaling_scale[i] != 1.0
1119
+
1120
+ num_conds = 1
1121
+ if do_classifier_free_guidance:
1122
+ num_conds += 1
1123
+ if do_spatio_temporal_guidance:
1124
+ num_conds += 1
1125
+
1126
+ if do_classifier_free_guidance and do_spatio_temporal_guidance:
1127
+ indices = slice(batch_size * 0, batch_size * 3)
1128
+ elif do_classifier_free_guidance:
1129
+ indices = slice(batch_size * 0, batch_size * 2)
1130
+ elif do_spatio_temporal_guidance:
1131
+ indices = slice(batch_size * 1, batch_size * 3)
1132
+ else:
1133
+ indices = slice(batch_size * 1, batch_size * 2)
1134
+
1135
+ # Prepare skip layer masks
1136
+ skip_layer_mask: Optional[torch.Tensor] = None
1137
+ if do_spatio_temporal_guidance:
1138
+ if skip_block_list is not None:
1139
+ skip_layer_mask = self.transformer.create_skip_layer_mask(
1140
+ batch_size, num_conds, num_conds - 1, skip_block_list[i]
1141
+ )
1142
+
1143
+ batch_pixel_coords = torch.cat([pixel_coords] * num_conds)
1144
+ conditioning_mask = orig_conditioning_mask
1145
+ if conditioning_mask is not None and is_video:
1146
+ assert num_images_per_prompt == 1
1147
+ conditioning_mask = torch.cat([conditioning_mask] * num_conds)
1148
+ fractional_coords = batch_pixel_coords.to(torch.float32)
1149
+ fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)
1150
+
1151
+ if conditioning_mask is not None and image_cond_noise_scale > 0.0:
1152
+ latents = self.add_noise_to_image_conditioning_latents(
1153
+ t,
1154
+ init_latents,
1155
+ latents,
1156
+ image_cond_noise_scale,
1157
+ orig_conditioning_mask,
1158
+ generator,
1159
+ )
1160
+
1161
+ latent_model_input = (
1162
+ torch.cat([latents] * num_conds) if num_conds > 1 else latents
1163
+ )
1164
+ latent_model_input = self.scheduler.scale_model_input(
1165
+ latent_model_input, t
1166
+ )
1167
+
1168
+ current_timestep = t
1169
+ if not torch.is_tensor(current_timestep):
1170
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1171
+ # This would be a good case for the `match` statement (Python 3.10+)
1172
+ is_mps = latent_model_input.device.type == "mps"
1173
+ if isinstance(current_timestep, float):
1174
+ dtype = torch.float32 if is_mps else torch.float64
1175
+ else:
1176
+ dtype = torch.int32 if is_mps else torch.int64
1177
+ current_timestep = torch.tensor(
1178
+ [current_timestep],
1179
+ dtype=dtype,
1180
+ device=latent_model_input.device,
1181
+ )
1182
+ elif len(current_timestep.shape) == 0:
1183
+ current_timestep = current_timestep[None].to(
1184
+ latent_model_input.device
1185
+ )
1186
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1187
+ current_timestep = current_timestep.expand(
1188
+ latent_model_input.shape[0]
1189
+ ).unsqueeze(-1)
1190
+
1191
+ if conditioning_mask is not None:
1192
+ # Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
1193
+ # and will start to be denoised when the current timestep is lower than their conditioning timestep.
1194
+ current_timestep = torch.min(
1195
+ current_timestep, 1.0 - conditioning_mask
1196
+ )
1197
+
1198
+ # Choose the appropriate context manager based on `mixed_precision`
1199
+ if mixed_precision:
1200
+ context_manager = torch.autocast(device.type, dtype=torch.bfloat16)
1201
+ else:
1202
+ context_manager = nullcontext() # Dummy context manager
1203
+
1204
+ # predict noise model_output
1205
+ with context_manager:
1206
+ noise_pred = self.transformer(
1207
+ latent_model_input.to(self.transformer.dtype),
1208
+ indices_grid=fractional_coords,
1209
+ encoder_hidden_states=prompt_embeds_batch[indices].to(
1210
+ self.transformer.dtype
1211
+ ),
1212
+ encoder_attention_mask=prompt_attention_mask_batch[indices],
1213
+ timestep=current_timestep,
1214
+ skip_layer_mask=skip_layer_mask,
1215
+ skip_layer_strategy=skip_layer_strategy,
1216
+ return_dict=False,
1217
+ )[0]
1218
+
1219
+ # perform guidance
1220
+ if do_spatio_temporal_guidance:
1221
+ noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(
1222
+ num_conds
1223
+ )[-2:]
1224
+ if do_classifier_free_guidance:
1225
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(num_conds)[:2]
1226
+
1227
+ if cfg_star_rescale:
1228
+ # Rescales the unconditional noise prediction using the projection of the conditional prediction onto it:
1229
+ # α = (⟨ε_text, ε_uncond⟩ / ||ε_uncond||²), then ε_uncond ← α * ε_uncond
1230
+ # where ε_text is the conditional noise prediction and ε_uncond is the unconditional one.
1231
+ positive_flat = noise_pred_text.view(batch_size, -1)
1232
+ negative_flat = noise_pred_uncond.view(batch_size, -1)
1233
+ dot_product = torch.sum(
1234
+ positive_flat * negative_flat, dim=1, keepdim=True
1235
+ )
1236
+ squared_norm = (
1237
+ torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
1238
+ )
1239
+ alpha = dot_product / squared_norm
1240
+ noise_pred_uncond = alpha * noise_pred_uncond
1241
+
1242
+ noise_pred = noise_pred_uncond + guidance_scale[i] * (
1243
+ noise_pred_text - noise_pred_uncond
1244
+ )
1245
+ elif do_spatio_temporal_guidance:
1246
+ noise_pred = noise_pred_text
1247
+ if do_spatio_temporal_guidance:
1248
+ noise_pred = noise_pred + stg_scale[i] * (
1249
+ noise_pred_text - noise_pred_text_perturb
1250
+ )
1251
+ if do_rescaling and stg_scale[i] > 0.0:
1252
+ noise_pred_text_std = noise_pred_text.view(batch_size, -1).std(
1253
+ dim=1, keepdim=True
1254
+ )
1255
+ noise_pred_std = noise_pred.view(batch_size, -1).std(
1256
+ dim=1, keepdim=True
1257
+ )
1258
+
1259
+ factor = noise_pred_text_std / noise_pred_std
1260
+ factor = rescaling_scale[i] * factor + (1 - rescaling_scale[i])
1261
+
1262
+ noise_pred = noise_pred * factor.view(batch_size, 1, 1)
1263
+
1264
+ current_timestep = current_timestep[:1]
1265
+ # learned sigma
1266
+ if (
1267
+ self.transformer.config.out_channels // 2
1268
+ == self.transformer.config.in_channels
1269
+ ):
1270
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1271
+
1272
+ # compute previous image: x_t -> x_t-1
1273
+ latents = self.denoising_step(
1274
+ latents,
1275
+ noise_pred,
1276
+ current_timestep,
1277
+ orig_conditioning_mask,
1278
+ t,
1279
+ extra_step_kwargs,
1280
+ stochastic_sampling=stochastic_sampling,
1281
+ )
1282
+
1283
+ # call the callback, if provided
1284
+ if i == len(timesteps) - 1 or (
1285
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1286
+ ):
1287
+ progress_bar.update()
1288
+
1289
+ if callback_on_step_end is not None:
1290
+ callback_on_step_end(self, i, t, {})
1291
+
1292
+ if offload_to_cpu:
1293
+ self.transformer = self.transformer.cpu()
1294
+ if self._execution_device == "cuda":
1295
+ torch.cuda.empty_cache()
1296
+
1297
+ # Remove the added conditioning latents
1298
+ latents = latents[:, num_cond_latents:]
1299
+
1300
+ latents = self.patchifier.unpatchify(
1301
+ latents=latents,
1302
+ output_height=latent_height,
1303
+ output_width=latent_width,
1304
+ out_channels=self.transformer.in_channels
1305
+ // math.prod(self.patchifier.patch_size),
1306
+ )
1307
+ if output_type != "latent":
1308
+ if self.vae.decoder.timestep_conditioning:
1309
+ noise = torch.randn_like(latents)
1310
+ if not isinstance(decode_timestep, list):
1311
+ decode_timestep = [decode_timestep] * latents.shape[0]
1312
+ if decode_noise_scale is None:
1313
+ decode_noise_scale = decode_timestep
1314
+ elif not isinstance(decode_noise_scale, list):
1315
+ decode_noise_scale = [decode_noise_scale] * latents.shape[0]
1316
+
1317
+ decode_timestep = torch.tensor(decode_timestep).to(latents.device)
1318
+ decode_noise_scale = torch.tensor(decode_noise_scale).to(
1319
+ latents.device
1320
+ )[:, None, None, None, None]
1321
+ latents = (
1322
+ latents * (1 - decode_noise_scale) + noise * decode_noise_scale
1323
+ )
1324
+ else:
1325
+ decode_timestep = None
1326
+ latents = self.tone_map_latents(latents, tone_map_compression_ratio)
1327
+ image = vae_decode(
1328
+ latents,
1329
+ self.vae,
1330
+ is_video,
1331
+ vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],
1332
+ timestep=decode_timestep,
1333
+ )
1334
+
1335
+ image = self.image_processor.postprocess(image, output_type=output_type)
1336
+
1337
+ else:
1338
+ image = latents
1339
+
1340
+ # Offload all models
1341
+ self.maybe_free_model_hooks()
1342
+
1343
+ if not return_dict:
1344
+ return (image,)
1345
+
1346
+ return ImagePipelineOutput(images=image)
1347
+
1348
+ def denoising_step(
1349
+ self,
1350
+ latents: torch.Tensor,
1351
+ noise_pred: torch.Tensor,
1352
+ current_timestep: torch.Tensor,
1353
+ conditioning_mask: torch.Tensor,
1354
+ t: float,
1355
+ extra_step_kwargs,
1356
+ t_eps=1e-6,
1357
+ stochastic_sampling=False,
1358
+ ):
1359
+ """
1360
+ Perform the denoising step for the required tokens, based on the current timestep and
1361
+ conditioning mask:
1362
+ Conditioning latents have an initial timestep and noising level of (1.0 - conditioning_mask)
1363
+ and will start to be denoised when the current timestep is equal or lower than their
1364
+ conditioning timestep.
1365
+ (hard-conditioning latents with conditioning_mask = 1.0 are never denoised)
1366
+ """
1367
+ # Denoise the latents using the scheduler
1368
+ denoised_latents = self.scheduler.step(
1369
+ noise_pred,
1370
+ t if current_timestep is None else current_timestep,
1371
+ latents,
1372
+ **extra_step_kwargs,
1373
+ return_dict=False,
1374
+ stochastic_sampling=stochastic_sampling,
1375
+ )[0]
1376
+
1377
+ if conditioning_mask is None:
1378
+ return denoised_latents
1379
+
1380
+ tokens_to_denoise_mask = (t - t_eps < (1.0 - conditioning_mask)).unsqueeze(-1)
1381
+ return torch.where(tokens_to_denoise_mask, denoised_latents, latents)
1382
+
1383
+ def prepare_conditioning(
1384
+ self,
1385
+ conditioning_items: Optional[List[ConditioningItem]],
1386
+ init_latents: torch.Tensor,
1387
+ num_frames: int,
1388
+ height: int,
1389
+ width: int,
1390
+ vae_per_channel_normalize: bool = False,
1391
+ generator=None,
1392
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
1393
+ """
1394
+ Prepare conditioning tokens based on the provided conditioning items.
1395
+
1396
+ This method encodes provided conditioning items (video frames or single frames) into latents
1397
+ and integrates them with the initial latent tensor. It also calculates corresponding pixel
1398
+ coordinates, a mask indicating the influence of conditioning latents, and the total number of
1399
+ conditioning latents.
1400
+
1401
+ Args:
1402
+ conditioning_items (Optional[List[ConditioningItem]]): A list of ConditioningItem objects.
1403
+ init_latents (torch.Tensor): The initial latent tensor of shape (b, c, f_l, h_l, w_l), where
1404
+ `f_l` is the number of latent frames, and `h_l` and `w_l` are latent spatial dimensions.
1405
+ num_frames, height, width: The dimensions of the generated video.
1406
+ vae_per_channel_normalize (bool, optional): Whether to normalize channels during VAE encoding.
1407
+ Defaults to `False`.
1408
+ generator: The random generator
1409
+
1410
+ Returns:
1411
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
1412
+ - `init_latents` (torch.Tensor): The updated latent tensor including conditioning latents,
1413
+ patchified into (b, n, c) shape.
1414
+ - `init_pixel_coords` (torch.Tensor): The pixel coordinates corresponding to the updated
1415
+ latent tensor.
1416
+ - `conditioning_mask` (torch.Tensor): A mask indicating the conditioning-strength of each
1417
+ latent token.
1418
+ - `num_cond_latents` (int): The total number of latent tokens added from conditioning items.
1419
+
1420
+ Raises:
1421
+ AssertionError: If input shapes, dimensions, or conditions for applying conditioning are invalid.
1422
+ """
1423
+ assert isinstance(self.vae, CausalVideoAutoencoder)
1424
+
1425
+ if conditioning_items:
1426
+ batch_size, _, num_latent_frames = init_latents.shape[:3]
1427
+
1428
+ init_conditioning_mask = torch.zeros(
1429
+ init_latents[:, 0, :, :, :].shape,
1430
+ dtype=torch.float32,
1431
+ device=init_latents.device,
1432
+ )
1433
+
1434
+ extra_conditioning_latents = []
1435
+ extra_conditioning_pixel_coords = []
1436
+ extra_conditioning_mask = []
1437
+ extra_conditioning_num_latents = 0 # Number of extra conditioning latents added (should be removed before decoding)
1438
+
1439
+ # Process each conditioning item
1440
+ for conditioning_item in conditioning_items:
1441
+ conditioning_item = self._resize_conditioning_item(
1442
+ conditioning_item, height, width
1443
+ )
1444
+ media_item = conditioning_item.media_item
1445
+ media_frame_number = conditioning_item.media_frame_number
1446
+ strength = conditioning_item.conditioning_strength
1447
+ assert media_item.ndim == 5 # (b, c, f, h, w)
1448
+ b, c, n_frames, h, w = media_item.shape
1449
+ assert (
1450
+ height == h and width == w
1451
+ ) or media_frame_number == 0, f"Dimensions do not match: {height}x{width} != {h}x{w} - allowed only when media_frame_number == 0"
1452
+ assert n_frames % 8 == 1
1453
+ assert (
1454
+ media_frame_number >= 0
1455
+ and media_frame_number + n_frames <= num_frames
1456
+ )
1457
+
1458
+ # Encode the provided conditioning media item
1459
+ media_item_latents = vae_encode(
1460
+ media_item.to(dtype=self.vae.dtype, device=self.vae.device),
1461
+ self.vae,
1462
+ vae_per_channel_normalize=vae_per_channel_normalize,
1463
+ ).to(dtype=init_latents.dtype)
1464
+
1465
+ # Handle the different conditioning cases
1466
+ if media_frame_number == 0:
1467
+ # Get the target spatial position of the latent conditioning item
1468
+ media_item_latents, l_x, l_y = self._get_latent_spatial_position(
1469
+ media_item_latents,
1470
+ conditioning_item,
1471
+ height,
1472
+ width,
1473
+ strip_latent_border=True,
1474
+ )
1475
+ b, c_l, f_l, h_l, w_l = media_item_latents.shape
1476
+
1477
+ # First frame or sequence - just update the initial noise latents and the mask
1478
+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l] = (
1479
+ torch.lerp(
1480
+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l],
1481
+ media_item_latents,
1482
+ strength,
1483
+ )
1484
+ )
1485
+ init_conditioning_mask[
1486
+ :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l
1487
+ ] = strength
1488
+ else:
1489
+ # Non-first frame or sequence
1490
+ if n_frames > 1:
1491
+ # Handle non-first sequence.
1492
+ # Encoded latents are either fully consumed, or the prefix is handled separately below.
1493
+ (
1494
+ init_latents,
1495
+ init_conditioning_mask,
1496
+ media_item_latents,
1497
+ ) = self._handle_non_first_conditioning_sequence(
1498
+ init_latents,
1499
+ init_conditioning_mask,
1500
+ media_item_latents,
1501
+ media_frame_number,
1502
+ strength,
1503
+ )
1504
+
1505
+ # Single frame or sequence-prefix latents
1506
+ if media_item_latents is not None:
1507
+ noise = randn_tensor(
1508
+ media_item_latents.shape,
1509
+ generator=generator,
1510
+ device=media_item_latents.device,
1511
+ dtype=media_item_latents.dtype,
1512
+ )
1513
+
1514
+ media_item_latents = torch.lerp(
1515
+ noise, media_item_latents, strength
1516
+ )
1517
+
1518
+ # Patchify the extra conditioning latents and calculate their pixel coordinates
1519
+ media_item_latents, latent_coords = self.patchifier.patchify(
1520
+ latents=media_item_latents
1521
+ )
1522
+ pixel_coords = latent_to_pixel_coords(
1523
+ latent_coords,
1524
+ self.vae,
1525
+ causal_fix=self.transformer.config.causal_temporal_positioning,
1526
+ )
1527
+
1528
+ # Update the frame numbers to match the target frame number
1529
+ pixel_coords[:, 0] += media_frame_number
1530
+ extra_conditioning_num_latents += media_item_latents.shape[1]
1531
+
1532
+ conditioning_mask = torch.full(
1533
+ media_item_latents.shape[:2],
1534
+ strength,
1535
+ dtype=torch.float32,
1536
+ device=init_latents.device,
1537
+ )
1538
+
1539
+ extra_conditioning_latents.append(media_item_latents)
1540
+ extra_conditioning_pixel_coords.append(pixel_coords)
1541
+ extra_conditioning_mask.append(conditioning_mask)
1542
+
1543
+ # Patchify the updated latents and calculate their pixel coordinates
1544
+ init_latents, init_latent_coords = self.patchifier.patchify(
1545
+ latents=init_latents
1546
+ )
1547
+ init_pixel_coords = latent_to_pixel_coords(
1548
+ init_latent_coords,
1549
+ self.vae,
1550
+ causal_fix=self.transformer.config.causal_temporal_positioning,
1551
+ )
1552
+
1553
+ if not conditioning_items:
1554
+ return init_latents, init_pixel_coords, None, 0
1555
+
1556
+ init_conditioning_mask, _ = self.patchifier.patchify(
1557
+ latents=init_conditioning_mask.unsqueeze(1)
1558
+ )
1559
+ init_conditioning_mask = init_conditioning_mask.squeeze(-1)
1560
+
1561
+ if extra_conditioning_latents:
1562
+ # Stack the extra conditioning latents, pixel coordinates and mask
1563
+ init_latents = torch.cat([*extra_conditioning_latents, init_latents], dim=1)
1564
+ init_pixel_coords = torch.cat(
1565
+ [*extra_conditioning_pixel_coords, init_pixel_coords], dim=2
1566
+ )
1567
+ init_conditioning_mask = torch.cat(
1568
+ [*extra_conditioning_mask, init_conditioning_mask], dim=1
1569
+ )
1570
+
1571
+ if self.transformer.use_tpu_flash_attention:
1572
+ # When flash attention is used, keep the original number of tokens by removing
1573
+ # tokens from the end.
1574
+ init_latents = init_latents[:, :-extra_conditioning_num_latents]
1575
+ init_pixel_coords = init_pixel_coords[
1576
+ :, :, :-extra_conditioning_num_latents
1577
+ ]
1578
+ init_conditioning_mask = init_conditioning_mask[
1579
+ :, :-extra_conditioning_num_latents
1580
+ ]
1581
+
1582
+ return (
1583
+ init_latents,
1584
+ init_pixel_coords,
1585
+ init_conditioning_mask,
1586
+ extra_conditioning_num_latents,
1587
+ )
1588
+
1589
+ @staticmethod
1590
+ def _resize_conditioning_item(
1591
+ conditioning_item: ConditioningItem,
1592
+ height: int,
1593
+ width: int,
1594
+ ):
1595
+ if conditioning_item.media_x or conditioning_item.media_y:
1596
+ raise ValueError(
1597
+ "Provide media_item in the target size for spatial conditioning."
1598
+ )
1599
+ new_conditioning_item = copy.copy(conditioning_item)
1600
+ new_conditioning_item.media_item = LTXVideoPipeline.resize_tensor(
1601
+ conditioning_item.media_item, height, width
1602
+ )
1603
+ return new_conditioning_item
1604
+
1605
+ def _get_latent_spatial_position(
1606
+ self,
1607
+ latents: torch.Tensor,
1608
+ conditioning_item: ConditioningItem,
1609
+ height: int,
1610
+ width: int,
1611
+ strip_latent_border,
1612
+ ):
1613
+ """
1614
+ Get the spatial position of the conditioning item in the latent space.
1615
+ If requested, strip the conditioning latent borders that do not align with target borders.
1616
+ (border latents look different then other latents and might confuse the model)
1617
+ """
1618
+ scale = self.vae_scale_factor
1619
+ h, w = conditioning_item.media_item.shape[-2:]
1620
+ assert (
1621
+ h <= height and w <= width
1622
+ ), f"Conditioning item size {h}x{w} is larger than target size {height}x{width}"
1623
+ assert h % scale == 0 and w % scale == 0
1624
+
1625
+ # Compute the start and end spatial positions of the media item
1626
+ x_start, y_start = conditioning_item.media_x, conditioning_item.media_y
1627
+ x_start = (width - w) // 2 if x_start is None else x_start
1628
+ y_start = (height - h) // 2 if y_start is None else y_start
1629
+ x_end, y_end = x_start + w, y_start + h
1630
+ assert (
1631
+ x_end <= width and y_end <= height
1632
+ ), f"Conditioning item {x_start}:{x_end}x{y_start}:{y_end} is out of bounds for target size {width}x{height}"
1633
+
1634
+ if strip_latent_border:
1635
+ # Strip one latent from left/right and/or top/bottom, update x, y accordingly
1636
+ if x_start > 0:
1637
+ x_start += scale
1638
+ latents = latents[:, :, :, :, 1:]
1639
+
1640
+ if y_start > 0:
1641
+ y_start += scale
1642
+ latents = latents[:, :, :, 1:, :]
1643
+
1644
+ if x_end < width:
1645
+ latents = latents[:, :, :, :, :-1]
1646
+
1647
+ if y_end < height:
1648
+ latents = latents[:, :, :, :-1, :]
1649
+
1650
+ return latents, x_start // scale, y_start // scale
1651
+
1652
+ @staticmethod
1653
+ def _handle_non_first_conditioning_sequence(
1654
+ init_latents: torch.Tensor,
1655
+ init_conditioning_mask: torch.Tensor,
1656
+ latents: torch.Tensor,
1657
+ media_frame_number: int,
1658
+ strength: float,
1659
+ num_prefix_latent_frames: int = 2,
1660
+ prefix_latents_mode: str = "concat",
1661
+ prefix_soft_conditioning_strength: float = 0.15,
1662
+ ):
1663
+ """
1664
+ Special handling for a conditioning sequence that does not start on the first frame.
1665
+ The special handling is required to allow a short encoded video to be used as middle
1666
+ (or last) sequence in a longer video.
1667
+ Args:
1668
+ init_latents (torch.Tensor): The initial noise latents to be updated.
1669
+ init_conditioning_mask (torch.Tensor): The initial conditioning mask to be updated.
1670
+ latents (torch.Tensor): The encoded conditioning item.
1671
+ media_frame_number (int): The target frame number of the first frame in the conditioning sequence.
1672
+ strength (float): The conditioning strength for the conditioning latents.
1673
+ num_prefix_latent_frames (int, optional): The length of the sequence prefix, to be handled
1674
+ separately. Defaults to 2.
1675
+ prefix_latents_mode (str, optional): Special treatment for prefix (boundary) latents.
1676
+ - "drop": Drop the prefix latents.
1677
+ - "soft": Use the prefix latents, but with soft-conditioning
1678
+ - "concat": Add the prefix latents as extra tokens (like single frames)
1679
+ prefix_soft_conditioning_strength (float, optional): The strength of the soft-conditioning for
1680
+ the prefix latents, relevant if `prefix_latents_mode` is "soft". Defaults to 0.1.
1681
+
1682
+ """
1683
+ f_l = latents.shape[2]
1684
+ f_l_p = num_prefix_latent_frames
1685
+ assert f_l >= f_l_p
1686
+ assert media_frame_number % 8 == 0
1687
+ if f_l > f_l_p:
1688
+ # Insert the conditioning latents **excluding the prefix** into the sequence
1689
+ f_l_start = media_frame_number // 8 + f_l_p
1690
+ f_l_end = f_l_start + f_l - f_l_p
1691
+ init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
1692
+ init_latents[:, :, f_l_start:f_l_end],
1693
+ latents[:, :, f_l_p:],
1694
+ strength,
1695
+ )
1696
+ # Mark these latent frames as conditioning latents
1697
+ init_conditioning_mask[:, f_l_start:f_l_end] = strength
1698
+
1699
+ # Handle the prefix-latents
1700
+ if prefix_latents_mode == "soft":
1701
+ if f_l_p > 1:
1702
+ # Drop the first (single-frame) latent and soft-condition the remaining prefix
1703
+ f_l_start = media_frame_number // 8 + 1
1704
+ f_l_end = f_l_start + f_l_p - 1
1705
+ strength = min(prefix_soft_conditioning_strength, strength)
1706
+ init_latents[:, :, f_l_start:f_l_end] = torch.lerp(
1707
+ init_latents[:, :, f_l_start:f_l_end],
1708
+ latents[:, :, 1:f_l_p],
1709
+ strength,
1710
+ )
1711
+ # Mark these latent frames as conditioning latents
1712
+ init_conditioning_mask[:, f_l_start:f_l_end] = strength
1713
+ latents = None # No more latents to handle
1714
+ elif prefix_latents_mode == "drop":
1715
+ # Drop the prefix latents
1716
+ latents = None
1717
+ elif prefix_latents_mode == "concat":
1718
+ # Pass-on the prefix latents to be handled as extra conditioning frames
1719
+ latents = latents[:, :, :f_l_p]
1720
+ else:
1721
+ raise ValueError(f"Invalid prefix_latents_mode: {prefix_latents_mode}")
1722
+ return (
1723
+ init_latents,
1724
+ init_conditioning_mask,
1725
+ latents,
1726
+ )
1727
+
1728
+ def trim_conditioning_sequence(
1729
+ self, start_frame: int, sequence_num_frames: int, target_num_frames: int
1730
+ ):
1731
+ """
1732
+ Trim a conditioning sequence to the allowed number of frames.
1733
+
1734
+ Args:
1735
+ start_frame (int): The target frame number of the first frame in the sequence.
1736
+ sequence_num_frames (int): The number of frames in the sequence.
1737
+ target_num_frames (int): The target number of frames in the generated video.
1738
+
1739
+ Returns:
1740
+ int: updated sequence length
1741
+ """
1742
+ scale_factor = self.video_scale_factor
1743
+ num_frames = min(sequence_num_frames, target_num_frames - start_frame)
1744
+ # Trim down to a multiple of temporal_scale_factor frames plus 1
1745
+ num_frames = (num_frames - 1) // scale_factor * scale_factor + 1
1746
+ return num_frames
1747
+
1748
+ @staticmethod
1749
+ def tone_map_latents(
1750
+ latents: torch.Tensor,
1751
+ compression: float,
1752
+ ) -> torch.Tensor:
1753
+ """
1754
+ Applies a non-linear tone-mapping function to latent values to reduce their dynamic range
1755
+ in a perceptually smooth way using a sigmoid-based compression.
1756
+
1757
+ This is useful for regularizing high-variance latents or for conditioning outputs
1758
+ during generation, especially when controlling dynamic behavior with a `compression` factor.
1759
+
1760
+ Parameters:
1761
+ ----------
1762
+ latents : torch.Tensor
1763
+ Input latent tensor with arbitrary shape. Expected to be roughly in [-1, 1] or [0, 1] range.
1764
+ compression : float
1765
+ Compression strength in the range [0, 1].
1766
+ - 0.0: No tone-mapping (identity transform)
1767
+ - 1.0: Full compression effect
1768
+
1769
+ Returns:
1770
+ -------
1771
+ torch.Tensor
1772
+ The tone-mapped latent tensor of the same shape as input.
1773
+ """
1774
+ if not (0 <= compression <= 1):
1775
+ raise ValueError("Compression must be in the range [0, 1]")
1776
+
1777
+ # Remap [0-1] to [0-0.75] and apply sigmoid compression in one shot
1778
+ scale_factor = compression * 0.75
1779
+ abs_latents = torch.abs(latents)
1780
+
1781
+ # Sigmoid compression: sigmoid shifts large values toward 0.2, small values stay ~1.0
1782
+ # When scale_factor=0, sigmoid term vanishes, when scale_factor=0.75, full effect
1783
+ sigmoid_term = torch.sigmoid(4.0 * scale_factor * (abs_latents - 1.0))
1784
+ scales = 1.0 - 0.8 * scale_factor * sigmoid_term
1785
+
1786
+ filtered = latents * scales
1787
+ return filtered
1788
+
1789
+
1790
+ def adain_filter_latent(
1791
+ latents: torch.Tensor, reference_latents: torch.Tensor, factor=1.0
1792
+ ):
1793
+ """
1794
+ Applies Adaptive Instance Normalization (AdaIN) to a latent tensor based on
1795
+ statistics from a reference latent tensor.
1796
+
1797
+ Args:
1798
+ latent (torch.Tensor): Input latents to normalize
1799
+ reference_latent (torch.Tensor): The reference latents providing style statistics.
1800
+ factor (float): Blending factor between original and transformed latent.
1801
+ Range: -10.0 to 10.0, Default: 1.0
1802
+
1803
+ Returns:
1804
+ torch.Tensor: The transformed latent tensor
1805
+ """
1806
+ result = latents.clone()
1807
+
1808
+ for i in range(latents.size(0)):
1809
+ for c in range(latents.size(1)):
1810
+ r_sd, r_mean = torch.std_mean(
1811
+ reference_latents[i, c], dim=None
1812
+ ) # index by original dim order
1813
+ i_sd, i_mean = torch.std_mean(result[i, c], dim=None)
1814
+
1815
+ result[i, c] = ((result[i, c] - i_mean) / i_sd) * r_sd + r_mean
1816
+
1817
+ result = torch.lerp(latents, result, factor)
1818
+ return result
1819
+
1820
+
1821
+ class LTXMultiScalePipeline:
1822
+ def _upsample_latents(
1823
+ self, latest_upsampler: LatentUpsampler, latents: torch.Tensor
1824
+ ):
1825
+ assert latents.device == latest_upsampler.device
1826
+
1827
+ latents = un_normalize_latents(
1828
+ latents, self.vae, vae_per_channel_normalize=True
1829
+ )
1830
+ upsampled_latents = latest_upsampler(latents)
1831
+ upsampled_latents = normalize_latents(
1832
+ upsampled_latents, self.vae, vae_per_channel_normalize=True
1833
+ )
1834
+ return upsampled_latents
1835
+
1836
+ def __init__(
1837
+ self, video_pipeline: LTXVideoPipeline, latent_upsampler: LatentUpsampler
1838
+ ):
1839
+ self.video_pipeline = video_pipeline
1840
+ self.vae = video_pipeline.vae
1841
+ self.latent_upsampler = latent_upsampler
1842
+
1843
+ def __call__(
1844
+ self,
1845
+ downscale_factor: float,
1846
+ first_pass: dict,
1847
+ second_pass: dict,
1848
+ *args: Any,
1849
+ **kwargs: Any,
1850
+ ) -> Any:
1851
+ original_kwargs = kwargs.copy()
1852
+ original_output_type = kwargs["output_type"]
1853
+ original_width = kwargs["width"]
1854
+ original_height = kwargs["height"]
1855
+
1856
+ x_width = int(kwargs["width"] * downscale_factor)
1857
+ downscaled_width = x_width - (x_width % self.video_pipeline.vae_scale_factor)
1858
+ x_height = int(kwargs["height"] * downscale_factor)
1859
+ downscaled_height = x_height - (x_height % self.video_pipeline.vae_scale_factor)
1860
+
1861
+ kwargs["output_type"] = "latent"
1862
+ kwargs["width"] = downscaled_width
1863
+ kwargs["height"] = downscaled_height
1864
+ kwargs.update(**first_pass)
1865
+ result = self.video_pipeline(*args, **kwargs)
1866
+ latents = result.images
1867
+
1868
+ upsampled_latents = self._upsample_latents(self.latent_upsampler, latents)
1869
+ upsampled_latents = adain_filter_latent(
1870
+ latents=upsampled_latents, reference_latents=latents
1871
+ )
1872
+
1873
+ kwargs = original_kwargs
1874
+
1875
+ kwargs["latents"] = upsampled_latents
1876
+ kwargs["output_type"] = original_output_type
1877
+ kwargs["width"] = downscaled_width * 2
1878
+ kwargs["height"] = downscaled_height * 2
1879
+ kwargs.update(**second_pass)
1880
+
1881
+ result = self.video_pipeline(*args, **kwargs)
1882
+ if original_output_type != "latent":
1883
+ num_frames = result.images.shape[2]
1884
+ videos = rearrange(result.images, "b c f h w -> (b f) c h w")
1885
+
1886
+ videos = F.interpolate(
1887
+ videos,
1888
+ size=(original_height, original_width),
1889
+ mode="bilinear",
1890
+ align_corners=False,
1891
+ )
1892
+ videos = rearrange(videos, "(b f) c h w -> b c f h w", f=num_frames)
1893
+ result.images = videos
1894
+
1895
+ return result