Diffusers documentation
LTX-Video
LTX-Video
LTX-Video 是一款扩散 Transformer,专为从文本和图像快速、实时地生成高分辨率视频而设计。LTX-Video 的核心特性是 Video-VAE。Video-VAE 具有更高的像素到潜在空间的压缩比(1:192),从而实现更高效的视频数据处理和更快的生成速度。为了支持并防止生成过程中精细细节的丢失,Video-VAE 解码器会执行潜在空间到像素的转换 以及 最后一步去噪。
您可以在 Lightricks 组织下找到所有原始的 LTX-Video 检查点。
点击右侧边栏中的 LTX-Video 模型,以查看其他视频生成任务的更多示例。
下面的示例演示了如何生成针对内存或推理速度进行优化的视频。
有关各种内存节省技术的详细信息,请参阅 减少内存使用 指南。
下方的 LTX-Video 模型需要约 10GB 的显存。
import torch
from diffusers import LTXPipeline, AutoModel
from diffusers.hooks import apply_group_offloading
from diffusers.utils import export_to_video
# fp8 layerwise weight-casting
transformer = AutoModel.from_pretrained(
"Lightricks/LTX-Video",
subfolder="transformer",
dtype=torch.bfloat16
)
transformer.enable_layerwise_casting(
storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16
)
pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, dtype=torch.bfloat16)
# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True)
apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2)
apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level")
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"
video = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
width=768,
height=512,
num_frames=161,
decode_timestep=0.03,
decode_noise_scale=0.025,
num_inference_steps=50,
).frames[0]
export_to_video(video, "output.mp4", fps=24)编译在首次执行时较慢,但后续对 pipeline 的调用会更快。缓存也可以通过存储并复用中间输出来加速推理。
import torch
from diffusers import LTXPipeline
from diffusers.utils import export_to_video
pipeline = LTXPipeline.from_pretrained(
"Lightricks/LTX-Video", dtype=torch.bfloat16
)
# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
pipeline.transformer, mode="max-autotune", fullgraph=True
)
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"
video = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
width=768,
height=512,
num_frames=161,
decode_timestep=0.03,
decode_noise_scale=0.025,
num_inference_steps=50,
).frames[0]
export_to_video(video, "output.mp4", fps=24)备注
请参考来自 LTX-Video 仓库的以下推荐生成设置。
- transformer、VAE 和文本编码器的推荐 dtype 为
torch.bfloat16。VAE 和文本编码器也可以使用torch.float32或torch.float16。 - 对于 LTX-Video 的 guidance-distilled 变体,请将
guidance_scale设置为1.0。其他模型的guidance_scale应设置为更高的值,例如5.0,以获得良好的生成质量。 - 对于支持时间步的 VAE 变体(LTX-Video 0.9.1 及以上版本),请将
decode_timestep设置为0.05,并将image_cond_noise_scale设置为0.025。 - 对于支持在多个条件图像和视频之间进行插值的变体(LTX-Video 0.9.5 及以上版本),建议使用相似程度较高的图像和视频以获得最佳效果。与条件输入的差异可能会导致生成的视频中出现突兀的过渡。
- transformer、VAE 和文本编码器的推荐 dtype 为
LTX-Video 0.9.7 包含一个空间潜在上采样器和一个 13B 参数的 transformer。在推理过程中,会先生成低分辨率视频,然后对其进行上采样和细化。
显示示例代码
import torch from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition from diffusers.utils import export_to_video, load_video pipeline = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-dev", dtype=torch.bfloat16) pipeline_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipeline.vae, dtype=torch.bfloat16) pipeline.to("cuda") # or "mps", "xpu", "cpu" pipe_upsample.to("cuda") pipeline.vae.enable_tiling() def round_to_nearest_resolution_acceptable_by_vae(height, width): height = height - (height % pipeline.vae_temporal_compression_ratio) width = width - (width % pipeline.vae_temporal_compression_ratio) return height, width video = load_video( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4" )[:21] # only use the first 21 frames as conditioning condition1 = LTXVideoCondition(video=video, frame_index=0) prompt = """ The video depicts 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. """ negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" expected_height, expected_width = 768, 1152 downscale_factor = 2 / 3 num_frames = 161 # 1. Generate video at smaller resolution # Text-only conditioning is also supported without the need to pass `conditions` downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor) downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width) latents = pipeline( conditions=[condition1], prompt=prompt, negative_prompt=negative_prompt, width=downscaled_width, height=downscaled_height, num_frames=num_frames, num_inference_steps=30, decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=5.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="latent", ).frames # 2. Upscale generated video using latent upsampler with fewer inference steps # The available latent upsampler upscales the height/width by 2x upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2 upscaled_latents = pipe_upsample( latents=latents, output_type="latent" ).frames # 3. Denoise the upscaled video with few steps to improve texture (optional, but recommended) video = pipeline( conditions=[condition1], prompt=prompt, negative_prompt=negative_prompt, width=upscaled_width, height=upscaled_height, num_frames=num_frames, denoise_strength=0.4, # Effectively, 4 inference steps out of 10 num_inference_steps=10, latents=upscaled_latents, decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=5.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="pil", ).frames[0] # 4. Downscale the video to the expected resolution video = [frame.resize((expected_width, expected_height)) for frame in video] export_to_video(video, "output.mp4", fps=24)LTX-Video 0.9.7 蒸馏模型经过 guidance 和 timestep 蒸馏以加快生成速度。需要将
guidance_scale设置为1.0,并且num_inference_steps应设置在4到10之间,以获得良好的生成质量。为了获得最佳效果,还应使用以下自定义 timesteps。- 用于为放大做准备的基础模型推理:
[1000, 993, 987, 981, 975, 909, 725, 0.03]。 - 上采样:
[1000, 909, 725, 421, 0]。
显示示例代码
import torch from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition from diffusers.utils import export_to_video, load_video pipeline = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-distilled", dtype=torch.bfloat16) pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipeline.vae, dtype=torch.bfloat16) pipeline.to("cuda") # or "mps", "xpu", "cpu" pipe_upsample.to("cuda") pipeline.vae.enable_tiling() def round_to_nearest_resolution_acceptable_by_vae(height, width): height = height - (height % pipeline.vae_spatial_compression_ratio) width = width - (width % pipeline.vae_spatial_compression_ratio) return height, width prompt = """ artistic anatomical 3d render, utlra quality, human half full male body with transparent skin revealing structure instead of organs, muscular, intricate creative patterns, monochromatic with backlighting, lightning mesh, scientific concept art, blending biology with botany, surreal and ethereal quality, unreal engine 5, ray tracing, ultra realistic, 16K UHD, rich details. camera zooms out in a rotating fashion """ negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" expected_height, expected_width = 768, 1152 downscale_factor = 2 / 3 num_frames = 161 # 1. Generate video at smaller resolution downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor) downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width) latents = pipeline( prompt=prompt, negative_prompt=negative_prompt, width=downscaled_width, height=downscaled_height, num_frames=num_frames, timesteps=[1000, 993, 987, 981, 975, 909, 725, 0.03], decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=1.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="latent", ).frames # 2. Upscale generated video using latent upsampler with fewer inference steps # The available latent upsampler upscales the height/width by 2x upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2 upscaled_latents = pipe_upsample( latents=latents, adain_factor=1.0, output_type="latent" ).frames # 3. Denoise the upscaled video with few steps to improve texture (optional, but recommended) video = pipeline( prompt=prompt, negative_prompt=negative_prompt, width=upscaled_width, height=upscaled_height, num_frames=num_frames, denoise_strength=0.999, # Effectively, 4 inference steps out of 5 timesteps=[1000, 909, 725, 421, 0], latents=upscaled_latents, decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=1.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="pil", ).frames[0] # 4. Downscale the video to the expected resolution video = [frame.resize((expected_width, expected_height)) for frame in video] export_to_video(video, "output.mp4", fps=24)- 用于为放大做准备的基础模型推理:
LTX-Video 0.9.8 蒸馏模型与 0.9.7 变体类似。它经过了 guidance 和 timestep 蒸馏,可以使用与上文相同的推理代码。该版本的改进之处在于支持生成非常长的视频。此外,它支持使用 tone mapping 来提升生成视频的质量,可通过
tone_map_compression_ratio参数进行设置。建议使用默认值0.6。查看示例代码
import torch from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition from diffusers.models.latent_upscaler import LTXLatentUpsamplerModel from diffusers.utils import export_to_video, load_video pipeline = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.8-13B-distilled", dtype=torch.bfloat16) # TODO: Update the checkpoint here once updated in LTX org upsampler = LTXLatentUpsamplerModel.from_pretrained("a-r-r-o-w/LTX-0.9.8-Latent-Upsampler", dtype=torch.bfloat16) pipe_upsample = LTXLatentUpsamplePipeline(vae=pipeline.vae, latent_upsampler=upsampler).to(torch.bfloat16) pipeline.to("cuda") # or "mps", "xpu", "cpu" pipe_upsample.to("cuda") pipeline.vae.enable_tiling() def round_to_nearest_resolution_acceptable_by_vae(height, width): height = height - (height % pipeline.vae_spatial_compression_ratio) width = width - (width % pipeline.vae_spatial_compression_ratio) return height, width prompt = """The camera pans over a snow-covered mountain range, revealing a vast expanse of snow-capped peaks and valleys.The mountains are covered in a thick layer of snow, with some areas appearing almost white while others have a slightly darker, almost grayish hue. The peaks are jagged and irregular, with some rising sharply into the sky while others are more rounded. The valleys are deep and narrow, with steep slopes that are also covered in snow. The trees in the foreground are mostly bare, with only a few leaves remaining on their branches. The sky is overcast, with thick clouds obscuring the sun. The overall impression is one of peace and tranquility, with the snow-covered mountains standing as a testament to the power and beauty of nature.""" # prompt = """A woman walks away from a white Jeep parked on a city street at night, then ascends a staircase and knocks on a door. The woman, wearing a dark jacket and jeans, walks away from the Jeep parked on the left side of the street, her back to the camera; she walks at a steady pace, her arms swinging slightly by her sides; the street is dimly lit, with streetlights casting pools of light on the wet pavement; a man in a dark jacket and jeans walks past the Jeep in the opposite direction; the camera follows the woman from behind as she walks up a set of stairs towards a building with a green door; she reaches the top of the stairs and turns left, continuing to walk towards the building; she reaches the door and knocks on it with her right hand; the camera remains stationary, focused on the doorway; the scene is captured in real-life footage.""" negative_prompt = "bright colors, symbols, graffiti, watermarks, worst quality, inconsistent motion, blurry, jittery, distorted" expected_height, expected_width = 480, 832 downscale_factor = 2 / 3 # num_frames = 161 num_frames = 361 # 1. Generate video at smaller resolution downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor) downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width) latents = pipeline( prompt=prompt, negative_prompt=negative_prompt, width=downscaled_width, height=downscaled_height, num_frames=num_frames, timesteps=[1000, 993, 987, 981, 975, 909, 725, 0.03], decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=1.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="latent", ).frames # 2. Upscale generated video using latent upsampler with fewer inference steps # The available latent upsampler upscales the height/width by 2x upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2 upscaled_latents = pipe_upsample( latents=latents, adain_factor=1.0, tone_map_compression_ratio=0.6, output_type="latent" ).frames # 3. Denoise the upscaled video with few steps to improve texture (optional, but recommended) video = pipeline( prompt=prompt, negative_prompt=negative_prompt, width=upscaled_width, height=upscaled_height, num_frames=num_frames, denoise_strength=0.999, # Effectively, 4 inference steps out of 5 timesteps=[1000, 909, 725, 421, 0], latents=upscaled_latents, decode_timestep=0.05, decode_noise_scale=0.025, image_cond_noise_scale=0.0, guidance_scale=1.0, guidance_rescale=0.7, generator=torch.Generator().manual_seed(0), output_type="pil", ).frames[0] # 4. Downscale the video to the expected resolution video = [frame.resize((expected_width, expected_height)) for frame in video] export_to_video(video, "output.mp4", fps=24)LTX-Video 支持通过 load_lora_weights() 加载 LoRA。
查看示例代码
import torch from diffusers import LTXConditionPipeline from diffusers.utils import export_to_video, load_image pipeline = LTXConditionPipeline.from_pretrained( "Lightricks/LTX-Video-0.9.5", dtype=torch.bfloat16 ) pipeline.load_lora_weights("Lightricks/LTX-Video-Cakeify-LoRA", adapter_name="cakeify") pipeline.set_adapters("cakeify") # use "CAKEIFY" to trigger the LoRA prompt = "CAKEIFY a person using a knife to cut a cake shaped like a Pikachu plushie" image = load_image("https://huggingface.co/Lightricks/LTX-Video-Cakeify-LoRA/resolve/main/assets/images/pikachu.png") video = pipeline( prompt=prompt, image=image, width=576, height=576, num_frames=161, decode_timestep=0.03, decode_noise_scale=0.025, num_inference_steps=50, ).frames[0] export_to_video(video, "output.mp4", fps=26)LTX-Video supports loading from single files, such as GGUF checkpoints, with loaders.FromOriginalModelMixin.from_single_file() or loaders.FromSingleFileMixin.from_single_file().
查看示例代码
import torch from diffusers.utils import export_to_video from diffusers import LTXPipeline, AutoModel, GGUFQuantizationConfig transformer = AutoModel.from_single_file( "https://huggingface.co/city96/LTX-Video-gguf/blob/main/ltx-video-2b-v0.9-Q3_K_S.gguf" quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16), dtype=torch.bfloat16 ) pipeline = LTXPipeline.from_pretrained( "Lightricks/LTX-Video", transformer=transformer, dtype=torch.bfloat16 )
LTXI2VLongMultiPromptPipeline
class diffusers.LTXI2VLongMultiPromptPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5TokenizerFasttransformer: LTXVideoTransformer3DModel )
参数
- transformer (LTXVideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
- scheduler(FlowMatchEulerDiscreteScheduler 或
LTXEulerAncestralRFScheduler)—— 用于与transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKLLTXVideo) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
- text_encoder (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
T5TokenizerFast) — T5TokenizerFast 类的分词器。
支持 ComfyUI 等效功能的长时长 I2V(图像到视频)多提示词流水线。
主要功能:
- 仅使用时序滑动窗口采样(不进行空间 H/W 分片);在窗口之间进行自回归融合。
- 在每个窗口内执行多提示分割,并在窗口头部实现平滑过渡。
- 通过逐 token 掩码对 I2V 进行首帧硬条件约束。
- 通过时间窗口和 VAE 分块解码来控制 VRAM。
参考:https://github.com/Lightricks/LTX-Video
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneprompt_segments: list[dict[str, Any]] | None = Noneheight: int = 512width: int = 704num_frames: int = 161frame_rate: float = 25guidance_scale: float = 1.0guidance_rescale: float = 0.0num_inference_steps: int | None = 8sigmas: list[float, torch.Tensor] | None = Nonegenerator: torch.Generator | list[torch.Generator] | None = Noneseed: int | None = 0cond_image: 'PIL.Image.Image' | torch.Tensor | None = Nonecond_strength: float = 0.5latents: torch.Tensor | None = Nonetemporal_tile_size: int = 80temporal_overlap: int = 24temporal_overlap_cond_strength: float = 0.5adain_factor: float = 0.25guidance_latents: torch.Tensor | None = Noneguiding_strength: float = 1.0negative_index_latents: torch.Tensor | None = Nonenegative_index_strength: float = 1.0skip_steps_sigma_threshold: float | None = 1decode_timestep: float | None = 0.05decode_noise_scale: float | None = 0.025decode_horizontal_tiles: int = 4decode_vertical_tiles: int = 4decode_overlap: int = 3output_type: str | None = 'latent'return_dict: bool = Trueattention_kwargs: dict[str, Any] | None = Nonecallback_on_step_end: Callable[[int, int], None] | None = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 每个窗口的正向文本提示。如果单个字符串中包含 ’|’,则按竖线进行拆分。 - negative_prompt (
str或list[str],可选) — 用于抑制不期望内容的负面提示词。 - prompt_segments (
list[dict], 可选) — 分段映射,包含 {“start_window”, “end_window”, “text”},用于按窗口覆盖提示词。 - height (
int,默认为512) — 输出图像的高度(以像素为单位);必须能被 32 整除。 - width (
int,默认为704) — 输出图像的宽度(以像素为单位);必须能被 32 整除。 - num_frames (
int,默认为161) — 输出帧数(在解码后的像素空间中)。 - frame_rate (
float,默认为25) — 每秒帧数;用于对video_coords中的时间坐标进行归一化。 - guidance_scale (
float,默认为1.0) — CFG 缩放系数;值大于 1 时启用无分类器引导。 - guidance_rescale (
float,默认为0.0) — 可选的重缩放,用于缓解 CFG 下的过度曝光问题(参见rescale_noise_cfg)。 - num_inference_steps(
int,可选,默认值为8)— 每个窗口的去噪步数。如果提供了sigmas,则忽略此参数。 - sigmas (
list[float]或torch.Tensor,可选) — 每个窗口的显式 sigma 调度;如果设置,将覆盖num_inference_steps。 - generator (
torch.Generator或list[torch.Generator],可选) — 控制随机性;接受列表,但仅使用第一个元素(batch=1)。 - seed (
int,可选,默认为0) — 如果提供,将为全局潜变量(global latents)的共享生成器设置种子,并为每个时间窗口派生一个使用seed + w_start作为种子的窗口局部生成器。 - cond_image (
PIL.Image.Image或torch.Tensor,可选) — 条件图像;当cond_strength > 0时,通过逐 token 掩码固定第 0 帧。 - cond_strength (
float,默认为0.5) — 首帧硬条件化的强度(cond_mask 越小,保留效果越强)。 - latents (
torch.Tensor, 可选) — 初始潜变量 [B, C_lat, F_lat, H_lat, W_lat];如果为 None,则使用randn_tensor进行采样。 - temporal_tile_size (
int,默认为80) — 时间窗口大小(以解码后的帧数计);内部会根据 VAE 的时间压缩进行缩放。 - temporal_overlap (
int,默认为24) — 连续窗口之间的重叠(以解码帧为单位);内部会根据压缩率进行缩放。 - temporal_overlap_cond_strength (
float,默认为0.5) — 在新窗口头部注入前一个窗口尾部潜在表示时的强度。 - adain_factor (
float,默认为0.25) — 用于跨窗口一致性的 AdaIN 归一化强度(设为 0 表示禁用)。 - guidance_latents(
torch.Tensor,可选)— 在窗口头部注入的参考潜变量;对于后续窗口,其长度会根据重叠部分进行裁剪。 - guiding_strength (
float,默认为1.0) —guidance_latents的注入强度。 - negative_index_latents (
torch.Tensor,可选) — 在窗口头部追加的单帧潜在表示,用于实现“负索引”语义。 - negative_index_strength (
float,默认为1.0) —negative_index_latents的注入强度。 - skip_steps_sigma_threshold(
float,可选,默认值为1)— 跳过 sigma 超过此阈值的步骤。 - decode_timestep (
float,可选,默认为0.05) — 解码时的时间步(如果 VAE 支持 timestep_conditioning)。 - decode_noise_scale (
float, 可选,默认为0.025) — 解码时的噪声混合比例(如果 VAE 支持 timestep_conditioning)。 - decode_horizontal_tiles (
int,默认为4) — VAE 解码期间的水平瓦片数量。 - decode_vertical_tiles (
int,默认为4) — VAE 解码时的垂直瓦片数量。 - decode_overlap (
int,默认为3) — 在 VAE 解码过程中,tile 之间的重叠区域(以潜在像素为单位)。 - output_type (
str,可选,默认为"latent") — 生成视频的输出格式。可选值包括 “latent”、“pt”、“np” 或 “pil”。如果设置为 “latent”,则返回未解码的潜变量。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.ltx.LTXPipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 转发给 transformer 的额外注意力参数。 - callback_on_step_end(
PipelineCallback或MultiPipelineCallbacks,可选)— 逐步回调钩子。 - callback_on_step_end_tensor_inputs(
list[str],默认为["latents"])— 要传递给回调函数的 locals() 中的键。 - max_sequence_length (
int,默认为128) — 用于提示词编码的分词器最大长度。
返回值
~pipelines.ltx.LTXPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.ltx.LTXPipelineOutput;否则返回一个 tuple,其中第一个元素是包含生成帧的列表。输出格式取决于 output_type:
- “latent”/“pt”:
torch.Tensor[B, C, F, H, W];“latent” 位于归一化的潜在空间,“pt” 位于 VAE 输出空间。 - “np”:经过后处理的
np.ndarray。 - “pil”:
list[PIL.Image.Image]PIL 图像列表。
通过时间滑动窗口和多提示词调度生成图像到视频的序列。
示例:
>>> import torch
>>> from diffusers import LTXEulerAncestralRFScheduler, LTXI2VLongMultiPromptPipeline
>>> pipe = LTXI2VLongMultiPromptPipeline.from_pretrained("LTX-Video-0.9.8-13B-distilled")
>>> # For ComfyUI parity, swap in the RF scheduler (keeps the original config).
>>> pipe.scheduler = LTXEulerAncestralRFScheduler.from_config(pipe.scheduler.config)
>>> pipe = pipe.to("cuda").to(dtype=torch.bfloat16)
>>> # Example A: get decoded frames (PIL)
>>> out = pipe(
... prompt="a chimpanzee walks | a chimpanzee eats",
... num_frames=161,
... height=512,
... width=704,
... temporal_tile_size=80,
... temporal_overlap=24,
... output_type="pil",
... return_dict=True,
... )
>>> frames = out.frames[0] # list of PIL.Image.Image
>>> # Example B: get latent video and decode later (saves VRAM during sampling)
>>> out_latent = pipe(prompt="a chimpanzee walking", output_type="latent", return_dict=True).frames
>>> frames = pipe.vae_decode_tiled(out_latent, output_type="pil")[0]形状: 潜在尺寸(当自动生成时):
- F_lat = (num_frames - 1) // vae_temporal_compression_ratio + 1
- H_lat = height // vae_spatial_compression_ratio
- W_lat = width // vae_spatial_compression_ratio
注意事项:
- Seeding:当提供
seed时,每个时间窗口都会使用以seed + w_start为种子的局部生成器;如果未传入生成器,则共享生成器仅针对全局潜变量初始化一次;否则,将复用传入的生成器。 - CFG:统一的
noise_pred = uncond + w * (text - uncond),并可选使用guidance_rescale。 - 内存:去噪执行全帧预测(不进行空间分块);解码可以分块以避免 OOM。
encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: torch.Tensor | None = Nonenegative_prompt_embeds: torch.Tensor | None = Noneprompt_attention_mask: torch.Tensor | None = Nonenegative_prompt_attention_mask: torch.Tensor | None = Nonemax_sequence_length: int = 128device: torch.device | None = Nonedtype: torch.dtype | None = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - do_classifier_free_guidance(
bool,可选,默认为True)— 是否使用 classifier free guidance。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - device — (
torch.device,可选): torch 设备 - dtype — (
torch.dtype,可选): torch 数据类型
将提示词编码为文本编码器的隐藏状态。
prepare_latents
< source >( batch_size: intnum_channels_latents: intheight: intwidth: intnum_frames: intdevice: torch.devicegenerator: torch.Generator | Nonedtype: torch.dtype = torch.float32latents: torch.Tensor | None = Nonecond_latents: torch.Tensor | None = Nonecond_strength: float = 0.0negative_index_latents: torch.Tensor | None = None )
准备基础潜变量,并可选择注入首帧条件潜变量。
vae_decode_tiled
< source >( latents: torch.Tensordecode_timestep: float | None = Nonedecode_noise_scale: float | None = Nonehorizontal_tiles: int = 4vertical_tiles: int = 4overlap: int = 3last_frame_fix: bool = Truegenerator: torch.Generator | None = Noneoutput_type: str = 'pt'auto_denormalize: bool = Truecompute_dtype: torch.dtype = torch.float32enable_vae_tiling: bool = False ) →
参数
- latents — [B, C_latent, F_latent, H_latent, W_latent]
- decode_timestep — 可选的解码时间步(仅在 VAE 支持 timestep_conditioning 时生效)
- decode_noise_scale — 可选的解码噪声插值(仅在 VAE 支持 timestep_conditioning 时生效)
- horizontal_tiles, vertical_tiles — 水平/垂直方向上的瓦片数量(>= 1)
- overlap — 潜在空间中的重叠(以潜在像素为单位,>= 0)
- last_frame_fix — 是否启用“重复最后一帧”修复
- generator — 随机数生成器(用于 decode_noise_scale 噪声)
- output_type — “latent” | “pt” | “np” | “pil”
- “latent”:原样返回潜在变量(适用于下游处理)
- “pt”:返回 VAE 输出空间中的张量
- “np”/“pil”:通过 VideoProcessor.postprocess_video 进行后处理的输出
- auto_denormalize — 如果为 True,则内部对
latents应用 LTX 反归一化(推荐) - compute_dtype — 在 tile 融合过程中使用的精度(默认为 float32;可显著减少接缝模糊)
- enable_vae_tiling — 如果为 True,则将分块处理委托给 VAE 内置的
tiled_decode(设置vae.use_tiling)。
返回值
- 如果 output_type="latent"
返回未修改的输入 latents
- 如果 output_type="pt":返回 [B, C, F, H, W](值大致在 [-1, 1] 范围内)
- 如果 output_type=“np”/“pil”:通过 postprocess_video 返回后处理后的输出
以 Diffusers 风格实现的基于 VAE 的空间分块解码(与 ComfyUI 保持一致)。
- 对重叠的图块进行线性羽化和混合,以避免接缝。
- 可选的 last_frame_fix:在解码前复制最后一个潜在帧,然后在末尾丢弃 time_scale_factor 帧。
- 支持 timestep_conditioning 和 decode_noise_scale 注入。
- 默认情况下,“归一化潜在变量”(去噪输出)会在内部进行反归一化处理(auto_denormalize=True)。
- Tile fusion 在 compute_dtype(默认为 float32)中计算,以减少模糊和颜色偏移。
LTXPipeline
类 diffusers.LTXPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
参数
- transformer (LTXVideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKLLTXVideo) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
- text_encoder (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer (
T5TokenizerFast) — 第二个 T5TokenizerFast 类的 Tokenizer。
用于文本到视频生成的 Pipeline。
参考:https://github.com/Lightricks/LTX-Video
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 512width: int = 704num_frames: int = 161frame_rate: int = 25num_inference_steps: int = 50timesteps: list[int] = Noneguidance_scale: float = 3guidance_rescale: float = 0.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: 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 = Noneoutput_type: str | None = '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[str] = ['latents']max_sequence_length: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput 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,默认为704) — 生成图像的宽度(以像素为单位)。默认设置为 848 以获得最佳效果。 - num_frames (
int,默认为161) — 要生成的视频帧数 - frame_rate (
int,默认为25) — 生成视频的目标帧率。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - guidance_scale (
float,默认为3) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。 - guidance_rescale (
float, optional, defaults to 0.0) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleis 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. - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词生成的视频数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - prompt_attention_mask (
torch.Tensor,可选) — 为文本嵌入预生成的注意力掩码。 - negative_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向文本嵌入。对于 PixArt-Sigma,此负向提示应为 ""。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_prompt_attention_mask (
torch.FloatTensor, 可选) — 为负向文本嵌入预生成的注意力掩码。 - decode_timestep (
float,默认为0.0) — 用于解码生成视频的 timestep。 - decode_noise_scale (
float,默认为None) — 在解码时间步上,随机噪声与去噪潜在表示之间的插值因子。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.ltx.LTXPipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
list,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为128)— 与prompt配合使用的最大序列长度。
返回值
~pipelines.ltx.LTXPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.ltx.LTXPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import LTXPipeline
>>> from diffusers.utils import export_to_video
>>> pipe = LTXPipeline.from_pretrained("Lightricks/LTX-Video", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> 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"
>>> video = pipe(
... prompt=prompt,
... negative_prompt=negative_prompt,
... width=704,
... height=480,
... num_frames=161,
... num_inference_steps=50,
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=24)encode_prompt
< source >( 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 = 128device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - do_classifier_free_guidance(
bool,可选,默认为True)— 是否使用 classifier free guidance。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - device — (
torch.device,可选): torch 设备 - dtype — (
torch.dtype,可选): torch 数据类型
将提示词编码为文本编码器的隐藏状态。
LTXImageToVideoPipeline
类 diffusers.LTXImageToVideoPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
参数
- transformer (LTXVideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKLLTXVideo) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
- text_encoder (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer (
T5TokenizerFast) — 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像到视频生成的 Pipeline。
参考:https://github.com/Lightricks/LTX-Video
__call__
< source >( 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 = 704num_frames: int = 161frame_rate: int = 25num_inference_steps: int = 50timesteps: list[int] = Noneguidance_scale: float = 3guidance_rescale: float = 0.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: 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 = Noneoutput_type: str | None = '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[str] = ['latents']max_sequence_length: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput 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,默认为704) — 生成图像的宽度(以像素为单位)。默认设置为 848 以获得最佳效果。 - num_frames (
int,默认为161) — 要生成的视频帧数 - frame_rate (
int,默认为25) — 生成视频的目标帧率。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - guidance_scale (
float,默认为3) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。 - guidance_rescale (
float, optional, defaults to 0.0) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleis 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. - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词生成的视频数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - prompt_attention_mask (
torch.Tensor,可选) — 为文本嵌入预生成的注意力掩码。 - negative_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向文本嵌入。对于 PixArt-Sigma,此负向提示应为 ""。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_prompt_attention_mask (
torch.FloatTensor, 可选) — 为负向文本嵌入预生成的注意力掩码。 - decode_timestep (
float,默认为0.0) — 用于解码生成视频的 timestep。 - decode_noise_scale (
float,默认为None) — 在解码时间步上,随机噪声与去噪潜在表示之间的插值因子。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.ltx.LTXPipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
list,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为128)— 与prompt配合使用的最大序列长度。
返回值
~pipelines.ltx.LTXPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.ltx.LTXPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import LTXImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> pipe = LTXImageToVideoPipeline.from_pretrained("Lightricks/LTX-Video", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> 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. Flames engulf the structure, with smoke billowing into the air. Firefighters in protective gear rush to the scene, a fire truck labeled '38' visible behind them. The girl's neutral expression contrasts sharply with the chaos of the fire, creating a poignant and emotionally charged scene."
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
>>> video = pipe(
... image=image,
... prompt=prompt,
... negative_prompt=negative_prompt,
... width=704,
... height=480,
... num_frames=161,
... num_inference_steps=50,
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=24)encode_prompt
< source >( 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 = 128device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - do_classifier_free_guidance(
bool,可选,默认为True)— 是否使用 classifier free guidance。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - device — (
torch.device,可选): torch 设备 - dtype — (
torch.dtype,可选): torch 数据类型
将提示词编码为文本编码器的隐藏状态。
LTXConditionPipeline
类 diffusers.LTXConditionPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
参数
- transformer (LTXVideoTransformer3DModel) — 用于对编码后的视频潜在变量进行去噪的条件 Transformer 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKLLTXVideo) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
- text_encoder (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer (
T5TokenizerFast) — 第二个 T5TokenizerFast 类的 Tokenizer。
用于文本/图像/视频到视频生成的 Pipeline。
参考:https://github.com/Lightricks/LTX-Video
__call__
< source >( conditions: diffusers.pipelines.ltx.pipeline_ltx_condition.LTXVideoCondition | list[diffusers.pipelines.ltx.pipeline_ltx_condition.LTXVideoCondition] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] = Noneframe_index: int | list[int] = 0strength: float | list[float] = 1.0denoise_strength: float = 1.0prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 512width: int = 704num_frames: int = 161frame_rate: int = 25num_inference_steps: int = 50timesteps: list[int] = Noneguidance_scale: float = 3guidance_rescale: float = 0.0image_cond_noise_scale: float = 0.15num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: 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 = Noneoutput_type: str | None = '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[str] = ['latents']max_sequence_length: int = 256 ) → ~pipelines.ltx.LTXPipelineOutput or tuple
参数
- conditions (
list[LTXVideoCondition], *optional*) — 用于视频生成的帧条件项列表。如果未提供,将使用image、video、frame_index和strength来创建条件。 - image (
PipelineImageInput或list[PipelineImageInput],可选) — 用于条件化视频生成的图像。如果未提供,则必须传入video或conditions。 - video (
list[PipelineImageInput],可选) — 用于条件化视频生成的视频。如果未提供,则必须传入image或conditions。 - frame_index (
int或list[int],可选) — 图像或视频将条件性地影响视频生成的帧索引或帧索引列表。如果未提供,则必须传入conditions。 - strength (
float或list[float],可选) — 条件效果的强度。如果未提供,则必须传入conditions。 - denoise_strength (
float,默认为1.0) — 用于编辑时添加到潜在表示中的噪声强度。强度越高,添加到潜在表示中的噪声越多,因此原始视频与生成视频之间的差异也越大。这对于视频到视频的编辑非常有用。 - prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - negative_prompt (
str或list[str],可选) — 用于引导图像生成的负面提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。 - height (
int,默认为512) — 生成图像的高度(以像素为单位)。默认设置为 480 以获得最佳效果。 - width (
int,默认为704) — 生成图像的宽度(以像素为单位)。默认设置为 848 以获得最佳效果。 - num_frames (
int,默认为161) — 要生成的视频帧数 - frame_rate (
int,默认为25) — 生成视频的目标帧率。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - guidance_scale (
float,默认为3) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。 - guidance_rescale (
float, optional, defaults to 0.0) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleis 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. - image_cond_noise_scale (
float,默认为0.15) — 添加到条件图像潜在表示中的噪声的缩放比例。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词生成的视频数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - prompt_attention_mask (
torch.Tensor,可选) — 为文本嵌入预生成的注意力掩码。 - negative_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向文本嵌入。对于 PixArt-Sigma,此负向提示应为 ""。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_prompt_attention_mask (
torch.FloatTensor, 可选) — 为负向文本嵌入预生成的注意力掩码。 - decode_timestep (
float,默认为0.0) — 用于解码生成视频的 timestep。 - decode_noise_scale (
float,默认为None) — 在解码时间步上,随机噪声与去噪潜在表示之间的插值因子。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.ltx.LTXPipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
list,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为128)— 与prompt配合使用的最大序列长度。
返回值
~pipelines.ltx.LTXPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.ltx.LTXPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXConditionPipeline, LTXVideoCondition
>>> from diffusers.utils import export_to_video, load_video, load_image
>>> pipe = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.5", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> # Load input image and video
>>> video = load_video(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4"
... )
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input.jpg"
... )
>>> # Create conditioning objects
>>> condition1 = LTXVideoCondition(
... image=image,
... frame_index=0,
... )
>>> condition2 = LTXVideoCondition(
... video=video,
... frame_index=80,
... )
>>> 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."
>>> negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
>>> # Generate video
>>> generator = torch.Generator("cuda").manual_seed(0)
>>> # Text-only conditioning is also supported without the need to pass `conditions`
>>> video = pipe(
... conditions=[condition1, condition2],
... prompt=prompt,
... negative_prompt=negative_prompt,
... width=768,
... height=512,
... num_frames=161,
... num_inference_steps=40,
... generator=generator,
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=24)add_noise_to_image_conditioning_latents
< source >( t: floatinit_latents: Tensorlatents: Tensornoise_scale: floatconditioning_mask: Tensorgeneratoreps = 1e-06 )
为硬条件潜变量添加时间步相关的噪声。这有助于提升运动连续性,尤其是在仅以单帧作为条件时。
encode_prompt
< source >( 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 = 256device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - do_classifier_free_guidance(
bool,可选,默认为True)— 是否使用 classifier free guidance。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量。用于放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - device — (
torch.device,可选): torch 设备 - dtype — (
torch.dtype,可选): torch 数据类型
将提示词编码为文本编码器的隐藏状态。
trim_conditioning_sequence
< source >( start_frame: intsequence_num_frames: inttarget_num_frames: int ) → int
将条件序列裁剪至允许的帧数。
LTXLatentUpsamplePipeline
class diffusers.LTXLatentUpsamplePipeline
< source >( vae: AutoencoderKLLTXVideolatent_upsampler: LTXLatentUpsamplerModel )
__call__
< source >( 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 = 704latents: typing.Optional[torch.Tensor] = Nonedecode_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],可选) — 用于上采样的输入视频帧。与latents互斥。 - height (
int,默认为512) — 上采样输出的像素高度。 - width (
int,默认为704) — 上采样输出的宽度(以像素为单位)。 - latents (
torch.Tensor, 可选) — 用于上采样的预编码视频潜变量。与video互斥。 - decode_timestep (
float或list[float],默认为0.0) — 用于解码上采样后潜变量的时间步。 - decode_noise_scale (
float或list[float],可选) — 在解码时间步上,随机噪声与去噪潜在表示之间的插值因子。 - adain_factor (
float,默认为0.0) — 应用于上采样潜变量的 AdaIN 统计匹配强度。 - tone_map_compression_ratio (
float,默认为0.0) — 用于对放大后的 latents 进行色调映射的压缩比。取值范围必须在 [0, 1] 之间。 - generator (
torch.Generator或list[torch.Generator],可选) — 用于使生成过程确定性的torch.Generator。 - output_type (
str,可选,默认为"pil") — 生成视频的输出格式。可选PIL.Image、np.array或latent。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.ltx.LTXPipelineOutput而不是普通元组。
返回值
~pipelines.ltx.LTXPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.ltx.LTXPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是上采样后的视频(如果 output_type="latent",则为潜在表示)。
调用用于潜在上采样的 pipeline 时调用的函数。
adain_filter_latent
< source >( latents: Tensorreference_latents: Tensorfactor: float = 1.0 ) → torch.Tensor
根据参考潜在张量的统计量,对潜在张量应用自适应实例归一化(AdaIN)。
tone_map_latents
< source >( latents: Tensorcompression: float )
使用基于 sigmoid 的压缩,对潜在值应用非线性色调映射函数,以感知平滑的方式降低其动态范围。
这在正则化高方差潜在变量或在生成过程中对输出进行条件化时非常有用,尤其是在使用compression因子控制动态行为时。
LTXPipelineOutput
class diffusers.pipelines.ltx.pipeline_output.LTXPipelineOutput
< source >( frames: Tensor )
LTX 流水线的输出类。