# Stable Diffusion 3

  
  

Stable Diffusion 3 (SD3) は、Patrick Esser、Sumith Kulal、Andreas Blattmann、Rahim Entezari、Jonas Muller、Harry Saini、Yam Levi、Dominik Lorenz、Axel Sauer、Frederic Boesel、Dustin Podell、Tim Dockhorn、Zion English、Kyle Lacey、Alex Goodwin、Yannik Marek、Robin Rombach によって提案された [Scaling Rectified Flow Transformers for High-Resolution Image Synthesis](https://huggingface.co/papers/2403.03206) で紹介されました。

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

*Diffusionモデルは、データからノイズへのフォワードパスを逆転させることでノイズからデータを生成し、画像や動画などの高次元で知覚的なデータに対する強力な生成モデリング手法として台頭してきました。Rectified flowは、データとノイズを直線で結ぶ最近の生成モデルの定式化です。理論的な性質が優れており概念的に単純であるにもかかわらず、まだ標準的な手法として確立されていません。本研究では、Rectified flowモデルの学習における既存のノイズサンプリング手法を、知覚的に関連性の高いスケールにバイアスを与えることで改善します。大規模な研究を通じて、このアプローチが高分解能のテキストから画像への合成において、確立されたDiffusionの定式化と比較して優れた性能を発揮することを示します。さらに、テキストから画像への生成のための新しいTransformerベースのアーキテクチャを提案します。このアーキテクチャは、2つのモダリティに対して別々の重みを使用し、画像トークンとテキストトークンの間で双方向の情報フローを可能にすることで、テキスト理解、タイポグラフィ、および人間の好み評価を向上させます。このアーキテクチャが予測可能なスケーリング傾向に従い、検証損失の低下が、各種メトリクスおよび人間評価によって測定されるテキストから画像への合成の改善と相関することを示します。*

## 使用例

_このモデルはゲート付き（アクセス制限付き）のため、diffusers で使用する前に、まず [Stable Diffusion 3 Medium の Hugging Face ページ](https://huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers) にアクセスし、フォームに記入してゲートの承認を行う必要があります。承認が完了したら、システムがゲートの承認済みであることを認識できるよう、ログインしてください。_

以下のコマンドを使用してログインします:

```bash
hf auth login
```

> [!TIP]
> SD3 パイプラインは、画像を生成するために3つのテキストエンコーダーを使用します。ほとんどの汎用ハードウェアで実行するには、モデルのオフローディングが必要です。メモリをさらに節約するには、`torch.float16` データ型を使用してください。

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world.png")
```

**注:** Stable Diffusion 3.5 は SD3 パイプラインを使用して実行することもでき、上記で言及した最適化やテクニックはすべてこれにも適用されます。SD3 ファミリーには、公式モデルが合計3つあります:
- [`stabilityai/stable-diffusion-3-medium-diffusers`](https://huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers)
- [`stabilityai/stable-diffusion-3.5-large`](https://huggingface.co/stabilityai/stable-diffusion-3-5-large)
- [`stabilityai/stable-diffusion-3.5-large-turbo`](https://huggingface.co/stabilityai/stable-diffusion-3-5-large-turbo)

## IP-Adapters を用いた画像プロンプト

IP-Adapterを使用すると、テキストプロンプトに加えて画像でもSD3に指示を出すことができます。これは、テキストだけでは表現が難しい複雑な概念を説明する場合や、参照画像がある場合に特に役立ちます。IP-Adapterを読み込んで使用するには、以下が必要です：

- `image_encoder`: 画像特徴を取得するために使用される事前学習済みビジョンモデル。通常は CLIP の画像エンコーダーです。
- `feature_extractor`: 選択した`image_encoder`の入力として、入力画像を準備する画像プロセッサ。
- `ip_adapter_id`: 画像クロスアテンション層および画像投影のパラメータを含むチェックポイント。

IP-Adapter は特定のモデルアーキテクチャ向けに学習されるため、ベースモデルのファインチューニング済みバリエーションでも動作します。`~SD3IPAdapterMixin.set_ip_adapter_scale` 関数を使用して、出力が画像プロンプトにどの程度強く一致するかを調整できます。値が大きいほど、モデルは画像プロンプトに忠実に従います。デフォルト値の 0.5 は通常、良いバランスを保ち、モデルがテキストプロンプトと画像プロンプトの両方を同等に考慮することを保証します。

```python
import torch
from PIL import Image

from diffusers import StableDiffusion3Pipeline
from transformers import SiglipVisionModel, SiglipImageProcessor

image_encoder_id = "google/siglip-so400m-patch14-384"
ip_adapter_id = "InstantX/SD3.5-Large-IP-Adapter"

feature_extractor = SiglipImageProcessor.from_pretrained(
    image_encoder_id,
    dtype=torch.float16
)
image_encoder = SiglipVisionModel.from_pretrained(
    image_encoder_id,
    dtype=torch.float16
).to( "cuda")  # or "mps", "xpu", "cpu"

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    dtype=torch.float16,
    feature_extractor=feature_extractor,
    image_encoder=image_encoder,
).to("cuda")

pipe.load_ip_adapter(ip_adapter_id)
pipe.set_ip_adapter_scale(0.6)

ref_img = Image.open("image.jpg").convert('RGB')

image = pipe(
    width=1024,
    height=1024,
    prompt="a cat",
    negative_prompt="lowres, low quality, worst quality",
    num_inference_steps=24,
    guidance_scale=5.0,
    ip_adapter_image=ref_img
).images[0]

image.save("result.jpg")
```

    
    プロンプト「a cat」のIP-Adapterの例

> [!TIP]
> IP-Adapter の仕組みについて詳しく知るには、[IP-Adapter](../../../using-diffusers/ip_adapter) をご覧ください。

## SD3のメモリ最適化

SD3は3つのテキストエンコーダーを使用しており、その1つは非常に大規模なT5-XXLモデルです。そのため、`fp16`精度を使用する場合でも、VRAMが24GB未満のGPUでモデルを実行するのは困難です。次のセクションでは、リソースの少ないハードウェアでSD3をより容易に実行できるようにするDiffusersのメモリ最適化についていくつか紹介します。

### モデルオフローディングによる推論の実行

Diffusers で利用可能な最も基本的なメモリ最適化では、推論中にモデルのコンポーネントを CPU にオフロードしてメモリを節約できます。その代わり、推論のレイテンシがわずかに増加します。モデルのオフロードでは、コンポーネントの実行が必要になったタイミングで GPU 上に移動し、それ以外のコンポーネントは CPU に保持されます。

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16)
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world.png")
```

### 推論時のT5テキストエンコーダーの省略

推論時にメモリ集約型の4.7BパラメータのT5-XXLテキストエンコーダを除去することで、性能の低下はわずかなものの、SD3のメモリ要件を大幅に削減できます。

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    text_encoder_3=None,
    tokenizer_3=None,
    dtype=torch.float16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world-no-T5.png")
```

### T5テキストエンコーダーの量子化バージョンの使用

`bitsandbytes` ライブラリを活用して、T5-XXL テキストエンコーダーを8ビット精度でロードおよび量子化できます。これにより、3つのテキストエンコーダーをすべて使い続けつつ、パフォーマンスへの影響をわずかに抑えることができます。

まず、`bitsandbytes`ライブラリをインストールしてください。

```shell
pip install bitsandbytes
```

次に、`BitsAndBytesConfig` を使用して T5-XXL モデルを読み込みます。

```python
import torch
from diffusers import StableDiffusion3Pipeline
from transformers import T5EncoderModel, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model_id = "stabilityai/stable-diffusion-3-medium-diffusers"
text_encoder = T5EncoderModel.from_pretrained(
    model_id,
    subfolder="text_encoder_3",
    quantization_config=quantization_config,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    model_id,
    text_encoder_3=text_encoder,
    device_map="balanced",
    dtype=torch.float16
)

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world-8bit-T5.png")
```

エンドツーエンドのスクリプトは[こちら](https://gist.github.com/sayakpaul/82acb5976509851f2db1a83456e504f1)で確認できます。

## SD3のパフォーマンス最適化

### Torch Compile を使用して推論を高速化

SD3 パイプラインでコンパイル済みコンポーネントを使用すると、推論が最大4倍速くなる場合があります。以下のコードスニペットは、SD3 パイプラインの Transformer と VAE コンポーネントをコンパイルする方法を示しています。

```python
import torch
from diffusers import StableDiffusion3Pipeline

torch.set_float32_matmul_precision("high")

torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch._inductor.config.coordinate_descent_check_all_directions = True

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.set_progress_bar_config(disable=True)

pipe.transformer.to(memory_format=torch.channels_last)
pipe.vae.to(memory_format=torch.channels_last)

pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=True)

