Adversarial Image Generation

Dive into Deep Learning · §16.5

Deep Convolutional GANs and Architectural Stabilization
transposed convolutions · DCGAN conventions · EMA & BatchNorm recalibration · normalization-free R3GAN backbone · FID, KID & precision/recall

Scaling from Flat Vectors to 64×64 RGB Images

Motivation

Dense MLP generators (§16.1) ignore 2D locality and gave grainy 28 \times 28 silhouettes; 64 \times 64 RGB is harder:

  • High-dimensional spatial synthesis: A 64 \times 64 RGB image contains 3 \times 64 \times 64 = 12{,}288 correlated pixel values generated from a 100-dimensional latent draw z \sim \mathcal{N}(0, I_{100}).
  • Benchmark dataset (40{,}597 Pokémon sprites): Resized to 64 \times 64 and scaled to [-1, 1], split into 36{,}538 training sprites and 4{,}059 held-out test sprites for quantitative evaluation.
  • Two guiding questions: (1) Do zero-centered gradient penalties (R_1 + R_2) replace BatchNorm and architectural stabilizers? (2) How do we score image fidelity and mode coverage without a likelihood?

36538 training and 4059 held-out images

Spatial Upsampling via Transposed Convolutions

Resolution Doubling

n_{\textrm{out}} = s(n - 1) + k - 2p

  • Resolution doubling hierarchy: Stage 1 (k = 4, s = 1, p = 0) projects 1 \times 1 \to 4 \times 4; Stages 2–5 (k = 4, s = 2, p = 1) double spatial width across 4 \to 8 \to 16 \to 32 \to 64.
  • Checkerboard overlap pitfall (Odena et al., 2016): When kernel size k is not divisible by stride s (e.g., k = 3, s = 2), adjacent output pixels receive alternating overlap counts (2, 1, 2, 1), imprinting checkerboard artifacts.

The 2015 DCGAN Architecture and Stabilizers

Architectural Conventions

Radford, Metz, and Chintala (2015) stabilized the unpenalized non-saturating logistic loss via five architectural conventions:

  1. All-convolutional hierarchy: Replace all pooling and fully connected layers with transposed convolutions in G (512 \to 256 \to 128 \to 64 \to 3) and strided convolutions in D.
  2. Batch normalization: Normalize activations after every convolution except the generator output layer and the discriminator input block.
  3. Activations, initialization & Adam: ReLU + output \tanh in G; leaky ReLU (\text{slope} = 0.2) throughout D; weights drawn from \mathcal{N}(0, 0.02^2); Adam with reduced momentum \beta_1 = 0.5.

Implementing DCGAN Generator and Critic Blocks

Code Construction

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

EMA Weight Averaging and BatchNorm Recalibration

Damping Rotational Orbits

Because minimax gradient iterates orbit around equilibrium (§16.4), their center of mass sits closer to the solution than the last iterate. We therefore sample from an exponential moving average (EMA) of the generator parameters:

  • Half-life parameterization (n_{1/2} steps, \beta = 2^{-1/n_{1/2}}): \bar{\theta} \leftarrow \beta\,\bar{\theta} + (1 - \beta)\,\theta We set the half-life to 32{,}000 images (n_{1/2} = 125 steps at batch size 256; 500 steps at batch size 64).
  • Pitfall: Stale BatchNorm statistics: Copying running mean/variance buffers from the live network mismatches the averaged weights \bar{\theta}. After training, we run 100 fresh forward batches in train() mode (0.9^{100} \approx 3 \times 10^{-5}) to recalibrate BatchNorm buffers for \bar{\theta}.
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)

DCGAN Training Results on Pokémon Sprites

20-Epoch Baseline

Training DCGAN for 20 epochs (2{,}840 steps at batch size 256, \text{lr} = 2 \times 10^{-4}, \beta_1 = 0.5) with the classic non-saturating logistic loss produces recognizable, diverse sprites:

