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
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import inspect
|
16 |
+
from dataclasses import dataclass
|
17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18 |
+
|
19 |
+
import PIL.Image
|
20 |
+
import torch
|
21 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
22 |
+
from diffusers.image_processor import PipelineImageInput
|
23 |
+
from diffusers.loaders import FromSingleFileMixin, LTXVideoLoraLoaderMixin
|
24 |
+
from diffusers.models.autoencoders import AutoencoderKLLTXVideo
|
25 |
+
from diffusers.models.transformers import LTXVideoTransformer3DModel
|
26 |
+
from diffusers.pipelines.ltx.pipeline_output import LTXPipelineOutput
|
27 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
28 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
29 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
30 |
+
from diffusers.utils.torch_utils import randn_tensor
|
31 |
+
from diffusers.video_processor import VideoProcessor
|
32 |
+
from transformers import T5EncoderModel, T5TokenizerFast
|
33 |
+
from torchvision.transforms.functional import center_crop, resize
|
34 |
+
|
35 |
+
if is_torch_xla_available():
|
36 |
+
import torch_xla.core.xla_model as xm
|
37 |
+
|
38 |
+
XLA_AVAILABLE = True
|
39 |
+
else:
|
40 |
+
XLA_AVAILABLE = False
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
43 |
+
|
44 |
+
EXAMPLE_DOC_STRING = """
|
45 |
+
Examples:
|
46 |
+
```py
|
47 |
+
>>> import torch
|
48 |
+
>>> from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXConditionPipeline, LTXVideoCondition
|
49 |
+
>>> from diffusers.utils import export_to_video, load_video, load_image
|
50 |
+
|
51 |
+
>>> pipe = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.5", torch_dtype=torch.bfloat16)
|
52 |
+
>>> pipe.to("cuda")
|
53 |
+
|
54 |
+
>>> # Load input image and video
|
55 |
+
>>> video = load_video(
|
56 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
|
57 |
+
... )
|
58 |
+
>>> image = load_image(
|
59 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
|
60 |
+
... )
|
61 |
+
|
62 |
+
>>> # Create conditioning objects
|
63 |
+
>>> condition1 = LTXVideoCondition(
|
64 |
+
... image=image,
|
65 |
+
... frame_index=0,
|
66 |
+
... )
|
67 |
+
>>> condition2 = LTXVideoCondition(
|
68 |
+
... video=video,
|
69 |
+
... frame_index=80,
|
70 |
+
... )
|
71 |
+
|
72 |
+
>>> prompt = "The video depicts a long, straight highway stretching into the distance, flanked by metal guardrails. The road is divided into multiple lanes, with a few vehicles visible in the far distance. The surrounding landscape features dry, grassy fields on one side and rolling hills on the other. The sky is mostly clear with a few scattered clouds, suggesting a bright, sunny day. And then the camera switch to a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region."
|
73 |
+
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
|
74 |
+
|
75 |
+
>>> # Generate video
|
76 |
+
>>> generator = torch.Generator("cuda").manual_seed(0)
|
77 |
+
>>> # Text-only conditioning is also supported without the need to pass `conditions`
|
78 |
+
>>> video = pipe(
|
79 |
+
... conditions=[condition1, condition2],
|
80 |
+
... prompt=prompt,
|
81 |
+
... negative_prompt=negative_prompt,
|
82 |
+
... width=768,
|
83 |
+
... height=512,
|
84 |
+
... num_frames=161,
|
85 |
+
... num_inference_steps=40,
|
86 |
+
... generator=generator,
|
87 |
+
... ).frames[0]
|
88 |
+
|
89 |
+
>>> export_to_video(video, "output.mp4", fps=24)
|
90 |
+
```
|
91 |
+
"""
|
92 |
+
|
93 |
+
|
94 |
+
@dataclass
|
95 |
+
class LTXVideoCondition:
|
96 |
+
"""
|
97 |
+
Defines a single frame-conditioning item for LTX Video - a single frame or a sequence of frames.
|
98 |
+
|
99 |
+
Attributes:
|
100 |
+
image (`PIL.Image.Image`):
|
101 |
+
The image to condition the video on.
|
102 |
+
video (`List[PIL.Image.Image]`):
|
103 |
+
The video to condition the video on.
|
104 |
+
frame_index (`int`):
|
105 |
+
The frame index at which the image or video will conditionally effect the video generation.
|
106 |
+
strength (`float`, defaults to `1.0`):
|
107 |
+
The strength of the conditioning effect. A value of `1.0` means the conditioning effect is fully applied.
|
108 |
+
"""
|
109 |
+
|
110 |
+
image: Optional[PIL.Image.Image] = None
|
111 |
+
video: Optional[List[PIL.Image.Image]] = None
|
112 |
+
frame_index: int = 0
|
113 |
+
strength: float = 1.0
|
114 |
+
|
115 |
+
|
116 |
+
# from LTX-Video/ltx_video/schedulers/rf.py
|
117 |
+
def linear_quadratic_schedule(num_steps, threshold_noise=0.025, linear_steps=None):
|
118 |
+
if linear_steps is None:
|
119 |
+
linear_steps = num_steps // 2
|
120 |
+
if num_steps < 2:
|
121 |
+
return torch.tensor([1.0])
|
122 |
+
linear_sigma_schedule = [i * threshold_noise / linear_steps for i in range(linear_steps)]
|
123 |
+
threshold_noise_step_diff = linear_steps - threshold_noise * num_steps
|
124 |
+
quadratic_steps = num_steps - linear_steps
|
125 |
+
quadratic_coef = threshold_noise_step_diff / (linear_steps * quadratic_steps**2)
|
126 |
+
linear_coef = threshold_noise / linear_steps - 2 * threshold_noise_step_diff / (quadratic_steps**2)
|
127 |
+
const = quadratic_coef * (linear_steps**2)
|
128 |
+
quadratic_sigma_schedule = [
|
129 |
+
quadratic_coef * (i**2) + linear_coef * i + const for i in range(linear_steps, num_steps)
|
130 |
+
]
|
131 |
+
sigma_schedule = linear_sigma_schedule + quadratic_sigma_schedule + [1.0]
|
132 |
+
sigma_schedule = [1.0 - x for x in sigma_schedule]
|
133 |
+
return torch.tensor(sigma_schedule[:-1])
|
134 |
+
|
135 |
+
|
136 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
137 |
+
def calculate_shift(
|
138 |
+
image_seq_len,
|
139 |
+
base_seq_len: int = 256,
|
140 |
+
max_seq_len: int = 4096,
|
141 |
+
base_shift: float = 0.5,
|
142 |
+
max_shift: float = 1.15,
|
143 |
+
):
|
144 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
145 |
+
b = base_shift - m * base_seq_len
|
146 |
+
mu = image_seq_len * m + b
|
147 |
+
return mu
|
148 |
+
|
149 |
+
|
150 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
151 |
+
def retrieve_timesteps(
|
152 |
+
scheduler,
|
153 |
+
num_inference_steps: Optional[int] = None,
|
154 |
+
device: Optional[Union[str, torch.device]] = None,
|
155 |
+
timesteps: Optional[List[int]] = None,
|
156 |
+
sigmas: Optional[List[float]] = None,
|
157 |
+
**kwargs,
|
158 |
+
):
|
159 |
+
r"""
|
160 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
161 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
162 |
+
|
163 |
+
Args:
|
164 |
+
scheduler (`SchedulerMixin`):
|
165 |
+
The scheduler to get timesteps from.
|
166 |
+
num_inference_steps (`int`):
|
167 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
168 |
+
must be `None`.
|
169 |
+
device (`str` or `torch.device`, *optional*):
|
170 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
171 |
+
timesteps (`List[int]`, *optional*):
|
172 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
173 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
174 |
+
sigmas (`List[float]`, *optional*):
|
175 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
176 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
177 |
+
|
178 |
+
Returns:
|
179 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
180 |
+
second element is the number of inference steps.
|
181 |
+
"""
|
182 |
+
if timesteps is not None and sigmas is not None:
|
183 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
184 |
+
if timesteps is not None:
|
185 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
186 |
+
if not accepts_timesteps:
|
187 |
+
raise ValueError(
|
188 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
189 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
190 |
+
)
|
191 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
192 |
+
timesteps = scheduler.timesteps
|
193 |
+
num_inference_steps = len(timesteps)
|
194 |
+
elif sigmas is not None:
|
195 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
196 |
+
if not accept_sigmas:
|
197 |
+
raise ValueError(
|
198 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
199 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
200 |
+
)
|
201 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
202 |
+
timesteps = scheduler.timesteps
|
203 |
+
num_inference_steps = len(timesteps)
|
204 |
+
else:
|
205 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
206 |
+
timesteps = scheduler.timesteps
|
207 |
+
return timesteps, num_inference_steps
|
208 |
+
|
209 |
+
|
210 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
211 |
+
def retrieve_latents(
|
212 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
213 |
+
):
|
214 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
215 |
+
return encoder_output.latent_dist.sample(generator)
|
216 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
217 |
+
return encoder_output.latent_dist.mode()
|
218 |
+
elif hasattr(encoder_output, "latents"):
|
219 |
+
return encoder_output.latents
|
220 |
+
else:
|
221 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
222 |
+
|
223 |
+
|
224 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
225 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
226 |
+
r"""
|
227 |
+
Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
|
228 |
+
Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
|
229 |
+
Flawed](https://huggingface.co/papers/2305.08891).
|
230 |
+
|
231 |
+
Args:
|
232 |
+
noise_cfg (`torch.Tensor`):
|
233 |
+
The predicted noise tensor for the guided diffusion process.
|
234 |
+
noise_pred_text (`torch.Tensor`):
|
235 |
+
The predicted noise tensor for the text-guided diffusion process.
|
236 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
237 |
+
A rescale factor applied to the noise predictions.
|
238 |
+
|
239 |
+
Returns:
|
240 |
+
noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
|
241 |
+
"""
|
242 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
243 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
244 |
+
# rescale the results from guidance (fixes overexposure)
|
245 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
246 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
247 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
248 |
+
return noise_cfg
|
249 |
+
|
250 |
+
|
251 |
+
class LTXConditionPipeline(DiffusionPipeline, FromSingleFileMixin, LTXVideoLoraLoaderMixin):
|
252 |
+
r"""
|
253 |
+
Pipeline for text/image/video-to-video generation.
|
254 |
+
|
255 |
+
Reference: https://github.com/Lightricks/LTX-Video
|
256 |
+
|
257 |
+
Args:
|
258 |
+
transformer ([`LTXVideoTransformer3DModel`]):
|
259 |
+
Conditional Transformer architecture to denoise the encoded video latents.
|
260 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
261 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
262 |
+
vae ([`AutoencoderKLLTXVideo`]):
|
263 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
264 |
+
text_encoder ([`T5EncoderModel`]):
|
265 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
266 |
+
the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
267 |
+
tokenizer (`CLIPTokenizer`):
|
268 |
+
Tokenizer of class
|
269 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
270 |
+
tokenizer (`T5TokenizerFast`):
|
271 |
+
Second Tokenizer of class
|
272 |
+
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
|
273 |
+
"""
|
274 |
+
|
275 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
276 |
+
_optional_components = []
|
277 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
278 |
+
|
279 |
+
def __init__(
|
280 |
+
self,
|
281 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
282 |
+
vae: AutoencoderKLLTXVideo,
|
283 |
+
text_encoder: T5EncoderModel,
|
284 |
+
tokenizer: T5TokenizerFast,
|
285 |
+
transformer: LTXVideoTransformer3DModel,
|
286 |
+
):
|
287 |
+
super().__init__()
|
288 |
+
|
289 |
+
self.register_modules(
|
290 |
+
vae=vae,
|
291 |
+
text_encoder=text_encoder,
|
292 |
+
tokenizer=tokenizer,
|
293 |
+
transformer=transformer,
|
294 |
+
scheduler=scheduler,
|
295 |
+
)
|
296 |
+
|
297 |
+
self.vae_spatial_compression_ratio = (
|
298 |
+
self.vae.spatial_compression_ratio if getattr(self, "vae", None) is not None else 32
|
299 |
+
)
|
300 |
+
self.vae_temporal_compression_ratio = (
|
301 |
+
self.vae.temporal_compression_ratio if getattr(self, "vae", None) is not None else 8
|
302 |
+
)
|
303 |
+
self.transformer_spatial_patch_size = (
|
304 |
+
self.transformer.config.patch_size if getattr(self, "transformer", None) is not None else 1
|
305 |
+
)
|
306 |
+
self.transformer_temporal_patch_size = (
|
307 |
+
self.transformer.config.patch_size_t if getattr(self, "transformer") is not None else 1
|
308 |
+
)
|
309 |
+
|
310 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_compression_ratio)
|
311 |
+
self.tokenizer_max_length = (
|
312 |
+
self.tokenizer.model_max_length if getattr(self, "tokenizer", None) is not None else 128
|
313 |
+
)
|
314 |
+
|
315 |
+
self.default_height = 512
|
316 |
+
self.default_width = 704
|
317 |
+
self.default_frames = 121
|
318 |
+
|
319 |
+
def _get_t5_prompt_embeds(
|
320 |
+
self,
|
321 |
+
prompt: Union[str, List[str]] = None,
|
322 |
+
num_videos_per_prompt: int = 1,
|
323 |
+
max_sequence_length: int = 256,
|
324 |
+
device: Optional[torch.device] = None,
|
325 |
+
dtype: Optional[torch.dtype] = None,
|
326 |
+
):
|
327 |
+
device = device or self._execution_device
|
328 |
+
dtype = dtype or self.text_encoder.dtype
|
329 |
+
|
330 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
331 |
+
batch_size = len(prompt)
|
332 |
+
|
333 |
+
text_inputs = self.tokenizer(
|
334 |
+
prompt,
|
335 |
+
padding="max_length",
|
336 |
+
max_length=max_sequence_length,
|
337 |
+
truncation=True,
|
338 |
+
add_special_tokens=True,
|
339 |
+
return_tensors="pt",
|
340 |
+
)
|
341 |
+
text_input_ids = text_inputs.input_ids
|
342 |
+
prompt_attention_mask = text_inputs.attention_mask
|
343 |
+
prompt_attention_mask = prompt_attention_mask.bool().to(device)
|
344 |
+
|
345 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
346 |
+
|
347 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
348 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
|
349 |
+
logger.warning(
|
350 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
351 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
352 |
+
)
|
353 |
+
|
354 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)[0]
|
355 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
356 |
+
|
357 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
358 |
+
_, seq_len, _ = prompt_embeds.shape
|
359 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
360 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
361 |
+
|
362 |
+
prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
|
363 |
+
prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1)
|
364 |
+
|
365 |
+
return prompt_embeds, prompt_attention_mask
|
366 |
+
|
367 |
+
# Copied from diffusers.pipelines.mochi.pipeline_mochi.MochiPipeline.encode_prompt
|
368 |
+
def encode_prompt(
|
369 |
+
self,
|
370 |
+
prompt: Union[str, List[str]],
|
371 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
372 |
+
do_classifier_free_guidance: bool = True,
|
373 |
+
num_videos_per_prompt: int = 1,
|
374 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
375 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
376 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
377 |
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
378 |
+
max_sequence_length: int = 256,
|
379 |
+
device: Optional[torch.device] = None,
|
380 |
+
dtype: Optional[torch.dtype] = None,
|
381 |
+
):
|
382 |
+
r"""
|
383 |
+
Encodes the prompt into text encoder hidden states.
|
384 |
+
|
385 |
+
Args:
|
386 |
+
prompt (`str` or `List[str]`, *optional*):
|
387 |
+
prompt to be encoded
|
388 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
389 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
390 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
391 |
+
less than `1`).
|
392 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
393 |
+
Whether to use classifier free guidance or not.
|
394 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
395 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
396 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
397 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
398 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
399 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
400 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
401 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
402 |
+
argument.
|
403 |
+
device: (`torch.device`, *optional*):
|
404 |
+
torch device
|
405 |
+
dtype: (`torch.dtype`, *optional*):
|
406 |
+
torch dtype
|
407 |
+
"""
|
408 |
+
device = device or self._execution_device
|
409 |
+
|
410 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
411 |
+
if prompt is not None:
|
412 |
+
batch_size = len(prompt)
|
413 |
+
else:
|
414 |
+
batch_size = prompt_embeds.shape[0]
|
415 |
+
|
416 |
+
if prompt_embeds is None:
|
417 |
+
prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
|
418 |
+
prompt=prompt,
|
419 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
420 |
+
max_sequence_length=max_sequence_length,
|
421 |
+
device=device,
|
422 |
+
dtype=dtype,
|
423 |
+
)
|
424 |
+
|
425 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
426 |
+
negative_prompt = negative_prompt or ""
|
427 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
428 |
+
|
429 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
430 |
+
raise TypeError(
|
431 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
432 |
+
f" {type(prompt)}."
|
433 |
+
)
|
434 |
+
elif batch_size != len(negative_prompt):
|
435 |
+
raise ValueError(
|
436 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
437 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
438 |
+
" the batch size of `prompt`."
|
439 |
+
)
|
440 |
+
|
441 |
+
negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
|
442 |
+
prompt=negative_prompt,
|
443 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
444 |
+
max_sequence_length=max_sequence_length,
|
445 |
+
device=device,
|
446 |
+
dtype=dtype,
|
447 |
+
)
|
448 |
+
|
449 |
+
return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
|
450 |
+
|
451 |
+
def check_inputs(
|
452 |
+
self,
|
453 |
+
prompt,
|
454 |
+
conditions,
|
455 |
+
image,
|
456 |
+
video,
|
457 |
+
frame_index,
|
458 |
+
strength,
|
459 |
+
denoise_strength,
|
460 |
+
height,
|
461 |
+
width,
|
462 |
+
callback_on_step_end_tensor_inputs=None,
|
463 |
+
prompt_embeds=None,
|
464 |
+
negative_prompt_embeds=None,
|
465 |
+
prompt_attention_mask=None,
|
466 |
+
negative_prompt_attention_mask=None,
|
467 |
+
reference_video=None,
|
468 |
+
):
|
469 |
+
if height % 32 != 0 or width % 32 != 0:
|
470 |
+
raise ValueError(f"`height` and `width` have to be divisible by 32 but are {height} and {width}.")
|
471 |
+
|
472 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
473 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
474 |
+
):
|
475 |
+
raise ValueError(
|
476 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
477 |
+
)
|
478 |
+
|
479 |
+
if prompt is not None and prompt_embeds is not None:
|
480 |
+
raise ValueError(
|
481 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
482 |
+
" only forward one of the two."
|
483 |
+
)
|
484 |
+
elif prompt is None and prompt_embeds is None:
|
485 |
+
raise ValueError(
|
486 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
487 |
+
)
|
488 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
489 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
490 |
+
|
491 |
+
if prompt_embeds is not None and prompt_attention_mask is None:
|
492 |
+
raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
|
493 |
+
|
494 |
+
if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
|
495 |
+
raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
|
496 |
+
|
497 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
498 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
499 |
+
raise ValueError(
|
500 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
501 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
502 |
+
f" {negative_prompt_embeds.shape}."
|
503 |
+
)
|
504 |
+
if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
|
505 |
+
raise ValueError(
|
506 |
+
"`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
|
507 |
+
f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
|
508 |
+
f" {negative_prompt_attention_mask.shape}."
|
509 |
+
)
|
510 |
+
|
511 |
+
if conditions is not None and (image is not None or video is not None):
|
512 |
+
raise ValueError("If `conditions` is provided, `image` and `video` must not be provided.")
|
513 |
+
|
514 |
+
if conditions is None:
|
515 |
+
if isinstance(image, list) and isinstance(frame_index, list) and len(image) != len(frame_index):
|
516 |
+
raise ValueError(
|
517 |
+
"If `conditions` is not provided, `image` and `frame_index` must be of the same length."
|
518 |
+
)
|
519 |
+
elif isinstance(image, list) and isinstance(strength, list) and len(image) != len(strength):
|
520 |
+
raise ValueError("If `conditions` is not provided, `image` and `strength` must be of the same length.")
|
521 |
+
elif isinstance(video, list) and isinstance(frame_index, list) and len(video) != len(frame_index):
|
522 |
+
raise ValueError(
|
523 |
+
"If `conditions` is not provided, `video` and `frame_index` must be of the same length."
|
524 |
+
)
|
525 |
+
elif isinstance(video, list) and isinstance(strength, list) and len(video) != len(strength):
|
526 |
+
raise ValueError("If `conditions` is not provided, `video` and `strength` must be of the same length.")
|
527 |
+
|
528 |
+
if denoise_strength < 0 or denoise_strength > 1:
|
529 |
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {denoise_strength}")
|
530 |
+
|
531 |
+
if reference_video is not None:
|
532 |
+
if not isinstance(reference_video, torch.Tensor):
|
533 |
+
raise ValueError(
|
534 |
+
"`reference_video` must be a torch.Tensor with shape [F, C, H, W] as returned by read_video()."
|
535 |
+
)
|
536 |
+
if reference_video.ndim != 4:
|
537 |
+
raise ValueError(
|
538 |
+
f"`reference_video` must be a 4D tensor with shape [F, C, H, W], but got shape {reference_video.shape}."
|
539 |
+
)
|
540 |
+
|
541 |
+
@staticmethod
|
542 |
+
def _prepare_video_ids(
|
543 |
+
batch_size: int,
|
544 |
+
num_frames: int,
|
545 |
+
height: int,
|
546 |
+
width: int,
|
547 |
+
patch_size: int = 1,
|
548 |
+
patch_size_t: int = 1,
|
549 |
+
device: torch.device = None,
|
550 |
+
) -> torch.Tensor:
|
551 |
+
latent_sample_coords = torch.meshgrid(
|
552 |
+
torch.arange(0, num_frames, patch_size_t, device=device),
|
553 |
+
torch.arange(0, height, patch_size, device=device),
|
554 |
+
torch.arange(0, width, patch_size, device=device),
|
555 |
+
indexing="ij",
|
556 |
+
)
|
557 |
+
latent_sample_coords = torch.stack(latent_sample_coords, dim=0)
|
558 |
+
latent_coords = latent_sample_coords.unsqueeze(0).repeat(batch_size, 1, 1, 1, 1)
|
559 |
+
latent_coords = latent_coords.reshape(batch_size, -1, num_frames * height * width)
|
560 |
+
|
561 |
+
return latent_coords
|
562 |
+
|
563 |
+
@staticmethod
|
564 |
+
def _scale_video_ids(
|
565 |
+
video_ids: torch.Tensor,
|
566 |
+
scale_factor: int = 32,
|
567 |
+
scale_factor_t: int = 8,
|
568 |
+
frame_index: int = 0,
|
569 |
+
device: torch.device = None,
|
570 |
+
) -> torch.Tensor:
|
571 |
+
scaled_latent_coords = (
|
572 |
+
video_ids
|
573 |
+
* torch.tensor([scale_factor_t, scale_factor, scale_factor], device=video_ids.device)[None, :, None]
|
574 |
+
)
|
575 |
+
scaled_latent_coords[:, 0] = (scaled_latent_coords[:, 0] + 1 - scale_factor_t).clamp(min=0)
|
576 |
+
scaled_latent_coords[:, 0] += frame_index
|
577 |
+
|
578 |
+
return scaled_latent_coords
|
579 |
+
|
580 |
+
@staticmethod
|
581 |
+
# Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._pack_latents
|
582 |
+
def _pack_latents(latents: torch.Tensor, patch_size: int = 1, patch_size_t: int = 1) -> torch.Tensor:
|
583 |
+
# Unpacked latents of shape are [B, C, F, H, W] are patched into tokens of shape [B, C, F // p_t, p_t, H // p, p, W // p, p].
|
584 |
+
# The patch dimensions are then permuted and collapsed into the channel dimension of shape:
|
585 |
+
# [B, F // p_t * H // p * W // p, C * p_t * p * p] (an ndim=3 tensor).
|
586 |
+
# dim=0 is the batch size, dim=1 is the effective video sequence length, dim=2 is the effective number of input features
|
587 |
+
batch_size, num_channels, num_frames, height, width = latents.shape
|
588 |
+
post_patch_num_frames = num_frames // patch_size_t
|
589 |
+
post_patch_height = height // patch_size
|
590 |
+
post_patch_width = width // patch_size
|
591 |
+
latents = latents.reshape(
|
592 |
+
batch_size,
|
593 |
+
-1,
|
594 |
+
post_patch_num_frames,
|
595 |
+
patch_size_t,
|
596 |
+
post_patch_height,
|
597 |
+
patch_size,
|
598 |
+
post_patch_width,
|
599 |
+
patch_size,
|
600 |
+
)
|
601 |
+
latents = latents.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7).flatten(1, 3)
|
602 |
+
return latents
|
603 |
+
|
604 |
+
@staticmethod
|
605 |
+
# Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._unpack_latents
|
606 |
+
def _unpack_latents(
|
607 |
+
latents: torch.Tensor, num_frames: int, height: int, width: int, patch_size: int = 1, patch_size_t: int = 1
|
608 |
+
) -> torch.Tensor:
|
609 |
+
# Packed latents of shape [B, S, D] (S is the effective video sequence length, D is the effective feature dimensions)
|
610 |
+
# are unpacked and reshaped into a video tensor of shape [B, C, F, H, W]. This is the inverse operation of
|
611 |
+
# what happens in the `_pack_latents` method.
|
612 |
+
batch_size = latents.size(0)
|
613 |
+
latents = latents.reshape(batch_size, num_frames, height, width, -1, patch_size_t, patch_size, patch_size)
|
614 |
+
latents = latents.permute(0, 4, 1, 5, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
615 |
+
return latents
|
616 |
+
|
617 |
+
@staticmethod
|
618 |
+
# Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._normalize_latents
|
619 |
+
def _normalize_latents(
|
620 |
+
latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
|
621 |
+
) -> torch.Tensor:
|
622 |
+
# Normalize latents across the channel dimension [B, C, F, H, W]
|
623 |
+
latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
624 |
+
latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
625 |
+
latents = (latents - latents_mean) * scaling_factor / latents_std
|
626 |
+
return latents
|
627 |
+
|
628 |
+
@staticmethod
|
629 |
+
# Copied from diffusers.pipelines.ltx.pipeline_ltx.LTXPipeline._denormalize_latents
|
630 |
+
def _denormalize_latents(
|
631 |
+
latents: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor, scaling_factor: float = 1.0
|
632 |
+
) -> torch.Tensor:
|
633 |
+
# Denormalize latents across the channel dimension [B, C, F, H, W]
|
634 |
+
latents_mean = latents_mean.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
635 |
+
latents_std = latents_std.view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
|
636 |
+
latents = latents * latents_std / scaling_factor + latents_mean
|
637 |
+
return latents
|
638 |
+
|
639 |
+
def trim_conditioning_sequence(self, start_frame: int, sequence_num_frames: int, target_num_frames: int):
|
640 |
+
"""
|
641 |
+
Trim a conditioning sequence to the allowed number of frames.
|
642 |
+
|
643 |
+
Args:
|
644 |
+
start_frame (int): The target frame number of the first frame in the sequence.
|
645 |
+
sequence_num_frames (int): The number of frames in the sequence.
|
646 |
+
target_num_frames (int): The target number of frames in the generated video.
|
647 |
+
Returns:
|
648 |
+
int: updated sequence length
|
649 |
+
"""
|
650 |
+
scale_factor = self.vae_temporal_compression_ratio
|
651 |
+
num_frames = min(sequence_num_frames, target_num_frames - start_frame)
|
652 |
+
# Trim down to a multiple of temporal_scale_factor frames plus 1
|
653 |
+
num_frames = (num_frames - 1) // scale_factor * scale_factor + 1
|
654 |
+
return num_frames
|
655 |
+
|
656 |
+
@staticmethod
|
657 |
+
def add_noise_to_image_conditioning_latents(
|
658 |
+
t: float,
|
659 |
+
init_latents: torch.Tensor,
|
660 |
+
latents: torch.Tensor,
|
661 |
+
noise_scale: float,
|
662 |
+
conditioning_mask: torch.Tensor,
|
663 |
+
generator,
|
664 |
+
eps=1e-6,
|
665 |
+
):
|
666 |
+
"""
|
667 |
+
Add timestep-dependent noise to the hard-conditioning latents. This helps with motion continuity, especially
|
668 |
+
when conditioned on a single frame.
|
669 |
+
"""
|
670 |
+
noise = randn_tensor(
|
671 |
+
latents.shape,
|
672 |
+
generator=generator,
|
673 |
+
device=latents.device,
|
674 |
+
dtype=latents.dtype,
|
675 |
+
)
|
676 |
+
# Add noise only to hard-conditioning latents (conditioning_mask = 1.0)
|
677 |
+
need_to_noise = (conditioning_mask > 1.0 - eps).unsqueeze(-1)
|
678 |
+
noised_latents = init_latents + noise_scale * noise * (t**2)
|
679 |
+
latents = torch.where(need_to_noise, noised_latents, latents)
|
680 |
+
return latents
|
681 |
+
|
682 |
+
def prepare_latents(
|
683 |
+
self,
|
684 |
+
conditions: Optional[List[torch.Tensor]] = None,
|
685 |
+
condition_strength: Optional[List[float]] = None,
|
686 |
+
condition_frame_index: Optional[List[int]] = None,
|
687 |
+
batch_size: int = 1,
|
688 |
+
num_channels_latents: int = 128,
|
689 |
+
height: int = 512,
|
690 |
+
width: int = 704,
|
691 |
+
num_frames: int = 161,
|
692 |
+
num_prefix_latent_frames: int = 2,
|
693 |
+
sigma: Optional[torch.Tensor] = None,
|
694 |
+
latents: Optional[torch.Tensor] = None,
|
695 |
+
generator: Optional[torch.Generator] = None,
|
696 |
+
device: Optional[torch.device] = None,
|
697 |
+
dtype: Optional[torch.dtype] = None,
|
698 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
|
699 |
+
num_latent_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
|
700 |
+
latent_height = height // self.vae_spatial_compression_ratio
|
701 |
+
latent_width = width // self.vae_spatial_compression_ratio
|
702 |
+
|
703 |
+
shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
|
704 |
+
|
705 |
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
706 |
+
if latents is not None and sigma is not None:
|
707 |
+
if latents.shape != shape:
|
708 |
+
raise ValueError(
|
709 |
+
f"Latents shape {latents.shape} does not match expected shape {shape}. Please check the input."
|
710 |
+
)
|
711 |
+
latents = latents.to(device=device, dtype=dtype)
|
712 |
+
sigma = sigma.to(device=device, dtype=dtype)
|
713 |
+
latents = sigma * noise + (1 - sigma) * latents
|
714 |
+
else:
|
715 |
+
latents = noise
|
716 |
+
|
717 |
+
if len(conditions) > 0:
|
718 |
+
condition_latent_frames_mask = torch.zeros(
|
719 |
+
(batch_size, num_latent_frames), device=device, dtype=torch.float32
|
720 |
+
)
|
721 |
+
|
722 |
+
extra_conditioning_latents = []
|
723 |
+
extra_conditioning_video_ids = []
|
724 |
+
extra_conditioning_mask = []
|
725 |
+
extra_conditioning_num_latents = 0
|
726 |
+
for data, strength, frame_index in zip(conditions, condition_strength, condition_frame_index, strict=False):
|
727 |
+
condition_latents = retrieve_latents(self.vae.encode(data), generator=generator)
|
728 |
+
condition_latents = self._normalize_latents(
|
729 |
+
condition_latents, self.vae.latents_mean, self.vae.latents_std
|
730 |
+
).to(device, dtype=dtype)
|
731 |
+
|
732 |
+
num_data_frames = data.size(2)
|
733 |
+
num_cond_frames = condition_latents.size(2)
|
734 |
+
|
735 |
+
if frame_index == 0:
|
736 |
+
latents[:, :, :num_cond_frames] = torch.lerp(
|
737 |
+
latents[:, :, :num_cond_frames], condition_latents, strength
|
738 |
+
)
|
739 |
+
condition_latent_frames_mask[:, :num_cond_frames] = strength
|
740 |
+
|
741 |
+
else:
|
742 |
+
if num_data_frames > 1:
|
743 |
+
if num_cond_frames < num_prefix_latent_frames:
|
744 |
+
raise ValueError(
|
745 |
+
f"Number of latent frames must be at least {num_prefix_latent_frames} but got {num_data_frames}."
|
746 |
+
)
|
747 |
+
|
748 |
+
if num_cond_frames > num_prefix_latent_frames:
|
749 |
+
start_frame = frame_index // self.vae_temporal_compression_ratio + num_prefix_latent_frames
|
750 |
+
end_frame = start_frame + num_cond_frames - num_prefix_latent_frames
|
751 |
+
latents[:, :, start_frame:end_frame] = torch.lerp(
|
752 |
+
latents[:, :, start_frame:end_frame],
|
753 |
+
condition_latents[:, :, num_prefix_latent_frames:],
|
754 |
+
strength,
|
755 |
+
)
|
756 |
+
condition_latent_frames_mask[:, start_frame:end_frame] = strength
|
757 |
+
condition_latents = condition_latents[:, :, :num_prefix_latent_frames]
|
758 |
+
|
759 |
+
noise = randn_tensor(condition_latents.shape, generator=generator, device=device, dtype=dtype)
|
760 |
+
condition_latents = torch.lerp(noise, condition_latents, strength)
|
761 |
+
|
762 |
+
condition_video_ids = self._prepare_video_ids(
|
763 |
+
batch_size,
|
764 |
+
condition_latents.size(2),
|
765 |
+
latent_height,
|
766 |
+
latent_width,
|
767 |
+
patch_size=self.transformer_spatial_patch_size,
|
768 |
+
patch_size_t=self.transformer_temporal_patch_size,
|
769 |
+
device=device,
|
770 |
+
)
|
771 |
+
condition_video_ids = self._scale_video_ids(
|
772 |
+
condition_video_ids,
|
773 |
+
scale_factor=self.vae_spatial_compression_ratio,
|
774 |
+
scale_factor_t=self.vae_temporal_compression_ratio,
|
775 |
+
frame_index=frame_index,
|
776 |
+
device=device,
|
777 |
+
)
|
778 |
+
condition_latents = self._pack_latents(
|
779 |
+
condition_latents,
|
780 |
+
self.transformer_spatial_patch_size,
|
781 |
+
self.transformer_temporal_patch_size,
|
782 |
+
)
|
783 |
+
condition_conditioning_mask = torch.full(
|
784 |
+
condition_latents.shape[:2], strength, device=device, dtype=dtype
|
785 |
+
)
|
786 |
+
|
787 |
+
extra_conditioning_latents.append(condition_latents)
|
788 |
+
extra_conditioning_video_ids.append(condition_video_ids)
|
789 |
+
extra_conditioning_mask.append(condition_conditioning_mask)
|
790 |
+
extra_conditioning_num_latents += condition_latents.size(1)
|
791 |
+
|
792 |
+
video_ids = self._prepare_video_ids(
|
793 |
+
batch_size,
|
794 |
+
num_latent_frames,
|
795 |
+
latent_height,
|
796 |
+
latent_width,
|
797 |
+
patch_size_t=self.transformer_temporal_patch_size,
|
798 |
+
patch_size=self.transformer_spatial_patch_size,
|
799 |
+
device=device,
|
800 |
+
)
|
801 |
+
if len(conditions) > 0:
|
802 |
+
conditioning_mask = condition_latent_frames_mask.gather(1, video_ids[:, 0])
|
803 |
+
else:
|
804 |
+
conditioning_mask, extra_conditioning_num_latents = None, 0
|
805 |
+
video_ids = self._scale_video_ids(
|
806 |
+
video_ids,
|
807 |
+
scale_factor=self.vae_spatial_compression_ratio,
|
808 |
+
scale_factor_t=self.vae_temporal_compression_ratio,
|
809 |
+
frame_index=0,
|
810 |
+
device=device,
|
811 |
+
)
|
812 |
+
latents = self._pack_latents(
|
813 |
+
latents, self.transformer_spatial_patch_size, self.transformer_temporal_patch_size
|
814 |
+
)
|
815 |
+
|
816 |
+
if len(conditions) > 0 and len(extra_conditioning_latents) > 0:
|
817 |
+
latents = torch.cat([*extra_conditioning_latents, latents], dim=1)
|
818 |
+
video_ids = torch.cat([*extra_conditioning_video_ids, video_ids], dim=2)
|
819 |
+
conditioning_mask = torch.cat([*extra_conditioning_mask, conditioning_mask], dim=1)
|
820 |
+
|
821 |
+
return latents, conditioning_mask, video_ids, extra_conditioning_num_latents
|
822 |
+
|
823 |
+
def get_timesteps(self, sigmas, timesteps, num_inference_steps, strength):
|
824 |
+
num_steps = min(int(num_inference_steps * strength), num_inference_steps)
|
825 |
+
start_index = max(num_inference_steps - num_steps, 0)
|
826 |
+
sigmas = sigmas[start_index:]
|
827 |
+
timesteps = timesteps[start_index:]
|
828 |
+
return sigmas, timesteps, num_inference_steps - start_index
|
829 |
+
|
830 |
+
@property
|
831 |
+
def guidance_scale(self):
|
832 |
+
return self._guidance_scale
|
833 |
+
|
834 |
+
@property
|
835 |
+
def guidance_rescale(self):
|
836 |
+
return self._guidance_rescale
|
837 |
+
|
838 |
+
@property
|
839 |
+
def do_classifier_free_guidance(self):
|
840 |
+
return self._guidance_scale > 1.0
|
841 |
+
|
842 |
+
@property
|
843 |
+
def num_timesteps(self):
|
844 |
+
return self._num_timesteps
|
845 |
+
|
846 |
+
@property
|
847 |
+
def current_timestep(self):
|
848 |
+
return self._current_timestep
|
849 |
+
|
850 |
+
@property
|
851 |
+
def attention_kwargs(self):
|
852 |
+
return self._attention_kwargs
|
853 |
+
|
854 |
+
@property
|
855 |
+
def interrupt(self):
|
856 |
+
return self._interrupt
|
857 |
+
|
858 |
+
@torch.no_grad()
|
859 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
860 |
+
def __call__(
|
861 |
+
self,
|
862 |
+
conditions: Union[LTXVideoCondition, List[LTXVideoCondition]] = None,
|
863 |
+
image: Union[PipelineImageInput, List[PipelineImageInput]] = None,
|
864 |
+
video: List[PipelineImageInput] = None,
|
865 |
+
frame_index: Union[int, List[int]] = 0,
|
866 |
+
strength: Union[float, List[float]] = 1.0,
|
867 |
+
denoise_strength: float = 1.0,
|
868 |
+
prompt: Union[str, List[str]] = None,
|
869 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
870 |
+
height: int = 512,
|
871 |
+
width: int = 704,
|
872 |
+
num_frames: int = 161,
|
873 |
+
frame_rate: int = 25,
|
874 |
+
num_inference_steps: int = 50,
|
875 |
+
timesteps: List[int] = None,
|
876 |
+
guidance_scale: float = 3,
|
877 |
+
guidance_rescale: float = 0.0,
|
878 |
+
image_cond_noise_scale: float = 0.15,
|
879 |
+
num_videos_per_prompt: Optional[int] = 1,
|
880 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
881 |
+
latents: Optional[torch.Tensor] = None,
|
882 |
+
reference_video: Optional[torch.Tensor] = None,
|
883 |
+
output_reference_comparison: bool = False,
|
884 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
885 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
886 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
887 |
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
888 |
+
decode_timestep: Union[float, List[float]] = 0.0,
|
889 |
+
decode_noise_scale: Optional[Union[float, List[float]]] = None,
|
890 |
+
output_type: Optional[str] = "pil",
|
891 |
+
return_dict: bool = True,
|
892 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
893 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
894 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
895 |
+
max_sequence_length: int = 256,
|
896 |
+
):
|
897 |
+
r"""
|
898 |
+
Function invoked when calling the pipeline for generation.
|
899 |
+
|
900 |
+
Args:
|
901 |
+
conditions (`List[LTXVideoCondition], *optional*`):
|
902 |
+
The list of frame-conditioning items for the video generation.If not provided, conditions will be
|
903 |
+
created using `image`, `video`, `frame_index` and `strength`.
|
904 |
+
image (`PipelineImageInput` or `List[PipelineImageInput]`, *optional*):
|
905 |
+
The image or images to condition the video generation. If not provided, one has to pass `video` or
|
906 |
+
`conditions`.
|
907 |
+
video (`List[PipelineImageInput]`, *optional*):
|
908 |
+
The video to condition the video generation. If not provided, one has to pass `image` or `conditions`.
|
909 |
+
frame_index (`int` or `List[int]`, *optional*):
|
910 |
+
The frame index or frame indices at which the image or video will conditionally effect the video
|
911 |
+
generation. If not provided, one has to pass `conditions`.
|
912 |
+
strength (`float` or `List[float]`, *optional*):
|
913 |
+
The strength or strengths of the conditioning effect. If not provided, one has to pass `conditions`.
|
914 |
+
denoise_strength (`float`, defaults to `1.0`):
|
915 |
+
The strength of the noise added to the latents for editing. Higher strength leads to more noise added
|
916 |
+
to the latents, therefore leading to more differences between original video and generated video. This
|
917 |
+
is useful for video-to-video editing.
|
918 |
+
prompt (`str` or `List[str]`, *optional*):
|
919 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
920 |
+
instead.
|
921 |
+
height (`int`, defaults to `512`):
|
922 |
+
The height in pixels of the generated image. This is set to 480 by default for the best results.
|
923 |
+
width (`int`, defaults to `704`):
|
924 |
+
The width in pixels of the generated image. This is set to 848 by default for the best results.
|
925 |
+
num_frames (`int`, defaults to `161`):
|
926 |
+
The number of video frames to generate
|
927 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
928 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
929 |
+
expense of slower inference.
|
930 |
+
timesteps (`List[int]`, *optional*):
|
931 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
932 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
933 |
+
passed will be used. Must be in descending order.
|
934 |
+
guidance_scale (`float`, defaults to `3 `):
|
935 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
936 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
937 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
938 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
939 |
+
the text `prompt`, usually at the expense of lower image quality.
|
940 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
941 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
942 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
943 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
944 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
945 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
946 |
+
The number of videos to generate per prompt.
|
947 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
948 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
949 |
+
to make generation deterministic.
|
950 |
+
latents (`torch.Tensor`, *optional*):
|
951 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
952 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
953 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
954 |
+
reference_video (`torch.Tensor`, *optional*):
|
955 |
+
An optional reference video to guide the generation process. Should be a tensor with shape
|
956 |
+
[F, C, H, W] in range [0, 1] as returned by `read_video()` from video_utils. The reference video
|
957 |
+
will be encoded and concatenated to the latent sequence, providing global guidance while remaining
|
958 |
+
unchanged during denoising. The reference video can be of any size and will be automatically
|
959 |
+
resized and cropped to match the target dimensions.
|
960 |
+
output_reference_comparison (`bool`, defaults to `False`):
|
961 |
+
Whether to output a side-by-side comparison showing both the reference video (if provided) and the
|
962 |
+
generated video. If `False`, only the generated video is returned. Only applies when `reference_video`
|
963 |
+
is provided.
|
964 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
965 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
966 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
967 |
+
prompt_attention_mask (`torch.Tensor`, *optional*):
|
968 |
+
Pre-generated attention mask for text embeddings.
|
969 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
970 |
+
Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
|
971 |
+
provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
|
972 |
+
negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
|
973 |
+
Pre-generated attention mask for negative text embeddings.
|
974 |
+
decode_timestep (`float`, defaults to `0.0`):
|
975 |
+
The timestep at which generated video is decoded.
|
976 |
+
decode_noise_scale (`float`, defaults to `None`):
|
977 |
+
The interpolation factor between random noise and denoised latents at the decode timestep.
|
978 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
979 |
+
The output format of the generate image. Choose between
|
980 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
981 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
982 |
+
Whether or not to return a [`~pipelines.ltx.LTXPipelineOutput`] instead of a plain tuple.
|
983 |
+
attention_kwargs (`dict`, *optional*):
|
984 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
985 |
+
`self.processor` in
|
986 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
987 |
+
callback_on_step_end (`Callable`, *optional*):
|
988 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
989 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
990 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
991 |
+
`callback_on_step_end_tensor_inputs`.
|
992 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
993 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
994 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
995 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
996 |
+
max_sequence_length (`int` defaults to `128 `):
|
997 |
+
Maximum sequence length to use with the `prompt`.
|
998 |
+
|
999 |
+
Examples:
|
1000 |
+
|
1001 |
+
Returns:
|
1002 |
+
[`~pipelines.ltx.LTXPipelineOutput`] or `tuple`:
|
1003 |
+
If `return_dict` is `True`, [`~pipelines.ltx.LTXPipelineOutput`] is returned, otherwise a `tuple` is
|
1004 |
+
returned where the first element is a list with the generated images.
|
1005 |
+
"""
|
1006 |
+
|
1007 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
1008 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
1009 |
+
# if latents is not None:
|
1010 |
+
# raise ValueError("Passing latents is not yet supported.")
|
1011 |
+
|
1012 |
+
# 1. Check inputs. Raise error if not correct
|
1013 |
+
self.check_inputs(
|
1014 |
+
prompt=prompt,
|
1015 |
+
conditions=conditions,
|
1016 |
+
image=image,
|
1017 |
+
video=video,
|
1018 |
+
frame_index=frame_index,
|
1019 |
+
strength=strength,
|
1020 |
+
denoise_strength=denoise_strength,
|
1021 |
+
height=height,
|
1022 |
+
width=width,
|
1023 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
1024 |
+
prompt_embeds=prompt_embeds,
|
1025 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
1026 |
+
prompt_attention_mask=prompt_attention_mask,
|
1027 |
+
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
1028 |
+
reference_video=reference_video,
|
1029 |
+
)
|
1030 |
+
|
1031 |
+
self._guidance_scale = guidance_scale
|
1032 |
+
self._guidance_rescale = guidance_rescale
|
1033 |
+
self._attention_kwargs = attention_kwargs
|
1034 |
+
self._interrupt = False
|
1035 |
+
self._current_timestep = None
|
1036 |
+
|
1037 |
+
# 2. Define call parameters
|
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 |
+
if conditions is not None:
|
1046 |
+
if not isinstance(conditions, list):
|
1047 |
+
conditions = [conditions]
|
1048 |
+
|
1049 |
+
strength = [condition.strength for condition in conditions]
|
1050 |
+
frame_index = [condition.frame_index for condition in conditions]
|
1051 |
+
image = [condition.image for condition in conditions]
|
1052 |
+
video = [condition.video for condition in conditions]
|
1053 |
+
elif image is not None or video is not None:
|
1054 |
+
if not isinstance(image, list):
|
1055 |
+
image = [image]
|
1056 |
+
num_conditions = 1
|
1057 |
+
elif isinstance(image, list):
|
1058 |
+
num_conditions = len(image)
|
1059 |
+
if not isinstance(video, list):
|
1060 |
+
video = [video]
|
1061 |
+
num_conditions = 1
|
1062 |
+
elif isinstance(video, list):
|
1063 |
+
num_conditions = len(video)
|
1064 |
+
|
1065 |
+
if not isinstance(frame_index, list):
|
1066 |
+
frame_index = [frame_index] * num_conditions
|
1067 |
+
if not isinstance(strength, list):
|
1068 |
+
strength = [strength] * num_conditions
|
1069 |
+
|
1070 |
+
device = self._execution_device
|
1071 |
+
vae_dtype = self.vae.dtype
|
1072 |
+
|
1073 |
+
# 3. Prepare text embeddings & conditioning image/video
|
1074 |
+
(
|
1075 |
+
prompt_embeds,
|
1076 |
+
prompt_attention_mask,
|
1077 |
+
negative_prompt_embeds,
|
1078 |
+
negative_prompt_attention_mask,
|
1079 |
+
) = self.encode_prompt(
|
1080 |
+
prompt=prompt,
|
1081 |
+
negative_prompt=negative_prompt,
|
1082 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1083 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
1084 |
+
prompt_embeds=prompt_embeds,
|
1085 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
1086 |
+
prompt_attention_mask=prompt_attention_mask,
|
1087 |
+
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
1088 |
+
max_sequence_length=max_sequence_length,
|
1089 |
+
device=device,
|
1090 |
+
)
|
1091 |
+
if self.do_classifier_free_guidance:
|
1092 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1093 |
+
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
|
1094 |
+
|
1095 |
+
conditioning_tensors = []
|
1096 |
+
is_conditioning_image_or_video = image is not None or video is not None
|
1097 |
+
if is_conditioning_image_or_video:
|
1098 |
+
for condition_image, condition_video, condition_frame_index, condition_strength in zip(
|
1099 |
+
image, video, frame_index, strength, strict=False
|
1100 |
+
):
|
1101 |
+
if condition_image is not None:
|
1102 |
+
condition_tensor = (
|
1103 |
+
self.video_processor.preprocess(condition_image, height, width)
|
1104 |
+
.unsqueeze(2)
|
1105 |
+
.to(device, dtype=vae_dtype)
|
1106 |
+
)
|
1107 |
+
elif condition_video is not None:
|
1108 |
+
condition_tensor = self.video_processor.preprocess_video(condition_video, height, width)
|
1109 |
+
num_frames_input = condition_tensor.size(2)
|
1110 |
+
num_frames_output = self.trim_conditioning_sequence(
|
1111 |
+
condition_frame_index, num_frames_input, num_frames
|
1112 |
+
)
|
1113 |
+
condition_tensor = condition_tensor[:, :, :num_frames_output]
|
1114 |
+
condition_tensor = condition_tensor.to(device, dtype=vae_dtype)
|
1115 |
+
else:
|
1116 |
+
raise ValueError("Either `image` or `video` must be provided for conditioning.")
|
1117 |
+
|
1118 |
+
if condition_tensor.size(2) % self.vae_temporal_compression_ratio != 1:
|
1119 |
+
raise ValueError(
|
1120 |
+
f"Number of frames in the video must be of the form (k * {self.vae_temporal_compression_ratio} + 1) "
|
1121 |
+
f"but got {condition_tensor.size(2)} frames."
|
1122 |
+
)
|
1123 |
+
conditioning_tensors.append(condition_tensor)
|
1124 |
+
|
1125 |
+
# 4. Prepare timesteps
|
1126 |
+
latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
|
1127 |
+
latent_height = height // self.vae_spatial_compression_ratio
|
1128 |
+
latent_width = width // self.vae_spatial_compression_ratio
|
1129 |
+
if timesteps is None:
|
1130 |
+
sigmas = linear_quadratic_schedule(num_inference_steps)
|
1131 |
+
timesteps = sigmas * 1000
|
1132 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
1133 |
+
sigmas = self.scheduler.sigmas
|
1134 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1135 |
+
|
1136 |
+
latent_sigma = None
|
1137 |
+
if denoise_strength < 1:
|
1138 |
+
sigmas, timesteps, num_inference_steps = self.get_timesteps(
|
1139 |
+
sigmas, timesteps, num_inference_steps, denoise_strength
|
1140 |
+
)
|
1141 |
+
latent_sigma = sigmas[:1].repeat(batch_size * num_videos_per_prompt)
|
1142 |
+
|
1143 |
+
self._num_timesteps = len(timesteps)
|
1144 |
+
|
1145 |
+
# 5. Prepare latent variables
|
1146 |
+
num_channels_latents = self.transformer.config.in_channels
|
1147 |
+
latents, conditioning_mask, video_coords, extra_conditioning_num_latents = self.prepare_latents(
|
1148 |
+
conditioning_tensors,
|
1149 |
+
strength,
|
1150 |
+
frame_index,
|
1151 |
+
batch_size=batch_size * num_videos_per_prompt,
|
1152 |
+
num_channels_latents=num_channels_latents,
|
1153 |
+
height=height,
|
1154 |
+
width=width,
|
1155 |
+
num_frames=num_frames,
|
1156 |
+
sigma=latent_sigma,
|
1157 |
+
latents=latents,
|
1158 |
+
generator=generator,
|
1159 |
+
device=device,
|
1160 |
+
dtype=torch.float32,
|
1161 |
+
)
|
1162 |
+
|
1163 |
+
# 4.5. Process reference video (if provided) and concatenate at the beginning
|
1164 |
+
reference_latents = None
|
1165 |
+
reference_num_latents = 0
|
1166 |
+
if reference_video is not None:
|
1167 |
+
# Work with the original tensor format [F, C, H, W]
|
1168 |
+
ref_frames = reference_video # [F, C, H, W]
|
1169 |
+
|
1170 |
+
# Resize maintaining aspect ratio (resize all frames)
|
1171 |
+
current_height, current_width = ref_frames.shape[2:]
|
1172 |
+
aspect_ratio = current_width / current_height
|
1173 |
+
target_aspect_ratio = width / height
|
1174 |
+
|
1175 |
+
if aspect_ratio > target_aspect_ratio:
|
1176 |
+
# Width is relatively larger, resize based on height
|
1177 |
+
resize_height = height
|
1178 |
+
resize_width = int(resize_height * aspect_ratio)
|
1179 |
+
else:
|
1180 |
+
# Height is relatively larger, resize based on width
|
1181 |
+
resize_width = width
|
1182 |
+
resize_height = int(resize_width / aspect_ratio)
|
1183 |
+
|
1184 |
+
ref_frames = resize(ref_frames, [resize_height, resize_width], antialias=True)
|
1185 |
+
|
1186 |
+
# Center crop to target dimensions
|
1187 |
+
ref_frames = center_crop(ref_frames, [height, width])
|
1188 |
+
|
1189 |
+
# Convert to VAE input format: [1, C, F, H, W] and proper range [-1, 1]
|
1190 |
+
reference_tensor = ref_frames.unsqueeze(0).permute(0, 2, 1, 3, 4) # [1, F, C, H, W] -> [1, C, F, H, W]
|
1191 |
+
reference_tensor = reference_tensor * 2.0 - 1.0 # [0, 1] -> [-1, 1]
|
1192 |
+
|
1193 |
+
# Trim reference video to proper frame count for temporal compression
|
1194 |
+
ref_num_frames_input = reference_tensor.size(2)
|
1195 |
+
ref_num_frames_output = self.trim_conditioning_sequence(0, ref_num_frames_input, num_frames)
|
1196 |
+
reference_tensor = reference_tensor[:, :, :ref_num_frames_output]
|
1197 |
+
reference_tensor = reference_tensor.to(device, dtype=vae_dtype)
|
1198 |
+
|
1199 |
+
# Ensure proper frame count for VAE temporal compression
|
1200 |
+
if reference_tensor.size(2) % self.vae_temporal_compression_ratio != 1:
|
1201 |
+
# Trim to make it compatible with temporal compression
|
1202 |
+
ref_frames_to_keep = (
|
1203 |
+
(reference_tensor.size(2) - 1) // self.vae_temporal_compression_ratio
|
1204 |
+
) * self.vae_temporal_compression_ratio + 1
|
1205 |
+
reference_tensor = reference_tensor[:, :, :ref_frames_to_keep]
|
1206 |
+
|
1207 |
+
# Expand reference tensor for batch and num_videos_per_prompt
|
1208 |
+
reference_tensor = reference_tensor.repeat(batch_size * num_videos_per_prompt, 1, 1, 1, 1)
|
1209 |
+
|
1210 |
+
# Encode reference video to latents
|
1211 |
+
reference_latents = retrieve_latents(self.vae.encode(reference_tensor), generator=generator)
|
1212 |
+
reference_latents = self._normalize_latents(
|
1213 |
+
reference_latents, self.vae.latents_mean, self.vae.latents_std
|
1214 |
+
).to(device, dtype=torch.float32)
|
1215 |
+
|
1216 |
+
# Create "clean" coordinates for reference video (as if no frame conditioning applied)
|
1217 |
+
ref_latent_frames = reference_latents.size(2)
|
1218 |
+
ref_latent_height = reference_latents.size(3)
|
1219 |
+
ref_latent_width = reference_latents.size(4)
|
1220 |
+
|
1221 |
+
reference_video_coords = self._prepare_video_ids(
|
1222 |
+
batch_size * num_videos_per_prompt,
|
1223 |
+
ref_latent_frames,
|
1224 |
+
ref_latent_height,
|
1225 |
+
ref_latent_width,
|
1226 |
+
patch_size_t=self.transformer_temporal_patch_size,
|
1227 |
+
patch_size=self.transformer_spatial_patch_size,
|
1228 |
+
device=device,
|
1229 |
+
)
|
1230 |
+
reference_video_coords = self._scale_video_ids(
|
1231 |
+
reference_video_coords,
|
1232 |
+
scale_factor=self.vae_spatial_compression_ratio,
|
1233 |
+
scale_factor_t=self.vae_temporal_compression_ratio,
|
1234 |
+
frame_index=0, # Reference video starts at frame 0
|
1235 |
+
device=device,
|
1236 |
+
)
|
1237 |
+
|
1238 |
+
# Pack reference latents
|
1239 |
+
reference_latents = self._pack_latents(
|
1240 |
+
reference_latents,
|
1241 |
+
self.transformer_spatial_patch_size,
|
1242 |
+
self.transformer_temporal_patch_size,
|
1243 |
+
)
|
1244 |
+
reference_num_latents = reference_latents.size(1)
|
1245 |
+
|
1246 |
+
# Concatenate reference latents at the beginning: [reference_latents, frame_conditions, target_latents]
|
1247 |
+
latents = torch.cat([reference_latents, latents], dim=1)
|
1248 |
+
|
1249 |
+
# Update video coordinates: [reference_coords, existing_coords]
|
1250 |
+
reference_video_coords = reference_video_coords.float()
|
1251 |
+
video_coords = torch.cat([reference_video_coords, video_coords], dim=2)
|
1252 |
+
video_coords[:, 0] = video_coords[:, 0] * (1.0 / frame_rate)
|
1253 |
+
|
1254 |
+
# Update conditioning mask to include reference (frozen = strength 1.0)
|
1255 |
+
if conditioning_mask is not None:
|
1256 |
+
reference_conditioning_mask = torch.ones(
|
1257 |
+
(batch_size * num_videos_per_prompt, reference_num_latents), device=device, dtype=torch.float32
|
1258 |
+
)
|
1259 |
+
conditioning_mask = torch.cat([reference_conditioning_mask, conditioning_mask], dim=1)
|
1260 |
+
else:
|
1261 |
+
# If no frame conditioning, still create mask for reference
|
1262 |
+
conditioning_mask = torch.ones(
|
1263 |
+
(batch_size * num_videos_per_prompt, reference_num_latents), device=device, dtype=torch.float32
|
1264 |
+
)
|
1265 |
+
# Add zeros for target latents
|
1266 |
+
target_conditioning_mask = torch.zeros(
|
1267 |
+
(batch_size * num_videos_per_prompt, latents.size(1) - reference_num_latents),
|
1268 |
+
device=device,
|
1269 |
+
dtype=torch.float32,
|
1270 |
+
)
|
1271 |
+
conditioning_mask = torch.cat([conditioning_mask, target_conditioning_mask], dim=1)
|
1272 |
+
|
1273 |
+
video_coords = video_coords.float()
|
1274 |
+
if reference_video is None:
|
1275 |
+
video_coords[:, 0] = video_coords[:, 0] * (1.0 / frame_rate)
|
1276 |
+
|
1277 |
+
init_latents = latents.clone() if is_conditioning_image_or_video or reference_video is not None else None
|
1278 |
+
|
1279 |
+
if self.do_classifier_free_guidance:
|
1280 |
+
video_coords = torch.cat([video_coords, video_coords], dim=0)
|
1281 |
+
|
1282 |
+
# 6. Denoising loop
|
1283 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1284 |
+
for i, t in enumerate(timesteps):
|
1285 |
+
if self.interrupt:
|
1286 |
+
continue
|
1287 |
+
|
1288 |
+
self._current_timestep = t
|
1289 |
+
|
1290 |
+
if image_cond_noise_scale > 0 and init_latents is not None:
|
1291 |
+
# Add timestep-dependent noise to the hard-conditioning latents
|
1292 |
+
# This helps with motion continuity, especially when conditioned on a single frame
|
1293 |
+
latents = self.add_noise_to_image_conditioning_latents(
|
1294 |
+
t / 1000.0,
|
1295 |
+
init_latents,
|
1296 |
+
latents,
|
1297 |
+
image_cond_noise_scale,
|
1298 |
+
conditioning_mask,
|
1299 |
+
generator,
|
1300 |
+
)
|
1301 |
+
|
1302 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1303 |
+
if is_conditioning_image_or_video or reference_video is not None:
|
1304 |
+
conditioning_mask_model_input = (
|
1305 |
+
torch.cat([conditioning_mask, conditioning_mask])
|
1306 |
+
if self.do_classifier_free_guidance
|
1307 |
+
else conditioning_mask
|
1308 |
+
)
|
1309 |
+
latent_model_input = latent_model_input.to(prompt_embeds.dtype)
|
1310 |
+
|
1311 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1312 |
+
timestep = t.expand(latent_model_input.shape[0]).unsqueeze(-1).float()
|
1313 |
+
if is_conditioning_image_or_video or reference_video is not None:
|
1314 |
+
timestep = torch.min(timestep, (1 - conditioning_mask_model_input) * 1000.0)
|
1315 |
+
|
1316 |
+
noise_pred = self.transformer(
|
1317 |
+
hidden_states=latent_model_input,
|
1318 |
+
encoder_hidden_states=prompt_embeds,
|
1319 |
+
timestep=timestep,
|
1320 |
+
encoder_attention_mask=prompt_attention_mask,
|
1321 |
+
video_coords=video_coords,
|
1322 |
+
attention_kwargs=attention_kwargs,
|
1323 |
+
return_dict=False,
|
1324 |
+
)[0]
|
1325 |
+
|
1326 |
+
if self.do_classifier_free_guidance:
|
1327 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1328 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1329 |
+
timestep, _ = timestep.chunk(2)
|
1330 |
+
|
1331 |
+
if self.guidance_rescale > 0:
|
1332 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
1333 |
+
noise_pred = rescale_noise_cfg(
|
1334 |
+
noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale
|
1335 |
+
)
|
1336 |
+
|
1337 |
+
denoised_latents = self.scheduler.step(
|
1338 |
+
-noise_pred, t, latents, per_token_timesteps=timestep, return_dict=False
|
1339 |
+
)[0]
|
1340 |
+
if is_conditioning_image_or_video or reference_video is not None:
|
1341 |
+
tokens_to_denoise_mask = (t / 1000 - 1e-6 < (1.0 - conditioning_mask)).unsqueeze(-1)
|
1342 |
+
latents = torch.where(tokens_to_denoise_mask, denoised_latents, latents)
|
1343 |
+
else:
|
1344 |
+
latents = denoised_latents
|
1345 |
+
|
1346 |
+
if callback_on_step_end is not None:
|
1347 |
+
callback_kwargs = {}
|
1348 |
+
for k in callback_on_step_end_tensor_inputs:
|
1349 |
+
callback_kwargs[k] = locals()[k]
|
1350 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1351 |
+
|
1352 |
+
latents = callback_outputs.pop("latents", latents)
|
1353 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1354 |
+
|
1355 |
+
# call the callback, if provided
|
1356 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1357 |
+
progress_bar.update()
|
1358 |
+
|
1359 |
+
if XLA_AVAILABLE:
|
1360 |
+
xm.mark_step()
|
1361 |
+
|
1362 |
+
# Handle reference video output processing
|
1363 |
+
if reference_video is not None and output_reference_comparison:
|
1364 |
+
# Split latents: [reference_latents, frame_conditions, target_latents]
|
1365 |
+
reference_latents_out = latents[:, :reference_num_latents]
|
1366 |
+
remaining_latents = latents[:, reference_num_latents:]
|
1367 |
+
|
1368 |
+
# Remove frame conditioning from remaining latents if needed
|
1369 |
+
if is_conditioning_image_or_video:
|
1370 |
+
target_latents_out = remaining_latents[:, extra_conditioning_num_latents:]
|
1371 |
+
else:
|
1372 |
+
target_latents_out = remaining_latents
|
1373 |
+
|
1374 |
+
# Process both reference and target latents
|
1375 |
+
videos = []
|
1376 |
+
for curr_latents in [reference_latents_out, target_latents_out]:
|
1377 |
+
if output_type == "latent":
|
1378 |
+
curr_video = curr_latents
|
1379 |
+
else:
|
1380 |
+
curr_latents = self._unpack_latents(
|
1381 |
+
curr_latents,
|
1382 |
+
latent_num_frames,
|
1383 |
+
latent_height,
|
1384 |
+
latent_width,
|
1385 |
+
self.transformer_spatial_patch_size,
|
1386 |
+
self.transformer_temporal_patch_size,
|
1387 |
+
)
|
1388 |
+
curr_latents = self._denormalize_latents(
|
1389 |
+
curr_latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor
|
1390 |
+
)
|
1391 |
+
curr_latents = curr_latents.to(prompt_embeds.dtype)
|
1392 |
+
|
1393 |
+
if not self.vae.config.timestep_conditioning:
|
1394 |
+
timestep = None
|
1395 |
+
else:
|
1396 |
+
noise = torch.randn(
|
1397 |
+
curr_latents.shape, generator=generator, device=device, dtype=curr_latents.dtype
|
1398 |
+
)
|
1399 |
+
if not isinstance(decode_timestep, list):
|
1400 |
+
decode_timestep = [decode_timestep] * batch_size
|
1401 |
+
if decode_noise_scale is None:
|
1402 |
+
decode_noise_scale = decode_timestep
|
1403 |
+
elif not isinstance(decode_noise_scale, list):
|
1404 |
+
decode_noise_scale = [decode_noise_scale] * batch_size
|
1405 |
+
|
1406 |
+
timestep = torch.tensor(decode_timestep, device=device, dtype=curr_latents.dtype)
|
1407 |
+
decode_noise_scale = torch.tensor(decode_noise_scale, device=device, dtype=curr_latents.dtype)[
|
1408 |
+
:, None, None, None, None
|
1409 |
+
]
|
1410 |
+
curr_latents = (1 - decode_noise_scale) * curr_latents + decode_noise_scale * noise
|
1411 |
+
|
1412 |
+
curr_video = self.vae.decode(curr_latents, timestep, return_dict=False)[0]
|
1413 |
+
curr_video = self.video_processor.postprocess_video(curr_video, output_type=output_type)
|
1414 |
+
videos.append(curr_video)
|
1415 |
+
|
1416 |
+
# Concatenate videos side-by-side (along width dimension for visual output)
|
1417 |
+
if output_type == "latent":
|
1418 |
+
video = torch.cat(videos, dim=0)
|
1419 |
+
# For video tensors, shape is [B, C, F, H, W] or list of PIL images
|
1420 |
+
elif isinstance(videos[0], list):
|
1421 |
+
# Handle PIL images case - concatenate each frame side by side
|
1422 |
+
video = []
|
1423 |
+
for batch_idx in range(len(videos[0])):
|
1424 |
+
combined_video = []
|
1425 |
+
for frame_idx in range(len(videos[0][batch_idx])):
|
1426 |
+
ref_frame = videos[0][batch_idx][frame_idx]
|
1427 |
+
gen_frame = videos[1][batch_idx][frame_idx]
|
1428 |
+
# Create side-by-side comparison
|
1429 |
+
import PIL.Image
|
1430 |
+
|
1431 |
+
if isinstance(ref_frame, PIL.Image.Image) and isinstance(gen_frame, PIL.Image.Image):
|
1432 |
+
combined_width = ref_frame.width + gen_frame.width
|
1433 |
+
combined_height = max(ref_frame.height, gen_frame.height)
|
1434 |
+
combined_frame = PIL.Image.new("RGB", (combined_width, combined_height))
|
1435 |
+
combined_frame.paste(ref_frame, (0, 0))
|
1436 |
+
combined_frame.paste(gen_frame, (ref_frame.width, 0))
|
1437 |
+
combined_video.append(combined_frame)
|
1438 |
+
else:
|
1439 |
+
combined_video.append(gen_frame) # Fallback to generated only
|
1440 |
+
video.append(combined_video)
|
1441 |
+
else:
|
1442 |
+
# Handle tensor case - concatenate along width dimension (dim=4)
|
1443 |
+
video = torch.cat(videos, dim=4)
|
1444 |
+
else:
|
1445 |
+
# Regular processing - just remove conditioning parts and output generated video
|
1446 |
+
if reference_video is not None:
|
1447 |
+
# Remove reference latents
|
1448 |
+
latents = latents[:, reference_num_latents:]
|
1449 |
+
|
1450 |
+
if is_conditioning_image_or_video:
|
1451 |
+
latents = latents[:, extra_conditioning_num_latents:]
|
1452 |
+
|
1453 |
+
latents = self._unpack_latents(
|
1454 |
+
latents,
|
1455 |
+
latent_num_frames,
|
1456 |
+
latent_height,
|
1457 |
+
latent_width,
|
1458 |
+
self.transformer_spatial_patch_size,
|
1459 |
+
self.transformer_temporal_patch_size,
|
1460 |
+
)
|
1461 |
+
|
1462 |
+
if output_type == "latent":
|
1463 |
+
video = latents
|
1464 |
+
else:
|
1465 |
+
latents = self._denormalize_latents(
|
1466 |
+
latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor
|
1467 |
+
)
|
1468 |
+
latents = latents.to(prompt_embeds.dtype)
|
1469 |
+
|
1470 |
+
if not self.vae.config.timestep_conditioning:
|
1471 |
+
timestep = None
|
1472 |
+
else:
|
1473 |
+
noise = torch.randn(latents.shape, generator=generator, device=device, dtype=latents.dtype)
|
1474 |
+
if not isinstance(decode_timestep, list):
|
1475 |
+
decode_timestep = [decode_timestep] * batch_size
|
1476 |
+
if decode_noise_scale is None:
|
1477 |
+
decode_noise_scale = decode_timestep
|
1478 |
+
elif not isinstance(decode_noise_scale, list):
|
1479 |
+
decode_noise_scale = [decode_noise_scale] * batch_size
|
1480 |
+
|
1481 |
+
timestep = torch.tensor(decode_timestep, device=device, dtype=latents.dtype)
|
1482 |
+
decode_noise_scale = torch.tensor(decode_noise_scale, device=device, dtype=latents.dtype)[
|
1483 |
+
:, None, None, None, None
|
1484 |
+
]
|
1485 |
+
latents = (1 - decode_noise_scale) * latents + decode_noise_scale * noise
|
1486 |
+
|
1487 |
+
video = self.vae.decode(latents, timestep, return_dict=False)[0]
|
1488 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
1489 |
+
|
1490 |
+
# Offload all models
|
1491 |
+
self.maybe_free_model_hooks()
|
1492 |
+
|
1493 |
+
if not return_dict:
|
1494 |
+
return (video,)
|
1495 |
+
|
1496 |
+
return LTXPipelineOutput(frames=video)
|