# Warm Up
prompt = "a photo of a cat holding a sign that says hello world"
for _ in range(3):
    _ = pipe(prompt=prompt, generator=torch.manual_seed(1))

# Run Inference
image = pipe(prompt=prompt, generator=torch.manual_seed(1)).images[0]
image.save("sd3_hello_world.png")
```

完全なスクリプトは[こちら](https://gist.github.com/sayakpaul/508d89d7aad4f454900813da5d42ca97)からご確認いただけます。

## 量子化

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

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

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SD3Transformer2DModel, StableDiffusion3Pipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    subfolder="text_encoder_3",
    quantization_config=quant_config,
    dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SD3Transformer2DModel.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt, num_inference_steps=28, guidance_scale=7.0).images[0]
image.save("sd3.png")
```

## T5テキストエンコーダーでの長いプロンプトの使用

デフォルトでは、T5 Text Encoder のプロンプトは最大シーケンス長 `256` を使用します。`max_sequence_length` を設定することで、受け入れるトークン数を減らすことも増やすこともできます。長いシーケンスは追加のリソースを必要とし、バッチ推論などの場合、生成時間が長くなる点にご注意ください。

```python
prompt = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. It features the distinctive, bulky body shape of a hippo. However, instead of the usual grey skin, the creature’s body resembles a golden-brown, crispy waffle fresh off the griddle. The skin is textured with the familiar grid pattern of a waffle, each square filled with a glistening sheen of syrup. The environment combines the natural habitat of a hippo with elements of a breakfast table setting, a river of warm, melted butter, with oversized utensils or plates peeking out from the lush, pancake-like foliage in the background, a towering pepper mill standing in for a tree.  As the sun rises in this fantastical world, it casts a warm, buttery glow over the scene. The creature, content in its butter river, lets out a yawn. Nearby, a flock of birds take flight"

image = pipe(
    prompt=prompt,
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=4.5,
    max_sequence_length=512,
).images[0]
```

