Diffusers documentation

テキストから画像へ

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

テキストから画像へ

拡散モデルを思い浮かべると、まず頭に浮かぶのがテキストから画像を生成する処理です。テキストから画像を生成する処理では、テキストの説明(例: “Astronaut in a jungle, cold color palette, muted colors, detailed, 8k”)から画像を生成します。このテキストの説明はプロンプトとも呼ばれます。

非常に大まかに言えば、拡散モデルはプロンプトとランダムな初期ノイズを受け取り、ノイズを反復的に除去することで画像を構築します。デノイジングプロセスはプロンプトによって導かれ、所定の数だけタイムステップが経過してデノイジングプロセスが終了すると、画像の表現が画像としてデコードされます。

Stable Diffusion はどのように動作しますか?のブログ記事を読み、潜在拡散モデルの動作について詳しく学んでください。

🤗 Diffusers では、プロンプトから画像を生成するには2つのステップで実行できます。

  1. AutoPipelineForText2Image クラスにチェックポイントをロードします。このクラスは、チェックポイントに基づいて使用する適切なパイプラインクラスを自動的に検出します。
from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
  1. パイプラインにプロンプトを渡して画像を生成します:
image = pipeline(
	"stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
).images[0]
image

人気モデル

最も一般的なテキストから画像を生成するモデルは、Stable Diffusion v1.5、Stable Diffusion XL (SDXL)、Kandinsky 2.2です。また、テキストから画像を生成するモデルと組み合わせて使用できる ControlNet モデルやアダプターもあり、これらを用いることで画像生成をより直接的に制御できます。各モデルはアーキテクチャや学習プロセスが異なるため、生成される結果にはわずかな違いがありますが、どのモデルを選んでも、その使い方はほぼ同じです。ここでは、各モデルに同じプロンプトを与えて、その結果を比較してみましょう。

Stable Diffusion v1.5

Stable Diffusion v1.5 は Stable Diffusion v1-4 から初期化された潜在拡散モデルであり、LAION-Aesthetics V2 データセットの 512x512 画像に対して 595K ステップでファインチューニングされています。このモデルは次のように使用できます。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

Stable Diffusion XL

SDXLは、従来のStable Diffusionモデルよりもはるかに大規模なバージョンであり、2段階のモデル処理により画像にさらに多くの詳細を追加します。また、被写体を中央に配置した高品質な画像を生成するために、いくつかの追加のマイクロコンディショニングが含まれています。使用方法の詳細については、より包括的なSDXLガイドをご覧ください。一般的に、SDXLは次のように使用できます。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

Kandinsky 2.2

Kandinskyモデルは、Stable Diffusionモデルとは少し異なり、拡散モデル内でテキストと画像をより適切に整合させるために使用される埋め込みを生成する画像事前モデルも使用します。

Kandinsky 2.2 を最も簡単に使用する方法は以下の通りです。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
image

ControlNet

ControlNetモデルは、Stable Diffusion v1.5などのテキストから画像を生成するモデルの上にファインチューニングされた、補助的なモデルまたはアダプターです。ControlNetモデルをテキストから画像を生成するモデルと組み合わせて使用することで、画像の生成方法に対してより明示的な制御を行うための多様な選択肢が得られます。ControlNetを使用すると、モデルに追加の条件付け入力画像を渡すことができます。例えば、人間のポーズ(通常は、複数のキーポイントが骨格として接続された形で表されます)の画像を条件付け入力として提供すると、モデルはその画像のポーズに従った画像を生成します。その他の条件付け入力やその使用方法については、より詳細なControlNetガイドを参照してください。

この例では、ヒューマンポーズ推定画像でControlNetを条件付けます。ヒューマンポーズ推定で事前学習されたControlNetモデルを読み込みます:

from diffusers import ControlNetModel, AutoPipelineForText2Image
from diffusers.utils import load_image
import torch

controlnet = ControlNetModel.from_pretrained(
	"lllyasviel/control_v11p_sd15_openpose", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
pose_image = load_image("https://huggingface.co/lllyasviel/control_v11p_sd15_openpose/resolve/main/images/control.png")

controlnet を AutoPipelineForText2Image に渡し、プロンプトとポーズ推定画像を指定します:

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=pose_image, generator=generator).images[0]
image
Stable Diffusion v1.5
Stable Diffusion XL
Kandinsky 2.2
ControlNet(ポーズ条件付け)

パイプラインのパラメータを設定

パイプラインでは、画像の生成方法に影響を与える複数のパラメータを設定できます。出力サイズの変更、画像の品質を向上させるためのネガティブプロンプトの指定などが可能です。このセクションでは、これらのパラメータの使用方法について詳しく説明します。

高さおよび幅

height と width パラメータは、生成される画像の高さと幅(ピクセル単位)を制御します。デフォルトでは、Stable Diffusion v1.5 モデルは 512x512 の画像を出力しますが、8 の倍数であれば任意のサイズに変更できます。例えば、長方形の画像を作成するには:

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", height=768, width=512
).images[0]
image

