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 기반의 파운데이션 모델로, 단일 모델 내에서 동기화된 비디오와 오디오를 생성하도록 설계되었습니다. 최신 비디오 생성의 핵심 구성 요소를 통합했으며, 오픈 웨이트를 제공하며 실용적인 로컬 실행에 초점을 맞추고 있습니다.

모든 원본 LTX-Video 체크포인트는 Lightricks 조직에서 찾을 수 있습니다.

LTX-2의 원본 코드베이스는 여기에서 찾을 수 있습니다.

2단계 생성

공유되는 LTX2Pipeline / LTX2ImageToVideoPipeline의 __call__ 기본값은 LTX-2.5 레퍼런스와 일치합니다(num_inference_steps=30; duration_head가 존재하는 경우 num_frames는 선택 사항이며, 그렇지 않으면 121로 대체됩니다). 아래 예제는 LTX-2.0/2.3에도 동일한 기본값을 사용합니다.

프로덕션 품질의 생성을 달성하기 위한 권장 파이프라인입니다. 이 파이프라인은 두 단계로 구성됩니다:

  • Stage 1: classifier-free guidance(CFG)를 사용한 diffusion sampling으로 목표 해상도의 비디오를 생성합니다. 이 단계에서는 텍스트/이미지 조건을 준수하는 일관된 저노이즈 비디오 시퀀스를 생성합니다.
  • Stage 2: Stage 1의 출력을 2배로 업샘플링하고, 디스틸된 LoRA 모델을 사용하여 세부 사항을 정제하여 충실도와 시각적 품질을 향상시킵니다. Stage 2에서는 Stage 1의 구조를 유지하면서 텍스처와 선명도를 강화하기 위해 더 가벼운 CFG를 적용할 수 있습니다.

text-to-video 2단계 파이프라인의 사용 예시

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

디스틸드 체크포인트 생성

디스틸된 체크포인트를 사용하는 가장 빠른 2단계 생성 파이프라인.

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를 사용하여 임의의 latent 인덱스에서 이미지 및/또는 비디오 조건을 지정할 수 있습니다. 예를 들어, 첫 번째 프레임과 마지막 프레임 조건을 모두 지정하여 first-last-frame-to-video(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",
)

조건부가 잠재 프레임(latent frames)을 통해 수행되므로, 이미지 조건에 대해 지정된 잠재 프레임에 해당하는 8개의 데이터 공간 프레임은 정적인 경향이 있습니다.

멀티모달 가이드

LTX-2.X 파이프라인은 멀티모달 가이던스를 지원합니다. 세 가지 항으로 구성되며, 모두 CFG 스타일의 업데이트 규칙을 사용합니다:

  1. Classifier-Free Guidance (CFG): 교란된(“더 약한”) 출력을 negative prompt를 사용하여 생성하는 표준 CFG입니다.
  2. Spatio-Temporal Guidance (STG): STG는 self-attention 연산을 단축하여 생성된 교란된 출력에서 벗어나, 대신 attention 값을 대입합니다. 이를 통해 더 선명한 비디오와 더 나은 시공간적 일관성을 만드는 것이 핵심 아이디어입니다.
  3. Modality Isolation Guidance: 크로스 모달리티(오디오-비디오 및 비디오-오디오) 크로스 어텐션을 비활성화하여 생성된 교란된 출력에서 벗어나도록 합니다. 이 가이던스는 LTX-2.X 모델에 더 구체적으로 적용되며, 이를 통해 생성된 오디오와 비디오 간의 일관성이 향상된다는 아이디어에 기반합니다.

이 값들은 guidance_scale, stg_scale, modality_scale 인자로 제어되며, 비디오와 오디오에 대해 각각 별도로 설정할 수 있습니다. 또한 STG의 경우, self-attention이 건너뛰어지는 transformer 블록 인덱스를 spatio_temporal_guidance_blocks 인자를 통해 지정해야 합니다. LTX-2.X 파이프라인은 guidance scale이 높은 값으로 설정될 때 발생할 수 있는 과노출 문제를 완화하기 위해 guidance rescaling도 지원합니다.

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 모델)를 사용해 제공된 프롬프트를 강화하는 프롬프트 강화(Prompt Enhancement)를 사용하면 샘플 품질을 향상시킬 수도 있습니다. 프롬프트 강화를 사용하려면 선택적 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 등의 클래스를 재사용하며, 이를 위한 별도의 파이프라인 클래스는 없습니다. 사용자가 인지할 수 있는 차이는 텍스트 인코더입니다. LTX-2.5는 Gemma 3 대신 Gemma 4(gemma4_unified) 체크포인트와 함께 사용됩니다. 변환된 LTX-2.5 체크포인트에 대해 from_pretrained를 호출하면(transformers의 Auto* 클래스를 통해) 자동으로 로드되므로 추론 시점에 추가 설정이 필요하지 않습니다. LTX-2.3 저장소 대신 LTX-2.5 저장소를 from_pretrained에 지정하기만 하면 됩니다.

Lightricks/LTX-2.5-Diffusers에는 두 가지 transformer가 함께 제공됩니다. model_index.json가 가리키는 transformer/에 있는 distilled DiT와, 명시적으로 로드해야 하는 transformer_full/에 있는 full/SFT DiT입니다(자세한 내용은 Full / SFT transformer 섹션을 참고하세요). 저장소의 scheduler/는 distilled checkpoint에 맞게 구성되어 있으며(use_dynamic_shifting=False, shift_terminal=None), 제공된 그대로 sigma schedule이 사용되도록 설정되어 있습니다. two-stage generation에 필요한 모든 것도 함께 제공됩니다: latent_upsampler/ 하위 폴더와 저장소 루트에 있는 stage 2 distilled LoRA인 ltx-2.5-22b-distilled-lora-450-bf16.safetensors입니다.

Distilled inference는 단계 수가 아닌 명시적인 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의 2단계 생성

LTX-2.5는 두 단계 변형을 모두 지원하며, DISTILLED_SIGMA_VALUES / STAGE_2_DISTILLED_SIGMA_VALUES는 해당 참조 스케줄입니다:

  • 양단계 모두에 대한 증류된 체크포인트 — 기본 transformer/의 레퍼런스 레시피이며, 아래에 표시된 것입니다. 트랜스포머가 이미 증류되었으므로 2단계 LoRA는 포함되지 않으며, 이는 LTX-2.5 가중치를 사용한 증류된 체크포인트 생성입니다.
  • Full/SFT stage 1 + distilled LoRA stage 2 — 이 페이지 상단에 설명된 Two-stages Generation을 transformer_full/와 함께 제공되는 LoRA를 사용하여 수행합니다. 변경되는 내용은 아래를 참조하세요.

Stage 1은 목표 해상도의 절반에서 실행되고, upsampler가 이를 두 배로 늘리며, stage 2는 전체 해상도에서 정밀도를 높입니다 — 비디오 및 오디오 모두 stage 1의 latents에서 noise_scale=STAGE_2_DISTILLED_SIGMA_VALUES[0]로 재시드됩니다. Stage 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",
)

길이가 명시적인 num_frames가 아니라 duration head에서来的时候, stage 2가 실행되기 전에 stage 1이 결정하고 그 latents([B, C, F, H, W])에서 실제 길이를 복원하도록 하세요. 두 번째로 예측하는 대신:

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

증류된 LoRA를 사용한 Stage 2

대신 Two-stages Generation를 실행하려면 — 1단계에는 full/SFT DiT, 2단계에는 distilled LoRA를 사용 — Full / SFT transformer와 동일한 방식으로 파이프라인을 구성하고 해당 guidance stack으로 1단계 latents를 생성합니다. 이후 LTX-2.0/2.3과 두 가지가 다릅니다. LoRA는 원래 가중치와 함께 있는 것이 아니라 diffusers 저장소 자체에 위치하며, 스케줄러의 방향이 반대입니다. LTX-2.5는 distilled 스케줄러 구성을 제공하므로, 1단계에서 dynamic shifting이 켜지고 2단계에서 다시 꺼집니다.

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 호출 자체는 위의 distilled 레시피와 동일합니다: sigmas=STAGE_2_DISTILLED_SIGMA_VALUES, noise_scale, guidance_scale=1.0가 모두 같으며, stage 2는 어쨌든 distilled 모델을 실행하기 때문입니다.

합성곱 및 확산 디코딩

LTX-2.5는 동일한 잠재 공간(latent space)을 공유하는 두 개의 비디오 디코더를 제공하므로, 잠재 변수(latents)는 두 디코더 간에 상호 교환 가능합니다:

  • vae/ — 합성곱 VAE(AutoencoderKLLTX2Video). 파이프라인이 디코딩하는 데 사용하는 모델로, 위 스니펫 모두 이미 이를 사용하고 있습니다. 두 모델 중 타일링(pipe.vae.enable_tiling())을 지원하는 유일한 모델이며, 이는 일반적으로 고해상도를 처리할 수 있게 해 주는 기능입니다.
  • diffusion_decoder/ — LTX2VideoDiffusionDecoderModel. 이는 파이프라인 구성 요소가 아닌 자체적인 diffusion 모델이므로 vae로 전달되지 않습니다. output_type="latent"로 파이프라인을 실행한 후, latents를 LTX2VideoDiffusionDecodePipeline에 전달하세요.

인코딩은 항상 vae/를 통해 이루어지므로 이미지 및 비디오 조건화는 선택에 영향을 받지 않습니다.

diffusion decoder로 디코딩할 때 두 가지가 달라집니다. output_type="latent"는 vocoder도 건너뛰므로 오디오가 latents로 반환되며 수동으로 마무리해야 하고, 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",
)

이것을 2단계 생성과 결합하려면, 2단계에서 output_type="latent"를 요청하고 이를 디코딩하세요.

decoder.enable_tiling()은 고해상도 디코딩을 메모리에 유지하는 역할을 하며, 이는 pipe.vae.enable_tiling()이 합성곱 VAE에서 수행하는 방식과 동일합니다. 디코딩에서 메모리 사용량이 가장 큰 부분인 마지막 업샘플링 단계와 디퓨전 단계는 오버랩되는 타일 위에서 실행된 후 다시 블렌딩되어 결합되므로, 피크 메모리는 비디오 크기가 아닌 타일 크기로 제한됩니다. Tiling은 latent가 하나의 타일을 초과할 때만 활성화되며, 타일 및 오버랩 크기는 tile_sample_min_* / tile_sample_stride_* 인수를 통해 조정할 수 있습니다(기본값은 참조 구현과 일치합니다). 디퓨전 단계가 각 타일을 개별적으로 디노이즈하기 때문에, 타일링된 디코딩은 타일링되지 않은 결과와 정확히 동일하지 않습니다.

