Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


title: “Stable Diffusion Image Generation” sidebar_label: “Stable Diffusion Image Generation” description: “State-of-the-art text-to-image generation with Stable Diffusion models via HuggingFace Diffusers”

{/* 本页面由 website/scripts/generate-skill-docs.py 根据技能对应的 SKILL.md 文件自动生成。请直接编辑源文件 SKILL.md,而非此页面。 */}

Stable Diffusion 图像生成

通过 HuggingFace Diffusers 库,利用先进的 Stable Diffusion 模型实现文本到图像的生成。适用于根据文本提示生成图像、执行图像间转换、修复缺失区域,或构建自定义的扩散模型工作流。

技能元数据

来源可选 — 通过 hermes skills install official/mlops/stable-diffusion 安装
路径optional-skills/mlops/stable-diffusion
版本1.0.0
开发者Orchestra Research
许可协议MIT
依赖项diffusers>=0.30.0, transformers>=4.41.0, accelerate>=0.31.0, torch>=2.0.0
支持平台linux、macos、windows
标签图像生成, Stable Diffusion, Diffusers, 文本到图像, 多模态, 计算机视觉

参考:完整的 SKILL.md 文件

:::info 以下是当触发该技能时 Hermes 会加载的完整技能定义。技能启用后,智能体将依据此内容执行操作。
::

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]

架构概览

三大核心组件设计

Diffusers 是基于三个核心组件构建的:

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]

生成参数

核心参数

参数默认值描述
prompt必填所需图像的文本描述
negative_prompt需要避免出现在图像中的内容
num_inference_steps50去噪步数(步数越多,图像质量越高)
guidance_scale7.5提示词遵循程度(通常范围为7-12)
height, width512/1024输出尺寸(需为8的倍数)
generator用于确保结果可复现的Torch生成器
num_images_per_prompt1批量生成数量

可复现的图像生成

import torch

generator = torch.Generator(device="cuda").manual_seed(42)

image = pipe(
    prompt="A cat wearing a top hat",
    generator=generator,
    num_inference_steps=50
).images[0]

否定提示词

image = pipe(
    prompt="Professional photo of a dog in a garden",
    negative_prompt="blurry, low quality, distorted, ugly, bad anatomy",
    guidance_scale=7.5
).images[0]

图像到图像转换

在文本引导下对现有图像进行变换:

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

添加空间条件控制,实现精准操控:

from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
import torch

# Load ControlNet for edge conditioning
controlnet = ControlNetModel.from_pretrained(
    "lllyasviel/control_v11p_sd15_canny",
    torch_dtype=torch.float16
)

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

# Use Canny edge image as control
control_image = get_canny_image(input_image)

image = pipe(
    prompt="A beautiful house in the style of Van Gogh",
    image=control_image,
    num_inference_steps=30
).images[0]

可用的 ControlNets

ControlNet输入类型使用场景
canny边缘图保留结构
openpose姿态骨架人体姿态
depth深度图具有3D感知的生成
normal法线图表面细节
mlsd线段建筑线条
scribble草图草图转图像

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