#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。-->

# LTX-2

  

[LTX-2](https://hf.co/papers/2601.03233) 是一款基于 DiT 的基础模型，旨在通过单一模型生成同步的视频和音频。它整合了现代视频生成的核心组件，提供开放权重，并专注于实用的本地部署。

您可以在 [Lightricks](https://huggingface.co/Lightricks) 组织下找到所有原始的 LTX-Video 检查点。

LTX-2 的原始代码库可以在[此处](https://github.com/Lightricks/LTX-2)找到。

## 两阶段生成

共享的 `LTX2Pipeline` / `LTX2ImageToVideoPipeline` `__call__` 默认值与 LTX-2.5 参考实现一致（`num_inference_steps=30`；当存在 `duration_head` 时，`num_frames` 为可选参数，否则回退到 `121`）。以下示例在 LTX-2.0/2.3 中也使用这些默认值。

推荐用于实现生产级生成质量的流水线，该流水线由两个阶段组成：

- 阶段 1：使用带有无分类器引导（CFG）的扩散采样，在目标分辨率下生成视频。此阶段会生成一个连贯的低噪声视频序列，并遵循文本/图像条件。
- 阶段 2：将阶段 1 的输出上采样 2 倍，并使用蒸馏 LoRA 模型细化细节，以提升保真度和视觉质量。阶段 2 可能会应用较轻的 CFG，以保留阶段 1 的结构，同时增强纹理和清晰度。

文本到视频两阶段流水线的示例用法

```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",
)
```

## 蒸馏检查点生成
使用蒸馏检查点实现的最快两阶段生成流水线。

```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",
)
```

## 条件化流水线生成

您可以使用 `LTX2ConditionPipeline` 在任意潜在索引处指定图像和/或视频条件。例如，我们可以同时指定首帧和末帧条件，以执行首末帧到视频（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",
)
```

您可以同时使用图像和视频条件：

```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",
)
```

由于条件化是通过潜在帧实现的，与图像条件指定的潜在帧相对应的 8 个数据空间帧往往会保持静态。

## 多模态引导

LTX-2.X 流水线支持多模态引导。它由三个项组成，均使用 CFG 风格的更新规则：

1. 无分类器引导（CFG）：标准的 [CFG](https://huggingface.co/papers/2207.12598)，其中扰动（“较弱”）的输出是使用负提示生成的。
2. 时空引导（STG）：[STG](https://huggingface.co/papers/2411.18664) 不再使用通过跳过自注意力操作生成的扰动输出，而是直接替换为注意力值。其思路是，这样做能生成更清晰的视频并提升时空一致性。
3. 模态隔离引导：通过禁用跨模态（音频到视频以及视频到音频）交叉注意力来生成扰动输出，从而偏离该输出。这种引导更具体地适用于 [LTX-2.X](https://huggingface.co/papers/2601.03233) 模型，其理念是这能提升生成音频与视频之间的一致性。

这些参数由 `guidance_scale`、`stg_scale` 和 `modality_scale` 参数控制，并且可以分别为视频和音频单独设置。此外，对于 STG，需要通过 `spatio_temporal_guidance_blocks` 参数指定跳过自注意力的 transformer 块索引。LTX-2.X 流水线还支持 [guidance rescaling](https://huggingface.co/papers/2305.08891)，有助于减少过曝问题，当 guidance 比例设置为较高值时可能会出现该问题。

```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",
)
```

## 提示词增强

LTX-2.X 模型对提示词风格较为敏感。有关如何撰写优质提示词的建议，请参阅[官方提示词指南](https://ltx.io/model/model-blog/prompting-guide-for-ltx-2)。使用提示词增强功能（即根据系统提示词，利用流水线中的文本编码器（默认为[Gemma 3](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized)模型）对提供的提示词进行增强）也可以提升样本质量。要使用提示词增强功能，必须存在可选的`processor`流水线组件。通过设置`enable_prompt_enhancement=True`和`system_prompt`来启用该功能（需主动选择，与 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 复用了与 LTX-2.3 相同的 `LTX2Pipeline`/`LTX2VideoTransformer3DModel`/`AutoencoderKLLTX2Video` 等类，没有为其单独设置 pipeline 类。用户可见的差异在于文本编码器：LTX-2.5 搭配的是 Gemma 4（`gemma4_unified`）检查点，而非 Gemma 3。在对转换后的 LTX-2.5 检查点调用 `from_pretrained` 时（通过 `transformers` 的 `Auto*` 类），该检查点会被自动加载，因此推理时无需额外配置——只需将 `from_pretrained` 指向 LTX-2.5 仓库，而不是 LTX-2.3 仓库即可。

[`Lightricks/LTX-2.5-Diffusers`](https://huggingface.co/Lightricks/LTX-2.5-Diffusers) 同时提供了两个 transformer：`transformer/` 中的**蒸馏** DiT，即 `model_index.json` 所指向的模型；以及 `transformer_full/` 中的完整/SFT DiT，后者需要显式加载（参见 [Full / SFT transformer](#full--sft-transformer)）。该仓库的 `scheduler/` 针对蒸馏检查点进行了配置（`use_dynamic_shifting=False`、`shift_terminal=None`），以便其 sigma 调度按原样使用。[两阶段生成](#two-stage-generation-for-ltx-25) 所需的一切也包含在其中：一个 `latent_upsampler/` 子文件夹，以及位于仓库根目录的第二阶段蒸馏 LoRA `ltx-2.5-22b-distilled-lora-450-bf16.safetensors`。

蒸馏推理由显式的 sigma 调度驱动，而非步数，并且以无引导方式运行（`guidance_scale=1.0`，因此 `negative_prompt` 不会被使用）。如果改为传入 `num_inference_steps`，模型将使用通用的线性调度，从而在不知不觉中降低质量：

```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",
)
```

### LTX-2.5 的两阶段生成

LTX-2.5 支持两种两阶段变体，`DISTILLED_SIGMA_VALUES` / `STAGE_2_DISTILLED_SIGMA_VALUES` 是其参考调度方案：

- **蒸馏检查点，两个阶段** — 默认 `transformer/` 的参考配方，也是下文所示的配方。由于 transformer 已经过蒸馏，因此不涉及阶段 2 的 LoRA；这是使用 LTX-2.5 权重进行的 [蒸馏检查点生成](#distilled-checkpoint-generation)。
- **Full/SFT 阶段 1 + 蒸馏 LoRA 阶段 2** — 如本页顶部所述，采用[两阶段生成](#two-stages-generation)，使用 `transformer_full/` 和随附的 LoRA。有关具体变更，请参见[下文](#stage-2-with-the-distilled-lora)。

阶段 1 以目标分辨率的一半运行，上采样器将其放大一倍，阶段 2 则以完整分辨率进行细化——视频*和*音频均从阶段 1 的潜变量重新播种，噪声尺度为 `noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0]`。由于阶段 1 会将每个维度减半，且最终仍需落在 VAE 的空间网格上，因此高度和宽度必须能被 64 整除。

```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",
)
```

当长度来自 [duration head](#automatic-duration-for-ltx-25) 而非显式的 `num_frames` 时，请让 stage 1 自行决定，并在 stage 2 运行之前从其潜变量（`[B, C, F, H, W]`）中恢复实际长度，而不是进行第二次预测：

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

#### 使用蒸馏 LoRA 的第二阶段

若要改为运行 [Two-stages Generation](#two-stages-generation) —— 第一阶段使用 full/SFT DiT，第二阶段使用蒸馏 LoRA —— 请按照 [Full / SFT transformer](#full--sft-transformer) 中的方式构建 pipeline，并使用该 guidance stack 生成第一阶段的 latents。随后，与 LTX-2.0/2.3 相比有两点不同。LoRA 位于 diffusers 仓库内部，而非与原始权重并列存放；此外，scheduler 的翻转方向相反：LTX-2.5 附带的是 *distilled* scheduler 配置，因此第一阶段是开启 dynamic shifting 的一方，而第二阶段则将其关闭。

```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
)
```

上采样步骤和 stage 2 的调用与上述蒸馏配方保持不变：使用相同的 `sigmas=STAGE_2_DISTILLED_SIGMA_VALUES`、相同的 `noise_scale`，以及 `guidance_scale=1.0`，因为 stage 2 无论如何运行的都是蒸馏模型。

### 卷积与扩散解码

LTX-2.5 提供了两个基于相同潜在空间的视频解码器，因此它们之间的潜在表示可以互换使用：

- `vae/` — 卷积 VAE（[AutoencoderKLLTX2Video](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video)）。它是流水线用于解码的组件，因此上述所有代码片段都已在使用它，并且它是两者中唯一支持分块（`pipe.vae.enable_tiling()`）的组件，这通常正是让高分辨率得以适配的关键。
- `diffusion_decoder/` — [LTX2VideoDiffusionDecoderModel](/docs/diffusers/v0.43.0/zh/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel)。它本身是一个扩散模型，而非流水线组件，因此不作为 `vae` 传入：请以 `output_type="latent"` 运行流水线，并将潜变量传递给 [LTX2VideoDiffusionDecodePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2VideoDiffusionDecodePipeline)。

编码始终通过 `vae/` 进行，因此图像和视频的条件输入不受该选择的影响。

使用扩散解码器进行解码时，有两点会发生变化。`output_type="latent"` 还会跳过声码器，因此音频将以潜在表示的形式返回，需要手动完成后续处理，并且在视频分辨率下，NATTEN 处理器实际上是必需的：

```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",
)
```

要将此功能与[两阶段生成](#two-stage-generation-for-ltx-25)结合使用，请让*第二阶段*返回`output_type="latent"`，然后对其进行解码。

`decoder.enable_tiling()` 的作用是让高分辨率解码保持在内存中，其原理与 `pipe.vae.enable_tiling()` 在卷积 VAE 中的作用相同。解码过程中占用内存最多的部分——最后的上采样阶段和扩散阶段——随后会在重叠的瓦片上运行，并将这些瓦片混合回原图，因此峰值内存由瓦片大小而非视频大小决定。只有当潜在表示超过一个瓦片时，分块处理才会生效，并且可以通过 `tile_sample_min_*` / `tile_sample_stride_*` 参数来调整瓦片和重叠的大小（默认值与参考实现一致）。由于扩散阶段对每个瓦片分别进行去噪，分块解码无法完全复现非分块解码的结果。

在单卡上，解码前也建议将 pipeline 移出显存（在捕获 `pipe.scheduler` 和 vocoder 的 `output_sampling_rate` 之后，执行 `pipe.to("cpu")` 和 `torch.cuda.empty_cache()`），因为解码器需要自身的显存余量。有关注意力后端、分块细节以及解码器的其他行为，请参阅 [LTX2VideoDiffusionDecoderModel](/docs/diffusers/v0.43.0/zh/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel)。

### 完整 / SFT 转换器

`transformer_full/` 未在 `model_index.json` 中引用，因此需要显式加载。此外，它还需要不同的调度器以及真实的 guidance 栈：随附的 `scheduler/` 是为蒸馏检查点配置的，而 guidance 默认值是 LTX-2.0 时代的通用设置，这会导致 LTX-2.5 SFT 运行明显 guidance 不足，且不会触发任何警告。[Multimodal Guidance](#multimodal-guidance) 中的建议在此处同样适用，包括在 block `28` 上启用 STG：

```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,
)
```

在此处省略 `sigmas` —— 完整的 DiT 会从调度器中获取其调度计划。

### LTX-2.5 的提示词增强

**强烈建议对 LTX-2.5 使用提示词增强；请传入 `enable_prompt_enhancement=True` 以启用该功能**（与 Lightricks 参考流水线一致）。与 LTX-2.0/2.3 不同（在后者中，同一个文本编码器检查点同时充当增强器，参见上文 [提示词增强](#prompt-enhancement)），LTX-2.5 的微调文本编码器并非为增强任务而训练。相反，增强功能使用一个独立的、现成的 `google/gemma-4-E2B-it` 检查点。将其加载到流水线的可选 `prompt_enhancer`/`processor` 组件中，然后启用增强——流水线默认使用 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` 以及 Gemma 4 配方（`do_sample=False`、`no_repeat_ngram_size=5`、`max_new_tokens=600`）。如需覆盖默认值，请显式传入 `system_prompt=`：

```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",
)
```

