Diffusers documentation
Sana-Video
Sana-Video
NVIDIA と MIT HAN Lab による 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: Efficient Video Generation with Block Linear Diffusion Transformer
論文の抄録は以下の通りです:
SANA-Video を紹介します。これは、最大 720x1280 の解像度と分単位の長さの動画を効率的に生成できる小型の拡散モデルです。SANA-Video は、RTX 5090 GPU にデプロイ可能であり、驚くほど高速な速度で、テキストと動画の整合性が強く、高解像度・高品質・長時間の動画を合成します。効率的かつ効果的な長時間動画生成を実現する 2 つの核心的な設計があります。(1) Linear DiT: 動画生成では大量のトークンを処理するため、バニラアテンションよりも効率的な線形アテンションをコア操作として活用しています。(2) Block Linear Attention 向けの定数メモリ KV キャッシュ: 線形アテンションの累積特性から導出される定数メモリ状態を採用することで、ブロック単位の自己回帰アプローチを設計し、長時間の動画生成を実現しています。この KV キャッシュにより、Linear DiT は固定のメモリコストでグローバルなコンテキストを取得でき、従来の KV キャッシュの必要性を排除し、効率的な分単位の動画生成を可能にします。さらに、効果的なデータフィルタとモデル学習戦略を探索し、64 枚の H100 GPU での学習コストを 12 日間に縮小しました。これは MovieGen のコストのわずか 1% です。この低コストにもかかわらず、SANA-Video は、最新の最先端の小型拡散モデル(例: Wan 2.1-1.3B や SkyReel-V2-1.3B)と比較して競争力のある性能を達成すると同時に、測定されたレイテンシでは 16 倍高速です。さらに、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)以下の例では、テキストの説明と開始フレームを使用して動画を生成するために、image-to-video パイプラインを使用する方法を示しています。
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)量子化
Quantizationは、モデルの重みを低精度のデータ型で保存することで、非常に大規模なモデルのメモリ要件を軽減するのに役立ちます。ただし、動画モデルによって、Quantizationが動画の品質に与える影響は異なります。
サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択方法については、Quantizationの概要を参照してください。以下の例では、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
クラス 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)— プロンプトをトークン化するために使用されるトークナイザーです。 - text_encoder (
Gemma2PreTrainedModel) — 入力プロンプトをエンコードするためのテキストエンコーダーモデルです。 - vae(
AutoencoderKLWan、AutoencoderDC、またはAutoencoderKLLTX2Video)— 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデルです。 - transformer (SanaVideoTransformer3DModel) — 入力潜在変数をノイズ除去するための条件付き Transformer。
- scheduler (DPMSolverMultistepScheduler) —
transformerと組み合わせて、エンコードされた動画の潜在変数(latents)のノイズ除去に使用するスケジューラ。
Sana を使用したテキストから動画への生成を行う Pipeline です。このモデルは DiffusionPipeline を継承しています。すべての Pipeline に実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 50timesteps: list = Nonesigmas: list = 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 = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["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]、任意) —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) — 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 ジェネレーター1つまたはリスト。 - latents (
torch.Tensor, 任意) — ガウス分布からサンプリングされた、動画生成の入力として使用する事前生成されたノイズ付き潜在変数。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。 - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - prompt_attention_mask (
torch.Tensor, 任意) — テキスト埋め込み用の事前生成されたアテンションマスク。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたネガティブテキストの埋め込みです。PixArt-Sigma の場合、このネガティブプロンプトは "" である必要があります。指定されない場合、negative_prompt入力引数から negative_prompt_embeds が生成されます。 - negative_prompt_attention_mask (
torch.Tensor, 任意) — ネガティブなテキスト埋め込み用の事前生成されたアテンションマスクです。 - output_type (
str、任意、デフォルトは"pil") — 生成された動画の出力形式です。mp4 またはnp.arrayから選択します。 - return_dict (
bool、省略可能、デフォルトはTrue) —SanaVideoPipelineOutputを返すか、通常のタプルを返すかを指定します。 - attention_kwargs —
指定された場合、diffusers.models.attention_processor で定義されている
self.processor配下のAttentionProcessorに渡される kwargs 辞書。 - 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 が返されます。
生成用のパイプラインを呼び出したときに実行される関数。
例:
>>> 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) — 1 つのプロンプトに対して生成する動画の数 - device — (
torch.device, 任意): 生成される埋め込みを配置する torch デバイス - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前生成されたネガティブテキストの埋め込み。Sana の場合は、"" 文字列の埋め込みである必要があります。 - clean_caption (
bool、デフォルトはFalse) —Trueの場合、エンコード前に提供されたキャプションを前処理してクリーニングします。 - 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)— プロンプトをトークン化するために使用されるトークナイザーです。 - text_encoder (
Gemma2PreTrainedModel) — 入力プロンプトをエンコードするためのテキストエンコーダーモデルです。 - vae(
AutoencoderKLWan、AutoencoderDC、またはAutoencoderKLLTX2Video)— 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデルです。 - transformer (SanaVideoTransformer3DModel) — 入力潜在変数をノイズ除去するための条件付き Transformer。
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformerと組み合わせて、エンコードされた動画の潜在変数(latents)のノイズ除去に使用するスケジューラ。
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 = Nonesigmas: list = 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 = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["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]、任意) —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) — 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 ジェネレーター1つまたはリスト。 - latents (
torch.Tensor, 任意) — ガウス分布からサンプリングされた、動画生成の入力として使用する事前生成されたノイズ付き潜在変数。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、潜在変数テンソルが生成されます。 - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - prompt_attention_mask (
torch.Tensor, 任意) — テキスト埋め込み用の事前生成されたアテンションマスク。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたネガティブテキストの埋め込みです。PixArt-Sigma の場合、このネガティブプロンプトは "" である必要があります。指定されない場合、negative_prompt入力引数から negative_prompt_embeds が生成されます。 - negative_prompt_attention_mask (
torch.Tensor, 任意) — ネガティブなテキスト埋め込み用の事前生成されたアテンションマスクです。 - output_type (
str、任意、デフォルトは"pil") — 生成された動画の出力形式です。mp4 またはnp.arrayから選択します。 - return_dict (
bool、省略可能、デフォルトはTrue) —SanaVideoPipelineOutputを返すか、通常のタプルを返すかを指定します。 - attention_kwargs —
指定された場合、diffusers.models.attention_processor で定義されている
self.processor配下のAttentionProcessorに渡される kwargs 辞書。 - 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 が返されます。
生成用のパイプラインを呼び出したときに実行される関数。
例:
>>> 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) — 1 つのプロンプトに対して生成する動画の数 - device — (
torch.device, 任意): 生成される埋め込みを配置する torch デバイス - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前生成されたネガティブテキストの埋め込み。Sana の場合は、"" 文字列の埋め込みである必要があります。 - clean_caption (
bool、デフォルトはFalse) —Trueの場合、エンコード前に提供されたキャプションを前処理してクリーニングします。 - max_sequence_length (
int、デフォルト値は 300) — プロンプトに使用する最大シーケンス長。 - complex_human_instruction (
list[str]、デフォルトはcomplex_human_instruction) —complex_human_instructionが空でない場合、プロンプトに複雑な Human 指示を使用します。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
SanaVideoPipelineOutput
クラス diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput
< source >( frames: Tensor )
パラメータ
- frames (
torch.Tensor,np.ndarray, or list[list[PIL.Image.Image]]) — List of video outputs - It can be a nested list of lengthbatch_size,with each sub-list containing denoised PIL image sequences of lengthnum_frames.It can also be a NumPy array or Torch tensor of shape(batch_size, num_frames, channels, height, width).
Sana-Video パイプライン用の出力クラスです。