import math
import torch
import torch.nn as nn
"""
Dinh ら (2016) の RealNVP を小さく実装する例(32×32 のカラー画像、スケール 2 つ)
・アフィン結合層(式 4〜9):y = b⊙x + (1−b)⊙(x⊙exp(s(b⊙x)) + t(b⊙x))、対数ヤコビアンは Σ s
・マスク:チェッカーボード(座標の和が奇数で 1)と、squeeze の後のチャネル(前半が 1)を交互に反転
・マルチスケール:結合層 3(チェッカーボード)→ squeeze → 結合層 3(チャネル)→ 半分を z として出す(3.6 節)
・前処理:logit(α + (1−α)·x/256)、α = 0.05(4.1 節)。その対数ヤコビアンも尤度に含める
PyTorch に RealNVP の組み込みはない。s, t の中のバッチ正規化・重みの正規化と、結合層の出力のバッチ正規化(3.7 節)は省いている
"""
def checkerboard(h, w, parity):
ii, jj = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
return (((ii + jj) % 2) == parity).float()[None, None] # [1, 1, h, w]
def channel_mask(c, parity):
m = torch.zeros(1, c, 1, 1)
m[:, : c // 2] = 1.0
return m if parity == 1 else 1.0 - m
class ResNetST(nn.Module):
"""s と t を出すネットワーク(ReLU と残差接続の畳み込み)"""
def __init__(self, c, hidden=64, blocks=2):
super().__init__()
self.inp = nn.Conv2d(c, hidden, 3, padding=1)
self.blocks = nn.ModuleList([
nn.Sequential(nn.ReLU(), nn.Conv2d(hidden, hidden, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden, hidden, 3, padding=1))
for _ in range(blocks)])
self.out = nn.Conv2d(hidden, 2 * c, 3, padding=1)
self.s_scale = nn.Parameter(torch.zeros(1, c, 1, 1)) # s = (学習する倍率) × tanh(·)
def forward(self, x):
h = self.inp(x)
for blk in self.blocks:
h = h + blk(h)
s, t = self.out(torch.relu(h)).chunk(2, dim=1)
return self.s_scale * torch.tanh(s), t
class AffineCoupling(nn.Module):
def __init__(self, c, mask):
super().__init__()
self.register_buffer("b", mask)
self.net = ResNetST(c)
def forward(self, x): # x → y と対数ヤコビアン
s, t = self.net(self.b * x)
s, t = (1 - self.b) * s, (1 - self.b) * t # マスクが 1 の所は変えない
y = self.b * x + (1 - self.b) * (x * torch.exp(s) + t)
return y, s.flatten(1).sum(1)
def inverse(self, y): # y → x(式 8)。s, t の逆関数は要らない
s, t = self.net(self.b * y)
s, t = (1 - self.b) * s, (1 - self.b) * t
return self.b * y + (1 - self.b) * ((y - t) * torch.exp(-s))
def squeeze(x): # [B, C, H, W] → [B, 4C, H/2, W/2]
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): # squeeze の逆
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 RealNVP(nn.Module):
def __init__(self, c=3, size=32):
super().__init__()
h = size
# スケール 1(32×32×3)
self.s1_a = nn.ModuleList([AffineCoupling(c, checkerboard(h, h, k % 2)) for k in range(3)])
self.s1_b = nn.ModuleList([AffineCoupling(4 * c, channel_mask(4 * c, k % 2)) for k in range(3)])
# 最後のスケール(半分を出したあとの 16×16×6):チェッカーボードの結合層 4 つ
self.s2 = nn.ModuleList([AffineCoupling(2 * c, checkerboard(h // 2, h // 2, k % 2)) for k in range(4)])
def forward(self, x): # x → z、対数ヤコビアンの和
logdet = torch.zeros(x.size(0), device=x.device)
for layer in self.s1_a:
x, ld = layer(x); logdet = logdet + ld
x = squeeze(x)
for layer in self.s1_b:
x, ld = layer(x); logdet = logdet + ld
z1, x = x.chunk(2, dim=1) # 半分を z(1) として先に出す
for layer in self.s2:
x, ld = layer(x); logdet = logdet + ld
return torch.cat([z1.flatten(1), x.flatten(1)], dim=1), logdet
@torch.no_grad()
def sample(self, n, size=32):
z = torch.randn(n, 3 * size * size)
half = z.size(1) // 2
z1 = z[:, :half].view(n, 6, size // 2, size // 2)
x = z[:, half:].view(n, 6, size // 2, size // 2)
for layer in reversed(self.s2):
x = layer.inverse(x)
x = torch.cat([z1, x], dim=1)
for layer in reversed(self.s1_b):
x = layer.inverse(x)
x = unsqueeze(x)
for layer in reversed(self.s1_a):
x = layer.inverse(x)
return 256 * (torch.sigmoid(x) - 0.05) / 0.95 # 前処理の逆(0〜256 の画素の値)
ALPHA = 0.05
def preprocess(x_uint8):
"""x:0〜255 の整数の画素。一様ノイズで連続にし、logit で境界の影響を避ける"""
x = x_uint8.float() + torch.rand_like(x_uint8.float()) # [0, 256)
p = ALPHA + (1 - ALPHA) * x / 256
y = torch.log(p) - torch.log1p(-p) # logit(p)
# dy/dx = (1−α)/256 / (p(1−p)) の対数を全画素で足す
logdet = (math.log(1 - ALPHA) - math.log(256) - torch.log(p) - torch.log1p(-p)).flatten(1).sum(1)
return y, logdet
def bits_per_dim(model, x_uint8):
y, ld_pre = preprocess(x_uint8)
z, ld = model(y)
log_pz = -0.5 * (z.pow(2) + math.log(2 * math.pi)).sum(1) # 標準正規分布
log_px = log_pz + ld + ld_pre # 変数変換の公式(式 3)
dims = x_uint8[0].numel()
return (-log_px / (dims * math.log(2))).mean()
model = RealNVP()
opt = torch.optim.Adam(model.parameters(), lr=1e-3) # 論文は Adam の既定値
x = torch.randint(0, 256, (8, 3, 32, 32)) # 本来はデータセットの画像
loss = bits_per_dim(model, x)
opt.zero_grad()
loss.backward()
opt.step()
images = model.sample(4) # [4, 3, 32, 32]
よくある質問
Q. RealNVP は、なぜ尤度を近似なしで計算できるのですか?
A.
すべての変換が可逆で、その対数ヤコビアンを簡単に求められるからです。変数変換の公式により、logpX(x)=logpZ(f(x))+log∣det(∂f/∂x⊤)∣ と書けます。アフィン結合層のヤコビ行列は三角行列なので、行列式は対角成分の積で、対数ヤコビアンは s の出力の和になります。VAE のような下限ではなく、この値そのものを最大化して学習します。
Q. アフィン結合層の $s$ と $t$ は、なぜ複雑なネットワークでよいのですか?
A.
結合層の逆変換は xd+1:D=(yd+1:D−t(y1:d))⊙exp(−s(y1:d)) で、そのまま通した y1:d から s, t を計算し直すだけです。対数ヤコビアンにも、s と t のヤコビ行列は出てきません。s, t を逆に解く必要がないので、論文では深い畳み込みの ResNet を使っています。