16.5 Adversarial Image Generation

The multilayer perceptron in Section 16.1 generated recognizable 28×2828 \times 28 Fashion-MNIST silhouettes, but its textures were grainy because fully connected layers ignore spatial locality. Generating a 64×6464 \times 64 RGB image requires producing 12,28812{,}288 pixel values from a 100-dimensional latent vector. Two questions arise:

  1. What convolutional architectures train stably for adversarial image generation?
  2. How can we evaluate and compare image generators quantitatively when no likelihood is available?

Convolutional generators and discriminators first scaled GANs to natural images with the Deep Convolutional GAN (DCGAN) of Radford et al. (2015). While diffusion models (Chapter 17) have since become the primary method for general-purpose image synthesis, convolutional discriminators and feature-space evaluation metrics remain central to modern image tokenizers and one-step distilled generators (Section 16.7).

In this section, we train on a dataset of 40,597 64×6464 \times 64 Pokémon sprites. We first implement the classic 2015 DCGAN architecture, and then construct a minimalist normalization-free convolutional backbone inspired by R3GAN (Huang et al., 2024). By training this normalization-free backbone under three objectives (unpenalized classic logistic loss, classic logistic loss with R1+R2R_1 + R_2 penalties, and relativistic pairing loss with R1+R2R_1 + R_2 penalties), we test whether zero-centered gradient penalties (Section 16.4) replace batch normalization and other architectural heuristics. We then implement the standard feature-space evaluation metrics, namely Fréchet Distance (FID), Kernel Inception Distance (KID), and kk-NN precision and recall, and examine latent space interpolation and discriminator overfitting.

import torchvision

16.5.1 The DCGAN Architecture#

DCGAN (Radford et al., 2015) retains the classic non-saturating logistic objective of Section 16.1 and stabilizes convolutional training through a set of architectural conventions:

  • Spatial upsampling in the generator uses transposed convolutions (fractional-strided convolutions), while downsampling in the discriminator uses strided convolutions instead of pooling layers.
  • Batch normalization is applied after every convolution except the generator output layer and the discriminator input layer.
  • The generator uses ReLU hidden activations and a tanh⁡\tanh output activation (matching pixel values in [−1,1][-1, 1]), whereas the discriminator uses leaky ReLU (slope=0.2\text{slope} = 0.2) throughout to prevent zero-gradient dead zones.
  • Weights are initialized from N(0,0.022)\mathcal{N}(0, 0.02^2), and Adam uses reduced momentum β1=0.5\beta_1 = 0.5.

16.5.1.1 The Pokémon Sprite Dataset#

Our dataset consists of 40,597 RGB sprites of 721 Pokémon species from pokemondb.net, resized to 64×6464 \times 64 and scaled to [−1,1][-1, 1]. Because the entire dataset fits in memory, load_pokemon decodes it into a single tensor.

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.shape
torch.Size([40597, 3, 64, 64])

A fixed permutation sets aside one tenth of the images, which are never used for training. They are the real sample against which generated images are scored, and they show whether the critic scores its training images higher than unseen ones. The split is by image, not by species, so variants of one species can fall on both sides, and a generator that copies a training sprite may land close to a held-out variant of it.

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

16.5.1.2 Transposed Convolutions and Batch Normalization#

To upsample a 1×11 \times 1 feature map with 100 channels into a 64×6464 \times 64 image, DCGAN uses transposed convolutions (Section 20.10). A transposed convolution with kernel size kk, stride ss, and padding pp maps an n×nn \times n spatial grid to an output of side

s(n−1)+k−2p.(16.5.1)s(n - 1) + k - 2p. \tag{16.5.1}

With k=4,s=2,p=1k = 4, s = 2, p = 1, each layer doubles the spatial resolution (n→2nn \to 2n); for the initial layer (k=4,s=1,p=0k = 4, s = 1, p = 0), a 1×11 \times 1 input expands to 4×44 \times 4. Conversely, a strided convolution with k=4,s=2,p=1k = 4, s = 2, p = 1 halves the spatial resolution.

