#
# Được cấp phép theo Giấy phép Apache, Phiên bản 2.0 (gọi là "Giấy phép");
# bạn có thể không sử dụng tệp này ngoại trừ tuân thủ theo Giấy phép.
# Bạn có thể nhận được một bản sao của Giấy phép tại
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Trừ khi được yêu cầu bởi luật pháp có hiệu lực hoặc được thỏa thuận bằng văn bản, phần mềm
# được phân phối theo Giấy phép được phân phối trên cơ sở
# KHÔNG CÓ BẢO HÀNH HOẶC ĐIỀU KIỆN DƯỚI BẤT KỲ HÌNH THỨC NÀO, dù được nêu rõ hay ngụ ý.
# Xem Giấy phép để biết ngôn ngữ cụ thể điều chỉnh các quyền và
# giới hạn theo Giấy phép. -->

# LTX-2

  

[LTX-2](https://hf.co/papers/2601.03233) là một mô hình nền tảng dựa trên DiT, được thiết kế để tạo ra video và âm thanh đồng bộ trong một mô hình duy nhất. Nó tập hợp các khối xây dựng cốt lõi của việc tạo video hiện đại, với trọng số mở và tập trung vào việc thực thi thực tế, cục bộ.

Bạn có thể tìm thấy tất cả các checkpoint gốc của LTX-Video dưới tổ chức [Lightricks](https://huggingface.co/Lightricks).

Mã nguồn gốc của LTX-2 có thể được tìm thấy [tại đây](https://github.com/Lightricks/LTX-2).

## Tạo hai giai đoạn

Các giá trị mặc định của `__call__` dùng chung cho `LTX2Pipeline` / `LTX2ImageToVideoPipeline` khớp với tham chiếu LTX-2.5 (`num_inference_steps=30`; `num_frames` là tùy chọn khi có `duration_head`, nếu không sẽ dùng giá trị dự phòng `121`). Các ví dụ bên dưới cũng sử dụng các giá trị mặc định đó cho LTX-2.0/2.3.

Quy trình được khuyến nghị để đạt chất lượng tạo ra ở mức sản xuất, quy trình này bao gồm hai giai đoạn:

- Giai đoạn 1: Tạo video ở độ phân giải đích bằng cách lấy mẫu khuếch tán với hướng dẫn không phân loại (CFG). Giai đoạn này tạo ra một chuỗi video nhiễu thấp nhất quán, tuân theo điều kiện văn bản/hình ảnh.
- Giai đoạn 2: Nhân đôi kích thước đầu ra của Giai đoạn 1 và tinh chỉnh chi tiết bằng một mô hình LoRA đã được chưng cất để cải thiện độ trung thực và chất lượng hình ảnh. Giai đoạn 2 có thể áp dụng CFG nhẹ hơn để bảo toàn cấu trúc từ Giai đoạn 1 trong khi tăng cường kết cấu và độ sắc nét.

Cách sử dụng mẫu của pipeline hai giai đoạn từ văn bản sang video

```py
import torch
from diffusers import FlowMatchEulerDiscreteScheduler
from diffusers.pipelines.ltx2 import LTX2Pipeline, LTX2LatentUpsamplePipeline
from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.utils import STAGE_2_DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video

device = "cuda:0"
width = 768
height = 512

pipe = LTX2Pipeline.from_pretrained(
    "Lightricks/LTX-2", dtype=torch.bfloat16
)
pipe.enable_sequential_cpu_offload(device=device)

prompt = "A beautiful sunset over the ocean"
negative_prompt = "shaky, glitchy, low quality, worst quality, deformed, distorted, disfigured, motion smear, motion artifacts, fused fingers, bad anatomy, weird hand, ugly, transition, static."

# Stage 1 default (non-distilled) inference
frame_rate = 24.0
video_latent, audio_latent = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=30,
    sigmas=None,
    guidance_scale=3.0,
    output_type="latent",
    return_dict=False,
)

latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    "Lightricks/LTX-2",
    subfolder="latent_upsampler",
    dtype=torch.bfloat16,
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
upsample_pipe.enable_model_cpu_offload(device=device)
upscaled_video_latent = upsample_pipe(
    latents=video_latent,
    output_type="latent",
    return_dict=False,
)[0]

# Load Stage 2 distilled LoRA
pipe.load_lora_weights(
    "Lightricks/LTX-2", adapter_name="stage_2_distilled", weight_name="ltx-2-19b-distilled-lora-384.safetensors"
)
pipe.set_adapters("stage_2_distilled", 1.0)
# VAE tiling is usually necessary to avoid OOM error when VAE decoding
pipe.vae.enable_tiling()
# Change scheduler to use Stage 2 distilled sigmas as is
new_scheduler = FlowMatchEulerDiscreteScheduler.from_config(
    pipe.scheduler.config, use_dynamic_shifting=False, shift_terminal=None
)
pipe.scheduler = new_scheduler
# Stage 2 inference with distilled LoRA and sigmas
video, audio = pipe(
    latents=upscaled_video_latent,
    audio_latents=audio_latent,
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=3,
    noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0], # renoise with first sigma value https://github.com/Lightricks/LTX-2/blob/main/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py#L218
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_lora_distilled_sample.mp4",
)
```

## Tạo checkpoint đã chưng cất
Đường ống tạo hai giai đoạn nhanh nhất sử dụng điểm kiểm tra đã chưng cất.

```py
import torch
from diffusers.pipelines.ltx2 import LTX2Pipeline, LTX2LatentUpsamplePipeline
from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "rootonchair/LTX-2-19b-distilled"

pipe = LTX2Pipeline.from_pretrained(
    model_path, dtype=torch.bfloat16
)
pipe.enable_sequential_cpu_offload(device=device)

prompt = "A beautiful sunset over the ocean"
negative_prompt = "shaky, glitchy, low quality, worst quality, deformed, distorted, disfigured, motion smear, motion artifacts, fused fingers, bad anatomy, weird hand, ugly, transition, static."

frame_rate = 24.0
video_latent, audio_latent = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=8,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    generator=generator,
    output_type="latent",
    return_dict=False,
)

latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    model_path,
    subfolder="latent_upsampler",
    dtype=torch.bfloat16,
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
upsample_pipe.enable_model_cpu_offload(device=device)
upscaled_video_latent = upsample_pipe(
    latents=video_latent,
    output_type="latent",
    return_dict=False,
)[0]

video, audio = pipe(
    latents=upscaled_video_latent,
    audio_latents=audio_latent,
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=3,
    noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0], # renoise with first sigma value https://github.com/Lightricks/LTX-2/blob/main/packages/ltx-pipelines/src/ltx_pipelines/distilled.py#L178
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    generator=generator,
    guidance_scale=1.0,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_distilled_sample.mp4",
)
```

## Điều kiện tạo Pipeline

Bạn có thể sử dụng `LTX2ConditionPipeline` để chỉ định điều kiện hình ảnh và/hoặc video tại các chỉ số latent tùy ý. Ví dụ, chúng ta có thể chỉ định cả điều kiện khung hình đầu và khung hình cuối để thực hiện tạo video từ khung hình đầu-cuối (FLF2V):

```py
import torch
from diffusers import LTX2ConditionPipeline, LTX2LatentUpsamplePipeline
from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video
from diffusers.utils import load_image

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "rootonchair/LTX-2-19b-distilled"

pipe = LTX2ConditionPipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

prompt = (
    "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are "
    "delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright "
    "sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, "
    "low-angle perspective."
)

first_image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png",
)
last_image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png",
)
first_cond = LTX2VideoCondition(frames=first_image, index=0, strength=1.0)
last_cond = LTX2VideoCondition(frames=last_image, index=-1, strength=1.0)
conditions = [first_cond, last_cond]

frame_rate = 24.0
video_latent, audio_latent = pipe(
    conditions=conditions,
    prompt=prompt,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=8,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    generator=generator,
    output_type="latent",
    return_dict=False,
)

latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    model_path,
    subfolder="latent_upsampler",
    dtype=torch.bfloat16,
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
upsample_pipe.enable_model_cpu_offload(device=device)
upscaled_video_latent = upsample_pipe(
    latents=video_latent,
    output_type="latent",
    return_dict=False,
)[0]

video, audio = pipe(
    latents=upscaled_video_latent,
    audio_latents=audio_latent,
    prompt=prompt,
    width=width * 2,
    height=height * 2,
    num_inference_steps=3,
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    generator=generator,
    guidance_scale=1.0,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_distilled_flf2v.mp4",
)
```

Bạn có thể sử dụng cả điều kiện hình ảnh và video:

```py
import torch
from diffusers import LTX2ConditionPipeline
from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition
from diffusers.utils import encode_video
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT
from diffusers.utils import load_image, load_video

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "rootonchair/LTX-2-19b-distilled"

pipe = LTX2ConditionPipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

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."
)

cond_video = load_video(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
)
cond_image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
)
video_cond = LTX2VideoCondition(frames=cond_video, index=0, strength=1.0)
image_cond = LTX2VideoCondition(frames=cond_image, index=8, strength=1.0)
conditions = [video_cond, image_cond]

frame_rate = 24.0
video, audio = pipe(
    conditions=conditions,
    prompt=prompt,
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=30,
    guidance_scale=3.0,
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_cond_video.mp4",
)
```

Vì việc điều kiện hóa được thực hiện thông qua các khung tiềm ẩn, 8 khung trong không gian dữ liệu tương ứng với khung tiềm ẩn được chỉ định cho điều kiện hình ảnh sẽ có xu hướng tĩnh.

## Hướng dẫn đa phương thức

Các pipeline LTX-2.X hỗ trợ hướng dẫn đa phương thức. Nó bao gồm ba thành phần, tất cả đều sử dụng quy tắc cập nhật theo phong cách CFG:

1. Classifier-Free Guidance (CFG): [CFG](https://huggingface.co/papers/2207.12598) tiêu chuẩn, trong đó đầu ra bị nhiễu ("yếu hơn") được tạo ra bằng cách sử dụng prompt âm.
2. Spatio-Temporal Guidance (STG): [STG](https://huggingface.co/papers/2411.18664) từ bỏ việc sử dụng đầu ra bị nhiễu tạo ra từ việc bỏ qua các thao tác self-attention và thay vào đó là thay thế bằng các giá trị attention. Ý tưởng là cách này tạo ra các video sắc nét hơn và tính nhất quán không-thời gian tốt hơn.
3. Hướng dẫn cách ly chế độ (Modality Isolation Guidance): chuyển hướng khỏi đầu ra bị nhiễu tạo ra từ việc vô hiệu hóa chú ý chéo giữa các chế độ (cross attention) (âm thanh-sang-video và video-sang-âm thanh). Hướng dẫn này đặc thù hơn cho các mô hình [LTX-2.X](https://huggingface.co/papers/2601.03233), với ý tưởng rằng cách này tạo ra sự nhất quán tốt hơn giữa âm thanh và video được tạo ra.

Các tham số này được điều khiển bởi các đối số `guidance_scale`, `stg_scale` và `modality_scale`, và có thể được thiết lập riêng biệt cho video và âm thanh. Ngoài ra, đối với STG, cần chỉ định các chỉ số khối transformer mà tại đó self-attention bị bỏ qua thông qua đối số `spatio_temporal_guidance_blocks`. Các pipeline LTX-2.X cũng hỗ trợ [guidance rescaling](https://huggingface.co/papers/2305.08891) để giúp giảm hiện tượng quá phơi sáng, vốn có thể là một vấn đề khi các thang độ guidance được đặt ở giá trị cao.

```py
import torch
from diffusers import LTX2ImageToVideoPipeline
from diffusers.utils import encode_video
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT
from diffusers.utils import load_image

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
frame_rate = 24.0
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "diffusers/LTX-2.3-Diffusers"

pipe = LTX2ImageToVideoPipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

prompt = (
    "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in "
    "gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs "
    "before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small "
    "fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly "
    "shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a "
    "smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the "
    "distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a "
    "breath-taking, movie-like shot."
)

image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
)

video, audio = pipe(
    image=image,
    prompt=prompt,
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=30,
    guidance_scale=3.0,  # Recommended LTX-2.3 guidance parameters
    stg_scale=1.0,  # Note that 0.0 (not 1.0) means that STG is disabled (all other guidance is disabled at 1.0)
    modality_scale=3.0,
    guidance_rescale=0.7,
    audio_guidance_scale=7.0,  # Note that a higher CFG guidance scale is recommended for audio
    audio_stg_scale=1.0,
    audio_modality_scale=3.0,
    audio_guidance_rescale=0.7,
    spatio_temporal_guidance_blocks=[28],
    use_cross_timestep=True,
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_3_i2v_stage_1.mp4",
)
```

## Tăng cường Prompt

Các mô hình LTX-2.X nhạy cảm với phong cách viết prompt. Hãy tham khảo [hướng dẫn viết prompt chính thức](https://ltx.io/model/model-blog/prompting-guide-for-ltx-2) để có các khuyến nghị về cách viết một prompt tốt. Việc sử dụng tăng cường prompt, trong đó các prompt được cung cấp sẽ được tăng cường bằng text encoder của pipeline (mặc định là một mô hình [Gemma 3](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized)) dựa trên một system prompt, cũng có thể cải thiện chất lượng mẫu. Thành phần pipeline tùy chọn `processor` cần phải có mặt để sử dụng tăng cường prompt. Bật tính năng này bằng `enable_prompt_enhancement=True` và một `system_prompt` (tùy chọn, khớp với các pipeline tham chiếu của Lightricks):

```py
import torch
from transformers import Gemma3Processor
from diffusers import LTX2Pipeline
from diffusers.utils import encode_video
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT, T2V_DEFAULT_SYSTEM_PROMPT

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
frame_rate = 24.0
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "diffusers/LTX-2.3-Diffusers"

pipe = LTX2Pipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_model_cpu_offload(device=device)
pipe.vae.enable_tiling()
if getattr(pipe, "processor", None) is None:
    processor = Gemma3Processor.from_pretrained("google/gemma-3-12b-it-qat-q4_0-unquantized")
    pipe.processor = processor

prompt = (
    "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in "
    "gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs "
    "before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small "
    "fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly "
    "shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a "
    "smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the "
    "distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a "
    "breath-taking, movie-like shot."
)

video, audio = pipe(
    prompt=prompt,
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    num_inference_steps=30,
    guidance_scale=3.0,
    stg_scale=1.0,
    modality_scale=3.0,
    guidance_rescale=0.7,
    audio_guidance_scale=7.0,
    audio_stg_scale=1.0,
    audio_modality_scale=3.0,
    audio_guidance_rescale=0.7,
    spatio_temporal_guidance_blocks=[28],
    use_cross_timestep=True,
    enable_prompt_enhancement=True,
    system_prompt=T2V_DEFAULT_SYSTEM_PROMPT,
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_3_t2v_stage_1.mp4",
)
```

## LTX-2.5

LTX-2.5 tái sử dụng các lớp `LTX2Pipeline`/`LTX2VideoTransformer3DModel`/`AutoencoderKLLTX2Video`/v.v. giống hệt như LTX-2.3 — không có lớp pipeline riêng biệt cho nó. Sự khác biệt mà người dùng nhìn thấy là text encoder: LTX-2.5 được ghép với checkpoint Gemma 4 (`gemma4_unified`) thay vì Gemma 3. Checkpoint này được tải tự động khi bạn gọi `from_pretrained` trên một checkpoint LTX-2.5 đã được chuyển đổi (thông qua các lớp `Auto*` của `transformers`), nên không cần thiết lập thêm gì ở thời điểm suy luận — chỉ cần trỏ `from_pretrained` đến một repo LTX-2.5 thay vì repo LTX-2.3.

[`Lightricks/LTX-2.5-Diffusers`](https://huggingface.co/Lightricks/LTX-2.5-Diffusers) cung cấp cả hai transformer: DiT **distilled** trong `transformer/`, đây là nơi `model_index.json` trỏ tới, và DiT full/SFT trong `transformer_full/`, cần được nạp một cách tường minh (xem [Full / SFT transformer](#full--sft-transformer)). Thư mục `scheduler/` của repo được cấu hình cho checkpoint distilled (`use_dynamic_shifting=False`, `shift_terminal=None`) để lịch sigma của nó được sử dụng đúng như đã cho. Mọi thứ cần cho [two-stage generation](#two-stage-generation-for-ltx-25) cũng được cung cấp ở đó: một thư mục con `latent_upsampler/` và LoRA distilled của giai đoạn 2, `ltx-2.5-22b-distilled-lora-450-bf16.safetensors`, ở gốc repo.

Suy luận đã chưng cất được điều khiển bởi một lịch sigma rõ ràng thay vì số bước, và chạy không có hướng dẫn (`guidance_scale=1.0`, do đó `negative_prompt` không được sử dụng). Việc truyền `num_inference_steps` thay vào đó sẽ cung cấp cho mô hình một lịch tuyến tính chung chung và âm thầm làm giảm chất lượng:

```py
import torch
from diffusers import LTX2Pipeline
from diffusers.utils import encode_video
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
frame_rate = 24.0
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "Lightricks/LTX-2.5-Diffusers"

pipe = LTX2Pipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

prompt = "A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees."

video, audio = pipe(
    prompt=prompt,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    audio_guidance_scale=1.0,
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_t2v.mp4",
)
```

### Tạo hai giai đoạn cho LTX-2.5

LTX-2.5 hỗ trợ cả hai biến thể hai giai đoạn, và `DISTILLED_SIGMA_VALUES` / `STAGE_2_DISTILLED_SIGMA_VALUES` là các lịch tham chiếu của nó:

- **Checkpoint đã chưng cất, cả hai giai đoạn** — công thức tham chiếu cho `transformer/` mặc định, và công thức được hiển thị bên dưới. Không có LoRA giai đoạn 2 nào được sử dụng, vì transformer đã được chưng cất; đây là [Định dạng tạo checkpoint đã chưng cất](#distilled-checkpoint-generation) với trọng số LTX-2.5.
- **Giai đoạn 1 Full/SFT + giai đoạn 2 LoRA đã chưng cất** — [Sinh hai giai đoạn](#two-stages-generation) như đã mô tả ở đầu trang này, sử dụng `transformer_full/` và LoRA đi kèm. Xem [bên dưới](#stage-2-with-the-distilled-lora) để biết những gì thay đổi.

Stage 1 chạy ở một nửa độ phân giải mục tiêu, upsampler nhân đôi độ phân giải đó, và stage 2 tinh chỉnh ở độ phân giải đầy đủ — cả video *và* audio, đều được reseed từ các latents của stage 1 tại `noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0]`. Chiều cao và chiều rộng phải chia hết cho 64, vì stage 1 chia đôi mỗi trục và vẫn phải khớp với lưới không gian của VAE.

```py
import torch
from diffusers.pipelines.ltx2 import LTX2Pipeline, LTX2LatentUpsamplePipeline
from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video

device = "cuda"  # or "mps", "xpu", "cpu"
width = 1536
height = 1024
num_frames = 121
frame_rate = 24.0
model_path = "Lightricks/LTX-2.5-Diffusers"

# One generator for the whole call, threaded through both stages, so stage 2 continues the noise
# stream instead of repeating stage 1's draw.
generator = torch.Generator(device).manual_seed(42)

pipe = LTX2Pipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)

prompt = "A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees."

# Stage 1: half resolution, 8 distilled sigmas
video_latent, audio_latent = pipe(
    prompt=prompt,
    width=width // 2,
    height=height // 2,
    num_frames=num_frames,
    frame_rate=frame_rate,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    audio_guidance_scale=1.0,
    generator=generator,
    output_type="latent",
    return_dict=False,
)

latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    model_path,
    subfolder="latent_upsampler",
    dtype=torch.bfloat16,
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
upsample_pipe.enable_model_cpu_offload(device=device)
# `latents_normalized=False`: `output_type="latent"` already applied the latent statistics, and the
# upsampler is trained on denormalized latents. Stage 2 renormalizes them in `prepare_latents`.
upscaled_video_latent = upsample_pipe(
    latents=video_latent,
    latents_normalized=False,
    output_type="latent",
    return_dict=False,
)[0]

# Stage 2: full resolution, 3 sigmas, reseeded from stage 1. Pass `num_frames` explicitly here --
# omitting it would run the duration head a second time instead of using the stage 1 length.
pipe.vae.enable_tiling()
video, audio = pipe(
    prompt=prompt,
    latents=upscaled_video_latent,
    audio_latents=audio_latent,
    width=width,
    height=height,
    num_frames=num_frames,
    frame_rate=frame_rate,
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0],  # renoise with the stage 2 entry sigma
    guidance_scale=1.0,
    audio_guidance_scale=1.0,
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_t2v_two_stages.mp4",
)
```

Khi độ dài được lấy từ [duration head](#automatic-duration-for-ltx-25) thay vì `num_frames` được chỉ định rõ, hãy để stage 1 quyết định và khôi phục độ dài thực tế từ các latents của nó (`[B, C, F, H, W]`) trước khi stage 2 chạy, thay vì dự đoán thêm một lần nữa:

```py
num_frames = (video_latent.shape[2] - 1) * pipe.vae_temporal_compression_ratio + 1
```

#### Giai đoạn 2 với LoRA đã chưng cất

Để chạy [Two-stages Generation](#two-stages-generation) thay vào đó — DiT full/SFT cho giai đoạn 1, LoRA distilled cho giai đoạn 2 — hãy xây dựng pipeline như trong [Full / SFT transformer](#full--sft-transformer) và tạo latents cho giai đoạn 1 bằng guidance stack đó. Hai điểm sau khác biệt so với LTX-2.0/2.3. LoRA nằm trong kho diffusers thay vì đặt cạnh các trọng số gốc, và việc lật scheduler diễn ra theo chiều ngược lại: LTX-2.5 đi kèm cấu hình scheduler *distilled*, do đó giai đoạn 1 là nơi bật dynamic shifting, và giai đoạn 2 tắt nó lại.

```py
pipe.load_lora_weights(
    "Lightricks/LTX-2.5-Diffusers",
    adapter_name="stage_2_distilled",
    weight_name="ltx-2.5-22b-distilled-lora-450-bf16.safetensors",
)
pipe.set_adapters("stage_2_distilled", 1.0)
pipe.vae.enable_tiling()

pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(
    pipe.scheduler.config, use_dynamic_shifting=False, shift_terminal=None
)
```

Bước upsample và lời gọi stage 2 không thay đổi so với công thức distilled ở trên: cùng `sigmas=STAGE_2_DISTILLED_SIGMA_VALUES`, cùng `noise_scale`, và `guidance_scale=1.0`, vì stage 2 đang chạy một mô hình distilled trong mọi trường hợp.

### Giải mã tích chập và khuếch tán

LTX-2.5 cung cấp hai bộ giải mã video trên cùng một không gian ẩn, do đó các ẩn có thể hoán đổi cho nhau giữa chúng:

- `vae/` — VAE tích chập ([AutoencoderKLLTX2Video](/docs/diffusers/main/vi/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video)). Đây là thành phần mà các pipeline dùng để giải mã, vì vậy mọi đoạn mã ở trên đã sử dụng nó, và đây là thành phần duy nhất trong hai thành phần hỗ trợ chia ô (`pipe.vae.enable_tiling()`), điều này thường giúp xử lý được độ phân giải cao.
- `diffusion_decoder/` — [LTX2VideoDiffusionDecoderModel](/docs/diffusers/main/vi/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel). Đây là một mô hình diffusion độc lập chứ không phải thành phần của pipeline, nên không được truyền dưới dạng `vae`: hãy chạy pipeline với `output_type="latent"` và truyền các latent sang [LTX2VideoDiffusionDecodePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2VideoDiffusionDecodePipeline).

Việc mã hóa luôn đi qua `vae/`, do đó điều kiện hóa hình ảnh và video không bị ảnh hưởng bởi lựa chọn này.

Hai điều thay đổi khi bạn giải mã bằng diffusion decoder. `output_type="latent"` cũng bỏ qua vocoder, vì vậy âm thanh được trả về dưới dạng latents và phải được hoàn thiện thủ công, và bộ xử lý NATTEN thực sự là bắt buộc ở độ phân giải video:

```py
import torch
from diffusers import LTX2Pipeline, LTX2VideoDiffusionDecodePipeline, LTX2VideoDiffusionDecoderModel
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoVaeNeighborhoodNattenProcessor
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video

device = "cuda"  # or "mps", "xpu", "cpu"
frame_rate = 24.0
generator = torch.Generator(device).manual_seed(42)
model_path = "Lightricks/LTX-2.5-Diffusers"

pipe = LTX2Pipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_model_cpu_offload(device=device)

prompt = "A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees."

latents, audio_latents = pipe(
    prompt=prompt,
    width=960,
    height=544,
    num_frames=121,
    frame_rate=frame_rate,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    audio_guidance_scale=1.0,
    generator=generator,
    output_type="latent",
    return_dict=False,
)

# `output_type="latent"` skips the vocoder, so finish the audio by hand. These latents are already
# denormalized, which is what `audio_vae.decode` expects.
mel = pipe.audio_vae.decode(audio_latents.to(pipe.audio_vae.dtype), return_dict=False)[0]
audio = pipe.vocoder(mel)

decoder = LTX2VideoDiffusionDecoderModel.from_pretrained(
    model_path, subfolder="diffusion_decoder", dtype=torch.bfloat16
).to(device)
# The decoder runs on the `flex` backend by default, and uncompiled `flex_attention` materializes the
# full score matrix -- tens of GB at video resolutions. NATTEN's kernels are what the original
# implementation uses; they are fetched from the Hub by `kernels` (`pip install kernels`), not from a
# local NATTEN build. Switching the attention *backend* instead raises: only `flex` takes the BlockMask.
decoder.set_attn_processor(LTX2VideoVaeNeighborhoodNattenProcessor())
# Decode in overlapping tiles so peak memory scales with the tile size rather than the video size.
decoder.enable_tiling()

decode_pipe = LTX2VideoDiffusionDecodePipeline(diffusion_decoder=decoder, scheduler=pipe.scheduler)

# `denormalize=False`: `output_type="latent"` already applied the latent statistics, so applying them
# again would rescale every channel by its std a second time. The decoder draws the noise it denoises,
# so pass a generator to make decoding reproducible.
video = decode_pipe(
    latents, generator=generator, output_type="np", denormalize=False, return_dict=False
)[0]

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_t2v_diffusion_decode.mp4",
)
```

Để kết hợp điều này với [sinh hai giai đoạn](#two-stage-generation-for-ltx-25), hãy yêu cầu *giai đoạn 2* trả về `output_type="latent"` và giải mã kết quả đó.

`decoder.enable_tiling()` là cách giữ cho quá trình giải mã độ phân giải cao nằm trong bộ nhớ, tương tự như cách `pipe.vae.enable_tiling()` thực hiện cho VAE tích chập. Phần chiếm dụng bộ nhớ chủ yếu của quá trình giải mã — giai đoạn lấy mẫu lên cuối cùng và giai đoạn khuếch tán — sau đó sẽ chạy trên các ô chồng lấn được trộn lại với nhau, do đó bộ nhớ đỉnh được giới hạn bởi kích thước ô thay vì kích thước video. Tiling chỉ kích hoạt khi latent vượt quá một ô, và kích thước ô cùng phần chồng lấn có thể được tinh chỉnh thông qua các đối số `tile_sample_min_*` / `tile_sample_stride_*` (giá trị mặc định khớp với bản triển khai tham chiếu). Vì giai đoạn khuếch tán khử nhiễu từng ô riêng biệt, một bản giải mã dạng ô sẽ không tái tạo chính xác kết quả của bản giải mã không chia ô.

Trên một card duy nhất, cũng đáng để di chuyển pipeline sang một bên trước khi giải mã (`pipe.to("cpu")` và `torch.cuda.empty_cache()`, sau khi đã lưu lại `pipe.scheduler` và `output_sampling_rate` của vocoder), vì bộ giải mã cần không gian riêng. Xem [LTX2VideoDiffusionDecoderModel](/docs/diffusers/main/vi/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel) để biết về các backend attention, chi tiết tiling và các hành vi khác của bộ giải mã.

### Transformer Full / SFT

`transformer_full/` không được tham chiếu bởi `model_index.json`, do đó cần nạp nó một cách tường minh. Nó cũng cần một scheduler khác và một bộ guidance thực sự: `scheduler/` đi kèm được cấu hình cho checkpoint distilled, và các giá trị mặc định của guidance là các giá trị chung chung từ thời LTX-2.0, khiến một lần chạy SFT của LTX-2.5 bị thiếu guidance rõ rệt mà không gây ra bất kỳ cảnh báo nào. Các khuyến nghị về [Multimodal Guidance](#multimodal-guidance) áp dụng nguyên vẹn ở đây, bao gồm cả STG trên block `28`:

```py
import torch
from diffusers import FlowMatchEulerDiscreteScheduler, LTX2Pipeline, LTX2VideoTransformer3DModel
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT

device = "cuda"  # or "mps", "xpu", "cpu"
model_path = "Lightricks/LTX-2.5-Diffusers"

# Passing `transformer=` keeps `from_pretrained` from fetching the distilled folder as well.
transformer = LTX2VideoTransformer3DModel.from_pretrained(
    model_path, subfolder="transformer_full", dtype=torch.bfloat16
)
pipe = LTX2Pipeline.from_pretrained(model_path, transformer=transformer, dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

# Re-enable dynamic shifting and the terminal shift, which the distilled configuration turns off.
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(
    pipe.scheduler.config, use_dynamic_shifting=True, shift_terminal=0.1
)

video, audio = pipe(
    prompt="A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees.",
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=768,
    height=512,
    num_frames=121,
    frame_rate=24.0,
    num_inference_steps=30,
    guidance_scale=3.0,
    stg_scale=1.0,
    modality_scale=3.0,
    guidance_rescale=0.7,
    audio_guidance_scale=7.0,
    audio_stg_scale=1.0,
    audio_modality_scale=3.0,
    audio_guidance_rescale=0.7,
    spatio_temporal_guidance_blocks=[28],
    use_cross_timestep=True,
    generator=torch.Generator(device).manual_seed(42),
    output_type="np",
    return_dict=False,
)
```

Bỏ `sigmas` ở đây — DiT đầy đủ lấy lịch trình từ scheduler.

### Tăng cường Prompt cho LTX-2.5

**Việc sử dụng prompt enhancement được khuyến nghị mạnh mẽ cho LTX-2.5; hãy truyền `enable_prompt_enhancement=True` để bật tính năng này** (giống như các pipeline tham chiếu của Lightricks). Khác với LTX-2.0/2.3, nơi cùng một checkpoint text encoder đóng vai trò kép là enhancer (xem [Prompt Enhancement](#prompt-enhancement) ở trên), text encoder được fine-tune của LTX-2.5 không được huấn luyện cho enhancement. Thay vào đó, enhancement sử dụng một checkpoint `google/gemma-4-E2B-it` riêng biệt, có sẵn. Nạp nó vào các thành phần tùy chọn `prompt_enhancer`/`processor` của pipeline, sau đó bật enhancement — pipeline mặc định sử dụng `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` và công thức Gemma 4 (`do_sample=False`, `no_repeat_ngram_size=5`, `max_new_tokens=600`). Truyền một `system_prompt=` rõ ràng để ghi đè:

```py
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor
from diffusers import LTX2Pipeline
from diffusers.utils import encode_video
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES

device = "cuda"  # or "mps", "xpu", "cpu"
width = 768
height = 512
random_seed = 42
frame_rate = 24.0
generator = torch.Generator(device).manual_seed(random_seed)
model_path = "Lightricks/LTX-2.5-Diffusers"
enhancer_model_id = "google/gemma-4-E2B-it"

pipe = LTX2Pipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.enable_model_cpu_offload(device=device)
pipe.vae.enable_tiling()
if getattr(pipe, "prompt_enhancer", None) is None:
    pipe.prompt_enhancer = AutoModelForImageTextToText.from_pretrained(enhancer_model_id)
    pipe.processor = AutoProcessor.from_pretrained(enhancer_model_id)

prompt = "A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees."

video, audio = pipe(
    prompt=prompt,
    width=width,
    height=height,
    num_frames=121,
    frame_rate=frame_rate,
    sigmas=DISTILLED_SIGMA_VALUES,
    guidance_scale=1.0,
    audio_guidance_scale=1.0,
    enable_prompt_enhancement=True,
    # No `system_prompt=` needed -- defaults to `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` when `prompt_enhancer` is set.
    generator=generator,
    output_type="np",
    return_dict=False,
)

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_t2v_enhanced.mp4",
)
```

Điều tương tự cũng áp dụng cho image-to-video với `LTX2ImageToVideoPipeline`: đặt `pipe.prompt_enhancer`/`pipe.processor` theo cách tương tự và truyền `enable_prompt_enhancement=True` (sử dụng `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`, điều kiện hóa dựa trên cả hình ảnh tham chiếu và text prompt) — một lần nữa, không cần `system_prompt=` trừ khi bạn muốn ghi đè lên nó.

### Thời lượng tự động cho LTX-2.5

Các checkpoint của LTX-2.5 đi kèm một `duration_head` nhỏ, dự đoán độ dài của cảnh được mô tả, từ cùng đầu ra text-connector mà transformer được điều kiện hóa. Khi pipeline được nạp có thành phần này, **`num_frames` sẽ được tự động dự đoán theo mặc định** — hãy bỏ qua tham số này và để mô hình tự chọn độ dài:

```py
video, audio = pipe(prompt=prompt, output_type="np", return_dict=False)
```

Để tự đặt độ dài, hãy truyền `num_frames` một cách tường minh. Một số nguyên luôn được ưu tiên hơn phần đầu:

```py
video, audio = pipe(prompt=prompt, num_frames=121, output_type="np", return_dict=False)
```

Pipelines được nạp từ checkpoint LTX-2.0 hoặc LTX-2.3 không có duration head và giữ nguyên mặc định trước đó là 121 khung hình, do đó điều này không thay đổi gì đối với chúng.

Truyền `min_seconds` / `max_seconds` để ràng buộc dự đoán. Dự đoán thô sẽ bị kẹp vào khoảng đó, sau đó được chuyển đổi thành khung hình:

```py
video, audio = pipe(
    prompt=prompt,
    min_seconds=2.0,
    max_seconds=10.0,
    frame_rate=frame_rate,
    output_type="np",
    return_dict=False,
)
```

Số khung hình dự đoán được làm tròn theo lưới thời gian nhân quả của VAE (`8k + 1`), do đó thời lượng thực tế bị lượng tử hóa — khoảng 0,33 giây mỗi bước ở 24 fps — và thay đổi theo `frame_rate`, vì đầu ra dự đoán số giây thay vì số khung hình. `min_seconds` phải nhỏ hơn nghiêm ngặt so với `max_seconds`. Các giới hạn này bị bỏ qua khi `num_frames` được đặt rõ ràng.

Các giới hạn hẹp hơn một bước lưới có thể không thể thỏa mãn chính xác: ở 24 fps, `[1.0s, 1.02s]` được chuyển đổi thành `[24, 24]` khung hình, và 24 không phải là `8k + 1`. Điểm lưới gần nhất sẽ được sử dụng và một cảnh báo được ghi lại, do đó độ dài trả về có thể nằm ngay ngoài các giới hạn chặt chẽ như vậy.

Để kiểm tra một dự đoán mà không tạo video, hãy gọi trực tiếp phần đầu (head). Mọi thứ cần thiết đều là công khai:

```py
prompt_embeds, prompt_attention_mask, _, _ = pipe.encode_prompt(prompt, do_classifier_free_guidance=False)
video_tokens, audio_tokens, _ = pipe.connectors(prompt_embeds, prompt_attention_mask)

num_frames = pipe.duration_head.predict_num_frames(
    video_tokens,
    audio_tokens,
    frame_rate=24.0,
    temporal_compression_ratio=pipe.vae_temporal_compression_ratio,
)
seconds = pipe.duration_head(video_tokens, audio_tokens).item()  # raw, before clamping
print(f"predicted {seconds:.2f}s -> {num_frames} frames")
```

Việc chuyển đổi checkpoint 2.5 sẽ tự động lấy phần head với `--full_pipeline`, hoặc riêng lẻ với `--duration_head`. Các checkpoint trước 2.5 không có trọng số như vậy, và quá trình chuyển đổi sẽ bỏ qua thành phần này thay vì báo lỗi.

### Tốc độ chuyển động cho LTX-2.5

LTX-2 đặt mỗi token video trên một trục thời gian tính bằng giây, mặc định được suy ra từ `frame_rate`, tức là tốc độ phát. `motion_speed` (mặc định là `1.0`) tách biệt hai yếu tố này: trục thời gian được điều kiện hóa bởi `frame_rate / motion_speed`, trong khi độ dài âm thanh, [duration head](#automatic-duration-for-ltx-25) và video được trả về vẫn tuân theo `frame_rate`. Với `frame_rate=24.0` và `motion_speed=0.2`, mô hình được thông báo rằng hành động được ghi lại ở 120 fps và kết quả được phát ở 24 fps, tạo ra hiệu ứng chậm 5 lần.

Mô hình cơ sở được huấn luyện ở khoảng 24/25/30/60 fps, do đó các tốc độ khác xa `1.0` chỉ có ý nghĩa khi dùng kèm một adapter được huấn luyện riêng cho chúng, chẳng hạn [`Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control`](https://huggingface.co/Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control) (có kiểm soát truy cập: hãy chấp nhận giấy phép của nó trên Hub trước). Nếu không có `motion_speed`, LoRA đó sẽ được nạp như một LoRA thông thường và không cung cấp bất kỳ khả năng kiểm soát chuyển động nào. Thẻ mô hình đề xuất các tốc độ `1.0`, `0.5`, `0.2`, `0.1`, `0.05` và `0.025`, với cường độ LoRA là `1.0`. Hãy bỏ các từ chỉ tốc độ ("slow motion", "high fps") ra khỏi prompt và tái sử dụng cùng một caption cho các tốc độ khác nhau, vì chỉ `motion_speed` mới quyết định hiệu ứng.

```py
import torch
from diffusers import LTX2ImageToVideoPipeline
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video, load_image

device = "cuda"  # or "mps", "xpu", "cpu"
width = 1920  # the LoRA's recommended resolution; the effect is much weaker at 768x512
height = 1088
frame_rate = 24.0  # playback rate, always 24 for this LoRA
model_path = "Lightricks/LTX-2.5-Diffusers"

pipe = LTX2ImageToVideoPipeline.from_pretrained(model_path, dtype=torch.bfloat16)
pipe.load_lora_weights(
    "Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control",
    weight_name="ltx-2.5-22b-lora-slow-motion-control-1.0.safetensors",
    adapter_name="slow_motion",
)
pipe.set_adapters("slow_motion", 1.0)
pipe.enable_sequential_cpu_offload(device=device)
pipe.vae.enable_tiling()

image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
)
# No speed wording: the same caption is reused at every speed.
prompt = (
    "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking apart and lunar dust "
    "lifting into the air, while the camera pushes in."
)

for motion_speed in (1.0, 0.2):
    video, audio = pipe(
        image=image,
        prompt=prompt,
        width=width,
        height=height,
        num_frames=121,
        frame_rate=frame_rate,
        motion_speed=motion_speed,  # 1.0 = real time, 0.2 = 5x slow motion
        sigmas=DISTILLED_SIGMA_VALUES,
        guidance_scale=1.0,
        audio_guidance_scale=1.0,
        generator=torch.Generator(device).manual_seed(42),
        output_type="np",
        return_dict=False,
    )

    encode_video(
        video[0],
        fps=frame_rate,  # the file plays at the playback rate, not frame_rate / motion_speed
        audio=audio[0].float().cpu(),
        audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
        output_path=f"ltx2_5_i2v_motion_speed_{motion_speed}.mp4",
    )
```

Cả hai đoạn clip đều dài 121 khung hình (khoảng 5 giây ở 24 fps) và chỉ tốc độ của chuyển động thay đổi. Trong [sinh hai giai đoạn](#two-stage-generation-for-ltx-25), hãy truyền cùng một `motion_speed` cho **cả hai** giai đoạn. Giai đoạn 2 khử nhiễu lại video, và nó sẽ hủy bỏ hiệu ứng chậm nếu chạy trên trục thời gian thực. [Trình điều khiển tham chiếu](https://huggingface.co/Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control/blob/main/distilled_speed_demo.py) thực hiện điều tương tự bằng cách bọc đối tượng giai đoạn mà cả hai lần chạy đều dùng chung.

`motion_speed` cũng là một đầu vào của các khối module LTX-2 / LTX-2.5, và nó được truyền vào pipeline module theo cách tương tự.

### LTX-2.5 Modular

LTX-2.5 cũng có sẵn dưới dạng pipeline modular. Blockset mặc định sử dụng diffusion decoder và dự đoán thời lượng video khi `num_frames` bị bỏ qua. Nó áp dụng guidance riêng biệt cho video và audio thông qua các thành phần `guider` và `audio_guider`. Xem [LTX2Guidance](/docs/diffusers/main/vi/api/modular_diffusers/guiders#diffusers.LTX2Guidance) để biết các tham số guidance khả dụng. Mặc định, pipeline modular sẽ tải prompt enhancer và processor từ repo [google/gemma-4-E2B-it](https://huggingface.co/google/gemma-4-E2B-it). Dưới đây là một ví dụ modular T2V:

```py
import torch
from diffusers import ModularPipeline, ComponentsManager
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoVaeNeighborhoodNattenProcessor
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT
from diffusers.utils import encode_video

device = "cuda"  # or "mps", "xpu", "cpu"
frame_rate = 24.0
random_seed = 42
generator = torch.Generator(device).manual_seed(random_seed)

model_path = "Lightricks/LTX-2.5-Diffusers"

cm = ComponentsManager()
pipe = ModularPipeline.from_pretrained(model_path, components_manager=cm)
pipe.load_components(dtype=torch.bfloat16)
# Set memory_reserve_margin higher to more aggressively offload component models
cm.enable_auto_cpu_offload(device=device, memory_reserve_margin="20GB")
# The NATTEN processor works if `kernels` is available (`pip install kernels`)
# Otherwise omit the below line to use the Flex Attention processor
pipe.diffusion_decoder.set_attn_processor(LTX2VideoVaeNeighborhoodNattenProcessor())
pipe.diffusion_decoder.enable_tiling()

prompt = (
    "A cinematic shot of a red fox walking through a snowy forest at dawn, golden light filtering through pine trees."
)

output_state = pipe(
    prompt=prompt,
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=768,
    height=512,
    num_frames=None,  # Set to an int (e.g. 121) to specify a fixed video length
    frame_rate=frame_rate,
    num_inference_steps=30,
    use_cross_timestep=True,
    enable_prompt_enhancement=True,
    generator=generator,
    output_type="np",
)
video = output_state.get("videos")
audio = output_state.get("audio")

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_modular_t2v.mp4",
)
```

Pipeline dạng module sẽ tự động chuyển đổi quy trình làm việc dựa trên các đầu vào được cung cấp. Ví dụ, nếu `image` được cung cấp, quy trình làm việc I2V sẽ được sử dụng:

```py
import torch
from diffusers import ModularPipeline, ComponentsManager
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoVaeNeighborhoodNattenProcessor
from diffusers.pipelines.ltx2.utils import DEFAULT_NEGATIVE_PROMPT
from diffusers.utils import encode_video, load_image

device = "cuda"  # or "mps", "xpu", "cpu"
frame_rate = 24.0
random_seed = 42
generator = torch.Generator(device).manual_seed(random_seed)

model_path = "Lightricks/LTX-2.5-Diffusers"

cm = ComponentsManager()
pipe = ModularPipeline.from_pretrained(model_path, components_manager=cm)
pipe.load_components(dtype=torch.bfloat16)
cm.enable_auto_cpu_offload(device=device, memory_reserve_margin="20GB")
pipe.diffusion_decoder.set_attn_processor(LTX2VideoVaeNeighborhoodNattenProcessor())
pipe.diffusion_decoder.enable_tiling()

prompt = (
    "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in "
    "gentle low-gravity motion."
)
image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
image = load_image(image_path)

output_state = pipe(
    image=image,
    prompt=prompt,
    negative_prompt=DEFAULT_NEGATIVE_PROMPT,
    width=768,
    height=512,
    num_frames=None,  # Set to an int (e.g. 121) to specify a fixed video length
    frame_rate=frame_rate,
    num_inference_steps=30,
    use_cross_timestep=True,
    enable_prompt_enhancement=True,
    generator=generator,
    output_type="np",
)
video = output_state.get("videos")
audio = output_state.get("audio")

encode_video(
    video[0],
    fps=frame_rate,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_modular_i2v.mp4",
)
```

Bạn có thể xem các workflow được hỗ trợ trong tài liệu của mỗi blockset (ví dụ: [LTX2AutoBlocks](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2AutoBlocks), [LTX25AutoBlocks](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX25AutoBlocks)).

### Diffusion Fidelity Rendering (DFR) cho LTX-2.5

`LTX2DFRPipeline` đánh đổi thời gian thực thi để đổi lấy độ chi tiết. Mỗi lần gọi `__call__` là **một lượt khử nhiễu** ở kích thước `height` × `width`: nó tạo ra video cùng các **khung khóa** dạng khung đơn pixel bổ sung, hoặc khử nhiễu lại các latent được cung cấp, có nguồn gốc từ các khung khóa đó. Người gọi sẽ kết hợp các giai đoạn theo cách tương tự như các pipeline hai giai đoạn khác của LTX — pipeline này, [LTX2LatentUpsamplePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2LatentUpsamplePipeline), lại pipeline này, sau đó là [LTX2DFRTemporalRefinePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline) cho mỗi vòng lặp theo thời gian.

Một slot tốn một khung latent đầy đủ các token để mua một khung pixel, điều này làm nới lỏng mức nén thời gian hiệu dụng tại vị trí đó — do đó, video xung quanh được điều kiện hóa dựa trên các khung thực sự mới thay vì các khung nội suy. Các vị trí slot đến từ một lưới phân đoạn được căn chỉnh với biên thời gian của VAE (24 hoặc 32 khung pixel, tùy cái nào đệm ít hơn cho yêu cầu). Bức tranh được đệm đến một số nguyên các phân đoạn bên trong; `output_type="latent"` trả về lưới đã đệm đó để một slot trên phần đệm không bị loại bỏ. Cắt bằng `trim_canvas` trước khi giải mã VAE.

Điều này yêu cầu một transformer có config đặt `use_keyframes_abs_pos_embedding`, đánh dấu các latent của khung hình đơn pixel bằng một embedding đã học. Các checkpoint của LTX-2.5 được cung cấp kèm theo; pipeline sẽ gây lỗi với bất kỳ phiên bản cũ hơn thay vì tiêu tốn ngân sách token cho các token mà nó không thể diễn giải.

Dự trù ngân sách cho các token bổ sung: mỗi slot thêm một lượng tương đương một khung hình latent, do đó giai đoạn 2 chạy một chuỗi dài hơn so với lượt chạy hai giai đoạn đã chưng cất tương đương — tăng 31% ở độ phân giải 1024x1536 / 121 khung hình (24576 -> 32256 token, 5 slot trên lưới phân đoạn 24 khung hình). Bộ nhớ kích hoạt đỉnh tăng theo tỷ lệ đó, nên một độ phân giải vừa vặn với công thức chưng cất thông thường có thể cần `enable_sequential_cpu_offload`, `vae.enable_tiling()`, hoặc một khung hình nhỏ hơn dưới DFR.

Composition sử dụng `return_dict=True` cho `keyframes` và `keyframe_positions` (`return_dict=False` trả về bốn trường tương tự dưới dạng tuple).

Công thức đầy đủ bên dưới là công thức đáng để bắt đầu: tạo video từ ảnh kích thước 1088×1920, một vòng tinh chỉnh thời gian x2, và IC-LoRA chi tiết hóa không gian x2 ở giai đoạn 2.

```py
import torch
from diffusers import (
    LTX2DFRPipeline,
    LTX2DFRTemporalRefinePipeline,
    LTX2LatentUpsamplePipeline,
    LTXEulerAncestralRFScheduler,
)
from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.utils import trim_canvas
from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition
from diffusers.pipelines.ltx2.utils import STAGE_2_DISTILLED_SIGMA_VALUES
from diffusers.utils import encode_video, load_image

pipe = LTX2DFRPipeline.from_pretrained("Lightricks/LTX-2.5-Diffusers", torch_dtype=torch.bfloat16)
latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    "Lightricks/LTX-2.5-Diffusers", subfolder="latent_upsampler", torch_dtype=torch.bfloat16
)
# The x2 temporal upsampler is not in the published `model_index.json` — convert it with
# `--temporal_latent_upsampler`.
temporal_latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
    "path/to/converted/temporal_latent_upsampler", torch_dtype=torch.bfloat16
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
temporal_pipe = LTX2DFRTemporalRefinePipeline(
    scheduler=LTXEulerAncestralRFScheduler(eta=0.5),
    vae=pipe.vae,
    audio_vae=pipe.audio_vae,
    text_encoder=pipe.text_encoder,
    tokenizer=pipe.tokenizer,
    connectors=pipe.connectors,
    transformer=pipe.transformer,
    vocoder=pipe.vocoder,
    temporal_latent_upsampler=temporal_latent_upsampler,
)

# All three pipelines share the same components, so place them together. Do not call
# `enable_model_cpu_offload()` on one of them: its hooks would own modules the other two also call,
# and `temporal_latent_upsampler` — held only by `temporal_pipe` — would never reach the device.
pipe.to("cuda")
upsample_pipe.to("cuda")
temporal_pipe.to("cuda")

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
prompt = "A tabby cat stretching in a sunlit window, dust motes drifting in the light"
conditions = [LTX2VideoCondition(frames=image, index=0, strength=1.0)]
height, width = 1088, 1920
frame_rate = 24.0
generator = torch.Generator(device="cuda").manual_seed(0)

num_frames = 121
out = pipe(
    prompt=prompt,
    conditions=conditions,
    height=height // 2,
    width=width // 2,
    num_frames=num_frames,
    frame_rate=frame_rate,
    generator=generator,
    output_type="latent",
)
up_video = upsample_pipe(latents=out.frames, output_type="latent", return_dict=False)[0]
up_keyframes = upsample_pipe(latents=out.keyframes, output_type="latent", return_dict=False)[0]

# Load after stage 1 so the adapter is never disabled. `set_adapters` does not re-enable a
# transformer that already had `disable_adapters()` called on it.
pipe.load_lora_weights("Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler", adapter_name="detailing")
pipe.set_adapters(["detailing"], adapter_weights=[0.5])
out2 = pipe(
    prompt=prompt,
    conditions=conditions,
    latents=up_video,
    audio_latents=out.audio,
    keyframes_latents=up_keyframes,
    keyframe_positions=out.keyframe_positions,
    reference_latents=out.frames,
    height=height,
    width=width,
    num_frames=num_frames,
    frame_rate=frame_rate,
    noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0],
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    generator=generator,
    output_type="latent",
)
pipe.transformer.disable_adapters()

# `num_frames` here is the *padded* canvas the latents actually cover, which `resolve_canvas` may have
# grown past the 121 that were asked for. `condition_num_frames` stays the original request so a
# negative `condition.index` does not wrap onto the pad.
ratio = pipe.vae.temporal_compression_ratio
canvas_frames = (out2.frames.shape[2] - 1) * ratio + 1
out3 = temporal_pipe(
    latents=out2.frames,
    keyframes_latents=out2.keyframes,
    keyframe_positions=out2.keyframe_positions,
    audio_latents=out.audio,
    prompt=prompt,
    conditions=conditions,
    height=height,
    width=width,
    num_frames=canvas_frames,
    frame_rate=frame_rate,
    source_seconds=canvas_frames / frame_rate,
    condition_num_frames=num_frames,
    generator=generator,
    output_type="latent",
)

# Keep the padded canvas until decode so a slot on the pad is not dropped. `trim_canvas` counts *pixel*
# frames, and the round mapped `N -> 2 (N - 1) + 1`.
playback_fps = frame_rate * 2
requested_frames = (num_frames - 1) * 2 + 1
video_latents = trim_canvas(out3.frames, requested_frames, ratio)
timestep = None
if pipe.vae.config.timestep_conditioning:
    timestep = torch.zeros(video_latents.shape[0], device=video_latents.device, dtype=pipe.vae.dtype)
video = pipe.vae.decode(video_latents.to(pipe.vae.dtype), timestep, return_dict=False)[0]
video = pipe.video_processor.postprocess_video(video, output_type="np")

# Audio is stage 1's. Cut it to the video's duration so a muxed container does not outlast the picture.
audio = pipe.vocoder(pipe.audio_vae.decode(out.audio.to(pipe.audio_vae.dtype), return_dict=False)[0])
audio_samples = round(requested_frames / playback_fps * pipe.vocoder.config.output_sampling_rate)
audio = audio[..., : min(audio.shape[-1], audio_samples)]

encode_video(
    video[0],
    fps=playback_fps,
    audio=audio[0].float().cpu(),
    audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
    output_path="ltx2_5_dfr.mp4",
)
```

`height` và `width` là **đường đi này**, không phải đầu ra cuối cùng. Giai đoạn 1 chạy ở một nửa canvas 1080p (544×960); giai đoạn 2 ở 1088×1920. Mỗi đường đi phải chia hết cho tỷ lệ nén không gian của VAE (32 trên LTX-2.5 cho một đường đi đơn; 64 khi giai đoạn 1 là một nửa của 1080p). Đây là lý do 1080p là **1920×1088** và 4K là **3840×2176**. Mỗi đường đi chạy một lịch trình chưng cất cố định (`sigmas`), vì vậy không có `num_inference_steps`; các lịch trình chưng cất được huấn luyện mà không có hướng dẫn, vì vậy cũng không có `negative_prompt` hay `guidance_scale`. Âm thanh được cung cấp là của giai đoạn 1 — các đường đi sau vẫn chạy một luồng âm thanh để nhánh video có chú ý liên phương thức; chính dạng sóng không được tinh chỉnh sau giai đoạn 1.

**Chi tiết hóa không gian.** Nạp IC-LoRA chi tiết hóa không gian 2x dưới một adapter có tên **sau giai đoạn 1** và kích hoạt nó chỉ cho giai đoạn 2 (`set_adapters(["detailing"], adapter_weights=[0.5])`). Giai đoạn 2 sau đó sẽ chú ý đến latent bán độ phân giải của giai đoạn 1 như `reference_latents`. Giai đoạn 1 và các vòng thời gian chạy với adapter tắt. Nếu bạn nạp LoRA trước giai đoạn 1, `transformer.disable_adapters()` sẽ tắt nó, và `set_adapters` sẽ **không** bật lại — hãy gọi `transformer.enable_adapters()` trước giai đoạn 2, hoặc nạp trọng số sau giai đoạn 1 như trong công thức. `reference_downscale_factor` (mặc định `2`) sẽ thu nhỏ tọa độ không gian của các token tham chiếu vào không gian tọa độ của mục tiêu.

**Tinh chỉnh theo thời gian.** [LTX2DFRTemporalRefinePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline) là một vòng: lấy mẫu lên theo thời gian, chia tile tại các điểm nối keyframe, khử nhiễu tổ tiên bằng `LTXEulerAncestralRFScheduler` (`eta=0.5`), ghép lại bằng cách bỏ phần lead-in của tile sau, và hợp nhất túi keyframe mang theo. Hãy tự xây dựng scheduler đó — vòng sẽ bị từ chối nếu dùng bất kỳ thứ gì khác, vì một bước xác định sẽ chạy đến hoàn tất và chỉ trả về một canvas mềm hơn. Gọi pipeline một lần mỗi vòng; lặp cho 2x / 4x, truyền `round_index`. Sau một vòng, `keyframe_positions` không thể suy ra lại từ `num_frames` ban đầu và phải được truyền qua. Mỗi tile được giao phần slice của audio giai đoạn 1 đã đóng băng, bao phủ cửa sổ phát của chính nó. `source_seconds` là thời lượng *giai đoạn 1* và giữ nguyên qua các vòng, nên các vòng sau phải truyền nó một cách tường minh thay vì dùng giá trị mặc định.

Tốc độ khung hình (fps) điều kiện luôn là 60 bất cứ khi nào tốc độ phát vượt quá 30, độc lập với quá trình ghép kênh (muxing): thời gian RoPE là `pixel_frame / fps`, do đó cơ sở thời gian 120 fps sẽ làm giảm một nửa khoảng thời gian của mỗi token so với phân phối đã huấn luyện, còn 48 fps sẽ làm giãn nó. Cả hai đều khai báo là 60 và xử lý các khung hình đã giải mã theo tốc độ phát.

**Giai đoạn không gian thứ ba.** Kết hợp nó; không có pipeline thứ tư. Upsample không gian **chỉ video**, xây dựng lại các keyframe carry trong RGB (`decode` → Lanczos ×2 → `encode` thông qua [rebuild_epilogue_keyframes()](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.rebuild_epilogue_keyframes); không bao giờ latent-upsample các keyframe epilogue), sau đó:

```py
from diffusers.pipelines.ltx2.dfr_layout import epilogue_tiles, pixel_to_latent_index

# One more doubling on top of the recipe above, so every stage below the output halves again:
# `epilogue_height` must be divisible by 128 (`4 * 32`), which is why 4K is 3840x2176.
epilogue_height, epilogue_width = height * 2, width * 2
refined_frames = (out3.frames.shape[2] - 1) * ratio + 1

up_video = upsample_pipe(latents=out3.frames, output_type="latent", return_dict=False)[0]
epilogue_keyframes = pipe.rebuild_epilogue_keyframes(
    out3.keyframes,
    decode_timestep=0.0,
    decode_noise_scale=0.0,
    seed=0,
    device=up_video.device,
    dtype=torch.float32,
)

# Temporal cuts land on the seams the *last* round stitched on -- the positions handed into it, doubled --
# not on every carry keyframe, since the slots that round invented sit mid-window.
tiles = epilogue_tiles(
    latent_shape=(
        (refined_frames - 1) // ratio + 1,
        epilogue_height // pipe.vae.spatial_compression_ratio,
        epilogue_width // pipe.vae.spatial_compression_ratio,
    ),
    frame_tiles=2,  # 2 ** number of temporal rounds
    frame_seams=[pixel_to_latent_index(2 * p, ratio) for p in out2.keyframe_positions],
)

pipe.transformer.enable_adapters()  # the epilogue is a detailing pass too
out4 = pipe(
    prompt=prompt,
    conditions=conditions,
    latents=up_video,
    audio_latents=out.audio,
    generate_slots=False,
    guidance_keyframe_latents=epilogue_keyframes,
    guidance_keyframe_positions=out3.keyframe_positions,
    reference_latents=out3.frames,
    height=epilogue_height,
    width=epilogue_width,
    num_frames=refined_frames,
    frame_rate=playback_fps,
    noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0],
    sigmas=STAGE_2_DISTILLED_SIGMA_VALUES,
    freeze_audio=True,
    video_tiles=tiles,
    generator=generator,
    output_type="latent",
)
pipe.transformer.disable_adapters()
```

Hai trục được nối liền theo các cách khác nhau. Không có phía nào của một biên không gian chứa một câu trả lời đã biết, do đó các phần chồng lấn đó được trộn lẫn với trọng số hình thang. Các ô thời gian được cắt tại các đường nối khung hình chính của vòng tinh chỉnh cuối cùng.

**Giải mã bằng bộ giải mã khuếch tán.** Để đạt độ trung thực chi tiết tối đa, hãy giữ `output_type="latent"` và truyền các latent (đã được chuẩn hóa ngược, có thể đã được `trim_canvas`) cho [LTX2VideoDiffusionDecodePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2VideoDiffusionDecodePipeline).

```py
from diffusers import LTX2VideoDiffusionDecodePipeline
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoDiffusionDecoderModel

decoder = LTX2VideoDiffusionDecoderModel.from_pretrained(
    "Lightricks/LTX-2.5-Diffusers", subfolder="diffusion_decoder", dtype=torch.bfloat16
)
decode_pipe = LTX2VideoDiffusionDecodePipeline(
    diffusion_decoder=decoder, scheduler=pipe.scheduler, vae=pipe.vae
)
decode_pipe.enable_model_cpu_offload()
# `denormalize=False`: the `output_type="latent"` path already applied the latent statistics.
video = decode_pipe(latents=out3.frames, denormalize=False, output_type="np", return_dict=False)[0]
```

## LTX2Pipeline[[diffusers.LTX2Pipeline]]

#### diffusers.LTX2Pipeline[[diffusers.LTX2Pipeline]]

```python
diffusers.LTX2Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLLTX2Video, audio_vae: AutoencoderKLLTX2Audio, text_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGeneration, tokenizer: GemmaTokenizer, connectors: LTX2TextConnectors, transformer: LTX2VideoTransformer3DModel, vocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWE, processor: transformers.processing_utils.ProcessorMixin | None = None, prompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = None, duration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L209)

**Tham số:**

transformer ([LTXVideoTransformer3DModel](/docs/diffusers/main/vi/api/models/ltx_video_transformer3d#diffusers.LTXVideoTransformer3DModel)) : Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

vae ([AutoencoderKLLTXVideo](/docs/diffusers/main/vi/api/models/autoencoderkl_ltx_video#diffusers.AutoencoderKLLTXVideo)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.

text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), cụ thể là biến thể [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer (`T5TokenizerFast`) : Tokenizer thứ hai của lớp [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).

connectors (`LTX2TextConnectors`) : Bộ kết nối văn bản được sử dụng để điều chỉnh các trạng thái ẩn của bộ mã hóa văn bản cho các nhánh video và âm thanh.

Pipeline để tạo video từ văn bản.

Tham khảo: https://github.com/Lightricks/LTX-Video

#### __call__[[diffusers.LTX2Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 512, width: int = 768, num_frames: int | None = None, min_seconds: float = 1.0, max_seconds: float = 20.0, frame_rate: float = 24.0, motion_speed: float = 1.0, num_inference_steps: int = 30, sigmas: list[float] | None = None, timesteps: list = None, guidance_scale: float = 3.0, stg_scale: float = 1.0, modality_scale: float = 3.0, guidance_rescale: float = 0.7, audio_guidance_scale: float | None = 7.0, audio_stg_scale: float | None = 1.0, audio_modality_scale: float | None = 3.0, audio_guidance_rescale: float | None = 0.7, spatio_temporal_guidance_blocks: list[int] | None = [28], noise_scale: float = 0.0, num_videos_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, audio_latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, use_cross_timestep: bool = True, system_prompt: str | None = None, enable_prompt_enhancement: bool = False, prompt_max_new_tokens: int | None = None, prompt_enhancement_kwargs: dict[str, typing.Any] | None = None, prompt_enhancement_seed: int = 10, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 1024)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L929)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 480 theo mặc định để đạt kết quả tốt nhất.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt thành 848 để đạt kết quả tốt nhất.

num_frames (`int`, *optional*) : Số khung hình video cần tạo. Nếu không được cung cấp, giá trị mặc định sẽ là thời lượng tự dự đoán khi pipeline này có thành phần `duration_head` (các checkpoint từ LTX-2.5 trở về sau), và là `121` trong các trường hợp còn lại. Truyền một số nguyên để đặt độ dài một cách rõ ràng. Các giá trị đếm tự dự đoán sẽ được làm tròn theo lưới thời gian nhân quả của VAE, do đó thời lượng thực tế sẽ bị lượng tử hóa (khoảng 0,33 giây ở 24 fps).

min_seconds (`float`, *optional*, mặc định là `1.0`) : Giới hạn dưới của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng.

max_seconds (`float`, *optional*, mặc định là `20.0`) : Giới hạn trên của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng. Phải lớn hơn `min_seconds` một cách nghiêm ngặt.

frame_rate (`float`, *tùy chọn*, mặc định là `24.0`) : Số khung hình mỗi giây (FPS) của video được tạo ra.

motion_speed (`float`, *tuỳ chọn*, mặc định là `1.0`) : Tốc độ của chuyển động so với thời gian thực. Các nhúng vị trí được điều kiện bởi `frame_rate / motion_speed`, do đó các giá trị nhỏ hơn 1 sẽ làm chậm chuyển động, ví dụ `0.2` cho chuyển động chậm 5 lần của Slow-Motion-Control LoRA. `frame_rate` vẫn là tốc độ phát: thời lượng âm thanh và số khung hình dự đoán sẽ tuân theo nó.

num_inference_steps (`int`, *optional*, mặc định là 30) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

sigmas (`List[float]`, *tùy chọn*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

guidance_scale (`float`, *tuỳ chọn*, mặc định là `4.0`) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. Được sử dụng cho chế độ video (có một giá trị riêng `audio_guidance_scale` cho chế độ âm thanh).

stg_scale (`float`, *optional*, mặc định là `0.0`) : Thang độ dẫn hướng video cho Spatio-Temporal Guidance (STG), được đề xuất trong [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664). STG sử dụng một ước lượng kiểu CFG, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu từ một phiên bản bị nhiễu của mô hình khử nhiễu. Việc bật STG sẽ dẫn đến một lần truyền tiến thêm của mô hình khử nhiễu; giá trị mặc định `0.0` có nghĩa là STG bị tắt.

modality_scale (`float`, *optional*, mặc định là `1.0`) : Thang độ dẫn hướng video cho việc cách ly chế độ (modality isolation guidance) của LTX-2.X, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu hơn được tạo ra bởi mô hình khử nhiễu với cross-attention liên chế độ (audio-to-video và video-to-audio) bị vô hiệu hóa, sử dụng ước tính kiểu CFG. Việc bật dẫn hướng chế độ sẽ dẫn đến một lần truyền tiến (forward pass) bổ sung của mô hình khử nhiễu; giá trị mặc định `1.0` có nghĩa là dẫn hướng chế độ bị vô hiệu hóa.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance được đề xuất bởi [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` được định nghĩa là `φ` trong phương trình 16. của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR. Được dùng cho chế độ video.

audio_guidance_scale (`float`, *optional* mặc định là `None`) : Thang độ dẫn hướng âm thanh cho CFG đối với prompt tiêu cực. Quy tắc cập nhật CFG giống nhau cho video và âm thanh, nhưng chúng có thể sử dụng các giá trị khác nhau cho thang độ dẫn hướng. Các tác giả của LTX-2.X gợi ý rằng `audio_guidance_scale` nên cao hơn so với `guidance_scale` của video (ví dụ: đối với LTX-2.3, họ gợi ý 3.0 cho video và 7.0 cho âm thanh). Nếu là `None`, mặc định sẽ là giá trị video `guidance_scale`.

audio_stg_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho STG. Tương tự như CFG, quy tắc cập nhật STG về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 1.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `stg_scale`.

audio_modality_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho hướng dẫn cách ly phương thức của LTX-2.X. Giống như CFG, quy tắc hướng dẫn phương thức về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 3.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `modality_scale`.

audio_guidance_rescale (`float`, *tuỳ chọn*, mặc định là `None`) : Hệ số rescale guidance riêng cho chế độ âm thanh. Nếu là `None`, mặc định sẽ dùng giá trị video `guidance_rescale`.

spatio_temporal_guidance_blocks (`list[int]`, *tuỳ chọn*, mặc định là `None`) : Các chỉ số khối transformer bắt đầu từ 0 tại đó áp dụng STG. Bắt buộc phải cung cấp nếu sử dụng STG (`stg_scale` hoặc `audio_stg_scale` lớn hơn `0`). Giá trị `[29]` được khuyến nghị cho LTX-2.0 và `[28]` được khuyến nghị cho LTX-2.3.

noise_scale (`float`, *tuỳ chọn*, mặc định là `0.0`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại mỗi bước thời gian. Áp dụng nhiễu lên `latents` và `audio_latents` trước khi tiếp tục khử nhiễu.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể được sử dụng để điều chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

audio_latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo âm thanh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_prompt_attention_mask (`torch.FloatTensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã.

use_cross_timestep (`bool` *optional*, mặc định là `True`) : Có sử dụng sigma của liên phương thức (âm thanh là phương thức liên kết của video, và ngược lại) khi tính toán các tham số điều biến chú ý liên kết hay không. `True` là hành vi của LTX-2.3/2.5; `False` là hành vi cũ của LTX-2.0.

system_prompt (`str`, *tùy chọn*, mặc định là `None`) : Prompt hệ thống tùy chọn để sử dụng cho việc tăng cường prompt. Prompt hệ thống sẽ được sử dụng bởi trình tăng cường prompt (một mô hình sinh có điều kiện Gemma -- thành phần `prompt_enhancer` chuyên dụng nếu được cấu hình, nếu không thì là `text_encoder` chính) để tạo ra một prompt đã được tăng cường từ `prompt` gốc nhằm điều kiện hóa quá trình sinh. Nếu không được cung cấp và một `prompt_enhancer` chuyên dụng được cấu hình (LTX-2.5), giá trị mặc định sẽ là `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` (từ `diffusers.pipelines.ltx2.utils`) -- xem `enable_prompt_enhancement`.

enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là `False`) : Có chạy tăng cường prompt hay không. Tính năng này là tùy chọn, phù hợp với các pipeline tham chiếu của Lightricks. Khi `True` và `system_prompt` bị bỏ qua, LTX-2.5 sẽ sử dụng `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` nếu đã cấu hình `prompt_enhancer` riêng; LTX-2.0/2.3 yêu cầu phải có `system_prompt` rõ ràng.

prompt_max_new_tokens (`int`, *tuỳ chọn*, mặc định là `None`) : Số lượng token mới tối đa cần tạo ra khi thực hiện tăng cường prompt. Nếu không được cung cấp, hệ thống sẽ sử dụng 600 cho `prompt_enhancer` Gemma 4 chuyên dụng (LTX-2.5) hoặc 512 cho phương án dự phòng `text_encoder` Gemma 3 (LTX-2.0/2.3).

prompt_enhancement_kwargs (`dict[str, Any]`, *tùy chọn*, mặc định là `None`) : Các đối số từ khóa cho lời gọi `.generate` của trình tăng cường prompt. Nếu không được cung cấp, giá trị luôn khớp với mô hình đang thực hiện tăng cường: `do_sample=False, no_repeat_ngram_size=5` (tham lam) khi sử dụng `prompt_enhancer` chuyên dụng (LTX-2.5), hoặc `do_sample=True, temperature=0.7` cho phương án dự phòng `text_encoder` (LTX-2.0/2.3). Xem https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate để biết thêm chi tiết.

prompt_enhancement_seed (`int`, *tuỳ chọn*, mặc định là `10`) : Hạt ngẫu nhiên cho bất kỳ thao tác ngẫu nhiên nào trong quá trình tăng cường prompt.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.ltx.LTX2PipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*, mặc định là `["latents"]`) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là `1024`) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

**Trả về:** `~pipelines.ltx.LTX2PipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `~pipelines.ltx.LTX2PipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2Pipeline
>>> from diffusers.utils import encode_video

>>> pipe = LTX2Pipeline.from_pretrained("Lightricks/LTX-2", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()

>>> prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage"
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"

>>> frame_rate = 24.0
>>> video, audio = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     width=768,
...     height=512,
...     num_frames=121,
...     frame_rate=frame_rate,
...     num_inference_steps=30,
...     guidance_scale=3.0,
...     output_type="np",
...     return_dict=False,
... )

>>> encode_video(
...     video[0],
...     fps=frame_rate,
...     audio=audio[0].float().cpu(),
...     audio_sample_rate=pipe.vocoder.config.output_sampling_rate,  # should be 24000
...     output_path="video.mp4",
... )
```

#### encode_prompt[[diffusers.LTX2Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 1024, scale_factor: int = 8, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L367)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng classifier free guidance hay không.

num_videos_per_prompt (`int`, *optional*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt. Thiết bị torch để đặt các embeddings kết quả lên

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### enhance_prompt[[diffusers.LTX2Pipeline.enhance_prompt]]

```python
enhance_prompt(prompt: str, system_prompt: str, max_new_tokens: int | None = None, seed: int = 10, generator: typing.Optional[torch.Generator] = None, generation_kwargs: dict[str, typing.Any] | None = None, device: typing.Union[str, torch.device, NoneType] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L574)

Tăng cường `prompt` được cung cấp bằng cách tạo một prompt mới từ `prompt` đó và một system prompt, sử dụng prompt enhancer (một mô hình sinh có điều kiện Gemma). Khi có `image`, enhancer cũng được điều kiện hóa dựa trên khung tham chiếu đó (tăng cường theo kiểu I2V / keyframe). Sử dụng thành phần `prompt_enhancer` chuyên dụng nếu có cấu hình (ví dụ: LTX-2.5, nơi text encoder không được huấn luyện cho việc tăng cường), nếu không sẽ dùng `text_encoder` chính (LTX-2.0/2.3, vốn đóng vai trò là enhancer của chính nó).

Các mẫu thông báo, kwargs giải mã, làm sạch phản hồi và chuẩn bị cạnh dài của ảnh khớp với `ltx-core` / `ltx-pipelines` (`enhance_t2v` / `enhance_i2v` / `generate_enhanced_prompt`).

## LTX2ImageToVideoPipeline[[diffusers.LTX2ImageToVideoPipeline]]

#### diffusers.LTX2ImageToVideoPipeline[[diffusers.LTX2ImageToVideoPipeline]]

```python
diffusers.LTX2ImageToVideoPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLLTX2Video, audio_vae: AutoencoderKLLTX2Audio, text_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGeneration, tokenizer: GemmaTokenizer, connectors: LTX2TextConnectors, transformer: LTX2VideoTransformer3DModel, vocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWE, processor: transformers.processing_utils.ProcessorMixin | None = None, prompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = None, duration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L229)

Pipeline để tạo video từ ảnh.

Tham khảo: https://github.com/Lightricks/LTX-Video

TODO

#### __call__[[diffusers.LTX2ImageToVideoPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 512, width: int = 768, num_frames: int | None = None, min_seconds: float = 1.0, max_seconds: float = 20.0, frame_rate: float = 24.0, motion_speed: float = 1.0, num_inference_steps: int = 30, sigmas: list[float] | None = None, timesteps: list[int] | None = None, guidance_scale: float = 3.0, stg_scale: float = 1.0, modality_scale: float = 3.0, guidance_rescale: float = 0.7, audio_guidance_scale: float | None = 7.0, audio_stg_scale: float | None = 1.0, audio_modality_scale: float | None = 3.0, audio_guidance_rescale: float | None = 0.7, spatio_temporal_guidance_blocks: list[int] | None = [28], noise_scale: float = 0.0, num_videos_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, audio_latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, use_cross_timestep: bool = True, system_prompt: str | None = None, enable_prompt_enhancement: bool = False, prompt_max_new_tokens: int | None = None, prompt_enhancement_kwargs: dict[str, typing.Any] | None = None, prompt_enhancement_seed: int = 10, image_crf: int | None = None, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 1024)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L983)

**Tham số:**

image (`PipelineImageInput`) : Ảnh đầu vào để điều kiện cho quá trình tạo. Phải là một ảnh, một danh sách các ảnh hoặc một `torch.Tensor`.

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 480 theo mặc định để đạt kết quả tốt nhất.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt thành 848 để đạt kết quả tốt nhất.

num_frames (`int`, *optional*) : Số khung hình video cần tạo. Nếu không được cung cấp, giá trị mặc định sẽ là thời lượng tự dự đoán khi pipeline này có thành phần `duration_head` (các checkpoint từ LTX-2.5 trở về sau), và là `121` trong các trường hợp còn lại. Truyền một số nguyên để đặt độ dài một cách rõ ràng. Các giá trị đếm tự dự đoán sẽ được làm tròn theo lưới thời gian nhân quả của VAE, do đó thời lượng thực tế sẽ bị lượng tử hóa (khoảng 0,33 giây ở 24 fps).

min_seconds (`float`, *optional*, mặc định là `1.0`) : Giới hạn dưới của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng.

max_seconds (`float`, *optional*, mặc định là `20.0`) : Giới hạn trên của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng. Phải lớn hơn `min_seconds` một cách nghiêm ngặt.

frame_rate (`float`, *tùy chọn*, mặc định là `24.0`) : Số khung hình mỗi giây (FPS) của video được tạo ra.

motion_speed (`float`, *tuỳ chọn*, mặc định là `1.0`) : Tốc độ của chuyển động so với thời gian thực. Các nhúng vị trí được điều kiện bởi `frame_rate / motion_speed`, do đó các giá trị nhỏ hơn 1 sẽ làm chậm chuyển động, ví dụ `0.2` cho chuyển động chậm 5 lần của Slow-Motion-Control LoRA. `frame_rate` vẫn là tốc độ phát: thời lượng âm thanh và số khung hình dự đoán sẽ tuân theo nó.

num_inference_steps (`int`, *optional*, mặc định là 30) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

sigmas (`List[float]`, *tùy chọn*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

timesteps (`List[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

guidance_scale (`float`, *tuỳ chọn*, mặc định là `4.0`) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. Được sử dụng cho chế độ video (có một giá trị riêng `audio_guidance_scale` cho chế độ âm thanh).

stg_scale (`float`, *optional*, mặc định là `0.0`) : Thang độ dẫn hướng video cho Spatio-Temporal Guidance (STG), được đề xuất trong [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664). STG sử dụng một ước lượng kiểu CFG, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu từ một phiên bản bị nhiễu của mô hình khử nhiễu. Việc bật STG sẽ dẫn đến một lần truyền tiến thêm của mô hình khử nhiễu; giá trị mặc định `0.0` có nghĩa là STG bị tắt.

modality_scale (`float`, *optional*, mặc định là `1.0`) : Thang độ dẫn hướng video cho việc cách ly chế độ (modality isolation guidance) của LTX-2.X, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu hơn được tạo ra bởi mô hình khử nhiễu với cross-attention liên chế độ (audio-to-video và video-to-audio) bị vô hiệu hóa, sử dụng ước tính kiểu CFG. Việc bật dẫn hướng chế độ sẽ dẫn đến một lần truyền tiến (forward pass) bổ sung của mô hình khử nhiễu; giá trị mặc định `1.0` có nghĩa là dẫn hướng chế độ bị vô hiệu hóa.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance được đề xuất bởi [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` được định nghĩa là `φ` trong phương trình 16. của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR. Được dùng cho chế độ video.

audio_guidance_scale (`float`, *optional* mặc định là `None`) : Thang độ dẫn hướng âm thanh cho CFG đối với prompt tiêu cực. Quy tắc cập nhật CFG giống nhau cho video và âm thanh, nhưng chúng có thể sử dụng các giá trị khác nhau cho thang độ dẫn hướng. Các tác giả của LTX-2.X gợi ý rằng `audio_guidance_scale` nên cao hơn so với `guidance_scale` của video (ví dụ: đối với LTX-2.3, họ gợi ý 3.0 cho video và 7.0 cho âm thanh). Nếu là `None`, mặc định sẽ là giá trị video `guidance_scale`.

audio_stg_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho STG. Tương tự như CFG, quy tắc cập nhật STG về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 1.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `stg_scale`.

audio_modality_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho hướng dẫn cách ly phương thức của LTX-2.X. Giống như CFG, quy tắc hướng dẫn phương thức về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 3.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `modality_scale`.

audio_guidance_rescale (`float`, *tuỳ chọn*, mặc định là `None`) : Hệ số rescale guidance riêng cho chế độ âm thanh. Nếu là `None`, mặc định sẽ dùng giá trị video `guidance_rescale`.

spatio_temporal_guidance_blocks (`list[int]`, *tuỳ chọn*, mặc định là `None`) : Các chỉ số khối transformer bắt đầu từ 0 tại đó áp dụng STG. Bắt buộc phải cung cấp nếu sử dụng STG (`stg_scale` hoặc `audio_stg_scale` lớn hơn `0`). Giá trị `[29]` được khuyến nghị cho LTX-2.0 và `[28]` được khuyến nghị cho LTX-2.3.

noise_scale (`float`, *tuỳ chọn*, mặc định là `0.0`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại mỗi bước thời gian. Áp dụng nhiễu lên `latents` và `audio_latents` trước khi tiếp tục khử nhiễu.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể được sử dụng để điều chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

audio_latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo âm thanh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_prompt_attention_mask (`torch.FloatTensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã.

use_cross_timestep (`bool` *optional*, mặc định là `True`) : Có sử dụng sigma của liên phương thức (âm thanh là phương thức liên kết của video, và ngược lại) khi tính toán các tham số điều biến chú ý liên kết hay không. `True` là hành vi của LTX-2.3/2.5; `False` là hành vi cũ của LTX-2.0.

system_prompt (`str`, *tùy chọn*, mặc định là `None`) : Prompt hệ thống tùy chọn để sử dụng cho việc tăng cường prompt. Prompt hệ thống sẽ được sử dụng bởi trình tăng cường prompt (một mô hình sinh có điều kiện Gemma -- thành phần `prompt_enhancer` chuyên dụng nếu được cấu hình, nếu không thì là `text_encoder` chính) để tạo ra một prompt đã được tăng cường từ `prompt` gốc và `image` đầu tiên để điều kiện hóa quá trình sinh. Nếu không được cung cấp và một `prompt_enhancer` chuyên dụng được cấu hình (LTX-2.5), giá trị mặc định sẽ là `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` (từ `diffusers.pipelines.ltx2.utils`) -- xem `enable_prompt_enhancement`.

enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là `False`) : Có chạy tăng cường prompt hay không. Tính năng này là tùy chọn, phù hợp với các pipeline tham chiếu của Lightricks. Khi `True` và `system_prompt` bị bỏ qua, LTX-2.5 sẽ sử dụng `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` nếu đã cấu hình `prompt_enhancer` riêng; LTX-2.0/2.3 yêu cầu phải có `system_prompt` rõ ràng.

prompt_max_new_tokens (`int`, *tuỳ chọn*, mặc định là `None`) : Số lượng token mới tối đa cần tạo ra khi thực hiện tăng cường prompt. Nếu không được cung cấp, hệ thống sẽ sử dụng 600 cho `prompt_enhancer` Gemma 4 chuyên dụng (LTX-2.5) hoặc 512 cho phương án dự phòng `text_encoder` Gemma 3 (LTX-2.0/2.3).

prompt_enhancement_kwargs (`dict[str, Any]`, *tùy chọn*, mặc định là `None`) : Các đối số từ khóa cho lời gọi `.generate` của trình tăng cường prompt. Nếu không được cung cấp, giá trị luôn khớp với mô hình đang thực hiện tăng cường: `do_sample=False, no_repeat_ngram_size=3` (tham lam) khi sử dụng `prompt_enhancer` chuyên dụng (LTX-2.5), hoặc `do_sample=True, temperature=0.7` cho phương án dự phòng `text_encoder` (LTX-2.0/2.3). Xem https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate để biết thêm chi tiết.

prompt_enhancement_seed (`int`, *tuỳ chọn*, mặc định là `10`) : Hạt ngẫu nhiên cho bất kỳ thao tác ngẫu nhiên nào trong quá trình tăng cường prompt.

image_crf (`int`, *tuỳ chọn*, mặc định là `None`) : CRF của H.264 được sử dụng để nén lại hình ảnh điều kiện `image` trước khi mã hóa VAE, khớp với mức nén mà mô hình được huấn luyện. `None` có nghĩa là "sử dụng mặc định của mô hình" (33 cho LTX-2.3, 18 cho LTX-2.5). Truyền `0` để bỏ qua việc nén lại. Yêu cầu `PIL.Image.Image` khi chạy nén lại.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.ltx.LTX2PipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là `1024`) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

**Trả về:** `~pipelines.ltx.LTX2PipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `~pipelines.ltx.LTX2PipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2ImageToVideoPipeline
>>> from diffusers.utils import encode_video
>>> from diffusers.utils import load_image

>>> pipe = LTX2ImageToVideoPipeline.from_pretrained("Lightricks/LTX-2", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()

>>> image = load_image(
...     "https://huggingface.co/datasets/a-r-r-o-w/tiny-meme-dataset-captioned/resolve/main/images/8.png"
... )
>>> prompt = "A young girl stands calmly in the foreground, looking directly at the camera, as a house fire rages in the background."
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"

>>> frame_rate = 24.0
>>> video, audio = pipe(
...     image=image,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     width=768,
...     height=512,
...     num_frames=121,
...     frame_rate=frame_rate,
...     num_inference_steps=30,
...     guidance_scale=3.0,
...     output_type="np",
...     return_dict=False,
... )

>>> encode_video(
...     video[0],
...     fps=frame_rate,
...     audio=audio[0].float().cpu(),
...     audio_sample_rate=pipe.vocoder.config.output_sampling_rate,  # should be 24000
...     output_path="video.mp4",
... )
```

#### encode_prompt[[diffusers.LTX2ImageToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 1024, scale_factor: int = 8, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L372)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng classifier free guidance hay không.

num_videos_per_prompt (`int`, *optional*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt. Thiết bị torch để đặt các embeddings kết quả lên

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### enhance_prompt[[diffusers.LTX2ImageToVideoPipeline.enhance_prompt]]

```python
enhance_prompt(prompt: str, system_prompt: str, max_new_tokens: int | None = None, seed: int = 10, generator: typing.Optional[torch.Generator] = None, generation_kwargs: dict[str, typing.Any] | None = None, device: typing.Union[str, torch.device, NoneType] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L580)

Tăng cường `prompt` được cung cấp bằng cách tạo một prompt mới từ nó và một system prompt, sử dụng prompt enhancer (một mô hình sinh có điều kiện Gemma). Khi có `image`, enhancer cũng được điều kiện hóa dựa trên khung tham chiếu đó (tăng cường theo kiểu I2V / keyframe). Sử dụng thành phần `prompt_enhancer` chuyên dụng nếu có cấu hình (ví dụ: LTX-2.5, nơi text encoder không được huấn luyện cho việc tăng cường), nếu không sẽ dùng `text_encoder` chính (LTX-2.0/2.3, vốn đóng vai trò là enhancer của chính nó).

Các mẫu thông báo, kwargs giải mã, làm sạch phản hồi và chuẩn bị cạnh dài của ảnh khớp với `ltx-core` / `ltx-pipelines` (`enhance_t2v` / `enhance_i2v` / `generate_enhanced_prompt`).

## LTX2ConditionPipeline[[diffusers.LTX2ConditionPipeline]]

#### diffusers.LTX2ConditionPipeline[[diffusers.LTX2ConditionPipeline]]

```python
diffusers.LTX2ConditionPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLLTX2Video, audio_vae: AutoencoderKLLTX2Audio, text_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGeneration, tokenizer: GemmaTokenizer, connectors: LTX2TextConnectors, transformer: LTX2VideoTransformer3DModel, vocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWE, audio_scheduler: diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler | None = None, processor: transformers.processing_utils.ProcessorMixin | None = None, prompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = None, duration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L266)

Pipeline để tạo video cho phép chèn các điều kiện hình ảnh vào các phần bất kỳ của video.

Tham khảo: https://github.com/Lightricks/LTX-Video

TODO

#### __call__[[diffusers.LTX2ConditionPipeline.__call__]]

```python
__call__(conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int = 512, width: int = 768, num_frames: int | None = None, min_seconds: float = 1.0, max_seconds: float = 20.0, frame_rate: float = 24.0, motion_speed: float = 1.0, num_inference_steps: int = 30, sigmas: list[float] | None = None, timesteps: list[float] | None = None, guidance_scale: float = 3.0, stg_scale: float = 1.0, modality_scale: float = 3.0, guidance_rescale: float = 0.7, audio_guidance_scale: float | None = 7.0, audio_stg_scale: float | None = 1.0, audio_modality_scale: float | None = 3.0, audio_guidance_rescale: float | None = 0.7, spatio_temporal_guidance_blocks: list[int] | None = [28], noise_scale: float | None = None, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, audio_latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, use_cross_timestep: bool = True, system_prompt: str | None = None, enable_prompt_enhancement: bool = False, prompt_max_new_tokens: int | None = None, prompt_enhancement_kwargs: dict[str, typing.Any] | None = None, prompt_enhancement_seed: int = 10, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 1024)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L1348)

**Tham số:**

conditions (`List[LTXVideoCondition], *optional*`) : Danh sách các mục điều kiện khung hình cho việc tạo video.

prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 480 theo mặc định để đạt kết quả tốt nhất.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt thành 848 để đạt kết quả tốt nhất.

num_frames (`int`, *optional*) : Số khung hình video cần tạo. Nếu không được cung cấp, giá trị mặc định sẽ là thời lượng tự dự đoán khi pipeline này có thành phần `duration_head` (các checkpoint từ LTX-2.5 trở về sau), và là `121` trong các trường hợp còn lại. Truyền một số nguyên để đặt độ dài một cách rõ ràng. Các giá trị đếm tự dự đoán sẽ được làm tròn theo lưới thời gian nhân quả của VAE, do đó thời lượng thực tế sẽ bị lượng tử hóa (khoảng 0,33 giây ở 24 fps).

min_seconds (`float`, *optional*, mặc định là `1.0`) : Giới hạn dưới của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng.

max_seconds (`float`, *optional*, mặc định là `20.0`) : Giới hạn trên của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua và có `duration_head`. Bỏ qua khi `num_frames` được đặt rõ ràng. Phải lớn hơn `min_seconds` một cách nghiêm ngặt.

frame_rate (`float`, *tùy chọn*, mặc định là `24.0`) : Số khung hình mỗi giây (FPS) của video được tạo ra.

motion_speed (`float`, *tuỳ chọn*, mặc định là `1.0`) : Tốc độ của chuyển động so với thời gian thực. Các nhúng vị trí được điều kiện bởi `frame_rate / motion_speed`, do đó các giá trị nhỏ hơn 1 sẽ làm chậm chuyển động, ví dụ `0.2` cho chuyển động chậm 5 lần của Slow-Motion-Control LoRA. `frame_rate` vẫn là tốc độ phát: thời lượng âm thanh và số khung hình dự đoán sẽ tuân theo nó.

num_inference_steps (`int`, *optional*, mặc định là 30) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

sigmas (`List[float]`, *tùy chọn*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

timesteps (`List[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

guidance_scale (`float`, *tuỳ chọn*, mặc định là `4.0`) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. Được sử dụng cho chế độ video (có một giá trị riêng `audio_guidance_scale` cho chế độ âm thanh).

stg_scale (`float`, *optional*, mặc định là `0.0`) : Thang độ dẫn hướng video cho Spatio-Temporal Guidance (STG), được đề xuất trong [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664). STG sử dụng một ước lượng kiểu CFG, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu từ một phiên bản bị nhiễu của mô hình khử nhiễu. Việc bật STG sẽ dẫn đến một lần truyền tiến thêm của mô hình khử nhiễu; giá trị mặc định `0.0` có nghĩa là STG bị tắt.

modality_scale (`float`, *optional*, mặc định là `1.0`) : Thang độ dẫn hướng video cho việc cách ly chế độ (modality isolation guidance) của LTX-2.X, trong đó chúng ta di chuyển mẫu ra xa khỏi một mẫu yếu hơn được tạo ra bởi mô hình khử nhiễu với cross-attention liên chế độ (audio-to-video và video-to-audio) bị vô hiệu hóa, sử dụng ước tính kiểu CFG. Việc bật dẫn hướng chế độ sẽ dẫn đến một lần truyền tiến (forward pass) bổ sung của mô hình khử nhiễu; giá trị mặc định `1.0` có nghĩa là dẫn hướng chế độ bị vô hiệu hóa.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance được đề xuất bởi [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` được định nghĩa là `φ` trong phương trình 16. của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR. Được dùng cho chế độ video.

audio_guidance_scale (`float`, *optional* mặc định là `None`) : Thang độ dẫn hướng âm thanh cho CFG đối với prompt tiêu cực. Quy tắc cập nhật CFG giống nhau cho video và âm thanh, nhưng chúng có thể sử dụng các giá trị khác nhau cho thang độ dẫn hướng. Các tác giả của LTX-2.X gợi ý rằng `audio_guidance_scale` nên cao hơn so với `guidance_scale` của video (ví dụ: đối với LTX-2.3, họ gợi ý 3.0 cho video và 7.0 cho âm thanh). Nếu là `None`, mặc định sẽ là giá trị video `guidance_scale`.

audio_stg_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho STG. Tương tự như CFG, quy tắc cập nhật STG về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 1.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `stg_scale`.

audio_modality_scale (`float`, *optional*, mặc định là `None`) : Thang độ dẫn hướng âm thanh cho hướng dẫn cách ly phương thức của LTX-2.X. Giống như CFG, quy tắc hướng dẫn phương thức về cơ bản là giống nhau cho cả video và âm thanh. Đối với LTX-2.3, giá trị 3.0 được đề xuất cho cả video và âm thanh. Nếu `None`, mặc định là giá trị video `modality_scale`.

audio_guidance_rescale (`float`, *tuỳ chọn*, mặc định là `None`) : Hệ số rescale guidance riêng cho chế độ âm thanh. Nếu là `None`, mặc định sẽ dùng giá trị video `guidance_rescale`.

spatio_temporal_guidance_blocks (`list[int]`, *tuỳ chọn*, mặc định là `None`) : Các chỉ số khối transformer bắt đầu từ 0 tại đó áp dụng STG. Bắt buộc phải cung cấp nếu sử dụng STG (`stg_scale` hoặc `audio_stg_scale` lớn hơn `0`). Giá trị `[29]` được khuyến nghị cho LTX-2.0 và `[28]` được khuyến nghị cho LTX-2.3.

noise_scale (`float`, *tuỳ chọn*, mặc định là `None`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại mỗi bước thời gian. Áp dụng nhiễu lên `latents` và `audio_latents` trước khi tiếp tục khử nhiễu. Nếu không được đặt, giá trị này sẽ được suy ra từ lịch sigma.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `List[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) để làm cho quá trình sinh trở nên tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể được sử dụng để điều chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

audio_latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo âm thanh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_prompt_attention_mask (`torch.FloatTensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã.

use_cross_timestep (`bool` *optional*, mặc định là `True`) : Có sử dụng sigma của liên phương thức (âm thanh là phương thức liên kết của video, và ngược lại) khi tính toán các tham số điều biến chú ý liên kết hay không. `True` là hành vi của LTX-2.3/2.5; `False` là hành vi cũ của LTX-2.0.

system_prompt (`str`, *tùy chọn*, mặc định là `None`) : Prompt hệ thống tùy chọn để sử dụng cho việc tăng cường prompt. Prompt hệ thống sẽ được sử dụng bởi trình tăng cường prompt (một mô hình sinh có điều kiện Gemma -- thành phần `prompt_enhancer` chuyên dụng nếu được cấu hình, nếu không thì là `text_encoder` chính) để tạo ra một prompt đã được tăng cường từ `prompt` gốc (và một hình ảnh điều kiện nếu có sẵn) nhằm điều kiện hóa quá trình sinh. Nếu không được cung cấp và một `prompt_enhancer` chuyên dụng được cấu hình (LTX-2.5), giá trị mặc định sẽ là `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` khi có hình ảnh điều kiện, nếu không thì là `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` -- xem `enable_prompt_enhancement`.

enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là `False`) : Xác định có chạy tăng cường prompt hay không. Tính năng này là tùy chọn, phù hợp với các pipeline tham chiếu của Lightricks. Khi `True` và `system_prompt` bị bỏ qua, LTX-2.5 sẽ chọn `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` / `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` dựa trên việc có sẵn hình ảnh điều kiện hay không.

prompt_max_new_tokens (`int`, *tuỳ chọn*, mặc định là `None`) : Số lượng token mới tối đa cần tạo ra khi thực hiện tăng cường prompt. Nếu không được cung cấp, hệ thống sẽ sử dụng 600 cho `prompt_enhancer` Gemma 4 chuyên dụng (LTX-2.5) hoặc 512 cho phương án dự phòng `text_encoder` Gemma 3 (LTX-2.0/2.3).

prompt_enhancement_kwargs (`dict[str, Any]`, *tùy chọn*, mặc định là `None`) : Các đối số từ khóa cho lời gọi `.generate` của trình tăng cường prompt. Nếu không được cung cấp, giá trị luôn khớp với mô hình đang thực hiện tăng cường: `do_sample=False, no_repeat_ngram_size=5` (tham lam) khi sử dụng `prompt_enhancer` chuyên dụng (LTX-2.5), hoặc `do_sample=True, temperature=0.7` cho phương án dự phòng `text_encoder` (LTX-2.0/2.3). Xem https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate để biết thêm chi tiết.

prompt_enhancement_seed (`int`, *tuỳ chọn*, mặc định là `10`) : Hạt ngẫu nhiên cho bất kỳ thao tác ngẫu nhiên nào trong quá trình tăng cường prompt.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.ltx.LTX2PipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là `1024`) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

**Trả về:** `~pipelines.ltx.LTX2PipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `~pipelines.ltx.LTX2PipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2ConditionPipeline
>>> from diffusers.utils import encode_video
>>> from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition
>>> from diffusers.utils import load_image

>>> pipe = LTX2ConditionPipeline.from_pretrained("Lightricks/LTX-2", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()

>>> first_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
... )
>>> last_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png"
... )
>>> first_cond = LTX2VideoCondition(frames=first_image, index=0, strength=1.0)
>>> last_cond = LTX2VideoCondition(frames=last_image, index=-1, strength=1.0)
>>> conditions = [first_cond, last_cond]
>>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings."
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted, static"

>>> frame_rate = 24.0
>>> video = pipe(
...     conditions=conditions,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     width=768,
...     height=512,
...     num_frames=121,
...     frame_rate=frame_rate,
...     num_inference_steps=30,
...     guidance_scale=3.0,
...     output_type="np",
...     return_dict=False,
... )
>>> video = (video * 255).round().astype("uint8")
>>> video = torch.from_numpy(video)

>>> encode_video(
...     video[0],
...     fps=frame_rate,
...     audio=audio[0].float().cpu(),
...     audio_sample_rate=pipe.vocoder.config.output_sampling_rate,  # should be 24000
...     output_path="video.mp4",
... )
```

#### apply_first_frame_conditioning[[diffusers.LTX2ConditionPipeline.apply_first_frame_conditioning]]

```python
apply_first_frame_conditioning(latents: Tensor, conditioning_mask: Tensor, condition_latents: list, condition_strengths: list, condition_indices: list, latent_height: int, latent_width: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L964)

**Tham số:**

latents (`torch.Tensor`) : Latents đã đóng gói (patchified) ban đầu có shape [batch_size, patch_seq_len, hidden_dim].

conditioning_mask (`torch.Tensor`) : Mặt nạ điều kiện đóng gói (patchified) ban đầu có hình dạng [batch_size, patch_seq_len, 1] với các giá trị trong [0, 1], trong đó 0 có nghĩa là đầu ra của mô hình khử nhiễu sẽ được sử dụng hoàn toàn và 1 có nghĩa là điều kiện sẽ được sử dụng hoàn toàn.

**Trả về:** `Tuple[torch.Tensor, torch.Tensor, torch.Tensor]`

Trả về một bộ ba tensor, trong đó:
1. Các latent video đã đóng gói với điều kiện khung hình đầu tiên được áp dụng.
2. Mặt nạ điều kiện đóng gói với cường độ khung hình đầu tiên được áp dụng.
3. Các latent điều kiện sạch ở các vị trí khung hình đầu tiên (các vị trí khác là số 0).

Áp dụng điều kiện thị giác khung hình đầu tiên bằng cách ghi đè các token tại các vị trí khung hình đầu tiên.

Chỉ các điều kiện có `latent_idx == 0` được áp dụng tại đây (khớp với `VideoConditionByLatentIndex` trong bản tham chiếu). Các điều kiện ở chỉ số latent khác 0 được thêm vào dưới dạng các token keyframe riêng biệt thông qua `prepare_keyframe_extras` (khớp với `VideoConditionByKeyframeIndex`) và bị bỏ qua tại đây.

#### encode_prompt[[diffusers.LTX2ConditionPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 1024, scale_factor: int = 8, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L419)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng classifier free guidance hay không.

num_videos_per_prompt (`int`, *optional*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt. Thiết bị torch để đặt các embeddings kết quả lên

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### enhance_prompt[[diffusers.LTX2ConditionPipeline.enhance_prompt]]

```python
enhance_prompt(prompt: str, system_prompt: str, max_new_tokens: int | None = None, seed: int = 10, generator: typing.Optional[torch.Generator] = None, generation_kwargs: dict[str, typing.Any] | None = None, device: typing.Union[str, torch.device, NoneType] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L627)

Tăng cường `prompt` được cung cấp bằng cách tạo một prompt mới từ `prompt` đó và một system prompt, sử dụng prompt enhancer (một mô hình sinh có điều kiện Gemma). Khi có `image`, enhancer cũng được điều kiện hóa dựa trên khung tham chiếu đó (tăng cường theo kiểu I2V / keyframe). Sử dụng thành phần `prompt_enhancer` chuyên dụng nếu có cấu hình (ví dụ: LTX-2.5, nơi text encoder không được huấn luyện cho việc tăng cường), nếu không sẽ dùng `text_encoder` chính (LTX-2.0/2.3, vốn đóng vai trò là enhancer của chính nó).

Các mẫu thông báo, kwargs giải mã, làm sạch phản hồi và chuẩn bị cạnh dài của ảnh khớp với `ltx-core` / `ltx-pipelines` (`enhance_t2v` / `enhance_i2v` / `generate_enhanced_prompt`).

#### prepare_latents[[diffusers.LTX2ConditionPipeline.prepare_latents]]

```python
prepare_latents(conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, batch_size: int = 1, num_channels_latents: int = 128, height: int = 512, width: int = 768, num_frames: int = 121, frame_rate: float = 24.0, noise_scale: float = 1.0, dtype: typing.Optional[torch.dtype] = None, device: typing.Optional[torch.device] = None, generator: typing.Optional[torch.Generator] = None, latents: typing.Optional[torch.Tensor] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L1071)

Chuẩn bị các latent video nhiễu, áp dụng các điều kiện khung hình.

Điều kiện khung hình đầu tiên (`latent_idx == 0`) được áp dụng bằng cách ghi đè các token tại các vị trí khung hình đầu tiên (theo ngữ nghĩa của `VideoConditionByLatentIndex`). Các điều kiện không phải khung hình đầu tiên (`latent_idx > 0`) được nối vào chuỗi latent chính với `conditioning_mask = strength` cho từng token (theo ngữ nghĩa của `VideoConditionByKeyframeIndex`) — sau đó, công thức timestep có sẵn của vòng lặp khử nhiễu `t * (1 - conditioning_mask)` và bước trộn hậu xử lý `denoised * (1 - conditioning_mask) + clean * conditioning_mask` sẽ điều khiển chúng qua các bước.

Trả về một 4-tuple:
- `latents`: các latents nhiễu đã đóng gói (các token gốc + bất kỳ token keyframe nào được ghép vào chiều sequence).
- `conditioning_mask`: packed conditioning mask có giá trị trong `[0, 1]` — `1` tại các vị trí khung hình đầu tiên, `strength` tại các vị trí keyframe, `0` ở các vị trí còn lại.
- `clean_latents`: các giá trị điều kiện sạch tại các vị trí được điều kiện (các vị trí khác là số 0); có cùng hình dạng với `latents`.
- `keyframe_coords`: tọa độ vị trí `[B, 3, num_keyframe_patches, 2]` để thêm vào `video_coords`, hoặc `None` nếu không có điều kiện nào khác ngoài khung hình đầu tiên.

#### preprocess_conditions[[diffusers.LTX2ConditionPipeline.preprocess_conditions]]

```python
preprocess_conditions(conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, height: int = 512, width: int = 768, num_frames: int = 121, device: typing.Optional[torch.device] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L846)

**Tham số:**

conditions (`LTX2VideoCondition` hoặc `List[LTX2VideoCondition]`, *tuỳ chọn*, mặc định là `None`) : Một danh sách các instance điều kiện ảnh/đoạn video.

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao mong muốn tính bằng pixel.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng mong muốn tính bằng pixel.

num_frames (`int`, *tuỳ chọn*, mặc định là `121`) : Số khung hình mong muốn trong video được tạo ra.

device (`torch.device`, *tùy chọn*, mặc định là `None`) : Thiết bị để đặt các tensor ảnh/đoạn video đã được tiền xử lý.

**Trả về:** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

Trả về một 4-tuple gồm các danh sách có độ dài `len(conditions)` như sau:
1. Danh sách đầu tiên là một danh sách các tensor video đã được tiền xử lý có hình dạng [batch_size=1, num_channels, num_frames, height, width].
2. Danh sách thứ hai là danh sách các mức độ điều kiện.
3. Danh sách thứ ba là danh sách các chỉ số không gian ẩn cho mỗi điều kiện.
4. Danh sách thứ tư là danh sách số lượng khung hình (đã cắt) trong không gian pixel cho mỗi điều kiện. Điều này cần thiết cho ngữ nghĩa tọa độ khung hình chính (các khung hình chính chỉ gồm một pixel có phạm vi thời gian bị kẹp).

Tiền xử lý các hình ảnh/đoạn video điều kiện thành các tensor torch.

#### trim_conditioning_sequence[[diffusers.LTX2ConditionPipeline.trim_conditioning_sequence]]

```python
trim_conditioning_sequence(start_frame: int, sequence_num_frames: int, target_num_frames: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L829)

**Tham số:**

start_frame (int) : Số khung đích của khung đầu tiên trong chuỗi.

sequence_num_frames (int) : Số lượng khung hình trong chuỗi.

target_num_frames (int) : Số khung hình mục tiêu trong video được tạo ra.

**Trả về:** `int`

chiều dài chuỗi đã cập nhật

Cắt ngắn một chuỗi điều kiện xuống số khung hình được phép.

## LTX2DFRPipeline[[diffusers.LTX2DFRPipeline]]

#### diffusers.LTX2DFRPipeline[[diffusers.LTX2DFRPipeline]]

```python
diffusers.LTX2DFRPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLLTX2Video, audio_vae: AutoencoderKLLTX2Audio, text_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGeneration, tokenizer: GemmaTokenizer, connectors: LTX2TextConnectors, transformer: LTX2VideoTransformer3DModel, vocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWE, processor: transformers.processing_utils.ProcessorMixin | None = None, prompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = None, duration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L122)

**Tham số:**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một scheduler được sử dụng kết hợp với `transformer` để khử nhiễu các latents video đã được mã hóa.

vae ([AutoencoderKLLTX2Video](/docs/diffusers/main/vi/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn.

audio_vae ([AutoencoderKLLTX2Audio](/docs/diffusers/main/vi/api/models/autoencoderkl_audio_ltx_2#diffusers.AutoencoderKLLTX2Audio)) : VAE âm thanh để mã hóa và giải mã phổ âm thanh.

text_encoder (`Gemma3ForConditionalGeneration` hoặc `Gemma4UnifiedForConditionalGeneration`): Mô hình mã hóa văn bản.

tokenizer (`GemmaTokenizer` hoặc `GemmaTokenizerFast`) : Tokenizer cho text encoder.

connectors (`LTX2TextConnectors`) : Bộ kết nối văn bản được sử dụng để điều chỉnh các trạng thái ẩn của bộ mã hóa văn bản cho các nhánh video và âm thanh.

transformer ([LTX2VideoTransformer3DModel](/docs/diffusers/main/vi/api/models/ltx2_video_transformer3d#diffusers.LTX2VideoTransformer3DModel)) : Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.

vocoder (`LTX2Vocoder` hoặc `LTX2VocoderWithBWE`) : Vocoder để chuyển đổi mel spectrograms thành dạng sóng âm thanh.

processor (`ProcessorMixin`, *tùy chọn*) : Bộ xử lý được sử dụng cho việc tăng cường prompt và chat templating.

prompt_enhancer (`Gemma4ForConditionalGeneration`, *tùy chọn*) : Mô hình tăng cường prompt chuyên dụng (LTX-2.5).

duration_head (`LTX2DurationHead`, *tùy chọn*) : Dự đoán `num_frames` từ các embedding của prompt khi `num_frames` không được cung cấp.

Quy trình cho một lượt khử nhiễu Diffusion Fidelity Rendering (DFR) với LTX-2.5.

Một lượt chạy tạo ra video *và* các khe keyframe khung hình đơn pixel bổ sung, hoặc khử nhiễu lại các latents được cung cấp, có hạt giống từ các khe đó. Người gọi sẽ kết hợp các giai đoạn: pipeline này ở độ phân giải một nửa, [LTX2LatentUpsamplePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2LatentUpsamplePipeline) theo không gian, pipeline này một lần nữa ở độ phân giải đầy đủ với các khe đã được tăng mẫu và một tham chiếu IC-LoRA, sau đó là [LTX2DFRTemporalRefinePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline) cho mỗi vòng tinh chỉnh thời gian. Xem tài liệu LTX-2 để biết công thức cho 1080p.

Vị trí slot được lấy từ lưới phân đoạn được căn chỉnh với biên thời gian của VAE (`resolve_canvas`). Lưới được đệm đến một số nguyên phân đoạn; `output_type="latent"` trả về lưới đã đệm đó để một slot nằm trên phần đệm không bị loại bỏ. Dùng `trim_canvas` để cắt bỏ trước khi giải mã VAE.

Yêu cầu một transformer có config đặt `use_keyframes_abs_pos_embedding` (LTX-2.5 trở lên) khi `generate_slots=True`.

Tham khảo: https://github.com/Lightricks/LTX-2

#### __call__[[diffusers.LTX2DFRPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, height: int = 704, width: int = 1216, num_frames: int | None = None, frame_rate: float = 24.0, min_seconds: float = 1.0, max_seconds: float = 20.0, latents: typing.Optional[torch.Tensor] = None, audio_latents: typing.Optional[torch.Tensor] = None, keyframes_latents: typing.Optional[torch.Tensor] = None, keyframe_positions: list[int] | None = None, reference_latents: typing.Optional[torch.Tensor] = None, reference_downscale_factor: int = 2, guidance_keyframe_latents: typing.Optional[torch.Tensor] = None, guidance_keyframe_positions: list[int] | None = None, guidance_keyframe_strength: float = 1.0, generate_slots: bool = True, sigmas: list = [1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875], noise_scale: float | None = None, freeze_audio: bool = False, video_tiles: list[diffusers.pipelines.ltx2.dfr_layout.LTX2DFREpilogueTile] | None = None, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, use_cross_timestep: bool = True, system_prompt: str | None = None, enable_prompt_enhancement: bool = False, prompt_max_new_tokens: int | None = None, prompt_enhancement_kwargs: dict[str, typing.Any] | None = None, prompt_enhancement_seed: int = 10, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 1024)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1522)

**Tham số:**

prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds`.

conditions (`LTX2VideoCondition` hoặc `List[LTX2VideoCondition]`, *optional*) : Điều kiện ảnh hoặc video ở cấp độ khung hình. `index` là chỉ số *latent* trên `num_frames` của lượt xử lý này.

height (`int`, *tuỳ chọn*, mặc định là `704`) : Chiều cao tính bằng pixel của **lượt xử lý này**, không phải của đầu ra tổng hợp cuối cùng.

width (`int`, *tuỳ chọn*, mặc định là `1216`) : Độ rộng tính bằng pixel của bước này.

num_frames (`int`, *tuỳ chọn*) : Số lượng khung hình pixel của bước này, trước khi đệm canvas nội bộ. Nếu không được cung cấp, thời lượng sẽ được dự đoán từ prompt bởi `duration_head`. Phải thỏa mãn `(num_frames - 1) % 8 == 0`.

frame_rate (`float`, *tuỳ chọn*, mặc định là `24.0`) : FPS phát lại của bước này. Thời gian RoPE sẽ được làm tròn về 60 khi giá trị này lớn hơn 30.

min_seconds (`float`, *optional*, mặc định là `1.0`) : Giới hạn dưới của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua.

max_seconds (`float`, *optional*, mặc định là `20.0`) : Giới hạn trên của thời lượng được tự động dự đoán khi `num_frames` bị bỏ qua.

latents (`torch.Tensor`, *tùy chọn*) : Các latent video thô có dạng `(batch_size, channels, frames, height, width)` để khử nhiễu lại (giai đoạn 2 / phần kết).

audio_latents (`torch.Tensor`, *tùy chọn*) : Các latent âm thanh thô chưa đóng gói có dạng `(batch_size, channels, length, mel_bins)`. Giai đoạn 2 vẫn thực hiện một lượt xử lý âm thanh chung; waveform được xuất ra của một công thức tổng hợp là của giai đoạn 1, và người gọi sẽ giữ lại waveform này.

keyframes_latents (`torch.Tensor`, *tùy chọn*) : Ban đầu của slot thô có dạng `(batch_size, channels, num_slots, height, width)`, được sử dụng khi `generate_slots=True`.

keyframe_positions (`list[int]`, *optional*) : Chỉ số khung pixel của các slot được tạo. Mặc định là `resolve_canvas(num_frames)`.

reference_latents (`torch.Tensor`, *tùy chọn*) : Video tham chiếu IC-LoRA thô (thường là các khung hình của giai đoạn 1).

reference_downscale_factor (`int`, *optional*, mặc định là `2`) : Tỷ lệ giữa bước này và độ phân giải tham chiếu, được sử dụng để điều chỉnh tọa độ token tham chiếu.

guidance_keyframe_latents (`torch.Tensor`, *tùy chọn*) : Các keyframe hướng dẫn gốc đã ghim `(batch_size, channels, K, height, width)` — đường dẫn epilogue. Không phải các slot được tạo.

guidance_keyframe_positions (`list[int]`, *tùy chọn*) : Chỉ số khung hình pixel cho `guidance_keyframe_latents`.

guidance_keyframe_strength (`float`, *tuỳ chọn*, mặc định là `1.0`) : Cường độ điều kiện cho các keyframe hướng dẫn cố định.

generate_slots (`bool`, *tùy chọn*, mặc định là `True`) : Thêm các token keyframe-slot đã tạo. Phần epilogue sẽ đặt giá trị này thành `False` và cố định `guidance_keyframe_latents` thay vào đó.

sigmas (`list[float]`, *tùy chọn*) : Lịch trình nhiễu cho bước này, không có `0.0` cuối cùng.

noise_scale (`float`, *optional*) : Mức nhiễu mà các token không điều kiện bắt đầu. Mặc định là `sigmas[0]`.

freeze_audio (`bool`, *tùy chọn*, mặc định là `False`) : Giữ âm thanh ở sigma 0 (phần kết / khi tiếp nối một waveform giai đoạn 1 đã đóng băng).

video_tiles (`list[LTX2DFREpilogueTile]`, *optional*) : Tiling epilogue từ `epilogue_tiles()`, nhờ đó một độ phân giải quá lớn cho một lần forward pass vẫn có thể xử lý từng bước trên một canvas duy nhất: mỗi bước chạy transformer một lần cho mỗi tile và trộn các dự đoán. Được giải quyết thành một kế hoạch token dựa trên tọa độ RoPE của chính pass này, đó là lý do tại sao layout được truyền thay vì kế hoạch — các tọa độ chỉ tồn tại sau khi [prepare_latents()](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents) đã chạy.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Bộ tạo ngẫu nhiên để đảm bảo khả năng tái lập.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Thang độ nhiễu khi giải mã.

use_cross_timestep (`bool`, *tuỳ chọn*, mặc định là `True`) : Có sử dụng sigma liên phương thức cho điều chế chú ý liên phương thức hay không. `True` cho LTX-2.3+.

system_prompt (`str`, *tùy chọn*) : Prompt hệ thống tùy chọn để tăng cường prompt. Xem `enable_prompt_enhancement`.

enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là `False`) : Có chạy tăng cường prompt hay không.

prompt_max_new_tokens (`int`, *tuỳ chọn*) : Số lượng token mới tối đa cần tạo ra khi thực hiện tăng cường prompt.

prompt_enhancement_kwargs (`dict[str, Any]`, *tùy chọn*) : Các đối số từ khóa cho cuộc gọi `.generate` của trình tăng cường prompt.

prompt_enhancement_seed (`int`, *tuỳ chọn*, mặc định là `10`) : Hạt ngẫu nhiên cho bất kỳ thao tác ngẫu nhiên nào trong quá trình tăng cường prompt.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra. Chọn `"pil"`, `"np"`, `"pt"` hoặc `"latent"`. Đầu ra latent là canvas chưa được cắt.

return_dict (`bool`, *tuỳ chọn*, mặc định là `True`) : Xác định việc trả về một [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) hay một tuple `(frames, audio, keyframes, keyframe_positions)` thông thường.

attention_kwargs (`dict`, *tùy chọn*) : Các kwargs bổ sung được truyền cho bộ xử lý chú ý.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*, mặc định là `["latents"]`) : Đầu vào Tensor cho hàm callback.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là `1024`) : Độ dài tối đa của chuỗi cho prompt văn bản.

**Trả về:** [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) sẽ được trả về, ngược lại một `tuple` của `(video, audio, keyframes, keyframe_positions)` sẽ được trả về.

Hàm được gọi khi gọi pipeline cho việc sinh.

Một lượt khử nhiễu tại `height` × `width`. Ghép các giai đoạn ở phía gọi: pipeline này ở độ phân giải một nửa, tăng mẫu không gian, pipeline này một lần nữa với `latents` / `keyframes_latents` / `reference_latents`, sau đó [LTX2DFRTemporalRefinePipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline) cho mỗi vòng thời gian.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2DFRPipeline
>>> from diffusers.utils import encode_video

>>> pipe = LTX2DFRPipeline.from_pretrained("Lightricks/LTX-2.5-Diffusers", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()

>>> frame_rate = 24.0
>>> video, audio, _, _ = pipe(
...     prompt="A tabby cat stretching in a sunlit window, dust motes drifting in the light",
...     height=704,
...     width=1216,
...     num_frames=121,
...     frame_rate=frame_rate,
...     output_type="np",
...     return_dict=False,
... )

>>> encode_video(
...     video[0],
...     fps=frame_rate,
...     audio=audio[0].float().cpu(),
...     audio_sample_rate=pipe.vocoder.config.output_sampling_rate,
...     output_path="dfr_output.mp4",
... )
```

#### denoise[[diffusers.LTX2DFRPipeline.denoise]]

```python
denoise(latents: Tensor, conditioning_mask: Tensor, clean_latents: Tensor, video_coords: Tensor, keyframes_mask: Tensor, prompt_embeds: Tensor, audio_prompt_embeds: Tensor, prompt_attention_mask: Tensor, sigmas: list, frame_rate: float, audio_latents: Tensor, freeze_audio: bool = False, video_tile_plan: list | None = None, generator: typing.Optional[torch.Generator] = None, use_cross_timestep: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, progress_bar = None, step_offset: int = 0, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1225)

**Tham số:**

sigmas (`list[float]`) : Lịch trình nhiễu cho bước này, không bao gồm `0.0` cuối cùng.

freeze_audio (`bool`, *tuỳ chọn*, mặc định là `False`) : Giữ `audio_latents` ở trạng thái sạch (timestep/sigma 0, không có bước Euler cho audio) trong khi vẫn thực hiện cross-attention từ audio sang video. Bỏ qua khi `audio_latents` là `None`.

video_tile_plan (`list`, *optional*) : Kế hoạch token cho từng tile từ `video_tile_plan`[`~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan`]. Khi được cung cấp, mỗi bước sẽ chạy transformer một lần cho mỗi tile và trộn các dự đoán, nhờ đó trình lấy mẫu vẫn thực hiện bước trên một canvas đầy đủ duy nhất và các tile sẽ khớp nhau ở phần chồng lấn ở mọi bước.

generator (`torch.Generator`, *optional*) : Được chuyển tiếp đến `LTXEulerAncestralRFScheduler.step()`. Các ô thời gian truyền một seed riêng cho từng ô để các lần rút mẫu tổ tiên không chia sẻ một luồng chung hoặc tiêu thụ trạng thái mà bước nhiễu ban đầu của ô tiếp theo sẽ đọc. Euler đã chưng cất không đọc giá trị này.

step_offset (`int`) : Chỉ số của bước đầu tiên của lượt này trong lịch trình tổng thể của pipeline, được dùng cho `callback_on_step_end` và thanh tiến độ dùng chung.

Chạy một lượt khử nhiễu DFR trên `sigmas` và trả về `(latents, audio_latents)`, cả hai vẫn được đóng gói.

Lịch trình đã được chưng cất được sử dụng mà không có classifier-free guidance, do đó mỗi bước chỉ cần một lần gọi transformer duy nhất. Mỗi lượt chạy đều thực thi cả hai luồng, vì nhánh video cần sự chú ý liên phương thức ngay cả khi âm thanh mà nó tạo ra bị loại bỏ. `freeze_audio=True` giữ luồng âm thanh ở sigma 0 (không có bước Euler) để video vẫn có thể chú ý chéo sang nó — các ô tinh chỉnh thời gian và phần kết thúc sử dụng điều này để bám theo giọng nói của giai đoạn 1 mà không cần mỗi ô khử nhiễu lại một thực thể âm thanh khác nhau.

Sau khi trộn điều kiện x0, vận tốc là `(latents - denoised) / sigma` nên một bước RF `x0 = x - σ v` sẽ khôi phục `denoised` đã được trộn. Giai đoạn 1 / 2 / phần kết thúc giữ nguyên [FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler) và thực hiện bước Euler đó như vậy. Temporal refine thay bằng `LTXEulerAncestralRFScheduler` (`eta=0.5`); bước đó thêm nhiễu lại cho mọi token, do đó việc trộn điều kiện phải được áp dụng lại sau đó, nếu không các neo mối nối strength-0.95 sẽ bị xói mòn.

#### encode_conditions[[diffusers.LTX2DFRPipeline.encode_conditions]]

```python
encode_conditions(conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None, height: int, width: int, num_frames: int, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None, generator: typing.Optional[torch.Generator] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1189)

Tiền xử lý và mã hóa điều kiện khung bằng VAE, được định vị theo khung pixel.

Trả về `(pixel_frame_index, latent, strength, num_pixel_frames)` cho mỗi điều kiện, sẵn sàng cho `condition_latents` của [prepare_latents()](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents). Việc mã hóa được tách riêng khỏi việc đặt vị trí vì các vòng lặp tinh chỉnh theo thời gian sẽ nhân vị trí của một điều kiện với `2 ** round` và đặt lại cơ sở cho từng ô, và không nên mã hóa lại cùng một khung hình tĩnh một lần cho mỗi ô để làm điều đó.

Chỉ số được trả về nằm trên lưới pixel riêng của `num_frames`; việc chuyển nó sang một canvas đã tinh chỉnh là trách nhiệm của người gọi.

#### encode_prompt[[diffusers.LTX2DFRPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 1024, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L529)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho `prompt_embeds`.

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

DFR chạy lịch trình sigma đã được chưng cất, được huấn luyện để sử dụng mà không cần classifier-free guidance, do đó không có nhánh âm ở đây.

#### enhance_prompt[[diffusers.LTX2DFRPipeline.enhance_prompt]]

```python
enhance_prompt(prompt: str, system_prompt: str, max_new_tokens: int | None = None, seed: int = 10, generator: typing.Optional[torch.Generator] = None, generation_kwargs: dict[str, typing.Any] | None = None, device: typing.Union[str, torch.device, NoneType] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L389)

Tăng cường `prompt` được cung cấp bằng cách tạo một prompt mới từ nó và một system prompt, sử dụng prompt enhancer (một mô hình sinh có điều kiện Gemma). Khi có `image`, enhancer cũng được điều kiện hóa dựa trên khung tham chiếu đó (tăng cường theo kiểu I2V / keyframe). Sử dụng thành phần `prompt_enhancer` chuyên dụng nếu có cấu hình (ví dụ: LTX-2.5, nơi text encoder không được huấn luyện cho việc tăng cường), nếu không sẽ dùng `text_encoder` chính (LTX-2.0/2.3, vốn đóng vai trò là enhancer của chính nó).

Các mẫu thông báo, kwargs giải mã, làm sạch phản hồi và chuẩn bị cạnh dài của ảnh khớp với `ltx-core` / `ltx-pipelines` (`enhance_t2v` / `enhance_i2v` / `generate_enhanced_prompt`).

#### prepare_latents[[diffusers.LTX2DFRPipeline.prepare_latents]]

```python
prepare_latents(conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, condition_latents: list[tuple[int, torch.Tensor, float, int]] | None = None, keyframe_latents: list[tuple[int, torch.Tensor, float]] | None = None, slot_frame_indices: list[int] | None = None, slot_initial_latents: typing.Optional[torch.Tensor] = None, reference_latents: typing.Optional[torch.Tensor] = None, reference_downscale_factor: int = 1, batch_size: int = 1, num_channels_latents: int = 128, height: int = 512, width: int = 768, num_frames: int = 121, frame_rate: float = 24.0, noise_scale: float = 1.0, dtype: typing.Optional[torch.dtype] = None, device: typing.Optional[torch.device] = None, generator: typing.Optional[torch.Generator] = None, latents: typing.Optional[torch.Tensor] = None, latents_normalized: bool = True)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L886)

**Tham số:**

conditions (`list[LTX2VideoCondition]`, *optional*) : Điều kiện ảnh / video ở cấp độ khung hình, được định vị theo chỉ số latent.

condition_latents (`list[tuple[int, torch.Tensor, float, int]]`, *tùy chọn*) : Bản mã hóa sẵn thay thế cho `conditions`, dưới dạng `(pixel_frame_index, latent, strength, num_pixel_frames)`. Dùng chỉ số pixel thay vì chỉ số latent, vì một vòng refine theo thời gian sẽ nhân vị trí của một điều kiện với `2 ** round` và kết quả thường không rơi đúng vào ranh giới latent -- chỉ một token keyframe được thêm vào mới có thể nằm ở đó, và nó được đặt theo pixel. `pixel_frame_index == 0` vẫn có nghĩa là "thay thế khung hình đầu tiên".

keyframe_latents (`list[tuple[int, torch.Tensor, float]]`, *tùy chọn*) : Hướng dẫn keyframe đã được mã hóa dưới dạng `(pixel_frame_index, latent, strength)`, trong đó `latent` có hình dạng `(batch_size, num_channels_latents, 1, latent_height, latent_width)`. Được sử dụng bởi các vòng lặp tinh chỉnh theo thời gian để cố định các keyframe nối tiếp được mang sang từ vòng lặp trước.

slot_frame_indices (`list[int]`, *tùy chọn*) : Vị trí khung hình pixel của các khe keyframe đã tạo.

slot_initial_latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width)` nội dung được ghi vào các token slot trước khi thêm nhiễu.

reference_latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, F, H, W)` Latent tham chiếu IC-LoRA.

reference_downscale_factor (`int`, mặc định là `1`) : Tỷ lệ giữa độ phân giải đích và độ phân giải tham chiếu.

latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, F, H, W)` nội dung ban đầu cho các token cơ sở. Latents của pipeline công khai là dạng thô (chưa chuẩn hóa); hãy truyền `latents_normalized=False` tại ranh giới đó. Các vòng lặp tile đã nằm trong không gian đã chuẩn hóa VAE thì giữ nguyên giá trị mặc định.

latents_normalized (`bool`, mặc định là `True`) : Xác định xem `latents`, `slot_initial_latents`, `reference_latents` và `keyframe_latents` đã được chuẩn hóa VAE hay chưa. Các vòng lặp tile nội bộ truyền `True`; mỗi pipeline `__call__` truyền `False`.

noise_scale (`float`, mặc định là `1.0`) : Mức nhiễu mà các token không điều kiện được khởi tạo, tức là sigma đầu tiên của lịch trình.

**Trả về:** `tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, slice | None]`

`(latents, conditioning_mask, clean_latents, video_coords, keyframes_mask, slot_token_slice)`. `slot_token_slice` chỉ định các token slot keyframe đã được tạo trong chuỗi đã đóng gói, hoặc `None` khi không có slot nào được yêu cầu.

Chuẩn bị các latent video đã đóng gói có nhiễu cho một lượt khử nhiễu DFR.

Chuỗi được đóng gói được bố trí theo dạng `[base | keyframes | slots | reference]`:

- Các token cơ bản bao phủ lưới ẩn mục tiêu, được khởi tạo từ `latents` khi được cung cấp.
- Các điều kiện khung hình với `index == 0` đặt mục tiêu sạch tại các vị trí khung hình đầu tiên; những điều kiện có `index > 0` và mọi phần tử của `keyframe_latents` được thêm vào như các token khung hình chính bổ sung, với mặt nạ điều kiện cho từng token bằng với cường độ của chúng.
- `slot_frame_indices` thêm một lượng token keyframe *được tạo* tương ứng với một khung latent cho mỗi vị trí, với mask điều kiện là `0` (đã khử nhiễu hoàn toàn) và phạm vi thời gian RoPE bằng đúng một khung pixel. Đây là các slot keyframe mang lại thêm các khung cho DFR; `slot_initial_latents` khởi tạo nội dung của chúng.
- `reference_latents` thêm latent bán độ phân giải của giai đoạn 1 như một tham chiếu IC-LoRA hoàn toàn sạch, với tọa độ không gian được nhân với `reference_downscale_factor` để ánh xạ vào không gian tọa độ đích.

Các token điều kiện được nối thêm mang nội dung của chúng trong `clean_latents` và một giá trị placeholder bằng 0 trong `latents`, trong khi các slot keyframe mang hạt giống của chúng trong `latents` và các giá trị 0 trong `clean_latents` -- `latents` được trả về là hỗn hợp có nhiễu của hai phần này (xem bước thêm nhiễu ở cuối phương thức này).

#### preprocess_conditions[[diffusers.LTX2DFRPipeline.preprocess_conditions]]

```python
preprocess_conditions(conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, height: int = 512, width: int = 768, num_frames: int = 121, device: typing.Optional[torch.device] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L707)

**Tham số:**

conditions (`LTX2VideoCondition` hoặc `List[LTX2VideoCondition]`, *tuỳ chọn*, mặc định là `None`) : Một danh sách các instance điều kiện ảnh/đoạn video.

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao mong muốn tính bằng pixel.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng mong muốn tính bằng pixel.

num_frames (`int`, *tuỳ chọn*, mặc định là `121`) : Số khung hình mong muốn trong video được tạo ra.

device (`torch.device`, *tùy chọn*, mặc định là `None`) : Thiết bị để đặt các tensor ảnh/đoạn video đã được tiền xử lý.

**Trả về:** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

Trả về một 4-tuple gồm các danh sách có độ dài `len(conditions)` như sau:
1. Danh sách đầu tiên là một danh sách các tensor video đã được tiền xử lý có hình dạng [batch_size=1, num_channels, num_frames, height, width].
2. Danh sách thứ hai là danh sách các mức độ điều kiện.
3. Danh sách thứ ba là danh sách các chỉ số không gian ẩn cho mỗi điều kiện.
4. Danh sách thứ tư là danh sách số lượng khung hình (đã cắt) trong không gian pixel cho mỗi điều kiện. Điều này cần thiết cho ngữ nghĩa tọa độ khung hình chính (các khung hình chính chỉ gồm một pixel có phạm vi thời gian bị kẹp).

Tiền xử lý các hình ảnh/đoạn video điều kiện thành các tensor torch.

#### rebuild_epilogue_keyframes[[diffusers.LTX2DFRPipeline.rebuild_epilogue_keyframes]]

```python
rebuild_epilogue_keyframes(keyframe_latents: Tensor, decode_timestep: float, decode_noise_scale: float, seed: int, device: device, dtype: dtype)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1454)

**Tham số:**

keyframe_latents (`torch.Tensor`) : `(batch_size, C, K, H, W)` thô chứa các keyframe, như một lượt trước đó đã trả về.

seed (`int`) : Seed gốc; mặt phẳng `i` được giải mã dưới `seed + 4000 + i`, do đó các pixel của một mặt phẳng không phụ thuộc vào số lượng mặt phẳng đã được giải mã trước đó.

**Trả về:** `torch.Tensor`

Các latents thô `(batch_size, C, K, 2H, 2W)`, sẵn sàng để truyền ngược lại trực tiếp dưới dạng `guidance_keyframe_latents`.

Mã hóa lại các khung hình mang (carry keyframes) ở độ phân giải gấp đôi thông qua RGB.

Đây là các khung hình mà các vòng lặp tinh chỉnh đã xác định, do đó phần kết *được cung cấp* các khung này thay vì yêu cầu tạo ra chúng. Việc giải mã sang pixel, phóng to x2 bằng Lanczos và mã hóa lại giúp giữ nguyên khung hình trong khi đặt nó lên lưới đầu ra, điều này cho phép phần kết cố định nó hoàn toàn sạch sẽ.

Mỗi mặt phẳng được giải mã như một clip một khung hình riêng biệt. VAE là nhân quả, do đó việc giải mã chồng lớp sẽ cho phép các mặt phẳng lân cận bị lẫn vào nhau -- chúng là các ảnh tĩnh độc lập, không phải một chuỗi.

#### trim_conditioning_sequence[[diffusers.LTX2DFRPipeline.trim_conditioning_sequence]]

```python
trim_conditioning_sequence(start_frame: int, sequence_num_frames: int, target_num_frames: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L689)

**Tham số:**

start_frame (int) : Số khung đích của khung đầu tiên trong chuỗi.

sequence_num_frames (int) : Số lượng khung hình trong chuỗi.

target_num_frames (int) : Số khung hình mục tiêu trong video được tạo ra.

**Trả về:** `int`

chiều dài chuỗi đã cập nhật

Cắt ngắn một chuỗi điều kiện xuống số khung hình được phép.

## LTX2DFRTemporalRefinePipeline[[diffusers.LTX2DFRTemporalRefinePipeline]]

#### diffusers.LTX2DFRTemporalRefinePipeline[[diffusers.LTX2DFRTemporalRefinePipeline]]

```python
diffusers.LTX2DFRTemporalRefinePipeline(scheduler: LTXEulerAncestralRFScheduler, vae: AutoencoderKLLTX2Video, audio_vae: AutoencoderKLLTX2Audio, text_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGeneration, tokenizer: GemmaTokenizer, connectors: LTX2TextConnectors, transformer: LTX2VideoTransformer3DModel, vocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWE, temporal_latent_upsampler: LTX2LatentUpsamplerModel)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L151)

**Tham số:**

scheduler (`LTXEulerAncestralRFScheduler`) : Trình lập lịch Euler tổ tiên trong tham số hóa rectified-flow. Khởi tạo với `eta=0.5` để khớp với công thức thời gian DFR.

vae ([AutoencoderKLLTX2Video](/docs/diffusers/main/vi/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn.

audio_vae ([AutoencoderKLLTX2Audio](/docs/diffusers/main/vi/api/models/autoencoderkl_audio_ltx_2#diffusers.AutoencoderKLLTX2Audio)) : VAE âm thanh để mã hóa và giải mã phổ âm thanh.

text_encoder (`Gemma3ForConditionalGeneration` hoặc `Gemma4UnifiedForConditionalGeneration`): Mô hình mã hóa văn bản.

tokenizer (`GemmaTokenizer` hoặc `GemmaTokenizerFast`) : Tokenizer cho text encoder.

connectors (`LTX2TextConnectors`) : Bộ kết nối văn bản được sử dụng để điều chỉnh các trạng thái ẩn của bộ mã hóa văn bản cho các nhánh video và âm thanh.

transformer ([LTX2VideoTransformer3DModel](/docs/diffusers/main/vi/api/models/ltx2_video_transformer3d#diffusers.LTX2VideoTransformer3DModel)) : Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.

vocoder (`LTX2Vocoder` hoặc `LTX2VocoderWithBWE`) : Vocoder để chuyển đổi mel spectrograms thành dạng sóng âm thanh.

temporal_latent_upsampler (`LTX2LatentUpsamplerModel`) : Bộ tăng độ phân giải latent theo thời gian x2 được áp dụng ở đầu vòng.

Một vòng tinh chỉnh DFR theo thời gian: nội suy canvas x2 theo thời gian, lát hóa tại các điểm nối keyframe, khử nhiễu tổ tiên cho từng lát, ghép lại bằng cách loại bỏ phần lead-in của lát sau, và hợp nhất túi carry-keyframe.

Trình lập lịch là `LTXEulerAncestralRFScheduler` (mặc định `eta=0.5`). Giai đoạn 1 / 2 / phần kết thúc không gian vẫn sử dụng [FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler) thông qua [LTX2DFRPipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipeline). Gọi pipeline này một lần mỗi vòng; bên gọi sẽ lặp lại cho 2x / 4x.

`latents` / `keyframes_latents` / `audio_latents` đầu vào là dữ liệu thô (chưa chuẩn hóa), khớp với [LTX2Pipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2Pipeline). `keyframe_positions` phải là các vị trí được trả về từ lượt chạy trước đó — chúng không thể được suy ra lại từ `num_frames` gốc sau khi một vòng đã chạy.

#### __call__[[diffusers.LTX2DFRTemporalRefinePipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, latents: Tensor = None, keyframes_latents: Tensor = None, keyframe_positions: list = None, audio_latents: Tensor = None, conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, height: int = 704, width: int = 1216, num_frames: int = 121, frame_rate: float = 24.0, source_seconds: float | None = None, condition_num_frames: int | None = None, round_index: int = 1, sigmas: list = [0.975, 0.909375, 0.725, 0.421875], noise_scale: float | None = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, use_cross_timestep: bool = True, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 1024)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1349)

**Tham số:**

prompt (`str` hoặc `List[str]`, *tùy chọn*) : Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds`.

latents (`torch.Tensor`) : Raw video latents của **input** canvas, `(batch_size, channels, frames, height, width)`.

keyframes_latents (`torch.Tensor`) : Các keyframe carry thô `(batch_size, channels, K, height, width)` từ lượt trước.

keyframe_positions (`list[int]`) : Chỉ số khung hình pixel của `keyframes_latents` trên canvas **đầu vào**.

audio_latents (`torch.Tensor`) : Âm thanh giai đoạn 1 đã đóng băng, đã giải nén và khử chuẩn hóa. Mỗi tile được cấp phát lát cắt bao phủ cửa sổ phát của nó; âm thanh được trả về chính là dạng sóng này, không phải là quá trình khử nhiễu lại cho từng tile.

conditions (`LTX2VideoCondition` hoặc `List[LTX2VideoCondition]`, *optional*) : Các điều kiện ở cấp độ khung hình được chỉ mục theo `condition_num_frames` (yêu cầu gốc). Mỗi vòng lặp sẽ nhân vị trí pixel của một điều kiện với `2 ** round_index`.

height (`int`, *tuỳ chọn*, mặc định là `704`) : Chiều cao pixel của bước này (giống với video đầu vào).

width (`int`, *tuỳ chọn*, mặc định là `1216`) : Độ rộng pixel của bước này.

num_frames (`int`, *tuỳ chọn*, mặc định là `121`) : Số khung hình pixel của **input** canvas (chưa cắt).

frame_rate (`float`, *tuỳ chọn*, mặc định là `24.0`) : FPS phát của **đầu vào**. Vòng tròn làm tăng gấp đôi giá trị này.

source_seconds (`float`, *optional*) : Thời lượng của giai đoạn 1 âm thanh bị đóng băng. Mặc định là `num_frames / frame_rate`, đây là giá trị chính xác cho vòng đầu tiên; các vòng sau phải truyền thời lượng gốc của giai đoạn 1 để các ô không bị lệch.

condition_num_frames (`int`, *optional*) : `num_frames` gốc được dùng để mã hóa `conditions`. Mặc định là `num_frames`. Sau khi đệm hoặc một vòng trước đó, hãy truyền yêu cầu gốc để `index=-1` không bị cuộn sang phần đệm ở cuối.

round_index (`int`, *optional*, mặc định là `1`) : số thứ tự vòng lặp bắt đầu từ 1. Tiles seed ancestral noise theo công thức `seed + 1000 * round_index + tile`, và các điều kiện được nhân với hệ số `2 ** round_index`.

sigmas (`list[float]`, *optional*) : Lịch trình đã cô đặc cho các ô của vòng này, không bao gồm `0.0` cuối cùng.

noise_scale (`float`, *optional*) : Mức nhiễu mà các token không điều kiện bắt đầu. Mặc định là `sigmas[0]`.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Bộ tạo ngẫu nhiên để đảm bảo khả năng tái lập. Các lần rút mẫu tổ tiên sử dụng một hạt riêng cho từng ô, được suy ra từ `initial_seed()` của bộ tạo này.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Thang độ nhiễu khi giải mã.

use_cross_timestep (`bool`, *tuỳ chọn*, mặc định là `True`) : Có sử dụng sigma liên phương thức cho điều chế chú ý liên phương thức hay không. `True` cho LTX-2.3+.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra. Chọn `"pil"`, `"np"`, `"pt"` hoặc `"latent"`. Đầu ra latent là canvas chưa được cắt.

return_dict (`bool`, *tuỳ chọn*, mặc định là `True`) : Xác định việc trả về một [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) hay một tuple `(frames, audio, keyframes, keyframe_positions)` thông thường.

attention_kwargs (`dict`, *tùy chọn*) : Các kwargs bổ sung được truyền cho bộ xử lý chú ý.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu, trên mọi ô gạch.

callback_on_step_end_tensor_inputs (`List`, *tùy chọn*, mặc định là `["latents"]`) : Đầu vào Tensor cho hàm callback.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là `1024`) : Độ dài tối đa của chuỗi cho prompt văn bản.

**Trả về:** [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [LTX2DFRPipelineOutput](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) sẽ được trả về, ngược lại một `tuple` của `(video, audio, keyframes, keyframe_positions)` sẽ được trả về.

Chạy một vòng tinh chỉnh thời gian.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2DFRPipeline, LTX2DFRTemporalRefinePipeline, LTXEulerAncestralRFScheduler
>>> from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel

>>> pipe = LTX2DFRPipeline.from_pretrained("Lightricks/LTX-2.5-Diffusers", torch_dtype=torch.bfloat16)
>>> temporal_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
...     "path/to/converted/temporal_latent_upsampler", torch_dtype=torch.bfloat16
... )
>>> temporal_pipe = LTX2DFRTemporalRefinePipeline(
...     scheduler=LTXEulerAncestralRFScheduler(eta=0.5),
...     vae=pipe.vae,
...     audio_vae=pipe.audio_vae,
...     text_encoder=pipe.text_encoder,
...     tokenizer=pipe.tokenizer,
...     connectors=pipe.connectors,
...     transformer=pipe.transformer,
...     vocoder=pipe.vocoder,
...     temporal_latent_upsampler=temporal_upsampler,
... )
>>> # `out` is a prior DFR pass at the same spatial size, `return_dict=True`.
>>> out = temporal_pipe(
...     latents=out.frames,
...     keyframes_latents=out.keyframes,
...     keyframe_positions=out.keyframe_positions,
...     audio_latents=out.audio,
...     prompt="A tabby cat stretching in a sunlit window",
...     height=1088,
...     width=1920,
...     num_frames=121,
...     output_type="latent",
... )
```

#### denoise[[diffusers.LTX2DFRTemporalRefinePipeline.denoise]]

```python
denoise(latents: Tensor, conditioning_mask: Tensor, clean_latents: Tensor, video_coords: Tensor, keyframes_mask: Tensor, prompt_embeds: Tensor, audio_prompt_embeds: Tensor, prompt_attention_mask: Tensor, sigmas: list, frame_rate: float, audio_latents: Tensor, freeze_audio: bool = False, video_tile_plan: list | None = None, generator: typing.Optional[torch.Generator] = None, use_cross_timestep: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, progress_bar = None, step_offset: int = 0, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1138)

**Tham số:**

sigmas (`list[float]`) : Lịch trình nhiễu cho bước này, không bao gồm `0.0` cuối cùng.

freeze_audio (`bool`, *tuỳ chọn*, mặc định là `False`) : Giữ `audio_latents` ở trạng thái sạch (timestep/sigma 0, không có bước Euler cho audio) trong khi vẫn thực hiện cross-attention từ audio sang video. Bỏ qua khi `audio_latents` là `None`.

video_tile_plan (`list`, *optional*) : Kế hoạch token cho từng tile từ `video_tile_plan`[`~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan`]. Khi được cung cấp, mỗi bước sẽ chạy transformer một lần cho mỗi tile và trộn các dự đoán, nhờ đó trình lấy mẫu vẫn thực hiện bước trên một canvas đầy đủ duy nhất và các tile sẽ khớp nhau ở phần chồng lấn ở mọi bước.

generator (`torch.Generator`, *optional*) : Được chuyển tiếp đến `LTXEulerAncestralRFScheduler.step()`. Các ô thời gian truyền một seed riêng cho từng ô để các lần rút mẫu tổ tiên không chia sẻ một luồng chung hoặc tiêu thụ trạng thái mà bước nhiễu ban đầu của ô tiếp theo sẽ đọc. Euler đã chưng cất không đọc giá trị này.

step_offset (`int`) : Chỉ số của bước đầu tiên của lượt này trong lịch trình tổng thể của pipeline, được dùng cho `callback_on_step_end` và thanh tiến độ dùng chung.

Chạy một lượt khử nhiễu DFR trên `sigmas` và trả về `(latents, audio_latents)`, cả hai vẫn được đóng gói.

Lịch trình đã được chưng cất được sử dụng mà không có classifier-free guidance, do đó mỗi bước chỉ cần một lần gọi transformer duy nhất. Mỗi lượt chạy đều thực thi cả hai luồng, vì nhánh video cần sự chú ý liên phương thức ngay cả khi âm thanh mà nó tạo ra bị loại bỏ. `freeze_audio=True` giữ luồng âm thanh ở sigma 0 (không có bước Euler) để video vẫn có thể chú ý chéo sang nó — các ô tinh chỉnh thời gian và phần kết thúc sử dụng điều này để bám theo giọng nói của giai đoạn 1 mà không cần mỗi ô khử nhiễu lại một thực thể âm thanh khác nhau.

Sau khi trộn điều kiện x0, vận tốc là `(latents - denoised) / sigma` nên một bước RF `x0 = x - σ v` sẽ khôi phục `denoised` đã được trộn. Giai đoạn 1 / 2 / phần kết thúc giữ nguyên [FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler) và thực hiện bước Euler đó như vậy. Temporal refine thay bằng `LTXEulerAncestralRFScheduler` (`eta=0.5`); bước đó thêm nhiễu lại cho mọi token, do đó việc trộn điều kiện phải được áp dụng lại sau đó, nếu không các neo mối nối strength-0.95 sẽ bị xói mòn.

#### encode_conditions[[diffusers.LTX2DFRTemporalRefinePipeline.encode_conditions]]

```python
encode_conditions(conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None, height: int, width: int, num_frames: int, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None, generator: typing.Optional[torch.Generator] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1101)

Tiền xử lý và mã hóa điều kiện khung bằng VAE, được định vị theo khung pixel.

Trả về `(pixel_frame_index, latent, strength, num_pixel_frames)` cho mỗi điều kiện, sẵn sàng cho `condition_latents` của [prepare_latents()](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents). Việc mã hóa được tách riêng khỏi việc đặt vị trí vì các vòng lặp tinh chỉnh theo thời gian sẽ nhân vị trí của một điều kiện với `2 ** round` và đặt lại cơ sở cho từng ô, và không nên mã hóa lại cùng một khung hình tĩnh một lần cho mỗi ô để làm điều đó.

Chỉ số được trả về nằm trên lưới pixel riêng của `num_frames`; việc chuyển nó sang một canvas đã tinh chỉnh là trách nhiệm của người gọi.

#### encode_prompt[[diffusers.LTX2DFRTemporalRefinePipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 1024, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L470)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần được tạo cho mỗi prompt.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho `prompt_embeds`.

device : (`torch.device`, *tùy chọn*): thiết bị torch

dtype : (`torch.dtype`, *tùy chọn*): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

DFR chạy lịch trình sigma đã được chưng cất, được huấn luyện để sử dụng mà không cần classifier-free guidance, do đó không có nhánh âm ở đây.

#### prepare_latents[[diffusers.LTX2DFRTemporalRefinePipeline.prepare_latents]]

```python
prepare_latents(conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, condition_latents: list[tuple[int, torch.Tensor, float, int]] | None = None, keyframe_latents: list[tuple[int, torch.Tensor, float]] | None = None, slot_frame_indices: list[int] | None = None, slot_initial_latents: typing.Optional[torch.Tensor] = None, reference_latents: typing.Optional[torch.Tensor] = None, reference_downscale_factor: int = 1, batch_size: int = 1, num_channels_latents: int = 128, height: int = 512, width: int = 768, num_frames: int = 121, frame_rate: float = 24.0, noise_scale: float = 1.0, dtype: typing.Optional[torch.dtype] = None, device: typing.Optional[torch.device] = None, generator: typing.Optional[torch.Generator] = None, latents: typing.Optional[torch.Tensor] = None, latents_normalized: bool = True)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L828)

**Tham số:**

conditions (`list[LTX2VideoCondition]`, *optional*) : Điều kiện ảnh / video ở cấp độ khung hình, được định vị theo chỉ số latent.

condition_latents (`list[tuple[int, torch.Tensor, float, int]]`, *tùy chọn*) : Bản mã hóa sẵn thay thế cho `conditions`, dưới dạng `(pixel_frame_index, latent, strength, num_pixel_frames)`. Dùng chỉ số pixel thay vì chỉ số latent, vì một vòng refine theo thời gian sẽ nhân vị trí của một điều kiện với `2 ** round` và kết quả thường không rơi đúng vào ranh giới latent -- chỉ một token keyframe được thêm vào mới có thể nằm ở đó, và nó được đặt theo pixel. `pixel_frame_index == 0` vẫn có nghĩa là "thay thế khung hình đầu tiên".

keyframe_latents (`list[tuple[int, torch.Tensor, float]]`, *tùy chọn*) : Hướng dẫn keyframe đã được mã hóa dưới dạng `(pixel_frame_index, latent, strength)`, trong đó `latent` có hình dạng `(batch_size, num_channels_latents, 1, latent_height, latent_width)`. Được sử dụng bởi các vòng lặp tinh chỉnh theo thời gian để cố định các keyframe nối tiếp được mang sang từ vòng lặp trước.

slot_frame_indices (`list[int]`, *tùy chọn*) : Vị trí khung hình pixel của các khe keyframe đã tạo.

slot_initial_latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width)` nội dung được ghi vào các token slot trước khi thêm nhiễu.

reference_latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, F, H, W)` Latent tham chiếu IC-LoRA.

reference_downscale_factor (`int`, mặc định là `1`) : Tỷ lệ giữa độ phân giải đích và độ phân giải tham chiếu.

latents (`torch.Tensor`, *tùy chọn*) : `(batch_size, num_channels_latents, F, H, W)` nội dung ban đầu cho các token cơ sở. Latents của pipeline công khai là dạng thô (chưa chuẩn hóa); hãy truyền `latents_normalized=False` tại ranh giới đó. Các vòng lặp tile đã nằm trong không gian đã chuẩn hóa VAE thì giữ nguyên giá trị mặc định.

latents_normalized (`bool`, mặc định là `True`) : Xác định xem `latents`, `slot_initial_latents`, `reference_latents` và `keyframe_latents` đã được chuẩn hóa VAE hay chưa. Các vòng lặp tile nội bộ truyền `True`; mỗi pipeline `__call__` truyền `False`.

noise_scale (`float`, mặc định là `1.0`) : Mức nhiễu mà các token không điều kiện được khởi tạo, tức là sigma đầu tiên của lịch trình.

**Trả về:** `tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, slice | None]`

`(latents, conditioning_mask, clean_latents, video_coords, keyframes_mask, slot_token_slice)`. `slot_token_slice` chỉ định các token slot keyframe đã được tạo trong chuỗi đã đóng gói, hoặc `None` khi không có slot nào được yêu cầu.

Chuẩn bị các latent video đã đóng gói có nhiễu cho một lượt khử nhiễu DFR.

Chuỗi được đóng gói được bố trí theo dạng `[base | keyframes | slots | reference]`:

- Các token cơ bản bao phủ lưới ẩn mục tiêu, được khởi tạo từ `latents` khi được cung cấp.
- Các điều kiện khung hình với `index == 0` đặt mục tiêu sạch tại các vị trí khung hình đầu tiên; những điều kiện có `index > 0` và mọi phần tử của `keyframe_latents` được thêm vào như các token khung hình chính bổ sung, với mặt nạ điều kiện cho từng token bằng với cường độ của chúng.
- `slot_frame_indices` thêm một lượng token keyframe *được tạo* tương ứng với một khung latent cho mỗi vị trí, với mask điều kiện là `0` (đã khử nhiễu hoàn toàn) và phạm vi thời gian RoPE bằng đúng một khung pixel. Đây là các slot keyframe mang lại thêm các khung cho DFR; `slot_initial_latents` khởi tạo nội dung của chúng.
- `reference_latents` thêm latent bán độ phân giải của giai đoạn 1 như một tham chiếu IC-LoRA hoàn toàn sạch, với tọa độ không gian được nhân với `reference_downscale_factor` để ánh xạ vào không gian tọa độ đích.

Các token điều kiện được nối thêm mang nội dung của chúng trong `clean_latents` và một giá trị placeholder bằng 0 trong `latents`, trong khi các slot keyframe mang hạt giống của chúng trong `latents` và các giá trị 0 trong `clean_latents` -- `latents` được trả về là hỗn hợp có nhiễu của hai phần này (xem bước thêm nhiễu ở cuối phương thức này).

#### preprocess_conditions[[diffusers.LTX2DFRTemporalRefinePipeline.preprocess_conditions]]

```python
preprocess_conditions(conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = None, height: int = 512, width: int = 768, num_frames: int = 121, device: typing.Optional[torch.device] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L648)

**Tham số:**

conditions (`LTX2VideoCondition` hoặc `List[LTX2VideoCondition]`, *tuỳ chọn*, mặc định là `None`) : Một danh sách các instance điều kiện ảnh/đoạn video.

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao mong muốn tính bằng pixel.

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng mong muốn tính bằng pixel.

num_frames (`int`, *tuỳ chọn*, mặc định là `121`) : Số khung hình mong muốn trong video được tạo ra.

device (`torch.device`, *tùy chọn*, mặc định là `None`) : Thiết bị để đặt các tensor ảnh/đoạn video đã được tiền xử lý.

**Trả về:** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

Trả về một 4-tuple gồm các danh sách có độ dài `len(conditions)` như sau:
1. Danh sách đầu tiên là một danh sách các tensor video đã được tiền xử lý có hình dạng [batch_size=1, num_channels, num_frames, height, width].
2. Danh sách thứ hai là danh sách các mức độ điều kiện.
3. Danh sách thứ ba là danh sách các chỉ số không gian ẩn cho mỗi điều kiện.
4. Danh sách thứ tư là danh sách số lượng khung hình (đã cắt) trong không gian pixel cho mỗi điều kiện. Điều này cần thiết cho ngữ nghĩa tọa độ khung hình chính (các khung hình chính chỉ gồm một pixel có phạm vi thời gian bị kẹp).

Tiền xử lý các hình ảnh/đoạn video điều kiện thành các tensor torch.

#### trim_conditioning_sequence[[diffusers.LTX2DFRTemporalRefinePipeline.trim_conditioning_sequence]]

```python
trim_conditioning_sequence(start_frame: int, sequence_num_frames: int, target_num_frames: int)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L630)

**Tham số:**

start_frame (int) : Số khung đích của khung đầu tiên trong chuỗi.

sequence_num_frames (int) : Số lượng khung hình trong chuỗi.

target_num_frames (int) : Số khung hình mục tiêu trong video được tạo ra.

**Trả về:** `int`

chiều dài chuỗi đã cập nhật

Cắt ngắn một chuỗi điều kiện xuống số khung hình được phép.

#### upsample_latents[[diffusers.LTX2DFRTemporalRefinePipeline.upsample_latents]]

```python
upsample_latents(latents: Tensor, upsampler: LTX2LatentUpsamplerModel)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1090)

Chạy `upsampler` trên các latent đã chuẩn hóa, thực hiện vòng lặp qua không gian latent VAE thô như kỳ vọng.

## LTX2DFRPipelineOutput[[diffusers.LTX2DFRPipelineOutput]]

#### diffusers.LTX2DFRPipelineOutput[[diffusers.LTX2DFRPipelineOutput]]

```python
diffusers.LTX2DFRPipelineOutput(frames: Tensor, audio: Tensor, keyframes: typing.Optional[torch.Tensor] = None, keyframe_positions: list[int] | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_output.py#L27)

**Tham số:**

frames (`torch.Tensor`, `np.ndarray`, hoặc list[list[PIL.Image.Image]]) : Video đã khử nhiễu. Đầu ra latent là canvas chưa được cắt, có hình dạng `(batch_size, num_channels, latent_frames, latent_height, latent_width)`.

audio (`torch.Tensor`, `np.ndarray`) : Audio latents hoặc waveform đi kèm.

keyframes (`torch.Tensor`, *tùy chọn*) : Các latent của keyframe được tạo ra hoặc mang theo, có hình dạng `(batch_size, num_channels, num_keyframes, latent_height, latent_width)`. Là `None` khi `output_type != "latent"`, hoặc khi lượt xử lý không tạo ra các slot (ví dụ: một epilogue dạng gạch).

keyframe_positions (`list[int]`, *optional*) : Chỉ số khung hình pixel của mỗi keyframe trên canvas của lượt xử lý này; `None` khi `keyframes` là `None`. Sau một vòng thời gian, các giá trị này không thể suy ra lại từ `num_frames` ban đầu và phải được truyền vào giai đoạn tiếp theo.

Lớp đầu ra cho các pipeline DFR.

## LTX2LatentUpsamplePipeline[[diffusers.LTX2LatentUpsamplePipeline]]

#### diffusers.LTX2LatentUpsamplePipeline[[diffusers.LTX2LatentUpsamplePipeline]]

```python
diffusers.LTX2LatentUpsamplePipeline(vae: AutoencoderKLLTX2Video, latent_upsampler: LTX2LatentUpsamplerModel)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L104)

#### __call__[[diffusers.LTX2LatentUpsamplePipeline.__call__]]

```python
__call__(video: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, height: int = 512, width: int = 768, num_frames: int = 121, spatial_patch_size: int = 1, temporal_patch_size: int = 1, latents: typing.Optional[torch.Tensor] = None, latents_normalized: bool = False, decode_timestep: float | list[float] = 0.0, decode_noise_scale: float | list[float] | None = None, adain_factor: float = 0.0, tone_map_compression_ratio: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str | None = 'pil', return_dict: bool = True)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L264)

**Tham số:**

video (`list[PipelineImageInput]`, *tùy chọn*) : Video cần được tăng mẫu (ví dụ như đầu ra của giai đoạn đầu tiên của LTX 2.0). Nếu không được cung cấp, `latents` phải được cung cấp.

height (`int`, *tuỳ chọn*, mặc định là `512`) : Chiều cao tính bằng pixel của video đầu vào (không phải video được tạo ra, video đó sẽ có độ phân giải lớn hơn).

width (`int`, *tuỳ chọn*, mặc định là `768`) : Độ rộng tính bằng pixel của video đầu vào (không phải video được tạo ra, video đó sẽ có độ phân giải lớn hơn).

num_frames (`int`, *tuỳ chọn*, mặc định là `121`) : Số khung hình trong video đầu vào.

spatial_patch_size (`int`, *tuỳ chọn*, mặc định là `1`) : Kích thước patch không gian của các latents video. Được sử dụng khi `latents` được cung cấp nếu cần giải nén.

temporal_patch_size (`int`, *tuỳ chọn*, mặc định là `1`) : Kích thước patch thời gian của các latents video. Được sử dụng khi `latents` được cung cấp nếu cần giải nén.

latents (`torch.Tensor`, *tùy chọn*) : Các latents video đã tạo trước. Tham số này có thể được cung cấp thay cho đối số `video`. Nó có thể là một chuỗi patch có hình dạng `(batch_size, seq_len, hidden_dim)` hoặc một video latent có hình dạng `(batch_size, latent_channels, latent_frames, latent_height, latent_width)`.

latents_normalized (`bool`, *tùy chọn*, mặc định là `False`) : Nếu `latents` được cung cấp, xác định xem `latents` có được chuẩn hóa bằng giá trị trung bình và độ lệch chuẩn của latent VAE hay không. Nếu `True`, `latents` sẽ được khử chuẩn hóa trước khi được cung cấp cho bộ tăng cấp latent.

decode_timestep (`float`, mặc định là `0.0`) : Bước thời gian tại đó video được tạo ra sẽ được giải mã.

decode_noise_scale (`float`, mặc định là `None`) : Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã.

adain_factor (`float`, *optional*, mặc định là `0.0`) : Hệ số trộn Adaptive Instance Normalization (AdaIN) giữa các latents được upsample và latents gốc. Giá trị nên nằm trong khoảng [-10.0, 10.0]; việc cung cấp 0.0 (mặc định) có nghĩa là không thực hiện AdaIN.

tone_map_compression_ratio (`float`, *optional*, mặc định là `0.0`) : Cường độ nén cho tone mapping, sẽ làm giảm dải động của các giá trị latent. Điều này hữu ích để chuẩn hóa các latent có phương sai cao hoặc để điều kiện hóa đầu ra trong quá trình sinh. Giá trị nên nằm trong [0, 1], trong đó 0.0 (mặc định) có nghĩa là không áp dụng tone mapping và 1.0 tương ứng với hiệu ứng nén đầy đủ.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.ltx.LTXPipelineOutput` thay vì một tuple thông thường hay không.

**Trả về:** `~pipelines.ltx.LTXPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `~pipelines.ltx.LTXPipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là video đã được upsample.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import LTX2ImageToVideoPipeline, LTX2LatentUpsamplePipeline
>>> from diffusers.utils import encode_video
>>> from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel
>>> from diffusers.utils import load_image

>>> pipe = LTX2ImageToVideoPipeline.from_pretrained("Lightricks/LTX-2", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()

>>> image = load_image(
...     "https://huggingface.co/datasets/a-r-r-o-w/tiny-meme-dataset-captioned/resolve/main/images/8.png"
... )
>>> prompt = "A young girl stands calmly in the foreground, looking directly at the camera, as a house fire rages in the background."
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"

>>> frame_rate = 24.0
>>> video, audio = pipe(
...     image=image,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     width=768,
...     height=512,
...     num_frames=121,
...     frame_rate=frame_rate,
...     num_inference_steps=40,
...     guidance_scale=4.0,
...     output_type="pil",
...     return_dict=False,
... )

>>> latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
...     "Lightricks/LTX-2", subfolder="latent_upsampler", torch_dtype=torch.bfloat16
... )
>>> upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
>>> upsample_pipe.vae.enable_tiling()
>>> upsample_pipe.to(device="cuda", dtype=torch.bfloat16)

>>> video = upsample_pipe(
...     video=video,
...     width=768,
...     height=512,
...     output_type="np",
...     return_dict=False,
... )[0]

>>> encode_video(
...     video[0],
...     fps=frame_rate,
...     audio=audio[0].float().cpu(),
...     audio_sample_rate=pipe.vocoder.config.output_sampling_rate,  # should be 24000
...     output_path="video.mp4",
... )
```

#### adain_filter_latent[[diffusers.LTX2LatentUpsamplePipeline.adain_filter_latent]]

```python
adain_filter_latent(latents: Tensor, reference_latents: Tensor, factor: float = 1.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L168)

**Tham số:**

latents (`torch.Tensor`) : Latent đầu vào cần chuẩn hóa

reference_latents (`torch.Tensor`) : Các latents tham chiếu cung cấp thống kê phong cách.

factor (`float`) : Hệ số trộn giữa latent gốc và latent đã biến đổi. Khoảng: -10.0 đến 10.0, Mặc định: 1.0

**Trả về:** `torch.Tensor`

Tensor ẩn đã được biến đổi

Áp dụng Chuẩn hóa Thực thể Thích ứng (AdaIN) lên một tensor ẩn dựa trên các thống kê từ một tensor ẩn tham chiếu.

#### tone_map_latents[[diffusers.LTX2LatentUpsamplePipeline.tone_map_latents]]

```python
tone_map_latents(latents: Tensor, compression: float)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L196)

**Tham số:**

latents : torch.Tensor Tensor ẩn đầu vào với hình dạng tùy ý. Được kỳ vọng nằm trong khoảng [-1, 1] hoặc [0, 1].

compression : float Cường độ nén trong khoảng [0, 1]. - 0.0: Không ánh xạ tông (biến đổi đồng nhất) - 1.0: Hiệu ứng nén toàn phần

**Trả về:**

torch.Tensor Tensor latent đã được tone-map có cùng hình dạng với đầu vào.

Áp dụng một hàm ánh xạ tông phi tuyến lên các giá trị tiềm ẩn để giảm phạm vi động của chúng một cách mượt mà về mặt cảm nhận bằng cách sử dụng nén dựa trên sigmoid.

Điều này hữu ích để chuẩn hóa các latent có phương sai cao hoặc để điều kiện hóa đầu ra trong quá trình tạo, đặc biệt khi kiểm soát hành vi động bằng hệ số `compression`.

## LTX2VideoDiffusionDecodePipeline[[diffusers.LTX2VideoDiffusionDecodePipeline]]

#### diffusers.LTX2VideoDiffusionDecodePipeline[[diffusers.LTX2VideoDiffusionDecodePipeline]]

```python
diffusers.LTX2VideoDiffusionDecodePipeline(diffusion_decoder: LTX2VideoDiffusionDecoderModel, scheduler, vae: AutoencoderKLLTX2Video = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_diffusion_decode.py#L27)

**Tham số:**

diffusion_decoder ([LTX2VideoDiffusionDecoderModel](/docs/diffusers/main/vi/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel)) : Bộ giải mã video khuếch tán.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)): Bộ lập lịch điều khiển các bước khử nhiễu của bộ giải mã.

vae ([AutoencoderKLLTX2Video](/docs/diffusers/main/vi/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video), *tùy chọn*) : Chỉ được tham chiếu để lấy thống kê ẩn dùng để khử chuẩn hóa. Khi bỏ qua, pipeline sẽ quay về mặc định của LTX-2, nên luồng làm việc chỉ giải mã không cần phải nạp một autoencoder thứ hai.

Giải mã các ẩn video LTX-2 bằng bộ giải mã khuếch tán được giới thiệu trong LTX-2.5.

Khác với bộ giải mã tích chập, bộ giải mã này tự nó là một mô hình khuếch tán nhỏ: nó khử nhiễu các pixel có điều kiện dựa trên một thể tích ngữ cảnh được xây dựng từ các latent, do đó nó cần một trình lập lịch (scheduler) và một bộ sinh (generator). Kết hợp nó với bất kỳ pipeline LTX-2 nào được chạy với `output_type="latent"`, và truyền `denormalize=False` vì đường dẫn đó đã áp dụng thống kê latent.

#### __call__[[diffusers.LTX2VideoDiffusionDecodePipeline.__call__]]

```python
__call__(latents: Tensor, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str = 'pil', return_dict: bool = True, denormalize: bool = True)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_ltx2_diffusion_decode.py#L79)

**Tham số:**

latents (`torch.Tensor`) : Latents có shape `(B, C, F, H, W)`. Lưu ý rằng một pipeline LTX-2 chạy với `output_type="latent"` sẽ trả về các latents *đã* được khử chuẩn hóa, vì vậy hãy truyền `denormalize=False` cho những trường hợp đó.

generator (`torch.Generator`, *tùy chọn*) : Bộ giải mã lấy mẫu nhiễu mà nó khử nhiễu, vì vậy hãy truyền một generator để đảm bảo quá trình giải mã có thể tái lập được.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của video đã giải mã. Chọn giữa `"pil"`, `"np"`, `"pt"` và `"latent"`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `LTX2VideoDecodeOutput` thay vì một tuple thông thường hay không.

denormalize (`bool`, *tùy chọn*, mặc định là `True`) : Xác định có áp dụng thống kê ẩn trước khi giải mã hay không. Đặt thành `False` nếu các ẩn đã được chuẩn hóa lại.

**Trả về:** `LTX2VideoDecodeOutput` hoặc `tuple`

## LTX2DurationHead[[diffusers.pipelines.ltx2.LTX2DurationHead]]

#### diffusers.pipelines.ltx2.LTX2DurationHead[[diffusers.pipelines.ltx2.LTX2DurationHead]]

```python
diffusers.pipelines.ltx2.LTX2DurationHead(video_cross_attention_dim: int = 4096, audio_cross_attention_dim: int = 2048, pooler_hidden_dim: int = 256, num_queries: int = 1, num_pooler_heads: int = 4, mlp_hidden_dim: int = 256)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/duration_head.py#L81)

**Tham số:**

video_cross_attention_dim (`int`, mặc định là `4096`) : Độ rộng của đầu ra bộ kết nối video.

audio_cross_attention_dim (`int`, mặc định là `2048`) : Độ rộng của đầu ra bộ kết nối âm thanh.

pooler_hidden_dim (`int`, mặc định là `256`) : Kích thước chiều ẩn chung mà cả hai phương thức (modality) đều được chiếu vào.

num_queries (`int`, mặc định là `1`) : Số lượng truy vấn pooling có thể học được.

num_pooler_heads (`int`, mặc định là `4`) : Số đầu attention được sử dụng bởi pooler.

mlp_hidden_dim (`int`, mặc định là `256`) : Độ rộng ẩn của MLP đầu ra. Được đặt tên với hậu tố `_dim` để tránh xung đột với submodule `mlp_hidden`, vốn sẽ bị che khuất bởi giá trị cấu hình này nếu không có `ConfigMixin.__getattr__`.

Dự đoán thời lượng tự nhiên của cảnh quay được ngụ ý bởi mô tả, từ các đầu ra của bộ kết nối văn bản LTX-2.

Head không phụ thuộc vào chế độ (modality): truyền vào một hoặc cả hai đầu ra của bộ kết nối video và audio. Các phép chiếu đầu vào cụ thể theo chế độ ánh xạ mỗi luồng vào một chiều pooler chung, các embedding chế độ có thể học được gắn nhãn cho các luồng để pooler có thể phân biệt chúng, và một MLP nhỏ chuyển vector đã pool thành log-duration. Mục tiêu hồi quy được huấn luyện theo log-giây, do đó `forward` sẽ mũ hóa và người gọi luôn nhận được giá trị theo giây.

Có sẵn từ các checkpoint của LTX-2.5 trở đi.

#### forward[[diffusers.pipelines.ltx2.LTX2DurationHead.forward]]

```python
forward(video_tokens: typing.Optional[torch.Tensor] = None, audio_tokens: typing.Optional[torch.Tensor] = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/duration_head.py#L134)

**Tham số:**

video_tokens (`torch.Tensor` có hình dạng `(batch_size, seq_len, video_cross_attention_dim)`, *tùy chọn*) : Đầu ra của bộ kết nối video.

audio_tokens (`torch.Tensor` có hình dạng `(batch_size, seq_len, audio_cross_attention_dim)`, *tùy chọn*) : Đầu ra của bộ kết nối âm thanh.

**Trả về:** `torch.Tensor` có hình dạng `(batch_size,)`

thời lượng dự đoán tính bằng giây.

#### predict_num_frames[[diffusers.pipelines.ltx2.LTX2DurationHead.predict_num_frames]]

```python
predict_num_frames(video_tokens: typing.Optional[torch.Tensor] = None, audio_tokens: typing.Optional[torch.Tensor] = None, frame_rate: float, temporal_compression_ratio: int, min_seconds: float = 1.0, max_seconds: float = 20.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/duration_head.py#L172)

**Tham số:**

video_tokens (`torch.Tensor`, *tùy chọn*) : Đầu ra của bộ kết nối video cho một prompt duy nhất.

audio_tokens (`torch.Tensor`, *tùy chọn*) : Đầu ra của bộ kết nối âm thanh cho một prompt duy nhất.

frame_rate (`float`) : Số khung hình mỗi giây được sử dụng để chuyển đổi thời lượng dự đoán thành số lượng khung hình.

temporal_compression_ratio (`int`) : Tỷ lệ nén thời gian của VAE, định nghĩa lưới khung hình.

min_seconds (`float`, mặc định là `1.0`) : Giới hạn dưới của dự đoán.

max_seconds (`float`, mặc định là `20.0`) : Giới hạn trên của dự đoán.

**Trả về:** `int`

số lượng khung hình nằm trên lưới thời gian của VAE.

Dự đoán số lượng khung hình từ các token kết nối, được kẹp trong khoảng `[min_seconds, max_seconds]` và làm tròn theo lưới thời gian nhân quả của VAE (`k * temporal_compression_ratio + 1`).

Việc kẹp (clamp) được áp dụng trước khi làm tròn (snap): số khung đã kẹp không nhất thiết phải căn chỉnh theo lưới, do đó nếu làm tròn trước sẽ cho kết quả khác. Vì làm tròn làm tròn xuống (floor), kết quả có thể rơi xuống dưới giá trị tối thiểu; khi điều đó xảy ra, kết quả sẽ được làm tròn lên đến điểm lưới tiếp theo, để đảm bảo số khung vẫn nằm trong phạm vi cho phép.

Các cận hẹp có thể chuyển đổi thành một cửa sổ khung hình không chứa bất kỳ điểm lưới nào -- ở 24 fps, `[1.0s, 1.02s]` được làm tròn thành `[24, 24]`, và 24 không phải là `8k + 1`. Điểm lưới gần nhất sẽ được sử dụng và một cảnh báo được ghi lại, vì việc vượt quá dưới một bước lưới còn tốt hơn là từ chối tạo. Do đó, số lượng được trả về luôn nằm trên lưới, nhưng trong trường hợp này có thể rơi ra ngoài các cận được yêu cầu một chút.

## LTX2PipelineOutput[[diffusers.pipelines.ltx2.LTX2PipelineOutput]]

#### diffusers.pipelines.ltx2.LTX2PipelineOutput[[diffusers.pipelines.ltx2.LTX2PipelineOutput]]

```python
diffusers.pipelines.ltx2.LTX2PipelineOutput(frames: Tensor, audio: Tensor)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ltx2/pipeline_output.py#L9)

**Tham số:**

frames (`torch.Tensor`, `np.ndarray`, hoặc list[list[PIL.Image.Image]]) : Danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dài `batch_size,` trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dài `num_frames.` Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng `(batch_size, num_frames, channels, height, width)`.

audio (`torch.Tensor`, `np.ndarray`) : TODO

Lớp đầu ra cho các pipeline LTX.

## LTX2ModularPipeline[[diffusers.LTX2ModularPipeline]]

#### diffusers.LTX2ModularPipeline[[diffusers.LTX2ModularPipeline]]

```python
diffusers.LTX2ModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/ltx2/modular_pipeline.py#L26)

Một ModularPipeline cho LTX-2 (tạo video + âm thanh đồng thời).

## LTX2AutoBlocks[[diffusers.LTX2AutoBlocks]]

#### diffusers.LTX2AutoBlocks[[diffusers.LTX2AutoBlocks]]

```python
diffusers.LTX2AutoBlocks()
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/ltx2/modular_blocks_ltx2.py#L1761)

Auto blocks cho LTX-2 hỗ trợ text-to-video, image-to-video, condition-to-video và in-context (IC-LoRA) generation (video + audio kết hợp).

Các quy trình làm việc được hỗ trợ:
- `text2video`: yêu cầu `prompt`
- `image2video`: yêu cầu `image`, `prompt`
- `condition`: yêu cầu `conditions`, `prompt`
- `in_context`: yêu cầu `reference_conditions`, `num_frames`, `prompt`

Các thành phần: prompt_enhancer (`PreTrainedModel`) processor (`ProcessorMixin`) text_encoder (`PreTrainedModel`) tokenizer (`PreTrainedTokenizerBase`) connectors (`LTX2TextConnectors`) duration_head (`LTX2DurationHead`) vae (`AutoencoderKLLTX2Video`) video_processor (`VideoProcessor`) transformer (`LTX2VideoTransformer3DModel`) scheduler (`FlowMatchEulerDiscreteScheduler`) audio_vae (`AutoencoderKLLTX2Audio`) guider (`LTX2Guidance`) audio_guider (`LTX2Guidance`) vocoder (`LTX2Vocoder`)

Inputs: prompt (`str`, *tùy chọn*): Prompt hoặc các prompt để định hướng việc tạo hình ảnh. conditions (`list`, *tùy chọn*): `LTX2VideoCondition` (hoặc danh sách các đối tượng này) đặt các điều kiện hình ảnh/đoạn video tại các chỉ số khung hình latent của video được tạo. enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là False): Có chạy trình tăng cường prompt hay không. Tính năng này được bật theo yêu cầu, phù hợp với các pipeline tham chiếu của Lightricks. system_prompt (`str`, *tùy chọn*): System prompt cho việc tăng cường. Mặc định là `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` khi có sẵn khung hình điều kiện `PIL.Image.Image`, nếu không thì là `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`. prompt_max_new_tokens (`int`, *tùy chọn*): Số lượng token mới tối đa để tạo trong quá trình tăng cường prompt. Mặc định là 600, ngân sách của trình tăng cường Gemma-4 của LTX-2.5. prompt_enhancement_kwargs (`dict`, *tùy chọn*): Các đối số từ khóa cho cuộc gọi `.generate` của trình tăng cường. Mặc định là giải mã tham lam (greedy decoding). prompt_enhancement_seed (`int`, *tùy chọn*, mặc định là 10): Hạt ngẫu nhiên cho việc tăng cường prompt (không có tác dụng dưới chế độ giải mã tham lam của LTX-2.5). generator (`Generator`, *tùy chọn*): Bộ tạo Torch cho việc tạo ra kết quả xác định. image (`Image | list`, *tùy chọn*): Hình ảnh tham chiếu để khử nhiễu. Có thể là một hình ảnh đơn lẻ hoặc danh sách các hình ảnh. negative_prompt (`str`, *tùy chọn*): Prompt hoặc các prompt không dùng để định hướng việc tạo hình ảnh. max_sequence_length (`int`, *tùy chọn*, mặc định là 1024): Độ dài chuỗi tối đa cho việc mã hóa prompt. min_seconds (`float`, *tùy chọn*, mặc định là 1.0): Giới hạn dưới của thời lượng được dự đoán tự động. max_seconds (`float`, *tùy chọn*, mặc định là 20.0): Giới hạn trên của thời lượng được dự đoán tự động. Phải lớn hơn nghiêm ngặt so với `min_seconds`. frame_rate (`float`, *tùy chọn*, mặc định là 24.0): Số khung hình mỗi giây của video được tạo. height (`int`, *tùy chọn*, mặc định là 512): Chiều cao tính bằng pixel của hình ảnh được tạo. width (`int`, *tùy chọn*, mặc định là 704): Chiều rộng tính bằng pixel của hình ảnh được tạo. image_crf (`int`, *tùy chọn*): CRF của H.264 được sử dụng để nén lại hình ảnh điều kiện `image` trước khi mã hóa VAE, phù hợp với mức nén mà mô hình được huấn luyện. `None` (mặc định) sẽ được xác định từ quá trình tạo của text-encoder (33 cho LTX-2.3 trở về trước, 18 cho LTX-2.5). Truyền `0` để bỏ qua việc nén lại. Yêu cầu một `PIL.Image.Image` khi chạy nén lại. num_frames (`int`, *tùy chọn*): Số lượng khung hình trong video được tạo. Bỏ qua để dự đoán tự động thông qua `duration_head` (xem `LTX2AutoDurationStep`). reference_conditions (`list`, *tùy chọn*): `LTX2ReferenceCondition` (hoặc danh sách các đối tượng này) mà các video của chúng được mã hóa thành các token latent bổ sung để bộ thích ứng IC-LoRA chú ý đến. reference_downscale_factor (`int`, *tùy chọn*, mặc định là 1): Tỷ lệ giữa độ phân giải đích và độ phân giải tham chiếu; 2 có nghĩa là hình tham chiếu được tiền xử lý ở một nửa độ phân giải đích. Các tọa độ không gian được nhân với hệ số này để các token tham chiếu nằm trong không gian tọa độ đích. Phải khớp với hệ số mà IC-LoRA được huấn luyện. conditioning_attention_strength (`float`, *tùy chọn*, mặc định là 1.0): Số vô hướng trong [0, 1] kiểm soát mức độ mạnh mẽ mà các token nhiễu và token tham chiếu chú ý đến nhau. 1.0 (mặc định) giữ cho sự chú ý không bị che khuất. conditioning_attention_mask (`Tensor`, *tùy chọn*): Mặt nạ không gian pixel tùy chọn có dạng (1, 1, F, H, W) với các giá trị trong [0, 1] cung cấp cường độ chú ý thay đổi theo không gian. Được giảm mẫu xuống lưới latent của tham chiếu và nhân với `conditioning_attention_strength`. motion_speed (`float`, *tùy chọn*, mặc định là 1.0): Tốc độ của chuyển động so với thời gian thực. Các nhúng vị trí được điều kiện bởi `frame_rate / motion_speed`, do đó các giá trị nhỏ hơn 1 làm chậm chuyển động, ví dụ `0.2` cho chuyển động chậm 5 lần của LoRA Slow-Motion-Control. `frame_rate` vẫn là tốc độ phát. num_videos_per_prompt (`int`, *tùy chọn*, mặc định là 1): Số lượng hình ảnh để tạo cho mỗi prompt. condition_latents (`list`, *tùy chọn*): Latent VAE đã chuẩn hóa cho từng điều kiện, có dạng [1, C, F, H, W]. condition_strengths (`list`, *tùy chọn*): Cường độ điều kiện cho từng điều kiện. condition_indices (`list`, *tùy chọn*): Chỉ số khung hình latent cho từng điều kiện, tại đó điều kiện được áp dụng. condition_pixel_frames (`list`, *tùy chọn*): Số lượng khung hình pixel đã cắt cho từng điều kiện, được sử dụng để kẹp các tọa độ keyframe đơn khung hình. reference_latents (`Tensor`, *tùy chọn*): Các token tham chiếu đã đóng gói có dạng [1, total_reference_tokens, C], hoặc `None` khi không có điều kiện tham chiếu nào được cung cấp (`LTX2AutoReferenceEncoderStep` bị bỏ qua). reference_coords (`Tensor`, *tùy chọn*): Tọa độ RoPE cho các token tham chiếu. reference_token_counts (`list`, *tùy chọn*): Số lượng token cho từng tham chiếu, theo thứ tự của `reference_conditions`. latents (`Tensor`): Latent nhiễu đã tạo trước cho việc tạo hình ảnh. noise_scale (`float`, *tùy chọn*): Mức nhiễu ban đầu cho các token không có điều kiện. `None` (mặc định) sẽ được xác định thành `sigmas[0]` khi các `sigmas` tùy chỉnh được cung cấp, nếu không thì là 1.0. sigmas (`list`, *tùy chọn*): Các sigma tùy chỉnh cho quá trình khử nhiễu. reference_cross_mask (`Tensor`, *tùy chọn*): Cường độ chú ý nhiễu<->tham chiếu cho từng token tham chiếu, có dạng [1, num_ref_tokens]. num_inference_steps (`int`): Số bước khử nhiễu. timesteps (`Tensor`): Các bước thời gian cho quá trình khử nhiễu. audio_latents (`Tensor`): Latent âm thanh đã mã hóa trước tùy chọn; nhiễu ngẫu nhiên được sử dụng khi không được cung cấp. **denoiser_input_fields (`None`, *tùy chọn*): Các đầu vào mô hình có điều kiện cho bộ khử nhiễu: ví dụ prompt_embeds, negative_prompt_embeds, v.v. use_cross_timestep (`bool`, *tùy chọn*, mặc định là True): Có điều kiện hóa transformer bằng một bước thời gian chéo riêng biệt cho từng token hay không (LTX-2.3+). attention_kwargs (`dict`, *tùy chọn*): Các kwargs bổ sung cho các bộ xử lý chú ý. image_latents (`Tensor`, *tùy chọn*): Latent của hình ảnh tham chiếu đã mã hóa VAE được sử dụng cho việc điều kiện từ hình ảnh sang video. output_type (`str`, *tùy chọn*, mặc định là pil): Định dạng đầu ra: 'pil', 'np', 'pt'. decode_timestep (`None`, *tùy chọn*, mặc định là 0.0): Bước thời gian tại đó VAE giải mã các latent cuối cùng. decode_noise_scale (`None`, *tùy chọn*): Hệ số nội suy nhiễu được áp dụng cho các latent tại bước thời gian giải mã.

Outputs: videos (`list`): Các video được tạo. audio (`Tensor`): Dạng sóng âm thanh được tạo.

## LTX25ModularPipeline[[diffusers.LTX25ModularPipeline]]

#### diffusers.LTX25ModularPipeline[[diffusers.LTX25ModularPipeline]]

```python
diffusers.LTX25ModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/ltx2/modular_pipeline.py#L125)

Một ModularPipeline cho LTX-2.5 (tạo video + âm thanh đồng thời).

Giống hệt [LTX2ModularPipeline](/docs/diffusers/main/vi/api/pipelines/ltx2#diffusers.LTX2ModularPipeline) ngoại trừ việc các khối mặc định của nó giải mã bằng bộ giải mã video khuếch tán, đây là mặc định gốc từ LTX-2.5 trở đi. Một checkpoint được định tuyến đến đây thông qua `modular_model_index.json`.

## LTX25AutoBlocks[[diffusers.LTX25AutoBlocks]]

#### diffusers.LTX25AutoBlocks[[diffusers.LTX25AutoBlocks]]

```python
diffusers.LTX25AutoBlocks()
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/ltx2/modular_blocks_ltx25.py#L215)

Auto blocks cho LTX-2.5 hỗ trợ text-to-video, image-to-video, condition-to-video và in-context (IC-LoRA) generation (video + audio kết hợp). Giống hệt `LTX2AutoBlocks` ngoại trừ video decoder là `LTX2DiffusionVaeDecoderStep`, vì diffusion decoder là mặc định gốc từ LTX-2.5 trở đi. Để decode bằng convolutional VAE thay thế, hãy thay thế decode block: `blocks.sub_blocks["decode"] = LTX2AutoDecoderStep()`.

Các quy trình làm việc được hỗ trợ:
- `text2video`: yêu cầu `prompt`
- `image2video`: yêu cầu `image`, `prompt`
- `condition`: yêu cầu `conditions`, `prompt`
- `in_context`: yêu cầu `reference_conditions`, `num_frames`, `prompt`

Các thành phần: prompt_enhancer (`PreTrainedModel`) processor (`ProcessorMixin`) text_encoder (`PreTrainedModel`) tokenizer (`PreTrainedTokenizerBase`) connectors (`LTX2TextConnectors`) duration_head (`LTX2DurationHead`) vae (`AutoencoderKLLTX2Video`) video_processor (`VideoProcessor`) transformer (`LTX2VideoTransformer3DModel`) scheduler (`FlowMatchEulerDiscreteScheduler`) audio_vae (`AutoencoderKLLTX2Audio`) guider (`LTX2Guidance`) audio_guider (`LTX2Guidance`) diffusion_decoder (`LTX2VideoDiffusionDecoderModel`) vocoder (`LTX2Vocoder`)

Inputs: prompt (`str`, *tùy chọn*): Prompt hoặc các prompt để định hướng việc tạo hình ảnh. conditions (`list`, *tùy chọn*): `LTX2VideoCondition` (hoặc danh sách các đối tượng này) đặt các điều kiện hình ảnh/đoạn video tại các chỉ số khung hình latent của video được tạo. enable_prompt_enhancement (`bool`, *tùy chọn*, mặc định là False): Có chạy trình tăng cường prompt hay không. Tính năng này được bật theo yêu cầu, phù hợp với các pipeline tham chiếu của Lightricks. system_prompt (`str`, *tùy chọn*): System prompt cho việc tăng cường. Mặc định là `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` khi có sẵn khung hình điều kiện `PIL.Image.Image`, nếu không thì là `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`. prompt_max_new_tokens (`int`, *tùy chọn*): Số lượng token mới tối đa để tạo trong quá trình tăng cường prompt. Mặc định là 600, ngân sách của trình tăng cường Gemma-4 của LTX-2.5. prompt_enhancement_kwargs (`dict`, *tùy chọn*): Các đối số từ khóa cho cuộc gọi `.generate` của trình tăng cường. Mặc định là giải mã tham lam (greedy decoding). prompt_enhancement_seed (`int`, *tùy chọn*, mặc định là 10): Hạt ngẫu nhiên cho việc tăng cường prompt (không có tác dụng dưới chế độ giải mã tham lam của LTX-2.5). generator (`Generator`, *tùy chọn*): Bộ tạo Torch cho việc tạo ra có tính xác định. image (`Image | list`, *tùy chọn*): Hình ảnh tham chiếu để khử nhiễu. Có thể là một hình ảnh đơn lẻ hoặc danh sách các hình ảnh. negative_prompt (`str`, *tùy chọn*): Prompt hoặc các prompt không dùng để định hướng việc tạo hình ảnh. max_sequence_length (`int`, *tùy chọn*, mặc định là 1024): Độ dài chuỗi tối đa cho việc mã hóa prompt. min_seconds (`float`, *tùy chọn*, mặc định là 1.0): Giới hạn dưới của thời lượng được dự đoán tự động. max_seconds (`float`, *tùy chọn*, mặc định là 20.0): Giới hạn trên của thời lượng được dự đoán tự động. Phải lớn hơn nghiêm ngặt so với `min_seconds`. frame_rate (`float`, *tùy chọn*, mặc định là 24.0): Số khung hình mỗi giây của video được tạo. height (`int`, *tùy chọn*, mặc định là 512): Chiều cao tính bằng pixel của hình ảnh được tạo. width (`int`, *tùy chọn*, mặc định là 704): Chiều rộng tính bằng pixel của hình ảnh được tạo. image_crf (`int`, *tùy chọn*): CRF của H.264 được sử dụng để nén lại hình ảnh điều kiện `image` trước khi mã hóa VAE, phù hợp với mức nén mà mô hình được huấn luyện. `None` (mặc định) sẽ được xác định từ quá trình tạo của text-encoder (33 cho LTX-2.3 trở về trước, 18 cho LTX-2.5). Truyền `0` để bỏ qua việc nén lại. Yêu cầu một `PIL.Image.Image` khi chạy nén lại. num_frames (`int`, *tùy chọn*): Số lượng khung hình trong video được tạo. Bỏ qua để dự đoán tự động thông qua `duration_head` (xem `LTX2AutoDurationStep`). reference_conditions (`list`, *tùy chọn*): `LTX2ReferenceCondition` (hoặc danh sách các đối tượng này) mà các video của chúng được mã hóa thành các token latent bổ sung để bộ thích ứng IC-LoRA chú ý đến. reference_downscale_factor (`int`, *tùy chọn*, mặc định là 1): Tỷ lệ giữa độ phân giải đích và độ phân giải tham chiếu; 2 có nghĩa là hình tham chiếu được tiền xử lý ở một nửa độ phân giải đích. Các tọa độ không gian được nhân với hệ số này để các token tham chiếu nằm trong không gian tọa độ đích. Phải khớp với hệ số mà IC-LoRA được huấn luyện. conditioning_attention_strength (`float`, *tùy chọn*, mặc định là 1.0): Số vô hướng trong [0, 1] kiểm soát mức độ mạnh mẽ mà các token nhiễu và token tham chiếu chú ý đến nhau. 1.0 (mặc định) giữ cho sự chú ý không bị che mờ. conditioning_attention_mask (`Tensor`, *tùy chọn*): Mặt nạ không gian pixel tùy chọn có dạng (1, 1, F, H, W) với các giá trị trong [0, 1] cung cấp cường độ chú ý thay đổi theo không gian. Được giảm mẫu xuống lưới latent của hình tham chiếu và nhân với `conditioning_attention_strength`. motion_speed (`float`, *tùy chọn*, mặc định là 1.0): Tốc độ của chuyển động so với thời gian thực. Các nhúng vị trí được điều kiện bởi `frame_rate / motion_speed`, do đó các giá trị nhỏ hơn 1 làm chậm chuyển động, ví dụ `0.2` cho chuyển động chậm 5 lần của LoRA Slow-Motion-Control. `frame_rate` vẫn là tốc độ phát. num_videos_per_prompt (`int`, *tùy chọn*, mặc định là 1): Số lượng hình ảnh để tạo cho mỗi prompt. condition_latents (`list`, *tùy chọn*): Các latent VAE đã chuẩn hóa cho từng điều kiện, có dạng [1, C, F, H, W]. condition_strengths (`list`, *tùy chọn*): Cường độ điều kiện cho từng điều kiện. condition_indices (`list`, *tùy chọn*): Chỉ số khung hình latent cho từng điều kiện, tại đó điều kiện được áp dụng. condition_pixel_frames (`list`, *tùy chọn*): Số lượng khung hình pixel đã cắt cho từng điều kiện, được sử dụng để kẹp các tọa độ keyframe đơn khung hình. reference_latents (`Tensor`, *tùy chọn*): Các token tham chiếu đã đóng gói có dạng [1, total_reference_tokens, C], hoặc `None` khi không có điều kiện tham chiếu nào được cung cấp (`LTX2AutoReferenceEncoderStep` bị bỏ qua). reference_coords (`Tensor`, *tùy chọn*): Tọa độ RoPE cho các token tham chiếu. reference_token_counts (`list`, *tùy chọn*): Số lượng token cho từng tham chiếu, theo thứ tự của `reference_conditions`. latents (`Tensor`): Các latent nhiễu đã tạo trước cho việc tạo hình ảnh. noise_scale (`float`, *tùy chọn*): Mức nhiễu ban đầu cho các token không có điều kiện. `None` (mặc định) sẽ được xác định thành `sigmas[0]` khi các `sigmas` tùy chỉnh được cung cấp, nếu không thì là 1.0. sigmas (`list`, *tùy chọn*): Các sigma tùy chỉnh cho quá trình khử nhiễu. reference_cross_mask (`Tensor`, *tùy chọn*): Cường độ chú ý nhiễu<->tham chiếu cho từng token tham chiếu, có dạng [1, num_ref_tokens]. num_inference_steps (`int`): Số bước khử nhiễu. timesteps (`Tensor`): Các bước thời gian cho quá trình khử nhiễu. audio_latents (`Tensor`): Các latent âm thanh đã mã hóa trước tùy chọn; nhiễu ngẫu nhiên được sử dụng khi không được cung cấp. **denoiser_input_fields (`None`, *tùy chọn*): các đầu vào mô hình có điều kiện cho bộ khử nhiễu: ví dụ prompt_embeds, negative_prompt_embeds, v.v. use_cross_timestep (`bool`, *tùy chọn*, mặc định là True): Có điều kiện hóa transformer bằng một bước thời gian chéo riêng biệt cho từng token hay không (LTX-2.3+). attention_kwargs (`dict`, *tùy chọn*): Các kwargs bổ sung cho các bộ xử lý chú ý. image_latents (`Tensor`, *tùy chọn*): Các latent của hình ảnh tham chiếu đã mã hóa VAE được sử dụng cho việc điều kiện từ hình ảnh sang video. output_type (`str`, *tùy chọn*, mặc định là pil): Định dạng đầu ra: 'pil', 'np', 'pt'.

Outputs: videos (`list`): Các video được tạo. audio (`Tensor`): Dạng sóng âm thanh được tạo.

