import torchvision16.5 对抗图像生成
16.1 节 中的多层感知机生成了可辨识的 \(28 \times 28\) Fashion-MNIST 轮廓,但由于全连接层忽略空间局部性,其纹理呈颗粒状。生成一张 \(64 \times 64\) RGB 图像需要从 100 维潜在向量产出 \(12{,}288\) 个像素值。由此引出两个问题:
- 什么样的卷积架构能够稳定地进行对抗图像生成训练?
- 在没有似然函数的情况下,如何定量评估并比较图像生成器?
卷积生成器与判别器最早通过 Radford 等 (2015年) 的深度卷积 GAN(DCGAN)将 GAN 扩展到了自然图像领域。尽管扩散模型(第 17 章)此后成为通用图像合成的主流方法,卷积判别器与特征空间评估指标在现代图像词元化器和单步蒸馏生成器中依然处于核心地位(16.7 节)。
本节在包含 40,597 张 \(64 \times 64\) 宝可梦像素图的数据集上展开训练。我们首先实现经典的 2015 年 DCGAN 架构,然后受 R3GAN (Huang 等 2024年) 启发构造一个极简的无归一化卷积主干。通过在三种目标函数(无惩罚经典 logistic 损失、带 \(R_1 + R_2\) 惩罚的经典 logistic 损失,以及带 \(R_1 + R_2\) 惩罚的相对配对损失)下训练这一无归一化主干,我们检验零中心梯度惩罚(16.4 节)能否取代批量归一化及其他架构启发式技巧。接着我们实现标准的特征空间评估指标——Fréchet 距离(FID)、核 Inception 距离(KID)以及 \(k\)-NN 精确率与召回率,并考察潜空间插值与判别器过拟合。
# 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 节 的经典非饱和 logistic 目标,并通过一组架构约定稳定卷积训练:
- 生成器中的空间上采样采用转置卷积(微步卷积),而判别器中的下采样采用带步幅卷积以取代汇聚层。
- 除生成器输出层与判别器输入层外,每个卷积层之后均施加批量归一化。
- 生成器隐藏层使用 ReLU、输出层使用 \(\tanh\)(匹配 \([-1, 1]\) 的像素范围),而判别器全程使用 leaky ReLU(\(\text{slope} = 0.2\))以防止零梯度死区。
- 权重从 \(\mathcal{N}(0, 0.02^2)\) 初始化,Adam 采用降低后的动量 \(\beta_1 = 0.5\)。
16.5.1.1 宝可梦像素图数据集
我们的数据集包含来自 pokemondb.net 的 721 种宝可梦共 40,597 张 RGB 像素图,已缩放至 \(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)
通过固定置换划出十分之一的图像,全程不参与训练。它们既作为评估生成图像的真实参照样本,也用于检验评判器是否给训练图像打出了高于未见图像的分数。划分按图像而非按物种进行,因此同一物种的不同变体可能同时出现在两边,复制训练像素图的生成器也可能落在留出变体附近。
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\) 时,每层将空间分辨率翻倍(\(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 生成器串联五个转置卷积,依次跨越分辨率 \(1 \to 4 \to 8 \to 16 \to 32 \to 64\),每阶段通道数减半,最终输出 3 个 RGB 通道。判别器以带步幅卷积镜像这一层级结构,直至输出单个 \(1 \times 1\) logit。
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))将四个 G_block 阶段与末尾的转置卷积及 tanh 堆叠构成 net_G,而四个 D_block 阶段(首块省略批量归一化)接一个 \(4 \times 4\) 卷积构成 net_D;对两个 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 使用经典损失进行训练
16.1 节 中交替执行评判器 logistic 回归步与生成器非饱和步的循环 d2l.train_gan 可原封不动地用于图像。我们沿用 DCGAN 配置,仅将小批量大小从论文的 128 增至 256:学习率 \(2 \cdot 10^{-4}\),\(\beta_1 = 0.5\),卷积核从 \(\mathcal{N}(0, 0.02^2)\) 初始化;批量归一化的缩放参数从 \(\mathcal{N}(1, 0.02^2)\) 初始化、偏置为零,与作者开源代码一致。
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 维护参数的指数滑动平均,每步更新为
\[\bar\theta \leftarrow \beta\, \bar\theta + (1 - \beta)\, \theta, \qquad \beta = 2^{-1/n_{1/2}}, \tag{16.5.2}\]
使得历史步的权重每过 \(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 步)的二十分之一。
打印出的评判器损失是 16.1 节 中两个小批量均值之和,在平衡点处等于 \(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 个新的潜在编码小批量驱动平均生成器,从而重新估计平均权重的批量归一化统计量。滑动统计量每批以 0.1 的速率遗忘,因此复制而来的旧值仅保留 \(0.9^{100} \approx 3 \cdot 10^{-5}\) 的权重,相当于完全清零。
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\),却并未引发模式坍缩。
16.5.2 无归一化主干网络
在 DCGAN 之后的数年间,大规模图像 GAN 累积了众多架构稳定技巧(StyleGAN2 (Karras, Laine, 等 2020年) 组合了十种不同技术)。R3GAN (Huang 等 2024年) 证明,一旦用 \(R_1 + R_2\) 梯度惩罚与相对配对损失对目标函数加以正则化,这些特设架构装置均可移除。特别是,使用 \(R_1\) 与 \(R_2\) 时必须在判别器中省去批量归一化,因为批量归一化在小批量内耦合各样本,会破坏逐样本输入梯度的计算。
16.5.2.1 架构与扇入初始化
我们构建一个不含归一化层、亦无输出 \(\tanh\) 的极简卷积主干(图 16.5.2):
- 生成器将可学习的 \(4 \times 4 \times 128\) 常量张量与 \(z\) 的线性投影(\(4 \times 4 \times 100\),外加 16.6 节 中用于类别条件控制的可选通道)拼接,再经四次双线性插值上采样(\(4 \to 8 \to 16 \to 32 \to 64\)),每次后接 \(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)\),再接线性输出头。
- 为在无批量归一化时保持跨层激活方差,所有权重采用针对斜率 \(0.2\) 的 leaky ReLU 缩放的 He 扇入初始化 (He 等 2015年):方差为 \(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 与双线性下采样将 \(64 \times 64\) 图像降至 \(4 \times 4\),随后经一个混合卷积与线性头返回单个分数。
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 三个实验组
我们从完全相同的初始权重出发,使用 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)\) 为经典 logistic 损失(d2l.gan_loss_D)或相对配对损失(d2l.rpgan_loss_D),生成器使用对应的非饱和损失:
| 实验组 | 评判器损失 | 梯度惩罚 | 步数 |
|---|---|---|---|
NS |
经典 logistic | \(\gamma = 0\)(无) | 6,000 |
NS + R1 + R2 |
经典 logistic | \(\gamma = 10\) | 12,000 |
RpGAN + R1 + R2 |
相对配对 | \(\gamma = 10\) | 12,000 |
对比前两组可隔离 \(R_1 + R_2\) 梯度惩罚的作用(无惩罚组在第 6,000 步提前停止,因为它远在此前就已坍缩);对比后两组可隔离成对排序的作用(练习 1 分析 \(\gamma\) 如何随图像分辨率缩放)。两个保存的辅助函数支撑训练循环: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 合并为每次训练迭代的单次 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 在翻转后的真实小批量上交替调用 16.4 节 的 d2l.critic_step 与 d2l.generator_step,并在每步后更新 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 在每组中用相同随机种子构造两个网络并完成训练,返回评判器的训练–留出差距:即它在 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 步内八次检查的平均评判器损失与惩罚值,以及训练–留出差距。
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
两个带惩罚评判器均稳定在略低于各自平衡值的水平(经典 logistic 为 \(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 训练轨迹与生成样本
每隔 250 步绘制评判器平方输入梯度 \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\)、成对排序准确率 \(\hat P(D(x) > D(x'))\) 以及相对排序权重 \(w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))]\),可以清晰看到梯度惩罚如何稳定训练:
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\) 时,评判器平方梯度范数飙升两个数量级(高达 \(1\text{--}8\),而带惩罚评判器仅为 \(\sim 0.01\))。尽管三个评判器都能正确排序 \(> 90\%\) 的样本对,带惩罚评判器保持了适度的分数间隔(\(w_{\mathrm{Rp}} \in [0.25, 0.40]\),对应约 \(0.7\) 的中位 logit 差),而无惩罚评判器则将 \(w_{\mathrm{Rp}}\) 压低至 \(0.15\) 以下。
为直观比较样本质量,我们先定义辅助函数 tile_images,将 \([-1, 1]\) 中的一批图像拼接成单个 \([0, 1]\) 网格:
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))现在我们在相同的 64 个潜在向量 z_show 上评估全部四个 EMA 生成器——DCGAN 与三个无归一化实验组——并将输出拼成 \(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 定量评估指标
目视检查很容易发现灾难性坍缩,但要比较两个正常工作的生成器,则需要定量指标。标准 GAN 评估流程通过预训练特征提取器 \(\phi(x) \in \mathbb{R}^d\) 嵌入 \(n\) 张真实图像与 \(n\) 张生成图像,并利用 16.2 节 中的闭式距离度量两个经验特征分布之间的差异。
16.5.4.1 FID 与 KID
Fréchet Inception 距离(FID)(Heusel 等 2017年) 用多维高斯分布 \(\mathcal{N}(\mu_p, \Sigma_p)\) 与 \(\mathcal{N}(\mu_q, \Sigma_q)\) 分别拟合真实与生成特征点云,并计算二者之间的平方 Wasserstein-2 距离 (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 仅依赖特征分布的前两阶矩,且其代入式样本协方差估计在有限样本量下具有 \(O(1/n)\) 的正偏差(练习 3)。
核 Inception 距离(KID)(Bińkowski 等 2018年) 采用三次多项式核 \(k(u, v) = (u^\top v / d + 1)^3\) 计算无偏平方最大均值差异(
d2l.mmd2_unbiased,16.2 节),可比较高达三阶的特征矩(练习 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年)。为保持本笔记本自包含,我们在 \(32 \times 32\) 分辨率上训练轻量级三块 CIFAR-10 分类器 d2l.FeatureCNN(39.9.4 节)15 轮,并取其 128 维倒数第二层作为 \(\phi\)(通过 \(2 \times 2\) 平均汇聚将 \(64 \times 64\) 像素图下采样至 \(32 \times 32\))。
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,在 \(32 \times 32\) 分辨率下带随机 4 像素平移训练 d2l.FeatureCNN,并验证其测试集分类准确率:
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\) 支集之外生成不逼真的图像)与覆盖度差(模式遗漏,未能覆盖 \(p\) 的部分区域)。Kynkäänniemi 等 (2019年) 利用特征空间中的 \(K\)-近邻球将二者分离。以每个真实特征 \(\phi(x_i)\) 为球心,作触及其第 \(K\) 近真实邻居的欧氏球 \(B(\phi(x_i), r_i)\);在生成特征中同理定义 \(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\)。
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 张留出像素图打分。每个生成器都在两组独立潜在编码抽样上评估,因此第二行反映了仅更换样本时的波动幅度。作为下限基准,我们将两组互不相交的 4,059 张训练图像互相对照:二者之间的任何距离均来自估计噪声,对 FD 而言还包含有限样本偏差。由于所用特征网络是我们自训的,我们将分数称为 FD 与 \(\mathrm{MMD}^2\) 而非 FID 与 KID;它们不能直接与论文发表值比较(后者样本量也高出十二倍)。无归一化主干没有 tanh 输出,因此打分前先对输出截断;最后两列报告截断前原始像素值大于 \(+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\) 张真实像素图得分为 \(\text{FD} \approx 0.2\)(源于有限样本协方差偏差)、\(\widehat{\mathrm{MMD}}^2 \approx 0.000\),以及 \(0.95\) 的精确率/召回率。更换第二组潜在编码抽样对 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 降低一个数量级(\(\sim 3.5\text{--}5.5\)),并将精确率提升至 \(\sim 0.35\text{--}0.4\)、召回率提升至 \(\sim 0.4\)。 - 特征空间敏感性(DCGAN 对比带惩罚主干):尽管带惩罚主干在 \(64 \times 64\) 下生成了更干净的视觉轮廓与纯白背景,2015 年的 DCGAN 在我们的 \(32 \times 32\) CIFAR-10 分类器特征下却取得了更低的 FD(\(\sim 2\))与 \(\widehat{\mathrm{MMD}}^2\)——因为 \(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年)。标准对策——自适应判别器增强(ADA,Karras, Aittala, 等 (2020年))与 DiffAugment (Zhao 等 2020年)——在梯度路径内对真实与生成图像同时施加可逆的无泄漏增强(相比之下,仅增强真实图像——如我们的水平翻转——会训练生成器去拟合增强后的分布;练习 6)。
16.5.6 小结
DCGAN 借助转置与带步幅卷积、批量归一化、小方差权重初始化(\(\sigma = 0.02\))以及 \(\beta_1 = 0.5\) 的 Adam,稳定了经典 logistic 损失下的卷积对抗训练。移除批量归一化与架构稳定器会导致无惩罚 logistic 损失彻底坍缩,而加入零中心梯度惩罚(\(R_1 + R_2\))可将评判器梯度降低两个数量级,使极简双线性重采样主干可靠训练。对生成器权重做指数滑动平均可进一步抑制极小极大振荡,但存在批量归一化时需重新校准其滑动统计量。最后,定量图像评估通过 Fréchet 距离(式 16.5.4)、核 Inception 距离(式 16.5.5)以及 \(K\)-NN 精确率与召回率比较真实与生成特征点云,并始终以真实对真实有限样本下限为标尺。
16.5.7 练习
梯度惩罚权重与图像分辨率。由于 \(\nabla_x D(x)\) 具有长度倒数的量纲,惩罚权重 \(\gamma\) 依赖图像分辨率与像素缩放。
- 设 \(U\) 将 \(64 \times 64\) 图像 \(x\) 的每个像素复制为 \(2 \times 2\) 块上采样至 \(128 \times 128\),设 \(A\) 对每个 \(2 \times 2\) 块取平均使得 \(D' = D \circ A\) 满足 \(D'(Ux) = D(x)\)。用 \(\|\nabla D(x)\|^2\) 表示 \(\|\nabla D'(Ux)\|^2\),并求出使 \(128 \times 128\) 惩罚等于 \(64 \times 64\) 惩罚的权重 \(\gamma'\)。
- 若将像素值归一化到 \([0, 1]\) 而非 \([-1, 1]\),\(\gamma\) 应如何重新缩放?
- 将(a)中的结果与 StyleGAN2-ADA (Karras, Aittala, 等 2020年) 中使用的经验公式 \(\gamma \propto r^2 / B\)(分辨率 \(r\)、批量大小 \(B\))联系起来。
[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\)。
- 对平移不变的配对评判器,\(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\) 在 \(D\) 的哪些变换下保持不变?当训练分数与留出分数服从相同分布时,它取何值?
- 修改
train_arm以返回net_D,并在 1,024 张图像上为三个实验组分别计算 \(r_v\) 与 \(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\)。
[code] FID 与 KID 的有限样本偏差。
- 对 \(n \in \{250, 500, 1000, 2000, 4059\}\) 各执行五次随机划分,计算两组互不相交的 \(n\) 张训练像素图之间的真实对真实 FD 与 \(\widehat{\mathrm{MMD}}^2\)。
- 对 FD 关于 \(1/n\) 作线性回归并外推至 \(1/n \to 0\)(Chong 和 Forsyth (2020年))。在 \(n = 500\) 与 \(n = 4{,}059\) 处有限样本偏差有多大?
- 对
RpGAN + R1 + R2生成器对照留出像素图重复 \(1/n\) 线性拟合。由于 \(1/n\) 的斜率依赖生成器的特征协方差,解释为何小 \(n\) 处的有限样本偏差可能逆转两个生成器的排序。
[code] 权重初始化与模式坍缩。● 将样本多样性定义为
z_show上生成图像的平均成对特征距离除以 64 张留出像素图的平均成对特征距离。- 对无惩罚
NS组在 He 扇入初始化以及 \(\sigma \in \{0.01, 0.02, 0.05\}\) 的 \(\mathcal{N}(0, \sigma^2)\) 初始化下,在 5,000 步内每隔 500 步记录样本多样性与 \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\)。评判器梯度范数的尖峰是否先于多样性骤降出现? - 用三个随机种子重复扇入初始化运行,测量坍缩步数在种子间的变化幅度。
- 对无惩罚
FID 与 KID 捕获的矩。●
利用二项式定理展开三次 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}\]
从而比较特征分布的前三阶矩。
在一维(\(d = 1\))下,计算 \(p = \mathcal{N}(0, 1)\) 与下列分布之间的总体 FID 及三次核 \(\mathrm{MMD}^2\):(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\) 为以概率 \(\rho\) 翻转来自 \(r\) 的样本所得到的分布。
- 当仅对真实图像以 \(\rho = \tfrac12\) 翻转(如
sample_real)时,生成器被训练拟合 \(T_{1/2} p\)。若比例为 \(\alpha\) 的真实像素图只朝左而无朝右对应物,最优生成器的样本中有多大比例会朝右? - 当在评判器内部对真实与生成图像同时施加 \(T_\rho\) 时,利用 \(F^2 = I\) 证明只要 \(\rho \neq \tfrac12\),就有 \(T_\rho q = T_\rho p \implies q = p\)(无泄漏,Karras, Aittala, 等 (2020年));而在 \(\rho = \tfrac12\) 处,任何与 \(p\) 共享翻转对称化密度的分布都无法与 \(p\) 区分。
- 当仅对真实图像以 \(\rho = \tfrac12\) 翻转(如