As shown in Figure 16.5.1, the DCGAN generator chains five transposed convolutions across resolutions 1→4→8→16→32→641 \to 4 \to 8 \to 16 \to 32 \to 64, halving the channel width at each stage before outputting 3 RGB channels. The discriminator mirrors this hierarchy with strided convolutions down to a single 1×11 \times 1 logit.

Figure 16.5.1:

The DCGAN architecture (Radford et al., 2015) (at base channel width 512 and 4×44 \times 4 kernels). The generator maps a 100D latent vector through transposed convolutions to a 64×6464 \times 64 RGB image; the critic reverses the hierarchy with strided convolutions. Batch normalization is used in every block except the generator output layer and critic input block.

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))

Stacking four G_block stages with a final transposed convolution and tanh forms net_G, while four D_block stages (omitting batch normalization in the first block) and a 4×44 \times 4 convolution form net_D; a forward pass on two 100-dimensional latent vectors verifies their output shapes:

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])

16.5.1.3 Training with the Classic Loss#

The loop d2l.train_gan of Section 16.1, which alternates a logistic-regression step of the critic with a non-saturating step of the generator, applies to images unchanged. We use the DCGAN settings with a larger minibatch, 256 images instead of the paper's 128: learning rate 2⋅10−42 \cdot 10^{-4}, β1=0.5\beta_1 = 0.5, and convolution kernels drawn from N(0,0.022)\mathcal{N}(0, 0.02^2). Batch-normalization scales start from N(1,0.022)\mathcal{N}(1, 0.02^2) and offsets at zero, as in the authors' released code.

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)

We sample from an average of the generator's recent weights rather than from its last ones. EMA keeps an exponential moving average of the parameters, updated after every step as

θˉ←β θˉ+(1−β) θ,β=2−1/n1/2,(16.5.2)\bar\theta \leftarrow \beta\, \bar\theta + (1 - \beta)\, \theta, \qquad \beta = 2^{-1/n_{1/2}}, \tag{16.5.2}

so that the weight of a past step halves every n1/2n_{1/2} steps, the half-life. The iterates of the game rotate around the equilibrium (Section 16.4), so their average sits closer to it than they do. Batch-normalization statistics are not parameters, and the average copies them from the live network. The copies belong to the live weights, not to the averaged ones, so after training we re-estimate them.

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)

The later runs of this section average over 32,000 images, a half-life of 500 steps at batch size 64. At batch size 256 the same 32,000 images take 125 steps, under a twentieth of this run's 2,840 steps (20 epochs of 142).

The printed critic loss is the sum of the two batch means of Section 16.1, which equals 2log⁡2≈1.392 \log 2 \approx 1.39 at the equilibrium; the generator's loss would equal log⁡2≈0.69\log 2 \approx 0.69 there.

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

The next cell re-estimates the batch-normalization statistics of the average by running the averaged generator in training mode on 100 fresh batches of latent codes. The running averages forget at rate 0.1 per batch, so the copied values keep a weight of 0.9100≈3⋅10−50.9^{100} \approx 3 \cdot 10^{-5}, which is to say none.

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();

We sample in evaluation mode, so that each image depends only on its own latent code.

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);

The generated sprites show diverse silhouettes and color palettes on white backgrounds, though with somewhat blotchy textures. Notice that the discriminator loss (∼0.25–0.45\sim 0.25\text{--}0.45) remains well below 2log⁡2≈1.392\log 2 \approx 1.39 without causing mode collapse.

16.5.2 A Normalization-Free Backbone#

Over the years following DCGAN, large-scale image GANs accumulated numerous architectural stabilizers (StyleGAN2 (Karras et al., 2020) combined ten distinct techniques). R3GAN (Huang et al., 2024) demonstrated that once the objective is regularized with R1+R2R_1 + R_2 gradient penalties and the relativistic pairing loss, those ad-hoc architectural devices can be removed. In particular, omitting batch normalization from the discriminator is essential when using R1R_1 and R2R_2, because batch normalization couples samples across a minibatch and invalidates per-sample input-gradient computation.

16.5.2.1 Architecture and Fan-In Initialization#

