mcpField
S
stable-diffusion-image-generation

stable-diffusion-image-generation

github.com/kalarislabsその他7342 回インストール3 日前に更新
リポジトリ

stable-diffusion-image-generation について

このスキルは、HuggingFace Diffusersを使ったStable Diffusionによる画像生成と編集のガイドです。画像生成ワークフローを構築する開発者向けに、複数のモデル、条件付け手法、メモリ設定を扱います。

主な機能

  1. 01テキストから画像・画像から画像へのパイプライン
  2. 02インペインティングとアウトペインティング
  3. 03ControlNetによる空間条件付け
  4. 04LoRAアダプターの読み込み
  5. 05メモリ最適化オプション

活用シーン

  1. 01プロンプトからの画像生成
  2. 02既存画像のスタイル変換や強化
  3. 03画像のマスク領域の補完
  4. 04LoRAスタイルによる生成結果の調整

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill stable-diffusion-image-generation

インストール後、Claude Code で/stable-diffusion-image-generationを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
advanced-usage.md
controlnet.md
generation-parameters.md
troubleshooting.md

詳細

Stable Diffusion による画像生成

HuggingFace Diffusers ライブラリを使用した Stable Diffusion による画像生成の包括的なガイドです。

Stable Diffusion を使う場面

次のような場合に Stable Diffusion を使用します:

  • テキストの説明から画像を生成する
  • 画像から画像への変換(スタイル転送、画質向上)を行う
  • インペインティング(マスクした領域を埋める)を行う
  • アウトペインティング(画像の境界を越えて拡張する)を行う
  • 既存の画像のバリエーションを作成する
  • カスタムの画像生成ワークフローを構築する

主な機能:

  • テキストから画像へ:自然言語のプロンプトから画像を生成します
  • 画像から画像へ:テキストのガイダンスを使って既存の画像を変換します
  • インペインティング:コンテキストを考慮した内容でマスク領域を埋めます
  • ControlNet:空間的な条件付け(エッジ、ポーズ、深度)を追加します
  • LoRA のサポート:効率的なファインチューニングとスタイル適応に対応します
  • 複数のモデル:SD 1.5、SDXL、SD 3.0、Flux に対応します

代わりに次の選択肢を使用します:

  • DALL-E 3:GPU を使わず API ベースで生成する場合
  • Midjourney:芸術的でスタイル化された出力を得る場合
  • Imagen:Google Cloud と統合する場合
  • Leonardo.ai:ウェブベースのクリエイティブなワークフローを構築する場合

クイックスタート

インストール
pip install diffusers transformers accelerate torch
pip install xformers  # Optional: memory-efficient attention
基本的なテキストから画像への生成
from diffusers import DiffusionPipeline
import torch

# Load pipeline (auto-detects model type)
pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe.to("cuda")

# Generate image
image = pipe(
    "A serene mountain landscape at sunset, highly detailed",
    num_inference_steps=50,
    guidance_scale=7.5
).images[0]

image.save("output.png")
SDXL の使用(より高品質)
from diffusers import AutoPipelineForText2Image
import torch

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# Enable memory optimization
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="A futuristic city with flying cars, cinematic lighting",
    height=1024,
    width=1024,
    num_inference_steps=30
).images[0]

アーキテクチャの概要

3 つの柱からなる設計

Diffusers は、次の 3 つの主要コンポーネントを中心に構築されています:

Pipeline (orchestration)
├── Model (neural networks)
│   ├── UNet / Transformer (noise prediction)
│   ├── VAE (latent encoding/decoding)
│   └── Text Encoder (CLIP/T5)
└── Scheduler (denoising algorithm)
パイプラインの推論フロー
Text Prompt → Text Encoder → Text Embeddings
                                    ↓
Random Noise → [Denoising Loop] ← Scheduler
                      ↓
               Predicted Noise
                      ↓
              VAE Decoder → Final Image

基本概念

パイプライン

パイプラインは、ワークフロー全体を統括します:

パイプライン用途
StableDiffusionPipelineテキストから画像への生成(SD 1.x/2.x)
StableDiffusionXLPipelineテキストから画像への生成(SDXL)
StableDiffusion3Pipelineテキストから画像への生成(SD 3.0)
FluxPipelineテキストから画像への生成(Flux モデル)
StableDiffusionImg2ImgPipeline画像から画像への変換
StableDiffusionInpaintPipelineインペインティング
スケジューラー

スケジューラーは、ノイズ除去のプロセスを制御します:

スケジューラーステップ数品質用途
EulerDiscreteScheduler20-50良好デフォルトの選択肢
EulerAncestralDiscreteScheduler20-50良好より多様な結果
DPMSolverMultistepScheduler15-25非常に良好高速かつ高品質
DDIMScheduler50-100良好決定論的
LCMScheduler4-8良好非常に高速
UniPCMultistepScheduler15-25非常に良好高速な収束
スケジューラーの切り替え
from diffusers import DPMSolverMultistepScheduler

# Swap for faster generation
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
    pipe.scheduler.config
)

# Now generate with fewer steps
image = pipe(prompt, num_inference_steps=20).images[0]

生成パラメーター

詳細、コード例、パラメーター表については、references/generation-parameters.md を参照してください。このステップを行う場合に読みます。

画像から画像への変換

テキストのガイダンスを使って既存の画像を変換します:

from diffusers import AutoPipelineForImage2Image
from PIL import Image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

init_image = Image.open("input.jpg").resize((512, 512))

image = pipe(
    prompt="A watercolor painting of the scene",
    image=init_image,
    strength=0.75,  # How much to transform (0-1)
    num_inference_steps=50
).images[0]

インペインティング

マスク領域を埋めます:

from diffusers import AutoPipelineForInpainting
from PIL import Image

pipe = AutoPipelineForInpainting.from_pretrained(
    "runwayml/stable-diffusion-inpainting",
    torch_dtype=torch.float16
).to("cuda")

image = Image.open("photo.jpg")
mask = Image.open("mask.png")  # White = inpaint region

result = pipe(
    prompt="A red car parked on the street",
    image=image,
    mask_image=mask,
    num_inference_steps=50
).images[0]

ControlNet

詳細、コード例、パラメーター表については、references/controlnet.md を参照してください。このステップを行う場合に読みます。

LoRA アダプター

ファインチューニング済みのスタイルアダプターを読み込みます:

from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

# Load LoRA weights
pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")

# Generate with LoRA style
image = pipe("A portrait in the trained style").images[0]

# Adjust LoRA strength
pipe.fuse_lora(lora_scale=0.8)

# Unload LoRA
pipe.unload_lora_weights()
複数の LoRA
# Load multiple LoRAs
pipe.load_lora_weights("lora1", adapter_name="style")
pipe.load_lora_weights("lora2", adapter_name="character")

# Set weights for each
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])

image = pipe("A portrait").images[0]

メモリーの最適化

CPU オフロードを有効にする
# Model CPU offload - moves models to CPU when not in use
pipe.enable_model_cpu_offload()

# Sequential CPU offload - more aggressive, slower
pipe.enable_sequential_cpu_offload()
Attention slicing
# Reduce memory by computing attention in chunks
pipe.enable_attention_slicing()

# Or specific chunk size
pipe.enable_attention_slicing("max")
xFormers によるメモリー効率の高い attention
# Requires xformers package
pipe.enable_xformers_memory_efficient_attention()
大きな画像向けの VAE slicing
# Decode latents in tiles for large images
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()

モデルのバリエーション

異なる精度で読み込む
# FP16 (recommended for GPU)
pipe = DiffusionPipeline.from_pretrained(
    "model-id",
    torch_dtype=torch.float16,
    variant="fp16"
)

# BF16 (better precision, requires Ampere+ GPU)
pipe = DiffusionPipeline.from_pretrained(
    "model-id",
    torch_dtype=torch.bfloat16
)
特定のコンポーネントを読み込む
from diffusers import UNet2DConditionModel, AutoencoderKL

# Load custom VAE
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse")

# Use with pipeline
pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    vae=vae,
    torch_dtype=torch.float16
)

バッチ生成

複数の画像を効率的に生成します:

# Multiple prompts
prompts = [
    "A cat playing piano",
    "A dog reading a book",
    "A bird painting a picture"
]

images = pipe(prompts, num_inference_steps=30).images

# Multiple images per prompt
images = pipe(
    "A beautiful sunset",
    num_images_per_prompt=4,
    num_inference_steps=30
).images

一般的なワークフロー

ワークフロー 1:高品質な生成
from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
import torch

# 1. Load SDXL with optimizations
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.enable_model_cpu_offload()

# 2. Generate with quality settings
image = pipe(
    prompt="A majestic lion in the savanna, golden hour lighting, 8k, detailed fur",
    negative_prompt="blurry, low quality, cartoon, anime, sketch",
    num_inference_steps=30,
    guidance_scale=7.5,
    height=1024,
    width=1024
).images[0]
ワークフロー 2:高速なプロトタイピング
from diffusers import AutoPipelineForText2Image, LCMScheduler
import torch

# Use LCM for 4-8 step generation
pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16
).to("cuda")

# Load LCM LoRA for fast generation
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.fuse_lora()

# Generate in ~1 second
image = pipe(
    "A beautiful landscape",
    num_inference_steps=4,
    guidance_scale=1.0
).images[0]

よくある問題

CUDA のメモリー不足:

# Enable memory optimizations
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing()
pipe.enable_vae_slicing()

# Or use lower precision
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)

黒い画像/ノイズ画像:

# Check VAE configuration
# Use safety checker bypass if needed
pipe.safety_checker = None

# Ensure proper dtype consistency
pipe = pipe.to(dtype=torch.float16)

生成が遅い:

# Use faster scheduler
from diffusers import DPMSolverMultistepScheduler
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)

# Reduce steps
image = pipe(prompt, num_inference_steps=20).images[0]

参考資料

リソース

エージェントの作業手順

  1. 環境を確認します。 GPU メモリ、モデルのチェックポイントとライセンス、フレームワークのバージョン、入力形式を確認します。
  2. 入力を明確にします。 データまたはユーザーに、形式、識別子、パラメーターを確認します。結果に影響する値は推測せず、質問します。
  3. まず小規模に実行します。 単一のサンプルを低解像度または短い長さで推論します。
  4. 上記の手順と参考情報を使用して、タスク全体を実行します。
  5. 結果を検証します。 出力を定性的に確認し、タスクの指標で評価します。生成コンテンツのライセンス制限も確認します。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確定の事項を明記します。
このような場合対応方法
大きな入力でメモリ不足が発生する解像度またはシーケンス長を下げる、半精度を使用する、または入力をタイルに分割します。
これらの手順に記載された関数、フラグ、エンドポイントがインストール済みのバージョンにないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認し、適宜対応してユーザーに伝えます。API をでっち上げてはいけません。
必須の入力、識別子、パラメーターが曖昧であるユーザーに質問するか、実行前に前提を明示します。

誠実性に関するルール

  • 結果、パラメーター、識別子、引用、統計を決して捏造しません。実行または検証できないことは、明確に伝えます。
  • 商用利用または公開利用の前に、モデルとデータセットのライセンスを確認します。
  • ここに記載されたバージョン固有の詳細は古くなっている可能性があるものとして扱い、インストール済みバージョンの公式ドキュメントで確認します。
  • 費用が発生する操作、共有 GPU やクラウドのクォータを消費する操作、個人データや患者データに触れる操作、元に戻せない操作を行う前に、ユーザーに確認します。

関連スキル

  • peft-fine-tuning:Hugging Face PEFT を使い、LoRA、QLoRA、IA3、AdaLoRA、prefix tuning、prompt tuning によって LLM をファインチューニングします。パラメーターの 1% 未満を調…
  • blip-2-vision-language:Salesforce BLIP-2(凍結された画像エンコーダーと OPT や FlanT5 などの LLM をつなぐ Q-Former)を HuggingFace Trans…
  • fine-tuning-openvla-oft:連続アクションヘッド、LoRA による適応、a…を用いて、ロボットのアクション生成向けに OpenVLA-OFT と OpenVLA-OFT+ のポリシーをファインチューニングし、評価します。

コメント