Diffusers documentation

LTX-2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

LTX-2

LoRA

LTX-2 是一款基于 DiT 的基础模型,旨在通过单一模型生成同步的视频和音频。它整合了现代视频生成的核心组件,提供开放权重,并专注于实用的本地部署。

您可以在 Lightricks 组织下找到所有原始的 LTX-Video 检查点。

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 的结构,同时增强纹理和清晰度。

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

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

蒸馏检查点生成

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

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)生成:

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

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

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,其中扰动(“较弱”)的输出是使用负提示生成的。
  2. 时空引导(STG):STG 不再使用通过跳过自注意力操作生成的扰动输出,而是直接替换为注意力值。其思路是,这样做能生成更清晰的视频并提升时空一致性。
  3. 模态隔离引导:通过禁用跨模态(音频到视频以及视频到音频)交叉注意力来生成扰动输出,从而偏离该输出。这种引导更具体地适用于 LTX-2.X 模型,其理念是这能提升生成音频与视频之间的一致性。

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

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 模型对提示词风格较为敏感。有关如何撰写优质提示词的建议,请参阅官方提示词指南。使用提示词增强功能(即根据系统提示词,利用流水线中的文本编码器(默认为Gemma 3模型)对提供的提示词进行增强)也可以提升样本质量。要使用提示词增强功能,必须存在可选的processor流水线组件。通过设置enable_prompt_enhancement=True和system_prompt来启用该功能(需主动选择,与 Lightricks 参考流水线保持一致):

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 同时提供了两个 transformer:位于 transformer/ 中的蒸馏 DiT,即 model_index.json 所指向的模型;以及位于 transformer_full/ 中的完整/SFT DiT,后者需要显式加载(参见 Full / SFT transformer)。该仓库的 scheduler/ 针对蒸馏检查点进行了配置(use_dynamic_shifting=False、shift_terminal=None),以便其 sigma 调度能够严格按照给定值使用。两阶段生成 所需的一切也包含在其中:一个 latent_upsampler/ 子文件夹,以及位于仓库根目录的第二阶段蒸馏 LoRA ltx-2.5-22b-distilled-lora-450-bf16.safetensors。

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

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 权重进行的 蒸馏检查点生成。
  • Full/SFT 阶段 1 + 蒸馏 LoRA 阶段 2 — 如本页顶部所述,采用两阶段生成,使用 transformer_full/ 和随附的 LoRA。有关具体变更,请参见下文。

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

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 而非显式的 num_frames 时,请让 stage 1 自行决定,并在 stage 2 运行之前从其潜变量([B, C, F, H, W])中恢复实际长度,而不是进行第二次预测:

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

使用蒸馏 LoRA 的第二阶段

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

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)。它是流水线用于解码的组件,因此上述所有代码片段都已在使用它,并且它是两者中唯一支持分块(pipe.vae.enable_tiling())的组件,这通常正是让高分辨率得以适配的关键。
  • diffusion_decoder/ — LTX2VideoDiffusionDecoderModel。它本身是一个扩散模型,而非流水线组件,因此不作为 vae 传入:请以 output_type="latent" 运行流水线,并将潜变量传递给 LTX2VideoDiffusionDecodePipeline。

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

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

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

要将此功能与两阶段生成结合使用,请让第二阶段返回output_type="latent",然后对其进行解码。

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

在单卡上,解码前也建议将流水线移出显存(在捕获 pipe.scheduler 和声码器的 output_sampling_rate 之后,执行 pipe.to("cpu") 和 torch.cuda.empty_cache()),因为解码器需要自身的显存余量。有关注意力后端、分块细节以及解码器的其他行为,请参阅 LTX2VideoDiffusionDecoderModel。

完整 / SFT 转换器

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

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 不同(在后者中,同一个文本编码器检查点同时充当增强器,参见上文 提示词增强),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=:

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 默认会自动预测——省略该参数,模型将自行决定时长:

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

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

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 以约束预测。原始预测值会被限制在该范围内,然后转换为帧数:

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。它所需的一切都是公开的:

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 以及返回的视频仍遵循 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,需先在 Hub 上接受其许可证)时才有意义。如果不使用 motion_speed,该 LoRA 将作为普通 LoRA 加载,无法提供任何运动控制功能。模型卡片建议的速度为 1.0、0.5、0.2、0.1、0.05 和 0.025,LoRA 强度为 1.0。请勿在提示词中包含速度相关的词汇(如“慢动作”、“高帧率”),并在不同速度下复用相同的字幕,因为仅 motion_speed 即可驱动该效果。

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 秒),且只有运动节奏发生变化。在 两阶段生成 中,需将相同的 motion_speed 传递给 两个 阶段。阶段 2 会对视频进行重新去噪,如果它在实时轴上运行,就会抵消慢动作效果。参考驱动器 通过包装两个路径共享的阶段对象,实现了相同的效果。

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

LTX-2.5 模块化

LTX-2.5 也可作为模块化流水线使用。默认 blockset 使用扩散解码器,并在省略 num_frames 时预测视频时长。它通过 guider 和 audio_guider 组件分别对视频和音频应用引导。有关可用的引导参数,请参阅 LTX2Guidance。默认情况下,模块化流水线会从 google/gemma-4-E2B-it 仓库下载提示词增强器和处理器。以下是一个 T2V 模块化示例:

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 工作流:

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、LTX25AutoBlocks)。