We build a minimalist convolutional backbone (Figure 16.5.2) without normalization layers or output tanh⁡\tanh:

  • The generator concatenates a learned 4×4×1284 \times 4 \times 128 constant tensor with a linear projection of zz (4×4×1004 \times 4 \times 100, plus optional extra channels used for class conditioning in Section 16.6) and upsamples four times (4→8→16→32→644 \to 8 \to 16 \to 32 \to 64) via bilinear interpolation followed by a 3×33 \times 3 convolution and leaky ReLU (slope=0.2\text{slope} = 0.2). Bilinear upsampling followed by a 3×33 \times 3 convolution avoids the checkerboard artifacts caused by uneven transposed-convolution overlap (Figure 16.5.3) (Odena et al., 2016).
  • The critic mirrors this structure with 3×33 \times 3 convolutions, leaky ReLU, and bilinear downsampling down to a 4×44 \times 4 feature map ϕ(x)\phi(x) followed by a linear head.
  • To preserve activation variance across layers without batch normalization, all weights use He fan-in initialization (He et al., 2015) scaled for leaky ReLU of slope 0.20.2: variance 2/((1+0.22) nin)2 / ((1 + 0.2^2)\,n_{\mathrm{in}}).
Figure 16.5.2:

The normalization-free convolutional backbone. The generator combines a learned 4×4×1284 \times 4 \times 128 constant with a projected latent vector, then applies four stages of bilinear upsampling, 3×33 \times 3 convolution, and leaky ReLU. The critic mirrors this hierarchy with bilinear downsampling to a linear head.

Figure 16.5.3:

Overlap counts of a transposed convolution with stride 2. Each input pixel stamps one copy of the kernel onto the output, and each number counts the stamps that cover that output pixel, away from the borders. Two neighboring stamps are outlined. With a 3×33 \times 3 kernel (left) the counts alternate between 4, 2 and 1, so even constant weights paint a checkerboard. With a 4×44 \times 4 kernel (right), whose size is a multiple of the stride, every pixel is covered four times.

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

The critic mirrors the generator. Four stages of convolution, leaky ReLU, and bilinear downsampling take a 64×6464 \times 64 image to 4×44 \times 4, and a mixing convolution and a linear head return one score.

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

The generator has ∼2.8M\sim 2.8\text{M} parameters and the critic ∼1.6M\sim 1.6\text{M} parameters.

16.5.3 A Controlled Loss Comparison#

16.5.3.1 Three Experimental Arms#

We train the normalization-free backbone three times from identical initial weights using Adam (β1=0,β2=0.99,lr=2×10−4\beta_1 = 0, \beta_2 = 0.99, \text{lr} = 2 \times 10^{-4}), batch size 64, random horizontal flips, and EMA (half-life=500\text{half-life} = 500 steps), varying only the training objective:

L(D)+γ2(Ex[∥∇xD(x)∥2]+Ex′[∥∇x′D(x′)∥2]),(16.5.3)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}

where L(D)L(D) is either the classic logistic loss (d2l.gan_loss_D) or the relativistic pairing loss (d2l.rpgan_loss_D), and the generator uses the corresponding non-saturating loss:

armcritic lossgradient penaltysteps
NSclassic logisticγ=0\gamma = 0 (none)6,000
NS + R1 + R2classic logisticγ=10\gamma = 1012,000
RpGAN + R1 + R2relativistic pairingγ=10\gamma = 1012,000

Comparing the first two arms isolates the effect of the R1+R2R_1 + R_2 gradient penalty (the unpenalized arm is stopped at 6,000 steps because it collapses well before then); comparing the second and third arms isolates the effect of pairwise ranking (Exercise 1 analyzes how γ\gamma scales with image resolution). Two saved helpers support the training loop: sample_real draws random minibatches with horizontal flips, and pair_stats computes pairwise ranking accuracy P^(D(x)>D(x′))\hat P(D(x) > D(x')) and the mean relativistic rank weight wRp=E[σ(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())

The saved loop train_r3gan alternates d2l.critic_step and d2l.generator_step of Section 16.4 on flipped real batches and updates the EMA generator after every step. The critic step returns the batch means of R1R_1 and R2R_2, so the critic's steepness on real images, Ex∥∇xD(x)∥2\mathbb{E}_x\|\nabla_x D(x)\|^2, is logged in every arm (with weight γ=0\gamma = 0 in the first). Every 250 steps the loop also applies pair_stats to 256 fresh pairs:

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()}

train_arm builds the two networks from the same seed in every arm, trains them, and returns the critic's train--holdout gap: the difference between its mean score on 1,024 training images and on 1,024 held-out images.

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)

