Skip to content

Stable Diffusion 扩散模型

Stable Diffusion 是开源图像生成领域的里程碑,其核心创新在于潜空间扩散(Latent Diffusion),将扩散过程从像素空间转移到低维潜空间,大幅降低了计算成本,使高质量图像生成在消费级 GPU 上成为可能。

Stable Diffusion架构

潜空间扩散模型(LDM)

Stable Diffusion 的核心架构由三个组件构成:

  1. VAE(变分自编码器):将图像压缩到低维潜空间(4×64×64),再解码回像素空间
  2. U-Net:在潜空间执行去噪扩散过程,预测并去除噪声
  3. 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.42022.08首个开源版本512×512
SD 1.52022.10训练优化,质量提升512×512
SD 2.02022.12OpenCLIP 文本编码器,v-prediction768×768
SD 2.12023.01微调改进768×768
SDXL2023.07双文本编码器,更大 U-Net1024×1024
SD 3.02024.06MMDiT 架构,Flow Matching1024×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]

相关资源

最近更新