LTX-2.5 的 Diffusion Fidelity Rendering (DFR)

LTX2DFRPipeline 以实际耗时换取细节保真度。每次 __call__ 都是在 height × width 分辨率下执行一次去噪:它生成视频以及额外的单像素帧关键帧槽位,或者对这些槽位中提供的潜变量进行重新去噪。调用方以与其他 LTX 两阶段流水线相同的方式组合各个阶段——先调用本流水线,再调用 LTX2LatentUpsamplePipeline,然后再次调用本流水线,最后对每个时间轮次调用 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。

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 执行一轮处理:在时间维度上上采样,在关键帧接缝处进行分块,使用 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() 进行 encode;切勿对 epilogue 关键帧进行潜在空间上采样),然后:

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。

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

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTX2Videoaudio_vae: AutoencoderKLLTX2Audiotext_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGenerationtokenizer: GemmaTokenizerconnectors: LTX2TextConnectorstransformer: LTX2VideoTransformer3DModelvocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWEprocessor: transformers.processing_utils.ProcessorMixin | None = Noneprompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = Noneduration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None )

参数

  • transformer (LTXVideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLLTXVideo) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
  • text_encoder (T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer (T5TokenizerFast) — 第二个 T5TokenizerFast 类的 Tokenizer。
  • connectors(LTX2TextConnectors)—— 用于将文本编码器的隐藏状态适配到视频和音频分支的文本连接器堆栈。

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

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

__call__

< >

( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 512width: int = 768num_frames: int | None = Nonemin_seconds: float = 1.0max_seconds: float = 20.0frame_rate: float = 24.0motion_speed: float = 1.0num_inference_steps: int = 30sigmas: list[float] | None = Nonetimesteps: list = Noneguidance_scale: float = 3.0stg_scale: float = 1.0modality_scale: float = 3.0guidance_rescale: float = 0.7audio_guidance_scale: float | None = 7.0audio_stg_scale: float | None = 1.0audio_modality_scale: float | None = 3.0audio_guidance_rescale: float | None = 0.7spatio_temporal_guidance_blocks: list[int] | None = [28]noise_scale: float = 0.0num_videos_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneaudio_latents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneuse_cross_timestep: bool = Truesystem_prompt: str | None = Noneenable_prompt_enhancement: bool = Falseprompt_max_new_tokens: int | None = Noneprompt_enhancement_kwargs: dict[str, typing.Any] | None = Noneprompt_enhancement_seed: int = 10output_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 1024 ) → ~pipelines.ltx.LTX2PipelineOutput or tuple

参数

  • 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], 可选) — 用于支持在 set_timesteps 方法中接受 sigmas 参数的调度器的去噪过程的自定义 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • timesteps (list[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 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 中提出。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 guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. 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 生成器,用于使生成过程具有确定性。
  • 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:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.ltx.LTX2PipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.processor 下定义。
  • 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 时调用的函数。

示例:

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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 1024scale_factor: int = 8device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

< >

( prompt: strsystem_prompt: strmax_new_tokens: int | None = Noneseed: int = 10generator: typing.Optional[torch.Generator] = Nonegeneration_kwargs: dict[str, typing.Any] | None = Nonedevice: typing.Union[str, torch.device, NoneType] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None )

通过提示词增强器(一个 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

class diffusers.LTX2ImageToVideoPipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTX2Videoaudio_vae: AutoencoderKLLTX2Audiotext_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGenerationtokenizer: GemmaTokenizerconnectors: LTX2TextConnectorstransformer: LTX2VideoTransformer3DModelvocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWEprocessor: transformers.processing_utils.ProcessorMixin | None = Noneprompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = Noneduration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None )

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

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

TODO

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 512width: int = 768num_frames: int | None = Nonemin_seconds: float = 1.0max_seconds: float = 20.0frame_rate: float = 24.0motion_speed: float = 1.0num_inference_steps: int = 30sigmas: list[float] | None = Nonetimesteps: list[int] | None = Noneguidance_scale: float = 3.0stg_scale: float = 1.0modality_scale: float = 3.0guidance_rescale: float = 0.7audio_guidance_scale: float | None = 7.0audio_stg_scale: float | None = 1.0audio_modality_scale: float | None = 3.0audio_guidance_rescale: float | None = 0.7spatio_temporal_guidance_blocks: list[int] | None = [28]noise_scale: float = 0.0num_videos_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneaudio_latents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneuse_cross_timestep: bool = Truesystem_prompt: str | None = Noneenable_prompt_enhancement: bool = Falseprompt_max_new_tokens: int | None = Noneprompt_enhancement_kwargs: dict[str, typing.Any] | None = Noneprompt_enhancement_seed: int = 10image_crf: int | None = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 1024 ) → ~pipelines.ltx.LTX2PipelineOutput or tuple

参数

  • 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], 可选) — 用于支持在 set_timesteps 方法中接受 sigmas 参数的调度器的去噪过程的自定义 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • timesteps (List[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 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 中提出。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 guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. 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 生成器,用于使生成过程具有确定性。
  • 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:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.ltx.LTX2PipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.processor 下定义。
  • 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 时调用的函数。

示例:

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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 1024scale_factor: int = 8device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

< >

( prompt: strsystem_prompt: strmax_new_tokens: int | None = Noneseed: int = 10generator: typing.Optional[torch.Generator] = Nonegeneration_kwargs: dict[str, typing.Any] | None = Nonedevice: typing.Union[str, torch.device, NoneType] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None )

通过提示词增强器(一个 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

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTX2Videoaudio_vae: AutoencoderKLLTX2Audiotext_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGenerationtokenizer: GemmaTokenizerconnectors: LTX2TextConnectorstransformer: LTX2VideoTransformer3DModelvocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWEaudio_scheduler: diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler | None = Noneprocessor: transformers.processing_utils.ProcessorMixin | None = Noneprompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = Noneduration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None )

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

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

TODO

__call__

< >

( conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 512width: int = 768num_frames: int | None = Nonemin_seconds: float = 1.0max_seconds: float = 20.0frame_rate: float = 24.0motion_speed: float = 1.0num_inference_steps: int = 30sigmas: list[float] | None = Nonetimesteps: list[float] | None = Noneguidance_scale: float = 3.0stg_scale: float = 1.0modality_scale: float = 3.0guidance_rescale: float = 0.7audio_guidance_scale: float | None = 7.0audio_stg_scale: float | None = 1.0audio_modality_scale: float | None = 3.0audio_guidance_rescale: float | None = 0.7spatio_temporal_guidance_blocks: list[int] | None = [28]noise_scale: float | None = Nonenum_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneaudio_latents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneuse_cross_timestep: bool = Truesystem_prompt: str | None = Noneenable_prompt_enhancement: bool = Falseprompt_max_new_tokens: int | None = Noneprompt_enhancement_kwargs: dict[str, typing.Any] | None = Noneprompt_enhancement_seed: int = 10output_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 1024 ) → ~pipelines.ltx.LTX2PipelineOutput or tuple

参数

  • 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], 可选) — 用于支持在 set_timesteps 方法中接受 sigmas 参数的调度器的去噪过程的自定义 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • timesteps (List[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 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 中提出。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 guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. 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 生成器,用于使生成过程具有确定性。
  • 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:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.ltx.LTX2PipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.processor 下定义。
  • 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 时调用的函数。

示例:

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

< >

( latents: Tensorconditioning_mask: Tensorcondition_latents: listcondition_strengths: listcondition_indices: listlatent_height: intlatent_width: int ) → Tuple[torch.Tensor, torch.Tensor, torch.Tensor]

参数

  • 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

< >

( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 1024scale_factor: int = 8device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • do_classifier_free_guidance(bool,可选,默认为 True)— 是否使用 classifier free guidance。
  • 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

< >

( prompt: strsystem_prompt: strmax_new_tokens: int | None = Noneseed: int = 10generator: typing.Optional[torch.Generator] = Nonegeneration_kwargs: dict[str, typing.Any] | None = Nonedevice: typing.Union[str, torch.device, NoneType] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None )

通过提示词增强器(一个 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

< >

( conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Nonebatch_size: int = 1num_channels_latents: int = 128height: int = 512width: int = 768num_frames: int = 121frame_rate: float = 24.0noise_scale: float = 1.0dtype: typing.Optional[torch.dtype] = Nonedevice: typing.Optional[torch.device] = Nonegenerator: typing.Optional[torch.Generator] = Nonelatents: typing.Optional[torch.Tensor] = None )

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

首帧条件(latent_idx == 0)通过覆盖首帧位置上的 token 来应用(VideoConditionByLatentIndex 语义)。非首帧条件(latent_idx > 0)则与主 latent 序列进行拼接,并为每个 token 设置 conditioning_mask = strength(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

< >

( conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneheight: int = 512width: int = 768num_frames: int = 121device: typing.Optional[torch.device] = None ) → Tuple[List[torch.Tensor], List[float], List[int], List[int]]

参数

  • 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

< >

( start_frame: intsequence_num_frames: inttarget_num_frames: int ) → int

参数

  • start_frame (int) — 序列中第一帧的目标帧编号。
  • sequence_num_frames (int) — 序列中的帧数。
  • target_num_frames (int) — 生成视频的目标帧数。

返回值

int

更新后的序列长度

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

LTX2DFRPipeline

class diffusers.LTX2DFRPipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTX2Videoaudio_vae: AutoencoderKLLTX2Audiotext_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGenerationtokenizer: GemmaTokenizerconnectors: LTX2TextConnectorstransformer: LTX2VideoTransformer3DModelvocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWEprocessor: transformers.processing_utils.ProcessorMixin | None = Noneprompt_enhancer: transformers.models.gemma4.modeling_gemma4.Gemma4ForConditionalGeneration | None = Noneduration_head: diffusers.pipelines.ltx2.duration_head.LTX2DurationHead | None = None )

参数

  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的视频潜变量进行去噪的调度器。
  • vae (AutoencoderKLLTX2Video) — 变分自编码器(VAE)模型,用于将视频编码和解码为潜在表示。
  • audio_vae (AutoencoderKLLTX2Audio) — 用于编码和解码音频频谱图的音频 VAE。
  • text_encoder(Gemma3ForConditionalGeneration 或 Gemma4UnifiedForConditionalGeneration)—— 文本编码器模型。
  • tokenizer(GemmaTokenizer 或 GemmaTokenizerFast)—— 文本编码器的分词器。
  • connectors(LTX2TextConnectors)—— 用于将文本编码器的隐藏状态适配到视频和音频分支的文本连接器堆栈。
  • transformer (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 会生成视频以及额外的单像素帧关键帧槽位,或者对源自这些槽位的已提供 latents 进行重新去噪。调用方组合各个阶段:先以半分辨率运行此 pipeline,再通过 LTX2LatentUpsamplePipeline 进行空间上采样,然后以全分辨率再次运行此 pipeline,使用上采样后的槽位和 IC-LoRA 参考,最后对每个时间细化轮次运行 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

__call__

< >

( prompt: str | list[str] = Noneconditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneheight: int = 704width: int = 1216num_frames: int | None = Noneframe_rate: float = 24.0min_seconds: float = 1.0max_seconds: float = 20.0latents: typing.Optional[torch.Tensor] = Noneaudio_latents: typing.Optional[torch.Tensor] = Nonekeyframes_latents: typing.Optional[torch.Tensor] = Nonekeyframe_positions: list[int] | None = Nonereference_latents: typing.Optional[torch.Tensor] = Nonereference_downscale_factor: int = 2guidance_keyframe_latents: typing.Optional[torch.Tensor] = Noneguidance_keyframe_positions: list[int] | None = Noneguidance_keyframe_strength: float = 1.0generate_slots: bool = Truesigmas: list = [1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875]noise_scale: float | None = Nonefreeze_audio: bool = Falsevideo_tiles: list[diffusers.pipelines.ltx2.dfr_layout.LTX2DFREpilogueTile] | None = Nonenum_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneuse_cross_timestep: bool = Truesystem_prompt: str | None = Noneenable_prompt_enhancement: bool = Falseprompt_max_new_tokens: int | None = Noneprompt_enhancement_kwargs: dict[str, typing.Any] | None = Noneprompt_enhancement_seed: int = 10output_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 1024 ) → LTX2DFRPipelineOutput or tuple

参数

  • 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 根据 prompt 进行预测。必须满足 (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, 可选) — 用于重新去噪的原始 (batch_size, channels, frames, height, width) 视频潜变量(阶段 2 / 尾声)。
  • 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) — 对应 epilogue 路径。不是生成的槽位。
  • guidance_keyframe_positions (list[int],可选) — guidance_keyframe_latents 的像素帧索引。
  • guidance_keyframe_strength (float,可选,默认值为 1.0) — 固定引导关键帧的条件强度。
  • generate_slots (bool,可选,默认为 True) — 追加生成的关键帧槽位 token。Epilogue 会将此值设为 False,并改为固定 guidance_keyframe_latents。
  • sigmas (list[float],可选) — 本次迭代的噪声调度,不包含末尾的 0.0。
  • noise_scale (float, 可选) — 无条件 token 的起始噪声水平。默认值为 sigmas[0]。
  • freeze_audio (bool,可选,默认为 False) — 将音频固定在 sigma 0(用于尾声阶段,或跟随已冻结的第一阶段波形时)。
  • video_tiles (list[LTX2DFREpilogueTile], 可选) — 来自 epilogue_tiles() 的 Epilogue 分块,使得即使分辨率过大、无法在一次前向传播中处理,仍可对单个画布进行步进:每个步进针对每个 tile 运行一次 transformer,并融合预测结果。该配置会针对本次前向传播自身的 RoPE 坐标解析为 token 计划,因此传递的是布局而非计划——这些坐标只有在 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 或普通的 (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 或 tuple

如果 return_dict 为 True,则返回 LTX2DFRPipelineOutput,否则返回 (video, audio, keyframes, keyframe_positions) 的 tuple。

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

在 height × width 分辨率下执行一次去噪。在调用方组合各阶段:先以半分辨率运行本流水线,进行空间上采样,然后再次运行本流水线并传入 latents / keyframes_latents / reference_latents,最后对每个时间轮次使用 LTX2DFRTemporalRefinePipeline。

示例:

>>> import torch
>>> from diffusers import LTX2DFRPipeline
>>> from diffusers.utils import encode_video

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

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

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

denoise

< >

( latents: Tensorconditioning_mask: Tensorclean_latents: Tensorvideo_coords: Tensorkeyframes_mask: Tensorprompt_embeds: Tensoraudio_prompt_embeds: Tensorprompt_attention_mask: Tensorsigmas: listframe_rate: floataudio_latents: Tensorfreeze_audio: bool = Falsevideo_tile_plan: list | None = Nonegenerator: typing.Optional[torch.Generator] = Noneuse_cross_timestep: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Noneprogress_bar = Nonestep_offset: int = 0callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] | None = None )

参数

  • sigmas (list[float]) — 本次迭代的噪声调度,不包含末尾的 0.0。
  • freeze_audio (bool,可选,默认为 False) — 保持 audio_latents 处于干净状态(timestep/sigma 为 0,不执行 audio Euler step),同时仍然运行 audio-to-video 交叉注意力。当 audio_latents 为 None 时,此参数将被忽略。
  • video_tile_plan (list,可选) — 来自 video_tile_plan[~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan] 的每个 tile 的 token 计划。 如果提供了该参数,每个 step 都会针对每个 tile 运行一次 transformer 并融合其预测结果,因此采样器仍然在单个完整画布上执行 step,且所有 tile 在每个 step 中对重叠区域保持一致。
  • generator (torch.Generator, 可选) — 转发至 LTXEulerAncestralRFScheduler.step()。时间块会传入每个块的种子,以确保祖先采样不共享随机数流,也不消耗下一个块初始加噪所读取的状态。蒸馏版 Euler 不会读取该参数。
  • step_offset (int) — 该 pass 在流水线整体调度中首个 step 的索引,用于 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,并直接采用该 Euler 步。时间细化则换用 LTXEulerAncestralRFScheduler(eta=0.5);该步骤会对每个 token 重新加噪,因此之后需要再次应用条件混合,否则强度为 0.95 的接缝锚点会逐渐失效。

encode_conditions

< >

( conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | Noneheight: intwidth: intnum_frames: intdevice: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = Nonegenerator: typing.Optional[torch.Generator] = None )

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

每个条件返回 (pixel_frame_index, latent, strength, num_pixel_frames),可直接用于 prepare_latents() 的 condition_latents。编码与放置保持分离,因为时间细化轮次会按 2 ** round 缩放条件的位置,并按 tile 重新设定基准,不应为了这样做而对同一静态帧在每个 tile 中重复编码。

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

encode_prompt

< >

( prompt: str | list[str]num_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 1024device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • 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 调度,该调度经过训练,可在不使用 classifier-free guidance 的情况下使用,因此这里没有 negative branch。

enhance_prompt

< >

( prompt: strsystem_prompt: strmax_new_tokens: int | None = Noneseed: int = 10generator: typing.Optional[torch.Generator] = Nonegeneration_kwargs: dict[str, typing.Any] | None = Nonedevice: typing.Union[str, torch.device, NoneType] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None )

通过提示词增强器(一个 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

< >

( conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Nonecondition_latents: list[tuple[int, torch.Tensor, float, int]] | None = Nonekeyframe_latents: list[tuple[int, torch.Tensor, float]] | None = Noneslot_frame_indices: list[int] | None = Noneslot_initial_latents: typing.Optional[torch.Tensor] = Nonereference_latents: typing.Optional[torch.Tensor] = Nonereference_downscale_factor: int = 1batch_size: int = 1num_channels_latents: int = 128height: int = 512width: int = 768num_frames: int = 121frame_rate: float = 24.0noise_scale: float = 1.0dtype: typing.Optional[torch.dtype] = Nonedevice: typing.Optional[torch.device] = Nonegenerator: typing.Optional[torch.Generator] = Nonelatents: typing.Optional[torch.Tensor] = Nonelatents_normalized: bool = True ) → tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, slice | None]

参数

  • 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) 内容 在添加噪声之前写入 slot 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 用于索引打包序列中生成的关键帧槽位 token;若未请求任何槽位,则为 None。

为一次 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 将第一阶段半分辨率的潜在表示作为完全干净的 IC-LoRA 参考进行追加,并通过 reference_downscale_factor 对空间坐标进行缩放,使其映射到目标坐标空间。

附加的条件 token 将其内容存储在 clean_latents 中,并在 latents 中放置零占位符;而关键帧槽位则将其种子存储在 latents 中,并在 clean_latents 中放置零值——返回的 latents 是这两者的加噪混合结果(参见该方法末尾的加噪步骤)。

preprocess_conditions

< >

( conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneheight: int = 512width: int = 768num_frames: int = 121device: typing.Optional[torch.device] = None ) → Tuple[List[torch.Tensor], List[float], List[int], List[int]]

参数

  • 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

< >

( keyframe_latents: Tensordecode_timestep: floatdecode_noise_scale: floatseed: intdevice: devicedtype: dtype ) → torch.Tensor

参数

  • 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 方式,以两倍分辨率重新编码关键帧。

这些是精修轮次已经确定的帧,因此尾声阶段是接收这些帧,而不是要求它生成它们。将帧解码为像素,使用 Lanczos 放大 2 倍,然后再次编码,可以在保持帧内容的同时将其对齐到输出网格,这正是尾声阶段能够将其完全固定为干净状态的原因。

每个平面被解码为各自独立的单帧片段。由于 VAE 具有因果性,若采用堆叠解码,相邻平面之间会发生信息串扰——它们本质上是彼此独立的静态图像,而非一个序列。

trim_conditioning_sequence

< >

( start_frame: intsequence_num_frames: inttarget_num_frames: int ) → int

参数

  • start_frame (int) — 序列中第一帧的目标帧编号。
  • sequence_num_frames (int) — 序列中的帧数。
  • target_num_frames (int) — 生成视频的目标帧数。

返回值

int

更新后的序列长度

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

LTX2DFRTemporalRefinePipeline

类 diffusers.LTX2DFRTemporalRefinePipeline

< >

( scheduler: LTXEulerAncestralRFSchedulervae: AutoencoderKLLTX2Videoaudio_vae: AutoencoderKLLTX2Audiotext_encoder: transformers.models.gemma3.modeling_gemma3.Gemma3ForConditionalGeneration | transformers.models.gemma4_unified.modeling_gemma4_unified.Gemma4UnifiedForConditionalGenerationtokenizer: GemmaTokenizerconnectors: LTX2TextConnectorstransformer: LTX2VideoTransformer3DModelvocoder: diffusers.pipelines.ltx2.vocoder.LTX2Vocoder | diffusers.pipelines.ltx2.vocoder.LTX2VocoderWithBWEtemporal_latent_upsampler: LTX2LatentUpsamplerModel )

参数

  • scheduler (LTXEulerAncestralRFScheduler) — 采用 rectified-flow 参数化的 Ancestral Euler 调度器。构造时设置 eta=0.5 以匹配 DFR 时间配方。
  • vae (AutoencoderKLLTX2Video) — 变分自编码器(VAE)模型,用于将视频编码和解码为潜在表示。
  • audio_vae (AutoencoderKLLTX2Audio) — 用于编码和解码音频频谱图的音频 VAE。
  • text_encoder(Gemma3ForConditionalGeneration 或 Gemma4UnifiedForConditionalGeneration)—— 文本编码器模型。
  • tokenizer(GemmaTokenizer 或 GemmaTokenizerFast)—— 文本编码器的分词器。
  • connectors(LTX2TextConnectors)—— 用于将文本编码器的隐藏状态适配到视频和音频分支的文本连接器堆栈。
  • transformer (LTX2VideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
  • vocoder(LTX2Vocoder 或 LTX2VocoderWithBWE)—— 用于将梅尔频谱图转换为音频波形的声码器。
  • temporal_latent_upsampler (LTX2LatentUpsamplerModel) — 在轮次开始时应用的时间维度 2 倍潜在上采样器。

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

调度器为 LTXEulerAncestralRFScheduler(默认 eta=0.5)。第 1 阶段 / 第 2 阶段 / 空间后处理部分通过 LTX2DFRPipeline 继续使用 FlowMatchEulerDiscreteScheduler。每轮调用一次该 pipeline;由调用方循环执行 2x / 4x。

传入的 latents / keyframes_latents / audio_latents 为原始(未归一化)数据,与 LTX2Pipeline 保持一致。keyframe_positions 必须是上一轮返回的位置——在一轮运行结束后,无法从原始的 num_frames 重新推导出来。

__call__

< >

( prompt: str | list[str] = Nonelatents: Tensor = Nonekeyframes_latents: Tensor = Nonekeyframe_positions: list = Noneaudio_latents: Tensor = Noneconditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneheight: int = 704width: int = 1216num_frames: int = 121frame_rate: float = 24.0source_seconds: float | None = Nonecondition_num_frames: int | None = Noneround_index: int = 1sigmas: list = [0.975, 0.909375, 0.725, 0.421875]noise_scale: float | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneuse_cross_timestep: bool = Trueoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 1024 ) → LTX2DFRPipelineOutput or tuple

参数

  • prompt (str 或 List[str],可选) — 用于引导视频生成的提示词或提示词列表。如果未定义,则必须传入 prompt_embeds。
  • latents (torch.Tensor) — input 画布的原始视频潜变量,形状为 (batch_size, channels, frames, height, width)。
  • keyframes_latents (torch.Tensor) — 来自上一轮传递的原始关键帧 (batch_size, channels, K, height, width)。
  • keyframe_positions (list[int]) — keyframes_latents 在 输入 画布上的像素帧索引。
  • audio_latents (torch.Tensor) — 冻结的 stage-1 音频,已解包并去归一化。每个 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) — 输入的播放帧率。取整后将其翻倍。
  • 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 开始的轮次编号。瓦片将祖先噪声播种为 seed + 1000 * round_index + tile,并且条件会按 2 ** round_index 进行缩放。
  • sigmas (list[float],可选) — 本轮 tile 的蒸馏调度,不包含末尾的 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 或普通的 (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 或 tuple

如果 return_dict 为 True,则返回 LTX2DFRPipelineOutput,否则返回 (video, audio, keyframes, keyframe_positions) 的 tuple。

运行一轮时间细化。

示例:

>>> import torch
>>> from diffusers import LTX2DFRPipeline, LTX2DFRTemporalRefinePipeline, LTXEulerAncestralRFScheduler
>>> from diffusers.models.latent_upscaler import LTX2LatentUpsamplerModel

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

denoise

< >

( latents: Tensorconditioning_mask: Tensorclean_latents: Tensorvideo_coords: Tensorkeyframes_mask: Tensorprompt_embeds: Tensoraudio_prompt_embeds: Tensorprompt_attention_mask: Tensorsigmas: listframe_rate: floataudio_latents: Tensorfreeze_audio: bool = Falsevideo_tile_plan: list | None = Nonegenerator: typing.Optional[torch.Generator] = Noneuse_cross_timestep: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Noneprogress_bar = Nonestep_offset: int = 0callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] | None = None )

参数

  • sigmas (list[float]) — 本次迭代的噪声调度,不包含末尾的 0.0。
  • freeze_audio (bool,可选,默认为 False) — 保持 audio_latents 处于干净状态(timestep/sigma 为 0,不执行 audio Euler step),同时仍然运行 audio-to-video 交叉注意力。当 audio_latents 为 None 时,此参数将被忽略。
  • video_tile_plan (list,可选) — 来自 video_tile_plan[~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan] 的每个 tile 的 token 计划。 如果提供了该参数,每个 step 都会针对每个 tile 运行一次 transformer 并融合其预测结果,因此采样器仍然在单个完整画布上执行 step,且所有 tile 在每个 step 中对重叠区域保持一致。
  • generator (torch.Generator, 可选) — 转发至 LTXEulerAncestralRFScheduler.step()。时间块会传入每个块的种子,以确保祖先采样不共享随机数流,也不消耗下一个块初始加噪所读取的状态。蒸馏版 Euler 不会读取该参数。
  • step_offset (int) — 该 pass 在流水线整体调度中首个 step 的索引,用于 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,并直接采用该 Euler 步。时间细化则换用 LTXEulerAncestralRFScheduler(eta=0.5);该步骤会对每个 token 重新加噪,因此之后需要再次应用条件混合,否则强度为 0.95 的接缝锚点会逐渐失效。

encode_conditions

< >

( conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | Noneheight: intwidth: intnum_frames: intdevice: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = Nonegenerator: typing.Optional[torch.Generator] = None )

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

每个条件返回 (pixel_frame_index, latent, strength, num_pixel_frames),可直接用于 prepare_latents() 的 condition_latents。编码与放置保持分离,因为时间细化轮次会按 2 ** round 缩放条件的位置,并按 tile 重新设定基准,不应为了这样做而对同一静态帧在每个 tile 中重复编码。

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

encode_prompt

< >

( prompt: str | list[str]num_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 1024device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • 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 调度,该调度经过训练,可在不使用 classifier-free guidance 的情况下使用,因此这里没有 negative branch。

prepare_latents

< >

( conditions: list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Nonecondition_latents: list[tuple[int, torch.Tensor, float, int]] | None = Nonekeyframe_latents: list[tuple[int, torch.Tensor, float]] | None = Noneslot_frame_indices: list[int] | None = Noneslot_initial_latents: typing.Optional[torch.Tensor] = Nonereference_latents: typing.Optional[torch.Tensor] = Nonereference_downscale_factor: int = 1batch_size: int = 1num_channels_latents: int = 128height: int = 512width: int = 768num_frames: int = 121frame_rate: float = 24.0noise_scale: float = 1.0dtype: typing.Optional[torch.dtype] = Nonedevice: typing.Optional[torch.device] = Nonegenerator: typing.Optional[torch.Generator] = Nonelatents: typing.Optional[torch.Tensor] = Nonelatents_normalized: bool = True ) → tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, slice | None]

参数

  • 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) 内容 在添加噪声之前写入 slot 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 用于索引打包序列中生成的关键帧槽位 token;若未请求任何槽位,则为 None。

为一次 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 将第一阶段半分辨率的潜在表示作为完全干净的 IC-LoRA 参考进行追加,并通过 reference_downscale_factor 对空间坐标进行缩放,使其映射到目标坐标空间。

附加的条件 token 将其内容存储在 clean_latents 中,并在 latents 中放置零占位符;而关键帧槽位则将其种子存储在 latents 中,并在 clean_latents 中放置零值——返回的 latents 是这两者的加噪混合结果(参见该方法末尾的加噪步骤)。

preprocess_conditions

< >

( conditions: diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition | list[diffusers.pipelines.ltx2.pipeline_ltx2_condition.LTX2VideoCondition] | None = Noneheight: int = 512width: int = 768num_frames: int = 121device: typing.Optional[torch.device] = None ) → Tuple[List[torch.Tensor], List[float], List[int], List[int]]

参数

  • 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

< >

( start_frame: intsequence_num_frames: inttarget_num_frames: int ) → int

参数

  • start_frame (int) — 序列中第一帧的目标帧编号。
  • sequence_num_frames (int) — 序列中的帧数。
  • target_num_frames (int) — 生成视频的目标帧数。

返回值

int

更新后的序列长度

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

upsample_latents

< >

( latents: Tensorupsampler: LTX2LatentUpsamplerModel )

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

LTX2DFRPipelineOutput

类 diffusers.LTX2DFRPipelineOutput

< >

( frames: Tensoraudio: Tensorkeyframes: typing.Optional[torch.Tensor] = Nonekeyframe_positions: list[int] | None = None )

参数

  • 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" 时,或者当该路径未生成槽位时(例如分块后处理),值为 None。
  • keyframe_positions (list[int], 可选) — 本次处理画布上每个关键帧的像素帧索引;当 keyframes 为 None 时,该值为 None。经过时间维度处理后,这些索引无法从原始的 num_frames 重新推导得出,必须显式传入下一阶段。

DFR 管道的输出类。

LTX2LatentUpsamplePipeline

class diffusers.LTX2LatentUpsamplePipeline

< >

( vae: AutoencoderKLLTX2Videolatent_upsampler: LTX2LatentUpsamplerModel )

__call__

< >

( video: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneheight: int = 512width: int = 768num_frames: int = 121spatial_patch_size: int = 1temporal_patch_size: int = 1latents: typing.Optional[torch.Tensor] = Nonelatents_normalized: bool = Falsedecode_timestep: float | list[float] = 0.0decode_noise_scale: float | list[float] | None = Noneadain_factor: float = 0.0tone_map_compression_ratio: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = True ) → ~pipelines.ltx.LTXPipelineOutput or tuple

参数

  • 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) 的 patch 序列,也可以是 (batch_size, latent_channels, latent_frames, latent_height, latent_width) 的视频潜变量。
  • latents_normalized (bool,可选,默认为 False) — 如果提供了 latents,则指示 latents 是否已使用 VAE 的潜在均值和标准差进行归一化。如果 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 生成器,用于使生成过程具有确定性。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.ltx.LTXPipelineOutput 而不是普通元组。

返回值

~pipelines.ltx.LTXPipelineOutput 或 tuple

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

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

示例:

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

< >

( latents: Tensorreference_latents: Tensorfactor: float = 1.0 ) → torch.Tensor

参数

  • latents (torch.Tensor) — 需要归一化的输入潜变量
  • reference_latents (torch.Tensor) — 提供风格统计信息的参考潜变量。
  • factor (float) — 原始潜在表示与变换后潜在表示之间的混合因子。取值范围:-10.0 到 10.0,默认值:1.0

返回值

torch.Tensor

转换后的潜在张量

根据参考潜在张量的统计量,对潜在张量应用自适应实例归一化(AdaIN)。

tone_map_latents

< >

( latents: Tensorcompression: float )

参数

  • latents — torch.Tensor 任意形状的输入潜在张量。预期大致位于 [-1, 1] 或 [0, 1] 范围内。
  • compression — float 压缩强度,取值范围为 [0, 1]。
    • 0.0:无色调映射(恒等变换)
    • 1.0:完全压缩效果

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

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

LTX2VideoDiffusionDecodePipeline

class diffusers.LTX2VideoDiffusionDecodePipeline

< >

( diffusion_decoder: LTX2VideoDiffusionDecoderModelschedulervae: AutoencoderKLLTX2Video = None )

参数

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

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

__call__

< >

( latents: Tensorgenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str = 'pil'return_dict: bool = Truedenormalize: bool = True ) → LTX2VideoDecodeOutput or tuple

参数

  • 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

class diffusers.pipelines.ltx2.LTX2DurationHead

< >

( video_cross_attention_dim: int = 4096audio_cross_attention_dim: int = 2048pooler_hidden_dim: int = 256num_queries: int = 1num_pooler_heads: int = 4mlp_hidden_dim: int = 256 )

参数

  • 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 的隐藏层宽度。名称带有 _dim 后缀,以避免与 mlp_hidden 子模块发生冲突,否则 ConfigMixin.__getattr__ 会用此配置值遮蔽该子模块。

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

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

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

forward

< >

( video_tokens: typing.Optional[torch.Tensor] = Noneaudio_tokens: typing.Optional[torch.Tensor] = None ) → torch.Tensor of shape (batch_size,)

参数

  • video_tokens(形状为 (batch_size, seq_len, video_cross_attention_dim) 的 torch.Tensor,可选) — 视频连接器输出。
  • audio_tokens (torch.Tensor,形状为 (batch_size, seq_len, audio_cross_attention_dim),可选) — 音频连接器输出。

返回值

形状为 (batch_size,) 的 torch.Tensor

以秒为单位的预测时长。

predict_num_frames

< >

( video_tokens: typing.Optional[torch.Tensor] = Noneaudio_tokens: typing.Optional[torch.Tensor] = Noneframe_rate: floattemporal_compression_ratio: intmin_seconds: float = 1.0max_seconds: float = 20.0 ) → int

参数

  • video_tokens (torch.Tensor, 可选) — 单个提示词的视觉连接器输出。
  • 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)。

钳制在吸附之前应用:经过钳制的帧数不一定与网格对齐,因此如果先进行吸附,会得到不同的结果。由于吸附操作会向下取整,结果可能会低于最小值;当这种情况发生时,结果会向上吸附到下一个网格点,从而确保帧数保持在有效范围内。

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

LTX2PipelineOutput

class diffusers.pipelines.ltx2.LTX2PipelineOutput

< >

( frames: Tensoraudio: Tensor )

参数

  • 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

< >

( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )

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

LTX2AutoBlocks

class diffusers.LTX2AutoBlocks

< >

( )

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(或其列表),其视频被编码为额外的特征 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 的值会减慢运动,例如 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, 可选): 每个参考的 token 数量,顺序与 reference_conditions 一致。 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

class diffusers.LTX25ModularPipeline

< >

( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )

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

与 LTX2ModularPipeline 相同,区别在于其默认块使用扩散视频解码器进行解码,这是 LTX-2.5 及以后版本的默认设置。检查点通过 modular_model_index.json 路由到此。

LTX25AutoBlocks

类 diffusers.LTX25AutoBlocks

< >

( )

Auto blocks for LTX-2.5,支持文本生成视频、图像生成视频、条件生成视频以及上下文(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 的值会减慢运动,例如 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, 可选): 每个参考的 token 数量,顺序与 reference_conditions 一致。 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,optional): 去噪器的条件模型输入:例如 prompt_embeds, negative_prompt_embeds 等。 use_cross_timestep (bool,optional, 默认为 True): 是否将 transformer 条件化为独立的逐 token 交叉时间步(LTX-2.3+)。 attention_kwargs (dict,optional): 注意力处理器的额外关键字参数。 image_latents (Tensor,optional): 用于图生视频条件的 VAE 编码参考图像特征。 output_type (str,optional*, 默认为 pil): 输出格式:‘pil’、‘np’、‘pt’。

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

Update on GitHub