python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Karras ら (2018) の StyleGAN の生成器の要(Figure 1 (b)、式 1、3.1 節、付録 B・C)を小さく実装する例
・マッピングネットワーク:z を正規化 → 全結合 8 層(Leaky ReLU 0.2)→ w(512 次元)
・合成ネットワーク:学習する定数 4×4×512 から始め、各層で 畳み込み → ノイズ(B)→ 活性化 → AdaIN(A)
・スタイルの混合(学習のとき)と、W での切り詰め(生成するとき)
PyTorch に StyleGAN の組み込みはない。学習率の均等化・双線形フィルタ・Progressive GAN の識別器と損失は省いている
(公式実装は GitHub の NVlabs/stylegan、TensorFlow)
"""
LATENT = 512
class MappingNetwork(nn.Module):
def __init__(self, depth=8):
super().__init__()
layers = []
for _ in range(depth):
layers += [nn.Linear(LATENT, LATENT), nn.LeakyReLU(0.2)]
self.net = nn.Sequential(*layers)
def forward(self, z):
z = z * torch.rsqrt(z.pow(2).mean(dim=1, keepdim=True) + 1e-8) # 入力の正規化(Normalize)
return self.net(z)
class AdaIN(nn.Module):
"""AdaIN(x_i, y) = y_s,i * (x_i − μ(x_i)) / σ(x_i) + y_b,i(式 1)"""
def __init__(self, channels):
super().__init__()
self.norm = nn.InstanceNorm2d(channels, affine=False) # 特徴マップを 1 枚ずつ正規化
self.affine = nn.Linear(LATENT, channels * 2) # A:w → スタイル y = (y_s, y_b)
nn.init.zeros_(self.affine.bias)
self.affine.bias.data[:channels] = 1.0 # y_s のバイアスは 1 で初期化(付録 C)
def forward(self, x, w):
y_s, y_b = self.affine(w)[:, :, None, None].chunk(2, dim=1)
return y_s * self.norm(x) + y_b
class NoiseInput(nn.Module):
"""1 チャネルのガウス雑音の画像に、チャネルごとの倍率(B)をかけて足す"""
def __init__(self, channels):
super().__init__()
self.scale = nn.Parameter(torch.zeros(1, channels, 1, 1)) # 倍率は 0 で初期化(付録 C)
def forward(self, x):
noise = torch.randn(x.size(0), 1, x.size(2), x.size(3), device=x.device)
return x + self.scale * noise
class StyleLayer(nn.Module):
def __init__(self, cin, cout, upsample=False):
super().__init__()
self.upsample = upsample
self.conv = nn.Conv2d(cin, cout, 3, padding=1)
self.noise, self.act, self.adain = NoiseInput(cout), nn.LeakyReLU(0.2), AdaIN(cout)
def forward(self, x, w):
if self.upsample:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
return self.adain(self.act(self.noise(self.conv(x))), w) # ノイズは非線形の前に足す
class SynthesisNetwork(nn.Module):
def __init__(self, channels=(512, 512, 256, 128)): # 4×4 → 8×8 → 16×16 → 32×32(例として小さく)
super().__init__()
c0 = channels[0]
self.const = nn.Parameter(torch.ones(1, c0, 4, 4)) # 学習する定数(1 で初期化)
self.noise0, self.act0, self.adain0 = NoiseInput(c0), nn.LeakyReLU(0.2), AdaIN(c0)
self.layers = nn.ModuleList([StyleLayer(c0, c0)]) # 4×4 の 2 層目
for cin, cout in zip(channels[:-1], channels[1:]): # 解像度ごとに 2 層
self.layers += [StyleLayer(cin, cout, upsample=True), StyleLayer(cout, cout)]
self.to_rgb = nn.Conv2d(channels[-1], 3, 1) # 1×1 の畳み込みで RGB に
self.num_styles = 1 + len(self.layers)
def forward(self, ws):
"""ws:[バッチ, 層の数, 512]。層ごとに使う w(スタイルの混合のため層ごとに持つ)"""
x = self.const.expand(ws.size(0), -1, -1, -1)
# 論文の図は定数の後の非線形の位置を描いていない。ここでは他の層とそろえて活性化をかけている
x = self.adain0(self.act0(self.noise0(x)), ws[:, 0])
for i, layer in enumerate(self.layers, start=1):
x = layer(x, ws[:, i])
return self.to_rgb(x)
class StyleGenerator(nn.Module):
def __init__(self):
super().__init__()
self.mapping, self.synthesis = MappingNetwork(), SynthesisNetwork()
def forward(self, z1, z2=None, mix_prob=0.9, psi=1.0, w_avg=None):
n = self.synthesis.num_styles
w1 = self.mapping(z1)
ws = w1[:, None].repeat(1, n, 1)
if self.training and z2 is not None and torch.rand(()) < mix_prob:
# スタイルの混合:ランダムな層を境に、後ろの層は w2 のスタイルを使う(論文の FFHQ は 90%)
cut = int(torch.randint(1, n, ()))
ws[:, cut:] = self.mapping(z2)[:, None]
if psi < 1.0 and w_avg is not None:
ws = w_avg + psi * (ws - w_avg) # W での切り詰め:w' = w̄ + ψ(w − w̄)
return self.synthesis(ws)
G = StyleGenerator()
# 学習のとき:G.train()。マッピングネットワークの学習率は 100 分の 1 にする(付録 C)
lr = 1e-3
opt = torch.optim.Adam([
{"params": G.synthesis.parameters(), "lr": lr},
{"params": G.mapping.parameters(), "lr": lr * 0.01},
], betas=(0.0, 0.99)) # betas はこの例で決めた値
fake = G(torch.randn(4, LATENT), torch.randn(4, LATENT)) # [4, 3, 32, 32]
# 生成のとき:w の平均を求めて切り詰める
G.eval()
with torch.no_grad():
w_avg = G.mapping(torch.randn(10000, LATENT)).mean(dim=0)
images = G(torch.randn(8, LATENT), psi=0.7, w_avg=w_avg)