他のモデルでは、トレーニングデータセットの画像サイズに応じて、デフォルトの画像サイズが異なる場合があります。例えば、SDXLのデフォルト画像サイズは1024x1024であり、heightとwidthの値を小さくすると、画像の品質が低下する可能性があります。まず、モデルのAPIリファレンスを確認してください。

ガイダンススケール

guidance_scale パラメータは、プロンプトが画像生成に与える影響の度合いを決定します。値を下げると、モデルはより自由な発想で、プロンプトとの関連が緩やかな画像を生成するようになります。一方、guidance_scale の値を上げると、モデルはプロンプトに忠実に従うようになり、この値が高すぎると、生成された画像にアーティファクト(不自然な部分)が現れる可能性があります。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", guidance_scale=3.5
).images[0]
image
guidance_scale = 2.5
guidance_scale = 7.5
guidance_scale = 10.5

ネガティブプロンプト

プロンプトが生成を導くように、ネガティブプロンプトは、モデルに生成してほしくない要素からモデルを遠ざける役割を果たします。これは、「低解像度」や「詳細の欠如」のような低品質な画像の特徴を除去することで、画像全体の品質を向上させるために一般的に使用されます。また、ネガティブプロンプトを用いることで、画像の内容やスタイルを削除・変更することも可能です。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
	negative_prompt="ugly, deformed, disfigured, poor details, bad anatomy",
).images[0]
image
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"
negative_prompt = "astronaut"

ジェネレーター

torch.Generator オブジェクトは、手動でシードを設定することにより、パイプラインにおける再現性を確保できます。Generator を使用して画像のバッチを生成し、決定論的な生成による画像品質の向上 ガイドに詳述されているように、シードから生成された画像を反復的に改善できます。

以下に示すように、シードとGeneratorを設定できます。Generatorを使用して画像を生成すると、毎回ランダムに新しい画像が生成されるのではなく、同じ結果が返されるようになります。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
generator = torch.Generator(device="cuda").manual_seed(30)
image = pipeline(
	"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
	generator=generator,
).images[0]
image

画像生成の制御

パイプラインのパラメータを設定する以外に、プロンプトの重み付けやControlNetモデルなど、画像の生成方法に対してより細かな制御を行う方法はいくつかあります。

プロンプトの重み付け

プロンプト重み付けは、プロンプト内の概念の重要度を上げ下げすることで、画像内の特定の機能を強調したり最小化したりするための技術です。重み付きプロンプト埋め込みの生成には、Compelライブラリの使用を推奨します。

Prompt weightingガイドで、プロンプト埋め込みの作成方法について学習してください。この例では、パイプライン内でプロンプト埋め込みを使用する方法に焦点を当てています。

埋め込みを作成した後、パイプラインの prompt_embeds パラメータ(ネガティブプロンプトを使用している場合は negative_prompt_embeds も)に渡すことができます。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
	"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
image = pipeline(
	prompt_embeds=prompt_embeds, # generated from Compel
	negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
).images[0]

ControlNet

ControlNetのセクションで見たように、これらのモデルは、追加の条件付け画像入力を組み込むことで、より柔軟かつ正確な画像生成を実現します。各ControlNetモデルは、特定のタイプの条件付け画像に対して事前学習されており、それに類似した新しい画像を生成します。例えば、深度マップで事前学習されたControlNetモデルに深度マップを条件付け入力として与えると、その空間情報を保持した画像を生成します。これは、プロンプトで深度情報を指定するよりも迅速かつ簡単です。Multi-ControlNetを使用すれば、複数の条件付け入力を組み合わせることも可能です。

使用できる条件付け入力には多くの種類があり、🤗 Diffusers は Stable Diffusion および SDXL モデルの ControlNet をサポートしています。これらのモデルの使用方法については、より包括的な ControlNet ガイドをご覧ください。

最適化

Diffusionモデルは規模が大きく、画像のノイズ除去を反復的に実行する性質上、計算コストが高く、計算負荷も大きくなります。しかし、それらのモデルを利用するために、高性能なGPUや多数のGPUへのアクセスが必須であるわけではありません。消費者向けリソースや無料ティアのリソース上でDiffusionモデルを実行するための最適化技術は多数存在します。例えば、モデルの重みを半精度で読み込むことでGPUメモリを節約し速度を向上させたり、モデル全体をGPUにオフロードしてさらにメモリを節約したりすることが可能です。

PyTorch 2.0 では、scaled dot product attention というよりメモリ効率の高いアテンション機構もサポートされており、PyTorch 2.0 を使用している場合は自動的に有効になります。これを torch.compile と組み合わせることで、コードをさらに高速化できます。

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16").to("cuda")  # or "mps", "xpu", "cpu"
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)

メモリを節約し、推論を高速化するためにコードを最適化する方法に関する詳細なヒントについては、Accelerate inferenceガイドとReduce memory usageガイドをお読みください。

Update on GitHub