eeuuia commited on
Commit
6c0add0
·
verified ·
1 Parent(s): 7db32ef

Upload pipeline_ltx_video (3).py

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