### T5 Text Encoder に別のプロンプトを送信する

CLIP Text Encoders と T5 Text Encoder に異なるプロンプトを送信することで、CLIP Text Encoders によるプロンプトの切り詰めを防止し、生成の品質を向上させることができます。

> [!TIP]
> CLIP Text Encoders を使用したプロンプトは、依然として 77 トークンの上限で切り詰められます。

```python
prompt = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. A river of warm, melted butter, pancake-like foliage in the background, a towering pepper mill standing in for a tree."

prompt_3 = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. It features the distinctive, bulky body shape of a hippo. However, instead of the usual grey skin, the creature’s body resembles a golden-brown, crispy waffle fresh off the griddle. The skin is textured with the familiar grid pattern of a waffle, each square filled with a glistening sheen of syrup. The environment combines the natural habitat of a hippo with elements of a breakfast table setting, a river of warm, melted butter, with oversized utensils or plates peeking out from the lush, pancake-like foliage in the background, a towering pepper mill standing in for a tree.  As the sun rises in this fantastical world, it casts a warm, buttery glow over the scene. The creature, content in its butter river, lets out a yawn. Nearby, a flock of birds take flight"

image = pipe(
    prompt=prompt,
    prompt_3=prompt_3,
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=4.5,
    max_sequence_length=512,
).images[0]
```

## Stable Diffusion 3用のTiny AutoEncoder

Stable Diffusion 3 の VAE を蒸留した小型版である Tiny AutoEncoder for Stable Diffusion (TAESD3) は、[Ollin Boer Bohan](https://github.com/madebyollin/taesd) によって開発され、[StableDiffusion3Pipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/stable_diffusion/stable_diffusion_3#diffusers.StableDiffusion3Pipeline) の潜在変数をほぼ瞬時にデコードできます。

Stable Diffusion 3 と一緒に使用するには:

```python
import torch
from diffusers import StableDiffusion3Pipeline, AutoencoderTiny

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16
)
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd3", dtype=torch.float16)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "slice of delicious New York-style berry cheesecake"
image = pipe(prompt, num_inference_steps=25).images[0]
image.save("cheesecake.png")
```

## `from_single_file` を使用して元のチェックポイントをロードする

`SD3Transformer2DModel`および`StableDiffusion3Pipeline`クラスは、`from_single_file`メソッドを通じて元のチェックポイントの読み込みをサポートしています。このメソッドを使用すると、モデルの学習に使用された元のチェックポイントファイルを読み込むことができます。

## `SD3Transformer2DModel` の元のチェックポイントをロードします

```python
from diffusers import SD3Transformer2DModel

model = SD3Transformer2DModel.from_single_file("https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium.safetensors")
```

## `StableDiffusion3Pipeline`の単一チェックポイントを読み込む

### T5なしで単一ファイルのチェックポイントをロードする

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium_incl_clips.safetensors",
    dtype=torch.float16,
    text_encoder_3=None
)
pipe.enable_model_cpu_offload()