图像到视频生成同样适用，使用 `LTX2ImageToVideoPipeline` 时：以相同方式设置 `pipe.prompt_enhancer`/`pipe.processor`，并传入 `enable_prompt_enhancement=True`（使用 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`，同时基于参考图像和文本提示词进行条件约束）——同样，除非你想覆盖默认值，否则无需设置 `system_prompt=`。

### LTX-2.5 的自动时长

LTX-2.5 检查点附带一个小型的 `duration_head`，它基于与 Transformer 条件相同的文本连接器输出，来预测所描述镜头的时长。当加载的流水线包含该组件时，**`num_frames` 默认会自动预测**——省略该参数，模型将自行决定时长：

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

若要自行设置长度，请显式传入 `num_frames`。整数始终优先于头部：

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

从 LTX-2.0 或 LTX-2.3 检查点加载的 Pipelines 没有 duration head，并且保持之前 121 帧的默认值，因此这对它们没有任何影响。

传入 `min_seconds` / `max_seconds` 以约束预测。原始预测值会被限制在该范围内，然后转换为帧数：

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

预测的帧数会被对齐到 VAE 的因果时间网格（`8k + 1`），因此实际时长会被量化——在 24 fps 下每步约 0.33 秒——并且会随 `frame_rate` 变化，因为模型头部预测的是秒数而非帧数。`min_seconds` 必须严格小于 `max_seconds`。当显式设置 `num_frames` 时，这些边界值将被忽略。

小于一个网格步长的边界可能无法被精确满足：在 24 fps 下，`[1.0s, 1.02s]` 会转换为 `[24, 24]` 帧，而 24 并不满足 `8k + 1`。系统会使用最近的网格点并记录一条警告，因此返回的长度可能会略微超出如此严格的边界范围。

若要检查预测结果而不生成视频，请直接调用 head。它所需的一切都是公开的：

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

将 2.5 检查点转换为 `--full_pipeline` 时，会自动选取头部；也可以单独使用 `--duration_head` 进行转换。2.5 之前的检查点不包含此类权重，转换时会跳过该组件，而不会导致失败。

### LTX-2.5 的运动速度

LTX-2 将每个视频 token 放置在以秒为单位的时间轴上，该时间轴默认由播放速率 `frame_rate` 推导得出。`motion_speed`（默认值为 `1.0`）将两者解耦：时间轴的条件基于 `frame_rate / motion_speed`，而音频长度、[duration head](#automatic-duration-for-ltx-25) 以及返回的视频仍遵循 `frame_rate`。当 `frame_rate=24.0` 且 `motion_speed=0.2` 时，模型被告知动作是以 120 fps 捕获的，而结果以 24 fps 播放，从而实现 5 倍慢动作效果。

基础模型是在约 24/25/30/60 fps 下训练的，因此远离 `1.0` 的速度只有在配合为其训练的适配器（例如 [`Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control`](https://huggingface.co/Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control)，需先在 Hub 上接受其许可证）时才有意义。如果不使用 `motion_speed`，该 LoRA 将作为普通 LoRA 加载，无法提供任何运动控制功能。模型卡片建议的速度为 `1.0`、`0.5`、`0.2`、`0.1`、`0.05` 和 `0.025`，LoRA 强度为 `1.0`。请勿在提示词中包含速度相关的词汇（如“慢动作”、“高帧率”），并在不同速度下复用相同的字幕，因为仅 `motion_speed` 即可驱动该效果。

```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",
    )
```

两个片段均为 121 帧（在 24 fps 下约为 5 秒），且只有运动节奏发生变化。在 [两阶段生成](#two-stage-generation-for-ltx-25) 中，需将相同的 `motion_speed` 传递给 **两个** 阶段。阶段 2 会对视频进行重新去噪，如果它在实时轴上运行，就会抵消慢动作效果。[参考驱动器](https://huggingface.co/Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control/blob/main/distilled_speed_demo.py) 通过包装两个路径共享的阶段对象，实现了相同的效果。

`motion_speed` 也是 LTX-2 / LTX-2.5 模块化块的输入，并且以相同的方式传递给模块化流水线。

### LTX-2.5 模块化

LTX-2.5 也可作为模块化流水线使用。默认 blockset 使用扩散解码器，并在省略 `num_frames` 时预测视频时长。它通过 `guider` 和 `audio_guider` 组件分别对视频和音频应用引导。有关可用的引导参数，请参阅 [LTX2Guidance](/docs/diffusers/v0.43.0/zh/api/modular_diffusers/guiders#diffusers.LTX2Guidance)。默认情况下，模块化流水线会从 [google/gemma-4-E2B-it](https://huggingface.co/google/gemma-4-E2B-it) 仓库下载提示词增强器和处理器。以下是一个 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",
)
```

模块化流水线会根据提供的输入自动切换工作流。例如，如果提供了 `image`，则会使用 I2V 工作流：

```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",
)
```

您可以在每个 blockset 的文档中查看其支持的工作流（例如 [LTX2AutoBlocks](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2AutoBlocks)、[LTX25AutoBlocks](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX25AutoBlocks)）。

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

`LTX2DFRPipeline` 以实际耗时换取细节保真度。每次 `__call__` 都是在 `height` × `width` 分辨率下执行**一次去噪**：它生成视频以及额外的单像素帧**关键帧槽位**，或者对这些槽位中提供的潜变量进行重新去噪。调用方以与其他 LTX 两阶段流水线相同的方式组合各个阶段——先调用本流水线，再调用 [LTX2LatentUpsamplePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2LatentUpsamplePipeline)，然后再次调用本流水线，最后对每个时间轮次调用 [LTX2DFRTemporalRefinePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline)。

一个 slot 需要消耗一整个潜在帧的 token 来生成一个像素帧，从而放宽了该位置的有效时间压缩——因此，周围的视频是基于真正的新帧而非插值帧进行条件化的。Slot 的位置来自与 VAE 时间边界（24 或 32 个像素帧，取对请求填充较少的那个）对齐的分段网格。画布在内部会被填充为整数个分段；`output_type="latent"` 会返回该填充后的网格，以确保位于填充区域的 slot 不会被丢弃。在 VAE 解码之前，请使用 `trim_canvas` 进行裁剪。

这需要配置中设置了 `use_keyframes_abs_pos_embedding` 的 transformer，该配置会用学习到的嵌入来标记单像素帧的潜变量。LTX-2.5 的检查点已包含此配置；对于更旧的版本，该流水线会直接抛出异常，而不是将 token 预算浪费在它无法解析的 token 上。

为额外 token 预留预算：每个 slot 会增加一帧 latent 的 token 量，因此第二阶段运行的序列比等效的两阶段蒸馏流程更长——在 1024x1536 / 121 帧（24 帧分段网格上的 5 个 slot）下，token 数增加 31%（24576 -> 32256）。峰值激活内存随之增长，因此在 DFR 下，原本刚好能容纳普通蒸馏方案的分辨率可能需要 `enable_sequential_cpu_offload`、`vae.enable_tiling()`，或更小的画布。

Composition 对 `keyframes` 和 `keyframe_positions` 使用 `return_dict=True`（`return_dict=False` 会将相同的四个字段作为元组返回）。

下面的完整配方是推荐的起点：1088×1920 的图像转视频，一轮 x2 时间细化，以及在第二阶段应用 x2 空间细节 IC-LoRA。

```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` 和 `width` 是**本次通过**的尺寸，而非最终输出。第一阶段在 1080p 画布的一半分辨率（544×960）下运行；第二阶段在 1088×1920 下运行。每个阶段的尺寸都必须能被 VAE 的空间压缩率整除（在 LTX-2.5 中，单次通过为 32；当第一阶段为 1080p 的一半时为 64）。这就是为什么 1080p 是 **1920×1088**，而 4K 是 **3840×2176**。每次通过都运行固定的蒸馏调度（`sigmas`），因此没有 `num_inference_steps`；由于蒸馏调度是在无引导的情况下训练的，因此也没有 `negative_prompt` 或 `guidance_scale`。随附的音频来自第一阶段——后续阶段仍会运行音频流，以便视频分支拥有跨模态注意力；但波形本身在之后不会进一步细化。

**Spatial detailing.** Load the 2x spatial detailing IC-LoRA under a named adapter **after stage 1** and activate it for stage 2 only (`set_adapters(["detailing"], adapter_weights=[0.5])`). Stage 2 then attends to the stage-1 half-resolution latent as `reference_latents`. Stage 1 and the temporal rounds run with the adapter off. If you load the LoRA before stage 1, `transformer.disable_adapters()` turns it off, and `set_adapters` does **not** turn it back on — call `transformer.enable_adapters()` before stage 2, or load the weights after stage 1 as in the recipe. `reference_downscale_factor` (default `2`) scales the reference tokens' spatial coordinates into the target's coordinate space.

**时间维度精化。** [LTX2DFRTemporalRefinePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline) 执行一轮处理：在时间维度上上采样，在关键帧接缝处进行分块，使用 `LTXEulerAncestralRFScheduler`（`eta=0.5`）进行祖先去噪，通过丢弃后一个分块的引导段进行拼接，并合并携带关键帧的集合。请自行构建该调度器——若使用其他调度器，该轮处理将被拒绝，因为确定性步骤会运行至完成，仅返回更柔和的画布。每轮调用一次该流水线；循环执行以实现 2x / 4x，并传入 `round_index`。一轮处理之后，`keyframe_positions` 无法从原始的 `num_frames` 重新推导，必须显式传递。每个分块会接收到冻结的 stage-1 音频中覆盖其自身播放窗口的切片。`source_seconds` 是 *stage-1* 的时长，在各轮之间保持不变，因此后续轮次必须显式传入该值，而不能使用默认值。

只要播放帧率高于 30，条件帧率就固定为 60，与混流方式无关：RoPE 的时间为 `pixel_frame / fps`，因此 120 fps 的时间基准会使每个 token 的时间跨度相对于训练分布减半，而 48 fps 则会将其拉长。两者都谎称自己是 60，并按播放速率处理解码后的帧。

**第三个空间阶段。**将其组合起来；不存在第四个流水线。仅对 **视频** 进行空间上采样，在 RGB 中重建 carry 关键帧（`decode` → Lanczos ×2 → 通过 [rebuild_epilogue_keyframes()](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.rebuild_epilogue_keyframes) 进行 `encode`；切勿对 epilogue 关键帧进行潜在空间上采样），然后：

```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()
```

两条轴线的拼接方式不同。空间边界两侧均无已知答案，因此这些重叠区域采用梯形权重进行混合。时间瓦片则沿上一轮细化中的关键帧接缝进行切割。

**使用扩散解码器进行解码。** 为了获得最高的细节保真度，请保持使用 `output_type="latent"`，并将（已反归一化、可能经过 `trim_canvas` 处理的）潜变量传递给 [LTX2VideoDiffusionDecodePipeline](/docs/diffusers/v0.43.0/zh/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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L209)

**参数：**