last epoch: loss_D 0.252, loss_G 3.188
  • Visual inspection: Generated sprites exhibit diverse silhouettes and color palettes on white backgrounds, though with high-frequency blotchy textures.
  • Sub-equilibrium critic loss: Even though loss_D (\sim 0.25\text{--}0.45) remains well below the random-guessing level 2\log 2 \approx 1.39, batch normalization and \mathcal{N}(0, 0.02^2) initialization prevent mode collapse.

Why Strip BatchNorm? The R3GAN Minimalist Backbone

From Heuristics to Penalized Objectives

  • Why remove BatchNorm for R_1 + R_2? Batch normalization couples all samples in a minibatch, which invalidates the independent per-sample input gradients \nabla_{x_i} D(x_i) penalized by R_1 and R_2.
  • Minimalist normalization-free architecture (inspired by R3GAN, Huang et al., 2024):
    • Bilinear resampling + 3 \times 3 convolutions: Replaces 4 \times 4 transposed/strided convolutions to avoid checkerboard artifacts.
    • No normalization layers & no output \tanh: Both G (2.8\text{M} params, starting from a learned 4 \times 4 \times 128 constant + projected z) and D (1.6\text{M} params) use leaky ReLU (\text{slope} = 0.2) with He fan-in initialization \mathrm{Var}(w) = \frac{2}{(1 + 0.2^2)\,n_{\mathrm{in}}}.

Implementing the Normalization-Free Generator

Code Architecture

  • 4×4 stem + 4 bilinear stages: Concatenates a learned 4 \times 4 \times 128 constant tensor with a projected latent vector and upsamples via bilinear resampling + 3 \times 3 convolutions + leaky ReLU:

Implementing the Normalization-Free Generator (Code)

Code Architecture

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

Implementing the Normalization-Free Critic

Code Architecture

  • Independent batch rows: Mirrors G with four stages of 3 \times 3 convolution, leaky ReLU, and bilinear downsampling down to a 4 \times 4 feature map \phi(x) without BatchNorm:

Implementing the Normalization-Free Critic (Code)

Code Architecture

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

A Controlled Three-Arm Objective Ablation

Experimental Design

We train the normalization-free backbone three times from identical initial weights (Adam \beta_1 = 0, \beta_2 = 0.99, \text{lr} = 2 \times 10^{-4}, batch size 64, horizontal flips, EMA half-life 500 steps), changing one objective ingredient at a time:

Experimental Arm Critic Loss L(D) Gradient Penalty \frac{\gamma}{2}(R_1 + R_2) Training Steps Hypothesis Tested
NS Classic logistic (gan_loss_D) \gamma = 0 (none) 6{,}000 Does the plain backbone train without BatchNorm or penalties?
NS + R1 + R2 Classic logistic (gan_loss_D) \gamma = 10 12{,}000 Do zero-centered penalties R_1 + R_2 replace BatchNorm?
RpGAN + R1 + R2 Relativistic pairing (rpgan_loss_D) \gamma = 10 12{,}000 Does pairwise ranking improve upon penalized classic log loss?
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

Critic Steepness, Pair Accuracy, and Rank Weights

Training Dynamics Traces

