import torchvision16.5 敵対的画像生成
16.1 節 の多層パーセプトロン(multilayer perceptron)は、識別可能な \(28 \times 28\) の Fashion-MNIST のシルエットを生成できたものの、全結合層が空間的局所性(spatial locality)を無視するため、テクスチャはざらついていた。\(64 \times 64\) の RGB 画像を生成するには、100 次元の潜在ベクトルから \(12{,}288\) 個のピクセル値を生成する必要がある。ここで 2 つの疑問が生じる。
- 敵対的画像生成において、どのような畳み込みアーキテクチャであれば安定して訓練できるのか。
- 尤度が利用できない状況で、画像生成器をどのように定量的に評価・比較できるのか。
畳み込みを用いた生成器と識別器は、Radford ほか (2015年) の Deep Convolutional GAN(DCGAN)によって初めて GAN を自然画像へとスケールさせた。その後、汎用的な画像生成では拡散モデル(diffusion model、第 17 章)が主流となったが、畳み込み識別器と特徴空間での評価指標は、現代の画像トークナイザや 1 ステップの蒸留生成器(16.7 節)において依然として中心的な役割を担っている。
本節では、40,597 枚の \(64 \times 64\) Pokémon スプライトからなるデータセット上でモデルを訓練する。まず 2015 年の古典的な DCGAN アーキテクチャを実装し、続いて R3GAN (Huang ほか 2024年) に着想を得た最小構成の正規化なし畳み込みバックボーンを構築する。この正規化なしバックボーンを 3 つの目的関数(ペナルティなしの古典的ロジスティック損失、\(R_1 + R_2\) ペナルティ付きの古典的ロジスティック損失、\(R_1 + R_2\) ペナルティ付きの相対論的ペアリング損失)のもとで訓練することで、ゼロ中心勾配ペナルティ(zero-centered gradient penalty、16.4 節)がバッチ正規化(batch normalization)やその他のアーキテクチャ上の経験則を代替できるかを検証する。その後、特徴空間における標準的な評価指標であるフレシェ距離(Fréchet Distance、FID)、Kernel Inception Distance(KID)、および \(k\)-NN の適合率(precision)と再現率(recall)を実装し、潜在空間での補間と識別器の過学習(overfitting)を調べる。
# Deterministic GPU kernels; JAX reads XLA_FLAGS once, before the imports
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_deterministic_ops=true').strip()16.5.1 DCGAN アーキテクチャ
DCGAN (Radford ほか 2015年) は、16.1 節 の古典的な非飽和ロジスティック目的関数を維持しつつ、以下の一連のアーキテクチャ規約によって畳み込みネットワークの訓練を安定化させる。
- 生成器における空間的なアップサンプリングには転置畳み込み(transposed convolution、分数ストライド畳み込み)を用い、識別器におけるダウンサンプリングにはプーリング層の代わりにストライド付き畳み込み(strided convolution)を用いる。
- 生成器の出力層と識別器の入力層を除くすべての畳み込みの後に、バッチ正規化を適用する。
- 生成器は隠れ層の活性化関数に ReLU、出力の活性化関数に \(\tanh\)(\([-1, 1]\) のピクセル値に対応)を用いるのに対し、識別器は勾配が 0 になるデッドゾーンを防ぐため、全体にわたって Leaky ReLU(\(\text{slope} = 0.2\))を用いる。
- 重みは \(\mathcal{N}(0, 0.02^2)\) から初期化し、Adam では通常より小さいモメンタム \(\beta_1 = 0.5\) を用いる。
16.5.1.1 Pokémon スプライトデータセット
ここで用いるデータセットは、pokemondb.net から取得した 721 種の Pokémon の RGB スプライト 40,597 枚で構成されており、\(64 \times 64\) にリサイズしたうえで \([-1, 1]\) にスケーリングしてある。データセット全体がメモリに収まるため、load_pokemon で単一のテンソルへとデコードする。
d2l.DATA_HUB['pokemon'] = (d2l.DATA_URL + 'pokemon.zip',
'c065c0e2593b8b161a2d7873e42418bf6a21106c')
def load_pokemon(resolution=64):
"""All Pokemon sprites as one (n, 3, h, w) tensor in [-1, 1]."""
import warnings
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((resolution, resolution)),
torchvision.transforms.PILToTensor()])
dataset = torchvision.datasets.ImageFolder(
d2l.download_extract('pokemon'), transform=transform)
loader = torch.utils.data.DataLoader(
dataset, batch_size=512, num_workers=d2l.get_dataloader_workers())
with warnings.catch_warnings(): # palette sprites with transparency
warnings.filterwarnings('ignore', message='Palette images')
return torch.cat([X for X, _ in loader]).float() / 127.5 - 1
images = load_pokemon()
images.shapetorch.Size([40597, 3, 64, 64])
d2l.DATA_HUB['pokemon'] = (d2l.DATA_URL + 'pokemon.zip',
'c065c0e2593b8b161a2d7873e42418bf6a21106c')
def load_pokemon(resolution=64):
"""All Pokemon sprites as one (n, h, w, 3) array in [-1, 1]."""
import warnings
from PIL import Image
data_dir = d2l.download_extract('pokemon')
files = sorted(os.path.join(root, f)
for root, _, names in os.walk(data_dir) for f in names
if f.lower().endswith(('.png', '.jpg', '.jpeg')))
def load(path):
img = Image.open(path).convert('RGB')
return np.asarray(img.resize((resolution, resolution), Image.BILINEAR),
dtype=np.float32)
with warnings.catch_warnings(): # palette sprites with transparency
warnings.filterwarnings('ignore', message='Palette images')
return np.stack([load(f) for f in files]) / 127.5 - 1
images = load_pokemon()
images.shape(40597, 64, 64, 3)
固定された順列によって画像の 10 分の 1 を取り分けておき、これらは訓練には一切使用しない。この画像は、生成画像をスコアリングする際の比較対象となる実サンプルであり、またクリティックが未知の画像よりも訓練画像に高いスコアを付けていないかを確かめる指標にもなる。分割は種ごとではなく画像ごとに行うため、同じ種の別バリエーションが訓練側とホールドアウト側の両方に含まれることがあり、訓練スプライトを丸写しした生成器がホールドアウト側の別バリエーションの近くに着地する可能性はある。
device = d2l.try_gpu()
perm = np.random.default_rng(12345).permutation(len(images))
n_holdout = len(images) // 10
train_imgs = images[perm[n_holdout:]].to(device)
holdout_imgs = images[perm[:n_holdout]].to(device)
print(f'{len(train_imgs)} training and {len(holdout_imgs)} held-out images')
d2l.show_images(train_imgs[:20].cpu().permute(0, 2, 3, 1) / 2 + 0.5,
num_rows=4, num_cols=5);36538 training and 4059 held-out images

perm = np.random.default_rng(12345).permutation(len(images))
n_holdout = len(images) // 10
train_imgs = jnp.asarray(images[perm[n_holdout:]])
holdout_imgs = jnp.asarray(images[perm[:n_holdout]])
print(f'{len(train_imgs)} training and {len(holdout_imgs)} held-out images')
d2l.show_images(np.asarray(train_imgs[:20]) / 2 + 0.5,
num_rows=4, num_cols=5);36538 training and 4059 held-out images

