Diffusers 文档
LTX-视频
并获得增强的文档体验
开始使用
LTX-视频
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",
torch_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, torch_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)
注意事项
请参考 LTX-Video 仓库中推荐的生成设置。
- Transformer、VAE 和文本编码器推荐的数据类型是
torch.bfloat16
。VAE 和文本编码器也可以是torch.float32
或torch.float16
。 - 对于 LTX-Video 的引导蒸馏变体,将
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 及以上版本),请使用相似的图像和视频以获得最佳结果。偏离条件输入可能会导致生成的视频中出现 abrupt transitionts。
- Transformer、VAE 和文本编码器推荐的数据类型是
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", torch_dtype=torch.bfloat16) pipeline_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipeline.vae, torch_dtype=torch.bfloat16) pipeline.to("cuda") 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_scale
设置为1.0
,并且num_inference_steps
应设置在4
到10
之间以获得良好的生成质量。您还应使用以下自定义时间步以获得最佳结果。- 为上采样做准备的基础模型推理:
[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", torch_dtype=torch.bfloat16) pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipeline.vae, torch_dtype=torch.bfloat16) pipeline.to("cuda") 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 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 支持使用 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", torch_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 支持从单个文件加载,例如 GGUF 检查点,使用 loaders.FromOriginalModelMixin.from_single_file() 或 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), torch_dtype=torch.bfloat16 ) pipeline = LTXPipeline.from_pretrained( "Lightricks/LTX-Video", transformer=transformer, torch_dtype=torch.bfloat16 )
LTXPipeline
类 diffusers.LTXPipeline
< 源代码 >( 调度器: FlowMatchEulerDiscreteScheduler vae: AutoencoderKLLTXVideo 文本编码器: T5EncoderModel 分词器: T5TokenizerFast Transformer: LTXVideoTransformer3DModel )
参数
- Transformer (LTXVideoTransformer3DModel) — 用于对编码视频潜在表示进行去噪的条件 Transformer 架构。
- 调度器 (FlowMatchEulerDiscreteScheduler) — 与
transformer
结合使用的调度器,用于对编码图像潜在表示进行去噪。 - vae (AutoencoderKLLTXVideo) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
- text_encoder (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - 分词器 (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - 分词器 (
T5TokenizerFast
) — 第二个 T5TokenizerFast 类的分词器。
用于文本到视频生成的流水线。
参考资料:https://github.com/Lightricks/LTX-Video
__call__
< 源代码 >( 提示词: typing.Union[str, typing.List[str]] = None 负向提示词: typing.Union[str, typing.List[str], NoneType] = None 高度: int = 512 宽度: int = 704 帧数: int = 161 帧率: int = 25 推理步数: int = 50 时间步: typing.List[int] = None 引导比例: float = 3 引导重缩放: float = 0.0 每个提示的视频数量: typing.Optional[int] = 1 生成器: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None 潜在向量: typing.Optional[torch.Tensor] = None 提示词嵌入: typing.Optional[torch.Tensor] = None 提示词注意力掩码: typing.Optional[torch.Tensor] = None 负向提示词嵌入: typing.Optional[torch.Tensor] = None 负向提示词注意力掩码: typing.Optional[torch.Tensor] = None 解码时间步: typing.Union[float, typing.List[float]] = 0.0 解码噪声比例: typing.Union[float, typing.List[float], NoneType] = None 输出类型: typing.Optional[str] = 'pil' 返回字典: bool = True 注意力参数: typing.Optional[typing.Dict[str, typing.Any]] = None 步结束回调: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None 步结束张量输入回调: typing.List[str] = ['latents'] 最大序列长度: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput
或 元组
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须传入prompt_embeds
。 - height (
int
, 默认为512
) — 生成图像的高度(像素)。为获得最佳效果,默认设置为 480。 - width (
int
, 默认为704
) — 生成图像的宽度(像素)。为获得最佳效果,默认设置为 848。 - num_frames (
int
, 默认为161
) — 要生成的视频帧数 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步数。更多去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步,适用于支持在其set_timesteps
方法中带有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
, 可选, 默认为 0.0) — 常见的扩散噪声调度和样本步骤存在缺陷 中提出的引导重缩放因子。guidance_scale
定义为 常见的扩散噪声调度和样本步骤存在缺陷 中公式 16 的φ
。引导重缩放因子应修复使用零终端信噪比时的过曝问题。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示词生成的视频数量。 - 生成器 (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。 - 潜在变量 (
torch.Tensor
, 可选) — 预生成的带噪声的潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在变量张量。 - 提示词嵌入 (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - 提示词注意力掩码 (
torch.Tensor
, 可选) — 预生成的文本嵌入注意力掩码。 - 负提示词嵌入 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入。对于 PixArt-Sigma,此负提示词应为""。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - 负提示词注意力掩码 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入注意力掩码。 - 解码时间步长 (
float
, 默认为0.0
) — 生成视频的解码时间步长。 - 解码噪声比例 (
float
, 默认为None
) — 在解码时间步长处,随机噪声与去噪潜在变量之间的插值因子。 - 输出类型 (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。选择 PIL:PIL.Image.Image
或np.array
。 - 返回字典 (
bool
, 可选, 默认为True
) — 是否返回~pipelines.ltx.LTXPipelineOutput
而不是普通元组。 - 注意力 kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则传递给 diffusers.models.attention_processor 中self.processor
下定义的AttentionProcessor
。 - 每步结束回调函数 (
Callable
, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。该函数以以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量列表。 - 每步结束回调张量输入 (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - 最大序列长度 (
int
默认为128
) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.ltx.LTXPipelineOutput
或 tuple
如果 return_dict
为 True
,则返回 ~pipelines.ltx.LTXPipelineOutput
,否则返回一个 tuple
,其中第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> 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)
编码提示
< 来源 >( 提示: typing.Union[str, typing.List[str]] 负提示: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True 每个提示的视频数量: int = 1 提示词嵌入: typing.Optional[torch.Tensor] = None 负提示词嵌入: typing.Optional[torch.Tensor] = None 提示词注意力掩码: typing.Optional[torch.Tensor] = None 负提示词注意力掩码: typing.Optional[torch.Tensor] = None max_sequence_length: int = 128 设备: typing.Optional[torch.device] = None 数据类型: typing.Optional[torch.dtype] = None )
参数
- 提示 (
str
或List[str]
, 可选) — 待编码的提示。 - 负提示 (
str
或List[str]
, 可选) — 不用于引导图像生成的提示。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
时),将忽略此参数。 - 是否使用分类器自由引导 (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - 每个提示词的视频数量 (
int
, 可选, 默认为 1) — 每个提示词应生成的视频数量。要放置结果嵌入的 torch 设备。 - 提示词嵌入 (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - 负提示词嵌入 (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - 设备 — (
torch.device
, 可选): torch 设备 - 数据类型 — (
torch.dtype
, 可选): torch 数据类型
将提示编码为文本编码器隐藏状态。
LTXImageToVideoPipeline
类 diffusers.LTXImageToVideoPipeline
< 来源 >( 调度器: FlowMatchEulerDiscreteScheduler vae: AutoencoderKLLTXVideo 文本编码器: T5EncoderModel 分词器: T5TokenizerFast Transformer: LTXVideoTransformer3DModel )
参数
- 变换器 (LTXVideoTransformer3DModel) — 用于对编码视频潜在变量进行去噪的条件变换器架构。
- 调度器 (FlowMatchEulerDiscreteScheduler) — 与
transformer
结合使用以对编码图像潜在变量进行去噪的调度器。 - 变分自动编码器 (AutoencoderKLLTXVideo) — 用于将图像编码和解码为潜在表示的变分自动编码器 (VAE) 模型。
- 文本编码器 (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - 分词器 (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - 分词器 (
T5TokenizerFast
) — 第二个 T5TokenizerFast 类的分词器。
图像到视频生成管道。
参考资料:https://github.com/Lightricks/LTX-Video
__call__
< 来源 >( 图像: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None 提示: typing.Union[str, typing.List[str]] = None 负提示: typing.Union[str, typing.List[str], NoneType] = None 高度: int = 512 宽度: int = 704 帧数: int = 161 帧率: int = 25 推理步数: int = 50 时间步长: typing.List[int] = None 引导比例: float = 3 引导重缩放: float = 0.0 每个提示的视频数量: typing.Optional[int] = 1 生成器: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None 潜在变量: typing.Optional[torch.Tensor] = None 提示词嵌入: typing.Optional[torch.Tensor] = None 提示词注意力掩码: typing.Optional[torch.Tensor] = None 负提示词嵌入: typing.Optional[torch.Tensor] = None 负提示词注意力掩码: typing.Optional[torch.Tensor] = None 解码时间步长: typing.Union[float, typing.List[float]] = 0.0 解码噪声比例: typing.Union[float, typing.List[float], NoneType] = None 输出类型: typing.Optional[str] = 'pil' 返回字典: bool = True 注意力 kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None 每步结束回调函数: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None 每步结束回调张量输入: typing.List[str] = ['latents'] 最大序列长度: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput
或 tuple
参数
- 图像 (
PipelineImageInput
) — 用于条件生成的输入图像。必须是图像、图像列表或torch.Tensor
。 - 提示 (
str
或List[str]
, 可选) — 用于引导图像生成的提示。如果未定义,则必须传递prompt_embeds
。 - 高度 (
int
, 默认为512
) — 生成图像的高度(像素)。为获得最佳效果,此值默认为 480。 - 宽度 (
int
, 默认为704
) — 生成图像的宽度(像素)。为获得最佳效果,此值默认为 848。 - 帧数 (
int
, 默认为161
) — 要生成的视频帧数。 - 推理步数 (
int
, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高的图像质量,但会牺牲推理速度。 - 时间步长 (
List[int]
, 可选) — 用于去噪过程的自定义时间步长,适用于在其set_timesteps
方法中支持timesteps
参数的调度器。如果未定义,将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - 引导比例 (
float
, 默认为3
) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale
定义为 Imagen Paper 方程 2 中的w
。通过设置guidance_scale > 1
启用引导比例。更高的引导比例鼓励生成与文本prompt
密切相关的图像,通常以牺牲图像质量为代价。 - 引导重缩放 (
float
, 可选, 默认为 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed 中提出的引导重缩放因子。guidance_scale
定义为 Common Diffusion Noise Schedules and Sample Steps are Flawed 方程 16 中的φ
。引导重缩放因子应在使用零终端信噪比时修复过度曝光。 - 每个提示的视频数量 (
int
, 可选, 默认为 1) — 每个提示要生成的视频数量。 - 生成器 (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。 - 潜在变量 (
torch.Tensor
, 可选) — 预生成的带噪声的潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在变量张量。 - 提示词嵌入 (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - 提示词注意力掩码 (
torch.Tensor
, 可选) — 预生成的文本嵌入注意力掩码。 - 负提示词嵌入 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入。对于 PixArt-Sigma,此负提示词应为""。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - 负提示词注意力掩码 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入注意力掩码。 - 解码时间步长 (
float
, 默认为0.0
) — 生成视频的解码时间步长。 - 解码噪声比例 (
float
, 默认为None
) — 在解码时间步长处,随机噪声与去噪潜在变量之间的插值因子。 - 输出类型 (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。选择 PIL:PIL.Image.Image
或np.array
。 - 返回字典 (
bool
, 可选, 默认为True
) — 是否返回~pipelines.ltx.LTXPipelineOutput
而不是普通元组。 - 注意力 kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则传递给 diffusers.models.attention_processor 中self.processor
下定义的AttentionProcessor
。 - 每步结束回调函数 (
Callable
, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。该函数以以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量列表。 - 每步结束回调张量输入 (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - 最大序列长度 (
int
默认为128
) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.ltx.LTXPipelineOutput
或 tuple
如果 return_dict
为 True
,则返回 ~pipelines.ltx.LTXPipelineOutput
,否则返回一个 tuple
,其中第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> 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)
编码提示
< source >( 提示: typing.Union[str, typing.List[str]] 负提示: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True 每个提示的视频数量: int = 1 提示词嵌入: typing.Optional[torch.Tensor] = None 负提示词嵌入: typing.Optional[torch.Tensor] = None 提示词注意力掩码: typing.Optional[torch.Tensor] = None 负提示词注意力掩码: typing.Optional[torch.Tensor] = None max_sequence_length: int = 128 设备: typing.Optional[torch.device] = None 数据类型: 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
) — 是否使用分类器自由指导。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示词应生成的视频数量。要放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor
, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据negative_prompt
输入参数生成 negative_prompt_embeds。 - device — (
torch.device
, 可选): torch 设备 - dtype — (
torch.dtype
, 可选): torch dtype
将提示编码为文本编码器隐藏状态。
LTXConditionPipeline
class diffusers.LTXConditionPipeline
< source >( 调度器: FlowMatchEulerDiscreteScheduler vae: AutoencoderKLLTXVideo 文本编码器: T5EncoderModel 分词器: T5TokenizerFast Transformer: 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 类的第二个分词器。
用于文本/图像/视频到视频生成的管道。
参考资料:https://github.com/Lightricks/LTX-Video
__call__
< source >( conditions: typing.Union[diffusers.pipelines.ltx.pipeline_ltx_condition.LTXVideoCondition, typing.List[diffusers.pipelines.ltx.pipeline_ltx_condition.LTXVideoCondition]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None video: typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]] = None frame_index: typing.Union[int, typing.List[int]] = 0 strength: typing.Union[float, typing.List[float]] = 1.0 denoise_strength: float = 1.0 prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: int = 512 width: int = 704 num_frames: int = 161 frame_rate: int = 25 num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 3 guidance_rescale: float = 0.0 image_cond_noise_scale: float = 0.15 num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None decode_timestep: typing.Union[float, typing.List[float]] = 0.0 decode_noise_scale: typing.Union[float, typing.List[float], NoneType] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 ) → ~pipelines.ltx.LTXPipelineOutput
或 tuple
参数
- conditions (
List[LTXVideoCondition], *可选*
) — 视频生成的帧条件项列表。如果未提供,将使用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
。 - height (
int
, 默认为512
) — 生成图像的高度(像素)。为了获得最佳结果,默认设置为 480。 - width (
int
, 默认为704
) — 生成图像的宽度(像素)。为了获得最佳结果,默认设置为 848。 - num_frames (
int
, 默认为161
) — 要生成的视频帧数 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会产生更高质量的图像,但会以较慢的推理速度为代价。 - timesteps (
List[int]
, 可选) — 用于去噪过程的自定义时间步,适用于支持在其set_timesteps
方法中使用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
, 可选, 默认为 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed 中提出的指导重缩放因子。guidance_scale
定义为 Common Diffusion Noise Schedules and Sample Steps are Flawed 中公式 16 的φ
。指导重缩放因子应解决在使用零终端信噪比时过度曝光的问题。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示词生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch generator(s),用于使生成具有确定性。 - latents (
torch.Tensor
, 可选) — 预生成的带噪声潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据prompt
输入参数生成文本嵌入。 - prompt_attention_mask (
torch.Tensor
, 可选) — 文本嵌入的预生成注意力掩码。 - negative_prompt_embeds (
torch.FloatTensor
, 可选) — 预先生成的负面文本嵌入。对于 PixArt-Sigma,此负面提示应为 ""。如果未提供,将根据negative_prompt
输入参数生成 negative_prompt_embeds。 - negative_prompt_attention_mask (
torch.FloatTensor
, 可选) — 负面文本嵌入的预生成注意力掩码。 - decode_timestep (
float
, 默认为0.0
) — 生成视频的解码时间步。 - 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 中self.processor
下定义的AttentionProcessor
。 - callback_on_step_end (
Callable
, 可选) — 在推理过程中每个去噪步骤结束时调用的函数。该函数将使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
默认为128
) — 用于prompt
的最大序列长度。
返回
~pipelines.ltx.LTXPipelineOutput
或 tuple
如果 return_dict
为 True
,则返回 ~pipelines.ltx.LTXPipelineOutput
,否则返回一个 tuple
,其中第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> 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: float init_latents: Tensor latents: Tensor noise_scale: float conditioning_mask: Tensor generator eps = 1e-06 )
为硬条件潜在表示添加时间步相关的噪声。这有助于运动的连续性,特别是在单个帧上进行条件化时。
编码提示
< source >( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None max_sequence_length: int = 256 device: typing.Optional[torch.device] = None dtype: 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
) — 是否使用分类器自由引导。 - num_videos_per_prompt (
int
, 可选, 默认为 1) — 每个提示应生成的视频数量。将生成的嵌入放置到torch设备上。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从negative_prompt
输入参数生成负文本嵌入。 - device — (
torch.device
, 可选): torch设备 - dtype — (
torch.dtype
, 可选): torch数据类型
将提示编码为文本编码器隐藏状态。
trim_conditioning_sequence
< 源代码 >( start_frame: int sequence_num_frames: int target_num_frames: int ) → int
将条件序列裁剪到允许的帧数。
LTXLatentUpsamplePipeline
class diffusers.LTXLatentUpsamplePipeline
< 源代码 >( vae: AutoencoderKLLTXVideo latent_upsampler: LTXLatentUpsamplerModel )
__call__
< 源代码 >( video: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None height: int = 512 width: int = 704 latents: typing.Optional[torch.Tensor] = None decode_timestep: typing.Union[float, typing.List[float]] = 0.0 decode_noise_scale: typing.Union[float, typing.List[float], NoneType] = None adain_factor: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True )
adain_filter_latent
< 源代码 >( latents: Tensor reference_latents: Tensor factor: float = 1.0 ) → torch.Tensor
根据参考潜在张量的统计信息,对潜在张量应用自适应实例归一化 (AdaIN)。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将返回一步计算解码。
禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling
,此方法将恢复一步计算解码。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。
启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成瓦片,分多步计算编码和解码。这对于节省大量内存和处理更大的图像非常有用。
LTXPipelineOutput
class diffusers.pipelines.ltx.pipeline_output.LTXPipelineOutput
< 源代码 >( frames: Tensor )
LTX管道的输出类。