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

# SANA-Sprint

  

NVIDIA、MIT HAN Lab、Hugging Face による Junsong Chen、Shuchen Xue、Yuyang Zhao、Jincheng Yu、Sayak Paul、Junyu Chen、Han Cai、Enze Xie、Song Han 著の [SANA-Sprint: One-Step Diffusion with Continuous-Time Consistency Distillation](https://huggingface.co/papers/2503.09641)

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

*本論文では、超高速なテキストから画像への生成（T2I）のための効率的な拡散モデルである SANA-Sprint を提案します。SANA-Sprint は事前学習済みの基盤モデルをベースに構築され、ハイブリッド蒸留を適用することで、推論ステップを 20 から 1〜4 に大幅に削減しています。本論文では 3 つの主要な革新を導入します。(1) 事前学習済みのフローマッチングモデルを連続時間一貫性蒸留（sCM）に変換する、学習不要のアプローチを提案します。これにより、ゼロからの高コストな学習を排除し、高い学習効率を実現します。私たちのハイブリッド蒸留戦略は、sCM と潜在敵対的蒸留（LADD）を組み合わせます。sCM は教師モデルとの整合性を確保し、LADD は 1 ステップ生成の忠実度を高めます。(2) SANA-Sprint は、1〜4 ステップで高品質な生成を実現する統一されたステップ適応型モデルであり、ステップ固有の学習を排除し、効率を向上させます。(3) SANA-Sprint に ControlNet を統合し、リアルタイムの対話型画像生成を可能にすることで、ユーザーインタラクションに対する即座の視覚フィードバックを実現します。SANA-Sprint は、速度と品質のトレードオフにおいて新たなパレートフロンティアを確立し、わずか 1 ステップで FID 7.59、GenEval 0.74 という最先端の性能を達成しています。これは FLUX-schnell（FID 7.94 / GenEval 0.71）を上回り、かつ 10 倍高速（H100 上で 0.1 秒 vs 1.1 秒）です。また、H100 上で 1024×1024 画像に対して T2I で 0.1 秒、ControlNet で 0.25 秒のレイテンシを達成し、RTX 4090 上では T2I で 0.31 秒を達成しています。これにより、その卓越した効率性と、AI 駆動の消費者向けアプリケーション（AIPC）への適用可能性を示しています。コードと事前学習済みモデルはオープンソース化されます。*

このパイプラインは、[lawrence-cj](https://github.com/lawrence-cj)、[shuchen Xue](https://github.com/scxue)、[Enze Xie](https://github.com/xieenze) によって提供されました。元のコードベースは[こちら](https://github.com/NVlabs/Sana)で確認できます。元の重みは [hf.co/Efficient-Large-Model](https://huggingface.co/Efficient-Large-Model/) 配下で確認できます。

利用可能なモデル:

|                                                                    モデル                                                                    | 推奨されるdtype |
|:-------------------------------------------------------------------------------------------------------------------------------------------:|:-----------------:|
| [`Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers) | `torch.bfloat16`  |
| [`Efficient-Large-Model/Sana_Sprint_0.6B_1024px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_Sprint_0.6B_1024px_diffusers) | `torch.bfloat16`  |

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

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

## 量子化

Quantizationは、モデルの重みを低精度のデータ型で保存することで、非常に大規模なモデルのメモリ要件を軽減するのに役立ちます。ただし、動画モデルによって、Quantizationが動画の品質に与える影響は異なります。

サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択方法については、[Quantization](../../quantization/overview)の概要を参照してください。以下の例では、bitsandbytesを使用して量子化された[SanaSprintPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_sprint#diffusers.SanaSprintPipeline)を読み込んで推論を実行する方法を示しています。

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaTransformer2DModel, SanaSprintPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = AutoModel.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    subfolder="text_encoder",
    quantization_config=quant_config,
    dtype=torch.bfloat16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SanaTransformer2DModel.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.bfloat16,
)

pipeline = SanaSprintPipeline.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.bfloat16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt).images[0]
image.save("sana.png")
```

## `max_timesteps`の設定

ユーザーは、生成される出力の視覚的な品質をテストするために、`max_timesteps` の値を調整できます。デフォルトの `max_timesteps` 値は、推論時の探索プロセスによって得られました。詳細については、論文を参照してください。

## 画像から画像へ 

[SanaSprintImg2ImgPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_sprint#diffusers.SanaSprintImg2ImgPipeline) は、画像から画像を生成するためのパイプラインです。入力画像とプロンプトを受け取り、それらを基に新しい画像を生成します。

```py
import torch
from diffusers import SanaSprintImg2ImgPipeline
from diffusers.utils.loading_utils import load_image

image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
)

pipe = SanaSprintImg2ImgPipeline.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", 
    dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a cute pink bear", 
    image=image, 
    strength=0.5, 
    height=832, 
    width=480
).images[0]
image.save("output.png")
```

## SanaSprintPipeline[[diffusers.SanaSprintPipeline]]

#### diffusers.SanaSprintPipeline[[diffusers.SanaSprintPipeline]]

```python
diffusers.SanaSprintPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: AutoencoderDC, transformer: SanaTransformer2DModel, scheduler: DPMSolverMultistepScheduler)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana/pipeline_sana_sprint.py#L140)