image = pipe("a picture of a cat holding a sign that says hello world").images[0]
image.save('sd3-single-file.png')
```

### T5で単一ファイルのチェックポイントを読み込む

> [!TIP]
> 次の例では、PyTorch 2.3 以降が必要となる 8 ビット浮動小数点形式で保存されたチェックポイントをロードします。

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium_incl_clips_t5xxlfp8.safetensors",
    dtype=torch.float16,
)
pipe.enable_model_cpu_offload()

image = pipe("a picture of a cat holding a sign that says hello world").images[0]
image.save('sd3-single-file-t5-fp8.png')
```

### Stable Diffusion 3.5 Transformer モデルの単一ファイルチェックポイントを読み込む

```python
import torch
from diffusers import SD3Transformer2DModel, StableDiffusion3Pipeline

transformer = SD3Transformer2DModel.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3.5-large-turbo/blob/main/sd3.5_large.safetensors",
    dtype=torch.bfloat16,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    transformer=transformer,
    dtype=torch.bfloat16,
)
pipe.enable_model_cpu_offload()
image = pipe("a cat holding a sign that says hello world").images[0]
image.save("sd35.png")
```

## StableDiffusion3Pipeline[[diffusers.StableDiffusion3Pipeline]]

#### diffusers.StableDiffusion3Pipeline[[diffusers.StableDiffusion3Pipeline]]

```python
diffusers.StableDiffusion3Pipeline(transformer: SD3Transformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, text_encoder_2: CLIPTextModelWithProjection, tokenizer_2: CLIPTokenizer, text_encoder_3: T5EncoderModel, tokenizer_3: T5Tokenizer, image_encoder: SiglipVisionModel = None, feature_extractor: SiglipImageProcessorPil = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L148)

**パラメータ:**

transformer ([SD3Transformer2DModel](/docs/diffusers/v0.43.0/ja/api/models/sd3_transformer2d#diffusers.SD3Transformer2DModel)) : エンコードされた画像の潜在変数をデノイズするための、条件付き Transformer (MMDiT) アーキテクチャ。

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

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントで、`hidden_size` を次元とする対角行列で初期化された追加の投影層が付け加えられています。

text_encoder_2 (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection)、具体的には [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) バリアントです。

text_encoder_3 (`T5EncoderModel`) : 凍結されたテキストエンコーダー。Stable Diffusion 3 は [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)、具体的には [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントを使用しています。

tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。

tokenizer_2 (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) の2番目の Tokenizer。

tokenizer_3 (`T5TokenizerFast`) : クラス [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer) のトークナイザー。

image_encoder (`SiglipVisionModel`、*任意*) : IP Adapter用の事前学習済みビジョンモデル。

feature_extractor (`SiglipImageProcessor`、*任意*) : IP Adapter用の画像プロセッサ。

#### __call__[[diffusers.StableDiffusion3Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, prompt_3: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | 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 = 256, skip_guidance_layers: list[int] = None, skip_layer_guidance_scale: float = 2.8, skip_layer_guidance_stop: float = 0.2, skip_layer_guidance_start: float = 0.01, mu: float | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L772)

**パラメータ:**

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

prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。

prompt_3 (`str` または `list[str]`、*省略可能*) : `tokenizer_3` および `text_encoder_3` に送信するプロンプトです。未定義の場合、代わりに `prompt` が使用されます

height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。

width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅（ピクセル単位）。最適な結果を得るため、デフォルトでは 1024 に設定されています。

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

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

guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [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` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。

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

negative_prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信する、画像生成を誘導しないためのプロンプトです。未定義の場合、代わりに `negative_prompt` が使用されます

