#
# Apache License, Version 2.0（「ライセンス」）の下でライセンスされています。
# このファイルは、ライセンスに準拠した場合にのみ使用できます。
# ライセンスのコピーは以下から入手できます
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 適用される法律で要求される場合、または書面による合意がある場合を除き、ソフトウェア
# ライセンスに基づき配布される本ソフトウェアは、「現状のまま」
# 明示的または黙示的を問わず、いかなる種類の保証や条件も付随しません。
# 権限を管理する特定の言語については、ライセンスを参照してください。
# ライセンスの下での制限。-->

# 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](https://huggingface.co/papers/2509.24695)

論文の抄録は以下の通りです：

*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](https://github.com/NVlabs/SANA)。*

このパイプラインは SANA Team によって提供されました。元のコードベースは[こちら](https://github.com/NVlabs/Sana)で確認できます。元の重みは[hf.co/Efficient-Large-Model](https://hf.co/collections/Efficient-Large-Model/sana-video)の下で確認できます。

利用可能なモデル:

| モデル | 推奨されるdtype |
|:-----:|:-----------------:|
| [`Efficient-Large-Model/SANA-Video_2B_480p_diffusers`](https://huggingface.co/Efficient-Large-Model/ANA-Video_2B_480p_diffusers) | `torch.bfloat16` |

詳細については、[こちら](https://huggingface.co/collections/Efficient-Large-Model/sana-video)のコレクションを参照してください。

注: 上記で言及している推奨のdtypeは、transformerの重みに関するものです。モデルが正しく動作するためには、テキストエンコーダーとVAEの重みは`torch.bfloat16`または`torch.float32`のままにしておく必要があります。推奨のdtypeでモデルを読み込む方法については、以下の推論の例を参照してください。

## 生成パイプライン

`

以下の例では、テキスト説明を使用して動画を生成するために、テキストから動画へのパイプラインを使用する方法を示しています。

```python
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 パイプラインを使用する方法を示しています。

```python
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](../../quantization/overview)の概要を参照してください。以下の例では、bitsandbytesを使用して量子化された[SanaVideoPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_video#diffusers.SanaVideoPipeline)を読み込んで推論を実行する方法を示しています。

```py
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]]

#### diffusers.SanaVideoPipeline[[diffusers.SanaVideoPipeline]]

```python
diffusers.SanaVideoPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan, transformer: SanaVideoTransformer3DModel, scheduler: DPMSolverMultistepScheduler)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video.py#L186)

**パラメータ:**

tokenizer (`GemmaTokenizer` または `GemmaTokenizerFast`) : プロンプトをトークン化するために使用されるトークナイザー。

text_encoder (`Gemma2PreTrainedModel`) : 入力プロンプトをエンコードするためのテキストエンコーダーモデル。

vae ([`AutoencoderKLWan`、`AutoencoderDC`、または `AutoencoderKLLTX2Video`]) : 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

transformer ([SanaVideoTransformer3DModel](/docs/diffusers/v0.43.0/ja/api/models/sana_video_transformer3d#diffusers.SanaVideoTransformer3DModel)) : 入力潜在変数をデノイズするための条件付き Transformer。

scheduler ([DPMSolverMultistepScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler)) : `transformer` と組み合わせて、エンコードされた動画の潜在変数からノイズを除去するために使用するスケジューラー。

[Sana](https://huggingface.co/papers/2509.24695) を使用したテキストから動画への生成を行う Pipeline です。このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべての Pipeline に実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[diffusers.SanaVideoPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, height: int = 480, width: int = 832, frames: int = 81, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, clean_caption: bool = False, use_resolution_binning: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 300, complex_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: '])
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video.py#L712)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : 動画生成をガイドするためのプロンプトまたはプロンプトのリストです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。

negative_prompt (`str` または `list[str]`、*省略可*) : 動画生成をガイドしないためのプロンプトまたはプロンプトのリストです。定義されていない場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイドを使用していない場合は無視されます（`guidance_scale` が `1` 未満の場合は無視されます）。

num_inference_steps (`int`、*optional*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

timesteps (`list[int]`、*任意*) : `set_timesteps` メソッドで `timesteps` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムタイムステップ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。降順で指定する必要があります。

sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。

guidance_scale (`float`、*任意*、デフォルト値は 4.5) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、テキストの `prompt` と密接に関連する動画の生成が促されますが、通常は動画の品質が低下する傾向があります。

num_videos_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する動画の数を指定します。

height (`int`、*optional*、デフォルトは 480) : 生成される動画のピクセル単位の縦幅。

width (`int`、*任意*、デフォルトは 832) : 生成される動画の幅（ピクセル単位）。

frames (`int`、*optional*、デフォルトは 81) : 生成される動画のフレーム数です。

eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 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](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `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](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_video#diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput) または `tuple`

`return_dict` が `True` の場合、[SanaVideoPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_video#diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput) が返され、それ以外の場合は、最初の要素が生成された動画のリストである `tuple` が返されます。

生成用のパイプラインを呼び出したときに実行される関数。

例:
```py
>>> 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[[diffusers.SanaVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_videos_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, complex_human_instruction: list[str] | None = None, lora_scale: float | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video.py#L303)

**パラメータ:**

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`、*optional*、デフォルトは 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 instruction を使用します。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

## SanaImageToVideoPipeline[[diffusers.SanaImageToVideoPipeline]]

#### diffusers.SanaImageToVideoPipeline[[diffusers.SanaImageToVideoPipeline]]

```python
diffusers.SanaImageToVideoPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan, transformer: SanaVideoTransformer3DModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video_i2v.py#L176)

**パラメータ:**

tokenizer (`GemmaTokenizer` または `GemmaTokenizerFast`) : プロンプトをトークン化するために使用されるトークナイザー。

text_encoder (`Gemma2PreTrainedModel`) : 入力プロンプトをエンコードするためのテキストエンコーダーモデル。

vae ([`AutoencoderKLWan`、`AutoencoderDC`、または `AutoencoderKLLTX2Video`]) : 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

transformer ([SanaVideoTransformer3DModel](/docs/diffusers/v0.43.0/ja/api/models/sana_video_transformer3d#diffusers.SanaVideoTransformer3DModel)) : 入力潜在変数をデノイズするための条件付き Transformer。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`と組み合わせて、エンコードされた動画の潜在変数（latents）のノイズ除去に使用するスケジューラー。

[Sana](https://huggingface.co/papers/2509.24695) を使用した画像/テキストから動画への生成を行う Pipeline です。このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべての Pipeline に実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[diffusers.SanaImageToVideoPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, height: int = 480, width: int = 832, frames: int = 81, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, clean_caption: bool = False, use_resolution_binning: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 300, complex_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: '])
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video_i2v.py#L739)

**パラメータ:**

image (`PipelineImageInput`) : 動画生成の条件として使用する入力画像です。生成される動画の最初のフレームは、この画像を条件として生成されます。

prompt (`str` または `list[str]`、*省略可能*) : 動画生成をガイドするためのプロンプトまたはプロンプトのリストです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。

negative_prompt (`str` または `list[str]`、*省略可*) : 動画生成をガイドしないためのプロンプトまたはプロンプトのリストです。定義されていない場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイドを使用していない場合は無視されます（`guidance_scale` が `1` 未満の場合は無視されます）。

num_inference_steps (`int`、*optional*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

timesteps (`list[int]`、*任意*) : `set_timesteps` メソッドで `timesteps` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムタイムステップ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。降順で指定する必要があります。

sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。

guidance_scale (`float`、*任意*、デフォルト値は 4.5) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、テキストの `prompt` と密接に関連する動画の生成が促されますが、通常は動画の品質が低下する傾向があります。

num_videos_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する動画の数を指定します。

height (`int`、*optional*、デフォルトは 480) : 生成される動画のピクセル単位の縦幅。

width (`int`、*任意*、デフォルトは 832) : 生成される動画の幅（ピクセル単位）。

frames (`int`、*optional*、デフォルトは 81) : 生成される動画のフレーム数です。

eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 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](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `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](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_video#diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput) または `tuple`

`return_dict` が `True` の場合、[SanaVideoPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_video#diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput) が返され、それ以外の場合は、最初の要素が生成された動画のリストである `tuple` が返されます。

生成用のパイプラインを呼び出したときに実行される関数。

例:
```py
>>> 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[[diffusers.SanaImageToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_videos_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, complex_human_instruction: list[str] | None = None, lora_scale: float | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_sana_video_i2v.py#L301)

**パラメータ:**

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`、*optional*、デフォルトは 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 instruction を使用します。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

## SanaVideoPipelineOutput[[diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput]]

#### diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput[[diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput]]

```python
diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput(frames: Tensor)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana_video/pipeline_output.py#L9)

**パラメータ:**

frames (`torch.Tensor`、`np.ndarray`、または list[list[PIL.Image.Image]]) : 動画出力のリスト - `batch_size,` 長のネストされたリストであり、各サブリストには `num_frames.` 長のデノイズ済み PIL 画像シーケンスが含まれる場合があります。また、`(batch_size, num_frames, channels, height, width)` の形状を持つ NumPy 配列や Torch テンソルである場合もあります。

Sana-Video パイプライン用の出力クラスです。