Logging \mathbb{E}_x[\|\nabla_x D(x)\|^2], pairwise ranking accuracy \hat{P}(D(x) > D(x')), and the relativistic rank weight w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))] every 250 steps explains why the unpenalized run collapses:

  • Critic steepness (\mathbb{E}_x\|\nabla_x D\|^2, left): Without R_1 + R_2, critic gradient norm climbs 100\times higher (1\text{--}8 vs. \sim 0.01 for both penalized arms).
  • Accuracy vs. rank weight (middle & right): All three critics order > 90\% of pairs correctly, so ranking accuracy alone does not warn of collapse. However, the unpenalized critic drives w_{\mathrm{Rp}} below 0.15, whereas penalized critics maintain a small logit margin (w_{\mathrm{Rp}} \in [0.25, 0.40], median difference \approx 0.7).

Visual Comparison: Penalties Prevent Collapse

Generated Sprite Grids

Evaluating all four EMA generators on the same 64 latent vectors z_show:

  • Without BatchNorm or R_1 + R_2, the unpenalized NS arm collapses completely to a uniform gray texture, whereas both penalized arms (NS + R1 + R2 and RpGAN + R1 + R2) produce crisp, diverse sprite silhouettes on clean white backgrounds.

Feature-Space Evaluation: FID and KID

Quantitative Quality Metrics

To compare generators quantitatively, we embed real and generated images through a pretrained feature extractor \phi(x) \in \mathbb{R}^d and compute closed-form distances between the feature distributions:

  • Fréchet Inception Distance (FID; Heusel et al., 2017): Fits Gaussians \mathcal{N}(\mu_p, \Sigma_p) and \mathcal{N}(\mu_q, \Sigma_q) to the real and generated features and computes their squared W_2 distance: \mathrm{FID} = \|\mu_p - \mu_q\|^2 + \operatorname{tr}\!\Big(\Sigma_p + \Sigma_q - 2\big(\Sigma_p^{1/2}\Sigma_q\Sigma_p^{1/2}\big)^{1/2}\Big) Captures first two moments; exhibits positive O(1/n) finite-sample covariance bias.
  • Kernel Inception Distance (KID; Bińkowski et al., 2018): Unbiased \widehat{\mathrm{MMD}}^2 with cubic polynomial kernel k(u, v) = (u^\top v / d + 1)^3 (compares up to 3rd moments; unbiased at any sample size n).

Feature-Space Evaluation: FID and KID (Code)

Quantitative Quality Metrics

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

Fidelity vs. Coverage: k-NN Precision and Recall

k-NN Support Estimation

A single distance like FID or KID conflates poor sample fidelity (unrealistic artifacts) with poor mode coverage (mode dropping). Kynkäänniemi et al. (2019) separate them using K-nearest-neighbor balls (K = 3) in feature space:

  • Around each real feature \phi(x_i), draw the Euclidean ball B(\phi(x_i), r_i) reaching its K-th nearest real neighbor; define B(\phi(x'_j), r'_j) analogously among generated features: \mathrm{precision} = \frac{1}{n_q}\sum_{j=1}^{n_q}\mathbb{1}\!\left[\phi(x'_j) \in \bigcup_i B\big(\phi(x_i), r_i\big)\right] \mathrm{recall} = \frac{1}{n_p}\sum_{i=1}^{n_p}\mathbb{1}\!\left[\phi(x_i) \in \bigcup_j B\big(\phi(x'_j), r'_j\big)\right]
  • When a generator collapses to one output, its radii r'_j \to 0, driving \mathrm{recall} \to 0.

Fidelity vs. Coverage: k-NN Precision and Recall (Code)

k-NN Support Estimation

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

Scoring Runs Against a Real-vs.-Real Floor

Scoring 4,059 Sprites

Using 128D features from our 3-block CIFAR-10 classifier FeatureCNN (64 \times 64 sprites average-pooled to 32 \times 32), we score n = 4{,}059 generated samples against the 4{,}059 held-out sprites across two independent latent draws:

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%
  • 1. Real-vs.-real floor: Two disjoint real sets score \mathrm{FD} \approx 0.18 (finite-sample covariance bias), \widehat{\mathrm{MMD}}^2 \approx 0.000, and precision/recall 0.95.

Scoring Runs Against a Real-vs.-Real Floor (cont.)

Scoring 4,059 Sprites

  • 2. Collapse vs. penalized arms: Unpenalized NS scores \mathrm{FD} \approx 64\text{--}72 with \mathrm{recall} = 0.00; adding R_1 + R_2 reduces FD tenfold (\sim 3.5\text{--}5.5) and restores precision to \sim 0.35\text{--}0.4 and recall to \sim 0.4.
  • 3. Feature-network invariance: Because 2 \times 2 pooling into 32 \times 32 FeatureCNN smooths out DCGAN’s high-frequency blotches, DCGAN achieves the lowest FD (\sim 2.0) despite looking blotchier at 64 \times 64.

Latent Space Interpolation vs. Pixel Cross-Fades

Testing Manifold Smoothness

To check that RpGAN + R1 + R2 learns a smooth image manifold rather than memorizing discrete templates, we linearly interpolate between 64 pairs of latent codes, z_t = (1 - t)z_0 + t z_1 (t \in [0, 1]), and compare G(z_t) against pixelwise cross-fades (1 - t)G(z_0) + t G(z_1):

  • On-manifold transitions: Intermediate latent steps maintain the generator’s full 3-NN feature precision (\sim 0.35\text{--}0.38) and transition smoothly in shape and color without discrete jumps.
  • Off-manifold cross-fades: Pixelwise blends create ghosted double exposures whose feature precision drops in half (\sim 0.18\text{--}0.21).

precision of the inner steps: latent walk 0.35, cross-fade 0.21

Critic Overfitting and Non-Leaking Augmentation

Small-Data Generalization Pitfall

  • Small-dataset overfitting hazard: Under R_1 + R_2, the train–holdout critic gap stays tiny (+0.02\text{--}0.05) on 36{,}538 sprites, but smaller datasets require data augmentation to prevent critic memorization.
  • Why augmenting only real images leaks: Applying a random flip T_\rho only to real images trains G to match T_\rho p (generating right-facing copies of strictly left-facing sprites).
  • Non-leaking augmentation (ADA / DiffAugment): Apply invertible T_\rho (\rho \neq \frac{1}{2}) to both real and generated images inside D so T_\rho q = T_\rho p \implies q = p.

Concept Check: Convolutions, Metrics, and Flips

Check Your Understanding

Test your understanding of convolutional GAN architectures and evaluation metrics:

  1. Resolution scaling of \gamma: Suppose a 64 \times 64 image x is upsampled to 128 \times 128 by replicating each pixel into a 2 \times 2 block (Ux), and a 128 \times 128 critic D'(Ux) = D(x) averages each 2 \times 2 block back. How does \|\nabla D'(Ux)\|^2 compare to \|\nabla D(x)\|^2, and how must \gamma' scale with resolution r to keep the penalty invariant?
  2. Diagnosing failure modes from Precision and Recall: Generator A achieves (\text{precision}, \text{recall}) = (0.78, 0.01), whereas Generator B achieves (\text{precision}, \text{recall}) = (0.12, 0.68). Which failure mode does each generator exhibit?

Answers:

  1. Because each pixel of x is split across 4 pixels of Ux with weight \frac{1}{4} each, \|\nabla D'(Ux)\|^2 = 4 \cdot \frac{1}{16}\|\nabla D(x)\|^2 = \mathbf{\frac{1}{4}\|\nabla D(x)\|^2}. To keep the penalty invariant when resolution doubles, the weight must quadruple: \gamma' = 4\gamma \propto r^2.
  2. Generator A has high precision but near-zero recall: it suffers from mode collapse (emitting realistic samples from only one or a few modes). Generator B has low precision but high recall: it covers the data support broadly but produces many low-fidelity / noisy outlier images.

Concept Check: Convolutions, Metrics, and Flips (cont.)

Check Your Understanding

  1. Leaking horizontal flips: Suppose a fraction \alpha of true sprites face left with no right-facing counterpart, while all other sprites are mirror-symmetric. If only real training images are flipped with probability \frac{1}{2}, what fraction of generated samples from an optimal generator will face right?

Answer:

  1. The generator matches the flip-symmetrized distribution T_{1/2}p, in which half of the asymmetric left-facing mass \alpha is flipped to face right—so a fraction \alpha / 2 of generated samples will face right.

Summary: Convolutional GANs and Image Evaluation

Key Takeaways

  • From DCGAN heuristics to R3GAN: Bilinear resampling + 3 \times 3 convolutions eliminate transposed-conv checkerboards, while removing BatchNorm keeps batch rows independent for exact per-sample R_1 + R_2 gradient penalties.
  • EMA weight averaging: Smooths out rotational minimax orbits (\bar{\theta} \leftarrow \beta\bar{\theta} + (1-\beta)\theta); requires 100 fresh train() passes to recalibrate BatchNorm buffers when BatchNorm is present.
  • Complementary feature metrics: Calibrate FID against the +O(1/n) real-vs.-real floor, use KID for unbiased finite-n comparisons, and report K-NN precision and recall to separate fidelity from mode coverage.