Stable Diffusion 扩散模型
Stable Diffusion 是开源图像生成领域的里程碑,其核心创新在于潜空间扩散(Latent Diffusion),将扩散过程从像素空间转移到低维潜空间,大幅降低了计算成本,使高质量图像生成在消费级 GPU 上成为可能。
潜空间扩散模型(LDM)
Stable Diffusion 的核心架构由三个组件构成:
- VAE(变分自编码器):将图像压缩到低维潜空间(4×64×64),再解码回像素空间
- U-Net:在潜空间执行去噪扩散过程,预测并去除噪声
- CLIP 文本编码器:将文本提示编码为条件向量,引导生成过程
python
import torch
import torch.nn as nn
class LatentDiffusionPipeline:
def __init__(self, vae, unet, text_encoder, scheduler):
self.vae = vae
self.unet = unet
self.text_encoder = text_encoder
self.scheduler = scheduler
@torch.no_grad()
def generate(self, prompt, num_inference_steps=50, guidance_scale=7.5):
# 编码文本条件
text_input = self.tokenizer(prompt, return_tensors="pt")
text_embeddings = self.text_encoder(**text_input).last_hidden_state
# 无条件嵌入(用于 CFG)
uncond_embeddings = self.text_encoder(
**self.tokenizer([""], return_tensors="pt")
).last_hidden_state
# 拼接条件和无条件
embeddings = torch.cat([uncond_embeddings, text_embeddings])
# 从纯噪声开始
latents = torch.randn(1, 4, 64, 64)
# 迭代去噪
for t in self.scheduler.timesteps:
# 分类器自由引导
noise_pred_uncond, noise_pred_text = self.unet(
torch.cat([latents] * 2), t, encoder_hidden_states=embeddings
).sample.chunk(2)
noise_pred = noise_pred_uncond + guidance_scale * (
noise_pred_text - noise_pred_uncond
)
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
# VAE 解码
image = self.vae.decode(latents / 0.18215).sample
return image分类器自由引导(CFG)
CFG 是 Stable Diffusion 生成高质量图像的关键技术:
$$\hat{\epsilon}\theta = \epsilon\theta(x_t, t, \emptyset) + s \cdot (\epsilon_\theta(x_t, t, c) - \epsilon_\theta(x_t, t, \emptyset))$$
其中 $s$ 是引导尺度(guidance scale),$c$ 是文本条件。引导尺度越高,生成图像越符合文本描述,但多样性降低。
引导尺度选择
- guidance_scale=1-3:创意性强,与提示关联弱
- guidance_scale=7-9:平衡质量与多样性(推荐默认值)
- guidance_scale=15+:高度遵循提示,但可能出现过饱和
Stable Diffusion 版本演进
| 版本 | 发布时间 | 核心改进 | 分辨率 |
|---|---|---|---|
| SD 1.4 | 2022.08 | 首个开源版本 | 512×512 |
| SD 1.5 | 2022.10 | 训练优化,质量提升 | 512×512 |
| SD 2.0 | 2022.12 | OpenCLIP 文本编码器,v-prediction | 768×768 |
| SD 2.1 | 2023.01 | 微调改进 | 768×768 |
| SDXL | 2023.07 | 双文本编码器,更大 U-Net | 1024×1024 |
| SD 3.0 | 2024.06 | MMDiT 架构,Flow Matching | 1024×1024 |
ControlNet:可控生成
ControlNet 为 Stable Diffusion 添加了空间条件控制能力,支持边缘图、深度图、姿态图等多种控制信号:
python
from diffusers import ControlNetModel, StableDiffusionControlNetPipeline
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/control_v11p_sd15_canny"
)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=controlnet
)
# 使用 Canny 边缘图控制生成
image = pipe("a beautiful landscape", image=canny_image).images[0]