python コピー
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Kingma & Dhariwal (2018) の Glow を小さく実装する例(Table 1、3 節、式 2・9〜11)
・流れの 1 ステップ:actnorm → 可逆な 1×1 畳み込み(LU 分解の形)→ アフィン結合層
・アフィン結合層:x_a, x_b = split(x)、(log s, t) = NN(x_b)、y_a = s ⊙ x_a + t、y_b = x_b
・マルチスケール:squeeze → ステップ × K → split を L − 1 回、最後は squeeze → ステップ × K
PyTorch に Glow の組み込みはない(公式実装は GitHub の openai/glow、TensorFlow)
"""
class ActNorm(nn.Module):
def __init__(self, c):
super().__init__()
self.logs = nn.Parameter(torch.zeros(1, c, 1, 1))
self.b = nn.Parameter(torch.zeros(1, c, 1, 1))
self.register_buffer("initialized", torch.tensor(False))
def forward(self, x):
if not self.initialized: # データにもとづく初期化:最初のミニバッチで平均 0・分散 1 に
with torch.no_grad():
mean = x.mean(dim=(0, 2, 3), keepdim=True)
std = x.std(dim=(0, 2, 3), keepdim=True) + 1e-6
self.b.data.copy_(-mean / std)
self.logs.data.copy_(-torch.log(std))
self.initialized.fill_(True)
y = x * torch.exp(self.logs) + self.b
logdet = x.size(2) * x.size(3) * self.logs.sum() # h·w·sum(log|s|)
return y, logdet
def inverse(self, y):
return (y - self.b) * torch.exp(-self.logs)
class InvConv1x1LU(nn.Module):
"""W = P L (U + diag(s))。log|det W| = sum(log|s|)(式 10〜11)"""
def __init__(self, c):
super().__init__()
w = torch.linalg.qr(torch.randn(c, c))[0] # ランダムな回転行列で初期化
P, L, U = torch.linalg.lu(w)
s = torch.diagonal(U)
self.register_buffer("P", P) # 並べ替えの行列は固定
self.register_buffer("sign_s", torch.sign(s))
self.register_buffer("l_mask", torch.tril(torch.ones(c, c), -1))
self.L = nn.Parameter(L)
self.U = nn.Parameter(torch.triu(U, 1))
self.log_s = nn.Parameter(torch.log(torch.abs(s)))
def weight(self):
c = self.L.size(0)
L = self.L * self.l_mask + torch.eye(c, device=self.L.device) # 対角が 1 の下三角
U = self.U * self.l_mask.T + torch.diag(self.sign_s * torch.exp(self.log_s))
return self.P @ L @ U
def forward(self, x):
W = self.weight()
y = F.conv2d(x, W[:, :, None, None])
return y, x.size(2) * x.size(3) * self.log_s.sum() # h·w·log|det W|
def inverse(self, y):
W_inv = torch.inverse(self.weight())
return F.conv2d(y, W_inv[:, :, None, None])
class AffineCoupling(nn.Module):
def __init__(self, c, hidden=512):
super().__init__()
self.nn = nn.Sequential(
nn.Conv2d(c // 2, hidden, 3, padding=1), nn.ReLU(),
nn.Conv2d(hidden, hidden, 1), nn.ReLU(),
nn.Conv2d(hidden, c, 3, padding=1), # log s と t(c/2 ずつ)
)
nn.init.zeros_(self.nn[-1].weight) # 最後の畳み込みを 0 で初期化 → 恒等変換から始まる
nn.init.zeros_(self.nn[-1].bias)
def forward(self, x):
x_a, x_b = x.chunk(2, dim=1)
log_s, t = self.nn(x_b).chunk(2, dim=1)
y_a = torch.exp(log_s) * x_a + t
return torch.cat([y_a, x_b], dim=1), log_s.flatten(1).sum(1)
def inverse(self, y):
y_a, y_b = y.chunk(2, dim=1)
log_s, t = self.nn(y_b).chunk(2, dim=1) # そのまま通した y_b から計算し直す
return torch.cat([(y_a - t) * torch.exp(-log_s), y_b], dim=1)
class FlowStep(nn.Module):
def __init__(self, c):
super().__init__()
self.layers = nn.ModuleList([ActNorm(c), InvConv1x1LU(c), AffineCoupling(c)])
def forward(self, x):
logdet = 0
for layer in self.layers:
x, ld = layer(x)
logdet = logdet + ld
return x, logdet
def inverse(self, y):
for layer in reversed(self.layers):
y = layer.inverse(y)
return y
def squeeze(x):
b, c, h, w = x.shape
x = x.view(b, c, h // 2, 2, w // 2, 2).permute(0, 1, 3, 5, 2, 4)
return x.reshape(b, c * 4, h // 2, w // 2)
def unsqueeze(x):
b, c, h, w = x.shape
x = x.view(b, c // 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3)
return x.reshape(b, c // 4, h * 2, w * 2)
class Glow(nn.Module):
def __init__(self, c=3, K=8, L=3): # 論文の CIFAR-10 は K = 32、L = 3
super().__init__()
self.levels = nn.ModuleList()
for l in range(L):
c = c * 4 # squeeze でチャネルが 4 倍
self.levels.append(nn.ModuleList([FlowStep(c) for _ in range(K)]))
if l < L - 1:
c = c // 2 # split で半分を先に出す
def forward(self, x):
logdet, zs = 0, []
for l, steps in enumerate(self.levels):
x = squeeze(x)
for step in steps:
x, ld = step(x)
logdet = logdet + ld
if l < len(self.levels) - 1:
z, x = x.chunk(2, dim=1) # z_l として先に出す
zs.append(z)
zs.append(x) # z_L
return zs, logdet
@torch.no_grad()
def sample(self, zs):
x = zs[-1]
for l in reversed(range(len(self.levels))):
if l < len(self.levels) - 1:
x = torch.cat([zs[l], x], dim=1)
for step in reversed(self.levels[l]):
x = step.inverse(x)
x = unsqueeze(x)
return x
def bits_per_dim(model, x, n_bins=256):
"""x:0〜1 に縮めた画像。一様ノイズで連続にして負の対数尤度を求める(式 2)"""
M = x[0].numel()
x = x + torch.rand_like(x) / n_bins # u ~ U(0, a)、a = 1/n_bins
zs, logdet = model(x - 0.5)
log_pz = sum((-0.5 * (z ** 2 + math.log(2 * math.pi))).flatten(1).sum(1) for z in zs)
log_px = log_pz + logdet - M * math.log(n_bins) # c = −M·log a
return (-log_px / (M * math.log(2))).mean()
model = Glow()
opt = torch.optim.Adam(model.parameters(), lr=1e-3) # 論文:Adam、α = 0.001
x = torch.rand(16, 3, 32, 32) # 本来はデータセットの画像
loss = bits_per_dim(model, x) # 最初の呼び出しで actnorm が初期化される
opt.zero_grad()
loss.backward()
opt.step()
# 温度 T で生成する(論文の 0.7。厳密に p^(T^2) になるのは加法的な結合層のとき)
T = 0.7
with torch.no_grad():
zs, _ = model(torch.rand(4, 3, 32, 32) - 0.5) # z の形を得るため
images = model.sample([T * torch.randn_like(z) for z in zs]) + 0.5