16.5.1.2 転置畳み込みとバッチ正規化
100 チャネルの \(1 \times 1\) 特徴マップを \(64 \times 64\) の画像へとアップサンプリングするため、DCGAN は転置畳み込み(32.10 節 (英語版))を用いる。カーネルサイズ \(k\)、ストライド \(s\)、パディング \(p\) の転置畳み込みは、\(n \times n\) の空間グリッドを次の辺長を持つ出力へと写像する。
\[s(n - 1) + k - 2p. \tag{16.5.1}\]
\(k = 4, s = 2, p = 1\) とすると、各層は空間解像度を 2 倍にする(\(n \to 2n\))。最初の層(\(k = 4, s = 1, p = 0\))では、\(1 \times 1\) の入力が \(4 \times 4\) へと拡大される。逆に、\(k = 4, s = 2, p = 1\) のストライド付き畳み込みは空間解像度を半分にする。
図 16.5.1 に示すように、DCGAN の生成器は 5 つの転置畳み込みを連ねて解像度を \(1 \to 4 \to 8 \to 16 \to 32 \to 64\) と拡大し、各ステージでチャネル幅を半分にしながら最終的に 3 つの RGB チャネルを出力する。識別器はこの階層構造を反転させ、ストライド付き畳み込みによって単一の \(1 \times 1\) ロジットへと集約する。
def G_block(c_in, c_out, stride=2, padding=1):
"""Transposed convolution (kernel 4), batch norm, ReLU."""
return nn.Sequential(
nn.ConvTranspose2d(c_in, c_out, 4, stride, padding, bias=False),
nn.BatchNorm2d(c_out), nn.ReLU())
def D_block(c_in, c_out, norm=True):
"""Strided convolution (kernel 4), batch norm, leaky ReLU."""
return nn.Sequential(
nn.Conv2d(c_in, c_out, 4, 2, 1, bias=False),
nn.BatchNorm2d(c_out) if norm else nn.Identity(), nn.LeakyReLU(0.2))conv_init = nnx.initializers.normal(0.02) # DCGAN: kernels from N(0, 0.02^2)
def bn_scale_init(key, shape, dtype=jnp.float32):
return 1 + 0.02 * jax.random.normal(key, shape, dtype) # N(1, 0.02^2)
def batch_norm(c, rngs):
# Running averages decay 0.9; the variance is computed in two passes
return nnx.BatchNorm(c, momentum=0.9, use_fast_variance=False,
scale_init=bn_scale_init, rngs=rngs)
def G_block(c_in, c_out, rngs, stride=2, padding='SAME'):
"""Transposed convolution (kernel 4), batch norm, ReLU."""
return nnx.Sequential(
nnx.ConvTranspose(c_in, c_out, (4, 4), strides=(stride, stride),
padding=padding, use_bias=False,
kernel_init=conv_init, rngs=rngs),
batch_norm(c_out, rngs), nnx.relu)
def D_block(c_in, c_out, rngs, norm=True):
"""Strided convolution (kernel 4), batch norm, leaky ReLU."""
return nnx.Sequential(
nnx.Conv(c_in, c_out, (4, 4), strides=(2, 2), padding='SAME',
use_bias=False, kernel_init=conv_init, rngs=rngs),
batch_norm(c_out, rngs) if norm else (lambda x: x),
lambda x: nnx.leaky_relu(x, 0.2))4 段の G_block に最終段の転置畳み込みと tanh を重ねて net_G を構成し、4 段の D_block(最初のブロックではバッチ正規化を省く)と \(4 \times 4\) 畳み込みによって net_D を構成する。2 個の 100 次元潜在ベクトルに対する順伝播で、それぞれの出力形状を確認しよう。
torch.manual_seed(0)
net_G = nn.Sequential( # (100,)
nn.Unflatten(1, (100, 1, 1)), # (100, 1, 1)
G_block(100, 512, stride=1, padding=0), # (512, 4, 4)
G_block(512, 256), G_block(256, 128), G_block(128, 64), # (64, 32, 32)
nn.ConvTranspose2d(64, 3, 4, 2, 1, bias=False), nn.Tanh()).to(device)
net_D = nn.Sequential( # (3, 64, 64)
D_block(3, 64, norm=False), # (64, 32, 32)
D_block(64, 128), D_block(128, 256), D_block(256, 512), # (512, 4, 4)
nn.Conv2d(512, 1, 4, bias=False)).to(device) # (1, 1, 1)
X = net_G(torch.zeros(2, 100, device=device))
print(X.shape, net_D(X).shape)torch.Size([2, 3, 64, 64]) torch.Size([2, 1, 1, 1])
rngs = nnx.Rngs(0)
net_G = nnx.Sequential( # (100,)
lambda z: z.reshape(-1, 1, 1, 100), # (1, 1, 100)
G_block(100, 512, rngs, stride=1, padding='VALID'), # (4, 4, 512)
G_block(512, 256, rngs), G_block(256, 128, rngs),
G_block(128, 64, rngs), # (32, 32, 64)
nnx.ConvTranspose(64, 3, (4, 4), strides=(2, 2), padding='SAME',
use_bias=False, kernel_init=conv_init, rngs=rngs),
nnx.tanh) # (64, 64, 3)
net_D = nnx.Sequential( # (64, 64, 3)
D_block(3, 64, rngs, norm=False), # (32, 32, 64)
D_block(64, 128, rngs), D_block(128, 256, rngs),
D_block(256, 512, rngs), # (4, 4, 512)
nnx.Conv(512, 1, (4, 4), padding='VALID', use_bias=False,
kernel_init=conv_init, rngs=rngs)) # (1, 1, 1)
X = net_G(jnp.zeros((2, 100)))
print(X.shape, net_D(X).shape)(2, 64, 64, 3) (2, 1, 1, 1)
16.5.1.3 古典的損失による訓練
クリティックのロジスティック回帰ステップと生成器の非飽和ステップを交互に繰り返す d2l.train_gan(16.1 節)のループは、画像にもそのまま適用できる。ここでは DCGAN の設定に従いつつ、ミニバッチサイズを元論文の 128 枚より大きい 256 枚とし、学習率 \(2 \cdot 10^{-4}\)、\(\beta_1 = 0.5\)、畳み込みカーネルの初期値を \(\mathcal{N}(0, 0.02^2)\) からの抽出とする。また、著者らの公開コードと同様に、バッチ正規化のスケールは \(\mathcal{N}(1, 0.02^2)\) から、オフセットは 0 から開始する。
def dcgan_init(module):
if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
nn.init.normal_(module.weight, 0, 0.02)
elif isinstance(module, nn.BatchNorm2d):
nn.init.normal_(module.weight, 1, 0.02)
nn.init.zeros_(module.bias)
for net in (net_D, net_G):
net.apply(dcgan_init)
dataset = torch.utils.data.TensorDataset(train_imgs)
# Sample whole minibatches of indices, so that the GPU tensor is indexed
# once per minibatch rather than once per image
sampler = torch.utils.data.BatchSampler(
torch.utils.data.RandomSampler(dataset), 256, drop_last=True)
data_iter = torch.utils.data.DataLoader(dataset, sampler=sampler,
batch_size=None)# The training images from the host array: the loader keeps them there
data_iter = d2l.ArrayLoader((images[perm[n_holdout:]],), 256, shuffle=True,
drop_last=True, key=jax.random.key(3))サンプリングには、生成器の最終ステップの重みではなく直近の重みの平均を用いる。EMA はパラメータの指数移動平均(exponential moving average)を保持し、各ステップの後に次の式で更新する。
\[\bar\theta \leftarrow \beta\, \bar\theta + (1 - \beta)\, \theta, \qquad \beta = 2^{-1/n_{1/2}}, \tag{16.5.2}\]
これにより、過去のステップの重みは半減期(half-life)である \(n_{1/2}\) ステップごとに半減する。ゲームの反復解は均衡点の周りを回転するため(16.4 節)、個々の反復解よりもその平均のほうが均衡点の近くに位置する。なお、バッチ正規化の統計量はパラメータではなく、移動平均モデルは訓練中のネットワークから統計量をそのままコピーする。しかし、コピーされた統計量は平均化された重みではなく訓練中の重みに対応しているため、訓練終了後に再推定する。
class EMA:
"""Exponential moving average of a model's parameters, given as a
half-life in steps. Buffers such as batch-norm statistics are copied;
the average is kept in evaluation mode."""
def __init__(self, model, half_life):
import copy # the d2l library preamble does not import it
self.model = copy.deepcopy(model).requires_grad_(False).eval()
self.decay = 0.5 ** (1 / half_life)
def update(self, model):
with torch.no_grad():
for avg, p in zip(self.model.parameters(), model.parameters()):
avg.lerp_(p, 1 - self.decay)
for avg, b in zip(self.model.buffers(), model.buffers()):
avg.copy_(b)
class EMA:
"""Exponential moving average of a model's parameters, given as a
half-life in steps. Other state such as batch-norm statistics is copied;
the average is kept in evaluation mode."""
def __init__(self, model, half_life):
self.model = nnx.clone(model)
self.model.eval()
self.decay = 0.5 ** (1 / half_life)
def update(self, model):
self.average(self.model, model, self.decay)
@staticmethod
@nnx.jit
def average(avg, model, decay):
"""Move the parameters of avg toward those of model, in place."""
params = jax.tree.map(lambda a, p: decay * a + (1 - decay) * p,
nnx.state(avg, nnx.Param),
nnx.state(model, nnx.Param))
nnx.update(avg, params, nnx.state(model, nnx.Not(nnx.Param)))本節の後半の実験では 32,000 枚の画像にわたって平均をとり、これはバッチサイズ 64 では 500 ステップの半減期に相当する。バッチサイズ 256 では、同じ 32,000 枚の画像は 125 ステップに相当し、今回の訓練全体の 2,840 ステップ(20 エポック、各 142 ステップ)の 20 分の 1 未満である。
出力されるクリティック損失は 16.1 節 における 2 つのバッチ平均の和であり、均衡点では \(2 \log 2 \approx 1.39\) に等しく、そこでの生成器の損失は \(\log 2 \approx 0.69\) に等しくなる。
ema = EMA(net_G, half_life=125) # 32,000 images, as in the later runs
history = d2l.train_gan(net_D, net_G, data_iter, num_epochs=20,
latent_dim=100, lr_D=0.0002, lr_G=0.0002, seed=1,
ema=ema)
loss_D, loss_G = history[-1]
print(f'last epoch: loss_D {loss_D:.3f}, loss_G {loss_G:.3f}')last epoch: loss_D 0.252, loss_G 3.188
ema = EMA(net_G, half_life=125) # 32,000 images, as in the later runs
history = d2l.train_gan(net_D, net_G, data_iter, num_epochs=20,
latent_dim=100, lr_D=0.0002, lr_G=0.0002, seed=1,
ema=ema)
loss_D, loss_G = history[-1]
print(f'last epoch: loss_D {loss_D:.3f}, loss_G {loss_G:.3f}')last epoch: loss_D 0.427, loss_G 3.027
次のセルでは、平均化された生成器を訓練モードにして新規の潜在コード 100 バッチを入力し、移動平均モデルのバッチ正規化統計量を再推定する。移動平均の統計量は 1 バッチあたり 0.1 の割合で過去の値を忘却するため、コピーされた値に残る重みは \(0.9^{100} \approx 3 \cdot 10^{-5}\)、すなわち実質的に 0 となる。
ema.model.train() # batch-norm statistics for the averaged weights
with torch.no_grad(): # 100 batches; running averages forget at rate 0.1
for _ in range(100):
ema.model(torch.randn(256, 100, device=device))
ema.model.eval();ema.model.train() # batch-norm statistics for the averaged weights
# 100 batches; running averages forget at rate 0.1
for key in jax.random.split(jax.random.key(4), 100):
ema.model(jax.random.normal(key, (256, 100)))
ema.model.eval()各画像が自身の潜在コードのみに依存するよう、サンプリングは評価モードで行う。
with torch.no_grad():
fake = ema.model(torch.randn(20, 100, device=device))
d2l.show_images(fake.cpu().permute(0, 2, 3, 1) / 2 + 0.5,
num_rows=4, num_cols=5);
fake = ema.model(jax.random.normal(jax.random.key(2), (20, 100)))
d2l.show_images(np.asarray(fake) / 2 + 0.5, num_rows=4, num_cols=5);
生成されたスプライトは、やや斑状のテクスチャが見られるものの、白背景の上に多様なシルエットと配色を示している。なお、識別器の損失(\(\sim 0.25\text{--}0.45\))は \(2\log 2 \approx 1.39\) を大きく下回ったままであるが、モード崩壊(mode collapse)は引き起こしていない。
16.5.2 正規化なしバックボーン
DCGAN 以降の数年間で、大規模な画像 GAN には数多くのアーキテクチャ上の安定化手法が積み重ねられていった(StyleGAN2 (Karras, Laine, ほか 2020年) は 10 種類の個別技術を組み合わせていた)。これに対し R3GAN (Huang ほか 2024年) は、目的関数を \(R_1 + R_2\) 勾配ペナルティと相対論的ペアリング損失で正則化すれば、そうした場当たり的なアーキテクチャ上の工夫を取り除けることを実証した。とりわけ、\(R_1\) と \(R_2\) を用いる際には識別器からバッチ正規化を省くことが不可欠である。バッチ正規化はミニバッチ内のサンプル同士を結合してしまうため、サンプルごとの入力勾配の計算が成り立たなくなるからである。
16.5.2.1 アーキテクチャとファンイン初期化
最小構成の畳み込みバックボーン(図 16.5.2)を、正規化層も出力の \(\tanh\) も用いずに構築する。
- 生成器は、学習される \(4 \times 4 \times 128\) の定数テンソルと \(z\) の線形射影(\(4 \times 4 \times 100\)、さらに 16.6 節 のクラス条件付けで用いる任意の追加チャネル)を連結し、4 回(\(4 \to 8 \to 16 \to 32 \to 64\))にわたって双線形補間(bilinear interpolation)とそれに続く \(3 \times 3\) 畳み込みおよび Leaky ReLU(\(\text{slope} = 0.2\))でアップサンプリングする。双線形アップサンプリングの後に \(3 \times 3\) 畳み込みを適用することで、転置畳み込みの不均一な重なりによって生じるチェッカーボードアーティファクト(図 16.5.3)を回避できる (Odena ほか 2016年)。
- クリティックはこの構造を反転させ、\(3 \times 3\) 畳み込み、Leaky ReLU、および双線形ダウンサンプリングによって \(4 \times 4\) の特徴マップ \(\phi(x)\) まで縮小し、最後に線形ヘッドを通す。
- バッチ正規化なしで各層にわたって活性化値の分散を保つため、すべての重みには He のファンイン初期化 (He ほか 2015年) を傾き \(0.2\) の Leaky ReLU 向けにスケーリングして用いる(分散は \(2 / ((1 + 0.2^2)\,n_{\mathrm{in}})\))。
def fan_in_init(module):
"""Fan-in normal weights with the leaky-ReLU gain, zero offsets."""
if isinstance(module, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(module.weight, a=0.2)
nn.init.zeros_(module.bias)
class Generator(nn.Module):
"""Learned 4x4 constant + projected latent (+ extra 4x4 input maps),
bilinearly upsampled to resolution x resolution; no normalization."""
def __init__(self, latent_dim, resolution, base_ch, *, extra_ch=0,
const_ch=128):
super().__init__()
self.latent_dim = latent_dim
self.const = nn.Parameter(torch.randn(1, const_ch, 4, 4))
self.z_proj = nn.Linear(latent_dim, 16 * latent_dim)
self.mix = nn.Conv2d(const_ch + latent_dim + extra_ch, base_ch, 3,
padding=1)
num_stages = int(np.log2(resolution / 4)) # 64: four doublings
chans = [base_ch // 2 ** i for i in range(num_stages + 1)]
self.stages = nn.ModuleList(
[nn.Conv2d(c_in, c_out, 3, padding=1)
for c_in, c_out in zip(chans[:-1], chans[1:])])
self.to_rgb = nn.Conv2d(chans[-1], 3, 3, padding=1)
self.act = nn.LeakyReLU(0.2)
self.apply(fan_in_init)
def forward(self, z, extra=None):
zc = self.z_proj(z).reshape(-1, self.latent_dim, 4, 4)
const = self.const.expand(z.shape[0], -1, -1, -1)
maps = [const, zc] + ([] if extra is None else [extra])
x = self.act(self.mix(torch.cat(maps, dim=1)))
for conv in self.stages: # 4 -> 8 -> ... -> 64
x = F.interpolate(x, scale_factor=2, mode='bilinear')
x = self.act(conv(x))
return self.to_rgb(x) # no tanh: raw output
# Fan-in initialization with the leaky-ReLU gain (normal, not truncated)
fan_in_init = nnx.initializers.variance_scaling(2 / (1 + 0.2 ** 2),
'fan_in', 'normal')
class Generator(nnx.Module):
"""Learned 4x4 constant + projected latent (+ extra 4x4 input maps),
bilinearly upsampled to resolution x resolution; no normalization."""
def __init__(self, latent_dim, resolution, base_ch, *, extra_ch=0,
const_ch=128, rngs):
self.latent_dim = latent_dim
self.const = nnx.Param(
jax.random.normal(rngs.params(), (1, 4, 4, const_ch)))
self.z_proj = nnx.Linear(latent_dim, 16 * latent_dim,
kernel_init=fan_in_init, rngs=rngs)
self.mix = nnx.Conv(const_ch + latent_dim + extra_ch, base_ch,
(3, 3), padding='SAME', kernel_init=fan_in_init,
rngs=rngs)
num_stages = int(np.log2(resolution / 4)) # 64: four doublings
chans = [base_ch // 2 ** i for i in range(num_stages + 1)]
self.stages = nnx.List(
[nnx.Conv(c_in, c_out, (3, 3), padding='SAME',
kernel_init=fan_in_init, rngs=rngs)
for c_in, c_out in zip(chans[:-1], chans[1:])])
self.to_rgb = nnx.Conv(chans[-1], 3, (3, 3), padding='SAME',
kernel_init=fan_in_init, rngs=rngs)
def __call__(self, z, extra=None):
zc = self.z_proj(z).reshape(-1, 4, 4, self.latent_dim)
const = jnp.broadcast_to(self.const[...],
(z.shape[0],) + self.const.shape[1:])
maps = [const, zc] + ([] if extra is None else [extra])
x = nnx.leaky_relu(self.mix(jnp.concatenate(maps, axis=-1)), 0.2)
for conv in self.stages: # 4 -> 8 -> ... -> 64
b, h, w, c = x.shape
x = jax.image.resize(x, (b, 2 * h, 2 * w, c), method='bilinear')
x = nnx.leaky_relu(conv(x), 0.2)
return self.to_rgb(x) # no tanh: raw outputクリティックは生成器と対称な構造を持つ。畳み込み、Leaky ReLU、双線形ダウンサンプリングからなる 4 つのステージで \(64 \times 64\) の画像を \(4 \times 4\) へと縮小し、混合用の畳み込みと線形ヘッドによって 1 つのスコアを返す。
class Discriminator(nn.Module):
"""Critic that mirrors the generator: conv + leaky ReLU + bilinear
downsampling to a 4x4 feature map phi(x), then a linear head on the
flattened map."""
def __init__(self, resolution, base_ch):
super().__init__()
num_stages = int(np.log2(resolution / 4))
chans = [3] + [base_ch * 2 ** i for i in range(num_stages)]
self.stages = nn.ModuleList(
[nn.Conv2d(c_in, c_out, 3, padding=1)
for c_in, c_out in zip(chans[:-1], chans[1:])])
self.mix = nn.Conv2d(chans[-1], 2 * chans[-1], 3, padding=1)
self.head = nn.Linear(2 * chans[-1] * 4 * 4, 1)
self.act = nn.LeakyReLU(0.2)
self.apply(fan_in_init)
def phi(self, x):
for conv in self.stages: # 64 -> 32 -> ... -> 4
x = F.interpolate(self.act(conv(x)), scale_factor=0.5,
mode='bilinear', antialias=True)
return self.act(self.mix(x))
def forward(self, x):
return self.head(self.phi(x).flatten(1))
for net in (Generator(latent_dim=100, resolution=64, base_ch=512),
Discriminator(resolution=64, base_ch=32)):
print(f'{type(net).__name__}: {d2l.num_params(net)} parameters')Generator: 2782851 parameters
Discriminator: 1576769 parameters
class Discriminator(nnx.Module):
"""Critic that mirrors the generator: conv + leaky ReLU + bilinear
downsampling to a 4x4 feature map phi(x), then a linear head on the
flattened map."""
def __init__(self, resolution, base_ch, *, rngs):
num_stages = int(np.log2(resolution / 4))
chans = [3] + [base_ch * 2 ** i for i in range(num_stages)]
self.stages = nnx.List(
[nnx.Conv(c_in, c_out, (3, 3), padding='SAME',
kernel_init=fan_in_init, rngs=rngs)
for c_in, c_out in zip(chans[:-1], chans[1:])])
self.mix = nnx.Conv(chans[-1], 2 * chans[-1], (3, 3),
padding='SAME', kernel_init=fan_in_init,
rngs=rngs)
self.head = nnx.Linear(2 * chans[-1] * 4 * 4, 1,
kernel_init=fan_in_init, rngs=rngs)
def phi(self, x):
for conv in self.stages: # 64 -> 32 -> ... -> 4
x = nnx.leaky_relu(conv(x), 0.2)
b, h, w, c = x.shape
x = jax.image.resize(x, (b, h // 2, w // 2, c),
method='bilinear')
return nnx.leaky_relu(self.mix(x), 0.2)
def __call__(self, x):
return self.head(self.phi(x).reshape(x.shape[0], -1))
for net in (Generator(100, 64, 512, rngs=nnx.Rngs(0)),
Discriminator(64, 32, rngs=nnx.Rngs(0))):
print(f'{type(net).__name__}: {d2l.num_params(net)} parameters')Generator: 2782851 parameters
Discriminator: 1576769 parameters
パラメータ数は、生成器が \(\sim 2.8\text{M}\)、クリティックが \(\sim 1.6\text{M}\) である。
16.5.3 統制された損失の比較
16.5.3.1 3 つの実験群
正規化なしバックボーンを同一の初期重みから 3 回訓練する。Adam(\(\beta_1 = 0, \beta_2 = 0.99, \text{lr} = 2 \times 10^{-4}\))、バッチサイズ 64、ランダム水平反転、および EMA(\(\text{half-life} = 500\) ステップ)を共通に用い、次の訓練目的関数のみを変化させる。
\[L(D) + \frac{\gamma}{2}\Big(\mathbb{E}_x\big[\|\nabla_x D(x)\|^2\big] + \mathbb{E}_{x'}\big[\|\nabla_{x'} D(x')\|^2\big]\Big), \tag{16.5.3}\]
ここで、\(L(D)\) は古典的ロジスティック損失(d2l.gan_loss_D)または相対論的ペアリング損失(d2l.rpgan_loss_D)のいずれかであり、生成器はそれに対応する非飽和損失を用いる。各実験群の設定は次のとおりである。
| 実験群 | クリティック損失 | 勾配ペナルティ | ステップ数 |
|---|---|---|---|
NS |
古典的ロジスティック | \(\gamma = 0\)(なし) | 6,000 |
NS + R1 + R2 |
古典的ロジスティック | \(\gamma = 10\) | 12,000 |
RpGAN + R1 + R2 |
相対論的ペアリング | \(\gamma = 10\) | 12,000 |
最初の 2 つの実験群を比較することで \(R_1 + R_2\) 勾配ペナルティの効果が切り分けられ(ペナルティなしの実験群は 6,000 ステップよりかなり前に崩壊するため、6,000 ステップで打ち切る)、2 番目と 3 番目の実験群を比較することでペアワイズランキングの効果が切り分けられる(演習問題 1 では、画像解像度に対する \(\gamma\) のスケーリングを解析する)。訓練ループは保存用の 2 つの補助関数で支える。すなわち、sample_real は水平反転を伴うランダムなミニバッチを抽出し、pair_stats はペアワイズランキング正解率 \(\hat P(D(x) > D(x'))\) と平均の相対論的ランク重み \(w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))]\) を計算する。
def sample_real(images, n, labels=None):
"""Draw a training batch with random horizontal flips; return it with
its labels (None without labels)."""
idx = torch.randint(0, len(images), (n,), device=images.device)
batch = images[idx]
flip = torch.rand(n, device=images.device) < 0.5
batch = torch.where(flip.view(-1, 1, 1, 1), batch.flip(-1), batch)
return batch, (None if labels is None else labels[idx])
def pair_stats(net_D, real, fake, y=None):
"""Ranking accuracy P(D(x) > D(x')) and mean rank weight
E[sigma(D(x') - D(x))] over aligned (real, generated) pairs; given
labels y, the critic is D(., y)."""
critic = net_D if y is None else lambda x: net_D(x, y)
with torch.no_grad():
diff = critic(fake) - critic(real)
return float((diff < 0).float().mean()), float(torch.sigmoid(diff).mean())
def sample_real(key, images, n, labels=None):
"""Draw a training batch with random horizontal flips; return it with
its labels (None without labels)."""
k1, k2 = jax.random.split(key)
idx = jax.random.randint(k1, (n,), 0, len(images))
batch = images[idx]
flip = jax.random.bernoulli(k2, 0.5, (n,))
batch = jnp.where(flip[:, None, None, None], batch[:, :, ::-1, :], batch)
return batch, (None if labels is None else labels[idx])
def pair_stats(net_D, real, fake, y=None):
"""Ranking accuracy P(D(x) > D(x')) and mean rank weight
E[sigma(D(x') - D(x))] over aligned (real, generated) pairs; given
labels y, the critic is D(., y)."""
critic = net_D if y is None else lambda x: net_D(x, y)
diff = critic(fake) - critic(real)
return float((diff < 0).mean()), float(jax.nn.sigmoid(diff).mean())JAX では、まず r3gan_step をコンパイルし、d2l.critic_step と d2l.generator_step を訓練反復あたり 1 回の JIT コンパイル済み呼び出しへとまとめる。
@nnx.jit(static_argnums=(4, 5))
def r3gan_step(net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma,
X, z, y, X2, z2, y2):
"""One critic step on X against G(z), one generator step on (X2, z2);
generated images take the labels y, y2 (None: unconditional). Return
the critic loss, R1, R2 and the generator loss."""
fake = net_G(z) if y is None else net_G(z, y)
loss_d, r1, r2 = d2l.critic_step(net_D, opt_D, loss_D, X, fake, gamma, y)
loss_g = d2l.generator_step(net_G, opt_G, loss_G, net_D, X2, z2, y2)
return loss_d, r1, r2, loss_g保存されるループ train_r3gan は、反転された実画像バッチ上で d2l.critic_step と d2l.generator_step(16.4 節)を交互に実行し、各ステップの後に EMA 生成器を更新する。クリティックのステップは \(R_1\) と \(R_2\) のバッチ平均を返すため、実画像に対するクリティックの急峻さ \(\mathbb{E}_x\|\nabla_x D(x)\|^2\) はすべての実験群で記録される(最初の実験群では重み \(\gamma = 0\))。さらに 250 ステップごとに、新規の 256 ペアに対して pair_stats を適用する。
def train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images,
labels=None, *, eval_images=None, eval_labels=None,
eval_size=256, batch_size=64, lr=2e-4, half_life=500,
log_every=250, seed=None):
"""Train with Adam (beta_1 = 0), alternating critic_step and
generator_step on flipped real batches; a generated batch takes the
labels of its real batch, if any. Every log_every steps, log the losses,
R1, R2 and pair_stats on fresh pairs from eval_images (default: images).
Return the EMA of the generator and the history, a dict of arrays."""
if seed is not None:
torch.manual_seed(seed)
if eval_images is None:
eval_images, eval_labels = images, labels
opt_G, opt_D = [torch.optim.Adam(net.parameters(), lr, betas=(0.0, 0.99))
for net in (net_G, net_D)]
noise = lambda n: torch.randn(n, net_G.latent_dim, device=images.device)
generate = lambda z, y: net_G(z) if y is None else net_G(z, y)
ema = EMA(net_G, half_life)
history = {k: [] for k in ('step', 'loss_D', 'loss_G', 'R1', 'R2',
'accuracy', 'rank_weight')}
for step in range(1, num_steps + 1):
X, y = sample_real(images, batch_size, labels)
with torch.no_grad():
fake = generate(noise(batch_size), y)
loss_d, r1, r2 = d2l.critic_step(net_D, opt_D, loss_D, X, fake,
gamma, y)
X, y = sample_real(images, batch_size, labels)
loss_g = d2l.generator_step(net_G, opt_G, loss_G, net_D, X,
noise(batch_size), y)
ema.update(net_G)
if step % log_every == 0: # fresh pairs of real and generated images
X, y = sample_real(eval_images, eval_size, eval_labels)
with torch.no_grad():
fake = generate(noise(eval_size), y)
acc, weight = pair_stats(net_D, X, fake, y)
logs = (step, loss_d, loss_g, r1, r2, acc, weight)
for k, v in zip(history, logs):
history[k].append(float(v))
return ema.model, {k: np.array(v) for k, v in history.items()}
def train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images,
labels=None, *, eval_images=None, eval_labels=None,
eval_size=256, batch_size=64, lr=2e-4, half_life=500,
log_every=250, seed=None):
"""Train with Adam (beta_1 = 0), alternating critic_step and
generator_step on flipped real batches; a generated batch takes the
labels of its real batch, if any. Every log_every steps, log the losses,
R1, R2 and pair_stats on fresh pairs from eval_images (default: images).
Return the EMA of the generator and the history, a dict of arrays."""
key = d2l.get_key() if seed is None else jax.random.key(seed)
if eval_images is None:
eval_images, eval_labels = images, labels
opt_G, opt_D = [nnx.Optimizer(net, optax.adam(lr, b1=0.0, b2=0.99),
wrt=nnx.Param) for net in (net_G, net_D)]
noise = lambda key, n: jax.random.normal(key, (n, net_G.latent_dim))
generate = lambda z, y: net_G(z) if y is None else net_G(z, y)
ema = EMA(net_G, half_life)
history = {k: [] for k in ('step', 'loss_D', 'loss_G', 'R1', 'R2',
'accuracy', 'rank_weight')}
for step in range(1, num_steps + 1):
key, kx, kz, kx2, kz2 = jax.random.split(key, 5)
X, y = sample_real(kx, images, batch_size, labels)
X2, y2 = sample_real(kx2, images, batch_size, labels)
loss_d, r1, r2, loss_g = r3gan_step(
net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma,
X, noise(kz, batch_size), y, X2, noise(kz2, batch_size), y2)
ema.update(net_G)
if step % log_every == 0: # fresh pairs of real and generated images
key, kx, kz = jax.random.split(key, 3)
X, y = sample_real(kx, eval_images, eval_size, eval_labels)
fake = generate(noise(kz, eval_size), y)
acc, weight = pair_stats(net_D, X, fake, y)
logs = (step, loss_d, loss_g, r1, r2, acc, weight)
for k, v in zip(history, logs):
history[k].append(float(v))
return ema.model, {k: np.array(v) for k, v in history.items()}train_arm は、すべての実験群で同じシードから 2 つのネットワークを構築して訓練し、クリティックの訓練・ホールドアウトギャップ(1,024 枚の訓練画像に対する平均スコアと 1,024 枚のホールドアウト画像に対する平均スコアの差)を返す。
def train_arm(loss_D, loss_G, gamma, num_steps):
torch.manual_seed(0) # the same initialization in every arm
net_G = Generator(100, 64, 512).to(device)
net_D = Discriminator(64, 32).to(device)
ema_G, history = train_r3gan(net_G, net_D, loss_D, loss_G, gamma,
num_steps, train_imgs, seed=1)
with torch.no_grad():
gap = (net_D(train_imgs[:1024]).mean()
- net_D(holdout_imgs[:1024]).mean())
return ema_G, history, float(gap)def train_arm(loss_D, loss_G, gamma, num_steps):
rngs = nnx.Rngs(0) # the same initialization in every arm
net_G = Generator(100, 64, 512, rngs=rngs)
net_D = Discriminator(64, 32, rngs=rngs)
ema_G, history = train_r3gan(net_G, net_D, loss_D, loss_G, gamma,
num_steps, train_imgs, seed=1)
gap = (net_D(train_imgs[:1024]).mean()
- net_D(holdout_imgs[:1024]).mean())
return ema_G, history, float(gap)ペナルティ付きのステップは、クリティックの入力勾配をもう一度微分するため、ペナルティなしのステップよりも計算コストがかかる。各実験の終了後に、最後の 2,000 ステップにおける 8 回の記録にわたって平均したクリティックの損失とペナルティ、および訓練・ホールドアウトギャップを表示する。
arms = {'NS': (d2l.gan_loss_D, d2l.gan_loss_G, 0, 6000),
'NS + R1 + R2': (d2l.gan_loss_D, d2l.gan_loss_G, 10, 12000),
'RpGAN + R1 + R2': (d2l.rpgan_loss_D, d2l.rpgan_loss_G, 10, 12000)}
runs = {}
for name, (loss_D, loss_G, gamma, num_steps) in arms.items():
ema_G, hist, gap = train_arm(loss_D, loss_G, gamma, num_steps)
runs[name] = (ema_G, hist)
loss, r1, r2 = (hist[k][-2000 // 250:].mean() # the last 2,000 steps
for k in ('loss_D', 'R1', 'R2'))
print(f'{name:16s} critic loss {loss:.2f}, '
f'penalty {gamma / 2 * (r1 + r2):.3f}, train-holdout gap {gap:+.2f}')NS critic loss 0.57, penalty 0.000, train-holdout gap +0.08
NS + R1 + R2 critic loss 1.04, penalty 0.127, train-holdout gap +0.05
RpGAN + R1 + R2 critic loss 0.51, penalty 0.077, train-holdout gap +0.02
arms = {'NS': (d2l.gan_loss_D, d2l.gan_loss_G, 0, 6000),
'NS + R1 + R2': (d2l.gan_loss_D, d2l.gan_loss_G, 10, 12000),
'RpGAN + R1 + R2': (d2l.rpgan_loss_D, d2l.rpgan_loss_G, 10, 12000)}
runs = {}
for name, (loss_D, loss_G, gamma, num_steps) in arms.items():
ema_G, hist, gap = train_arm(loss_D, loss_G, gamma, num_steps)
runs[name] = (ema_G, hist)
loss, r1, r2 = (hist[k][-2000 // 250:].mean() # the last 2,000 steps
for k in ('loss_D', 'R1', 'R2'))
print(f'{name:16s} critic loss {loss:.2f}, '
f'penalty {gamma / 2 * (r1 + r2):.3f}, train-holdout gap {gap:+.2f}')NS critic loss 0.58, penalty 0.000, train-holdout gap +0.29
NS + R1 + R2 critic loss 1.04, penalty 0.122, train-holdout gap +0.05
RpGAN + R1 + R2 critic loss 0.47, penalty 0.092, train-holdout gap +0.03
ペナルティ付きの 2 つのクリティックはいずれも均衡値をやや下回る水準に落ち着くのに対し(古典的ロジスティックでは \(1.04\) 対 \(2\log 2 \approx 1.39\)、ペアリングでは \(0.47\text{--}0.51\) 対 \(\log 2 \approx 0.69\))、ペナルティなしのクリティックは \(0.57\text{--}0.58\) まで低下する。
16.5.3.2 訓練の推移と生成サンプル
クリティックの二乗入力勾配 \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\)、ペアワイズランキング正解率 \(\hat P(D(x) > D(x'))\)、および相対論的ランク重み \(w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))]\) を 250 ステップごとにプロットすると、勾配ペナルティがどのように訓練を安定化させるかがわかる。
fig, axes = d2l.plt.subplots(1, 3, figsize=(12, 3.2))
hists = [hist for _, hist in runs.values()]
for ax, key, ylabel, yscale in zip(
axes, ('R1', 'accuracy', 'rank_weight'),
(r'$E\,\|\nabla_x D(x)\|^2$', 'ranking accuracy',
r'rank weight $w_{\mathrm{Rp}}$'),
('log', 'linear', 'linear')):
d2l.plot([h['step'] for h in hists], [h[key] for h in hists], 'step',
ylabel, yscale=yscale, axes=ax)
axes[0].legend(list(runs), loc='center right')
fig.tight_layout()fig, axes = d2l.plt.subplots(1, 3, figsize=(12, 3.2))
hists = [hist for _, hist in runs.values()]
for ax, key, ylabel, yscale in zip(
axes, ('R1', 'accuracy', 'rank_weight'),
(r'$E\,\|\nabla_x D(x)\|^2$', 'ranking accuracy',
r'rank weight $w_{\mathrm{Rp}}$'),
('log', 'linear', 'linear')):
d2l.plot([h['step'] for h in hists], [h[key] for h in hists], 'step',
ylabel, yscale=yscale, axes=ax)
axes[0].legend(list(runs), loc='center right')
fig.tight_layout()\(R_1 + R_2\) がない場合、クリティックの二乗勾配ノルムは 2 桁上昇する(\(1\text{--}8\) に達するのに対し、ペナルティ付きクリティックでは \(\sim 0.01\))。3 つのクリティックはいずれもペアの \(> 90\%\) を正しく順序付けるが、ペナルティ付きクリティックは小さなスコアマージンを維持するのに対し(\(w_{\mathrm{Rp}} \in [0.25, 0.40]\)、ロジット差の中央値で \(0.7\) 前後に相当)、ペナルティなしクリティックは \(w_{\mathrm{Rp}}\) を \(0.15\) 未満へと押し下げる。
サンプル品質を視覚的に比較するため、まず \([-1, 1]\) の画像バッチを単一の \([0, 1]\) グリッドに並べる補助関数 tile_images を定義する。
def tile_images(imgs, num_rows):
"""Tile images (n, 3, h, w) in [-1, 1] into one (rows * h, cols * w, 3)
array in [0, 1]."""
n, c, h, w = imgs.shape
grid = (imgs.clamp(-1, 1) + 1) / 2
grid = grid.reshape(num_rows, n // num_rows, c, h, w)
grid = grid.permute(0, 3, 1, 4, 2) # (rows, h, cols, w, c)
return grid.reshape(num_rows * h, -1, c).cpu().numpy()
def tile_images(imgs, num_rows):
"""Tile images (n, h, w, 3) in [-1, 1] into one (rows * h, cols * w, 3)
array in [0, 1]."""
n, h, w, c = imgs.shape
grid = (jnp.clip(imgs, -1, 1) + 1) / 2
grid = grid.reshape(num_rows, n // num_rows, h, w, c)
grid = grid.transpose(0, 2, 1, 3, 4) # (rows, h, cols, w, c)
return np.asarray(grid.reshape(num_rows * h, -1, c))それでは、4 つの EMA 生成器すべて(DCGAN と正規化なしの 3 つの実験群)を同じ 64 個の潜在ベクトル z_show 上で評価し、その出力を \(8 \times 8\) のグリッドに並べてみよう。
torch.manual_seed(42)
z_show = torch.randn(64, 100, device=device)
gens = {'DCGAN': ema.model,
**{name: ema_G for name, (ema_G, _) in runs.items()}}
with torch.no_grad():
grids = [tile_images(G(z_show), 8) for G in gens.values()]
d2l.show_images(grids, 1, 4, titles=list(gens), scale=3.4);z_show = jax.random.normal(jax.random.key(42), (64, 100))
gens = {'DCGAN': ema.model,
**{name: ema_G for name, (ema_G, _) in runs.items()}}
grids = [tile_images(G(z_show), 8) for G in gens.values()]
d2l.show_images(grids, 1, 4, titles=list(gens), scale=3.4);バッチ正規化も勾配ペナルティもない場合、NS 実験群は完全なモード崩壊を起こす(64 個すべての潜在コードにわたって一様な灰色のテクスチャを生成する。演習問題 4 を参照)。一方、\(R_1 + R_2\) を加えることで(NS + R1 + R2 および RpGAN + R1 + R2)崩壊が防がれ、きれいな白背景の中央に多様なスプライトのシルエットが生成される。
16.5.4 定量的評価指標
壊滅的な崩壊は目視でも容易に見抜けるが、正常に機能している 2 つの生成器を比較するには定量的な指標が必要である。標準的な GAN の評価では、\(n\) 枚の実画像と \(n\) 枚の生成画像を事前学習済みの特徴抽出器 \(\phi(x) \in \mathbb{R}^d\) で埋め込み、得られた 2 つの経験特徴量分布の間の乖離を 16.2 節 の閉形式の距離によって測定する。
16.5.4.1 FID と KID
Fréchet Inception Distance(FID) (Heusel ほか 2017年) は、実画像と生成画像の特徴量の点群に多変量ガウス分布 \(\mathcal{N}(\mu_p, \Sigma_p)\) と \(\mathcal{N}(\mu_q, \Sigma_q)\) を当てはめ、両者の間の二乗 2 次ワッサースタイン距離(Wasserstein-2 distance)を計算する (Dowson と Landau 1982年; Givens と Shortt 1984年)。
\[ \begin{aligned} \mathrm{FID} &= \big\| \mu_p - \mu_q \big\|^2 \\ &\quad + \operatorname{tr}\!\Big( \Sigma_p + \Sigma_q - 2 \big( \Sigma_p^{1/2}\, \Sigma_q\, \Sigma_p^{1/2} \big)^{1/2} \Big). \end{aligned} \tag{16.5.4}\]
FID は特徴量分布の最初の 2 つのモーメントのみに依存し、そのプラグイン標本共分散推定量は有限サンプルサイズにおいて正の \(O(1/n)\) の統計的バイアスを持つ(演習問題 3)。
Kernel Inception Distance(KID) (Bińkowski ほか 2018年) は、3 次多項式カーネル \(k(u, v) = (u^\top v / d + 1)^3\) を用いて二乗最大平均値差異(maximum mean discrepancy、MMD)の不偏推定量(
d2l.mmd2_unbiased、16.2 節)を計算するものであり、特徴量の 3 次までのモーメントを比較する(演習問題 5)。\[ \begin{aligned} \widehat{\mathrm{MMD}}^2 &= \frac{1}{n_p(n_p-1)} \sum_{i \neq i'} k\big(\phi(x_i), \phi(x_{i'})\big) \\ &\quad + \frac{1}{n_q(n_q-1)} \sum_{j \neq j'} k\big(\phi(x'_j), \phi(x'_{j'})\big) \\ &\quad - \frac{2}{n_p n_q} \sum_{i,j} k\big(\phi(x_i), \phi(x'_j)\big). \end{aligned} \tag{16.5.5}\]
def fid_score(feat_p, feat_q):
"""Frechet distance between Gaussians fitted to two feature sets."""
feat_p = np.asarray(feat_p, np.float64)
feat_q = np.asarray(feat_q, np.float64)
mu_p, mu_q = feat_p.mean(0), feat_q.mean(0)
C_p = np.cov(feat_p, rowvar=False)
C_q = np.cov(feat_q, rowvar=False)
lam, U = np.linalg.eigh(C_p)
sqrt_C_p = (U * np.sqrt(np.maximum(lam, 0))) @ U.T
M = sqrt_C_p @ C_q @ sqrt_C_p
cross = np.linalg.eigvalsh((M + M.T) / 2) # symmetric up to rounding
return (((mu_p - mu_q) ** 2).sum() + np.trace(C_p) + np.trace(C_q)
- 2 * np.sqrt(np.maximum(cross, 0)).sum())
def kid_score(feat_p, feat_q):
"""Unbiased MMD^2 between two feature sets, cubic polynomial kernel."""
d = feat_p.shape[1]
kernel = lambda a, b: (a @ b.T / d + 1) ** 3
return d2l.mmd2_unbiased(kernel(feat_p, feat_p), kernel(feat_q, feat_q),
kernel(feat_p, feat_q))
def fid_score(feat_p, feat_q):
"""Frechet distance between Gaussians fitted to two feature sets."""
feat_p = np.asarray(feat_p, np.float64)
feat_q = np.asarray(feat_q, np.float64)
mu_p, mu_q = feat_p.mean(0), feat_q.mean(0)
C_p = np.cov(feat_p, rowvar=False)
C_q = np.cov(feat_q, rowvar=False)
lam, U = np.linalg.eigh(C_p)
sqrt_C_p = (U * np.sqrt(np.maximum(lam, 0))) @ U.T
M = sqrt_C_p @ C_q @ sqrt_C_p
cross = np.linalg.eigvalsh((M + M.T) / 2) # symmetric up to rounding
return (((mu_p - mu_q) ** 2).sum() + np.trace(C_p) + np.trace(C_q)
- 2 * np.sqrt(np.maximum(cross, 0)).sum())
def kid_score(feat_p, feat_q):
"""Unbiased MMD^2 between two feature sets, cubic polynomial kernel."""
d = feat_p.shape[1]
kernel = lambda a, b: (a @ b.T / d + 1) ** 3
return d2l.mmd2_unbiased(kernel(feat_p, feat_p), kernel(feat_q, feat_q),
kernel(feat_p, feat_q))16.5.4.2 特徴ネットワーク
標準的なベンチマークでは、ImageNet で事前学習された Inception-v3 ネットワークの 2,048 次元の特徴量、あるいは自己教師ありの DINOv2 特徴量を用いて FID と KID を計算する (Stein ほか 2023年; Oquab ほか 2024年)。このノートブックを自己完結させるため、ここでは軽量な 3 ブロックの CIFAR-10 分類器 d2l.FeatureCNN(39.9.4 節)を \(32 \times 32\) の解像度で 15 エポック訓練し、その出力直前の 128 次元層を \(\phi\) として用いる(\(64 \times 64\) のスプライトは \(32 \times 32\) へと \(2 \times 2\) の平均プーリングでダウンサンプリングする)。
def batched(f, X, batch_size=1000):
"""Apply f to X in batches, without gradients, and concatenate."""
with torch.no_grad():
return torch.cat([f(X_k) for X_k in X.split(batch_size)])
def batched(f, X, batch_size=1000):
"""Apply f to X in batches and concatenate."""
return jnp.concatenate([f(X[i:i + batch_size])
for i in range(0, len(X), batch_size)])メモリを圧迫せずに評価できるよう batched を用い、CIFAR-10 を読み込んで、ランダムな 4 ピクセルシフトを伴いながら d2l.FeatureCNN を \(32 \times 32\) の解像度で訓練し、テストセットにおける分類正解率を確認する。
cifar_X, cifar_y, test_X, test_y = d2l.load_cifar10_arrays()
torch.manual_seed(0)
cnn = d2l.FeatureCNN(resolution=32).to(device)
d2l.train_feature_cnn(cnn, cifar_X, cifar_y, shift=4)
pred = batched(cnn, test_X).argmax(1)
print(f'CIFAR-10 test accuracy: {float((pred == test_y).float().mean()):.3f}')CIFAR-10 test accuracy: 0.778
cifar_X, cifar_y, test_X, test_y = d2l.load_cifar10_arrays()
cnn = d2l.FeatureCNN(resolution=32, rngs=nnx.Rngs(1))
d2l.train_feature_cnn(cnn, cifar_X, cifar_y, shift=4)
pred = batched(cnn, test_X).argmax(1)
print(f'CIFAR-10 test accuracy: {float((pred == test_y).mean()):.3f}')CIFAR-10 test accuracy: 0.781
16.5.4.3 適合率と再現率
FID や KID のような単一の距離指標は、\(p\) の台の外側に非現実的な画像を生成する低い忠実度(poor fidelity)と、モード欠落(mode dropping)によって \(p\) の一部を覆い損ねる低い被覆(poor coverage)という 2 つの異なる失敗モードを混同してしまう。Kynkäänniemi ほか (2019年) は、特徴量空間における \(K\) 最近傍球を用いてこれらを分離した。各実特徴量 \(\phi(x_i)\) の周りで、\(B(\phi(x_i), r_i)\) をその \(K\) 番目に近い実特徴量まで届くユークリッド球とし、生成特徴量の間でも \(B(\phi(x'_j), r'_j)\) を同様に定義する(ここでは \(K = 3\) を用いる)。すると、次の式が得られる。
\[ \begin{aligned} \mathrm{precision} &= \frac{1}{n_q} \sum_{j=1}^{n_q} \mathbb{1}\Big[\phi(x'_j) \in \textstyle\bigcup_i B\big(\phi(x_i), r_i\big)\Big], \\ \mathrm{recall} &= \frac{1}{n_p} \sum_{i=1}^{n_p} \mathbb{1}\Big[\phi(x_i) \in \textstyle\bigcup_j B\big(\phi(x'_j), r'_j\big)\Big]. \end{aligned} \]
適合率は推定された実特徴量の台に含まれる生成サンプルの割合であり、再現率は推定された生成特徴量の台によって覆われる実サンプルの割合である。生成器が単一の出力へと崩壊すると、その \(K\)-NN 半径 \(r'_j\) は 0 に縮小し、再現率は \(0\) になる。
def precision_recall(feat_real, feat_gen, k=3, chunk=1000):
"""k-NN precision and recall of two feature sets: the fraction of each
set inside the union of the other set's balls, each ball reaching to its
center's k-th nearest neighbor; return (precision, recall)."""
P = np.asarray(feat_real, np.float64)
Q = np.asarray(feat_gen, np.float64)
def dists(A, B): # (len(A), len(B)) Euclidean distances
sq = (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)
return np.sqrt(np.maximum(sq, 0))
def chunks(A):
return (A[i:i + chunk] for i in range(0, len(A), chunk))
def radii(A): # sorted distances start with the point itself, at 0
return np.concatenate([np.partition(dists(a, A), k, axis=1)[:, k]
for a in chunks(A)])
def covered(A, B, r_B): # is each row of A inside some ball of B?
return np.concatenate([(dists(a, B) <= r_B).any(1)
for a in chunks(A)])
return (float(covered(Q, P, radii(P)).mean()),
float(covered(P, Q, radii(Q)).mean()))
def precision_recall(feat_real, feat_gen, k=3, chunk=1000):
"""k-NN precision and recall of two feature sets: the fraction of each
set inside the union of the other set's balls, each ball reaching to its
center's k-th nearest neighbor; return (precision, recall)."""
P = np.asarray(feat_real, np.float64)
Q = np.asarray(feat_gen, np.float64)
def dists(A, B): # (len(A), len(B)) Euclidean distances
sq = (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)
return np.sqrt(np.maximum(sq, 0))
def chunks(A):
return (A[i:i + chunk] for i in range(0, len(A), chunk))
def radii(A): # sorted distances start with the point itself, at 0
return np.concatenate([np.partition(dists(a, A), k, axis=1)[:, k]
for a in chunks(A)])
def covered(A, B, r_B): # is each row of A inside some ball of B?
return np.concatenate([(dists(a, B) <= r_B).any(1)
for a in chunks(A)])
return (float(covered(Q, P, radii(P)).mean()),
float(covered(P, Q, radii(Q)).mean()))16.5.4.4 各実行のスコアリング
各生成器の移動平均モデルから抽出した \(n = 4{,}059\) 個のサンプルを、4,059 枚のホールドアウトスプライトすべてに対してスコアリングする。各生成器は潜在コードの 2 回の抽出それぞれで評価するため、2 行目はサンプルのみが変わったときにスコアがどれだけ変動するかを表す。下限の目安(フロア)として、互いに素な 4,059 枚ずつの訓練画像の 2 セット同士もスコアリングする。両者の間の距離はすべて推定量のノイズであり、FD においてはさらに有限サンプルの統計的バイアスが含まれる。特徴量ネットワークは独自のものであるため、ここではスコアを FID や KID ではなく FD および \(\mathrm{MMD}^2\) と呼ぶ。これらは 12 倍のサンプル数を用いる既存の公表値とは直接比較できない。また、このバックボーンは出力に tanh を持たないため、スコアリング前に出力をクランプし、最後の 2 列には生のピクセル値のうち \(+1\) を超える割合と \(-1\) を下回る割合を示す。
features = lambda imgs: batched( # 2 x 2 averages: 64 x 64 -> 32 x 32
cnn.features, F.avg_pool2d(imgs, 2)).cpu().numpy()
n = len(holdout_imgs)
zs = []
for seed in (7, 8): # a second latent draw gives the sampling range
torch.manual_seed(seed)
zs.append(torch.randn(n, 100, device=device))
z_score = zs[0]
feat_gen, out_of_range = {}, {} # out_of_range: fractions above +1, below -1
for name, G in gens.items():
for row, z in zip((name, ' second draw'), zs):
x = batched(G, z)
out_of_range[(name, row)] = (float((x > 1).float().mean()),
float((x < -1).float().mean()))
feat_gen[(name, row)] = features(x.clamp(-1, 1))
feat_real = features(holdout_imgs)
feat_a, feat_b = features(train_imgs[:n]), features(train_imgs[n:2 * n])
white = float((holdout_imgs == 1).float().mean())features = lambda imgs: np.asarray(batched( # 2 x 2 averages: 64 -> 32
cnn.features, nnx.avg_pool(imgs, (2, 2), strides=(2, 2))))
n = len(holdout_imgs)
zs = [jax.random.normal(jax.random.key(seed), (n, 100))
for seed in (7, 8)] # a second latent draw gives the sampling range
z_score = zs[0]
feat_gen, out_of_range = {}, {} # out_of_range: fractions above +1, below -1
for name, G in gens.items():
for row, z in zip((name, ' second draw'), zs):
x = batched(G, z)
out_of_range[(name, row)] = (float((x > 1).mean()),
float((x < -1).mean()))
feat_gen[(name, row)] = features(jnp.clip(x, -1, 1))
feat_real = features(holdout_imgs)
feat_a, feat_b = features(train_imgs[:n]), features(train_imgs[n:2 * n])
white = float((holdout_imgs == 1).mean())各特徴量セットをホールドアウトスプライトの特徴量セットと比較する。最初の行は下限の目安(フロア)である。
print(f'{"run":17s}{"FD":>7s}{"MMD^2":>8s}{"precision":>11s}{"recall":>8s}'
f'{"> +1":>7s}{"< -1":>7s}')
scored = {(None, 'real vs. real'): (feat_a, feat_b),
**{key: (feat_real, feat) for key, feat in feat_gen.items()}}
for key, (ref, feat) in scored.items():
precision, recall = precision_recall(ref, feat)
oor = ''.join(f'{v:7.3f}' for v in out_of_range.get(key, ()))
print(f'{key[1]:17s}{fid_score(ref, feat):7.2f}{kid_score(ref, feat):8.3f}'
f'{precision:11.2f}{recall:8.2f}{oor}')
print(f'real pixel values equal to +1: {white:.0%}')run FD MMD^2 precision recall > +1 < -1
real vs. real 0.19 0.003 0.95 0.95
DCGAN 2.05 0.115 0.34 0.48 0.000 0.000
second draw 2.01 0.108 0.36 0.47 0.000 0.000
NS 64.44 7.626 0.07 0.00 0.009 0.000
second draw 64.32 7.628 0.07 0.00 0.010 0.000
NS + R1 + R2 5.32 1.092 0.33 0.42 0.150 0.001
second draw 5.38 1.116 0.34 0.43 0.148 0.001
RpGAN + R1 + R2 3.51 0.652 0.36 0.44 0.143 0.001
second draw 3.69 0.710 0.36 0.44 0.139 0.001
real pixel values equal to +1: 45%
print(f'{"run":17s}{"FD":>7s}{"MMD^2":>8s}{"precision":>11s}{"recall":>8s}'
f'{"> +1":>7s}{"< -1":>7s}')
scored = {(None, 'real vs. real'): (feat_a, feat_b),
**{key: (feat_real, feat) for key, feat in feat_gen.items()}}
for key, (ref, feat) in scored.items():
precision, recall = precision_recall(ref, feat)
oor = ''.join(f'{v:7.3f}' for v in out_of_range.get(key, ()))
print(f'{key[1]:17s}{fid_score(ref, feat):7.2f}{kid_score(ref, feat):8.3f}'
f'{precision:11.2f}{recall:8.2f}{oor}')
print(f'real pixel values equal to +1: {white:.0%}')run FD MMD^2 precision recall > +1 < -1
real vs. real 0.17 -0.001 0.95 0.95
DCGAN 1.80 0.083 0.39 0.48 0.000 0.000
second draw 1.84 0.090 0.37 0.50 0.000 0.000
NS 71.97 7.502 0.00 0.00 0.001 0.000
second draw 71.95 7.501 0.00 0.00 0.001 0.000
NS + R1 + R2 3.96 0.663 0.40 0.41 0.146 0.001
second draw 4.06 0.687 0.41 0.42 0.144 0.001
RpGAN + R1 + R2 3.71 0.603 0.41 0.42 0.149 0.001
second draw 3.78 0.608 0.41 0.43 0.149 0.001
real pixel values equal to +1: 45%
この表から、いくつかの重要な教訓が読み取れる。
- 実画像対実画像のベースラインフロア:互いに素な \(4{,}059\) 枚ずつの実スプライトの 2 セットでは、\(\text{FD} \approx 0.2\)(有限サンプルの共分散推定による統計的バイアスのため)、\(\widehat{\mathrm{MMD}}^2 \approx 0.000\)、適合率・再現率は \(0.95\) となる。潜在コードの 2 回目の抽出で評価しても、FD の変化は \(\leq 0.2\) に収まる。
- 崩壊対ペナルティ付き訓練:崩壊したペナルティなしの
NS実験群では、\(\text{FD} \approx 64\text{--}72\)、\(\text{recall} = 0.00\)、\(\text{precision} \leq 0.07\) となる。ここに \(R_1 + R_2\) を加えると、FD は 1 桁減少し(\(\sim 3.5\text{--}5.5\))、適合率は \(\sim 0.35\text{--}0.4\)、再現率は \(\sim 0.4\) へと向上する。 - 特徴空間への感度(DCGAN 対ペナルティ付きバックボーン):ペナルティ付きバックボーンのほうが \(64 \times 64\) では輪郭が鮮明で白背景もきれいであるにもかかわらず、2015 年の DCGAN のほうが低い FD(\(\sim 2\))および \(\widehat{\mathrm{MMD}}^2\) をこの \(32 \times 32\) CIFAR-10 分類器の特徴量において達成する。これは \(2 \times 2\) のダウンサンプリングによって DCGAN の高周波の斑模様が平滑化されるためである。特徴空間の評価指標には、基盤となる特徴ネットワークの不変性と解像度が常に反映される。
16.5.5 潜在補間とクリティックの過学習
16.5.5.1 潜在空間での補間
生成器が離散的なテンプレートを暗記しているのではなく、潜在コードから画像への滑らかな写像を学習していることを確かめるため、64 組の潜在ベクトルのペアの間を \(z_t = (1 - t)z_0 + t z_1\)(\(t \in [0, 1]\))と線形補間し、生成画像 \(G(z_t)\) をピクセルごとのクロスフェード \((1 - t)G(z_0) + t G(z_1)\) と比較する。
G = runs['RpGAN + R1 + R2'][0]
torch.manual_seed(0)
z0, z1 = torch.randn(2, 64, 1, 100, device=device) # 64 pairs of codes
t = torch.linspace(0, 1, 8, device=device).view(1, 8, 1)
path = batched(G, ((1 - t) * z0 + t * z1).reshape(-1, 100)).clamp(-1, 1)
path = path.reshape(64, 8, 3, 64, 64) # (pair, step, image)
t = t.view(1, 8, 1, 1, 1)
fade = (1 - t) * path[:, :1] + t * path[:, -1:] # pixel cross-fades
inner = lambda x: features(x[:, 1:-1].flatten(0, 1))
print(f'precision of the inner steps: latent walk '
f'{precision_recall(feat_real, inner(path))[0]:.2f}, '
f'cross-fade {precision_recall(feat_real, inner(fade))[0]:.2f}')
d2l.show_images([tile_images(x[:8].flatten(0, 1), 8) for x in (path, fade)],
1, 2, titles=['latent walk', 'pixel cross-fade'], scale=4.5);precision of the inner steps: latent walk 0.35, cross-fade 0.21
G = runs['RpGAN + R1 + R2'][0]
z0, z1 = jax.random.normal(jax.random.key(0), (2, 64, 1, 100)) # 64 pairs
t = jnp.linspace(0, 1, 8).reshape(1, 8, 1)
path = jnp.clip(batched(G, ((1 - t) * z0 + t * z1).reshape(-1, 100)), -1, 1)
path = path.reshape(64, 8, 64, 64, 3) # (pair, step, image)
t = t.reshape(1, 8, 1, 1, 1)
fade = (1 - t) * path[:, :1] + t * path[:, -1:] # pixel cross-fades
inner = lambda x: features(x[:, 1:-1].reshape(-1, 64, 64, 3))
print(f'precision of the inner steps: latent walk '
f'{precision_recall(feat_real, inner(path))[0]:.2f}, '
f'cross-fade {precision_recall(feat_real, inner(fade))[0]:.2f}')
d2l.show_images([tile_images(x[:8].reshape(-1, 64, 64, 3), 8)
for x in (path, fade)],
1, 2, titles=['latent walk', 'pixel cross-fade'], scale=4.5);precision of the inner steps: latent walk 0.38, cross-fade 0.18
潜在空間における中間補間点は、生成器からのランダムな抽出と同等の特徴量適合率(\(\sim 0.35\text{--}0.38\))を維持しながら形状や色が滑らかに遷移するのに対し、ピクセルごとのクロスフェードでは残像を伴う二重露光のような画像が生じ、適合率は半分(\(\sim 0.18\text{--}0.21\))に低下する。
16.5.5.2 クリティックの過学習とリークしないデータ拡張
\(1.6\text{M}\) 個のパラメータと \(36{,}538\) 枚の訓練スプライトのもとで、クリティックは 12,000 ステップの間に各訓練画像を約 20 回参照する。ペナルティ付きクリティックにおける訓練・ホールドアウト間のスコア差はごくわずかである(\(+0.02\)〜\(+0.05\) であり、実画像対生成画像のマージン \(\sim 0.7\) と比べて小さい。演習問題 2 を参照)。しかし、より小規模なデータセットやより長時間の訓練では、識別器による暗記が FID を悪化させることがある (Karras, Aittala, ほか 2020年)。これに対する標準的な対策である Adaptive Discriminator Augmentation(ADA、Karras, Aittala, ほか (2020年))および DiffAugment (Zhao ほか 2020年) は、勾配経路の内部で実画像と生成画像の双方に可逆かつリークしない(non-leaking)データ拡張を適用する(これに対し、本節の水平反転のように実画像のみを拡張すると、生成器は拡張後の分布に一致するように訓練される。演習問題 6 を参照)。
16.5.6 まとめ
DCGAN は、転置畳み込みとストライド付き畳み込み、バッチ正規化、小さな標準偏差による重みの初期化(\(\sigma = 0.02\))、および \(\beta_1 = 0.5\) の Adam によって、古典的ロジスティック損失のもとでの畳み込み敵対的訓練を安定化させる。バッチ正規化とアーキテクチャ上の安定化手法を取り除くと、ペナルティなしのロジスティック損失は完全に崩壊するが、ゼロ中心勾配ペナルティ(\(R_1 + R_2\))を加えればクリティックの勾配が 2 桁減衰し、最小構成の双線形リサンプリングバックボーンを安定して訓練できる。生成器の重みの指数移動平均はミニマックス振動をさらに減衰させるが、バッチ正規化を用いる場合には移動統計量の再較正が必要である。最後に、定量的な画像評価では、フレシェ距離(式 16.5.4)、Kernel Inception Distance(式 16.5.5)、および \(K\)-NN の適合率と再現率を用いて実画像と生成画像の特徴量の点群を比較し、常に実画像対実画像の有限サンプルフロアを基準として較正する。
16.5.7 演習問題
勾配ペナルティ重みと画像解像度。\(\nabla_x D(x)\) は長さの逆数の単位を持つため、ペナルティ重み \(\gamma\) は画像解像度とピクセル値のスケーリングに依存する。
- \(U\) を \(64 \times 64\) の画像 \(x\) を \(128 \times 128\) へアップサンプリングする作用素(各ピクセルを \(2 \times 2\) ブロックに複製)とし、\(A\) を各 \(2 \times 2\) ブロックの平均をとる作用素として \(D' = D \circ A\) が \(D'(Ux) = D(x)\) を満たすとする。\(\|\nabla D'(Ux)\|^2\) を \(\|\nabla D(x)\|^2\) を用いて表し、ペナルティ重み \(\gamma'\) として \(128 \times 128\) のペナルティを \(64 \times 64\) のペナルティと等しくするものを求めよ。
- \(\gamma\) は、ピクセル値を \([0, 1]\) へと正規化した場合(\([-1, 1]\) の代わりに)、どのように再スケーリングしなければならないか。
- の結果を、StyleGAN2-ADA で用いられている経験則 \(\gamma \propto r^2 / B\)(解像度 \(r\)、バッチサイズ \(B\))と関連づけて説明せよ (Karras, Aittala, ほか 2020年)。
[code] スケールに依存しないクリティックの過学習統計量。スコアスケールの異なる目的関数の間でクリティックの暗記を比較するため、Karras, Aittala, ほか (2020年) は次の量を定義している。
\[ \begin{aligned} r_v &= \frac{\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{holdout}}]}{\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{generated}}]}, \\ r_t &= \mathbb{E}\big[\operatorname{sign}(D_{\textrm{train}})\big]. \end{aligned} \]
- \(r_v\) は正のアフィン変換 \(D \mapsto aD + c\)(\(a > 0\))に対して不変であるのに対し、生のギャップ \(\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{holdout}}]\) は \(a\) 倍にスケーリングされ、\(r_t\) は平行移動 \(c\) に依存することを示せ。
- シフト不変なペアリングクリティックについて、\(D\) のどのような変換のもとで \(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\) が不変になるか。また、訓練スコアとホールドアウトスコアが同一の分布に従うとき、この量はどの値をとるか。
train_armを変更してnet_Dを返すようにし、3 つの実験群それぞれについて 1,024 枚の画像にわたる \(r_v\) と \(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\) を計算せよ。
[code] FID と KID における有限サンプルの統計的バイアス。
- 互いに素な実画像対実画像の FD と \(\widehat{\mathrm{MMD}}^2\) を、\(n\) 枚ずつの訓練スプライトの 2 セット間で \(n \in \{250, 500, 1000, 2000, 4059\}\) の各値についてランダムな 5 分割にわたって計算せよ。
- FD を \(1/n\) に対して線形回帰で当てはめ、\(1/n \to 0\) へと外挿せよ(Chong と Forsyth (2020年))。\(n = 500\) および \(n = 4{,}059\) における有限サンプルバイアスはどの程度の大きさか。
- ホールドアウトスプライトに対する
RpGAN + R1 + R2生成器についても \(1/n\) による線形当てはめを繰り返せ。\(1/n\) の傾きは生成器の特徴量共分散に依存するため、小さな \(n\) における有限サンプルバイアスが 2 つの生成器のランキングを逆転させ得る理由を説明せよ。
[code] 重みの初期化とモード崩壊。 ● サンプル多様性を、
z_show上の生成画像におけるペアごとの平均特徴量距離を 64 枚のホールドアウトスプライトにおけるペアごとの平均特徴量距離で割ったものとして定義する。- サンプル多様性と \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\) を 5,000 ステップにわたり 500 ステップごとに、ペナルティなしの
NS実験群について、He のファンイン初期化のもとで、および \(\mathcal{N}(0, \sigma^2)\)(\(\sigma \in \{0.01, 0.02, 0.05\}\))による初期化のもとでそれぞれ記録せよ。クリティックの勾配ノルムの急上昇は、多様性の低下に先行するか。 - ファンイン初期化での実験を 3 つのシードにわたって繰り返し、崩壊が起きるステップ数がシードごとにどの程度変動するかを測定せよ。
- サンプル多様性と \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\) を 5,000 ステップにわたり 500 ステップごとに、ペナルティなしの
FID と KID が捉えるモーメント。 ●
3 次多項式の KID カーネル \(k(u, v) = (u^\top v / d + 1)^3\) を二項定理によって展開し、母集団の \(\mathrm{MMD}^2(p, q)\) が
\[\sum_{j=1}^{3} \binom{3}{j} d^{-j}\, \big\| \mathbb{E}_p[u^{\otimes j}] - \mathbb{E}_q[u^{\otimes j}] \big\|_F^2, \tag{16.5.6}\]
に等しく、したがって特徴量分布の最初の 3 つのモーメントを比較することを示せ。
1 次元(\(d = 1\))において、母集団の FID と 3 次カーネルの \(\mathrm{MMD}^2\) を、\(p = \mathcal{N}(0, 1)\) と、(i) 平行移動した指数分布 \(X - 1\)(ただし \(X \sim \textrm{Exp}(1)\) であり、平均 \(0\)、分散 \(1\)、歪度 \(2\))、および (ii) 対称な混合分布 \(\tfrac12\mathcal{N}(-a, 1 - a^2) + \tfrac12\mathcal{N}(a, 1 - a^2)\)(\(0 < a < 1\))のそれぞれとの間で計算せよ。
リークしないデータ拡張。 ● \(F\) を水平反転作用素とし、\(T_\rho r = (1 - \rho)r + \rho\,F_\# r\) を \(r\) からのサンプルを確率 \(\rho\) で反転させて得られる分布とする。
sample_realのように実画像のみを \(\rho = \tfrac12\) で反転させた場合、生成器は \(T_{1/2} p\) に向かって訓練される。真のスプライトのうち割合 \(\alpha\) が左向きで対応する右向き個体を持たないとき、最適な生成器からのサンプルのうちどれだけの割合が右向きになるか。- クリティックの内部で実画像と生成画像の双方に \(T_\rho\) を適用するとき、\(F^2 = I\) を用いて、\(T_\rho q = T_\rho p \implies q = p\) が \(\rho \neq \tfrac12\) のときに常に成り立つこと(リークしない性質、Karras, Aittala, ほか (2020年))、一方で \(\rho = \tfrac12\) のときには \(p\) と同じ反転対称化密度を持つ任意の分布が \(p\) と識別不能になることを示せ。