transformer ([LTXVideoTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/ltx_video_transformer3d#diffusers.LTXVideoTransformer3DModel))：用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

vae ([AutoencoderKLLTXVideo](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_ltx_video#diffusers.AutoencoderKLLTXVideo))：一种变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码为图像。

text_encoder (`T5EncoderModel`)：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 变体。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer (`T5TokenizerFast`)：第二个 [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) 类的 Tokenizer。

connectors (`LTX2TextConnectors`)：用于适配文本编码器隐藏状态以服务于视频和音频分支的文本连接器堆栈。

用于文本到视频生成的 Pipeline。

参考：https://github.com/Lightricks/LTX-Video

#### __调用__[[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[int] = 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[str] = ['latents'], max_sequence_length: int = 1024)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L929)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

height (`int`，*可选*，默认值为 `512`)：生成图像的高度（以像素为单位）。为获得最佳效果，默认设置为 480。

width (`int`，*可选*，默认值为 `768`)：生成图像的像素宽度。为获得最佳效果，默认设置为 848。

num_frames (`int`, *可选*) : 要生成的视频帧数。如果未提供，当此流水线包含 `duration_head` 组件时（LTX-2.5 检查点及之后的版本），默认使用自动预测的时长；否则默认为 `121`。传入一个整数可显式设置长度。自动预测的帧数会对齐到 VAE 的因果时间网格，因此实际时长是量化的（在 24 fps 下约为 0.33 秒）。

min_seconds (`float`，*可选*，默认值为 `1.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的下限。如果显式设置了 `num_frames`，则忽略此参数。

max_seconds (`float`，*可选*，默认值为 `20.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的上限。如果显式设置了 `num_frames`，则忽略此参数。必须严格大于 `min_seconds`。

frame_rate (`float`，*可选*，默认值为 `24.0`)：生成视频的帧率（FPS）。

motion_speed (`float`，*可选*，默认值为 `1.0`)：相对于真实时间的运动速度。位置嵌入以 `frame_rate / motion_speed` 为条件，因此小于 1 的值会减慢运动速度，例如 Slow-Motion-Control LoRA 的 5 倍慢动作使用 `0.2`。`frame_rate` 保持为播放速率：音频时长和预测的帧数均遵循该值。

num_inference_steps (`int`，*可选*，默认值为 30)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

sigmas (`List[float]`, *可选*) : 用于去噪过程的自定义 sigmas，适用于其 `set_timesteps` 方法支持 `sigmas` 参数的调度器。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`, *可选*，默认值为 `4.0`) : 在 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导比例。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导比例。较高的引导比例会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。用于视频模态（音频模态有单独的值 `audio_guidance_scale`）。

stg_scale (`float`, *可选*，默认为 `0.0`)：用于 Spatio-Temporal Guidance (STG) 的视频引导尺度，该概念由 [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) 提出。STG 使用类似 CFG 的估计方法，将样本从去噪模型的扰动版本生成的弱样本方向移开。启用 STG 将导致额外的去噪模型前向传播；默认值 `0.0` 表示 STG 处于禁用状态。

modality_scale (`float`, *可选*，默认为 `1.0`) : LTX-2.X 模态隔离引导的视频引导尺度。在此过程中，我们使用类似 CFG 的估计，将样本移离由禁用跨模态（音频到视频和视频到音频）交叉注意力的去噪模型生成的较弱样本。启用模态引导将导致额外的去噪模型前向传播；默认值 `1.0` 表示模态引导已禁用。

guidance_rescale (`float`, *optional*, defaults to 0.0) : Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when using zero terminal SNR. Used for the video modality.

audio_guidance_scale (`float`，*可选*，默认为 `None`)：针对负向提示词的 CFG 音频引导尺度。视频和音频的 CFG 更新规则相同，但可以使用不同的引导尺度值。LTX-2.X 的作者建议 `audio_guidance_scale` 相对于视频的 `guidance_scale` 应更高（例如，对于 LTX-2.3，他们建议视频为 3.0，音频为 7.0）。如果为 `None`，则默认为视频值 `guidance_scale`。

audio_stg_scale (`float`, *可选*，默认为 `None`) : STG 的音频引导尺度。与 CFG 类似，STG 的更新规则在视频和音频方面是相同的。对于 LTX-2.3，建议视频和音频的值均设为 1.0。如果为 `None`，则默认为视频值 `stg_scale`。

audio_modality_scale (`float`，*可选*，默认值为 `None`)：用于 LTX-2.X 模态隔离引导的音频引导尺度。与 CFG 类似，视频和音频的模态引导规则相同。对于 LTX-2.3，建议视频和音频均使用 3.0。如果为 `None`，则默认为视频值 `modality_scale`。

audio_guidance_rescale (`float`，*可选*，默认为 `None`)：用于音频模态的独立 guidance rescale 因子。如果为 `None`，则默认为视频值 `guidance_rescale`。

spatio_temporal_guidance_blocks (`list[int]`，*可选*，默认为 `None`)：应用 STG 的零索引 transformer 块索引。如果使用 STG（即 `stg_scale` 或 `audio_stg_scale` 大于 `0`），则必须提供此参数。对于 LTX-2.0，建议值为 `[29]`；对于 LTX-2.3，建议值为 `[28]`。

noise_scale (`float`，*可选*，默认值为 `0.0`)：每个时间步中随机噪声与去噪潜在表示之间的插值因子。在继续去噪之前，对 `latents` 和 `audio_latents` 应用噪声。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的视频数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

audio_latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作音频生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_prompt_attention_mask (`torch.FloatTensor`, *可选*) : 为负文本嵌入预生成的注意力掩码。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：在解码时间步中，随机噪声与去噪潜在表示之间的插值因子。

use_cross_timestep (`bool` *可选*，默认为 `True`) : 在计算交叉注意力调制参数时，是否使用跨模态（音频是视频的跨模态，反之亦然）sigma。`True` 对应 LTX-2.3/2.5 的行为；`False` 对应旧版 LTX-2.0 的行为。

system_prompt (`str`, *可选*，默认为 `None`) : 用于提示词增强的可选系统提示词。该提示词将由提示词增强器（一个 Gemma 条件生成模型——如果已配置专用的 `prompt_enhancer` 组件，则使用该组件；否则使用主 `text_encoder`）来根据原始 `prompt` 生成增强后的提示词，以作为生成的条件。如果未提供且已配置专用的 `prompt_enhancer`（LTX-2.5），则默认为 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`（来自 `diffusers.pipelines.ltx2.utils`）——参见 `enable_prompt_enhancement`。

enable_prompt_enhancement (`bool`，*可选*，默认为 `False`)：是否运行提示词增强。此为可选功能，与 Lightricks 参考流水线保持一致。当 `True` 且未提供 `system_prompt` 时，如果已配置专用的 `prompt_enhancer`，LTX-2.5 将使用 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`；LTX-2.0/2.3 则要求显式提供 `system_prompt`。

prompt_max_new_tokens (`int`，*可选*，默认为 `None`)：执行提示词增强时生成的新 token 的最大数量。如果未提供，则对于专用的 Gemma 4 `prompt_enhancer`（LTX-2.5）使用 600，对于 Gemma 3 `text_encoder` 回退方案（LTX-2.0/2.3）使用 512。

prompt_enhancement_kwargs (`dict[str, Any]`，*可选*，默认为 `None`)：用于提示词增强器 `.generate` 调用的关键字参数。如果未提供，则始终与执行增强任务的模型相匹配：使用专用 `prompt_enhancer`（LTX-2.5）时为 `do_sample=False, no_repeat_ngram_size=5`（贪心解码），使用 `text_encoder` 回退方案（LTX-2.0/2.3）时为 `do_sample=True, temperature=0.7`。更多详情请参见 https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate。

prompt_enhancement_seed (`int`，*可选*，默认为 `10`)：提示词增强过程中任何随机操作的随机种子。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.ltx.LTX2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`List`，*可选*，默认为 `["latents"]`)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传入。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `1024`)：与 `prompt` 一起使用的最大序列长度。

**返回：** `~pipelines.ltx.LTX2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `~pipelines.ltx.LTX2PipelineOutput`，否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L367)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2.py#L574)

通过提示词增强器（一个 Gemma 条件生成模型）基于给定的 `prompt` 和系统提示词生成新的提示词，从而增强该提示词。当提供 `image` 时，增强器还会以该参考帧作为条件（I2V / 关键帧式增强）。如果已配置专用的 `prompt_enhancer` 组件（例如 LTX-2.5，其文本编码器未针对增强任务进行训练），则使用该组件；否则回退到主 `text_encoder`（LTX-2.0/2.3，其自身兼作增强器）。

消息模板、解码 kwargs、响应清理以及图像长边预处理与 `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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L229)

用于图像到视频生成的 Pipeline。

参考：https://github.com/Lightricks/LTX-Video

TODO

#### __调用__[[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[str] = ['latents'], max_sequence_length: int = 1024)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L983)

**参数：**

image (`PipelineImageInput`)：用于条件生成的输入图像。必须是一张图像、一个图像列表或一个 `torch.Tensor`。

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

height (`int`，*可选*，默认值为 `512`)：生成图像的高度（以像素为单位）。为获得最佳效果，默认设置为 480。

width (`int`，*可选*，默认值为 `768`)：生成图像的像素宽度。为获得最佳效果，默认设置为 848。

num_frames (`int`, *可选*) : 要生成的视频帧数。如果未提供，当此流水线包含 `duration_head` 组件时（LTX-2.5 检查点及之后的版本），默认使用自动预测的时长；否则默认为 `121`。传入一个整数可显式设置长度。自动预测的帧数会对齐到 VAE 的因果时间网格，因此实际时长是量化的（在 24 fps 下约为 0.33 秒）。

min_seconds (`float`，*可选*，默认值为 `1.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的下限。如果显式设置了 `num_frames`，则忽略此参数。

max_seconds (`float`，*可选*，默认值为 `20.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的上限。如果显式设置了 `num_frames`，则忽略此参数。必须严格大于 `min_seconds`。

frame_rate (`float`，*可选*，默认值为 `24.0`)：生成视频的帧率（FPS）。

motion_speed (`float`，*可选*，默认值为 `1.0`)：相对于真实时间的运动速度。位置嵌入以 `frame_rate / motion_speed` 为条件，因此小于 1 的值会减慢运动速度，例如 Slow-Motion-Control LoRA 的 5 倍慢动作使用 `0.2`。`frame_rate` 保持为播放速率：音频时长和预测的帧数均遵循该值。

num_inference_steps (`int`，*可选*，默认值为 30)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

sigmas (`List[float]`, *可选*) : 用于去噪过程的自定义 sigmas，适用于其 `set_timesteps` 方法支持 `sigmas` 参数的调度器。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。

timesteps (`List[int]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `timesteps` 参数的调度器的去噪过程的自定义时间步。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`, *可选*，默认值为 `4.0`) : 在 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导比例。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导比例。较高的引导比例会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。用于视频模态（音频模态有单独的值 `audio_guidance_scale`）。

stg_scale (`float`, *可选*，默认为 `0.0`)：用于 Spatio-Temporal Guidance (STG) 的视频引导尺度，该概念由 [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) 提出。STG 使用类似 CFG 的估计方法，将样本从去噪模型的扰动版本生成的弱样本方向移开。启用 STG 将导致额外的去噪模型前向传播；默认值 `0.0` 表示 STG 处于禁用状态。

modality_scale (`float`, *可选*，默认为 `1.0`) : LTX-2.X 模态隔离引导的视频引导尺度。在此过程中，我们使用类似 CFG 的估计，将样本移离由禁用跨模态（音频到视频和视频到音频）交叉注意力的去噪模型生成的较弱样本。启用模态引导将导致额外的去噪模型前向传播；默认值 `1.0` 表示模态引导已禁用。

guidance_rescale (`float`, *optional*, defaults to 0.0) : Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when using zero terminal SNR. Used for the video modality.

audio_guidance_scale (`float`，*可选*，默认为 `None`)：针对负向提示词的 CFG 音频引导尺度。视频和音频的 CFG 更新规则相同，但可以使用不同的引导尺度值。LTX-2.X 的作者建议 `audio_guidance_scale` 相对于视频的 `guidance_scale` 应更高（例如，对于 LTX-2.3，他们建议视频为 3.0，音频为 7.0）。如果为 `None`，则默认为视频值 `guidance_scale`。

audio_stg_scale (`float`, *可选*，默认为 `None`) : STG 的音频引导尺度。与 CFG 类似，STG 的更新规则在视频和音频方面是相同的。对于 LTX-2.3，建议视频和音频的值均设为 1.0。如果为 `None`，则默认为视频值 `stg_scale`。

audio_modality_scale (`float`，*可选*，默认值为 `None`)：用于 LTX-2.X 模态隔离引导的音频引导尺度。与 CFG 类似，视频和音频的模态引导规则相同。对于 LTX-2.3，建议视频和音频均使用 3.0。如果为 `None`，则默认为视频值 `modality_scale`。

audio_guidance_rescale (`float`，*可选*，默认为 `None`)：用于音频模态的独立 guidance rescale 因子。如果为 `None`，则默认为视频值 `guidance_rescale`。

spatio_temporal_guidance_blocks (`list[int]`，*可选*，默认为 `None`)：应用 STG 的零索引 transformer 块索引。如果使用 STG（即 `stg_scale` 或 `audio_stg_scale` 大于 `0`），则必须提供此参数。对于 LTX-2.0，建议值为 `[29]`；对于 LTX-2.3，建议值为 `[28]`。

noise_scale (`float`，*可选*，默认值为 `0.0`)：每个时间步中随机噪声与去噪潜在表示之间的插值因子。在继续去噪之前，对 `latents` 和 `audio_latents` 应用噪声。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的视频数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

audio_latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作音频生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_prompt_attention_mask (`torch.FloatTensor`, *可选*) : 为负文本嵌入预生成的注意力掩码。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：在解码时间步中，随机噪声与去噪潜在表示之间的插值因子。

use_cross_timestep (`bool` *可选*，默认为 `True`) : 在计算交叉注意力调制参数时，是否使用跨模态（音频是视频的跨模态，反之亦然）sigma。`True` 对应 LTX-2.3/2.5 的行为；`False` 对应旧版 LTX-2.0 的行为。

system_prompt (`str`, *可选*，默认为 `None`) : 用于提示词增强的可选系统提示词。该提示词将由提示词增强器（一个 Gemma 条件生成模型——如果配置了专用的 `prompt_enhancer` 组件则使用该组件，否则使用主 `text_encoder`）来根据原始 `prompt` 和第一张 `image` 生成增强后的提示词，以作为生成的条件。如果未提供且已配置专用的 `prompt_enhancer`（LTX-2.5），则默认为 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`（来自 `diffusers.pipelines.ltx2.utils`）——参见 `enable_prompt_enhancement`。

enable_prompt_enhancement (`bool`，*可选*，默认为 `False`)：是否运行提示词增强。此为可选功能，与 Lightricks 参考流水线保持一致。当 `True` 且未提供 `system_prompt` 时，如果已配置专用的 `prompt_enhancer`，LTX-2.5 将使用 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`；LTX-2.0/2.3 则要求显式提供 `system_prompt`。

prompt_max_new_tokens (`int`，*可选*，默认为 `None`)：执行提示词增强时生成的新 token 的最大数量。如果未提供，则对于专用的 Gemma 4 `prompt_enhancer`（LTX-2.5）使用 600，对于 Gemma 3 `text_encoder` 回退方案（LTX-2.0/2.3）使用 512。

prompt_enhancement_kwargs (`dict[str, Any]`，*可选*，默认为 `None`)：用于提示词增强器 `.generate` 调用的关键字参数。如果未提供，则始终与执行增强任务的模型相匹配：使用专用的 `prompt_enhancer`（LTX-2.5）时为 `do_sample=False, no_repeat_ngram_size=3`（贪心解码），使用 `text_encoder` 回退方案（LTX-2.0/2.3）时为 `do_sample=True, temperature=0.7`。更多详情请参阅 https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate。

prompt_enhancement_seed (`int`，*可选*，默认为 `10`)：提示词增强过程中任何随机操作的随机种子。

image_crf (`int`, *可选*，默认为 `None`) : 在 VAE 编码之前，用于对条件 `image` 进行重新压缩的 H.264 CRF 值，以匹配模型训练时所使用的压缩设置。`None` 表示“使用模型默认值”（LTX-2.3 及之前版本为 33，LTX-2.5 为 18）。传入 `0` 可跳过重新压缩。执行重新压缩时，需要传入 `PIL.Image.Image`。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.ltx.LTX2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`List`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `1024`)：与 `prompt` 一起使用的最大序列长度。

**返回：** `~pipelines.ltx.LTX2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `~pipelines.ltx.LTX2PipelineOutput`，否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L372)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py#L580)

通过提示词增强器（一个 Gemma 条件生成模型）基于给定的 `prompt` 和系统提示词生成新的提示词，从而增强该提示词。当提供 `image` 时，增强器还会以该参考帧作为条件（I2V / 关键帧式增强）。如果已配置专用的 `prompt_enhancer` 组件（例如 LTX-2.5，其文本编码器未针对增强任务进行训练），则使用该组件；否则回退到主 `text_encoder`（LTX-2.0/2.3，其自身兼作增强器）。

消息模板、解码 kwargs、响应清理以及图像长边预处理与 `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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L266)

用于视频生成的 Pipeline，允许在视频的任意位置插入图像条件。

参考：https://github.com/Lightricks/LTX-Video

TODO

#### __调用__[[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[str] = ['latents'], max_sequence_length: int = 1024)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L1348)

**参数：**

conditions (`List[LTXVideoCondition], *optional*`) : 用于视频生成的帧条件项列表。

prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须改为传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

height (`int`，*可选*，默认值为 `512`)：生成图像的高度（以像素为单位）。为获得最佳效果，默认设置为 480。

width (`int`，*可选*，默认值为 `768`)：生成图像的像素宽度。为获得最佳效果，默认设置为 848。

num_frames (`int`, *可选*) : 要生成的视频帧数。如果未提供，当此流水线包含 `duration_head` 组件时（LTX-2.5 检查点及之后的版本），默认使用自动预测的时长；否则默认为 `121`。传入一个整数可显式设置长度。自动预测的帧数会对齐到 VAE 的因果时间网格，因此实际时长是量化的（在 24 fps 下约为 0.33 秒）。

min_seconds (`float`，*可选*，默认值为 `1.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的下限。如果显式设置了 `num_frames`，则忽略此参数。

max_seconds (`float`，*可选*，默认值为 `20.0`)：当省略 `num_frames` 且存在 `duration_head` 时，自动预测时长的上限。如果显式设置了 `num_frames`，则忽略此参数。必须严格大于 `min_seconds`。

frame_rate (`float`，*可选*，默认值为 `24.0`)：生成视频的帧率（FPS）。

motion_speed (`float`，*可选*，默认值为 `1.0`)：相对于真实时间的运动速度。位置嵌入以 `frame_rate / motion_speed` 为条件，因此小于 1 的值会减慢运动速度，例如 Slow-Motion-Control LoRA 的 5 倍慢动作使用 `0.2`。`frame_rate` 保持为播放速率：音频时长和预测的帧数均遵循该值。

num_inference_steps (`int`，*可选*，默认值为 30)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

sigmas (`List[float]`, *可选*) : 用于去噪过程的自定义 sigmas，适用于其 `set_timesteps` 方法支持 `sigmas` 参数的调度器。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。

timesteps (`List[int]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `timesteps` 参数的调度器的去噪过程的自定义时间步。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`, *可选*，默认值为 `4.0`) : 在 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导比例。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导比例。较高的引导比例会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。用于视频模态（音频模态有单独的值 `audio_guidance_scale`）。

stg_scale (`float`, *可选*，默认为 `0.0`)：用于 Spatio-Temporal Guidance (STG) 的视频引导尺度，该概念由 [Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) 提出。STG 使用类似 CFG 的估计方法，将样本从去噪模型的扰动版本生成的弱样本方向移开。启用 STG 将导致额外的去噪模型前向传播；默认值 `0.0` 表示 STG 处于禁用状态。

modality_scale (`float`, *可选*，默认为 `1.0`) : LTX-2.X 模态隔离引导的视频引导尺度。在此过程中，我们使用类似 CFG 的估计，将样本移离由禁用跨模态（音频到视频和视频到音频）交叉注意力的去噪模型生成的较弱样本。启用模态引导将导致额外的去噪模型前向传播；默认值 `1.0` 表示模态引导已禁用。

guidance_rescale (`float`, *optional*, defaults to 0.0) : Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when using zero terminal SNR. Used for the video modality.

audio_guidance_scale (`float`，*可选*，默认为 `None`)：针对负向提示词的 CFG 音频引导尺度。视频和音频的 CFG 更新规则相同，但可以使用不同的引导尺度值。LTX-2.X 的作者建议 `audio_guidance_scale` 相对于视频的 `guidance_scale` 应更高（例如，对于 LTX-2.3，他们建议视频为 3.0，音频为 7.0）。如果为 `None`，则默认为视频值 `guidance_scale`。

audio_stg_scale (`float`, *可选*，默认为 `None`) : STG 的音频引导尺度。与 CFG 类似，STG 的更新规则在视频和音频方面是相同的。对于 LTX-2.3，建议视频和音频的值均设为 1.0。如果为 `None`，则默认为视频值 `stg_scale`。

audio_modality_scale (`float`，*可选*，默认值为 `None`)：用于 LTX-2.X 模态隔离引导的音频引导尺度。与 CFG 类似，视频和音频的模态引导规则相同。对于 LTX-2.3，建议视频和音频均使用 3.0。如果为 `None`，则默认为视频值 `modality_scale`。

audio_guidance_rescale (`float`，*可选*，默认为 `None`)：用于音频模态的独立 guidance rescale 因子。如果为 `None`，则默认为视频值 `guidance_rescale`。

spatio_temporal_guidance_blocks (`list[int]`，*可选*，默认为 `None`)：应用 STG 的零索引 transformer 块索引。如果使用 STG（即 `stg_scale` 或 `audio_stg_scale` 大于 `0`），则必须提供此参数。对于 LTX-2.0，建议值为 `[29]`；对于 LTX-2.3，建议值为 `[28]`。

noise_scale (`float`, *可选*，默认为 `None`)：每个时间步中随机噪声与去噪潜在表示之间的插值因子。在继续去噪之前，对 `latents` 和 `audio_latents` 施加噪声。如果未设置，将从 sigma 调度中推断得出。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的视频数量。

generator (`torch.Generator` 或 `List[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

audio_latents (`torch.Tensor`, *可选*) : 预生成的噪声潜变量，从高斯分布中采样得到，用作音频生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。对于 PixArt-Sigma，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_prompt_attention_mask (`torch.FloatTensor`, *可选*) : 为负文本嵌入预生成的注意力掩码。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：在解码时间步中，随机噪声与去噪潜在表示之间的插值因子。

use_cross_timestep (`bool` *可选*，默认为 `True`) : 在计算交叉注意力调制参数时，是否使用跨模态（音频是视频的跨模态，反之亦然）sigma。`True` 对应 LTX-2.3/2.5 的行为；`False` 对应旧版 LTX-2.0 的行为。

system_prompt (`str`, *可选*，默认为 `None`) : 用于提示词增强的可选系统提示词。该提示词将由提示词增强器（一个 Gemma 条件生成模型——如果已配置专用的 `prompt_enhancer` 组件，则使用该组件；否则使用主 `text_encoder`）来根据原始 `prompt`（以及可用的条件图像）生成增强后的提示词，以控制生成过程。如果未提供且已配置专用的 `prompt_enhancer`（LTX-2.5），则在存在条件图像时默认为 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`，否则为 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`——参见 `enable_prompt_enhancement`。

enable_prompt_enhancement (`bool`，*可选*，默认为 `False`)：是否运行提示词增强。此为可选功能，与 Lightricks 参考流水线保持一致。当 `True` 且未提供 `system_prompt` 时，LTX-2.5 会根据是否存在条件图像，选择 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT` 或 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`。

prompt_max_new_tokens (`int`，*可选*，默认为 `None`)：执行提示词增强时生成的新 token 的最大数量。如果未提供，则对于专用的 Gemma 4 `prompt_enhancer`（LTX-2.5）使用 600，对于 Gemma 3 `text_encoder` 回退方案（LTX-2.0/2.3）使用 512。

prompt_enhancement_kwargs (`dict[str, Any]`，*可选*，默认为 `None`)：用于提示词增强器 `.generate` 调用的关键字参数。如果未提供，则始终与执行增强任务的模型相匹配：使用专用 `prompt_enhancer`（LTX-2.5）时为 `do_sample=False, no_repeat_ngram_size=5`（贪心解码），使用 `text_encoder` 回退方案（LTX-2.0/2.3）时为 `do_sample=True, temperature=0.7`。更多详情请参见 https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate。

prompt_enhancement_seed (`int`，*可选*，默认为 `10`)：提示词增强过程中任何随机操作的随机种子。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.ltx.LTX2PipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`List`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认为 `1024`)：与 `prompt` 一起使用的最大序列长度。

**返回：** `~pipelines.ltx.LTX2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `~pipelines.ltx.LTX2PipelineOutput`，否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```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[torch.Tensor], condition_strengths: list[float], condition_indices: list[int], latent_height: int, latent_width: int)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L964)

**参数：**

latents (`torch.Tensor`) : 初始打包（分块化）的潜变量，形状为 [batch_size, patch_seq_len, hidden_dim]。

conditioning_mask (`torch.Tensor`) : 初始打包（分块化）条件掩码，形状为 [batch_size, patch_seq_len, 1]，取值范围为 [0, 1]，其中 0 表示将完全使用去噪模型的输出，1 表示将完全使用条件。

**返回：** `Tuple[torch.Tensor, torch.Tensor, torch.Tensor]`

返回一个包含三个张量的元组，其中：
1. 应用了首帧条件的打包视频潜在表示。
2. 应用了首帧强度的打包条件掩码。
3. 位于首帧位置的干净条件潜在变量（其余位置为零）。

通过覆盖第一帧位置处的 token，应用第一帧视觉条件。

此处仅应用 `latent_idx == 0` 的条件（与参考实现中的 `VideoConditionByLatentIndex` 保持一致）。位于非零潜在索引处的条件会通过 `prepare_keyframe_extras` 作为独立的关键帧 token 追加（与 `VideoConditionByKeyframeIndex` 保持一致），并在此处被跳过。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L419)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L627)

通过提示词增强器（一个 Gemma 条件生成模型）基于给定的 `prompt` 和系统提示词生成新的提示词，从而增强该提示词。当提供 `image` 时，增强器还会以该参考帧作为条件（I2V / 关键帧式增强）。如果已配置专用的 `prompt_enhancer` 组件（例如 LTX-2.5，其文本编码器未针对增强任务进行训练），则使用该组件；否则回退到主 `text_encoder`（LTX-2.0/2.3，其自身兼作增强器）。

消息模板、解码 kwargs、响应清理以及图像长边预处理与 `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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L1071)

准备带噪声的视频潜变量，并应用帧条件。

首帧条件（`latent_idx == 0`）通过覆盖首帧位置上的 token 来应用（`VideoConditionByLatentIndex` 语义）。非首帧条件（`latent_idx > 0`）则以逐 token 的 `conditioning_mask = strength` 拼接到主 latent 序列上（`VideoConditionByKeyframeIndex` 语义）——随后，去噪循环中现有的时间步公式 `t * (1 - conditioning_mask)` 和后处理混合 `denoised * (1 - conditioning_mask) + clean * conditioning_mask` 将驱动这些条件在各步骤中生效。

返回一个 4 元组：
- `latents`：打包后的含噪潜变量（基础 token 与任意关键帧 token 在序列维度上拼接而成）。
- `conditioning_mask`：打包的条件掩码，取值范围为 `[0, 1]` —— 首帧位置为 `1`，关键帧位置为 `strength`，其余位置为 `0`。
- `clean_latents`：在条件位置处的干净条件值（其他位置为零）；形状与 `latents` 相同。
- `keyframe_coords`：要附加到 `video_coords` 的位置坐标，形状为 `[B, 3, num_keyframe_patches, 2]`；若不存在非首帧条件，则为 `None`。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L846)

**参数：**

conditions (`LTX2VideoCondition` 或 `List[LTX2VideoCondition]`，*可选*，默认为 `None`)：图像/视频条件实例的列表。

height (`int`，*可选*，默认为 `512`)：期望的像素高度。

width (`int`，*可选*，默认为 `768`)：期望的像素宽度。

num_frames (`int`，*可选*，默认值为 `121`)：生成视频所需的帧数。

device (`torch.device`，*可选*，默认为 `None`)：用于放置预处理后的图像/视频张量的设备。

**返回：** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

返回一个由 4 个列表组成的元组，每个列表的长度均为 `len(conditions)`，具体如下：
1. 第一个列表是一个预处理后的视频张量列表，其形状为 [batch_size=1, num_channels, num_frames, height, width]。
2. 第二个列表是条件强度列表。
3. 第三个列表是每个条件对应的潜在空间索引列表。
4. 第四个列表是每个条件下（经过裁剪的）像素空间帧数。这对于关键帧坐标语义是必需的（单像素帧的关键帧具有被钳制的时域范围）。

将条件图像/视频预处理为 torch 张量。

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py#L829)

**参数：**

start_frame (int)：序列中第一帧的目标帧编号。

sequence_num_frames (int)：序列中的帧数。

target_num_frames (int)：生成视频的目标帧数。

**返回值：** `int`

更新后的序列长度

将条件序列裁剪至允许的帧数。

## 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L122)

**参数：**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的视频潜变量进行去噪的调度器。

vae ([AutoencoderKLLTX2Video](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video))：用于将视频编码和解码为潜在表示的变分自编码器（VAE）模型。

audio_vae ([AutoencoderKLLTX2Audio](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_audio_ltx_2#diffusers.AutoencoderKLLTX2Audio))：用于编码和解码音频频谱图的音频 VAE。

text_encoder （`Gemma3ForConditionalGeneration` 或 `Gemma4UnifiedForConditionalGeneration`）：文本编码器模型。

tokenizer (`GemmaTokenizer` 或 `GemmaTokenizerFast`)：用于文本编码器的分词器。

connectors (`LTX2TextConnectors`)：用于适配文本编码器隐藏状态以服务于视频和音频分支的文本连接器堆栈。

transformer ([LTX2VideoTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/ltx2_video_transformer3d#diffusers.LTX2VideoTransformer3DModel))：用于对编码后的视频潜变量进行去噪的条件 Transformer 架构。

vocoder (`LTX2Vocoder` 或 `LTX2VocoderWithBWE`)：用于将梅尔频谱图转换为音频波形的声码器。

processor (`ProcessorMixin`，*可选*)：用于提示词增强聊天模板的处理器。

prompt_enhancer (`Gemma4ForConditionalGeneration`，*可选*)：专用的提示词增强模型（LTX-2.5）。

duration_head (`LTX2DurationHead`，*可选*)：当未提供 `num_frames` 时，根据提示词嵌入预测 `num_frames`。

使用 LTX-2.5 执行一次 Diffusion Fidelity Rendering (DFR) 去噪通道的流程。

一次 pass 会生成视频 *以及* 额外的单像素帧关键帧槽位，或者对这些槽位中播种的给定潜变量进行重新去噪。调用方组合各个阶段：先以半分辨率运行此流水线，再通过 [LTX2LatentUpsamplePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2LatentUpsamplePipeline) 进行空间上采样，然后使用上采样后的槽位和 IC-LoRA 参考再次以全分辨率运行此流水线，最后对每个时间细化轮次调用 [LTX2DFRTemporalRefinePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline)。有关 1080p 配方，请参阅 LTX-2 文档。

槽位位置来自与 VAE 时间边界对齐的片段网格（`resolve_canvas`）。画布会被填充至整数个片段；`output_type="latent"` 会返回该填充后的网格，以确保位于填充区域的槽位不会被丢弃。在 VAE 解码之前，请使用 `trim_canvas` 进行裁剪。

当 `generate_slots=True` 时，需要配置了 `use_keyframes_abs_pos_embedding` 的 transformer（LTX-2.5 及更高版本）。

参考：https://github.com/Lightricks/LTX-2

#### __调用__[[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[float] = [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[str] = ['latents'], max_sequence_length: int = 1024)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1522)

**参数：**

prompt (`str` 或 `List[str]`，*可选*)：用于引导视频生成的提示词或提示词列表。如果未定义，则必须传入 `prompt_embeds`。

conditions (`LTX2VideoCondition` 或 `List[LTX2VideoCondition]`，*可选*)：帧级图像或视频条件。`index` 是本次传递中 `num_frames` 上的 *latent* 索引。

height (`int`，*可选*，默认为 `704`)：**此通道**的像素高度，而非最终合成输出的高度。

width (`int`，*可选*，默认值为 `1216`)：此通道的像素宽度。

num_frames (`int`, *可选*) : 此 pass 的像素帧数，位于内部画布填充之前。如果未提供，`duration_head` 将根据提示词预测时长。必须满足 `(num_frames - 1) % 8 == 0`。

frame_rate (`float`，*可选*，默认值为 `24.0`)：此 pass 的播放帧率。当该值大于 30 时，RoPE 时间会固定为 60。

min_seconds (`float`, *可选*，默认为 `1.0`) : 当省略 `num_frames` 时，自动预测时长的下限。

max_seconds (`float`, *可选*，默认为 `20.0`) : 当省略 `num_frames` 时，自动预测时长的上限。

latents (`torch.Tensor`, *可选*) : 用于重新去噪（阶段 2 / 尾声）的原始 `(batch_size, channels, frames, height, width)` 视频潜变量。

audio_latents (`torch.Tensor`, *可选*) : 原始未打包的 `(batch_size, channels, length, mel_bins)` 音频潜变量。阶段 2 仍会执行联合音频处理；合成配方所附带的波形来自阶段 1，由调用方保留。

keyframes_latents (`torch.Tensor`, *可选*) : 原始的 `(batch_size, channels, num_slots, height, width)` 槽位初始值，在 `generate_slots=True` 时使用。

keyframe_positions (`list[int]`, *可选*) : 生成槽位的像素帧索引。默认值为 `resolve_canvas(num_frames)`。

reference_latents (`torch.Tensor`, *可选*) : 原始 IC-LoRA 参考视频（通常为第一阶段的帧）。

reference_downscale_factor (`int`，*可选*，默认为 `2`)：当前通道与参考分辨率之间的比例，用于缩放参考 token 坐标。

guidance_keyframe_latents (`torch.Tensor`, *可选*) : 原始固定内存引导关键帧 `(batch_size, channels, K, height, width)` — 尾声路径。非生成槽位。

guidance_keyframe_positions (`list[int]`，*可选*)：`guidance_keyframe_latents` 的像素帧索引。

guidance_keyframe_strength (`float`，*可选*，默认为 `1.0`)：用于固定引导关键帧的条件强度。

generate_slots (`bool`，*可选*，默认为 `True`)：追加生成的关键帧槽位 token。尾声部分会将其设置为 `False`，并固定 `guidance_keyframe_latents`。

sigmas (`list[float]`, *可选*) : 此步骤的噪声调度，不包含末尾的 `0.0`。

noise_scale (`float`, *可选*) : 非条件 token 的起始噪声水平。默认值为 `sigmas[0]`。

freeze_audio (`bool`，*可选*，默认为 `False`)：在 sigma 0 处保持音频（尾声 / 跟随冻结的 stage-1 波形时）。

video_tiles (`list[LTX2DFREpilogueTile]`, *optional*) : 来自 `epilogue_tiles()` 的 Epilogue 分块，因此即使分辨率过大而无法在单次前向传播中处理，仍可以逐步处理单个画布：每一步针对每个 tile 运行一次 transformer，并融合预测结果。该配置会针对本次前向传播自身的 RoPE 坐标解析为 token 计划，这就是为什么传递的是 layout 而非 plan——这些坐标只有在 [prepare_latents()](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents) 运行之后才会存在。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的视频数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于确保可复现性的随机数生成器。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：解码时的噪声缩放。

use_cross_timestep (`bool`，*可选*，默认为 `True`)：是否使用跨模态 sigma 进行交叉注意力调制。LTX-2.3+ 版本为 `True`。

system_prompt (`str`, *可选*) : 用于提示词增强的可选系统提示词。参见 `enable_prompt_enhancement`。

enable_prompt_enhancement (`bool`，*可选*，默认为 `False`)：是否运行提示词增强。

prompt_max_new_tokens (`int`, *可选*) : 执行提示增强时生成的新 token 的最大数量。

prompt_enhancement_kwargs (`dict[str, Any]`，*可选*)：用于提示词增强器 `.generate` 调用的关键字参数。

prompt_enhancement_seed (`int`，*可选*，默认为 `10`)：提示词增强过程中任何随机操作的随机种子。

output_type (`str`，*可选*，默认为 `"pil"`)：输出格式。可选择 `"pil"`、`"np"`、`"pt"` 或 `"latent"`。Latent 输出为未裁剪的画布。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) 或普通的 `(frames, audio, keyframes, keyframe_positions)` 元组。

attention_kwargs (`dict`，*可选*)：传递给注意力处理器的额外 kwargs。

callback_on_step_end (`Callable`，*可选*)：在每个去噪步骤结束时调用的函数。

callback_on_step_end_tensor_inputs (`List`，*可选*，默认为 `["latents"]`)：回调函数的张量输入。

max_sequence_length (`int`，*可选*，默认为 `1024`)：文本提示词的最大序列长度。

**返回：** [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput)，否则返回 `(video, audio, keyframes, keyframe_positions)` 的 `tuple`。

调用生成 pipeline 时调用的函数。

在 `height` × `width` 分辨率下执行一次去噪。在调用方组合各阶段：先以半分辨率运行本流水线，然后进行空间上采样，再次运行本流水线并传入 `latents` / `keyframes_latents` / `reference_latents`，最后对每个时间轮次使用 [LTX2DFRTemporalRefinePipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRTemporalRefinePipeline)。

示例：
```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",
... )
```

#### 去噪[[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[float], 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1225)

**参数：**

sigmas (`list[float]`) : 本次迭代的噪声调度，不包含末尾的 `0.0`。

freeze_audio (`bool`，*可选*，默认为 `False`)：在仍然执行音频到视频的交叉注意力机制的同时，保持 `audio_latents` 处于干净状态（时间步/σ 为 0，不执行音频 Euler 步）。当 `audio_latents` 为 `None` 时，此参数将被忽略。

video_tile_plan (`list`, *可选*) : 来自 `video_tile_plan`[`~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan`] 的每个图块的 token 计划。提供该参数时，每个步骤会对每个图块各运行一次 transformer，并对预测结果进行融合，因此采样器仍然对单个完整画布进行步进，且各图块在每个步骤的重叠区域保持一致。

generator (`torch.Generator`, *可选*) : 转发至 `LTXEulerAncestralRFScheduler.step()`。时间块会传入每个块的种子，以确保祖先采样不会共享随机数流，也不会消耗下一个块初始加噪所读取的状态。蒸馏版 Euler 不会读取该参数。

step_offset (`int`) : 该 pass 的第一个步骤在整个 pipeline 调度中的索引，用于 `callback_on_step_end` 和共享进度条。

对 `sigmas` 执行一次 DFR 去噪，并返回 `(latents, audio_latents)`，两者均保持打包状态。

蒸馏后的调度器在不使用无分类器引导的情况下运行，因此每个步骤只需调用一次 Transformer。由于视频分支需要跨模态注意力，即使其生成的音频会被丢弃，每次迭代也会同时运行两个流。`freeze_audio=True` 将音频流保持在 sigma 0（不执行 Euler 步），以便视频仍能对其进行跨模态注意力——时间细化瓦片和尾声部分利用此机制来跟随第一阶段语音，而无需每个瓦片重新去噪不同的音频实现。

在 x0 条件混合之后，速度为 `(latents - denoised) / sigma`，因此 RF 步 `x0 = x - σ v` 可以恢复混合后的 `denoised`。阶段 1 / 2 / 尾声部分保留 [FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)，并直接采用该 Euler 步。时间细化则换用 `LTXEulerAncestralRFScheduler`（`eta=0.5`）；该步骤会对每个 token 重新加噪，因此之后需要再次应用条件混合，否则强度为 0.95 的接缝锚点会退化。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1189)

按像素帧定位，对帧条件进行预处理和 VAE 编码。

每个条件返回 `(pixel_frame_index, latent, strength, num_pixel_frames)`，可直接用于 [prepare_latents()](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents) 的 `condition_latents`。编码与放置保持分离，因为时间细化轮次会按 `2 ** round` 缩放条件的位置，并按 tile 重新定位，不应为了这样做而对同一静态帧在每个 tile 中重复编码。

返回的索引位于 `num_frames` 自身的像素网格上；将其映射到细化后的画布上由调用方负责。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L529)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为 `prompt_embeds` 预生成的注意力掩码。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

DFR 运行的是蒸馏后的 sigma 调度，该调度经过训练，可在不使用无分类器引导的情况下使用，因此这里没有负向分支。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L389)

通过提示词增强器（一个 Gemma 条件生成模型）基于给定的 `prompt` 和系统提示词生成新的提示词，从而增强该提示词。当提供 `image` 时，增强器还会以该参考帧作为条件（I2V / 关键帧式增强）。如果已配置专用的 `prompt_enhancer` 组件（例如 LTX-2.5，其文本编码器未针对增强任务进行训练），则使用该组件；否则回退到主 `text_encoder`（LTX-2.0/2.3，其自身兼作增强器）。

消息模板、解码 kwargs、响应清理以及图像长边预处理与 `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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L886)

**参数：**

conditions (`list[LTX2VideoCondition]`，*可选*)：帧级图像/视频条件，通过潜在索引进行定位。

condition_latents (`list[tuple[int, torch.Tensor, float, int]]`, *可选*) : `conditions` 的已编码替代项，格式为 `(pixel_frame_index, latent, strength, num_pixel_frames)`。此处使用像素索引而非潜在索引，因为时间细化轮次会将条件的位置乘以 `2 ** round`，而结果通常不会恰好落在潜在边界上——只有追加的关键帧标记可以位于该处，且其位置是按像素确定的。`pixel_frame_index == 0` 仍然表示“替换第一帧”。

keyframe_latents (`list[tuple[int, torch.Tensor, float]]`, *可选*) : 已编码的关键帧引导，格式为 `(pixel_frame_index, latent, strength)`，其中 `latent` 的形状为 `(batch_size, num_channels_latents, 1, latent_height, latent_width)`。用于时间细化轮次，以固定从上一轮次传入的接缝关键帧。

slot_frame_indices (`list[int]`, *可选*) : 生成的关键帧槽位的像素帧位置。

slot_initial_latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width)` 在添加噪声之前写入槽位 token 的内容。

reference_latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, F, H, W)` IC-LoRA 参考潜在变量。

reference_downscale_factor (`int`，默认为 `1`)：目标分辨率与参考分辨率之间的比例。

latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, F, H, W)` 基础 token 的初始内容。公共 pipeline 的 latents 是原始值（未归一化）；在该边界处请传入 `latents_normalized=False`。已经处于 VAE 归一化空间中的 tile 循环保持默认值即可。

latents_normalized (`bool`，默认为 `True`)：指示 `latents`、`slot_initial_latents`、`reference_latents` 和 `keyframe_latents` 是否已经过 VAE 归一化。内部 tile 循环会传入 `True`；每个 pipeline 的 `__call__` 会传入 `False`。

noise_scale (`float`，默认为 `1.0`)：无条件 token 的初始噪声水平，即调度器的第一个 sigma。

**返回：** `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` 为 `None`；否则，它用于在打包序列中索引生成的关键帧槽位 token。

为一次 DFR 去噪过程准备带噪声的打包视频潜变量。

打包序列的布局为 `[base | keyframes | slots | reference]`：

- 基础 token 覆盖目标潜在网格，若提供了 `latents`，则以其作为初始值。
- 满足 `index == 0` 条件的帧会在首帧位置设置干净目标；而满足 `index > 0` 条件的帧以及 `keyframe_latents` 中的每一项，都会作为额外的关键帧 token 追加，其逐 token 的条件掩码等于各自的强度。
- `slot_frame_indices` 在每个位置追加一个潜在帧的*生成*关键帧 token，其条件掩码为 `0`（完全去噪），且 RoPE 时间范围恰好为一个像素帧。这些关键帧槽位为 DFR 提供了额外的帧；`slot_initial_latents` 用于初始化其内容。
- `reference_latents` 将第一阶段半分辨率的 latent 作为完全干净的 IC-LoRA 参考附加进去，并通过 `reference_downscale_factor` 对空间坐标进行缩放，使其映射到目标坐标空间。

附加的条件 token 将其内容存储在 `clean_latents` 中，并在 `latents` 中放置一个零占位符；而关键帧槽位则将其种子存储在 `latents` 中，并在 `clean_latents` 中填充零——返回的 `latents` 是这两者的加噪混合结果（参见该方法末尾的加噪步骤）。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L707)

**参数：**

conditions (`LTX2VideoCondition` 或 `List[LTX2VideoCondition]`，*可选*，默认为 `None`)：图像/视频条件实例的列表。

height (`int`，*可选*，默认为 `512`)：期望的像素高度。

width (`int`，*可选*，默认为 `768`)：期望的像素宽度。

num_frames (`int`，*可选*，默认值为 `121`)：生成视频所需的帧数。

device (`torch.device`，*可选*，默认为 `None`)：用于放置预处理后的图像/视频张量的设备。

**返回：** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

返回一个由 4 个列表组成的元组，每个列表的长度均为 `len(conditions)`，具体如下：
1. 第一个列表是一个预处理后的视频张量列表，其形状为 [batch_size=1, num_channels, num_frames, height, width]。
2. 第二个列表是条件强度列表。
3. 第三个列表是每个条件对应的潜在空间索引列表。
4. 第四个列表是每个条件下（经过裁剪的）像素空间帧数。这对于关键帧坐标语义是必需的（单像素帧的关键帧具有被钳制的时域范围）。

将条件图像/视频预处理为 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L1454)