단일 카드에서는 디코딩 전에 파이프라인을 다른 곳으로 이동하는 것도 가치가 있습니다(pipe.scheduler와 보코더의 output_sampling_rate를 캡처한 후 pipe.to("cpu") 및 torch.cuda.empty_cache()를 호출). 디코더는 자체적인 여유 공간이 필요하기 때문입니다. 어텐션 백엔드, 타일링 세부 사항 및 디코더의 나머지 동작에 대해서는 LTX2VideoDiffusionDecoderModel을 참조하세요.

Full / SFT transformer

transformer_full/은 model_index.json에 참조되지 않으므로 명시적으로 로드해야 합니다. 또한 다른 스케줄러와 실제 가이던스 스택이 필요합니다. 포함된 scheduler/는 증류된 체크포인트용으로 설정되어 있으며, 가이던스 기본값은 LTX-2.0 시대의 범용 설정으로, 아무런 오류를 발생시키지 않으면서도 LTX-2.5 SFT 실행이 눈에 띄게 가이던스가 부족하게 됩니다. Multimodal Guidance 권장 사항은 여기에도 그대로 적용되며, 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 체크포인트에는 transformer가 조건으로 사용하는 동일한 텍스트 커넥터 출력으로부터 설명된 샷의 길이를 예측하는 작은 duration_head가 포함되어 있습니다. 로드된 파이프라인에 이 헤드가 있는 경우, 기본적으로 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이 아닙니다. 가장 가까운 그리드 점이 사용되고 경고가 기록되므로, 반환된 길이가 이러한 좁은 범위를 약간 벗어날 수 있습니다.

비디오를 생성하지 않고 예측을 검사하려면 헤드를 직접 호출하세요. 필요한 모든 것이 공개되어 있습니다:

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는 모든 비디오 토큰을 초 단위의 시간 축에 배치하며, 이 축은 기본적으로 재생 속도인 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로 로드되어 모션 제어 기능이 전혀 제공되지 않습니다. 모델 카드에서는 LoRA 강도 1.0에서 1.0, 0.5, 0.2, 0.1, 0.05, 0.025의 속도를 권장합니다. 프롬프트에서 속도 관련 단어(“slow motion”, “high fps”)를 제외하고, 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프레임(24fps 기준 약 5초) 길이이며, 움직임의 속도만 달라집니다. 2단계 생성에서는 두 단계 모두에 동일한 motion_speed를 전달해야 합니다. 2단계는 비디오를 다시 디노이즈하며, 실시간 축에서 실행되면 슬로 모션 효과가 사라집니다. 참조 드라이버는 두 패스가 공유하는 단계 객체를 래핑하여 동일한 동작을 수행합니다.

motion_speed는 LTX-2 / LTX-2.5 모듈 블록의 입력이기도 하며, 모듈형 파이프라인에도 동일한 방식으로 전달됩니다.

LTX-2.5 모듈형

LTX-2.5는 모듈형 파이프라인으로도 사용할 수 있습니다. 기본 블록셋은 diffusion decoder를 사용하며, num_frames가 생략된 경우 비디오 길이를 예측합니다. guider와 audio_guider 구성 요소를 통해 비디오와 오디오에 각각 guidance를 적용합니다. 사용 가능한 guidance 매개변수는 LTX2Guidance를 참고하세요. 기본적으로 모듈형 파이프라인은 google/gemma-4-E2B-it 저장소에서 prompt enhancer와 processor를 다운로드합니다. 아래는 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",
)

각 블록셋의 문서(예: LTX2AutoBlocks, LTX25AutoBlocks)에서 지원되는 워크플로를 확인할 수 있습니다.

LTX-2.5용 Diffusion Fidelity Rendering(DFR)

LTX2DFRPipeline는 실제 실행 시간을 디테일 충실도로 교환합니다. 각 __call__은 height × width 해상도로 단일 디노이즈 패스를 수행합니다. 이 패스는 비디오와 추가 단일 픽셀 프레임 키프레임 슬롯을 생성하거나, 해당 슬롯에서 시드된 제공된 레이턴트를 다시 디노이즈합니다. 호출자는 다른 LTX 2단계 파이프라인과 동일한 방식으로 단계를 구성합니다. 즉, 이 파이프라인, LTX2LatentUpsamplePipeline, 다시 이 파이프라인, 그리고 각 시간 라운드마다 LTX2DFRTemporalRefinePipeline을 호출합니다.

슬롯은 픽셀 프레임 하나를 얻기 위해 토큰의 완전한 잠재 프레임 하나를 소모하며, 이는 해당 위치의 유효 시간 압축을 완화합니다. 따라서 주변 비디오는 보간된 프레임이 아닌 실제로 새로운 프레임에 조건부화됩니다. 슬롯 위치는 VAE의 시간 경계(요청을 덜 패딩하는 24 또는 32 픽셀 프레임 중 하나)에 정렬된 세그먼트 그리드에서 가져옵니다. 캔버스는 내부적으로 세그먼트의 정수 배로 패딩되며, output_type="latent"는 패딩된 그리드를 반환하여 패딩에 있는 슬롯이 제거되지 않도록 합니다. VAE 디코딩 전에 trim_canvas로 트리밍하세요.

use_keyframes_abs_pos_embedding를 설정하는 config를 가진 transformer가 필요합니다. 이 설정은 단일 픽셀 프레임의 latents를 학습된 embedding으로 표시합니다. LTX-2.5 체크포인트에는 해당 설정이 포함되어 있으며, 파이프라인은 해석할 수 없는 토큰에 토큰 예산을 소모하기보다 더 오래된 버전에서 예외를 발생시킵니다.

추가 토큰에 대한 예산을 계획하세요: 각 슬롯은 하나의 잠재 프레임 분량만큼을 추가하므로, 2단계는 동등한 2단계 증류 패스보다 더 긴 시퀀스를 실행합니다 — 1024x1536 / 121 프레임에서 +31% (24576 -> 32256 토큰, 24프레임 세그먼트 그리드에서 5개 슬롯). 피크 활성화 메모리는 이에 따라 확장되므로, 일반 증류 레시피에 간신히 맞는 해상도의 경우 DFR 환경에서 enable_sequential_cpu_offload, vae.enable_tiling(), 또는 더 작은 캔버스가 필요할 수 있습니다.

Composition은 keyframes와 keyframe_positions에 대해 return_dict=True를 사용합니다(return_dict=False는 동일한 네 필드를 튜플로 반환합니다).

아래의 전체 레시피는 시작점으로 적합합니다: 1088×1920 이미지-투-비디오, x2 시간적 리파인 라운드 1회, 그리고 2단계에서 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는 최종 출력이 아니라 해당 패스의 값입니다. 1단계는 1080p 캔버스의 절반 크기인 544×960에서, 2단계는 1088×1920에서 실행됩니다. 각 패스의 크기는 VAE의 공간 압축 비율(단일 패스인 경우 LTX-2.5에서 32, 1단계가 1080p의 절반인 경우 64)로 나누어떨어져야 합니다. 이것이 1080p가 1920×1088이고 4K가 3840×2176인 이유입니다. 각 패스는 고정된 증류 스케줄(sigmas)을 실행하므로 num_inference_steps가 없습니다. 증류 스케줄은 가이던스 없이 학습되었기 때문에 negative_prompt나 guidance_scale도 없습니다. 포함된 오디오는 1단계의 것입니다. 이후 패스에서도 비디오 브랜치가 크로스 모달 어텐션을 수행할 수 있도록 오디오 스트림이 실행되지만, 웨이브폼 자체는 1단계 이후에 정제되지 않습니다.

공간 디테일링. 2x 공간 디테일링 IC-LoRA를 1단계 이후에 이름이 지정된 어댑터로 로드하고, 2단계에서만 활성화합니다(set_adapters(["detailing"], adapter_weights=[0.5])). 그러면 2단계는 1단계의 반해상도 latent를 reference_latents로 참조합니다. 1단계와 시간적 라운드는 어댑터가 꺼진 상태로 실행됩니다. 1단계 전에 LoRA를 로드한 경우, transformer.disable_adapters()로 이를 끄고, set_adapters는 이를 다시 켜지 않습니다 — 2단계 전에 transformer.enable_adapters()를 호출하거나, 레시피와 같이 1단계 후에 가중치를 로드하세요. reference_downscale_factor(기본값 2)는 참조 토큰의 공간 좌표를 대상의 좌표 공간으로 스케일링합니다.

시간적 정제. LTX2DFRTemporalRefinePipeline는 한 라운드를 수행합니다. 시간적 업샘플링, 키프레임 이음새에서의 타일링, LTXEulerAncestralRFScheduler(eta=0.5)를 사용한 선조 노이즈 제거, 후속 타일의 리드인을 제거하여 스티칭, 그리고 캐리 키프레임 백을 병합하는 과정입니다. 해당 스케줄러는 직접 구성해야 합니다. 결정적 단계는 완주하여 더 부드러운 캔버스만 반환하기 때문에, 다른 스케줄러를 사용하면 라운드가 거부됩니다. 라운드당 파이프라인을 한 번씩 호출하고, 2x / 4x를 위해 round_index를 전달하며 루프를 실행합니다. 라운드 이후에는 keyframe_positions를 원래의 num_frames에서 다시 유도할 수 없으므로, 반드시 그대로 전달해야 합니다. 각 타일에는 해당 재생 윈도우를 덮는 동결된 1단계 오디오의 슬라이스가 전달됩니다. source_seconds는 1단계의 길이이며 라운드 간에 고정되므로, 후속 라운드에서는 기본값을 사용하는 대신 명시적으로 전달해야 합니다.

muxing과 무관하게, 재생이 30을 초과하는 경우 Conditioning fps는 항상 60입니다. RoPE 시간은 pixel_frame / fps이므로, 120 fps 시간 기준은 학습된 분포에 비해 모든 토큰의 시간 범위를 절반으로 줄이고, 48 fps는 이를 늘립니다. 두 경우 모두 60이라고 거짓말하고 재생 속도로 디코딩된 프레임을 취급합니다.

