Diffusers documentation
Sana-Video
Sana-Video
来自 NVIDIA 和 MIT HAN Lab 的 SANA-Video: Efficient Video Generation with Block Linear Diffusion Transformer,作者为 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。
该论文的摘要如下:
我们推出了 SANA-Video,一个小型扩散模型,能够高效生成分辨率高达 720x1280、时长可达分钟级的视频。SANA-Video 以极快的速度合成高分辨率、高质量且长时长的视频,并具备强大的文本-视频对齐能力,可部署在 RTX 5090 GPU 上。两项核心设计确保了高效、有效且长时长的视频生成:(1) Linear DiT:我们利用线性注意力作为核心操作,鉴于视频生成中处理的 token 数量庞大,这比原生注意力机制更高效。(2) 用于块线性注意力的恒定内存 KV 缓存:我们通过采用源自线性注意力累积特性的恒定内存状态,设计了用于长视频生成的块级自回归方法。该 KV 缓存以固定的内存成本为 Linear DiT 提供全局上下文,消除了对传统 KV 缓存的需求,从而实现了高效的分钟级视频生成。此外,我们探索了有效的数据过滤和模型训练策略,将训练成本降低至 64 块 H100 GPU 上 12 天,仅为 MovieGen 成本的 1%。凭借低成本,SANA-Video 在实测延迟上快 16 倍的同时,相较于现代最先进的中小型扩散模型(例如 Wan 2.1-1.3B 和 SkyReel-V2-1.3B)实现了具有竞争力的性能。此外,SANA-Video 可以以 NVFP4 精度部署在 RTX 5090 GPU 上,将生成 5 秒 720p 视频的推理速度从 71 秒加速至 29 秒(2.4 倍加速)。总之,SANA-Video 实现了低成本、高质量的视频生成。this https URL。
此流水线由 SANA Team 贡献。原始代码库可在此处找到。原始权重可在 hf.co/Efficient-Large-Model 下找到。
可用模型:
| 模型 | 推荐的 dtype |
|---|---|
Efficient-Large-Model/SANA-Video_2B_480p_diffusers | torch.bfloat16 |
有关更多信息,请参阅此集合。
注意:上述推荐的 dtype 适用于 transformer 权重。为了确保模型正确运行,文本编码器和 VAE 的权重必须保持为 torch.bfloat16 或 torch.float32。请参阅下方的推理示例,了解如何以推荐的 dtype 加载模型。
生成流水线
下面的示例演示了如何使用文本到视频流水线,根据文本描述生成视频。
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)下面的示例演示了如何使用图像到视频流水线,根据文本描述和起始帧生成视频。
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)量化
量化通过以较低精度的数据类型存储模型权重,有助于降低超大模型的内存需求。不过,量化对视频质量的影响会因视频模型的不同而有所差异。
请参阅 量化 概述,以了解支持的量化后端以及如何选择支持您使用场景的量化后端。以下示例演示了如何使用 bitsandbytes 加载量化的 SanaVideoPipeline 进行推理。
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
class 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 )
参数
- tokenizer(
GemmaTokenizer或GemmaTokenizerFast)—— 用于对提示词进行分词的 tokenizer。 - text_encoder (
Gemma2PreTrainedModel) — 用于编码输入提示的文本编码器模型。 - vae(
AutoencoderKLWan、AutoencoderDC或AutoencoderKLLTX2Video)—— 用于将视频编码和解码为潜在表示的变分自编码器(VAE)模型。 - transformer (SanaVideoTransformer3DModel) — 用于对输入潜变量进行去噪的条件 Transformer。
- scheduler (DPMSolverMultistepScheduler) —
用于与
transformer配合,对编码后的视频潜变量进行去噪的调度器。
使用 Sana 进行文本到视频生成的 Pipeline。该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。
__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
参数
- prompt (
str或list[str],可选) — 用于引导视频生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - negative_prompt (
str或list[str],可选) — 用于不引导视频生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时(即guidance_scale小于1时)将被忽略。 - num_inference_steps (
int,可选,默认值为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的视频,但推理速度会变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float,可选,默认值为 4.5) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的视频,但通常以牺牲视频质量为代价。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词生成的视频数量。 - height (
int,可选,默认值为 480) — 生成视频的高度(以像素为单位)。 - width (
int,可选,默认为 832) — 生成视频的宽度(以像素为单位)。 - frames (
int,可选,默认为 81) — 生成视频的帧数。 - eta(
float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - prompt_attention_mask (
torch.Tensor,可选) — 为文本嵌入预生成的注意力掩码。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 PixArt-Sigma,此负向提示应为 ""。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_prompt_attention_mask (
torch.Tensor, 可选) — 为负向文本嵌入预生成的注意力掩码。 - output_type (
str,可选,默认为"pil") — 生成视频的输出格式。可选 mp4 或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回SanaVideoPipelineOutput而不是普通元组。 - attention_kwargs —
一个 kwargs 字典,如果指定,将传递给
AttentionProcessor,该处理器在 diffusers.models.attention_processor 中定义,并位于self.processor下。 - clean_caption (
bool,可选,默认为True) — 是否在创建嵌入之前清理字幕。需要安装beautifulsoup4和ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。 - use_resolution_binning (
bool,默认为True) — 如果设置为True,请求的高度和宽度会先通过ASPECT_RATIO_480_BIN或ASPECT_RATIO_720_BIN映射到最接近的分辨率。生成的潜变量解码为视频后,会重新调整回请求的分辨率。适用于生成非正方形视频。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传入。您只能包含流水线类的._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为300)— 与prompt配合使用的最大序列长度。 - complex_human_instruction (
list[str], 可选) — 用于复杂人类注意力的指令: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55。
返回值
SanaVideoPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 SanaVideoPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成视频的列表
调用生成 pipeline 时调用的函数。
示例:
>>> 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 )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导视频生成的提示词。如果未定义,则必须改为传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。对于 PixArt-Alpha,此值应为 ""。 - do_classifier_free_guidance (
bool,可选,默认为True) — 是否使用 classifier free guidance - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量 - device — (
torch.device,可选): 用于放置生成的嵌入向量的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 Sana,它应该是空字符串 "" 的嵌入。 - clean_caption (
bool,默认为False) — 如果为True,该函数将在编码之前对提供的 caption 进行预处理和清理。 - max_sequence_length (
int,默认为 300) — 用于提示词的最大序列长度。 - complex_human_instruction (
list[str],默认为complex_human_instruction) — 如果complex_human_instruction不为空,该函数将使用复杂的 Human 指令作为提示词。
将提示词编码为文本编码器的隐藏状态。
SanaImageToVideoPipeline
class 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 )
参数
- tokenizer(
GemmaTokenizer或GemmaTokenizerFast)—— 用于对提示词进行分词的 tokenizer。 - text_encoder (
Gemma2PreTrainedModel) — 用于编码输入提示的文本编码器模型。 - vae(
AutoencoderKLWan、AutoencoderDC或AutoencoderKLLTX2Video)—— 用于将视频编码和解码为潜在表示的变分自编码器(VAE)模型。 - transformer (SanaVideoTransformer3DModel) — 用于对输入潜变量进行去噪的条件 Transformer。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的视频潜变量进行去噪的调度器。
使用 Sana 进行图像/文本到视频生成的 Pipeline。该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。
__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
参数
- image (
PipelineImageInput) — 用于条件化视频生成的输入图像。生成视频的第一帧将基于此图像进行条件化。 - prompt (
str或list[str],可选) — 用于引导视频生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - negative_prompt (
str或list[str],可选) — 用于不引导视频生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时(即guidance_scale小于1时)将被忽略。 - num_inference_steps (
int,可选,默认值为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的视频,但推理速度会变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float,可选,默认值为 4.5) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的视频,但通常以牺牲视频质量为代价。 - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词生成的视频数量。 - height (
int,可选,默认值为 480) — 生成视频的高度(以像素为单位)。 - width (
int,可选,默认为 832) — 生成视频的宽度(以像素为单位)。 - frames (
int,可选,默认为 81) — 生成视频的帧数。 - eta(
float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - prompt_attention_mask (
torch.Tensor,可选) — 为文本嵌入预生成的注意力掩码。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 PixArt-Sigma,此负向提示应为 ""。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_prompt_attention_mask (
torch.Tensor, 可选) — 为负向文本嵌入预生成的注意力掩码。 - output_type (
str,可选,默认为"pil") — 生成视频的输出格式。可选 mp4 或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回SanaVideoPipelineOutput而不是普通元组。 - attention_kwargs —
一个 kwargs 字典,如果指定,将传递给
AttentionProcessor,该处理器在 diffusers.models.attention_processor 中定义,并位于self.processor下。 - clean_caption (
bool,可选,默认为True) — 是否在创建嵌入之前清理字幕。需要安装beautifulsoup4和ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。 - use_resolution_binning (
bool,默认为True) — 如果设置为True,请求的高度和宽度会先通过ASPECT_RATIO_480_BIN或ASPECT_RATIO_720_BIN映射到最接近的分辨率。生成的潜变量解码为视频后,会重新调整回请求的分辨率。适用于生成非正方形视频。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传入。您只能包含流水线类的._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为300)— 与prompt配合使用的最大序列长度。 - complex_human_instruction (
list[str], 可选) — 用于复杂人类注意力的指令: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55。
返回值
SanaVideoPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 SanaVideoPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成视频的列表
调用生成 pipeline 时调用的函数。
示例:
>>> 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 )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - negative_prompt (
str或list[str],可选) — 用于不引导视频生成的提示词。如果未定义,则必须改为传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。对于 PixArt-Alpha,此值应为 ""。 - do_classifier_free_guidance (
bool,可选,默认为True) — 是否使用 classifier free guidance - num_videos_per_prompt (
int,可选,默认为 1) — 每个提示词应生成的视频数量 - device — (
torch.device,可选): 用于放置生成的嵌入向量的 torch 设备 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 Sana,它应该是空字符串 "" 的嵌入。 - clean_caption (
bool,默认为False) — 如果为True,该函数将在编码之前对提供的 caption 进行预处理和清理。 - max_sequence_length (
int,默认为 300) — 用于提示词的最大序列长度。 - complex_human_instruction (
list[str],默认为complex_human_instruction) — 如果complex_human_instruction不为空,该函数将使用复杂的 Human 指令作为提示词。
将提示词编码为文本编码器的隐藏状态。
SanaVideoPipelineOutput
class diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput
< source >( frames: Tensor )
Sana-Video 流水线的输出类。