**参数：**

keyframe_latents (`torch.Tensor`) : 原始的 `(batch_size, C, K, H, W)` 关键帧，由上一轮处理返回。

seed (`int`) : 基础种子；平面 `i` 在 `seed + 4000 + i` 下解码，因此某个平面的像素不取决于它之前解码了多少个平面。

**返回：** `torch.Tensor`

原始的 `(batch_size, C, K, 2H, 2W)` 潜在变量，可直接作为 `guidance_keyframe_latents` 传回。

通过 RGB 方式，以两倍分辨率重新编码关键帧。

这些是 refine 轮次已经确定的帧，因此 epilogue 会直接*接收*这些帧，而不是要求它生成。将帧解码为像素，使用 Lanczos 进行 2 倍放大，然后再次编码，可以在保留帧内容的同时将其对齐到输出网格，这正是 epilogue 能够将其完全干净地固定的原因。

每个平面被解码为各自独立的单帧片段。由于 VAE 是因果的，堆叠解码会导致相邻平面相互渗透——它们是独立的静态图像，而非一个序列。

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py#L689)

**参数：**

start_frame (int)：序列中第一帧的目标帧编号。

sequence_num_frames (int)：序列中的帧数。

target_num_frames (int)：生成视频的目标帧数。

**返回值：** `int`