세 번째 공간 단계. 이를 구성합니다. 네 번째 파이프라인은 없습니다. 비디오만 공간적으로 업샘플링하고, RGB에서 carry keyframes를 재구성합니다(decode → Lanczos ×2 → rebuild_epilogue_keyframes()를 통해 encode; epilogue keyframes는 절대 latent-upsample하지 않음), 그리고 다음을 수행합니다:

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

두 축은 서로 다른 방식으로 봉합됩니다. 공간 경계의 어느 쪽에도 알려진 답이 없으므로, 해당 겹침 부분은 사다리꼴 가중치를 사용하여 혼합됩니다. 시간 타일은 마지막 refine 라운드의 keyframe 봉합선을 기준으로 잘립니다.

Diffusion decoder를 사용한 디코딩. 최대 수준의 디테일 충실도를 위해 output_type="latent"를 유지하고, (이미 정규화 해제되고, 필요 시 trim_canvas가 적용된) latents를 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와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLLTXVideo) — 잠재 표현으로 이미지를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • text_encoder (T5EncoderModel) — 구체적으로 google/t5-v1_1-xxl 변형을 사용하는 T5입니다.
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 클래스의 두 번째 토크나이저.
  • 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 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다.
  • timesteps (list[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 선택 사항, 기본값 4.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다. guidance_scale은 Imagen Paper의 방정식 2의 w로 정의됩니다. guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 보통 이미지 품질이 낮아지는 대가를 치릅니다. 비디오 모달리티에 사용됩니다(오디오 모달리티에는 별도의 값 audio_guidance_scale이 있습니다).
  • stg_scale (float, 선택 사항, 기본값 0.0) — Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling에서 제안한 Spatio-Temporal Guidance(STG)를 위한 비디오 가이던스 스케일입니다. 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인 경우, video 값인 guidance_rescale를 기본값으로 사용합니다.
  • spatio_temporal_guidance_blocks (list[int], 선택 사항, 기본값 None) — STG를 적용할 transformer 블록의 0부터 시작하는 인덱스입니다. STG를 사용하는 경우(stg_scale 또는 audio_stg_scale이 0보다 큰 경우) 반드시 제공해야 합니다. LTX-2.0에는 [29]를, LTX-2.3에는 [28]를 권장합니다.
  • noise_scale (float, 선택 사항, 기본값 0.0) — 각 timestep에서 랜덤 노이즈와 디노이즈된 latents 사이의 보간 계수입니다. 디노이징을 계속하기 전에 latents와 audio_latents에 노이즈를 적용합니다.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 비디오의 수입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 비디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • audio_latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 오디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • negative_prompt_attention_mask (torch.FloatTensor, 선택 사항) — 부정 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • decode_timestep (float, 기본값 0.0) — 생성된 비디오가 디코딩되는 timestep입니다.
  • decode_noise_scale (float, 기본값 None) — 디코드 타임스텝에서 랜덤 노이즈와 디노이즈된 레이턴트 사이의 보간 계수입니다.
  • use_cross_timestep (bool 선택 사항, 기본값 True) — 크로스 어텐션 모듈레이션 매개변수를 계산할 때 크로스 모달리티(영상의 크로스 모달리티는 오디오이며, 그 반대도 성립) 시그마를 사용할지 여부입니다. 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) — 프롬프트 강화 수행 시 생성할 최대 토큰 수입니다. 지정되지 않으면 전용 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, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • 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이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

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 )

prompt를 입력받아 프롬프트 강화기(Gemma 조건 생성 모델)와 시스템 프롬프트를 활용하여 새로운 프롬프트를 생성하여 강화합니다. image가 제공되면, 해당 참조 프레임에도 조건을 부여하여 강화합니다(I2V/키프레임 스타일 강화). 구성된 전용 prompt_enhancer 구성 요소가 있으면 이를 사용합니다(예: 강화용으로 학습되지 않은 텍스트 인코더를 가진 LTX-2.5). 그렇지 않으면 메인 text_encoder(자체 강화기로도 기능하는 LTX-2.0/2.3)로 대체합니다.

메시지 템플릿, 디코딩 kwargs, 응답 정제, 이미지 긴 변 준비는 ltx-core / ltx-pipelines의 enhance_t2v / enhance_i2v / generate_enhanced_prompt와 일치합니다.

LTX2ImageToVideoPipeline

클래스 diffusers.LTX2ImageToVideoPipeline

< >

( 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 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다.
  • timesteps (List[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 선택 사항, 기본값 4.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다. guidance_scale은 Imagen Paper의 방정식 2의 w로 정의됩니다. guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 보통 이미지 품질이 낮아지는 대가를 치릅니다. 비디오 모달리티에 사용됩니다(오디오 모달리티에는 별도의 값 audio_guidance_scale이 있습니다).
  • stg_scale (float, 선택 사항, 기본값 0.0) — Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling에서 제안한 Spatio-Temporal Guidance(STG)를 위한 비디오 가이던스 스케일입니다. 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인 경우, video 값인 guidance_rescale를 기본값으로 사용합니다.
  • spatio_temporal_guidance_blocks (list[int], 선택 사항, 기본값 None) — STG를 적용할 transformer 블록의 0부터 시작하는 인덱스입니다. STG를 사용하는 경우(stg_scale 또는 audio_stg_scale이 0보다 큰 경우) 반드시 제공해야 합니다. LTX-2.0에는 [29]를, LTX-2.3에는 [28]를 권장합니다.
  • noise_scale (float, 선택 사항, 기본값 0.0) — 각 timestep에서 랜덤 노이즈와 디노이즈된 latents 사이의 보간 계수입니다. 디노이징을 계속하기 전에 latents와 audio_latents에 노이즈를 적용합니다.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 비디오의 수입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 비디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • audio_latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 오디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • negative_prompt_attention_mask (torch.FloatTensor, 선택 사항) — 부정 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • decode_timestep (float, 기본값 0.0) — 생성된 비디오가 디코딩되는 timestep입니다.
  • decode_noise_scale (float, 기본값 None) — 디코드 타임스텝에서 랜덤 노이즈와 디노이즈된 레이턴트 사이의 보간 계수입니다.
  • use_cross_timestep (bool 선택 사항, 기본값 True) — 크로스 어텐션 모듈레이션 매개변수를 계산할 때 크로스 모달리티(영상의 크로스 모달리티는 오디오이며, 그 반대도 성립) 시그마를 사용할지 여부입니다. 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) — 프롬프트 강화 수행 시 생성할 최대 토큰 수입니다. 지정되지 않으면 전용 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, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • 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이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> 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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

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 )

prompt를 입력받아 프롬프트 강화기(Gemma 조건 생성 모델)와 시스템 프롬프트를 활용하여 새로운 프롬프트를 생성하여 강화합니다. 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 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다.
  • timesteps (List[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 선택 사항, 기본값 4.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다. guidance_scale은 Imagen Paper의 방정식 2의 w로 정의됩니다. guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 보통 이미지 품질이 낮아지는 대가를 치릅니다. 비디오 모달리티에 사용됩니다(오디오 모달리티에는 별도의 값 audio_guidance_scale이 있습니다).
  • stg_scale (float, 선택 사항, 기본값 0.0) — Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling에서 제안한 Spatio-Temporal Guidance(STG)를 위한 비디오 가이던스 스케일입니다. 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인 경우, video 값인 guidance_rescale를 기본값으로 사용합니다.
  • spatio_temporal_guidance_blocks (list[int], 선택 사항, 기본값 None) — STG를 적용할 transformer 블록의 0부터 시작하는 인덱스입니다. STG를 사용하는 경우(stg_scale 또는 audio_stg_scale이 0보다 큰 경우) 반드시 제공해야 합니다. LTX-2.0에는 [29]를, LTX-2.3에는 [28]를 권장합니다.
  • noise_scale (float, 선택 사항, 기본값 None) — 각 timestep에서 랜덤 노이즈와 디노이즈된 latents 사이의 보간 계수입니다. 디노이징을 계속하기 전에 latents와 audio_latents에 노이즈를 적용합니다. 설정되지 않으면 sigma schedule에서 추론됩니다.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 비디오의 수입니다.
  • generator (torch.Generator 또는 List[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 비디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • audio_latents (torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링하여 생성된 노이즈가 포함된 사전 생성된 latents로, 오디오 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 무작위 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • negative_prompt_attention_mask (torch.FloatTensor, 선택 사항) — 부정 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • decode_timestep (float, 기본값 0.0) — 생성된 비디오가 디코딩되는 timestep입니다.
  • decode_noise_scale (float, 기본값 None) — 디코드 타임스텝에서 랜덤 노이즈와 디노이즈된 레이턴트 사이의 보간 계수입니다.
  • use_cross_timestep (bool 선택 사항, 기본값 True) — 크로스 어텐션 모듈레이션 매개변수를 계산할 때 크로스 모달리티(영상의 크로스 모달리티는 오디오이며, 그 반대도 성립) 시그마를 사용할지 여부입니다. 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) — 프롬프트 강화 수행 시 생성할 최대 토큰 수입니다. 지정되지 않으면 전용 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, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • 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이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> 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] 형태의 초기 패킹(패치화)된 latents.
  • conditioning_mask (torch.Tensor) — [0, 1] 범위의 값을 가지며, 0은 denoising 모델의 출력이 완전히 사용됨을, 1은 조건이 완전히 사용됨을 의미하는 [batch_size, patch_seq_len, 1] 형태의 초기 packed (patchified) conditioning mask입니다.

반환값

Tuple[torch.Tensor, torch.Tensor, torch.Tensor]

다음과 같은 3개의 텐서 튜플을 반환합니다:

  1. 첫 프레임 조건이 적용된 패킹된 비디오 잠재 변수입니다.
  2. 첫 프레임 강도가 적용된 패킹된 조건화 마스크.
  3. 첫 번째 프레임 위치의 깨끗한 조건부 잠재 변수(나머지 위치는 0).

first-frame 위치의 토큰을 덮어써서 첫 프레임 시각 조건화를 적용합니다.

여기서는 latent_idx == 0인 조건만 적용됩니다(참조 구현의 VideoConditionByLatentIndex와 일치). 0이 아닌 latent 인덱스에 있는 조건은 prepare_keyframe_extras를 통해 별도의 keyframe 토큰으로 추가되며(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 device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

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 )

prompt를 입력받아 프롬프트 강화기(Gemma 조건 생성 모델)와 시스템 프롬프트를 활용하여 새로운 프롬프트를 생성하여 강화합니다. 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 )

noisy video latents를 준비하고, 프레임 조건을 적용합니다.

첫 프레임 조건(latent_idx == 0)은 첫 프레임 위치의 토큰을 덮어쓰는 방식으로 적용됩니다(VideoConditionByLatentIndex 의미론). 첫 프레임이 아닌 조건(latent_idx > 0)은 토큰별 conditioning_mask = strength를 사용하여(VideoConditionByKeyframeIndex 의미론) 메인 latent 시퀀스에 연결됩니다. 이후 디노이징 루프의 기존 timestep 공식 t * (1 - conditioning_mask)와 후처리 블렌딩 denoised * (1 - conditioning_mask) + clean * conditioning_mask이 이를 단계별로 처리합니다.

4-튜플을 반환합니다:

  • latents: 패킹된 노이저티드 레이턴트(베이스 토큰 + 시퀀스 차원에 cat된 모든 키프레임 토큰).
  • conditioning_mask: [0, 1] 범위의 값으로 구성된 packed conditioning mask — 첫 번째 프레임 위치에는 1, keyframe 위치에는 strength, 그 외에는 0.
  • clean_latents: 조건부 위치의 clean condition 값(나머지 위치는 0); latents와 동일한 shape.
  • 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]]

다음과 같이 len(conditions) 길이의 리스트 4개로 구성된 4-tuple을 반환합니다:

  1. 첫 번째 목록은 [batch_size=1, num_channels, num_frames, height, width] 모양의 전처리된 비디오 텐서 목록입니다.
  2. 두 번째 목록은 조건화 강도(conditioning strengths)의 목록입니다.
  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

클래스 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) — 인코딩된 비디오 latents의 노이즈를 제거하기 위해 transformer와 함께 사용되는 스케줄러입니다.
  • vae (AutoencoderKLLTX2Video) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • audio_vae (AutoencoderKLLTX2Audio) — 오디오 스펙트로그램을 인코딩 및 디코딩하는 오디오 VAE입니다.
  • text_encoder (Gemma3ForConditionalGeneration 또는 Gemma4UnifiedForConditionalGeneration) — 텍스트 인코더 모델입니다.
  • tokenizer (GemmaTokenizer 또는 GemmaTokenizerFast) — 텍스트 인코더용 토크나이저.
  • connectors (LTX2TextConnectors) — 비디오 및 오디오 브랜치를 위해 텍스트 인코더의 히든 상태를 적응시키기 위해 사용되는 텍스트 커넥터 스택입니다.
  • transformer (LTX2VideoTransformer3DModel) — 인코딩된 비디오 잠재 변수를 디노이즈하기 위한 조건부 Transformer 아키텍처.
  • vocoder (LTX2Vocoder 또는 LTX2VocoderWithBWE) — 멜 스펙트로그램을 오디오 웨이브폼으로 변환하는 Vocoder.
  • processor (ProcessorMixin, 선택 사항) — 프롬프트 강화용 채팅 템플릿팅에 사용되는 프로세서입니다.
  • prompt_enhancer (Gemma4ForConditionalGeneration, 선택 사항) — 전용 프롬프트 강화 모델(LTX-2.5).
  • duration_head (LTX2DurationHead, 선택 사항) — num_frames가 제공되지 않은 경우 프롬프트 임베딩에서 num_frames를 예측합니다.

