使用 Diffusers 的 Stable Diffusion

TL;DR

Hugging Face 发布了一篇指南,介绍如何使用 🤗 Diffusers 库运行 Stable Diffusion v1‑4(以及后续版本),内容涵盖安装、许可、推理代码以及底层的潜在扩散架构。

License requirements

Stable Diffusion 模型的许可证规定:(1) 禁止非法或有害的生成;(2) 赋予用户对生成输出的全部权利,同时要求用户对其负责;(3) 允许商业使用和权重再分发,但必须将相同的限制传递给下游用户。

Quick start with Diffusers

  • 安装所需的包:
pip install diffusers==0.10.2 transformers scipy ftfy accelerate
  • 加载管道(示例为 v1‑4;其他版本如 1.5、2、2.1 也类似):
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
pipe.to("cuda")
  • 对于显存小于 10 GB 的 GPU,加载 fp16 检查点:
pipe = StableDiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16
)
  • 生成图像:
prompt = "a photograph of an astronaut riding a horse"
image = pipe(prompt).images[0]
  • 通过为 torch.Generator 设置种子并将其传入管道,可实现确定性输出。
  • guidance_scale 参数(默认 7.5)控制 classifier‑free guidance;推荐取值在 7 到 8.5 之间。
  • 去噪步数 (num_inference_steps) 默认是 50;减少步数可以加快生成速度,但会降低质量。
  • 通过指定 heightwidth(两者必须是 8 的倍数)可以生成非方形图像。使用 512 作为一维,另一维取更大的 8 的倍数可获得最佳效果。

Understanding Stable Diffusion’s architecture

Stable Diffusion 是一种 潜在扩散 模型,通过在压缩的潜在空间中操作(空间降采样 8×8,即 512×512 的图像会变为 64×64 的潜在张量),从而降低内存和计算需求。它由三个核心组件组成:

  1. 变分自编码器 (VAE) – 将图像编码为潜在表示,再将潜在解码回像素空间;推理时仅需解码器。
  2. U‑Net – 为每个扩散步骤预测噪声残差;包含基于文本嵌入的交叉注意力层。
  3. 文本编码器 – 预训练的 CLIP 文本模型 (CLIPTextModel),将提示转换为 77×768 的嵌入;在训练期间保持冻结。

推理时,随机的潜在种子和文本嵌入被送入 U‑Net,U‑Net 在约 50 步内使用调度器(默认 PNDM,亦可选 DDIM 与 K‑LMS)迭代去噪。最终的潜在由 VAE 解码,得到 512×512 的图像。

Customizing the pipeline

高级用户可以通过 subfolder 参数从模型仓库加载并替换单独的组件(例如 VAE、调度器、UNet):

from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)

博客中的示例展示了使用 K‑LMS 调度器、classifier‑free guidance 以及手动潜在处理的完整推理循环。

Practical tips

  • 在显存受限的 GPU 上使用 torch.float16
  • height/width 设置为 8 的倍数,以避免形状不匹配。
  • 提高 guidance_scale 可增强对提示的遵循,但会降低多样性。
  • 减少 num_inference_steps 可加快生成速度;增加则提升保真度。
  • 管道返回的字典包含 imagesnsfw_content_detected 标志。

Resources

Citation

@article{patil2022stable,
  author = {Patil, Suraj and Cuenca, Pedro and Lambert, Nathan and von Platen, Patrick},
  title = {Stable Diffusion with 🧨 Diffusers},
  journal = {Hugging Face Blog},
  year = {2022},
  note = {https://huggingface.co/blog/stable_diffusion}
}

Sources