A penalized step costs more than an unpenalized one, because the penalty differentiates the critic's input gradient a second time. After each run we print the critic's loss and penalty, averaged over the eight checks of the last 2,000 steps, and the train--holdout gap.

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

Both penalized critics settle moderately below their equilibrium values (1.041.04 vs. 2log⁡2≈1.392\log 2 \approx 1.39 for classic logistic; 0.47–0.510.47\text{--}0.51 vs. log⁡2≈0.69\log 2 \approx 0.69 for pairing), whereas the unpenalized critic drops to 0.57–0.580.57\text{--}0.58.

16.5.3.2 Training Traces and Generated Samples#

Plotting the critic's squared input gradient Ex[∥∇xD(x)∥2]\mathbb{E}_x[\|\nabla_x D(x)\|^2], the pairwise ranking accuracy P^(D(x)>D(x′))\hat P(D(x) > D(x')), and the relativistic rank weight wRp=E[σ(D(x′)−D(x))]w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))] every 250 steps shows how the gradient penalty stabilizes training:

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()

Without R1+R2R_1 + R_2, the critic's squared gradient norm climbs by two orders of magnitude (reaching 1–81\text{--}8 vs. ∼0.01\sim 0.01 for the penalized critics). While all three critics order >90%> 90\% of pairs correctly, the penalized critics maintain a small score margin (wRp∈[0.25,0.40]w_{\mathrm{Rp}} \in [0.25, 0.40], corresponding to a median logit difference around 0.70.7), whereas the unpenalized critic drives wRpw_{\mathrm{Rp}} below 0.150.15.

To compare sample quality visually, we first define a helper tile_images that arranges a batch of images in [−1,1][-1, 1] into a single [0,1][0, 1] grid:

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()

We now evaluate all four EMA generators—DCGAN and the three normalization-free arms—on the same 64 latent vectors z_show and tile their outputs into 8×88 \times 8 grids:

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);

Without batch normalization or gradient penalties, the NS arm suffers complete mode collapse (producing a uniform gray texture across all 64 latent codes; see Exercise 4). Adding R1+R2R_1 + R_2 (NS + R1 + R2 and RpGAN + R1 + R2) prevents collapse and produces diverse, centered sprite silhouettes on clean white backgrounds.

16.5.4 Quantitative Evaluation Metrics#

Visual inspection easily spots catastrophic collapse, but comparing two working generators requires quantitative metrics. Standard GAN evaluation embeds nn real images and nn generated images through a pretrained feature extractor ϕ(x)∈Rd\phi(x) \in \mathbb{R}^d and measures the discrepancy between the two empirical feature distributions using closed-form distances from Section 16.2.

16.5.4.1 FID and KID#

  1. Fréchet Inception Distance (FID) (Heusel et al., 2017) fits multivariate Gaussians N(μp,Σp)\mathcal{N}(\mu_p, \Sigma_p) and N(μq,Σq)\mathcal{N}(\mu_q, \Sigma_q) to the real and generated feature clouds and computes the squared Wasserstein-2 distance between them (Dowson and Landau, 1982; Givens and Shortt, 1984):
FID=∥μp−μq∥2+tr⁡ ⁣(Σp+Σq−2(Σp1/2 Σq Σp1/2)1/2).(16.5.4)\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 depends only on the first two moments of the feature distribution, and its plug-in sample covariance estimator has a positive O(1/n)O(1/n) bias at finite sample sizes (Exercise 3).

  1. Kernel Inception Distance (KID) (Bińkowski et al., 2018) computes the unbiased squared Maximum Mean Discrepancy (d2l.mmd2_unbiased, Section 16.2) using the cubic polynomial kernel k(u,v)=(u⊤v/d+1)3k(u, v) = (u^\top v / d + 1)^3, which compares feature moments up to order three (Exercise 5):