LTX-2.5를 사용한 Diffusion Fidelity Rendering(DFR) 디노이즈 패스 1회용 파이프라인.

패스는 비디오와 추가적인 단일 픽셀 프레임의 키프레임 슬롯을 그리고 생성하거나, 해당 슬롯에서 시드된 제공된 잠재를 다시 디노이즈합니다. 호출자는 단계를 구성합니다: 이 파이프라인을 반 해상도로 실행하고, LTX2LatentUpsamplePipeline로 공간적으로 업샘플링한 뒤, 업샘플링된 슬롯과 IC-LoRA 참조를 사용하여 전체 해상도로 이 파이프라인을 다시 실행하고, 각 시간적 정제 라운드마다 LTX2DFRTemporalRefinePipeline를 실행합니다. 1080p 레시피에 대해서는 LTX-2 문서를 참조하세요.

Slot 위치는 VAE의 시간 경계에 정렬된 세그먼트 그리드(resolve_canvas)에서 가져옵니다. 캔버스는 세그먼트의 정수 배로 패딩되며, output_type="latent"는 패딩된 그리드를 반환하여 패딩 영역에 있는 slot이 제거되지 않도록 합니다. VAE 디코딩 전에 trim_canvas로 잘라내야 합니다.

generate_slots=True인 경우, use_keyframes_abs_pos_embedding를 설정하는 config를 가진 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, 선택 사항) — 내부 캔버스 패딩을 적용하기 전 이 패스의 픽셀 프레임 수입니다. 값을 제공하지 않으면 duration_head가 프롬프트로부터 지속 시간을 예측합니다. (num_frames - 1) % 8 == 0 조건을 만족해야 합니다.
  • frame_rate (float, 선택 사항, 기본값 24.0) — 이 패스의 재생 fps입니다. 이 값이 30을 초과하면 RoPE 시간이 60으로 고정됩니다.
  • min_seconds (float, 선택 사항, 기본값 1.0) — num_frames가 생략된 경우 자동 예측된 길이의 하한값입니다.
  • max_seconds (float, 선택 사항, 기본값 20.0) — num_frames가 생략된 경우 자동 예측된 길이의 상한값입니다.
  • latents (torch.Tensor, 선택 사항) — 재디노이즈(2단계 / 에필로그)할 원시 (batch_size, channels, frames, height, width) 비디오 latents입니다.
  • audio_latents (torch.Tensor, 선택 사항) — 압축 해제된 원본 (batch_size, channels, length, mel_bins) 오디오 잠재 변수입니다. Stage 2에서는 여전히 결합된 오디오 패스가 실행되며, 구성 레시피의 제공되는 웨이브폼은 Stage 1의 것입니다. 호출자는 이를 유지합니다.
  • keyframes_latents (torch.Tensor, 선택 사항) — generate_slots=True일 때 사용되는 (batch_size, channels, num_slots, height, width) 크기의 원시 슬롯 초기값입니다.
  • keyframe_positions (list[int], 선택 사항) — 생성된 슬롯의 픽셀 프레임 인덱스입니다. 기본값은 resolve_canvas(num_frames)입니다.
  • reference_latents (torch.Tensor, 선택 사항) — 원본 IC-LoRA 참조 비디오(일반적으로 1단계의 프레임).
  • reference_downscale_factor (int, 선택 사항, 기본값 2) — 해당 패스와 기준 해상도 사이의 비율로, 기준 토큰 좌표를 스케일링하는 데 사용됩니다.
  • guidance_keyframe_latents (torch.Tensor, 선택 사항) — 고정된(raw pinned) guidance keyframes (batch_size, channels, K, height, width) — epilogue 경로입니다. 생성된 슬롯이 아닙니다.
  • guidance_keyframe_positions (list[int], 선택 사항) — guidance_keyframe_latents에 대한 픽셀 프레임 인덱스입니다.
  • guidance_keyframe_strength (float, 선택 사항, 기본값 1.0) — 고정된 guidance keyframe에 대한 conditioning strength입니다.
  • generate_slots (bool, 선택 사항, 기본값 True) — 생성된 keyframe-slot 토큰을 추가합니다. epilogue는 이 값을 False로 설정하고 대신 guidance_keyframe_latents를 고정합니다.
  • sigmas (list[float], 선택 사항) — 이 패스에 대한 노이즈 스케줄이며, 종단 0.0은 제외됩니다.
  • noise_scale (float, 선택 사항) — 무조건 토큰이 시작하는 노이즈 레벨입니다. 기본값은 sigmas[0]입니다.
  • freeze_audio (bool, 선택 사항, 기본값 False) — 오디오를 시그마 0에 고정합니다(에필로그 / 동결된 1단계 웨이브폼을 따를 때).
  • video_tiles (list[LTX2DFREpilogueTile], 선택 사항) — epilogue_tiles()에서 가져온 에피로그 타일링으로, 단일 포워드 패스에 너무 큰 해상도라도 단일 캔버스를 단계별로 처리할 수 있습니다. 각 단계에서 변환기를 타일당 한 번씩 실행하고 예측치를 블렌딩합니다. 이 패스 자체의 RoPE 좌표에 대해 토큰 계획으로 해석되므로, 좌표는 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) — cross attention modulation에 cross-modality sigma를 사용할지 여부입니다. LTX-2.3+의 경우 True입니다.
  • system_prompt (str, 선택 사항) — 프롬프트 강화에 사용할 선택적 시스템 프롬프트입니다. enable_prompt_enhancement를 참조하세요.
  • enable_prompt_enhancement (bool, 선택 사항, 기본값 False) — 프롬프트 강화 실행 여부를 지정합니다.
  • prompt_max_new_tokens (int, 선택 사항) — 프롬프트 강화 수행 시 생성할 새 토큰의 최대 수입니다.
  • 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, 선택 사항) — attention processor에 전달되는 추가 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이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

height × width 해상도로 denoise 패스를 한 번 수행합니다. 호출부에서 단계를 구성합니다: 이 파이프라인을 반 해상도로 실행하고, 공간 업샘플링을 수행한 뒤, 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, 오디오 Euler 단계 없음)로 유지하면서 오디오-비디오 크로스 어텐션을 계속 실행합니다. audio_latents가 None인 경우 무시됩니다.
  • video_tile_plan (list, 선택 사항) — video_tile_plan[~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan]에서 가져온 타일별 토큰 계획입니다. 이 값이 주어지면 각 단계에서 변환기가 타일별로 한 번씩 실행되고 예측 결과가 블렌딩되므로, 샘플러는 여전히 단일 전체 캔버스를 단계별로 처리하며 모든 단계에서 타일 간 겹치는 부분이 일치합니다.
  • generator (torch.Generator, 선택 사항) — LTXEulerAncestralRFScheduler.step()에 전달됩니다. 시간 타일은 타일별 시드를 전달하여, 선조 샘플링이 스트림을 공유하거나 다음 타일의 초기 노이즈가 읽는 상태를 소모하지 않도록 합니다. Distilled Euler는 이 값을 읽지 않습니다.
  • step_offset (int) — 파이프라인 전체 스케줄 내에서 이 패스의 첫 번째 스텝에 해당하는 인덱스로, callback_on_step_end 및 공유된 진행률 표시줄에 사용됩니다.

