关于 stable-diffusion-image-generation
这项技能介绍如何通过 HuggingFace Diffusers 使用 Stable Diffusion 生成和编辑图像,面向构建图像生成工作流的开发者,涵盖多种模型、条件控制方法及内存选项。
主要功能
- 01文生图与图生图管线
- 02图像修补与扩展工作流
- 03ControlNet 空间条件控制
- 04加载 LoRA 适配器
- 05内存优化选项
适用场景
- 01根据提示词生成图像
- 02为现有图像转换风格或增强效果
- 03填充图像的遮罩区域
- 04通过 LoRA 风格调整生成结果
安装
复制下面的命令,在终端中运行。
$
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:通过 API 生成图像,无需 GPU
- Midjourney:生成艺术化、风格化的图像
- Imagen:集成 Google Cloud
- Leonardo.ai:基于 Web 的创意工作流
快速开始
安装
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]
架构概览
三大核心组件
Diffusers 围绕三个核心组件构建:
Pipeline (orchestration)
├── Model (neural networks)
│ ├── UNet / Transformer (noise prediction)
│ ├── VAE (latent encoding/decoding)
│ └── Text Encoder (CLIP/T5)
└── Scheduler (denoising algorithm)
Pipeline 推理流程
Text Prompt → Text Encoder → Text Embeddings
↓
Random Noise → [Denoising Loop] ← Scheduler
↓
Predicted Noise
↓
VAE Decoder → Final Image
核心概念
Pipeline
Pipeline 协调整个工作流:
| Pipeline | 用途 |
|---|---|
StableDiffusionPipeline | 文生图(SD 1.x/2.x) |
StableDiffusionXLPipeline | 文生图(SDXL) |
StableDiffusion3Pipeline | 文生图(SD 3.0) |
FluxPipeline | 文生图(Flux 模型) |
StableDiffusionImg2ImgPipeline | 图生图 |
StableDiffusionInpaintPipeline | 图像修复 |
Scheduler
Scheduler 控制去噪过程:
| Scheduler | 步数 | 质量 | 使用场景 |
|---|---|---|---|
EulerDiscreteScheduler | 20-50 | 良好 | 默认选择 |
EulerAncestralDiscreteScheduler | 20-50 | 良好 | 更多变化 |
DPMSolverMultistepScheduler | 15-25 | 极佳 | 快速且高质量 |
DDIMScheduler | 50-100 | 良好 | 确定性生成 |
LCMScheduler | 4-8 | 良好 | 速度极快 |
UniPCMultistepScheduler | 15-25 | 极佳 | 快速收敛 |
更换 Scheduler
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()
注意力切片
# Reduce memory by computing attention in chunks
pipe.enable_attention_slicing()
# Or specific chunk size
pipe.enable_attention_slicing("max")
xFormers 高效内存注意力
# Requires xformers package
pipe.enable_xformers_memory_efficient_attention()
大尺寸图像的 VAE 切片
# 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
Agent 操作流程
- 检查环境。 确认 GPU 内存、模型检查点及许可证、框架版本和输入格式。
- 明确输入。 根据数据或用户提供的信息确认格式、标识符和参数。任何会影响结果的值都应先询问,不要猜测。
- 先运行小规模版本。 先对单个样本以低分辨率或较短长度运行推理。
- 使用上述说明和参考资料 执行完整任务。
- 验证结果。 通过定性检查和任务指标检查输出;确认生成内容的许可证限制。
- 汇报。 说明运行了什么(版本、命令、参数)、检查了什么,以及仍有哪些不确定之处。
| 如果发生以下情况 | 请执行以下操作 |
|---|---|
| 大型输入导致内存不足 | 降低分辨率或序列长度、使用半精度,或对输入进行分块。 |
| 这些说明中提到的函数、标志或端点在已安装版本中不存在 | 查阅已安装版本自己的文档(help()、--help、官方文档),调整做法并告知用户。切勿编造 API。 |
| 必需的输入、标识符或参数不明确 | 询问用户,或在运行前明确说明所作的假设。 |
诚信规则
- 切勿捏造结果、参数、标识符、引文或统计数据。如果无法运行或验证某项内容,请如实说明。
- 用于商业用途或公开发布前,先检查模型和数据集的许可证。
- 将这里与特定版本相关的细节视为可能已过时:请根据已安装版本的官方文档进行确认。
- 对于需要花费资金、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,请先征得同意。
相关技能
peft-fine-tuning:使用 Hugging Face PEFT,通过 LoRA、QLoRA、IA3、AdaLoRA、前缀微调和提示词微调对大模型进行微调,以便在不到 1% 的参数 ar…blip-2-vision-language:介绍如何通过 HuggingFace Trans… 使用 Salesforce BLIP-2(Q-Former 连接冻结的图像编码器与 OPT 或 FlanT5 等大模型)fine-tuning-openvla-oft:针对机器人动作生成,对 OpenVLA-OFT 和 OpenVLA-OFT+ 策略进行微调和评估,使用连续动作头、LoRA 适配以及……
评论
支持 Markdown