更新后的序列长度

将条件序列裁剪至允许的帧数。

## 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L151)

**参数：**

scheduler (`LTXEulerAncestralRFScheduler`)：采用 rectified-flow 参数化的 Ancestral Euler 调度器。构造时设置 `eta=0.5` 以匹配 DFR 时间配方。

vae ([AutoencoderKLLTX2Video](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video))：用于将视频编码和解码为潜在表示的变分自编码器（VAE）模型。

audio_vae ([AutoencoderKLLTX2Audio](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_audio_ltx_2#diffusers.AutoencoderKLLTX2Audio))：用于编码和解码音频频谱图的音频 VAE。

text_encoder （`Gemma3ForConditionalGeneration` 或 `Gemma4UnifiedForConditionalGeneration`）：文本编码器模型。

tokenizer (`GemmaTokenizer` 或 `GemmaTokenizerFast`)：用于文本编码器的分词器。

connectors (`LTX2TextConnectors`)：用于适配文本编码器隐藏状态以服务于视频和音频分支的文本连接器堆栈。

transformer ([LTX2VideoTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/ltx2_video_transformer3d#diffusers.LTX2VideoTransformer3DModel))：用于对编码后的视频潜变量进行去噪的条件 Transformer 架构。

vocoder (`LTX2Vocoder` 或 `LTX2VocoderWithBWE`)：用于将梅尔频谱图转换为音频波形的声码器。

temporal_latent_upsampler (`LTX2LatentUpsamplerModel`)：在轮次开始时应用的时间维度 2 倍潜在上采样器。

一次时间维度的 DFR 精修轮次：在时间轴上将画布 x2 进行插值，在关键帧接缝处进行分块，对每个分块执行祖先去噪，通过丢弃后一个分块的引导段进行拼接，并合并携带关键帧的包。

调度器为 `LTXEulerAncestralRFScheduler`（默认 `eta=0.5`）。第 1 阶段 / 第 2 阶段 / 空间后处理部分通过 [LTX2DFRPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipeline) 继续使用 [FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)。每轮调用一次该 pipeline；由调用方循环执行 2x / 4x。

传入的 `latents` / `keyframes_latents` / `audio_latents` 为原始（未归一化）数据，与 [LTX2Pipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2Pipeline) 保持一致。`keyframe_positions` 必须是上一轮返回的位置——在一轮运行结束后，无法从原始的 `num_frames` 重新推导出来。

#### __调用__[[diffusers.LTX2DFRTemporalRefinePipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, latents: Tensor = None, keyframes_latents: Tensor = None, keyframe_positions: list[int] = 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[float] = [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[str] = ['latents'], max_sequence_length: int = 1024)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1349)

**参数：**

prompt (`str` 或 `List[str]`，*可选*)：用于引导视频生成的提示词或提示词列表。如果未定义，则必须传入 `prompt_embeds`。

latents (`torch.Tensor`) : **input** 画布的原始视频潜变量，`(batch_size, channels, frames, height, width)`。

keyframes_latents (`torch.Tensor`) : 来自上一轮传递的原始 carry 关键帧 `(batch_size, channels, K, height, width)`。

keyframe_positions (`list[int]`) : `keyframes_latents` 在 **输入** 画布上的像素帧索引。

audio_latents (`torch.Tensor`) ：冻结的第一阶段音频，已解包并去归一化。每个 tile 接收覆盖其播放窗口的切片；返回的音频是该波形，而非针对每个 tile 重新去噪的结果。

conditions (`LTX2VideoCondition` 或 `List[LTX2VideoCondition]`，*可选*)：按 `condition_num_frames`（原始请求）索引的帧级条件。每一轮都会将条件的像素位置乘以 `2 ** round_index`。

height (`int`，*可选*，默认为 `704`)：此通道的像素高度（与输入视频相同）。

width (`int`，*可选*，默认值为 `1216`)：此通道的像素宽度。

num_frames (`int`，*可选*，默认值为 `121`)：**输入** 画布的像素帧数（未裁剪）。

frame_rate (`float`，*可选*，默认值为 `24.0`)：**输入**的播放帧率。round 会将其翻倍。

source_seconds (`float`, *可选*) : 冻结的 stage-1 音频时长。默认值为 `num_frames / frame_rate`，这对于第一轮是正确的；后续轮次必须传入原始的 stage-1 时长，以避免 tile 发生漂移。

condition_num_frames (`int`, *可选*) : 用于编码 `conditions` 的原始生成 `num_frames`。默认值为 `num_frames`。在填充或前一轮之后，请传入原始请求，以免 `index=-1` 回绕到填充的尾部。

round_index (`int`，*可选*，默认为 `1`)：从 1 开始的轮次编号。Tiles 将祖先噪声初始化为 `seed + 1000 * round_index + tile`，并且条件会按 `2 ** round_index` 进行缩放。

sigmas (`list[float]`, *可选*) : 本轮瓦片的蒸馏调度，不包含末尾的 `0.0`。

noise_scale (`float`, *可选*) : 非条件 token 的起始噪声水平。默认值为 `sigmas[0]`。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于可复现性的随机数生成器。祖先采样使用从此生成器的 `initial_seed()` 派生的独立分块种子。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：解码时的噪声缩放。

use_cross_timestep (`bool`，*可选*，默认为 `True`)：是否使用跨模态 sigma 进行交叉注意力调制。LTX-2.3+ 版本为 `True`。

output_type (`str`，*可选*，默认为 `"pil"`)：输出格式。可选择 `"pil"`、`"np"`、`"pt"` 或 `"latent"`。Latent 输出为未裁剪的画布。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) 或普通的 `(frames, audio, keyframes, keyframe_positions)` 元组。

attention_kwargs (`dict`，*可选*)：传递给注意力处理器的额外 kwargs。

callback_on_step_end (`Callable`，*可选*)：在每个去噪步骤结束时，针对每个 tile 调用的函数。

callback_on_step_end_tensor_inputs (`List`，*可选*，默认为 `["latents"]`)：回调函数的张量输入。

max_sequence_length (`int`，*可选*，默认为 `1024`)：文本提示词的最大序列长度。

**返回：** [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [LTX2DFRPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipelineOutput)，否则返回 `(video, audio, keyframes, keyframe_positions)` 的 `tuple`。

运行一轮时间细化。

示例：
```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",
... )
```

#### 去噪[[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[float], 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1138)

**参数：**

sigmas (`list[float]`) : 本次迭代的噪声调度，不包含末尾的 `0.0`。

freeze_audio (`bool`，*可选*，默认为 `False`)：在仍然执行音频到视频的交叉注意力机制的同时，保持 `audio_latents` 处于干净状态（时间步/σ 为 0，不执行音频 Euler 步）。当 `audio_latents` 为 `None` 时，此参数将被忽略。

video_tile_plan (`list`, *可选*) : 来自 `video_tile_plan`[`~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan`] 的每个图块的 token 计划。提供该参数时，每个步骤会对每个图块各运行一次 transformer，并对预测结果进行融合，因此采样器仍然对单个完整画布进行步进，且各图块在每个步骤的重叠区域保持一致。

generator (`torch.Generator`, *可选*) : 转发至 `LTXEulerAncestralRFScheduler.step()`。时间块会传入每个块的种子，以确保祖先采样不会共享随机数流，也不会消耗下一个块初始加噪所读取的状态。蒸馏版 Euler 不会读取该参数。

step_offset (`int`) : 该 pass 的第一个步骤在整个 pipeline 调度中的索引，用于 `callback_on_step_end` 和共享进度条。

对 `sigmas` 执行一次 DFR 去噪，并返回 `(latents, audio_latents)`，两者均保持打包状态。

蒸馏后的调度器在不使用无分类器引导的情况下运行，因此每个步骤只需调用一次 Transformer。由于视频分支需要跨模态注意力，即使其生成的音频会被丢弃，每次迭代也会同时运行两个流。`freeze_audio=True` 将音频流保持在 sigma 0（不执行 Euler 步），以便视频仍能对其进行跨模态注意力——时间细化瓦片和尾声部分利用此机制来跟随第一阶段语音，而无需每个瓦片重新去噪不同的音频实现。

在 x0 条件混合之后，速度为 `(latents - denoised) / sigma`，因此 RF 步 `x0 = x - σ v` 可以恢复混合后的 `denoised`。阶段 1 / 2 / 尾声部分保留 [FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)，并直接采用该 Euler 步。时间细化则换用 `LTXEulerAncestralRFScheduler`（`eta=0.5`）；该步骤会对每个 token 重新加噪，因此之后需要再次应用条件混合，否则强度为 0.95 的接缝锚点会退化。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1101)

按像素帧定位，对帧条件进行预处理和 VAE 编码。

每个条件返回 `(pixel_frame_index, latent, strength, num_pixel_frames)`，可直接用于 [prepare_latents()](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2DFRPipeline.prepare_latents) 的 `condition_latents`。编码与放置保持分离，因为时间细化轮次会按 `2 ** round` 缩放条件的位置，并按 tile 重新定位，不应为了这样做而对同一静态帧在每个 tile 中重复编码。

返回的索引位于 `num_frames` 自身的像素网格上；将其映射到细化后的画布上由调用方负责。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L470)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的视频数量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为 `prompt_embeds` 预生成的注意力掩码。

device : (`torch.device`, *可选*): torch 设备

dtype : (`torch.dtype`, *可选*): torch 数据类型

将提示词编码为文本编码器的隐藏状态。

DFR 运行的是蒸馏后的 sigma 调度，该调度经过训练，可在不使用无分类器引导的情况下使用，因此这里没有负向分支。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L828)

**参数：**

conditions (`list[LTX2VideoCondition]`，*可选*)：帧级图像/视频条件，通过潜在索引进行定位。

condition_latents (`list[tuple[int, torch.Tensor, float, int]]`, *可选*) : `conditions` 的已编码替代项，格式为 `(pixel_frame_index, latent, strength, num_pixel_frames)`。此处使用像素索引而非潜在索引，因为时间细化轮次会将条件的位置乘以 `2 ** round`，而结果通常不会恰好落在潜在边界上——只有追加的关键帧标记可以位于该处，且其位置是按像素确定的。`pixel_frame_index == 0` 仍然表示“替换第一帧”。

keyframe_latents (`list[tuple[int, torch.Tensor, float]]`, *可选*) : 已编码的关键帧引导，格式为 `(pixel_frame_index, latent, strength)`，其中 `latent` 的形状为 `(batch_size, num_channels_latents, 1, latent_height, latent_width)`。用于时间细化轮次，以固定从上一轮次传入的接缝关键帧。

slot_frame_indices (`list[int]`, *可选*) : 生成的关键帧槽位的像素帧位置。

slot_initial_latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width)` 在添加噪声之前写入槽位 token 的内容。

reference_latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, F, H, W)` IC-LoRA 参考潜在变量。