sigmas에 대해 DFR 노이즈 제거 패스를 한 번 실행하고, 둘 다 여전히 패킹된 상태인 (latents, audio_latents)를 반환합니다.

디스틸된 스케줄은 classifier-free guidance 없이 사용되므로, 각 단계마다 transformer 호출이 한 번만 수행됩니다. 모든 패스에서 두 스트림이 모두 실행됩니다. 생성된 오디오가 폐기되는 경우에도 비디오 브랜치는 크로스 모달 어텐션이 필요하기 때문입니다. freeze_audio=True는 오디오 스트림을 sigma 0에 고정하여(Euler step 없음) 비디오가 여전히 해당 스트림에 대해 크로스 어텐션을 수행할 수 있게 합니다. 시간적 refine 타일과 에필로그는 이를 사용하여 각 타일이 서로 다른 오디오 실현을 다시 디노이즈하지 않고 stage-1의 발화를 따릅니다.

x0 conditioning blend 이후, velocity는 (latents - denoised) / sigma가 되므로 RF step x0 = x - σ v는 blend된 denoised를 복원합니다. Stage 1 / 2 / epilogue는 FlowMatchEulerDiscreteScheduler를 유지하고 해당 Euler step을 그대로 사용합니다. Temporal refine은 LTXEulerAncestralRFScheduler(eta=0.5)로 교체합니다. 이 step은 모든 token을 재노이즈하므로, 이후에 conditioning blend를 다시 적용하지 않으면 strength-0.95 seam anchors가 침식됩니다.

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에 바로 사용할 수 있는 형태입니다. 인코딩은 배치와 분리되어 유지됩니다. 이는 temporal refine 라운드가 각 타일마다 조건의 위치를 2 ** round로 스케일링하고 다시 기준을 설정하기 때문에, 동일한 정지 프레임을 타일마다 한 번씩 다시 인코딩하는 것을 방지해야 하기 때문입니다.

반환된 인덱스는 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 device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

DFR은 classifier-free guidance 없이 사용하도록 학습된 distilled sigma schedule을 실행하므로, 여기에는 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 )

prompt를 입력받아 프롬프트 강화기(Gemma 조건 생성 모델)와 시스템 프롬프트를 활용하여 새로운 프롬프트를 생성하여 강화합니다. 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], 선택 사항) — latent 인덱스로 위치가 지정되는 프레임 수준의 이미지/비디오 조건입니다.
  • condition_latents (list[tuple[int, torch.Tensor, float, int]], 선택 사항) — conditions의 이미 인코딩된 대체 값으로, (pixel_frame_index, latent, strength, num_pixel_frames) 형식입니다. temporal refine 라운드에서 조건의 위치가 2 ** round 배로 스케일링되므로, 그 결과가 일반적으로 latent 경계에 정확히 위치하지 않기 때문에 latent 인덱스가 아닌 픽셀 인덱스를 사용합니다. 해당 위치에 배치될 수 있는 것은 추가된 keyframe 토큰뿐이며, 이는 픽셀 기준으로 배치됩니다. pixel_frame_index == 0은 여전히 “첫 번째 프레임을 대체한다”는 의미를 가집니다.
  • keyframe_latents (list[tuple[int, torch.Tensor, float]], 선택 사항) — 이미 인코딩된 keyframe guidance를 (pixel_frame_index, latent, strength) 형식으로 나타내며, 여기서 latent의 shape은 (batch_size, num_channels_latents, 1, latent_height, latent_width)입니다. 이전 라운드에서 가져온 seam keyframe을 고정하기 위해 temporal refine 라운드에서 사용됩니다.
  • slot_frame_indices (list[int], 선택 사항) — 생성된 키프레임 슬롯의 픽셀 프레임 위치입니다.
  • slot_initial_latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width) 형식의 콘텐츠로, 노이즈를 추가하기 전에 슬롯 토큰에 기록됩니다.
  • reference_latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, F, H, W) IC-LoRA 참조 latent.
  • reference_downscale_factor (int, 기본값 1) — 목표 해상도와 참조 해상도 사이의 비율입니다.
  • latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, F, H, W) 기본 토큰의 초기 콘텐츠입니다. 공개 파이프라인의 latents는 원본(정규화되지 않은) 상태이며, 해당 경계에서는 latents_normalized=False를 전달해야 합니다. 이미 VAE 정규화 공간에 있는 타일 루프의 경우 기본값을 유지합니다.
  • latents_normalized (bool, 기본값 True) — latents, slot_initial_latents, reference_latents, keyframe_latents가 이미 VAE 정규화되어 있는지 여부입니다. 내부 타일 루프에서는 True를 전달하며, 각 파이프라인의 __call__에서는 False를 전달합니다.
  • noise_scale (float, 기본값 1.0) — 무조건 토큰이 초기화되는 노이즈 레벨, 즉 스케줄의 첫 번째 시그마입니다.

반환값

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은 패킹된 시퀀스에서 생성된 keyframe slot token을 인덱싱하며, 요청된 slot이 없으면 None입니다.

DFR 디노이징 패스 하나를 위해 노이즈가 포함된 패킹된 비디오 라텐트를 준비합니다.

패킹된 시퀀스는 [base | keyframes | slots | reference]로 배치됩니다:

  • Base tokens는 latents가 제공된 경우 이를 시드로 사용하여 대상 latent grid를 커버합니다.
  • index == 0인 프레임 조건은 첫 번째 프레임 위치에 깨끗한 타겟을 설정하며, index > 0인 조건과 keyframe_latents의 모든 항목은 토큰별 조건화 마스크가 해당 강도와 같도록 추가적인 키프레임 토큰으로 추가됩니다.
  • slot_frame_indices는 각 위치마다 생성된 keyframe 토큰을 하나의 latent frame 분량만큼 추가하며, conditioning mask는 0(완전히 denoise된 상태)이고 RoPE의 temporal extent는 정확히 하나의 pixel frame입니다. 이는 DFR에 추가 프레임을 제공하는 keyframe 슬롯이며, slot_initial_latents가 이들의 내용을 초기화합니다.
  • reference_latents는 스테이지 1의 반해상도 latent를 완전히 깨끗한 IC-LoRA 참조로 추가하며, reference_downscale_factor으로 공간 좌표를 스케일링하여 대상 좌표 공간에 매핑되도록 합니다.

추가된 conditioning 토큰은 clean_latents에 내용을, latents에는 0 플레이스홀더를 담고, keyframe 슬롯은 latents에 시드를, clean_latents에는 0을 담습니다. 반환되는 latents는 이 둘의 노이즈 혼합 결과입니다(해당 메서드 끝의 noising 단계 참조).

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

다음과 같이 len(conditions) 길이의 리스트 4개로 구성된 4-tuple을 반환합니다:

  1. 첫 번째 목록은 [batch_size=1, num_channels, num_frames, height, width] 모양의 전처리된 비디오 텐서 목록입니다.
  2. 두 번째 목록은 조건화 강도(conditioning strengths)의 목록입니다.
  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) 형태의 Raw latents로, guidance_keyframe_latents로 바로 다시 전달할 수 있는 상태입니다.

RGB를 통해 carry keyframe을 원래 해상도의 두 배로 재인코딩합니다.

이 프레임들은 refine 라운드에서 이미 결정된 것이므로, epilogue는 생성을 요청받지 않고 주어지는 상태입니다. 픽셀로 디코딩한 뒤 Lanczos로 2배 확대하고 다시 인코딩하면 프레임이 보존되면서 출력 그리드에 정확히 위치하게 되며, 이를 통해 epilogue가 프레임을 완전히 깨끗하게 고정할 수 있습니다.

각 평면은 자체의 1프레임 클립으로 디코딩됩니다. VAE는 인과적(causal)이므로, 스택된 디코딩을 사용하면 인접한 평면이 서로 영향을 미칩니다. 이들은 독립적인 정지 이미지이지 시퀀스가 아니기 때문입니다.

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 스케줄러입니다. DFR 시간 레시피와 일치하도록 eta=0.5로 구성하세요.
  • vae (AutoencoderKLLTX2Video) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • audio_vae (AutoencoderKLLTX2Audio) — 오디오 스펙트로그램을 인코딩 및 디코딩하는 오디오 VAE입니다.
  • text_encoder (Gemma3ForConditionalGeneration 또는 Gemma4UnifiedForConditionalGeneration) — 텍스트 인코더 모델입니다.
  • tokenizer (GemmaTokenizer 또는 GemmaTokenizerFast) — 텍스트 인코더용 토크나이저.
  • connectors (LTX2TextConnectors) — 비디오 및 오디오 브랜치를 위해 텍스트 인코더의 히든 상태를 적응시키기 위해 사용되는 텍스트 커넥터 스택입니다.
  • transformer (LTX2VideoTransformer3DModel) — 인코딩된 비디오 잠재 변수를 디노이즈하기 위한 조건부 Transformer 아키텍처.
  • vocoder (LTX2Vocoder 또는 LTX2VocoderWithBWE) — 멜 스펙트로그램을 오디오 웨이브폼으로 변환하는 Vocoder.
  • temporal_latent_upsampler (LTX2LatentUpsamplerModel) — 라운드 시작 시 적용되는 Temporal x2 latent upsampler입니다.

One temporal DFR refine round: 캔버스를 시간 방향으로 2배 보간하고, 키프레임 경계에 타일링한 뒤 각 타일을 ancestral-denoise 처리합니다. 이후 뒤쪽 타일의 lead-in을 제거하여 스티칭하고, carry-keyframe bag을 병합합니다.

스케줄러는 LTXEulerAncestralRFScheduler입니다(기본값은 eta=0.5). Stage 1 / 2 / spatial epilogue는 LTX2DFRPipeline을 통해 FlowMatchEulerDiscreteScheduler를 유지합니다. 이 파이프라인은 라운드당 한 번 호출하며, 호출 측에서 2x / 4x를 반복합니다.

