python
import math
import torch
import torch.nn as nn
"""
Peebles & Xie(2023)の DiT を、論文の 3.2 節どおりに書いた小さな実装。
潜在(例:32×32×4)を p×p のパッチに分けて Transformer で処理し、ノイズ eps と共分散 Sigma を出す。
条件は段 t とクラス y の埋め込みの和で、adaLN-Zero のブロックで入れる
"""
def modulate(x, shift, scale):
"""拡大・平行移動:gamma * LN(x) + beta(scale は 1 + 出力にして、初めは gamma = 1 にする実装が多い)"""
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
def timestep_embedding(t, dim):
"""段 t の正弦波の埋め込み"""
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.cos(args), torch.sin(args)], dim=1)
class DiTBlock(nn.Module):
"""adaLN-Zero の DiT ブロック:c から gamma1, beta1, alpha1, gamma2, beta2, alpha2 を回帰する"""
def __init__(self, d, heads, mlp_ratio=4.0):
super().__init__()
self.norm1 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6) # gamma・beta は条件から作るので持たない
self.attn = nn.MultiheadAttention(d, heads, batch_first=True)
self.norm2 = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6)
# 位置ごとの全結合。幅(4 倍)と活性化関数は論文に書かれていないので、ここでは例として置いている
self.ffn = nn.Sequential(nn.Linear(d, int(d * mlp_ratio)), nn.GELU(approximate="tanh"), nn.Linear(int(d * mlp_ratio), d))
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 6 * d))
nn.init.zeros_(self.ada[-1].weight) # Zero:alpha = 0 で、ブロックは恒等写像から始まる
nn.init.zeros_(self.ada[-1].bias)
def forward(self, x, c):
b1, g1, a1, b2, g2, a2 = self.ada(c).chunk(6, dim=1)
h = modulate(self.norm1(x), b1, g1)
x = x + a1.unsqueeze(1) * self.attn(h, h, h, need_weights=False)[0]
x = x + a2.unsqueeze(1) * self.ffn(modulate(self.norm2(x), b2, g2))
return x
class DiT(nn.Module):
def __init__(self, input_size=32, patch=2, in_ch=4, d=384, depth=12, heads=6, num_classes=1000):
super().__init__() # 既定は DiT-S/2 の大きさ
self.p, self.c, self.n = patch, in_ch, input_size // patch
self.patchify = nn.Conv2d(in_ch, d, kernel_size=patch, stride=patch) # p×p のパッチを線形に埋め込む
self.register_buffer("pos", self.sincos_2d(d, self.n), persistent=False)
self.t_mlp = nn.Sequential(nn.Linear(256, d), nn.SiLU(), nn.Linear(d, d))
self.y_emb = nn.Embedding(num_classes + 1, d) # 最後の番号は分類器なしガイダンス用の「条件なし」
self.blocks = nn.ModuleList([DiTBlock(d, heads) for _ in range(depth)])
self.norm = nn.LayerNorm(d, elementwise_affine=False, eps=1e-6)
self.ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
self.out = nn.Linear(d, patch * patch * 2 * in_ch) # 各トークン → p×p×2C(ノイズと共分散)
nn.init.zeros_(self.out.weight) # 最後の線形層は 0 で初期化
nn.init.zeros_(self.out.bias)
@staticmethod
def sincos_2d(d, n):
"""ViT と同じ、2 次元の正弦波の位置の埋め込み(縦と横に半分ずつ)"""
def one_d(dim, pos):
omega = 1.0 / 10000 ** (torch.arange(dim // 2, dtype=torch.float64) / (dim / 2))
out = pos.reshape(-1, 1).double() * omega[None]
return torch.cat([torch.sin(out), torch.cos(out)], dim=1)
gy, gx = torch.meshgrid(torch.arange(n), torch.arange(n), indexing="ij")
return torch.cat([one_d(d // 2, gy), one_d(d // 2, gx)], dim=1).float()[None]
def forward(self, z_t, t, y):
x = self.patchify(z_t).flatten(2).transpose(1, 2) + self.pos # (B, T, d)、T = (I/p)^2
c = self.t_mlp(timestep_embedding(t, 256)) + self.y_emb(y) # 条件:段 t とクラス y の埋め込みの和
for blk in self.blocks:
x = blk(x, c)
shift, scale = self.ada(c).chunk(2, dim=1)
x = self.out(modulate(self.norm(x), shift, scale)) # 最後のレイヤー正規化も adaLN
B = x.size(0)
x = x.view(B, self.n, self.n, self.p, self.p, 2 * self.c) # 元の空間の並びに戻す
x = x.permute(0, 5, 1, 3, 2, 4).reshape(B, 2 * self.c, self.n * self.p, self.n * self.p)
eps, sigma = x.chunk(2, dim=1) # 前半がノイズ、後半が共分散の予測
return eps, sigma
model = DiT()
z_t = torch.randn(2, 4, 32, 32) # 256×256 の画像の潜在(VAE で縦横 1/8)
eps, sigma = model(z_t, torch.randint(0, 1000, (2,)), torch.randint(0, 1000, (2,)))