11. 生成模型
生成模型学习数据分布 $P(x)$,能生成新样本。三大主流:VAE、GAN、Diffusion。
11.1 任务类型
| 任务 | 输入 | 输出 |
|---|---|---|
| 图像生成 | 噪声 | 图像 |
| 文本生成 | 提示 | 文本 |
| 音乐生成 | 噪声 / 条件 | 音频 |
| 视频生成 | 噪声 / 文本 | 视频 |
| 图像翻译 | 图像 A | 图像 B |
| 超分 | 低分 | 高分 |
11.2 自回归模型 (Autoregressive)
思想
$P(x) = \prod_i P(x_i | x_{<i})$
模型
- PixelCNN:逐像素生成
- GPT 系列:逐 token
- WaveNet:逐采样点
- LLaMA:LLM 主流
优点
- 似然精确
- 高质量样本
缺点
- 慢(顺序)
- 似然难优化
11.3 VAE (Variational Autoencoder)
思想
学习隐空间 $z$,采样 + 解码生成。
数学
ELBO:
$$ \log P(x) \geq \mathbb{E}_{q(z|x)}[\log p(x|z)] - \text{KL}(q(z|x) | p(z)) $$
- $q(z|x)$:编码器(推断网络)
- $p(x|z)$:解码器(生成网络)
- $p(z)$:先验(标准正态)
重参数化技巧
$$ z = \mu + \sigma \cdot \epsilon, \quad \epsilon \sim \mathcal{N}(0, 1) $$
让采样可微。
PyTorch 实现
class VAE(nn.Module):
def __init__(self, in_dim, latent_dim, hidden_dim=400):
super().__init__()
# 编码器
self.encoder = nn.Sequential(
nn.Linear(in_dim, hidden_dim), nn.ReLU(),
)
self.fc_mu = nn.Linear(hidden_dim, latent_dim)
self.fc_logvar = nn.Linear(hidden_dim, latent_dim)
# 解码器
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim), nn.ReLU(),
nn.Linear(hidden_dim, in_dim), nn.Sigmoid(),
)
def encode(self, x):
h = self.encoder(x)
return self.fc_mu(h), self.fc_logvar(h)
def reparameterize(self, mu, logvar):
std = (logvar * 0.5).exp()
return mu + std * torch.randn_like(std)
def decode(self, z):
return self.decoder(z)
def forward(self, x):
mu, logvar = self.encode(x.view(-1, self.in_dim))
z = self.reparameterize(mu, logvar)
return self.decode(z), mu, logvar
# 损失
def vae_loss(recon_x, x, mu, logvar):
BCE = F.binary_cross_entropy(recon_x, x.view(-1, in_dim), reduction='sum')
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD
优缺点
优点:理论优雅、可嵌入下游 缺点:样本模糊、ELBO 不紧
变体
- β-VAE:加 $\beta \cdot \text{KL}$ 增强解耦
- VQ-VAE:离散隐空间
- VQ-VAE-2:分层
- NVAE:深度
- Hierarchical VAE
11.4 GAN (Generative Adversarial Network)
思想
两个网络对抗训练: - 生成器 G:噪声 → 假样本 - 判别器 D:判真假
数学
$$ \min_G \max_D V(D, G) = \mathbb{E}{x \sim p{\text{data}}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))] $$
PyTorch 实现
class Generator(nn.Module):
def __init__(self, latent_dim=100, out_dim=784):
super().__init__()
self.net = nn.Sequential(
nn.Linear(latent_dim, 256), nn.LeakyReLU(0.2),
nn.Linear(256, 512), nn.LeakyReLU(0.2),
nn.Linear(512, out_dim), nn.Tanh(),
)
def forward(self, z):
return self.net(z)
class Discriminator(nn.Module):
def __init__(self, in_dim=784):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, 512), nn.LeakyReLU(0.2),
nn.Linear(512, 256), nn.LeakyReLU(0.2),
nn.Linear(256, 1),
)
def forward(self, x):
return self.net(x)
# 训练
for real, _ in dataloader:
# 真实样本
real_labels = torch.ones(batch_size, 1)
fake_labels = torch.zeros(batch_size, 1)
# 训练 D
d_real = D(real)
d_fake = D(G(z))
d_loss = (F.binary_cross_entropy(d_real, real_labels) +
F.binary_cross_entropy(d_fake, fake_labels))
# 训练 G
g_loss = F.binary_cross_entropy(D(G(z)), real_labels)
训练技巧
- 交替训练 G / D
- 标签平滑:real 0.9 而非 1.0
- TTUR:D 比 G 小 LR
- 梯度惩罚 / Spectral Norm
优缺点
优点:样本锐利、质量高 缺点:训练不稳、模式崩溃、多样性差
GAN 变体
DCGAN
CNN + GAN。BatchNorm 关键。
WGAN (Wasserstein GAN)
Wasserstein 距离 + 梯度裁剪 / 梯度惩罚。
LSGAN
最小二乘损失,更稳。
CycleGAN
无配对图像翻译。
$$ L = L_{\text{GAN}}(G, D_Y, X, Y) + L_{\text{GAN}}(F, D_X, Y, X) + \lambda L_{\text{cyc}}(G, F) $$
StyleGAN
Style-based 生成器,高质量人脸。
Conditional GAN
条件生成:
class ConditionalGenerator(nn.Module):
def forward(self, z, label):
embed = self.label_emb(label)
x = torch.cat([z, embed], dim=1)
return self.net(x)
ProgressiveGAN
渐进式增长。
BigGAN
大规模 + Big + 强大正则。
11.5 Diffusion Model (扩散模型) ⭐
思想
两个过程: - 前向:逐步加噪 → 纯高斯 - 反向:逐步去噪 → 数据
DDPM
前向过程
$$ q(x_t | x_{t-1}) = \mathcal{N}(x_t; \sqrt{1 - \beta_t} x_{t-1}, \beta_t I) $$
直接任意步:
$$ x_t = \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1 - \bar{\alpha}_t} \epsilon, \quad \epsilon \sim \mathcal{N}(0, I) $$
反向过程
$$ p_\theta(x_{t-1} | x_t) = \mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \Sigma_\theta(x_t, t)) $$
简化损失
$$ L = \mathbb{E}{t, x_0, \epsilon} | \epsilon - \epsilon\theta(\sqrt{\bar{\alpha}_t} x_0 + \sqrt{1-\bar{\alpha}_t} \epsilon, t) |^2 $$
预测噪声 $\epsilon$。
PyTorch 实现
class DiffusionModel:
def __init__(self, eps_model, n_steps=1000, beta_start=1e-4, beta_end=0.02):
self.eps_model = eps_model
self.betas = torch.linspace(beta_start, beta_end, n_steps)
self.alphas = 1 - self.betas
self.alpha_bars = torch.cumprod(self.alphas, dim=0)
self.n_steps = n_steps
def q_sample(self, x0, t, noise):
sqrt_a_bar = self.alpha_bars[t].sqrt()[:, None, None, None]
sqrt_one_minus = (1 - self.alpha_bars[t]).sqrt()[:, None, None, None]
return sqrt_a_bar * x0 + sqrt_one_minus * noise
def train_step(self, x0):
B = x0.size(0)
t = torch.randint(0, self.n_steps, (B,)).to(x0.device)
noise = torch.randn_like(x0)
x_t = self.q_sample(x0, t, noise)
pred_noise = self.eps_model(x_t, t)
return F.mse_loss(pred_noise, noise)
@torch.no_grad()
def sample(self, B, device, shape):
x = torch.randn(B, *shape, device=device)
for t in reversed(range(self.n_steps)):
pred_noise = self.eps_model(x, torch.full((B,), t, device=device))
beta_t = self.betas[t]
alpha_t = self.alphas[t]
alpha_bar_t = self.alpha_bars[t]
mean = (1 / alpha_t.sqrt()) * (
x - beta_t / (1 - alpha_bar_t).sqrt() * pred_noise
)
if t > 0:
noise = torch.randn_like(x)
sigma = beta_t.sqrt()
x = mean + sigma * noise
else:
x = mean
return x
UNet (去噪网络)
class UNet(nn.Module):
"""简化版 UNet for diffusion."""
def __init__(self, in_ch=3, base_ch=64, time_dim=256):
super().__init__()
self.time_embed = nn.Sequential(
nn.Linear(1, time_dim), nn.SiLU(),
nn.Linear(time_dim, time_dim),
)
# Encoder
self.down1 = self._block(in_ch, base_ch)
self.down2 = self._block(base_ch, base_ch * 2)
self.down3 = self._block(base_ch * 2, base_ch * 4)
# Bottleneck
self.bot = self._block(base_ch * 4, base_ch * 4)
# Decoder
self.up3 = self._block(base_ch * 4, base_ch * 2)
self.up2 = self._block(base_ch * 2, base_ch)
self.up1 = nn.Conv2d(base_ch, in_ch, 1)
def forward(self, x, t):
t_emb = self.time_embed(t.unsqueeze(-1).float())
# ... UNet 主体 + skip connection
关键改进
DDIM
- 确定性采样
- 加速 10-50x
- 步骤数无关
DPM-Solver
更先进的 ODE 求解器,10-20 步达质量。
Latent Diffusion (Stable Diffusion)
在潜空间扩散 → 大幅加速:
x_0 (图像) → VAE Encoder → z_0 (潜空间) → 扩散 + UNet → VAE Decoder → 图像
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16,
).to("cuda")
image = pipe("A photo of a cat").images[0]
Classifier-Free Guidance
无分类器条件控制:
$$ \tilde{\epsilon} = (1 + w) \epsilon_\theta(x_t, c) - w \epsilon_\theta(x_t, \emptyset) $$
ControlNet
条件控制(pose、edge、depth)。
Sora / DiT
- Transformer + Diffusion
- 视频生成
- 扩散 Transformer (DiT)
参考
- Ho et al., 2020 Denoising Diffusion Probabilistic Models (DDPM)
- Song et al., 2021 Denoising Diffusion Implicit Models (DDIM)
- Rombach et al., 2022 High-Resolution Image Synthesis with Latent Diffusion Models (LDM)
- Peebles & Xie, 2023 Scalable Diffusion Models with Transformers (DiT)
11.6 Flow 模型
Normalizing Flow
通过可逆变换将简单分布映射到复杂分布:
$$ p_X(x) = p_Z(f^{-1}(x)) \left| \det \frac{\partial f^{-1}(x)}{\partial x} \right| $$
主流
- RealNVP:仿射耦合层
- Glow:可逆 1x1 卷积
- FFJORD:连续 flow
优点
- 精确似然
- 可逆
缺点
- 计算量大
11.7 自回归视频 (Sora 范式)
Patch-based Video Generation
视频切成 patch → Transformer → patch token
世界模型
类似 Sora:将视频建模为时空序列。
11.8 模型对比
| VAE | GAN | Diffusion | AR | |
|---|---|---|---|---|
| 训练稳定 | ✅ | ❌ | ✅ | ✅ |
| 样本质量 | 中 | 高 | 极高 | 高 |
| 多样性 | ✅ | ❌ 模式崩溃 | ✅ | ✅ |
| 似然 | ELBO | 无 | ELBO | 精确 |
| 推理速度 | 快 | 极快 | 慢 (10-1000 步) | 顺序 |
| 训练成本 | 低 | 中 | 高 | 高 |
11.9 评估
FID (Fréchet Inception Distance)
$$ \text{FID} = |\mu_r - \mu_g|^2 + \text{Tr}(\Sigma_r + \Sigma_g - 2(\Sigma_r \Sigma_g)^{1/2}) $$
越低越好。
IS (Inception Score)
结合质量 + 多样性。
LPIPS / SSIM / PSNR
像素级距离。
人类评估
最可靠但贵。
11.10 实战:Stable Diffusion
from diffusers import (
StableDiffusionPipeline,
DPMSolverMultistepScheduler,
)
import torch
model_id = "stabilityai/stable-diffusion-2-1"
pipe = StableDiffusionPipeline.from_pretrained(
model_id, torch_dtype=torch.float16,
).to("cuda")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
# 推理
image = pipe(
prompt="A cyberpunk cat in Tokyo",
negative_prompt="blurry, low quality",
num_inference_steps=25, # DPM-Solver 快
guidance_scale=7.5,
height=512, width=512,
).images[0]
image.save("cat.png")
11.11 LoRA 微调 SD
# peft + diffusers
from peft import LoraConfig, get_peft_model
lora_config = LoraConfig(
r=8, lora_alpha=16,
target_modules=["to_q", "to_v"], # UNet 注意力层
)
unet = get_peft_model(unet, lora_config)
训练自己的角色 / 风格
- 数据:20-100 张同主题
- 工具:kohya-ss / ai-toolkit / diffusers-trainer
- 工具链:dreambooth / LoRA / Textual Inversion
11.12 多模态生成
文本 → 图像
- DALL-E 3 / Imagen 2 / Stable Diffusion 3 / Midjourney
文本 → 视频
- Sora / Runway Gen-3 / Luma Dream Machine / Kling
文本 → 3D
- DreamFusion (SDS) / Magic3D / Gaussian Splatting
文本 → 音频
- AudioLDM / Bark / MusicGen
文本 → 音乐
- Suno / Udio / MusicGen
11.13 应用场景
| 场景 | 推荐模型 |
|---|---|
| 高质量图像 | SD 3 / Midjourney |
| 实时生成 | StyleGAN / Tiny Diffusion |
| 视频生成 | Sora / Kling |
| 图像编辑 | InstructPix2Pix / SD + ControlNet |
| 超分辨率 | Real-ESRGAN / Latent Diffusion |
| 风格迁移 | CycleGAN / Style Transfer |
| 文本生成 | LLaMA / GPT |
| 3D | Gaussian Splatting |
11.14 参考
- Kingma & Welling, 2014 Auto-Encoding Variational Bayes (VAE)
- Goodfellow et al., 2014 Generative Adversarial Networks (GAN)
- Mirza & Osindero, 2014 Conditional GAN
- Karras et al., 2019 A Style-Based Generator Architecture for Generative Adversarial Networks (StyleGAN)
- Ho et al., 2020 Denoising Diffusion Probabilistic Models (DDPM)
- Song et al., 2021 Denoising Diffusion Implicit Models (DDIM)
- Rombach et al., 2022 High-Resolution Image Synthesis with Latent Diffusion Models (SD)
- Peebles & Xie, 2023 Scalable Diffusion Models with Transformers (DiT)
- Brooks et al., 2023 InstructPix2Pix