stable-diffusion-image-generation について
このスキルは、HuggingFace Diffusersを使ったStable Diffusionによる画像生成と編集のガイドです。画像生成ワークフローを構築する開発者向けに、複数のモデル、条件付け手法、メモリ設定を扱います。
主な機能
- 01テキストから画像・画像から画像へのパイプライン
- 02インペインティングとアウトペインティング
- 03ControlNetによる空間条件付け
- 04LoRAアダプターの読み込み
- 05メモリ最適化オプション
活用シーン
- 01プロンプトからの画像生成
- 02既存画像のスタイル変換や強化
- 03画像のマスク領域の補完
- 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.mdcontrolnet.mdgeneration-parameters.mdtroubleshooting.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 | インペインティング |
スケジューラー
スケジューラーは、ノイズ除去のプロセスを制御します:
| スケジューラー | ステップ数 | 品質 | 用途 |
|---|---|---|---|
EulerDiscreteScheduler | 20-50 | 良好 | デフォルトの選択肢 |
EulerAncestralDiscreteScheduler | 20-50 | 良好 | より多様な結果 |
DPMSolverMultistepScheduler | 15-25 | 非常に良好 | 高速かつ高品質 |
DDIMScheduler | 50-100 | 良好 | 決定論的 |
LCMScheduler | 4-8 | 良好 | 非常に高速 |
UniPCMultistepScheduler | 15-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]
参考資料
- 高度な使用方法 - カスタムパイプライン、ファインチューニング、デプロイ
- トラブルシューティング - よくある問題と解決策
リソース
- ドキュメント: https://huggingface.co/docs/diffusers
- リポジトリ: https://github.com/huggingface/diffusers
- モデルハブ: https://huggingface.co/models?library=diffusers
- Discord: https://discord.gg/diffusers
エージェントの作業手順
- 環境を確認します。 GPU メモリ、モデルのチェックポイントとライセンス、フレームワークのバージョン、入力形式を確認します。
- 入力を明確にします。 データまたはユーザーに、形式、識別子、パラメーターを確認します。結果に影響する値は推測せず、質問します。
- まず小規模に実行します。 単一のサンプルを低解像度または短い長さで推論します。
- 上記の手順と参考情報を使用して、タスク全体を実行します。
- 結果を検証します。 出力を定性的に確認し、タスクの指標で評価します。生成コンテンツのライセンス制限も確認します。
- 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確定の事項を明記します。
| このような場合 | 対応方法 |
|---|---|
| 大きな入力でメモリ不足が発生する | 解像度またはシーケンス長を下げる、半精度を使用する、または入力をタイルに分割します。 |
| これらの手順に記載された関数、フラグ、エンドポイントがインストール済みのバージョンにない | インストール済みバージョンのドキュメント(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+ のポリシーをファインチューニングし、評価します。
コメント
Markdown 対応