[SANA-Sprint](https://huggingface.co/papers/2503.09641) を使用したテキストから画像を生成する Pipeline です。

#### __call__[[diffusers.SanaSprintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, num_inference_steps: int = 2, timesteps: list[int] = None, max_timesteps: float = 1.5708, intermediate_timesteps: float = 1.3, guidance_scale: float = 4.5, num_images_per_prompt: int | None = 1, height: int = 1024, width: int = 1024, 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, 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 image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete 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 curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus 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/pipeline_sana_sprint.py#L561)

**パラメータ:**

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

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

max_timesteps (`float`、*任意*、デフォルト値は 1.57080) : SCM スケジューラーで使用する最大タイムステップ値です。

intermediate_timesteps (`float`、*任意*、デフォルト値は 1.3) : SCM スケジューラーで使用する中間タイムステップの値です（num_inference_steps=2 の場合のみ使用されます）。

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

guidance_scale (`float`、*任意*、デフォルト値は 4.5) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` の値を高くすると、`prompt` により一貫性のある画像を生成するようモデルを促しますが、その代わりとして画像の品質が低下します。ガイダンス蒸留モデルは、`guidance_scale` > 1 に対して、真のクラスファイアフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

height (`int`, *optional*, デフォルトは self.unet.config.sample_size) : 生成される画像のピクセル単位の縦幅。

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

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`, *任意*) : テキスト埋め込み用の事前生成されたアテンションマスク。

output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)（`PIL.Image.Image`）または `np.array` から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく`~pipelines.stable_diffusion.IFPipelineOutput`を返すかどうか。

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_1024_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.

**戻り値:** [SanaPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_sprint#diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput) または `tuple`

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

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

例:
```py
>>> import torch
>>> from diffusers import SanaSprintPipeline

>>> pipe = SanaSprintPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(prompt="a tiny astronaut hatching from an egg on the moon")[0]
>>> image[0].save("output.png")
```

#### encode_prompt[[diffusers.SanaSprintPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, 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/pipeline_sana_sprint.py#L232)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト

num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数

device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

clean_caption (`bool`、デフォルトは`False`) : `True`の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。

max_sequence_length (`int`、デフォルトは 300) : プロンプトに使用する最大シーケンス長。

complex_human_instruction (`list[str]`、デフォルトは `complex_human_instruction`) : `complex_human_instruction` が空でない場合、この関数はプロンプトに複雑な Human instruction を使用します。

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

## SanaSprintImg2ImgPipeline[[diffusers.SanaSprintImg2ImgPipeline]]

#### diffusers.SanaSprintImg2ImgPipeline[[diffusers.SanaSprintImg2ImgPipeline]]

```python
diffusers.SanaSprintImg2ImgPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: AutoencoderDC, transformer: SanaTransformer2DModel, scheduler: DPMSolverMultistepScheduler)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py#L146)

[SANA-Sprint](https://huggingface.co/papers/2503.09641) を使用したテキストから画像を生成する Pipeline です。

#### __call__[[diffusers.SanaSprintImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, num_inference_steps: int = 2, timesteps: list[int] = None, max_timesteps: float = 1.5708, intermediate_timesteps: float = 1.3, guidance_scale: float = 4.5, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.6, num_images_per_prompt: int | None = 1, height: int = 1024, width: int = 1024, 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, 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 image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete 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 curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus 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/pipeline_sana_sprint_img2img.py#L629)

**パラメータ:**

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

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

max_timesteps (`float`、*任意*、デフォルト値は 1.57080) : SCM スケジューラーで使用する最大タイムステップ値です。

intermediate_timesteps (`float`、*任意*、デフォルト値は 1.3) : SCM スケジューラーで使用する中間タイムステップの値です（num_inference_steps=2 の場合のみ使用されます）。

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

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

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : 開始点として使用される画像バッチを表す `Image`、NumPy 配列、またはテンソル。画像の潜在変数（latents）を `image` として直接渡すこともできますが、その場合は再度エンコードされません。

strength (`float`、*任意*、デフォルト値は 0.6) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

height (`int`, *optional*, デフォルトは self.unet.config.sample_size) : 生成される画像のピクセル単位の縦幅。

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

eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://arxiv.org/abs/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`, *任意*) : テキスト埋め込み用の事前生成されたアテンションマスク。

output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)（`PIL.Image.Image`）または `np.array` から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく`~pipelines.stable_diffusion.IFPipelineOutput`を返すかどうか。

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_1024_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.

**戻り値:** [SanaPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/sana_sprint#diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput) または `tuple`

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

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

例:
```py
>>> import torch
>>> from diffusers import SanaSprintImg2ImgPipeline
>>> from diffusers.utils.loading_utils import load_image

>>> pipe = SanaSprintImg2ImgPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
... )

>>> image = pipe(prompt="a cute pink bear", image=image, strength=0.5, height=832, width=480).images[0]
>>> image[0].save("output.png")
```

#### encode_prompt[[diffusers.SanaSprintImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, 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/pipeline_sana_sprint_img2img.py#L240)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト

num_images_per_prompt (`int`、*optional*、デフォルトは 1) : プロンプトごとに生成する画像の枚数

device : (`torch.device`, *任意*): 生成される埋め込みを配置する torch デバイス

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

clean_caption (`bool`、デフォルトは`False`) : `True`の場合、エンコード前に提供されたキャプションを前処理してクリーニングします。

max_sequence_length (`int`、デフォルトは 300) : プロンプトに使用する最大シーケンス長。

complex_human_instruction (`list[str]`、デフォルトは `complex_human_instruction`) : `complex_human_instruction` が空でない場合、この関数はプロンプトに複雑な Human instruction を使用します。

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

## SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

#### diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

```python
diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

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

**パラメータ:**

images (`list[PIL.Image.Image]` または `np.ndarray`) : 長さ `batch_size` のデノイズ済み PIL イメージのリスト、または形状 `(batch_size, height, width, num_channels)` の numpy 配列。PIL イメージまたは numpy 配列は、拡散パイプラインのデノイズ済みイメージを表します。

Sana パイプライン用の出力クラス。