reference_downscale_factor (`int`，默认为 `1`)：目标分辨率与参考分辨率之间的比例。

latents (`torch.Tensor`, *可选*) : `(batch_size, num_channels_latents, F, H, W)` 基础 token 的初始内容。公共 pipeline 的 latents 是原始值（未归一化）；在该边界处请传入 `latents_normalized=False`。已经处于 VAE 归一化空间中的 tile 循环保持默认值即可。

latents_normalized (`bool`，默认为 `True`)：指示 `latents`、`slot_initial_latents`、`reference_latents` 和 `keyframe_latents` 是否已经过 VAE 归一化。内部 tile 循环会传入 `True`；每个 pipeline 的 `__call__` 会传入 `False`。

noise_scale (`float`，默认为 `1.0`)：无条件 token 的初始噪声水平，即调度器的第一个 sigma。

**返回：** `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` 为 `None`；否则，它用于在打包序列中索引生成的关键帧槽位 token。

为一次 DFR 去噪过程准备带噪声的打包视频潜变量。

打包序列的布局为 `[base | keyframes | slots | reference]`：

- 基础 token 覆盖目标潜在网格，若提供了 `latents`，则以其作为初始值。
- 满足 `index == 0` 条件的帧会在首帧位置设置干净目标；而满足 `index > 0` 条件的帧以及 `keyframe_latents` 中的每一项，都会作为额外的关键帧 token 追加，其逐 token 的条件掩码等于各自的强度。
- `slot_frame_indices` 在每个位置追加一个潜在帧的*生成*关键帧 token，其条件掩码为 `0`（完全去噪），且 RoPE 时间范围恰好为一个像素帧。这些关键帧槽位为 DFR 提供了额外的帧；`slot_initial_latents` 用于初始化其内容。
- `reference_latents` 将第一阶段半分辨率的 latent 作为完全干净的 IC-LoRA 参考附加进去，并通过 `reference_downscale_factor` 对空间坐标进行缩放，使其映射到目标坐标空间。