MMD^2=1np(np−1)∑i≠i′k(ϕ(xi),ϕ(xi′))+1nq(nq−1)∑j≠j′k(ϕ(xj′),ϕ(xj′′))−2npnq∑i,jk(ϕ(xi),ϕ(xj′)).(16.5.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))

16.5.4.2 A Feature Network#

Standard benchmarks compute FID and KID using 2,048D features from an ImageNet-pretrained Inception-v3 network or self-supervised DINOv2 features (Stein et al., 2023; Oquab et al., 2024). To keep this notebook self-contained, we train a lightweight 3-block CIFAR-10 classifier d2l.FeatureCNN (Section 27.9.4) at 32×3232 \times 32 resolution for 15 epochs and use its 128D penultimate layer as ϕ\phi (downsampling the 64×6464 \times 64 sprites to 32×3232 \times 32 via 2×22 \times 2 average pooling).

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)])

Using batched for memory-safe evaluation, we load CIFAR-10, train d2l.FeatureCNN at 32×3232 \times 32 resolution with random 4-pixel shifts, and verify its test-set classification accuracy:

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

16.5.4.3 Precision and Recall#

A single distance like FID or KID conflates two distinct failure modes: poor fidelity (generating unrealistic images outside the support of pp) and poor coverage (mode dropping, failing to cover parts of pp). Kynkäänniemi et al. (2019) separate them using KK-nearest-neighbor balls in feature space. Around each real feature ϕ(xi)\phi(x_i), let B(ϕ(xi),ri)B(\phi(x_i), r_i) be the Euclidean ball reaching its KK-th nearest real neighbor; define B(ϕ(xj′),rj′)B(\phi(x'_j), r'_j) analogously among the generated features (we use K=3K = 3). Then:

precision=1nq∑j=1nq1[ϕ(xj′)∈⋃iB(ϕ(xi),ri)],recall=1np∑i=1np1[ϕ(xi)∈⋃jB(ϕ(xj′),rj′)].\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}

Precision is the fraction of generated samples that fall within the estimated real feature support, while recall is the fraction of real samples covered by the estimated generated feature support. When a generator collapses to a single output, its KK-NN radii rj′r'_j shrink to zero, driving recall to 00.

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 Scoring the Runs#

We score n=4,059n = 4{,}059 samples of each generator, taken from its moving average, against all 4,059 held-out sprites. Each generator is scored on two draws of latent codes, so the second row shows how much a score moves when only the samples change. As a floor we score two disjoint sets of 4,059 training images against each other: any distance between them is estimator noise and, for FD, finite-sample bias. Because the feature network is our own, we call the scores FD and MMD2\mathrm{MMD}^2 rather than FID and KID; they cannot be compared with published values, which also use twelve times as many samples. The backbone has no tanh, so we clamp its outputs before scoring; the last two columns report the fractions of raw pixel values above +1+1 and below −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())

Each feature set is compared with that of the held-out sprites; the first row is the floor.

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%

The table highlights several key lessons:

  1. Real-versus-real baseline floor: Two disjoint sets of 4,0594{,}059 real sprites score FD≈0.2\text{FD} \approx 0.2 (due to finite-sample covariance bias), MMD^2≈0.000\widehat{\mathrm{MMD}}^2 \approx 0.000, and precision/recall of 0.950.95. Evaluating a second draw of latent codes changes FD by ≤0.2\leq 0.2.
  2. Collapse vs. penalized training: The collapsed unpenalized NS arm scores FD≈64–72\text{FD} \approx 64\text{--}72 with recall=0.00\text{recall} = 0.00 and precision≤0.07\text{precision} \leq 0.07. Adding R1+R2R_1 + R_2 reduces FD by an order of magnitude (∼3.5–5.5\sim 3.5\text{--}5.5) and raises precision to ∼0.35–0.4\sim 0.35\text{--}0.4 and recall to ∼0.4\sim 0.4.
  3. Feature-space sensitivity (DCGAN vs. penalized backbone): Even though the penalized backbone produces cleaner visual outlines and white backgrounds at 64×6464 \times 64, the 2015 DCGAN achieves a lower FD (∼2\sim 2) and MMD^2\widehat{\mathrm{MMD}}^2 in our 32×3232 \times 32 CIFAR-10 classifier features, where 2×22 \times 2 downsampling smooths out DCGAN's high-frequency blotches. Feature-space metrics always reflect the invariance and resolution of their underlying feature network.

