Diffusers documentation

Stable Diffusion 3

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Stable Diffusion 3

LoRA MPS

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 で紹介されました。

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

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

使用例

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

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

hf auth login

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

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つあります:

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 は通常、良いバランスを保ち、モデルがテキストプロンプトと画像プロンプトの両方を同等に考慮することを保証します。

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の例

IP-Adapter の仕組みについて詳しく知るには、IP-Adapter をご覧ください。

SD3のメモリ最適化

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

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

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

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のメモリ要件を大幅に削減できます。

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ライブラリをインストールしてください。

pip install bitsandbytes

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

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")

エンドツーエンドのスクリプトはこちらで確認できます。

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

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

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

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")

完全なスクリプトはこちらからご確認いただけます。

量子化

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

サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択について詳しく知るには、Quantizationの概要を参照してください。以下の例では、bitsandbytesを使用して量子化されたStableDiffusion3Pipelineを読み込んで推論を実行する方法を示しています。

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 を設定することで、受け入れるトークン数を減らすことも増やすこともできます。長いシーケンスは追加のリソースを必要とし、バッチ推論などの場合、生成時間が長くなる点にご注意ください。

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 によるプロンプトの切り詰めを防止し、生成の品質を向上させることができます。

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

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 によって開発され、StableDiffusion3Pipeline の潜在変数(latents)をほぼ瞬時にデコードできます。

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

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の元のチェックポイントをロードします

from diffusers import SD3Transformer2DModel

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

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

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

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で単一ファイルのチェックポイントを読み込む

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

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 モデルの単一ファイルチェックポイントを読み込む

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

< >

( transformer: SD3Transformer2DModelscheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertext_encoder_2: CLIPTextModelWithProjectiontokenizer_2: CLIPTokenizertext_encoder_3: T5EncoderModeltokenizer_3: T5Tokenizerimage_encoder: SiglipVisionModel = Nonefeature_extractor: SiglipImageProcessorPil = None )

パラメータ

  • transformer (SD3Transformer2DModel) — エンコードされた画像潜在変数からノイズを除去するための、条件付き Transformer (MMDiT) アーキテクチャ。
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。
  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • text_encoder (CLIPTextModelWithProjection) — CLIP、 具体的には clip-vit-large-patch14 バリアントで、 hidden_size を次元とする対角行列で初期化された追加の投影層を備えています。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP、 具体的には laion/CLIP-ViT-bigG-14-laion2B-39B-b160k バリアントです。
  • text_encoder_3 (T5EncoderModel) — 凍結されたテキストエンコーダーです。Stable Diffusion 3 は T5、具体的には t5-v1_1-xxl バリアントを使用しています。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • tokenizer_2 (CLIPTokenizer) — クラス CLIPTokenizer の2番目の Tokenizer。
  • tokenizer_3 (T5TokenizerFast) — クラス T5Tokenizer のトークナイザー。
  • image_encoder (SiglipVisionModel、任意) — IP Adapter用の事前学習済みビジョンモデル。
  • feature_extractor (SiglipImageProcessor、任意) — IP Adapter用の画像プロセッサ。

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_3: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 256skip_guidance_layers: list[int] = Noneskip_layer_guidance_scale: float = 2.8skip_layer_guidance_stop: float = 0.2skip_layer_guidance_start: float = 0.01mu: float | None = None ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple

パラメータ

  • 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 で定義されているガイダンススケールです。guidance_scale は、Imagen Paper の数式 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 ジェネレーター1つまたはリスト。
  • latents (torch.FloatTensor, 任意) — 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイジーな潜在変数です。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム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: PIL.Image.Image または np.array から選択します。
  • return_dict (bool、省略可、デフォルトは True) — プレーンなタプルではなく ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput を返すかどうか。
  • joint_attention_kwargs (dict、省略可) — 指定された場合、diffusers.models.attention_processor で定義されている self.processor 配下の AttentionProcessor に渡される kwargs の辞書です。
  • clip_skip (int, 任意) — プロンプト埋め込みを計算する際に、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], 任意) — guidance 時にスキップするレイヤーを指定する整数のリストです。指定しない場合、すべてのレイヤーが guidance に使用されます。指定した場合、リストに指定されたレイヤーにのみ guidance が適用されます。StabiltyAI が Stable Diffusion 3.5 Medium に対して推奨する値は [7, 8, 9] です。
  • skip_layer_guidance_scale (int、任意) — skip_guidance_layers で指定されたレイヤーに対するガイダンスのスケールです。ガイダンスは、skip_guidance_layers で指定されたレイヤーに skip_layer_guidance_scale のスケールで適用されます。その他のレイヤーには、1 のスケールで適用されます。
  • skip_layer_guidance_stop (int, 任意) — skip_guidance_layers で指定されたレイヤーに対するガイダンスが停止するステップです。ガイダンスは、skip_guidance_layers で指定されたレイヤーに対して、skip_layer_guidance_stop で指定された割合まで適用されます。StabiltyAI が Stable Diffusion 3.5 Medium に対して推奨する値は 0.2 です。
  • skip_layer_guidance_start (int, 任意) — skip_guidance_layers で指定されたレイヤーへのガイダンスが開始されるステップです。ガイダンスは、skip_layer_guidance_start で指定された割合から、skip_guidance_layers で指定されたレイヤーに適用されます。StabilityAI が Stable Diffusion 3.5 Medium に対して推奨する値は 0.01 です。
  • mu (float, 任意) — dynamic_shifting に使用される mu の値。

戻り値

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput または tuple

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

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

例:

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

< >

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

パラメータ

  • image (PipelineImageInput) — エンコード対象の入力画像。
  • device — (torch.device): Torch のデバイス。

戻り値

torch.Tensor

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

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

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str]prompt_3: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneclip_skip: int | None = Nonemax_sequence_length: int = 256lora_scale: float | None = None )

パラメータ

  • 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 に送信するプロンプトです。定義されていない場合、すべてのテキストエンコーダーで prompt が使用されます。
  • device — (torch.device): torch デバイス
  • num_images_per_prompt (int) — 1つのプロンプトに対して生成する画像の数
  • 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, 任意) — プロンプト埋め込みを計算する際に、CLIP からスキップするレイヤー数です。値が 1 の場合、最終レイヤーの直前のレイヤーの出力がプロンプト埋め込みの計算に使用されます。
  • lora_scale (float, 省略可) — LoRA レイヤーが読み込まれている場合、テキストエンコーダーのすべての LoRA レイヤーに適用される LoRA スケールです。

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] = Noneip_adapter_image_embeds: typing.Optional[torch.Tensor] = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = True )

パラメータ

  • 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 のいずれかを渡す必要があります。

Update on GitHub