附加的条件 token 将其内容存储在 `clean_latents` 中，并在 `latents` 中放置一个零占位符；而关键帧槽位则将其种子存储在 `latents` 中，并在 `clean_latents` 中填充零——返回的 `latents` 是这两者的加噪混合结果（参见该方法末尾的加噪步骤）。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L648)

**参数：**

conditions (`LTX2VideoCondition` 或 `List[LTX2VideoCondition]`，*可选*，默认为 `None`)：图像/视频条件实例的列表。

height (`int`，*可选*，默认为 `512`)：期望的像素高度。

width (`int`，*可选*，默认为 `768`)：期望的像素宽度。

num_frames (`int`，*可选*，默认值为 `121`)：生成视频所需的帧数。

device (`torch.device`，*可选*，默认为 `None`)：用于放置预处理后的图像/视频张量的设备。

**返回：** `Tuple[List[torch.Tensor], List[float], List[int], List[int]]`

返回一个由 4 个列表组成的元组，每个列表的长度均为 `len(conditions)`，具体如下：
1. 第一个列表是一个预处理后的视频张量列表，其形状为 [batch_size=1, num_channels, num_frames, height, width]。
2. 第二个列表是条件强度列表。
3. 第三个列表是每个条件对应的潜在空间索引列表。
4. 第四个列表是每个条件下（经过裁剪的）像素空间帧数。这对于关键帧坐标语义是必需的（单像素帧的关键帧具有被钳制的时域范围）。

将条件图像/视频预处理为 torch 张量。

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L630)

**参数：**

start_frame (int)：序列中第一帧的目标帧编号。

sequence_num_frames (int)：序列中的帧数。

target_num_frames (int)：生成视频的目标帧数。

**返回值：** `int`

更新后的序列长度

将条件序列裁剪至允许的帧数。

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py#L1090)

在归一化的潜变量上运行 `upsampler`，并按照其预期，往返于原始 VAE 潜空间。

## 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_output.py#L27)

**参数：**

frames (`torch.Tensor`、`np.ndarray` 或 list[list[PIL.Image.Image]]) : 去噪后的视频。潜在输出是未裁剪的画布，形状为 `(batch_size, num_channels, latent_frames, latent_height, latent_width)`。

audio (`torch.Tensor`, `np.ndarray`) : 伴随的音频潜在表示或波形。

keyframes (`torch.Tensor`, *可选*) : 生成或携带的关键帧潜变量，形状为 `(batch_size, num_channels, num_keyframes, latent_height, latent_width)`。当 `output_type != "latent"` 时，或当该 pass 未生成槽位时（例如 tiled epilogue），值为 `None`。

keyframe_positions (`list[int]`, *可选*) : 本次处理画布上每个关键帧的像素帧索引；当 `keyframes` 为 `None` 时，该值为 `None`。经过时间维度处理后，这些索引无法从原始的 `num_frames` 重新推导得出，必须传入下一阶段。

DFR 管道的输出类。

## LTX2LatentUpsamplePipeline[[diffusers.LTX2LatentUpsamplePipeline]]

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L104)

#### __调用__[[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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L264)

**参数：**

video (`list[PipelineImageInput]`，*可选*)：要上采样的视频（例如 LTX 2.0 第一阶段输出）。如果未提供，则应提供 `latents`。

height (`int`，*可选*，默认值为 `512`)：输入视频的高度（以像素为单位，而非生成视频的高度，后者的分辨率会更高）。

width (`int`，*可选*，默认值为 `768`)：输入视频的像素宽度（而非生成视频的宽度，后者的分辨率会更高）。

num_frames (`int`，*可选*，默认为 `121`)：输入视频的帧数。

spatial_patch_size (`int`，*可选*，默认为 `1`)：视频潜变量的空间块大小。当提供 `latents` 且需要解包时使用。

temporal_patch_size (`int`，*可选*，默认为 `1`)：视频潜在表示的时间维度 patch 大小。当提供了 `latents` 且需要解包时使用。

latents (`torch.Tensor`, *可选*) : 预生成的视频潜在表示。可以替代 `video` 参数提供。其形状可以是 `(batch_size, seq_len, hidden_dim)` 的补丁序列，也可以是 `(batch_size, latent_channels, latent_frames, latent_height, latent_width)` 的视频潜在表示。

latents_normalized (`bool`，*可选*，默认为 `False`)：如果提供了 `latents`，则指定是否使用 VAE 的潜在均值和标准差对 `latents` 进行归一化。如果为 `True`，则 `latents` 在提供给潜在上采样器之前会先进行反归一化。

decode_timestep (`float`，默认为 `0.0`)：用于解码生成视频的 timestep。

decode_noise_scale (`float`，默认为 `None`)：在解码时间步中，随机噪声与去噪潜在表示之间的插值因子。

adain_factor (`float`, *可选*，默认为 `0.0`) : 上采样后的潜在表示与原始潜在表示之间的自适应实例归一化（AdaIN）混合因子。取值范围应为 [-10.0, 10.0]；提供 0.0（默认值）表示不执行 AdaIN。

tone_map_compression_ratio (`float`, *可选*，默认为 `0.0`) : 色调映射的压缩强度，用于降低潜在值的动态范围。这对于正则化高方差潜在值或在生成过程中对输出进行条件化非常有用。取值应在 [0, 1] 范围内，其中 0.0（默认值）表示不应用色调映射，1.0 表示完全压缩效果。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.ltx.LTXPipelineOutput` 而不是普通元组。

**返回：** `~pipelines.ltx.LTXPipelineOutput` 或 `tuple`

如果 `return_dict` 为 `True`，则返回 `~pipelines.ltx.LTXPipelineOutput`，否则返回一个 `tuple`，其中第一个元素是上采样后的视频。

调用生成 pipeline 时调用的函数。

示例：
```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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L168)

**参数：**

latents (`torch.Tensor`) : 需要归一化的输入潜变量

reference_latents (`torch.Tensor`)：提供风格统计信息的参考潜变量。

factor (`float`) : 原始潜在表示与变换后潜在表示之间的混合因子。取值范围：-10.0 到 10.0，默认值：1.0

**返回：** `torch.Tensor`

转换后的潜在张量

根据参考潜在张量的统计量，对潜在张量应用自适应实例归一化（AdaIN）。

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

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_latent_upsample.py#L196)

**参数：**

latents : torch.Tensor 输入潜在张量，形状任意。预期其值大致位于 [-1, 1] 或 [0, 1] 范围内。

compression : float 压缩强度，取值范围为 [0, 1]。 - 0.0：不进行色调映射（恒等变换） - 1.0：完全压缩效果

**返回值：**

torch.Tensor 色调映射后的潜在张量，其形状与输入相同。

使用基于 sigmoid 的压缩，对潜在值应用非线性色调映射函数，以感知平滑的方式降低其动态范围。

这在正则化高方差潜在变量或在生成过程中对输出进行条件化时非常有用，尤其是在使用`compression`因子控制动态行为时。

## LTX2VideoDiffusionDecodePipeline[[diffusers.LTX2VideoDiffusionDecodePipeline]]

#### diffusers.LTX2VideoDiffusionDecodePipeline[[diffusers.LTX2VideoDiffusionDecodePipeline]]

```python
diffusers.LTX2VideoDiffusionDecodePipeline(diffusion_decoder: LTX2VideoDiffusionDecoderModel, scheduler, vae: AutoencoderKLLTX2Video = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_diffusion_decode.py#L27)

**参数：**

diffusion_decoder ([LTX2VideoDiffusionDecoderModel](/docs/diffusers/v0.43.0/zh/api/models/ltx2_diffusion_decoder#diffusers.LTX2VideoDiffusionDecoderModel))：扩散视频解码器。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：驱动解码器去噪步骤的调度器。

vae ([AutoencoderKLLTX2Video](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_ltx_2#diffusers.AutoencoderKLLTX2Video)，*可选*)：仅用于查询反归一化所需的潜在统计量。若省略，流水线将回退到 LTX-2 的默认值，因此仅解码的工作流无需加载第二个自编码器。

使用 LTX-2.5 中引入的扩散解码器解码 LTX-2 视频潜在表示。

与卷积解码器不同，该解码器本身是一个小型扩散模型：它以由潜变量构建的上下文体积为条件对像素进行去噪，因此需要一个调度器和生成器。请将其与任何以 `output_type="latent"` 运行的 LTX-2 流水线搭配使用，并传入 `denormalize=False`，因为该路径已经应用了潜变量统计量。

#### __调用__[[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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_ltx2_diffusion_decode.py#L79)

**参数：**

latents (`torch.Tensor`) : 形状为 `(B, C, F, H, W)` 的潜变量。请注意，使用 `output_type="latent"` 运行的 LTX-2 流水线返回的潜变量已*经*反归一化，因此对于此类情况，请传入 `denormalize=False`。

generator (`torch.Generator`，*可选*)：解码器会采样其去噪的噪声，因此传入一个生成器可使解码过程可复现。

output_type (`str`，*可选*，默认为 `"pil"`)：解码后视频的输出格式。可选值包括 `"pil"`、`"np"`、`"pt"` 和 `"latent"`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `LTX2VideoDecodeOutput` 而非普通元组。

denormalize (`bool`，*可选*，默认为 `True`)：是否在解码前应用潜在变量统计量。如果潜在变量已经过反归一化，请将其设置为 `False`。

**返回：** `LTX2VideoDecodeOutput` 或 `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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/duration_head.py#L81)

