python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Ho ら(2020)の DDPM を、論文の式どおりに書いた小さな実装。
T = 1000、beta は 1e-4 から 0.02 まで直線(4 章)。学習は Algorithm 1、生成は Algorithm 2。
論文のネットワークは残差ブロックと自己注意を持つ U-Net。ここでは形を示すための小さな CNN にしている
"""
T = 1000
betas = torch.linspace(1e-4, 0.02, T) # beta_1, ..., beta_T
alphas = 1.0 - betas # alpha_t = 1 - beta_t
alpha_bars = torch.cumprod(alphas, dim=0) # alpha_bar_t = alpha_1 * ... * alpha_t
def timestep_embedding(t, dim):
"""段 t を正弦波で埋め込む(Transformer の位置エンコーディングと同じ式)"""
half = dim // 2
freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
args = t.float()[:, None] * freqs[None]
return torch.cat([torch.sin(args), torch.cos(args)], dim=1)
class TinyEpsModel(nn.Module):
"""x_t と t から、足されたノイズ epsilon を予測する(論文では U-Net)"""
def __init__(self, ch=64, t_dim=128):
super().__init__()
self.t_mlp = nn.Sequential(nn.Linear(t_dim, ch), nn.SiLU(), nn.Linear(ch, ch))
self.inp = nn.Conv2d(3, ch, 3, padding=1)
self.body = nn.Sequential(nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1),
nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1))
self.out = nn.Conv2d(ch, 3, 3, padding=1)
self.t_dim = t_dim
def forward(self, x, t):
h = self.inp(x)
h = h + self.t_mlp(timestep_embedding(t, self.t_dim))[:, :, None, None] # t の埋め込みを足す
return self.out(h + self.body(h))
def q_sample(x0, t, eps):
"""式 4:x_t = sqrt(alpha_bar_t) x_0 + sqrt(1 - alpha_bar_t) eps を 1 回で作る"""
ab = alpha_bars.to(x0.device)[t - 1].view(-1, 1, 1, 1) # t は 1〜T
return ab.sqrt() * x0 + (1 - ab).sqrt() * eps
def loss_simple(model, x0):
"""式 14(Algorithm 1):足したノイズと予測したノイズの二乗誤差"""
t = torch.randint(1, T + 1, (x0.size(0),), device=x0.device) # t ~ Uniform({1, ..., T})
eps = torch.randn_like(x0) # epsilon ~ N(0, I)
return F.mse_loss(model(q_sample(x0, t, eps), t), eps)
@torch.no_grad()
def sample(model, shape, device):
"""Algorithm 2:x_T ~ N(0, I) から 1 段ずつ戻る(sigma_t^2 = beta_t)"""
x = torch.randn(shape, device=device)
for t in range(T, 0, -1):
tt = torch.full((shape[0],), t, device=device, dtype=torch.long)
a, ab, b = alphas[t - 1].item(), alpha_bars[t - 1].item(), betas[t - 1].item()
eps = model(x, tt)
mean = (x - b / math.sqrt(1 - ab) * eps) / math.sqrt(a) # 式 11 の平均
z = torch.randn_like(x) if t > 1 else torch.zeros_like(x) # 最後の段だけ z = 0
x = mean + math.sqrt(b) * z
return x.clamp(-1, 1)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = TinyEpsModel().to(device)
ema = TinyEpsModel().to(device)
ema.load_state_dict(model.state_dict())
optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) # 論文の CIFAR-10 の学習率
x0 = torch.rand(8, 3, 32, 32, device=device) * 2 - 1 # 画素を [-1, 1] に縮めた画像(ここでは乱数で代用)
model.train()
loss = loss_simple(model, x0)
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad(): # パラメータの指数移動平均(減衰率 0.9999)
for p_ema, p in zip(ema.parameters(), model.parameters()):
p_ema.mul_(0.9999).add_(p, alpha=1 - 0.9999)
ema.eval()
images = sample(ema, (4, 3, 32, 32), device) # 生成には EMA の重みを使う