수신되는 latents / keyframes_latents / audio_latents는 정규화되지 않은 원시(raw) 값이며, 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 캔버스의 원시 비디오 latents, (batch_size, channels, frames, height, width).
  • keyframes_latents (torch.Tensor) — 이전 패스에서 가져온 원시 carry keyframes (batch_size, channels, K, height, width).
  • keyframe_positions (list[int]) — 입력 캔버스에서 keyframes_latents의 픽셀 프레임 인덱스입니다.
  • audio_latents (torch.Tensor) — 동결된 stage-1 오디오로, unpacked 및 denormalized 상태입니다. 각 타일에는 해당 재생 윈도우를 덮는 슬라이스가 전달되며, 반환되는 오디오는 타일별 재디노이즈가 아닌 이 웨이브폼입니다.
  • 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) — 입력의 재생 fps입니다. 라운드는 이를 두 배로 만듭니다.
  • source_seconds (float, 선택 사항) — 동결된 stage-1 오디오의 길이입니다. 기본값은 num_frames / frame_rate이며, 이는 첫 번째 라운드에서 올바른 값입니다. 이후 라운드에서는 타일이 어긋나지 않도록 원래 stage-1 길이를 전달해야 합니다.
  • 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], 선택 사항) — 이 라운드의 타일에 대한 증류된 스케줄이며, 종단 0.0은 제외됩니다.
  • noise_scale (float, 선택 사항) — 무조건 토큰이 시작하는 노이즈 레벨입니다. 기본값은 sigmas[0]입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 재현성을 위한 랜덤 생성기입니다. Ancestral draws는 이 생성기의 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) — cross attention modulation에 cross-modality 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, 선택 사항) — attention processor에 전달되는 추가 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이 반환됩니다.

temporal refine 라운드를 한 번 실행합니다.

예:

>>> 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, 오디오 Euler 단계 없음)로 유지하면서 오디오-비디오 크로스 어텐션을 계속 실행합니다. audio_latents가 None인 경우 무시됩니다.
  • video_tile_plan (list, 선택 사항) — video_tile_plan[~diffusers.pipelines.ltx2.dfr_layout.video_tile_plan]에서 가져온 타일별 토큰 계획입니다. 이 값이 주어지면 각 단계에서 변환기가 타일별로 한 번씩 실행되고 예측 결과가 블렌딩되므로, 샘플러는 여전히 단일 전체 캔버스를 단계별로 처리하며 모든 단계에서 타일 간 겹치는 부분이 일치합니다.
  • generator (torch.Generator, 선택 사항) — LTXEulerAncestralRFScheduler.step()에 전달됩니다. 시간 타일은 타일별 시드를 전달하여, 선조 샘플링이 스트림을 공유하거나 다음 타일의 초기 노이즈가 읽는 상태를 소모하지 않도록 합니다. Distilled Euler는 이 값을 읽지 않습니다.
  • step_offset (int) — 파이프라인 전체 스케줄 내에서 이 패스의 첫 번째 스텝에 해당하는 인덱스로, callback_on_step_end 및 공유된 진행률 표시줄에 사용됩니다.

sigmas에 대해 DFR 노이즈 제거 패스를 한 번 실행하고, 둘 다 여전히 패킹된 상태인 (latents, audio_latents)를 반환합니다.

디스틸된 스케줄은 classifier-free guidance 없이 사용되므로, 각 단계마다 transformer 호출이 한 번만 수행됩니다. 모든 패스에서 두 스트림이 모두 실행됩니다. 생성된 오디오가 폐기되는 경우에도 비디오 브랜치는 크로스 모달 어텐션이 필요하기 때문입니다. freeze_audio=True는 오디오 스트림을 sigma 0에 고정하여(Euler step 없음) 비디오가 여전히 해당 스트림에 대해 크로스 어텐션을 수행할 수 있게 합니다. 시간적 refine 타일과 에필로그는 이를 사용하여 각 타일이 서로 다른 오디오 실현을 다시 디노이즈하지 않고 stage-1의 발화를 따릅니다.

x0 conditioning blend 이후, velocity는 (latents - denoised) / sigma가 되므로 RF step x0 = x - σ v는 blend된 denoised를 복원합니다. Stage 1 / 2 / epilogue는 FlowMatchEulerDiscreteScheduler를 유지하고 해당 Euler step을 그대로 사용합니다. Temporal refine은 LTXEulerAncestralRFScheduler(eta=0.5)로 교체합니다. 이 step은 모든 token을 재노이즈하므로, 이후에 conditioning blend를 다시 적용하지 않으면 strength-0.95 seam anchors가 침식됩니다.

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에 바로 사용할 수 있는 형태입니다. 인코딩은 배치와 분리되어 유지됩니다. 이는 temporal refine 라운드가 각 타일마다 조건의 위치를 2 ** round로 스케일링하고 다시 기준을 설정하기 때문에, 동일한 정지 프레임을 타일마다 한 번씩 다시 인코딩하는 것을 방지해야 하기 때문입니다.

반환된 인덱스는 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 device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

DFR은 classifier-free guidance 없이 사용하도록 학습된 distilled sigma schedule을 실행하므로, 여기에는 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], 선택 사항) — latent 인덱스로 위치가 지정되는 프레임 수준의 이미지/비디오 조건입니다.
  • condition_latents (list[tuple[int, torch.Tensor, float, int]], 선택 사항) — conditions의 이미 인코딩된 대체 값으로, (pixel_frame_index, latent, strength, num_pixel_frames) 형식입니다. temporal refine 라운드에서 조건의 위치가 2 ** round 배로 스케일링되므로, 그 결과가 일반적으로 latent 경계에 정확히 위치하지 않기 때문에 latent 인덱스가 아닌 픽셀 인덱스를 사용합니다. 해당 위치에 배치될 수 있는 것은 추가된 keyframe 토큰뿐이며, 이는 픽셀 기준으로 배치됩니다. pixel_frame_index == 0은 여전히 “첫 번째 프레임을 대체한다”는 의미를 가집니다.
  • keyframe_latents (list[tuple[int, torch.Tensor, float]], 선택 사항) — 이미 인코딩된 keyframe guidance를 (pixel_frame_index, latent, strength) 형식으로 나타내며, 여기서 latent의 shape은 (batch_size, num_channels_latents, 1, latent_height, latent_width)입니다. 이전 라운드에서 가져온 seam keyframe을 고정하기 위해 temporal refine 라운드에서 사용됩니다.
  • slot_frame_indices (list[int], 선택 사항) — 생성된 키프레임 슬롯의 픽셀 프레임 위치입니다.
  • slot_initial_latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, len(slot_frame_indices), latent_height, latent_width) 형식의 콘텐츠로, 노이즈를 추가하기 전에 슬롯 토큰에 기록됩니다.
  • reference_latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, F, H, W) IC-LoRA 참조 latent.
  • reference_downscale_factor (int, 기본값 1) — 목표 해상도와 참조 해상도 사이의 비율입니다.
  • latents (torch.Tensor, 선택 사항) — (batch_size, num_channels_latents, F, H, W) 기본 토큰의 초기 콘텐츠입니다. 공개 파이프라인의 latents는 원본(정규화되지 않은) 상태이며, 해당 경계에서는 latents_normalized=False를 전달해야 합니다. 이미 VAE 정규화 공간에 있는 타일 루프의 경우 기본값을 유지합니다.
  • latents_normalized (bool, 기본값 True) — latents, slot_initial_latents, reference_latents, keyframe_latents가 이미 VAE 정규화되어 있는지 여부입니다. 내부 타일 루프에서는 True를 전달하며, 각 파이프라인의 __call__에서는 False를 전달합니다.
  • noise_scale (float, 기본값 1.0) — 무조건 토큰이 초기화되는 노이즈 레벨, 즉 스케줄의 첫 번째 시그마입니다.

반환값

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은 패킹된 시퀀스에서 생성된 keyframe slot token을 인덱싱하며, 요청된 slot이 없으면 None입니다.

DFR 디노이징 패스 하나를 위해 노이즈가 포함된 패킹된 비디오 라텐트를 준비합니다.

패킹된 시퀀스는 [base | keyframes | slots | reference]로 배치됩니다:

  • Base tokens는 latents가 제공된 경우 이를 시드로 사용하여 대상 latent grid를 커버합니다.
  • index == 0인 프레임 조건은 첫 번째 프레임 위치에 깨끗한 타겟을 설정하며, index > 0인 조건과 keyframe_latents의 모든 항목은 토큰별 조건화 마스크가 해당 강도와 같도록 추가적인 키프레임 토큰으로 추가됩니다.
  • slot_frame_indices는 각 위치마다 생성된 keyframe 토큰을 하나의 latent frame 분량만큼 추가하며, conditioning mask는 0(완전히 denoise된 상태)이고 RoPE의 temporal extent는 정확히 하나의 pixel frame입니다. 이는 DFR에 추가 프레임을 제공하는 keyframe 슬롯이며, slot_initial_latents가 이들의 내용을 초기화합니다.
  • reference_latents는 스테이지 1의 반해상도 latent를 완전히 깨끗한 IC-LoRA 참조로 추가하며, reference_downscale_factor으로 공간 좌표를 스케일링하여 대상 좌표 공간에 매핑되도록 합니다.

추가된 conditioning 토큰은 clean_latents에 내용을, latents에는 0 플레이스홀더를 담고, keyframe 슬롯은 latents에 시드를, clean_latents에는 0을 담습니다. 반환되는 latents는 이 둘의 노이즈 혼합 결과입니다(해당 메서드 끝의 noising 단계 참조).

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

다음과 같이 len(conditions) 길이의 리스트 4개로 구성된 4-tuple을 반환합니다:

  1. 첫 번째 목록은 [batch_size=1, num_channels, num_frames, height, width] 모양의 전처리된 비디오 텐서 목록입니다.
  2. 두 번째 목록은 조건화 강도(conditioning strengths)의 목록입니다.
  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를 정규화된 latents에 실행합니다. upsampler가 기대하는 대로 raw VAE latent space를 경유합니다.

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]]) — 노이즈가 제거된 비디오. Latent 출력은 트리밍되지 않은 캔버스이며, shape은 (batch_size, num_channels, latent_frames, latent_height, latent_width)입니다.
  • audio (torch.Tensor, np.ndarray) — 해당하는 오디오 레이턴트 또는 웨이브폼.
  • keyframes (torch.Tensor, 선택 사항) — 생성되거나 전달된 keyframe latents로, shape은 (batch_size, num_channels, num_keyframes, latent_height, latent_width)입니다. output_type != "latent"인 경우 또는 패스가 슬롯을 생성하지 않은 경우(예: tiled epilogue)에는 None입니다.
  • keyframe_positions (list[int], 선택 사항) — 이 패스의 캔버스에서 각 keyframe의 픽셀 프레임 인덱스입니다. keyframes가 None인 경우 None입니다. 시간적 라운드 이후에는 원래의 num_frames에서 다시 유도할 수 없으므로 다음 단계에 전달해야 합니다.