16.5.5 Latent Interpolation and Critic Overfitting#

16.5.5.1 Latent Space Interpolation#

To check that the generator has learned a smooth mapping from latent codes to images rather than memorizing discrete templates, we linearly interpolate between 64 pairs of latent vectors, zt=(1−t)z0+tz1z_t = (1 - t)z_0 + t z_1 for t∈[0,1]t \in [0, 1], and compare the generated images G(zt)G(z_t) against pixelwise cross-fades (1−t)G(z0)+tG(z1)(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

The intermediate latent interpolants maintain the same feature precision (∼0.35–0.38\sim 0.35\text{--}0.38) as random generator draws and transition smoothly in shape and color, whereas pixelwise cross-fades produce ghosted double exposures whose precision drops in half (∼0.18–0.21\sim 0.18\text{--}0.21).

16.5.5.2 Critic Overfitting and Non-Leaking Augmentation#

With 1.6M1.6\text{M} parameters and 36,53836{,}538 training sprites, the critic sees each training image roughly 20 times over 12,000 steps. The penalized critics exhibit a very small train–holdout score gap (+0.02+0.02 to +0.05+0.05 compared to a real-versus-fake margin of ∼0.7\sim 0.7; Exercise 2). On smaller datasets or longer runs, however, discriminator memorization can degrade FID (Karras et al., 2020). The standard remedy, Adaptive Discriminator Augmentation (ADA, Karras et al. (2020)) and DiffAugment (Zhao et al., 2020), applies invertible, non-leaking augmentations to both real and generated images inside the gradient path (whereas augmenting only real images, like our horizontal flips, trains the generator to match the augmented distribution; Exercise 6).

16.5.6 Summary#

DCGAN stabilizes convolutional adversarial training under the classic logistic loss through transposed and strided convolutions, batch normalization, small weight initialization (σ=0.02\sigma = 0.02), and Adam with β1=0.5\beta_1 = 0.5. Removing batch normalization and architectural stabilizers causes the unpenalized logistic loss to collapse completely, whereas adding zero-centered gradient penalties (R1+R2R_1 + R_2) damps critic gradients by two orders of magnitude and allows a minimalist bilinear-resampling backbone to train reliably. Exponential moving averaging of the generator weights damps minimax oscillations further, provided batch-normalization running statistics are recalibrated when present. Finally, quantitative image evaluation compares real and generated feature clouds via Fréchet Distance ((16.5.4)), Kernel Inception Distance ((16.5.5)), and KK-NN precision and recall, always calibrated against a real-versus-real finite-sample floor.

16.5.7 Exercises#

  1. Gradient penalty weight and image resolution. Because ∇xD(x)\nabla_x D(x) has units of inverse length, the penalty weight γ\gamma depends on image resolution and pixel scaling.

    1. Let UU upsample a 64×6464 \times 64 image xx to 128×128128 \times 128 by replicating each pixel into a 2×22 \times 2 block, and let AA average each 2×22 \times 2 block so that D′=D∘AD' = D \circ A satisfies D′(Ux)=D(x)D'(Ux) = D(x). Express ∥∇D′(Ux)∥2\|\nabla D'(Ux)\|^2 in terms of ∥∇D(x)∥2\|\nabla D(x)\|^2, and find the penalty weight γ′\gamma' that makes the 128×128128 \times 128 penalty equal to the 64×6464 \times 64 penalty.
    2. How must γ\gamma be rescaled if pixel values are normalized to [0,1][0, 1] instead of [−1,1][-1, 1]?
    3. Relate your result in (a) to the heuristic γ∝r2/B\gamma \propto r^2 / B (for resolution rr and batch size BB) used in StyleGAN2-ADA (Karras et al., 2020).
  2. [code] Scale-free critic overfitting statistics. To compare critic memorization across objectives with different score scales, Karras et al. (2020) define

rv=E[Dtrain]−E[Dholdout]E[Dtrain]−E[Dgenerated],rt=E[sign⁡(Dtrain)].\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}
  1. Show that rvr_v is invariant to positive affine transformations D↦aD+cD \mapsto aD + c (a>0a > 0), whereas the raw gap E[Dtrain]−E[Dholdout]\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{holdout}}] scales with aa and rtr_t depends on the shift cc.
  2. For a shift-invariant pairing critic, under what transformations of DD is E[sign⁡(Dtrain−Dholdout)]\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})] invariant, and what value does it take when training and held-out scores have identical distributions?
  3. Modify train_arm to return net_D and compute rvr_v and E[sign⁡(Dtrain−Dholdout)]\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})] across 1,024 images for each of the three arms.
  1. [code] Finite-sample bias of FID versus KID.

    1. Compute the real-versus-real FD and MMD^2\widehat{\mathrm{MMD}}^2 between two disjoint sets of nn training sprites for n∈{250,500,1000,2000,4059}n \in \{250, 500, 1000, 2000, 4059\} across five random splits each.
    2. Fit a linear regression of FD against 1/n1/n and extrapolate to 1/n→01/n \to 0 (Chong and Forsyth (2020)). How large is the finite-sample bias at n=500n = 500 and n=4,059n = 4{,}059?
    3. Repeat the 1/n1/n linear fit for the RpGAN + R1 + R2 generator against held-out sprites. Because the 1/n1/n slope depends on the generator's feature covariance, explain how finite-sample bias at small nn can reverse the ranking of two generators.
  2. [code] Weight initialization and mode collapse. ● Define sample diversity as the mean pairwise feature distance of generated images on z_show divided by the mean pairwise feature distance of 64 held-out sprites.

    1. Log sample diversity and Ex[∥∇xD(x)∥2]\mathbb{E}_x[\|\nabla_x D(x)\|^2] every 500 steps over 5,000 steps for the unpenalized NS arm under He fan-in initialization and under N(0,σ2)\mathcal{N}(0, \sigma^2) initialization with σ∈{0.01,0.02,0.05}\sigma \in \{0.01, 0.02, 0.05\}. Does the spike in critic gradient norm precede the drop in diversity?
    2. Repeat the fan-in run across three seeds and measure how much the collapse step varies from seed to seed.
  3. Moments captured by FID and KID. ●

    1. Expand the cubic KID kernel k(u,v)=(u⊤v/d+1)3k(u, v) = (u^\top v / d + 1)^3 via the binomial theorem to show that the population MMD2(p,q)\mathrm{MMD}^2(p, q) equals
