Diffusers documentation
Sana-Video
Sana-Video
SANA-Video: Hiệu quả hóa tạo video với Block Linear Diffusion Transformer từ NVIDIA và MIT HAN Lab, bởi Junsong Chen, Yuyang Zhao, Jincheng Yu, Ruihang Chu, Junyu Chen, Shuai Yang, Xianbang Wang, Yicheng Pan, Daquan Zhou, Huan Ling, Haozhe Liu, Hongwei Yi, Hao Zhang, Muyang Li, Yukang Chen, Han Cai, Sanja Fidler, Ping Luo, Song Han, Enze Xie.
Tóm tắt từ bài báo là:
Chúng tôi giới thiệu SANA-Video, một mô hình khuếch tán nhỏ có khả năng tạo video hiệu quả với độ phân giải lên đến 720x1280 và thời lượng dài tới vài phút. SANA-Video tổng hợp các video độ phân giải cao, chất lượng cao và dài với sự tương thích mạnh mẽ giữa văn bản và video ở tốc độ nhanh đáng kể, có thể triển khai trên GPU RTX 5090. Hai thiết kế cốt lõi đảm bảo việc tạo video hiệu quả, hiệu suất cao và dài của chúng tôi: (1) Linear DiT: Chúng tôi tận dụng chú ý tuyến tính (linear attention) làm thao tác cốt lõi, hiệu quả hơn so với chú ý thông thường (vanilla attention) khi xử lý số lượng token lớn trong tạo video. (2) Bộ nhớ đệm KV có bộ nhớ không đổi cho Block Linear Attention: chúng tôi thiết kế phương pháp tự hồi quy theo khối (block-wise autoregressive) cho việc tạo video dài bằng cách sử dụng trạng thái bộ nhớ không đổi, được suy ra từ các tính chất tích lũy của chú ý tuyến tính. Bộ nhớ đệm KV này cung cấp ngữ cảnh toàn cục cho Linear DiT với chi phí bộ nhớ cố định, loại bỏ nhu cầu về bộ nhớ đệm KV truyền thống và cho phép tạo video dài vài phút một cách hiệu quả. Ngoài ra, chúng tôi khám phá các bộ lọc dữ liệu và chiến lược huấn luyện mô hình hiệu quả, thu hẹp chi phí huấn luyện xuống còn 12 ngày trên 64 GPU H100, chỉ bằng 1% chi phí của MovieGen. Với chi phí thấp, SANA-Video đạt hiệu suất cạnh tranh so với các mô hình khuếch tán nhỏ tiên tiến hiện đại (ví dụ: Wan 2.1-1.3B và SkyReel-V2-1.3B) trong khi nhanh hơn 16 lần về độ trễ đo được. Hơn nữa, SANA-Video có thể được triển khai trên GPU RTX 5090 với độ chính xác NVFP4, tăng tốc độ suy luận khi tạo video 720p dài 5 giây từ 71 giây xuống 29 giây (tăng tốc 2,4 lần). Tóm lại, SANA-Video cho phép tạo video chất lượng cao với chi phí thấp. this https URL.
Pipeline này được đóng góp bởi SANA Team. Mã nguồn gốc có thể được tìm thấy tại đây. Trọng số gốc có thể được tìm thấy tại hf.co/Efficient-Large-Model.
Các model có sẵn:
| Mô hình | dtype được khuyến nghị |
|---|---|
Efficient-Large-Model/SANA-Video_2B_480p_diffusers | torch.bfloat16 |
Tham khảo bộ sưu tập này để biết thêm thông tin.
Lưu ý: dtype được đề cập ở trên là dành cho trọng số của transformer. Trọng số của text encoder và VAE phải được giữ ở torch.bfloat16 hoặc torch.float32 để mô hình hoạt động chính xác. Vui lòng tham khảo ví dụ suy luận bên dưới để xem cách tải mô hình với dtype được khuyến nghị.
Các đường ống tạo
Ví dụ dưới đây minh họa cách sử dụng pipeline text-to-video để tạo video từ một mô tả bằng văn bản.
pipe = SanaVideoPipeline.from_pretrained(
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
dtype=torch.bfloat16,
)
pipe.text_encoder.to(torch.bfloat16)
pipe.vae.to(torch.float32)
pipe.to("cuda") # or "mps", "xpu", "cpu"
prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_scale = 30
motion_prompt = f" motion score: {motion_scale}."
prompt = prompt + motion_prompt
video = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
height=480,
width=832,
frames=81,
guidance_scale=6,
num_inference_steps=50,
generator=torch.Generator(device="cuda").manual_seed(0),
).frames[0]
export_to_video(video, "sana_video.mp4", fps=16)Ví dụ dưới đây minh họa cách sử dụng pipeline image-to-video để tạo video bằng mô tả văn bản và khung hình bắt đầu.
pipe = SanaImageToVideoPipeline.from_pretrained(
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
dtype=torch.bfloat16,
)
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, flow_shift=8.0)
pipe.vae.to(torch.float32)
pipe.text_encoder.to(torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = load_image("https://raw.githubusercontent.com/NVlabs/Sana/refs/heads/main/asset/samples/i2v-1.png")
prompt = "A woman stands against a stunning sunset backdrop, her long, wavy brown hair gently blowing in the breeze. She wears a sleeveless, light-colored blouse with a deep V-neckline, which accentuates her graceful posture. The warm hues of the setting sun cast a golden glow across her face and hair, creating a serene and ethereal atmosphere. The background features a blurred landscape with soft, rolling hills and scattered clouds, adding depth to the scene. The camera remains steady, capturing the tranquil moment from a medium close-up angle."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_scale = 30
motion_prompt = f" motion score: {motion_scale}."
prompt = prompt + motion_prompt
motion_scale = 30.0
video = pipe(
image=image,
prompt=prompt,
negative_prompt=negative_prompt,
height=480,
width=832,
frames=81,
guidance_scale=6,
num_inference_steps=50,
generator=torch.Generator(device="cuda").manual_seed(0),
).frames[0]
export_to_video(video, "sana-i2v.mp4", fps=16)Lượng tử hóa
Quantization giúp giảm yêu cầu về bộ nhớ của các mô hình rất lớn bằng cách lưu trữ trọng số mô hình trong kiểu dữ liệu có độ chính xác thấp hơn. Tuy nhiên, lượng tử hóa có thể ảnh hưởng khác nhau đến chất lượng video tùy thuộc vào mô hình video.
Tham khảo phần tổng quan Lượng tử hóa để tìm hiểu thêm về các backend lượng tử hóa được hỗ trợ và cách chọn một backend lượng tử hóa phù hợp với trường hợp sử dụng của bạn. Ví dụ bên dưới minh họa cách tải một SanaVideoPipeline đã được lượng tử hóa để suy luận bằng bitsandbytes.
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaVideoTransformer3DModel, SanaVideoPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel
quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = AutoModel.from_pretrained(
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
subfolder="text_encoder",
quantization_config=quant_config,
dtype=torch.float16,
)
quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SanaVideoTransformer3DModel.from_pretrained(
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
subfolder="transformer",
quantization_config=quant_config,
dtype=torch.float16,
)
pipeline = SanaVideoPipeline.from_pretrained(
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
text_encoder=text_encoder_8bit,
transformer=transformer_8bit,
dtype=torch.float16,
device_map="balanced",
)
model_score = 30
prompt = "Evening, backlight, side lighting, soft light, high contrast, mid-shot, centered composition, clean solo shot, warm color. A young Caucasian man stands in a forest, golden light glimmers on his hair as sunlight filters through the leaves. He wears a light shirt, wind gently blowing his hair and collar, light dances across his face with his movements. The background is blurred, with dappled light and soft tree shadows in the distance. The camera focuses on his lifted gaze, clear and emotional."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_prompt = f" motion score: {model_score}."
prompt = prompt + motion_prompt
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
height=480,
width=832,
num_frames=81,
guidance_scale=6.0,
num_inference_steps=50
).frames[0]
export_to_video(output, "sana-video-output.mp4", fps=16)SanaVideoPipeline
lớp diffusers.SanaVideoPipeline
< source >( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWantransformer: SanaVideoTransformer3DModelscheduler: DPMSolverMultistepScheduler )
Tham số
- tokenizer (
GemmaTokenizerhoặcGemmaTokenizerFast) — Tokenizer được sử dụng để tokenize prompt. - text_encoder (
Gemma2PreTrainedModel) — Mô hình text encoder để mã hóa các prompt đầu vào. - vae ([
AutoencoderKLWan,AutoencoderDC, hoặcAutoencoderKLLTX2Video]) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations). - transformer (SanaVideoTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (DPMSolverMultistepScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents video đã được mã hóa.
Pipeline để tạo video từ văn bản sử dụng Sana. Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 50timesteps: list[int] = Nonesigmas: list[float] = Noneguidance_scale: float = 6.0num_videos_per_prompt: int | None = 1height: int = 480width: int = 832frames: int = 81eta: float = 0.0generator: 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] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 300complex_human_instruction: list[str] = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for video generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, motion, and temporal relationships to create vivid and dynamic scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat slowly settling into a curled position, peacefully falling asleep on a warm sunny windowsill, with gentle sunlight filtering through surrounding pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps gradually lighting up, a diverse crowd of people in colorful clothing walking past, and a double-decker bus smoothly passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) → SanaVideoPipelineOutput 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 video. 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 video. 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). - 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 video có chất lượng cao hơn, với cái giá 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. - sigmas (
list[float], tùy chọn) — Các sigma 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ốsigmastrong 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 sẽ được sử dụng. - guidance_scale (
float, tùy chọn, mặc định là 4.5) — 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 video gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng video thấp hơ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. - height (
int, tùy chọn, mặc định là 480) — Chiều cao của video được tạo, tính bằng pixel. - width (
int, tùy chọn, mặc định là 832) — Chiều rộng của video được tạo, tính bằng pixel. - frames (
int, tùy chọn, mặc định là 81) — Số lượng khung hình trong video được tạo ra. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - 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 video. 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 sẵn cho các vector nhúng văn bản. - negative_prompt_embeds (
torch.Tensor, 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.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo sẵn cho các vector nhúng văn bản âm (negative text embeddings). - 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ữa mp4 hoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtSanaVideoPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs —
Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến
AttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô. - use_resolution_binning (
boolmặc định làTrue) — Nếu được đặt thànhTrue, chiều cao và chiều rộng yêu cầu sẽ được ánh xạ trước tiên đến các độ phân giải gần nhất bằng cách sử dụngASPECT_RATIO_480_BINhoặcASPECT_RATIO_720_BIN. Sau khi các latents được tạo ra được giải mã thành video, chúng sẽ được thay đổi kích thước trở lại độ phân giải yêu cầu. Hữu ích để tạo ra các video không vuông. - 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à300) — Chiều dài tối đa của chuỗi để sử dụng vớiprompt. - complex_human_instruction (
list[str], tùy chọn) — Hướng dẫn cho sự chú ý phức tạp của con người: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.
Trả về
SanaVideoPipelineOutput hoặc tuple
Nếu return_dict là True, SanaVideoPipelineOutput 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 video đã tạo
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> import torch
>>> from diffusers import SanaVideoPipeline
>>> from diffusers.utils import export_to_video
>>> pipe = SanaVideoPipeline.from_pretrained("Efficient-Large-Model/SANA-Video_2B_480p_diffusers")
>>> pipe.transformer.to(torch.bfloat16)
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> motion_score = 30
>>> prompt = "Evening, backlight, side lighting, soft light, high contrast, mid-shot, centered composition, clean solo shot, warm color. A young Caucasian man stands in a forest, golden light glimmers on his hair as sunlight filters through the leaves. He wears a light shirt, wind gently blowing his hair and collar, light dances across his face with his movements. The background is blurred, with dappled light and soft tree shadows in the distance. The camera focuses on his lifted gaze, clear and emotional."
>>> negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
>>> motion_prompt = f" motion score: {motion_score}."
>>> prompt = prompt + motion_prompt
>>> output = pipe(
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=480,
... width=832,
... frames=81,
... guidance_scale=6,
... num_inference_steps=50,
... generator=torch.Generator(device="cuda").manual_seed(42),
... ).frames[0]
>>> export_to_video(output, "sana-video-output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenegative_prompt: str = ''num_videos_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_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] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | 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 không dùng để định hướng việc tạo video. Nếu không được định nghĩa, bạn phải 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). Đối với PixArt-Alpha, giá trị này nên là "". - 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 - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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. Đối với Sana, đây nên là các embedding của chuỗi "". - clean_caption (
bool, mặc định làFalse) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa. - max_sequence_length (
int, mặc định là 300) — Độ dài tối đa của chuỗi được sử dụng cho prompt. - complex_human_instruction (
list[str], mặc định làcomplex_human_instruction) — Nếucomplex_human_instructionkhông rỗng, hàm sẽ sử dụng chỉ thị Human phức tạp cho prompt.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
SanaImageToVideoPipeline
lớp diffusers.SanaImageToVideoPipeline
< source >( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWantransformer: SanaVideoTransformer3DModelscheduler: FlowMatchEulerDiscreteScheduler )
Tham số
- tokenizer (
GemmaTokenizerhoặcGemmaTokenizerFast) — Tokenizer được sử dụng để tokenize prompt. - text_encoder (
Gemma2PreTrainedModel) — Mô hình text encoder để mã hóa các prompt đầu vào. - vae ([
AutoencoderKLWan,AutoencoderDC, hoặcAutoencoderKLLTX2Video]) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations). - transformer (SanaVideoTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents video đã được mã hóa.
Pipeline để tạo video từ ảnh/văn bản sử dụng Sana. Mô hình này kế thừa từ DiffusionPipeline. Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 50timesteps: list[int] = Nonesigmas: list[float] = Noneguidance_scale: float = 6.0num_videos_per_prompt: int | None = 1height: int = 480width: int = 832frames: int = 81eta: float = 0.0generator: 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] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 300complex_human_instruction: list[str] = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for video generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, motion, and temporal relationships to create vivid and dynamic scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat slowly settling into a curled position, peacefully falling asleep on a warm sunny windowsill, with gentle sunlight filtering through surrounding pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps gradually lighting up, a diverse crowd of people in colorful clothing walking past, and a double-decker bus smoothly passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) → SanaVideoPipelineOutput or tuple
Tham số
- image (
PipelineImageInput) — Hình ảnh đầu vào để điều kiện hóa việc tạo video. Khung đầu tiên của video được tạo sẽ được điều kiện hóa dựa trên hình ảnh này. - prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo video. 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 video. 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). - 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 video có chất lượng cao hơn, với cái giá 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. - sigmas (
list[float], tùy chọn) — Các sigma 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ốsigmastrong 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 sẽ được sử dụng. - guidance_scale (
float, tùy chọn, mặc định là 4.5) — 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 video gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng video thấp hơ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. - height (
int, tùy chọn, mặc định là 480) — Chiều cao của video được tạo, tính bằng pixel. - width (
int, tùy chọn, mặc định là 832) — Chiều rộng của video được tạo, tính bằng pixel. - frames (
int, tùy chọn, mặc định là 81) — Số lượng khung hình trong video được tạo ra. - eta (
float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác. - 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 video. 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 sẵn cho các vector nhúng văn bản. - negative_prompt_embeds (
torch.Tensor, 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.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo sẵn cho các vector nhúng văn bản âm (negative text embeddings). - 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ữa mp4 hoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtSanaVideoPipelineOutputthay vì một tuple thông thường hay không. - attention_kwargs —
Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến
AttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - clean_caption (
bool, tùy chọn, mặc định làTrue) — Có nên làm sạch caption trước khi tạo embeddings hay không. Yêu cầubeautifulsoup4vàftfyphải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô. - use_resolution_binning (
boolmặc định làTrue) — Nếu được đặt thànhTrue, chiều cao và chiều rộng yêu cầu sẽ được ánh xạ trước tiên đến các độ phân giải gần nhất bằng cách sử dụngASPECT_RATIO_480_BINhoặcASPECT_RATIO_720_BIN. Sau khi các latents được tạo ra được giải mã thành video, chúng sẽ được thay đổi kích thước trở lại độ phân giải yêu cầu. Hữu ích để tạo ra các video không vuông. - 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à300) — Chiều dài tối đa của chuỗi để sử dụng vớiprompt. - complex_human_instruction (
list[str], tùy chọn) — Hướng dẫn cho sự chú ý phức tạp của con người: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.
Trả về
SanaVideoPipelineOutput hoặc tuple
Nếu return_dict là True, SanaVideoPipelineOutput 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 video đã tạo
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> import torch
>>> from diffusers import SanaImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> pipe = SanaImageToVideoPipeline.from_pretrained("Efficient-Large-Model/SANA-Video_2B_480p_diffusers")
>>> pipe.transformer.to(torch.bfloat16)
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> motion_score = 30
>>> prompt = "A woman stands against a stunning sunset backdrop, her long, wavy brown hair gently blowing in the breeze. She wears a sleeveless, light-colored blouse with a deep V-neckline, which accentuates her graceful posture. The warm hues of the setting sun cast a golden glow across her face and hair, creating a serene and ethereal atmosphere. The background features a blurred landscape with soft, rolling hills and scattered clouds, adding depth to the scene. The camera remains steady, capturing the tranquil moment from a medium close-up angle."
>>> negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
>>> motion_prompt = f" motion score: {motion_score}."
>>> prompt = prompt + motion_prompt
>>> image = load_image("https://raw.githubusercontent.com/NVlabs/Sana/refs/heads/main/asset/samples/i2v-1.png")
>>> output = pipe(
... image=image,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=480,
... width=832,
... frames=81,
... guidance_scale=6,
... num_inference_steps=50,
... generator=torch.Generator(device="cuda").manual_seed(42),
... ).frames[0]
>>> export_to_video(output, "sana-ti2v-output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenegative_prompt: str = ''num_videos_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_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] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | 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 không dùng để định hướng việc tạo video. Nếu không được định nghĩa, bạn phải 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). Đối với PixArt-Alpha, giá trị này nên là "". - 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 - device — (
torch.device, tùy chọn): thiết bị torch để đặt các embedding kết quả lên - 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. Đối với Sana, đây nên là các embedding của chuỗi "". - clean_caption (
bool, mặc định làFalse) — NếuTrue, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa. - max_sequence_length (
int, mặc định là 300) — Độ dài tối đa của chuỗi được sử dụng cho prompt. - complex_human_instruction (
list[str], mặc định làcomplex_human_instruction) — Nếucomplex_human_instructionkhông rỗng, hàm sẽ sử dụng chỉ thị Human phức tạp cho prompt.
Mã hóa prompt thành các trạng thái ẩn của text encoder.
SanaVideoPipelineOutput
lớp diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput
< 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 Sana-Video.