DFR 파이프라인의 출력 클래스입니다.

LTX2LatentUpsamplePipeline

클래스 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 1단계 출력). 제공되지 않으면 latents를 제공해야 합니다.
  • height (int, 선택 사항, 기본값 512) — 입력 비디오의 픽셀 단위 높이입니다(생성된 비디오는 해상도가 더 높으므로 해당하지 않음).
  • width (int, 선택 사항, 기본값 768) — 입력 비디오의 픽셀 단위 너비입니다(생성된 비디오는 해상도가 더 높으므로 해당하지 않음).
  • num_frames (int, 선택 사항, 기본값 121) — 입력 비디오의 프레임 수입니다.
  • spatial_patch_size (int, 선택 사항, 기본값 1) — 비디오 latents의 공간 패치 크기입니다. latents가 제공되고 언패킹이 필요한 경우 사용됩니다.
  • temporal_patch_size (int, 선택 사항, 기본값 1) — 비디오 latents의 temporal patch size입니다. latents가 제공되고 unpacking이 필요한 경우 사용됩니다.
  • latents (torch.Tensor, 선택 사항) — 미리 생성된 비디오 latents입니다. video 인수의 대안으로 사용할 수 있습니다. (batch_size, seq_len, hidden_dim) 형태의 patch sequence이거나, (batch_size, latent_channels, latent_frames, latent_height, latent_width) 형태의 비디오 latent일 수 있습니다.
  • latents_normalized (bool, 선택 사항, 기본값 False) — latents가 제공된 경우, latents가 VAE latent의 평균과 표준편차로 정규화되었는지를 나타냅니다. True인 경우, latents는 latent upsampler에 전달되기 전에 비정규화됩니다.
  • decode_timestep (float, 기본값 0.0) — 생성된 비디오가 디코딩되는 timestep입니다.
  • decode_noise_scale (float, 기본값 None) — 디코드 타임스텝에서 랜덤 노이즈와 디노이즈된 레이턴트 사이의 보간 계수입니다.
  • adain_factor (float, 선택 사항, 기본값 0.0) — 업샘플링된 latent와 원래 latent 사이의 Adaptive Instance Normalization(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 generator 하나 또는 목록
  • 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이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> 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) — 정규화할 입력 latents
  • reference_latents (torch.Tensor) — 스타일 통계를 제공하는 참조 잠재 변수입니다.
  • factor (float) — 원본과 변환된 latent 사이의 블렌딩 계수. 범위: -10.0 ~ 10.0, 기본값: 1.0

반환값

torch.Tensor

변환된 잠재 텐서

참조 latent tensor의 통계량을 기반으로 latent tensor에 Adaptive Instance Normalization(AdaIN)을 적용합니다.

tone_map_latents

< >

( latents: Tensorcompression: float )

매개변수

  • latents — torch.Tensor 임의의 형태를 가진 입력 latent 텐서. 대략 [-1, 1] 또는 [0, 1] 범위에 있을 것으로 예상됩니다.
  • compression — float [0, 1] 범위의 압축 강도.
    • 0.0: 톤 매핑 없음(항등 변환)
    • 1.0: 완전 압축 효과

시그모이드 기반 압축을 사용하여 잠재 값의 동적 범위를 지각적으로 매끄러운 방식으로 줄이기 위해 비선형 톤 매핑 함수를 적용합니다.

compression 팩터를 사용하여 동적 동작을 제어하는 경우를 포함하여, 생성 과정에서 출력을 조건화하거나 높은 분산의 latents를 정규화하는 데 유용합니다.

LTX2VideoDiffusionDecodePipeline

클래스 diffusers.LTX2VideoDiffusionDecodePipeline

< >

( diffusion_decoder: LTX2VideoDiffusionDecoderModelschedulervae: AutoencoderKLLTX2Video = None )

매개변수

  • diffusion_decoder (LTX2VideoDiffusionDecoderModel) — 확산 비디오 디코더입니다.
  • scheduler (FlowMatchEulerDiscreteScheduler) — 디코더의 디노이징 단계를 제어하는 스케줄러.
  • vae (AutoencoderKLLTX2Video, 선택 사항) — 비정규화(denormalize)에 사용되는 잠재 통계(latent statistics) 조회에만 사용됩니다. 생략할 경우 파이프라인은 LTX-2 기본값으로 대체되므로, 디코딩 전용 워크플로에서는 두 번째 오토인코더를 로드할 필요가 없습니다.

LTX-2.5에서 소개된 diffusion decoder를 사용하여 LTX-2 비디오 latents를 디코딩합니다.

컨볼루션 디코더와 달리 이 디코더는 자체적으로 작은 diffusion 모델입니다: latent에서 구축된 context volume에 조건부 설정하여 픽셀의 노이즈를 제거하므로, scheduler와 generator가 필요합니다. output_type="latent"로 실행된 LTX-2 파이프라인과 함께 사용하며, 해당 경로에서 이미 latent 통계가 적용되었으므로 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) 형태의 Latents입니다. output_type="latent"로 실행된 LTX-2 파이프라인은 이미 비정규화된 latents를 반환하므로, 해당 경우 denormalize=False를 전달하세요.
  • generator (torch.Generator, 선택 사항) — 디코더는 노이즈를 제거할 노이즈를 샘플링하므로, 디코딩을 재현 가능하게 하려면 생성자를 전달하세요.
  • output_type (str, 선택 사항, 기본값 "pil") — 디코딩된 비디오의 출력 형식입니다. "pil", "np", "pt", "latent" 중 하나를 선택할 수 있습니다.
  • return_dict (bool, 선택 사항, 기본값 True) — LTX2VideoDecodeOutput을 반환할지, 아니면 단순 튜플을 반환할지를 결정합니다.
  • denormalize (bool, 선택 사항, 기본값 True) — 디코딩 전에 latent 통계량을 적용할지 여부입니다. latents가 이미 denormalize되어 있다면 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) — Pooler가 사용하는 Attention heads입니다.
  • mlp_hidden_dim (int, 기본값 256) — 출력 MLP의 숨겨진 폭입니다. mlp_hidden 서브모듈과 이름이 충돌하지 않도록 _dim 접미사를 붙였습니다. 그렇지 않으면 ConfigMixin.__getattr__가 이 설정 값으로 해당 서브모듈을 가리게 됩니다.

LTX-2 텍스트 커넥터 출력에서 캡션이 암시하는 샷의 자연스러운 길이를 예측합니다.

head는 모달리티에 무관합니다: video와 audio 커넥터 출력 중 하나 또는 둘 다를 전달할 수 있습니다. 모달리티별 입력 투영은 각 스트림을 공유된 pooler 차원으로 매핑하고, 학습 가능한 모달리티 임베딩은 pooler가 스트림을 구별할 수 있도록 태그를 부여하며, 작은 MLP는 풀링된 벡터를 log-duration으로 변환합니다. 회귀 목표는 log-초 단위로 학습되므로 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 (torch.Tensor, shape (batch_size, seq_len, video_cross_attention_dim), 선택 사항) — Video connector 출력입니다.
  • audio_tokens (torch.Tensor, shape (batch_size, seq_len, audio_cross_attention_dim), 선택 사항) — 오디오 커넥터 출력입니다.

반환값

torch.Tensor, shape (batch_size,)

초 단위로 예측된 지속 시간입니다.

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의 시간적 그리드에 있는 프레임 수

커넥터 토큰에서 프레임 수를 예측하며, [min_seconds, max_seconds]로 클램프되고 VAE의 인과적 시간 그리드(k * temporal_compression_ratio + 1)에 스냅됩니다.

클램프는 스냅핑 전에 적용됩니다. 클램프된 프레임 수는 그리드에 정렬되지 않을 수 있으므로, 스냅핑을 먼저 수행하면 결과가 달라집니다. 스냅핑은 버림(floor)을 수행하므로 최소값보다 아래에 위치할 수 있습니다. 이 경우 프레임 수가 범위를 벗어나지 않도록 다음 그리드 포인트로 위로 스냅핑됩니다.

좁은 범위는 그리드 포인트가 전혀 없는 프레임 윈도우로 변환될 수 있습니다. 24 fps에서 [1.0s, 1.02s]은 [24, 24]으로 반올림되며, 24는 8k + 1이 아닙니다. 그리드 스텝 하나 미만의 초과가 생성을 거부하는 것보다 나으므로, 가장 가까운 그리드 포인트가 사용되고 경고가 기록됩니다. 따라서 반환되는 개수는 항상 그리드 위에 있지만, 이 경우 요청된 범위를 약간 벗어날 수 있습니다.

LTX2PipelineOutput

클래스 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

클래스 diffusers.LTX2AutoBlocks

< >

( )

텍스트-투-비디오, 이미지-투-비디오, 조건-투-비디오 및 컨텍스트 내(IC-LoRA) 생성(비디오 + 오디오 결합)을 지원하는 LTX-2용 Auto 블록