negative_prompt_3 (`str` または `list[str]`、*省略可能*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_3` および `text_encoder_3` に送信されます。定義されていない場合、代わりに `negative_prompt` が使用されます。

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

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。

latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数（latents）。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。

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

negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

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

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

ip_adapter_image (`PipelineImageInput`, *任意*) : IP Adapter で使用する任意の画像入力。

ip_adapter_image_embeds (`torch.Tensor`, *任意*) : IP-Adapter用の事前生成された画像埋め込み。形状が`(batch_size, num_images, emb_dim)`のテンソルである必要があります。`do_classifier_free_guidance`が`True`に設定されている場合、負の画像埋め込みを含む必要があります。指定されない場合、`ip_adapter_image`入力引数から埋め込みが計算されます。

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

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

joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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`、デフォルトは 256) : `prompt` に使用する最大シーケンス長。

skip_guidance_layers (`list[int]`, *optional*) : ガイダンス中にスキップするレイヤーを指定する整数のリストです。指定しない場合、すべてのレイヤーがガイダンスに使用されます。指定した場合、リストに指定されたレイヤーにのみガイダンスが適用されます。StabiltyAI が Stable Diffusion 3.5 Medium に対して推奨する値は [7, 8, 9] です。

skip_layer_guidance_scale (`int`, *optional*) : `skip_guidance_layers` で指定されたレイヤーに対するガイダンスのスケールです。ガイダンスは、`skip_guidance_layers` で指定されたレイヤーには `skip_layer_guidance_scale` のスケールで、それ以外のレイヤーには `1` のスケールで適用されます。

skip_layer_guidance_stop (`int`、*任意*) : `skip_guidance_layers` で指定されたレイヤーに対するガイダンスが停止するステップです。ガイダンスは、`skip_layer_guidance_stop` で指定された割合まで、`skip_guidance_layers` で指定されたレイヤーに適用されます。Stable Diffusion 3.5 Medium における StabilityAI による推奨値は 0.2 です。

skip_layer_guidance_start (`int`、*任意*) : `skip_guidance_layers` で指定されたレイヤーに対するガイダンスが開始されるステップです。`skip_guidance_layers` で指定されたレイヤーには、`skip_layer_guidance_start` で指定された割合からガイダンスが適用されます。Stable Diffusion 3.5 Medium における StabilityAI による推奨値は 0.01 です。

mu (`float`, *任意*) : `dynamic_shifting` に使用される `mu` の値。

**戻り値:** `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` または `tuple`

`return_dict` が True の場合は `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。

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

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

>>> pipe = StableDiffusion3Pipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt).images[0]
>>> image.save("sd3.png")
```

#### encode_image[[diffusers.StableDiffusion3Pipeline.encode_image]]

```python
encode_image(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], device: device)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L696)

**パラメータ:**

image (`PipelineImageInput`) : エンコード対象の入力画像。

device : (`torch.device`): Torch デバイス。

**戻り値:** `torch.Tensor`

エンコードされた画像の特徴表現。

事前学習済みの画像エンコーダーを使用して、指定された画像を特徴表現にエンコードします。

#### encode_prompt[[diffusers.StableDiffusion3Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str], prompt_3: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, clip_skip: int | None = None, max_sequence_length: int = 256, lora_scale: float | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L344)

**パラメータ:**

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

prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。

prompt_3 (`str` または `list[str]`、*省略可*) : `tokenizer_3` および `text_encoder_3` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。

device : (`torch.device`): torch デバイス

num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数

do_classifier_free_guidance (`bool`) : classifier free guidance を使用するかどうか

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

negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。

negative_prompt_3 (`str` または `list[str]`、*省略可*) : `tokenizer_3` および `text_encoder_3` に送信する、画像生成を誘導しないためのプロンプトです。定義されていない場合、すべての text-encoder で `negative_prompt` が使用されます。

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

negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

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

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

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。

#### prepare_ip_adapter_image_embeds[[diffusers.StableDiffusion3Pipeline.prepare_ip_adapter_image_embeds]]

```python
prepare_ip_adapter_image_embeds(ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L716)

**パラメータ:**

ip_adapter_image (`PipelineImageInput`, *任意*) : IP-Adapter用の特徴量抽出の対象となる入力画像。

ip_adapter_image_embeds (`torch.Tensor`, *任意*) : 事前計算された画像埋め込み。

device : (`torch.device`, *任意*): Torch デバイス。

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

do_classifier_free_guidance (`bool`、デフォルトは True) : classifier free guidance を使用するかどうか。

IP-Adapterで使用する画像エンベディングを準備します。

`ip_adapter_image` または `ip_adapter_image_embeds` のいずれかを渡す必要があります。

