Diffusers documentation
LTX-Video
LTX-Video
LTX-Video là một diffusion transformer được thiết kế để tạo video độ phân giải cao từ văn bản và hình ảnh một cách nhanh chóng và theo thời gian thực. Tính năng chính của LTX-Video là Video-VAE. Video-VAE có tỷ lệ nén từ pixel sang latent cao hơn (1:192), cho phép xử lý dữ liệu video hiệu quả hơn và tốc độ tạo nhanh hơn. Để hỗ trợ và ngăn chặn việc mất các chi tiết tinh tế trong quá trình tạo, bộ giải mã Video-VAE thực hiện việc chuyển đổi từ latent sang pixel và bước khử nhiễu cuối cùng.
Bạn có thể tìm thấy tất cả các checkpoint gốc của LTX-Video dưới tổ chức Lightricks.
Nhấp vào các mô hình LTX-Video ở thanh bên phải để xem thêm các ví dụ về các tác vụ tạo video khác.
Ví dụ dưới đây minh họa cách tạo video được tối ưu hóa cho bộ nhớ hoặc tốc độ suy luận.
Tham khảo hướng dẫn Giảm mức sử dụng bộ nhớ để biết thêm chi tiết về các kỹ thuật tiết kiệm bộ nhớ khác nhau.
Mô hình LTX-Video bên dưới yêu cầu ~10GB VRAM.
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)Compilation sẽ chậm ở lần đầu tiên nhưng các lần gọi pipeline sau đó sẽ nhanh hơn. Caching cũng có thể tăng tốc suy luận bằng cách lưu trữ và tái sử dụng các đầu ra trung gian.
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)Ghi chú
Tham khảo các cài đặt được khuyến nghị sau để tạo nội dung từ kho LTX-Video.
- dtype được khuyến nghị cho transformer, VAE và text encoder là
torch.bfloat16. VAE và text encoder cũng có thể làtorch.float32hoặctorch.float16. - Đối với các biến thể LTX-Video được chưng cất bằng guidance, hãy đặt
guidance_scalethành1.0.guidance_scalecủa bất kỳ model nào khác nên được đặt cao hơn, chẳng hạn5.0, để đạt chất lượng sinh thành tốt. - Đối với các biến thể VAE nhận biết bước thời gian (LTX-Video 0.9.1 trở lên), đặt
decode_timestepthành0.05vàimage_cond_noise_scalethành0.025. - Đối với các biến thể hỗ trợ nội suy giữa nhiều hình ảnh và video điều kiện (LTX-Video 0.9.5 trở lên), hãy sử dụng các hình ảnh và video tương tự để đạt kết quả tốt nhất. Sự khác biệt so với các đầu vào điều kiện có thể dẫn đến các chuyển cảnh đột ngột trong video được tạo ra.
- dtype được khuyến nghị cho transformer, VAE và text encoder là
LTX-Video 0.9.7 bao gồm một bộ tăng độ phân giải không gian cho latent và một transformer có 13B tham số. Trong quá trình suy luận, một video độ phân giải thấp sẽ được tạo nhanh trước, sau đó được tăng độ phân giải và tinh chỉnh.
Hiển thị mã ví dụ
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)Mô hình distilled LTX-Video 0.9.7 được distilled về guidance và timestep để tăng tốc độ tạo nội dung. Nó yêu cầu
guidance_scalephải được đặt thành1.0vànum_inference_stepsnên được đặt trong khoảng từ4đến10để đạt chất lượng tạo tốt. Bạn cũng nên sử dụng các timestep tùy chỉnh sau để có kết quả tốt nhất.- Suy luận mô hình cơ bản để chuẩn bị cho việc tăng độ phân giải:
[1000, 993, 987, 981, 975, 909, 725, 0.03]. - Upscaling:
[1000, 909, 725, 421, 0].
Hiển thị mã ví dụ
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)- Suy luận mô hình cơ bản để chuẩn bị cho việc tăng độ phân giải:
Mô hình LTX-Video 0.9.8 distilled tương tự biến thể 0.9.7. Nó được distilled về guidance và timestep, và có thể sử dụng mã suy luận tương tự như ở trên. Một cải tiến của phiên bản này là hỗ trợ tạo các video rất dài. Ngoài ra, nó hỗ trợ sử dụng tone mapping để cải thiện chất lượng video được tạo ra bằng tham số
tone_map_compression_ratio. Giá trị mặc định0.6được khuyến nghị.Xem mã mẫu
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 hỗ trợ LoRA với load_lora_weights().
Hiển thị mã ví dụ
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 hỗ trợ nạp từ các tệp đơn lẻ, chẳng hạn như GGUF checkpoints, bằng loaders.FromOriginalModelMixin.from_single_file() hoặc loaders.FromSingleFileMixin.from_single_file().
Xem mã ví dụ
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
lớp diffusers.LTXI2VLongMultiPromptPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5TokenizerFasttransformer: LTXVideoTransformer3DModel )
Tham số
- transformer (LTXVideoTransformer3DModel) — Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler hoặc
LTXEulerAncestralRFScheduler) — Một scheduler được sử dụng kết hợp vớitransformerđể khử nhiễu các latents của ảnh đã được mã hóa. - vae (AutoencoderKLLTXVideo) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl. - tokenizer (
T5TokenizerFast) — Tokenizer của lớp T5TokenizerFast.
Pipeline đa prompt I2V (image-to-video) thời lượng dài với độ tương thích ComfyUI.
Các tính năng chính:
- Chỉ lấy mẫu cửa sổ trượt theo thời gian (không chia sẻ không gian H/W); kết hợp tự hồi quy giữa các cửa sổ.
- Phân đoạn đa prompt cho mỗi cửa sổ với các chuyển tiếp mượt mà tại đầu cửa sổ.
- Điều kiện cứng khung hình đầu tiên thông qua mặt nạ theo từng token cho I2V.
- Kiểm soát VRAM thông qua phân tách theo thời gian và giải mã VAE theo từng ô.
Tham khảo: 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
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Các prompt văn bản dương cho mỗi cửa sổ. Nếu một chuỗi duy nhất chứa ký tự ’|’, các phần sẽ được tách theo các thanh. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt âm để loại bỏ nội dung không mong muốn. - prompt_segments (
list[dict], tùy chọn) — Bản ánh xạ phân đoạn với {“start_window”, “end_window”, “text”} để ghi đè prompt theo từng cửa sổ. - height (
int, mặc định là512) — Chiều cao của ảnh đầu ra tính bằng pixel; phải chia hết cho 32. - width (
int, mặc định là704) — Chiều rộng của ảnh đầu ra tính bằng pixel; phải chia hết cho 32. - num_frames (
int, mặc định là161) — Số lượng khung hình đầu ra (trong không gian pixel đã giải mã). - frame_rate (
float, mặc định là25) — Số khung hình mỗi giây; được dùng để chuẩn hóa các tọa độ thời gian trongvideo_coords. - guidance_scale (
float, mặc định là1.0) — Thang CFG; các giá trị > 1 bật classifier-free guidance. - guidance_rescale (
float, mặc định là0.0) — Tùy chọn rescale để giảm thiểu hiện tượng quá phơi sáng dưới CFG (xemrescale_noise_cfg). - num_inference_steps (
int, tùy chọn, mặc định là8) — Số bước khử nhiễu cho mỗi cửa sổ. Bỏ qua nếusigmasđược cung cấp. - sigmas (
list[float]hoặctorch.Tensor, tùy chọn) — Lịch sigma rõ ràng cho mỗi cửa sổ; nếu được đặt, sẽ ghi đè lênnum_inference_steps. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Kiểm soát tính ngẫu nhiên; chấp nhận danh sách nhưng chỉ sử dụng phần tử đầu tiên (batch=1). - seed (
int, tùy chọn, mặc định là0) — Nếu được cung cấp, sẽ khởi tạo bộ tạo số ngẫu nhiên dùng chung cho các biến tiềm năng toàn cục và suy ra bộ tạo số ngẫu nhiên cục bộ theo cửa sổ vớiseed + w_startcho mỗi cửa sổ thời gian. - cond_image (
PIL.Image.Imagehoặctorch.Tensor, tùy chọn) — Hình ảnh điều kiện; cố định khung 0 thông qua mặt nạ theo từng token khicond_strength > 0. - cond_strength (
float, mặc định là0.5) — Độ mạnh của điều kiện cứng cho khung hình đầu tiên (cond_mask càng nhỏ ⇒ mức độ bảo toàn càng mạnh). - latents (
torch.Tensor, tùy chọn) — Latents ban đầu [B, C_lat, F_lat, H_lat, W_lat]; nếu là None, sẽ được lấy mẫu bằngrandn_tensor. - temporal_tile_size (
int, mặc định là80) — Kích thước cửa sổ thời gian (tính bằng số khung hình đã giải mã); bên trong được nhân theo hệ số nén thời gian của VAE. - temporal_overlap (
int, mặc định là24) — Phần chồng lấn giữa các cửa sổ liên tiếp (tính bằng số khung hình đã giải mã); được nhân nội bộ theo hệ số nén. - temporal_overlap_cond_strength (
float, mặc định là0.5) — Độ mạnh để tiêm các latent ở phần đuôi của cửa sổ trước vào phần đầu của cửa sổ mới. - adain_factor (
float, mặc định là0.25) — Độ mạnh của chuẩn hóa AdaIN cho tính nhất quán giữa các cửa sổ (0 để tắt). - guidance_latents (
torch.Tensor, tùy chọn) — Các latents tham chiếu được chèn vào đầu cửa sổ; độ dài được cắt bớt bởi phần chồng lấn cho các cửa sổ tiếp theo. - guiding_strength (
float, mặc định là1.0) — Độ mạnh tiêm choguidance_latents. - negative_index_latents (
torch.Tensor, tùy chọn) — Một latent khung đơn được thêm vào đầu cửa sổ cho ngữ nghĩa “negative index”. - negative_index_strength (
float, mặc định là1.0) — Độ mạnh tiêm chonegative_index_latents. - skip_steps_sigma_threshold (
float, tùy chọn, mặc định là1) — Bỏ qua các bước có sigma vượt quá ngưỡng này. - decode_timestep (
float, tùy chọn, mặc định là0.05) — Timestep khi giải mã (nếu VAE hỗ trợ timestep_conditioning). - decode_noise_scale (
float, tùy chọn, mặc định là0.025) — Thang độ pha trộn nhiễu khi giải mã (nếu VAE hỗ trợ timestep_conditioning). - decode_horizontal_tiles (
int, mặc định là4) — Số lượng ô ngang trong quá trình giải mã VAE. - decode_vertical_tiles (
int, mặc định là4) — Số lượng ô dọc trong quá trình giải mã VAE. - decode_overlap (
int, mặc định là3) — Phần chồng lấn (tính bằng pixel tiềm ẩn) giữa các ô gạch trong quá trình giải mã VAE. - output_type (
str, tùy chọn, mặc định là"latent") — Định dạng đầu ra của video được tạo. Chọn giữa “latent”, “pt”, “np” hoặc “pil”. Nếu là “latent”, trả về latents mà không giải mã. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.ltx.LTXPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs (
dict, tùy chọn) — Các tham số attention bổ sung được chuyển tiếp đến transformer. - callback_on_step_end (
PipelineCallbackhoặcMultiPipelineCallbacks, tùy chọn) — Hook callback cho từng bước. - callback_on_step_end_tensor_inputs (
list[str], mặc định là["latents"]) — Các khóa từ locals() để truyền vào callback. - max_sequence_length (
int, mặc định là128) — Độ dài tối đa của tokenizer cho việc mã hóa prompt.
Trả về
~pipelines.ltx.LTXPipelineOutput hoặc tuple
Nếu return_dict là True, ~pipelines.ltx.LTXPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các khung hình đã tạo. Định dạng đầu ra phụ thuộc vào output_type:
- “latent”/“pt”:
torch.Tensor[B, C, F, H, W]; “latent” nằm trong không gian latent đã chuẩn hóa, “pt” là không gian đầu ra của VAE. - “np”:
np.ndarrayđã xử lý hậu kỳ. - “pil”:
list[PIL.Image.Image]danh sách các hình ảnh PIL.
Tạo chuỗi hình ảnh-đoạn video thông qua các cửa sổ trượt theo thời gian và lịch trình đa prompt.
Ví dụ:
>>> 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]Các hình dạng: Kích thước ẩn (khi được tạo tự động):
- F_lat = (num_frames - 1) // vae_temporal_compression_ratio + 1
- H_lat = height // vae_spatial_compression_ratio
- W_lat = width // vae_spatial_compression_ratio
Ghi chú:
- Seeding: khi
seedđược cung cấp, mỗi cửa sổ thời gian sử dụng một trình tạo cục bộ được khởi tạo bằngseed + w_start, trong khi trình tạo dùng chung được khởi tạo một lần cho các latent toàn cục nếu không có trình tạo nào được truyền vào; ngoài ra, trình tạo được truyền vào sẽ được tái sử dụng. - CFG:
noise_pred = uncond + w * (text - uncond)thống nhất vớiguidance_rescaletùy chọn. - Bộ nhớ: denoising thực hiện dự đoán toàn khung hình (không chia ô không gian); quá trình giải mã có thể được chia ô để tránh 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 )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
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 )
Chuẩn bị các latents cơ bản và tùy chọn tiêm các latents điều kiện khung hình đầu tiên.
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 ) →
Tham số
- latents — [B, C_latent, F_latent, H_latent, W_latent]
- decode_timestep — Timestep giải mã tùy chọn (chỉ có hiệu lực nếu VAE hỗ trợ timestep_conditioning)
- decode_noise_scale — Nội suy nhiễu giải mã tùy chọn (chỉ có hiệu lực nếu VAE hỗ trợ timestep_conditioning)
- horizontal_tiles, vertical_tiles — Số lượng ô theo chiều ngang/dọc (>= 1)
- overlap — Chồng lấn trong không gian ẩn (theo pixel ẩn, >= 0)
- last_frame_fix — Có bật sửa lỗi “lặp lại khung hình cuối” hay không
- generator — Bộ tạo ngẫu nhiên (được dùng cho nhiễu decode_noise_scale)
- output_type — “latent” | “pt” | “np” | “pil”
- “latent”: trả về các latent không thay đổi (hữu ích cho xử lý tiếp theo)
- “pt”: trả về tensor trong không gian đầu ra của VAE
- “np”/“pil”: đầu ra sau khi xử lý qua VideoProcessor.postprocess_video
- auto_denormalize — Nếu là True, áp dụng khử chuẩn hóa LTX cho
latentsbên trong (khuyến nghị) - compute_dtype — Độ chính xác được sử dụng trong quá trình hợp nhất tile (mặc định là float32; giảm đáng kể hiện tượng mờ ở các đường nối)
- enable_vae_tiling — Nếu là True, chuyển việc chia tile cho
tiled_decodetích hợp sẵn của VAE (đặtvae.use_tiling).
Trả về
- Nếu output_type="latent"
trả về latents đầu vào không thay đổi
- Nếu output_type=“pt”: trả về [B, C, F, H, W] (giá trị xấp xỉ trong [-1, 1])
- Nếu output_type=“np”/“pil”: trả về các đầu ra đã xử lý hậu kỳ thông qua postprocess_video
Giải mã không gian dạng gạch (spatial tiled) dựa trên VAE (tương đương ComfyUI) được triển khai theo phong cách Diffusers.
- Làm mờ tuyến tính và trộn các ô chồng lấn để tránh các đường nối.
- Tuỳ chọn last_frame_fix: nhân bản khung latent cuối cùng trước khi giải mã, sau đó loại bỏ time_scale_factor khung ở cuối.
- Hỗ trợ tiêm (injection) timestep_conditioning và decode_noise_scale.
- Mặc định, “normalized latents” (kết quả khử nhiễu) sẽ được khử chuẩn hóa bên trong (auto_denormalize=True).
- Tile fusion được tính toán trong compute_dtype (mặc định là float32) để giảm mờ và sai lệch màu.
LTXPipeline
lớp diffusers.LTXPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
Tham số
- transformer (LTXVideoTransformer3DModel) — Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLLTXVideo) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl. - tokenizer (
CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer. - tokenizer (
T5TokenizerFast) — Tokenizer thứ hai thuộc lớp T5TokenizerFast.
Pipeline để tạo video từ văn bản.
Tham khảo: 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 = 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 = ['latents']max_sequence_length: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput or tuple
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1). - height (
int, mặc định là512) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị mặc định là 480 để đạt kết quả tốt nhất. - width (
int, mặc định là704) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 848 theo mặc định để đạt kết quả tốt nhất. - num_frames (
int, mặc định là161) — Số lượng khung hình video cần tạo - frame_rate (
int, mặc định là25) — Tốc độ khung hình mục tiêu của video được tạo ra. - num_inference_steps (
int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - timesteps (
list[int], tùy chọn) — Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối sốtimestepstrong phương thứcset_timestepscủa chúng. Nếu không được định nghĩa, hành vi mặc định khinum_inference_stepsđược truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. - guidance_scale (
float, mặc định là3) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_rescale (
float, tùy chọn, mặc định là 0.0) — Hệ số rescale guidance được đề xuất trong Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleđược định nghĩa làφtrong phương trình 16. của Common Diffusion Noise Schedules and Sample Steps are Flawed. Hệ số rescale guidance nên khắc phục tình trạng phơi sáng quá mức khi sử dụng zero terminal SNR. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - prompt_attention_mask (
torch.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - negative_prompt_attention_mask (
torch.FloatTensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm (negative text embeddings). - decode_timestep (
float, mặc định là0.0) — Bước thời gian (timestep) tại đó video được tạo ra sẽ được giải mã. - decode_noise_scale (
float, mặc định làNone) — Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.ltx.LTXPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs (
dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - callback_on_step_end (
Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
intmặc định là128) — Chiều dài tối đa của chuỗi để sử dụng vớiprompt.
Trả về
~pipelines.ltx.LTXPipelineOutput hoặc tuple
Nếu return_dict là True, ~pipelines.ltx.LTXPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã được tạo.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> 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 )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
LTXImageToVideoPipeline
lớp diffusers.LTXImageToVideoPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
Tham số
- transformer (LTXVideoTransformer3DModel) — Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLLTXVideo) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl. - tokenizer (
CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer. - tokenizer (
T5TokenizerFast) — Tokenizer thứ hai thuộc lớp T5TokenizerFast.
Pipeline để tạo video từ ảnh.
Tham khảo: 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 = 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 = ['latents']max_sequence_length: int = 128 ) → ~pipelines.ltx.LTXPipelineOutput or tuple
Tham số
- image (
PipelineImageInput) — Hình ảnh đầu vào để điều kiện cho quá trình tạo. Phải là một hình ảnh, một danh sách các hình ảnh hoặc mộttorch.Tensor. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1). - height (
int, mặc định là512) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị mặc định là 480 để đạt kết quả tốt nhất. - width (
int, mặc định là704) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 848 theo mặc định để đạt kết quả tốt nhất. - num_frames (
int, mặc định là161) — Số lượng khung hình video cần tạo - frame_rate (
int, mặc định là25) — Tốc độ khung hình mục tiêu của video được tạo ra. - num_inference_steps (
int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - timesteps (
list[int], tùy chọn) — Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối sốtimestepstrong phương thứcset_timestepscủa chúng. Nếu không được định nghĩa, hành vi mặc định khinum_inference_stepsđược truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. - guidance_scale (
float, mặc định là3) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_rescale (
float, tùy chọn, mặc định là 0.0) — Hệ số rescale guidance được đề xuất trong Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleđược định nghĩa làφtrong phương trình 16. của Common Diffusion Noise Schedules and Sample Steps are Flawed. Hệ số rescale guidance nên khắc phục tình trạng phơi sáng quá mức khi sử dụng zero terminal SNR. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - prompt_attention_mask (
torch.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - negative_prompt_attention_mask (
torch.FloatTensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm (negative text embeddings). - decode_timestep (
float, mặc định là0.0) — Bước thời gian (timestep) tại đó video được tạo ra sẽ được giải mã. - decode_noise_scale (
float, mặc định làNone) — Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.ltx.LTXPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs (
dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - callback_on_step_end (
Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
intmặc định là128) — Chiều dài tối đa của chuỗi để sử dụng vớiprompt.
Trả về
~pipelines.ltx.LTXPipelineOutput hoặc tuple
Nếu return_dict là True, ~pipelines.ltx.LTXPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã được tạo.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> 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 )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
LTXConditionPipeline
lớp diffusers.LTXConditionPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLLTXVideotext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: LTXVideoTransformer3DModel )
Tham số
- transformer (LTXVideoTransformer3DModel) — Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (AutoencoderKLLTXVideo) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
- text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl. - tokenizer (
CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer. - tokenizer (
T5TokenizerFast) — Tokenizer thứ hai thuộc lớp T5TokenizerFast.
Pipeline để tạo video từ văn bản/hình ảnh/video.
Tham khảo: 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 = 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 = 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 = ['latents']max_sequence_length: int = 256 ) → ~pipelines.ltx.LTXPipelineOutput or tuple
Tham số
- conditions (
list[LTXVideoCondition], *optional*) — Danh sách các mục điều kiện khung hình cho việc tạo video. Nếu không được cung cấp, các điều kiện sẽ được tạo bằng cách sử dụngimage,video,frame_indexvàstrength. - image (
PipelineImageInputhoặclist[PipelineImageInput], tùy chọn) — Hình ảnh hoặc các hình ảnh để điều kiện hóa việc tạo video. Nếu không được cung cấp, người dùng phải truyềnvideohoặcconditions. - video (
list[PipelineImageInput], tùy chọn) — Video để điều kiện hóa việc tạo video. Nếu không được cung cấp, bạn phải truyềnimagehoặcconditions. - frame_index (
inthoặclist[int], tùy chọn) — Chỉ số khung hình hoặc các chỉ số khung hình tại đó hình ảnh hoặc video sẽ có tác động có điều kiện đến việc tạo video. Nếu không được cung cấp, người dùng phải truyềnconditions. - strength (
floathoặclist[float], tùy chọn) — Độ mạnh hoặc các độ mạnh của hiệu ứng điều kiện. Nếu không được cung cấp, bạn phải truyềnconditions. - denoise_strength (
float, mặc định là1.0) — Mức độ mạnh của nhiễu được thêm vào các latents để chỉnh sửa. Mức độ càng cao thì càng nhiều nhiễu được thêm vào các latents, do đó dẫn đến nhiều khác biệt hơn giữa video gốc và video được tạo ra. Điều này hữu ích cho việc chỉnh sửa video-to-video. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1). - height (
int, mặc định là512) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị mặc định là 480 để đạt kết quả tốt nhất. - width (
int, mặc định là704) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Giá trị này được đặt là 848 theo mặc định để đạt kết quả tốt nhất. - num_frames (
int, mặc định là161) — Số lượng khung hình video cần tạo - frame_rate (
int, mặc định là25) — Tốc độ khung hình mục tiêu của video được tạo ra. - num_inference_steps (
int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn. - timesteps (
list[int], tùy chọn) — Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối sốtimestepstrong phương thứcset_timestepscủa chúng. Nếu không được định nghĩa, hành vi mặc định khinum_inference_stepsđược truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. - guidance_scale (
float, mặc định là3) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_rescale (
float, tùy chọn, mặc định là 0.0) — Hệ số rescale guidance được đề xuất trong Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleđược định nghĩa làφtrong phương trình 16. của Common Diffusion Noise Schedules and Sample Steps are Flawed. Hệ số rescale guidance nên khắc phục tình trạng phơi sáng quá mức khi sử dụng zero terminal SNR. - image_cond_noise_scale (
float, mặc định là0.15) — Thang độ của nhiễu được thêm vào các latents của ảnh điều kiện. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụnggeneratorngẫu nhiên được cung cấp. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - prompt_attention_mask (
torch.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản. - negative_prompt_embeds (
torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - negative_prompt_attention_mask (
torch.FloatTensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm (negative text embeddings). - decode_timestep (
float, mặc định là0.0) — Bước thời gian (timestep) tại đó video được tạo ra sẽ được giải mã. - decode_noise_scale (
float, mặc định làNone) — Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo. Chọn giữa PIL:PIL.Image.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.ltx.LTXPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs (
dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - callback_on_step_end (
Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargssẽ bao gồm danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham sốcallback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính._callback_tensor_inputscủa lớp pipeline của bạn. - max_sequence_length (
intmặc định là128) — Chiều dài tối đa của chuỗi để sử dụng vớiprompt.
Trả về
~pipelines.ltx.LTXPipelineOutput hoặc tuple
Nếu return_dict là True, ~pipelines.ltx.LTXPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã được tạo.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> 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 )
Thêm nhiễu phụ thuộc vào bước thời gian vào các latent điều kiện cứng. Điều này giúp cải thiện tính liên tục của chuyển động, đặc biệt khi điều kiện dựa trên một khung hình duy nhất.
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 )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vàonegative_prompt. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
trim_conditioning_sequence
< source >( start_frame: intsequence_num_frames: inttarget_num_frames: int ) → int
Cắt ngắn một chuỗi điều kiện xuống số khung hình được phép.
LTXLatentUpsamplePipeline
lớp 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
Tham số
- video (
list[PipelineImageInput], tùy chọn) — Các khung hình video đầu vào để tăng mẫu. Loại trừ lẫn nhau vớilatents. - height (
int, mặc định là512) — Chiều cao (tính bằng pixel) của đầu ra đã được tăng mẫu. - width (
int, mặc định là704) — Chiều rộng tính bằng pixel của đầu ra đã được tăng mẫu. - latents (
torch.Tensor, tùy chọn) — Các latents video đã mã hóa trước để mở rộng. Loại trừ lẫn nhau vớivideo. - decode_timestep (
floathoặclist[float], mặc định là0.0) — Bước thời gian (timestep) tại đó các latents đã được mở rộng (upsampled) được giải mã. - decode_noise_scale (
floathoặclist[float], tùy chọn) — Hệ số nội suy giữa nhiễu ngẫu nhiên và latents đã khử nhiễu tại bước thời gian giải mã. - adain_factor (
float, mặc định là0.0) — Độ mạnh của việc khớp thống kê AdaIN được áp dụng cho các latents đã được tăng mẫu. - tone_map_compression_ratio (
float, mặc định là0.0) — Tỷ lệ nén được sử dụng để tone mapping các latents đã được upsample. Phải nằm trong khoảng [0, 1]. - generator (
torch.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.Generatorđể làm cho quá trình sinh ra kết quả xác định. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của video được tạo. Chọn giữaPIL.Image,np.arrayhoặclatent. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một~pipelines.ltx.LTXPipelineOutputthay vì một tuple thông thường hay không.
Trả về
~pipelines.ltx.LTXPipelineOutput hoặc tuple
~pipelines.ltx.LTXPipelineOutput nếu return_dict là
True, ngược lại là một tuple. Khi trả về tuple, phần tử đầu tiên là video đã được upsample (hoặc latents
nếu output_type="latent").
Hàm được gọi khi gọi pipeline để tăng độ phân giải tiềm ẩn (latent upsampling).
adain_filter_latent
< source >( latents: Tensorreference_latents: Tensorfactor: float = 1.0 ) → torch.Tensor
Tham số
- latents (
torch.Tensor) — Latents đầu vào cần chuẩn hóa - reference_latents (
torch.Tensor) — Các latents tham chiếu cung cấp thống kê về phong cách. - factor (
float) — Hệ số trộn giữa latent gốc và latent đã biến đổi. Khoảng: -10.0 đến 10.0, Mặc định: 1.0
Trả về
torch.Tensor
Tensor ẩn đã được biến đổi
Áp dụng Chuẩn hóa Thực thể Thích ứng (AdaIN) lên một tensor ẩn dựa trên các thống kê từ một tensor ẩn tham chiếu.
tone_map_latents
< source >( latents: Tensorcompression: float )
Áp dụng một hàm ánh xạ tông phi tuyến lên các giá trị tiềm ẩn để giảm phạm vi động của chúng một cách mượt mà về mặt cảm nhận bằng cách sử dụng nén dựa trên sigmoid.
Điều này hữu ích để chuẩn hóa các latent có phương sai cao hoặc để điều kiện hóa đầu ra trong quá trình tạo, đặc biệt khi kiểm soát hành vi động bằng hệ số compression.
LTXPipelineOutput
lớp diffusers.pipelines.ltx.pipeline_output.LTXPipelineOutput
< source >( frames: Tensor )
Tham số
- frames (
torch.Tensor,np.ndarray, hoặc list[list[PIL.Image.Image]]) — danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dàibatch_size,trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dàinum_frames.Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng(batch_size, num_frames, channels, height, width).
Lớp đầu ra cho các pipeline LTX.