지원되는 워크플로:

  • 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, 선택 사항): 프롬프트 향상 중에 생성할 새 토큰의 최대 수입니다. 기본값은 LTX-2.5 Gemma-4 향상기의 예산인 600입니다. prompt_enhancement_kwargs (dict, 선택 사항): 향상기의 .generate 호출에 사용할 키워드 인자입니다. 기본값은 탐욕 디코딩입니다. prompt_enhancement_seed (int, 선택 사항, 기본값 10): 프롬프트 향상을 위한 무작위 시드입니다 (LTX-2.5의 탐욕 디코딩에서는 효과가 없습니다). generator (Generator, 선택 사항): 결정론적 생성을 위한 Torch 생성기입니다. image (Image | list, 선택 사항): 디노이징을 위한 참조 이미지입니다. 단일 이미지 또는 이미지 목록일 수 있습니다. negative_prompt (str, 선택 사항): 이미지 생성을 안내하지 않을 프롬프트입니다. max_sequence_length (int, 선택 사항, 기본값 1024): 프롬프트 인코딩을 위한 최대 시퀀스 길이입니다. min_seconds (float, 선택 사항, 기본값 1.0): 자동 예측된 길이의 하한입니다. max_seconds (float, 선택 사항, 기본값 20.0): 자동 예측된 길이의 상한입니다. min_seconds보다 엄격하게 커야 합니다. frame_rate (float, 선택 사항, 기본값 24.0): 생성된 비디오의 초당 프레임 수입니다. height (int, 선택 사항, 기본값 512): 생성된 이미지의 픽셀 단위 높이입니다. width (int, 선택 사항, 기본값 704): 생성된 이미지의 픽셀 단위 너비입니다. image_crf (int, 선택 사항): VAE 인코딩 전에 조건부 image를 다시 압축하는 데 사용되는 H.264 CRF 값으로, 모델이 학습된 압축과 일치합니다. None(기본값)은 텍스트 인코더 생성에서 결정됩니다 (LTX-2.3까지는 33, LTX-2.5는 18). 다시 압축을 건너뛰려면 0을 전달합니다. 다시 압축이 실행될 때 PIL.Image.Image가 필요합니다. num_frames (int, 선택 사항): 생성된 비디오의 프레임 수입니다. 생략하면 duration_head를 통해 자동 예측됩니다 (LTX2AutoDurationStep 참조). reference_conditions (list, 선택 사항): LTX2ReferenceCondition (또는 그 목록)으로, 해당 비디오는 IC-LoRA 어댑터가 주의를 기울이는 추가 잠재 토큰으로 인코딩됩니다. reference_downscale_factor (int, 선택 사항, 기본값 1): 대상 해상도와 참조 해상도 사이의 비율입니다. 2는 참조가 대상 해상도의 절반으로 전처리됨을 의미합니다. 공간 좌표는 이 계수로 스케일링되어 참조 토큰이 대상 좌표 공간에 위치하도록 합니다. IC-LoRA 학습 시 사용된 계수와 일치해야 합니다. conditioning_attention_strength (float, 선택 사항, 기본값 1.0): 노이즈 토큰과 참조 토큰이 서로 얼마나 강하게 주의를 기울이는지 제어하는 [0, 1] 범위의 스칼라입니다. 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, 선택 사항): [1, C, F, H, W] 모양의 조건별 정규화된 VAE 잠재 변수입니다. condition_strengths (list, 선택 사항): 조건별 조건부 강도입니다. condition_indices (list, 선택 사항): 조건이 적용되는 조건별 잠재 프레임 인덱스입니다. condition_pixel_frames (list, 선택 사항): 단일 프레임 키프레임 좌표를 클램프하는 데 사용되는 조건별 잘린 픽셀 프레임 수입니다. reference_latents (Tensor, 선택 사항): [1, total_reference_tokens, C] 모양의 패킹된 참조 토큰 또는 참조 조건이 제공되지 않은 경우 None (LTX2AutoReferenceEncoderStep이 건너뜁니다). reference_coords (Tensor, 선택 사항): 참조 토큰을 위한 RoPE 좌표입니다. reference_token_counts (list, 선택 사항): reference_conditions 순서대로의 참조별 토큰 수입니다. latents (Tensor): 이미지 생성을 위한 사전 생성된 노이즈 잠재 변수입니다. noise_scale (float, 선택 사항): 비조건부 토큰의 초기 노이즈 수준입니다. None(기본값)은 사용자 지정 sigmas가 제공된 경우 sigmas[0]으로, 그렇지 않으면 1.0으로 결정됩니다. sigmas (list, 선택 사항): 디노이징 프로세스를 위한 사용자 지정 시그마입니다. reference_cross_mask (Tensor, 선택 사항): [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): 트랜스포머를 개별 토큰별 크로스 타임스텝에 조건부할지 여부입니다 (LTX-2.3+). attention_kwargs (dict,선택 사항): 주의 프로세서에 사용할 추가 kwargs입니다. image_latents (Tensor,선택 사항): 이미지-비디오 조건부에 사용되는 VAE 인코딩된 참조 이미지 잠재 변수입니다. output_type (str,선택 사항, 기본값 pil): 출력 형식: ‘pil’, ‘np’, ‘pt’. decode_timestep (None,선택 사항, 기본값 0.0): VAE가 최종 잠재 변수를 디코딩하는 타임스텝입니다. decode_noise_scale (None,선택 사항*): 디코딩 타임스텝에서 잠재 변수에 적용되는 노이즈 보간 계수입니다.

Outputs: videos (list): 생성된 비디오. audio (Tensor): 생성된 오디오 웨이브폼.

LTX25ModularPipeline

클래스 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부터 네이티브 기본값인 diffusion video decoder로 디코딩합니다. 체크포인트는 modular_model_index.json을 통해 여기로 라우팅됩니다.

LTX25AutoBlocks

클래스 diffusers.LTX25AutoBlocks

< >

( )

텍스트-투-비디오, 이미지-투-비디오, 조건-투-비디오 및 인-컨텍스트(IC-LoRA) 생성(비디오 + 오디오 결합)을 지원하는 LTX-2.5용 Auto 블록입니다. LTX2AutoBlocks와 동일하지만, LTX-2.5부터 기본값이 되는 네이티브 디퓨전 디코더를 사용하므로 비디오 디코더가 LTX2DiffusionVaeDecoderStep입니다. 대신 합성곱 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, 선택 사항): 프롬프트 향상 중에 생성할 새 토큰의 최대 수입니다. 기본값은 LTX-2.5 Gemma-4 향상기의 예산인 600입니다. prompt_enhancement_kwargs (dict, 선택 사항): 향상기의 .generate 호출에 사용할 키워드 인자입니다. 기본값은 탐욕 디코딩입니다. prompt_enhancement_seed (int, 선택 사항, 기본값 10): 프롬프트 향상을 위한 무작위 시드입니다 (LTX-2.5의 탐욕 디코딩에서는 효과가 없습니다). generator (Generator, 선택 사항): 결정론적 생성을 위한 Torch 생성기입니다. image (Image | list, 선택 사항): 디노이징을 위한 참조 이미지입니다. 단일 이미지 또는 이미지 목록일 수 있습니다. negative_prompt (str, 선택 사항): 이미지 생성을 안내하지 않을 프롬프트입니다. max_sequence_length (int, 선택 사항, 기본값 1024): 프롬프트 인코딩을 위한 최대 시퀀스 길이입니다. min_seconds (float, 선택 사항, 기본값 1.0): 자동 예측된 길이의 하한입니다. max_seconds (float, 선택 사항, 기본값 20.0): 자동 예측된 길이의 상한입니다. min_seconds보다 엄격하게 커야 합니다. frame_rate (float, 선택 사항, 기본값 24.0): 생성된 비디오의 초당 프레임 수입니다. height (int, 선택 사항, 기본값 512): 생성된 이미지의 픽셀 단위 높이입니다. width (int, 선택 사항, 기본값 704): 생성된 이미지의 픽셀 단위 너비입니다. image_crf (int, 선택 사항): VAE 인코딩 전에 조건부 image를 다시 압축하는 데 사용되는 H.264 CRF 값으로, 모델이 학습된 압축과 일치합니다. None(기본값)은 텍스트 인코더 생성에서 결정됩니다 (LTX-2.3까지는 33, LTX-2.5는 18). 다시 압축을 건너뛰려면 0을 전달합니다. 다시 압축이 실행될 때 PIL.Image.Image가 필요합니다. num_frames (int, 선택 사항): 생성된 비디오의 프레임 수입니다. 생략하면 duration_head를 통해 자동 예측됩니다 (LTX2AutoDurationStep 참조). reference_conditions (list, 선택 사항): LTX2ReferenceCondition (또는 그 목록)으로, 해당 비디오는 IC-LoRA 어댑터가 주의를 기울이는 추가 잠재 토큰으로 인코딩됩니다. reference_downscale_factor (int, 선택 사항, 기본값 1): 대상 해상도와 참조 해상도 사이의 비율입니다. 2는 참조가 대상 해상도의 절반으로 전처리됨을 의미합니다. 공간 좌표는 이 계수로 스케일링되어 참조 토큰이 대상 좌표 공간에 위치하도록 합니다. IC-LoRA 학습 시 사용된 계수와 일치해야 합니다. conditioning_attention_strength (float, 선택 사항, 기본값 1.0): 노이즈 토큰과 참조 토큰이 서로 얼마나 강하게 주의를 기울이는지 제어하는 [0, 1] 범위의 스칼라입니다. 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, 선택 사항): [1, C, F, H, W] 모양의 조건별 정규화된 VAE 잠재 변수입니다. condition_strengths (list, 선택 사항): 조건별 조건부 강도입니다. condition_indices (list, 선택 사항): 조건이 적용되는 조건별 잠재 프레임 인덱스입니다. condition_pixel_frames (list, 선택 사항): 단일 프레임 키프레임 좌표를 클램프하는 데 사용되는 조건별 잘린 픽셀 프레임 수입니다. reference_latents (Tensor, 선택 사항): [1, total_reference_tokens, C] 모양의 패킹된 참조 토큰 또는 참조 조건이 제공되지 않은 경우 None (LTX2AutoReferenceEncoderStep이 건너뜁니다). reference_coords (Tensor, 선택 사항): 참조 토큰을 위한 RoPE 좌표입니다. reference_token_counts (list, 선택 사항): reference_conditions 순서대로의 참조별 토큰 수입니다. latents (Tensor): 이미지 생성을 위한 사전 생성된 노이즈 잠재 변수입니다. noise_scale (float, 선택 사항): 비조건부 토큰의 초기 노이즈 수준입니다. None(기본값)은 사용자 지정 sigmas가 제공된 경우 sigmas[0]으로, 그렇지 않으면 1.0으로 결정됩니다. sigmas (list, 선택 사항): 디노이징 프로세스를 위한 사용자 지정 시그마입니다. reference_cross_mask (Tensor, 선택 사항): [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): 트랜스포머를 개별 토큰별 크로스 타임스텝에 조건부할지 여부입니다 (LTX-2.3+). attention_kwargs (dict,선택 사항): 주의 프로세서에 대한 추가 kwargs입니다. image_latents (Tensor,선택 사항): 이미지-비디오 조건부에 사용되는 VAE 인코딩된 참조 이미지 잠재 변수입니다. output_type (str,선택 사항*, 기본값 pil): 출력 형식: ‘pil’, ‘np’, ‘pt’.

Outputs: videos (list): 생성된 비디오. audio (Tensor): 생성된 오디오 웨이브폼.

Update on GitHub