∑j=13(3j)d−j ∥Ep[u⊗j]−Eq[u⊗j]∥F2,(16.5.6)\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}

and thus compares the first three moments of the feature distribution.

  1. In 1D (d=1d = 1), compute the population FID and cubic-kernel MMD2\mathrm{MMD}^2 between p=N(0,1)p = \mathcal{N}(0, 1) and (i) a shifted exponential distribution X−1X - 1 with X∼Exp(1)X \sim \textrm{Exp}(1) (mean 00, variance 11, skewness 22), and (ii) the symmetric mixture 12N(−a,1−a2)+12N(a,1−a2)\tfrac12\mathcal{N}(-a, 1 - a^2) + \tfrac12\mathcal{N}(a, 1 - a^2) (0<a<10 \lt a \lt 1).
  1. Non-leaking data augmentations. ● Let FF be the horizontal flip operator and Tρr=(1−ρ)r+ρ F#rT_\rho r = (1 - \rho)r + \rho\,F_\# r be the distribution obtained by flipping samples from rr with probability ρ\rho.
    1. When only real images are flipped with ρ=12\rho = \tfrac12 (as in sample_real), the generator is trained toward T1/2pT_{1/2} p. If a fraction α\alpha of true sprites face left without a right-facing counterpart, what fraction of samples from an optimal generator will face right?
    2. When TρT_\rho is applied to both real and generated images inside the critic, use F2=IF^2 = I to show that Tρq=Tρp  ⟹  q=pT_\rho q = T_\rho p \implies q = p whenever ρ≠12\rho \neq \tfrac12 (non-leaking, Karras et al. (2020)), whereas at ρ=12\rho = \tfrac12 any distribution sharing the flip-symmetrized density of pp is indistinguishable from pp.

Discussions