**参数：**

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`)：输出 MLP 的隐藏层宽度。为避免与 `mlp_hidden` 子模块发生冲突，该参数名称带有 `_dim` 后缀，否则 `ConfigMixin.__getattr__` 会用此配置值遮蔽该子模块。

根据 LTX-2 文本连接器的输出，预测字幕所暗示的镜头自然时长。

Head 与模态无关：可以传入视频和音频连接器输出中的任意一个或两者。模态特定的输入投影将每个流映射到共享的 pooler 维度，可学习的模态嵌入为各流打上标签，使 pooler 能够区分它们，随后一个小型 MLP 将池化后的向量转换为对数时长。回归目标以对数秒为单位进行训练，因此 `forward` 会执行指数运算，调用方始终获得以秒为单位的时长。

从 LTX-2.5 检查点开始提供。

#### forward[[diffusers.pipelines.ltx2.LTX2DurationHead.forward]]

```python
forward(video_tokens: typing.Optional[torch.Tensor] = None, audio_tokens: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/duration_head.py#L134)

**参数：**

video_tokens (`torch.Tensor`，形状为 `(batch_size, seq_len, video_cross_attention_dim)`，*可选*)：视频连接器输出。

audio_tokens (`torch.Tensor`，形状为 `(batch_size, seq_len, audio_cross_attention_dim)`，*可选*)：音频连接器输出。

**返回：** 形状为 `(batch_size,)` 的 `torch.Tensor`

以秒为单位的预测时长。

#### 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/duration_head.py#L172)

**参数：**

video_tokens (`torch.Tensor`, *可选*) : 单个提示词的 Video connector 输出。

audio_tokens (`torch.Tensor`, *可选*) : 单个提示词的音频连接器输出。

frame_rate (`float`) : 用于将预测时长转换为帧数的每秒帧数。

temporal_compression_ratio (`int`) : VAE 的时间压缩比，用于定义帧网格。

min_seconds (`float`，默认为 `1.0`)：预测值的下界。

max_seconds (`float`，默认为 `20.0`)：预测的上限。

**返回值：** `int`

位于 VAE 时间网格上的帧数。

根据连接器 token 预测帧数，并将其限制在 `[min_seconds, max_seconds]` 范围内，同时对齐到 VAE 的因果时间网格（`k * temporal_compression_ratio + 1`）。

Clamp 操作在 Snap 之前应用：经过 Clamp 处理的帧数不一定与网格对齐，因此如果先执行 Snap，会得到不同的结果。由于 Snap 采用向下取整，结果可能会低于最小值；当这种情况发生时，结果会向上 Snap 到下一个网格点，从而确保帧数保持在有效范围内。

过窄的边界范围可能会转换为一个完全不包含任何网格点的帧窗口——在 24 fps 下，`[1.0s, 1.02s]` 会舍入为 `[24, 24]`，而 24 并不满足 `8k + 1`。此时会使用最近的网格点并记录一条警告，因为超出不足一个网格步长总比拒绝生成要好。因此，返回的计数始终位于网格上，但在此情况下可能会刚好落在请求的边界之外。

## LTX2PipelineOutput[[diffusers.pipelines.ltx2.LTX2PipelineOutput]]

#### diffusers.pipelines.ltx2.LTX2PipelineOutput[[diffusers.pipelines.ltx2.LTX2PipelineOutput]]

```python
diffusers.pipelines.ltx2.LTX2PipelineOutput(frames: Tensor, audio: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/ltx2/pipeline_output.py#L9)

**参数：**

frames (`torch.Tensor`、`np.ndarray` 或 list[list[PIL.Image.Image]]) : 视频输出列表 - 它可以是一个长度为 `batch_size,` 的嵌套列表，其中每个子列表包含长度为 `num_frames.` 的去噪 PIL 图像序列。它也可以是一个形状为 `(batch_size, num_frames, channels, height, width)` 的 NumPy 数组或 Torch 张量。

audio (`torch.Tensor`，`np.ndarray`) : TODO

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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/ltx2/modular_pipeline.py#L26)

用于 LTX-2（联合视频 + 音频生成）的 ModularPipeline。

## LTX2AutoBlocks[[diffusers.LTX2AutoBlocks]]

#### diffusers.LTX2AutoBlocks[[diffusers.LTX2AutoBlocks]]

```python
diffusers.LTX2AutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/ltx2/modular_blocks_ltx2.py#L1761)

Auto 块，支持 LTX-2 的文本生成视频、图像生成视频、条件生成视频以及上下文（IC-LoRA）生成（联合视频 + 音频）。

支持的工作流：
- `text2video`：需要 `prompt`
- `image2video`：需要 `image`、`prompt`
- `condition`：需要 `conditions`、`prompt`
- `in_context`：需要 `reference_conditions`、`num_frames`、`prompt`

组件：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`)

输入：prompt (`str`, *可选*)：用于引导图像生成的提示词或提示词列表。conditions (`list`, *可选*)：`LTX2VideoCondition`（或其列表），用于在生成视频的特征帧索引处放置图像/视频条件。enable_prompt_enhancement (`bool`, *可选*, 默认为 False)：是否运行提示词增强器。需显式启用，以匹配 Lightricks 参考流水线。system_prompt (`str`, *可选*)：用于增强的系统提示词。当存在 `PIL.Image.Image` 条件帧时，默认为 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`，否则为 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`。prompt_max_new_tokens (`int`, *可选*)：提示词增强期间生成的新 token 的最大数量。默认为 600，即 LTX-2.5 Gemma-4 增强器的预算。prompt_enhancement_kwargs (`dict`, *可选*)：增强器 `.generate` 调用的关键字参数。默认为贪心解码。prompt_enhancement_seed (`int`, *可选*, 默认为 10)：提示词增强的随机种子（在 LTX-2.5 的贪心解码下无效）。generator (`Generator`, *可选*)：用于确定性生成的 Torch 生成器。image (`Image | list`, *可选*)：用于去噪的参考图像。可以是单张图像或图像列表。negative_prompt (`str`, *可选*)：用于不引导图像生成的提示词或提示词列表。max_sequence_length (`int`, *可选*, 默认为 1024)：提示词编码的最大序列长度。min_seconds (`float`, *可选*, 默认为 1.0)：自动预测时长的下限。max_seconds (`float`, *可选*, 默认为 20.0)：自动预测时长的上限。必须严格大于 `min_seconds`。frame_rate (`float`, *可选*, 默认为 24.0)：生成视频的每秒帧数。height (`int`, *可选*, 默认为 512)：生成图像的高度（像素）。width (`int`, *可选*, 默认为 704)：生成图像的宽度（像素）。image_crf (`int`, *可选*)：在 VAE 编码前用于重新压缩条件 `image` 的 H.264 CRF，以匹配模型训练时使用的压缩。默认为 `None`，将从文本编码器生成中解析（LTX-2.3 及之前为 33，LTX-2.5 为 18）。传入 `0` 可跳过重新压缩。执行重新压缩时需要 `PIL.Image.Image`。num_frames (`int`, *可选*)：生成视频的帧数。省略时通过 `duration_head` 自动预测（参见 `LTX2AutoDurationStep`）。reference_conditions (`list`, *可选*)：`LTX2ReferenceCondition`（或其列表），其视频被编码为 IC-LoRA 适配器所关注的额外特征 token。reference_downscale_factor (`int`, *可选*, 默认为 1)：目标分辨率与参考分辨率之间的比率；2 表示参考图像以目标分辨率的一半进行预处理。空间坐标按此因子缩放，使参考 token 落在目标坐标空间中。必须与训练 IC-LoRA 时使用的因子匹配。conditioning_attention_strength (`float`, *可选*, 默认为 1.0)：[0, 1] 范围内的标量，控制噪声 token 和参考 token 之间相互关注的强度。1.0（默认）表示不屏蔽注意力。conditioning_attention_mask (`Tensor`, *可选*)：可选的像素空间掩码，形状为 (1, 1, F, H, W)，值在 [0, 1] 之间，提供空间变化的注意力强度。会下采样到参考特征网格，并与 `conditioning_attention_strength` 相乘。motion_speed (`float`, *可选*, 默认为 1.0)：相对于真实时间的运动速度。位置嵌入以 `frame_rate / motion_speed` 为条件，因此小于 1 的值会减慢运动，例如 Slow-Motion-Control LoRA 的 5 倍慢动作使用 `0.2`。`frame_rate` 保持为播放速率。num_videos_per_prompt (`int`, *可选*, 默认为 1)：每个提示词生成的图像数量。condition_latents (`list`, *可选*)：每个条件的归一化 VAE 特征，形状为 [1, C, F, H, W]。condition_strengths (`list`, *可选*)：每个条件的条件强度。condition_indices (`list`, *可选*)：应用条件的每个条件的特征帧索引。condition_pixel_frames (`list`, *可选*)：每个条件的裁剪像素帧数，用于限制单帧关键帧坐标。reference_latents (`Tensor`, *可选*)：打包的参考 token，形状为 [1, total_reference_tokens, C]，或者在未提供参考条件时为 `None`（`LTX2AutoReferenceEncoderStep` 将被跳过）。reference_coords (`Tensor`, *可选*)：参考 token 的 RoPE 坐标。reference_token_counts (`list`, *可选*)：按 `reference_conditions` 顺序排列的每个参考的 token 数量。latents (`Tensor`)：用于图像生成的预生成噪声特征。noise_scale (`float`, *可选*)：无条件 token 的初始噪声水平。默认为 `None`，当提供自定义 `sigmas` 时解析为 `sigmas[0]`，否则为 1.0。sigmas (`list`, *可选*)：去噪过程的自定义 sigmas。reference_cross_mask (`Tensor`, *可选*)：每个参考 token 的噪声<->参考注意力强度，形状为 [1, num_ref_tokens]。num_inference_steps (`int`)：去噪步骤数。timesteps (`Tensor`)：去噪过程的时间步。audio_latents (`Tensor`)：可选的预编码音频特征；未提供时使用随机噪声。**denoiser_input_fields (`None`, *可选*)：去噪器的条件模型输入：例如 prompt_embeds、negative_prompt_embeds 等。use_cross_timestep (`bool`, *可选*, 默认为 True)：是否将 transformer 条件化为独立的每 token 交叉时间步（LTX-2.3+）。attention_kwargs (`dict`, *可选*)：注意力处理器的额外关键字参数。image_latents (`Tensor`, *可选*)：用于图生视频条件的 VAE 编码参考图像特征。output_type (`str`, *可选*, 默认为 pil)：输出格式：'pil'、'np'、'pt'。decode_timestep (`None`, *可选*, 默认为 0.0)：VAE 解码最终特征的时间步。decode_noise_scale (`None`, *可选*)：应用于解码时间步特征的噪声插值因子。

输出：videos (`list`)：生成的视频。audio (`Tensor`)：生成的音频波形。

## 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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/ltx2/modular_pipeline.py#L125)

用于 LTX-2.5 的 ModularPipeline（联合视频 + 音频生成）。

与 [LTX2ModularPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/ltx2#diffusers.LTX2ModularPipeline) 完全相同，区别在于其默认块使用扩散视频解码器进行解码，这是 LTX-2.5 及以后版本的默认设置。检查点通过 `modular_model_index.json` 路由到此。

## LTX25AutoBlocks[[diffusers.LTX25AutoBlocks]]

#### diffusers.LTX25AutoBlocks[[diffusers.LTX25AutoBlocks]]

```python
diffusers.LTX25AutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/ltx2/modular_blocks_ltx25.py#L215)

LTX-2.5 的 Auto blocks，支持文生视频、图生视频、条件生视频以及上下文（IC-LoRA）生成（联合视频 + 音频）。与 `LTX2AutoBlocks` 完全相同，区别在于视频解码器为 `LTX2DiffusionVaeDecoderStep`，因为从 LTX-2.5 开始，扩散解码器是原生默认配置。若要改用卷积 VAE 进行解码，请替换解码块：`blocks.sub_blocks["decode"] = LTX2AutoDecoderStep()`。

支持的工作流：
- `text2video`：需要 `prompt`
- `image2video`：需要 `image`、`prompt`
- `condition`：需要 `conditions`、`prompt`
- `in_context`：需要 `reference_conditions`、`num_frames`、`prompt`

组件：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`)

输入：prompt (`str`, *可选*)：用于引导图像生成的提示词或提示词列表。conditions (`list`, *可选*)：`LTX2VideoCondition`（或其列表），用于在生成视频的特征帧索引处放置图像/视频条件。enable_prompt_enhancement (`bool`, *可选*, 默认为 False)：是否运行提示词增强器。需显式启用，与 Lightricks 参考流水线保持一致。system_prompt (`str`, *可选*)：用于增强的系统提示词。当存在 `PIL.Image.Image` 条件帧时，默认为 `LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`，否则为 `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT`。prompt_max_new_tokens (`int`, *可选*)：提示词增强期间生成的新 token 的最大数量。默认为 600，即 LTX-2.5 Gemma-4 增强器的预算。prompt_enhancement_kwargs (`dict`, *可选*)：增强器 `.generate` 调用的关键字参数。默认为贪心解码。prompt_enhancement_seed (`int`, *可选*, 默认为 10)：提示词增强的随机种子（在 LTX-2.5 的贪心解码下无效）。generator (`Generator`, *可选*)：用于确定性生成的 Torch 生成器。image (`Image | list`, *可选*)：用于去噪的参考图像。可以是单张图像或图像列表。negative_prompt (`str`, *可选*)：不希望引导图像生成的提示词或提示词列表。max_sequence_length (`int`, *可选*, 默认为 1024)：提示词编码的最大序列长度。min_seconds (`float`, *可选*, 默认为 1.0)：自动预测时长的下限。max_seconds (`float`, *可选*, 默认为 20.0)：自动预测时长的上限。必须严格大于 `min_seconds`。frame_rate (`float`, *可选*, 默认为 24.0)：生成视频的每秒帧数。height (`int`, *可选*, 默认为 512)：生成图像的高度（像素）。width (`int`, *可选*, 默认为 704)：生成图像的宽度（像素）。image_crf (`int`, *可选*)：在 VAE 编码前用于重新压缩条件 `image` 的 H.264 CRF 值，以匹配模型训练时使用的压缩设置。`None`（默认值）根据文本编码器版本解析（LTX-2.3 及之前为 33，LTX-2.5 为 18）。传入 `0` 可跳过重新压缩。执行重新压缩时需要 `PIL.Image.Image`。num_frames (`int`, *可选*)：生成视频的帧数。省略时通过 `duration_head` 自动预测（参见 `LTX2AutoDurationStep`）。reference_conditions (`list`, *可选*)：`LTX2ReferenceCondition`（或其列表），其视频被编码为额外的特征 token，供 IC-LoRA 适配器关注。reference_downscale_factor (`int`, *可选*, 默认为 1)：目标分辨率与参考分辨率之间的比例；2 表示参考图像以目标分辨率的一半进行预处理。空间坐标按此因子缩放，使参考 token 落在目标坐标空间中。必须与训练 IC-LoRA 时使用的因子一致。conditioning_attention_strength (`float`, *可选*, 默认为 1.0)：[0, 1] 范围内的标量，控制噪声 token 和参考 token 之间相互关注的强度。1.0（默认值）表示不屏蔽注意力。conditioning_attention_mask (`Tensor`, *可选*)：可选的像素空间掩码，形状为 (1, 1, F, H, W)，值在 [0, 1] 之间，提供空间变化的注意力强度。会下采样到参考特征网格，并与 `conditioning_attention_strength` 相乘。motion_speed (`float`, *可选*, 默认为 1.0)：相对于真实时间的运动速度。位置嵌入以 `frame_rate / motion_speed` 为条件，因此小于 1 的值会减慢运动，例如 `0.2` 对应 Slow-Motion-Control LoRA 的 5 倍慢动作。`frame_rate` 保持为播放速率。num_videos_per_prompt (`int`, *可选*, 默认为 1)：每个提示词生成的图像数量。condition_latents (`list`, *可选*)：每个条件的归一化 VAE 特征，形状为 [1, C, F, H, W]。condition_strengths (`list`, *可选*)：每个条件的条件强度。condition_indices (`list`, *可选*)：应用条件的每个条件的特征帧索引。condition_pixel_frames (`list`, *可选*)：每个条件裁剪后的像素帧数，用于限制单帧关键帧坐标。reference_latents (`Tensor`, *可选*)：打包的参考 token，形状为 [1, total_reference_tokens, C]，或者在未提供参考条件时为 `None`（`LTX2AutoReferenceEncoderStep` 将被跳过）。reference_coords (`Tensor`, *可选*)：参考 token 的 RoPE 坐标。reference_token_counts (`list`, *可选*)：按 `reference_conditions` 顺序排列的每个参考的 token 数量。latents (`Tensor`)：用于图像生成的预生成噪声特征。noise_scale (`float`, *可选*)：无条件 token 的初始噪声水平。`None`（默认值）在提供自定义 `sigmas` 时解析为 `sigmas[0]`，否则为 1.0。sigmas (`list`, *可选*)：去噪过程的自定义 sigmas。reference_cross_mask (`Tensor`, *可选*)：每个参考 token 的噪声<->参考注意力强度，形状为 [1, num_ref_tokens]。num_inference_steps (`int`)：去噪步数。timesteps (`Tensor`)：去噪过程的时间步。audio_latents (`Tensor`)：可选的预编码音频特征；未提供时使用随机噪声。**denoiser_input_fields (`None`, *可选*)：去噪器的条件模型输入：例如 prompt_embeds、negative_prompt_embeds 等。use_cross_timestep (`bool`, *可选*, 默认为 True)：是否将 transformer 条件化为独立的逐 token 交叉时间步（LTX-2.3+）。attention_kwargs (`dict`, *可选*)：注意力处理器的额外关键字参数。image_latents (`Tensor`, *可选*)：用于图生视频条件的 VAE 编码参考图像特征。output_type (`str`, *可选*, 默认为 pil)：输出格式：'pil'、'np'、'pt'。

输出：videos (`list`)：生成的视频。audio (`Tensor`)：生成的音频波形。

