扩散模型基础:从图像生成到去噪概率模型
扩散模型(Diffusion Model)是当前图像生成领域效果最好的深度学习框架之一,在机器学习算法中占据核心地位。DDPM(Denoising Diffusion Probabilistic Models)通过前向加噪和反向去噪两个过程实现高质量图像生成,Stable Diffusion、DALL-E等AI模型部署均以该原理为基础。扩散模型的核心思想是将图像生成过程建模为马尔可夫链,通过逐步去噪从随机高斯分布恢复出清晰图像。
DDPM前向扩散过程:逐步添加高斯噪声
前向过程对原始图像x0按预定义的噪声调度(noise schedule)逐步添加高斯噪声,经过T个时间步后得到近似纯噪声的xT。每个时间步的加噪操作是一个固定的高斯变换,不涉及可学习参数。
import torch
import torch.nn.functional as F
def forward_diffusion(x_0, t, sqrt_alphas_cumprod, sqrt_one_minus_alphas_cumprod, noise=None):
"""前向扩散:给定原始图像x_0和时间步t,返回加噪后的x_t"""
if noise is None:
noise = torch.randn_like(x_0)
sqrt_alpha = sqrt_alphas_cumprod[t].view(-1, 1, 1, 1)
sqrt_one_minus = sqrt_one_minus_alphas_cumprod[t].view(-1, 1, 1, 1)
# x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * noise
return sqrt_alpha * x_0 + sqrt_one_minus * noise, noise
噪声调度通常采用线性调度(linear schedule)或余弦调度(cosine schedule),后者在低分辨率图像上表现更优。累积乘积alpha_bar_t决定了每个时间步保留原始信号的比例,当T足够大时xT近似服从标准正态分布。
DDPM反向去噪过程:U-Net噪声预测网络
反向过程训练一个神经网络预测每个时间步添加的噪声,从而实现逐步去噪。网络架构普遍采用U-Net,它通过跳跃连接保留多尺度特征信息,适合图像这类结构化数据。训练时不需要遍历所有时间步,而是随机采样时间步进行训练,每个batch内不同样本可对应不同时间步,大幅提升训练效率。
class DiffusionModel:
def __init__(self, model, timesteps=1000, beta_start=1e-4, beta_end=0.02):
self.model = model # U-Net网络
self.timesteps = timesteps
self.betas = torch.linspace(beta_start, beta_end, timesteps)
self.alphas = 1.0 - self.betas
self.alpha_bars = torch.cumprod(self.alphas, dim=0)
def compute_loss(self, x_0):
"""计算训练损失:预测噪声与真实噪声的MSE"""
t = torch.randint(0, self.timesteps, (x_0.shape[0],), device=x_0.device)
noise = torch.randn_like(x_0)
sqrt_ab = self.alpha_bars[t].view(-1,1,1,1).sqrt()
x_t = sqrt_ab * x_0 + (1 - self.alpha_bars[t].view(-1,1,1,1)).sqrt() * noise
predicted_noise = self.model(x_t, t)
return F.mse_loss(noise, predicted_noise)
损失函数采用简单的MSE,无需复杂的对抗训练,这是扩散模型相比GAN的优势之一:训练稳定,不存在模式崩溃问题。
DDIM确定性采样:加速生成过程
DDPM采样需要数百至上千步迭代才能生成高质量图像,推理速度成为AI模型部署的瓶颈。DDIM(Denoising Diffusion Implicit Models)通过构造非马尔可夫的前向过程,在保持生成质量的前提下将采样步数压缩到20-50步。
@torch.no_grad()
def ddim_sample(model, shape, timesteps, alphas_cumprod, eta=0.0, ddim_steps=50):
"""DDIM采样:eta=0为确定性采样,eta>0引入随机性"""
device = next(model.parameters()).device
b = shape[0]
x = torch.randn(shape, device=device)
# 从1000步中均匀选取50步
ddim_timesteps = torch.linspace(0, timesteps-1, ddim_steps, dtype=torch.long)
ddim_timesteps = ddim_timesteps.flip(0)
for i, t in enumerate(ddim_timesteps):
t_batch = torch.full((b,), t, device=device, dtype=torch.long)
eps = model(x, t_batch)
alpha_bar_t = alphas_cumprod[t]
x0_pred = (x - (1 - alpha_bar_t).sqrt() * eps) / alpha_bar_t.sqrt()
if i < len(ddim_timesteps) - 1:
t_next = ddim_timesteps[i + 1]
alpha_bar_next = alphas_cumprod[t_next]
x = alpha_bar_next.sqrt() * x0_pred + (1 - alpha_bar_next - eta**2 * (1 - alpha_bar_next)).sqrt() * eps
return x
eta参数控制采样的随机性:eta=0时为完全确定性采样,相同输入始终产生相同输出;eta=1时退化为标准DDPM采样。实际部署中通常取eta=0配合20-50步DDIM采样,生成质量与1000步DDPM相当,推理速度提升20倍以上。
噪声调度选择与损失改进
噪声调度的选择直接影响生成质量。线性调度在高分辨率下后期信噪比过低,训练信号稀疏;余弦调度通过非线性衰减缓解了该问题。
def cosine_beta_schedule(timesteps, s=0.008):
"""余弦噪声调度"""
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps)
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
return torch.clip(betas, 0.0001, 0.9999)
无分类器引导(classifier-free guidance)是条件扩散模型的核心技术,训练时以一定概率丢弃条件标签,推理时通过有条件和无条件预测的差值放大条件信号,实现类别控制而无需额外分类器。
AI模型部署中的推理优化策略
扩散模型的AI模型部署需要兼顾生成质量和推理速度。常见优化手段包括:使用潜在扩散(Latent Diffusion)在压缩的潜在空间而非像素空间执行扩散过程,大幅降低计算量;采用flash attention优化U-Net中的注意力计算;利用量化技术将模型权重从FP32压缩到FP16甚至INT8,减少显存占用。Stable Diffusion即采用潜在扩散,在512x512分辨率下仅需4GB显存即可运行,使扩散模型在消费级GPU上可用。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kuo-san-mo-xing-tu-xiang-sheng-cheng-yuan-li-ddpm-qu-zao/