TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Generative Adversarial Networks

Generative Adversarial Networks

A VAE generates by decoding prior samples, and its per-pixel likelihood makes those samples blurry, because the decoder outputs the average of the plausible images. A generative adversarial network (GAN, Goodfellow et al., 2014) has no likelihood at all. A generator GG turns noise z\mathbf{z} into samples, and a discriminator DD learns to tell those samples from real data. The generator's only training signal is the discriminator's gradient. A sample is good when DD cannot tell it from real data, so there is no reward for averaging and samples can be sharp. The price is a training process that is a two-player game, not a minimisation, and games can oscillate or settle on a few outputs.

This lesson writes the objective down, checks two of its key facts numerically, trains a two-parameter GAN in NumPy that shows both convergence and oscillation, and trains a PyTorch GAN on eight 2-D modes where coverage can be counted. It ends with the standard stabilisation tricks and conditional GANs.

The training loop

z ~ N(0, I) G fake x real x D D(x) step 1: Dreal 1, fake 0 step 2: Gfake called 1 G's gradient flows back through D (D's weights stay fixed in step 2) data

Each iteration has two steps. In step 1, the discriminator gets a batch of real samples labelled 1 and a batch of generated samples labelled 0, and takes one gradient step on binary cross-entropy. The fakes are detached, so this step does not touch GG. In step 2, the generator makes a fresh batch, the discriminator scores it, and the generator takes a step that makes DD call its samples real. The gradient passes through DD, but only GG's optimiser steps.

The objective

Goodfellow et al. wrote the game as a minimax problem:

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼p(z)[log⁡(1−D(G(z)))]\min_G \max_D \; V(D, G) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}\left[\log D(\mathbf{x})\right] + \mathbb{E}_{\mathbf{z} \sim p(\mathbf{z})}\left[\log\left(1 - D(G(\mathbf{z}))\right)\right]

For a fixed generator with sample density pgp_g, maximising the integrand pointwise gives the optimal discriminator

D∗(x)=pdata(x)pdata(x)+pg(x)D^*(\mathbf{x}) = \frac{p_{\text{data}}(\mathbf{x})}{p_{\text{data}}(\mathbf{x}) + p_g(\mathbf{x})}

and putting it back gives V(D∗,G)=−log⁡4+2 JSD⁡(pdata∥pg)V(D^*, G) = -\log 4 + 2\, \operatorname{JSD}(p_{\text{data}} \Vert p_g). So, against a perfect discriminator, the generator minimises the Jensen-Shannon divergence, whose minimum is at pg=pdatap_g = p_{\text{data}}, with D∗=12D^* = \tfrac{1}{2} everywhere (Entropy, Cross-Entropy and KL Divergence covers the divergences).

The non-saturating loss. Early in training the discriminator wins easily, D(G(z))≈0D(G(\mathbf{z})) \approx 0, and log⁡(1−D)\log(1 - D) is flat there. If D=σ(a)D = \sigma(a), the gradient of log⁡(1−σ(a))\log(1 - \sigma(a)) with respect to the logit aa is −σ(a)=−D-\sigma(a) = -D, close to 0. In practice the generator therefore minimises −log⁡D(G(z))-\log D(G(\mathbf{z})) instead, whose gradient is −(1−D)-(1 - D), close to −1-1 in exactly that regime. Both losses push in the same direction and have the same fixed point. Only the gradient's size differs.

The first part of the code prints those gradients. The second part checks D∗D^* by training a logistic regression (the discriminator's own loss) to separate samples of pdata=N(0,1)p_{\text{data}} = \mathcal{N}(0, 1) from pg=N(1.5,0.72)p_g = \mathcal{N}(1.5, 0.7^2). The log-ratio of two Gaussian densities is quadratic in xx, so features 1,x,x21, x, x^2 can represent D∗D^* exactly. The last part checks the JSD identity by numerical integration.

python · try it yourself
import numpy as np

# The generator's gradient with respect to the discriminator's logit a on a fake sample, D = sigmoid(a)
print("  D(G(z))   saturating log(1 - D)   non-saturating -log D")
for d in (0.001, 0.01, 0.1, 0.5, 0.9):
    grad_sat = -d          # d/da log(1 - sigmoid(a)) = -sigmoid(a)     (the generator minimises this)
    grad_ns = -(1 - d)     # d/da -log sigmoid(a)     = -(1 - sigmoid(a))
    print(f"  {d:7.3f}   {grad_sat:20.3f}   {grad_ns:21.3f}")

# The optimal discriminator for fixed p_data and p_g, found by training a classifier
rng = np.random.default_rng(0)
n = 20_000
real = rng.normal(0.0, 1.0, n)                      # p_data = N(0, 1)
fake = rng.normal(1.5, 0.7, n)                      # p_g    = N(1.5, 0.7^2)
feats = lambda x: np.stack([np.ones_like(x), x, x ** 2], axis=1)   # log-ratio of two Gaussians is quadratic
F = feats(np.r_[real, fake]); t = np.r_[np.ones(n), np.zeros(n)]
w = np.zeros(3)
for _ in range(3000):                               # logistic regression = the discriminator's own loss
    p = 1 / (1 + np.exp(-F @ w))
    w -= 0.5 * F.T @ (p - t) / len(t)
pdf = lambda x, m, s: np.exp(-0.5 * ((x - m) / s) ** 2) / (s * np.sqrt(2 * np.pi))
for x in (-1.0, 0.0, 1.0, 1.5, 2.5):
    d_opt = pdf(x, 0, 1) / (pdf(x, 0, 1) + pdf(x, 1.5, 0.7))
    d_fit = 1 / (1 + np.exp(-feats(np.array([x])) @ w))[0]
    print(f"x = {x:4.1f}   p_data/(p_data + p_g) = {d_opt:.3f}   trained D = {d_fit:.3f}")

# At D*, the minimax value equals -log 4 + 2 JSD(p_data, p_g)
xs = np.linspace(-8, 8, 160_001); dx = xs[1] - xs[0]
p, q = pdf(xs, 0, 1), pdf(xs, 1.5, 0.7); mid = (p + q) / 2
jsd = 0.5 * np.sum(p * np.log(p / mid)) * dx + 0.5 * np.sum(q * np.log(q / mid)) * dx
value = np.sum(p * np.log(p / (p + q))) * dx + np.sum(q * np.log(q / (p + q))) * dx
print(f"V(D*, G) = {value:.4f}   -log 4 + 2 JSD = {-np.log(4) + 2 * jsd:.4f}   JSD = {jsd:.4f}")
  D(G(z))   saturating log(1 - D)   non-saturating -log D
    0.001                 -0.001                  -0.999
    0.010                 -0.010                  -0.990
    0.100                 -0.100                  -0.900
    0.500                 -0.500                  -0.500
    0.900                 -0.900                  -0.100
x = -1.0   p_data/(p_data + p_g) = 0.996   trained D = 0.995
x =  0.0   p_data/(p_data + p_g) = 0.874   trained D = 0.870
x =  1.0   p_data/(p_data + p_g) = 0.354   trained D = 0.360
x =  1.5   p_data/(p_data + p_g) = 0.185   trained D = 0.188
x =  2.5   p_data/(p_data + p_g) = 0.079   trained D = 0.075
V(D*, G) = -0.8108   -log 4 + 2 JSD = -0.8108   JSD = 0.2878

When the discriminator rejects a fake with D=0.001D = 0.001, the minimax loss gives the generator a gradient of −0.001-0.001 and the non-saturating loss gives −0.999-0.999, about a thousand times more signal. The trained discriminator matches the formula to within 0.006 at all five points. It is 0.870 at x=0x = 0, where real data is dense, and 0.075 at x=2.5x = 2.5, where fakes dominate. The value at D∗D^*, −0.8108-0.8108, equals −log⁡4+2⋅0.2878-\log 4 + 2 \cdot 0.2878.

A two-parameter GAN in NumPy

The smallest GAN that shows the dynamics has a generator G(z)=az+bG(z) = az + b and a quadratic logistic discriminator, both updated by hand. The data is N(1,0.52)\mathcal{N}(1, 0.5^2), so the right answer is b=1b = 1, ∣a∣=0.5\lvert a \rvert = 0.5. The generator's gradient goes through the discriminator: ∂(−log⁡D)/∂x=−(1−D)(w1+2w2x)\partial(-\log D)/\partial x = -(1 - D)(w_1 + 2 w_2 x), then the chain rule into aa and bb. The same game is played twice with different learning rates.

python · try it yourself
import numpy as np

sig = lambda t: 1 / (1 + np.exp(-t))
feats = lambda x: np.stack([np.ones_like(x), x, x ** 2], axis=1)

def train_gan(lr_d, lr_g, steps=4000, n=256, seed=0):
    rng = np.random.default_rng(seed)
    a, b = 1.0, 0.0                                 # generator G(z) = a z + b, z ~ N(0, 1)
    w = np.zeros(3)                                 # discriminator D(x) = sigmoid(w0 + w1 x + w2 x^2)
    history = []
    for step in range(1, steps + 1):
        # 1) discriminator step on real (label 1) and fake (label 0) samples; G is held fixed
        x_real = rng.normal(1.0, 0.5, n)            # data: N(1, 0.5^2)
        x_fake = a * rng.standard_normal(n) + b
        F = feats(np.r_[x_real, x_fake]); t = np.r_[np.ones(n), np.zeros(n)]
        w -= lr_d * F.T @ (sig(F @ w) - t) / (2 * n)
        # 2) generator step: non-saturating loss -mean log D(G(z)), backpropagated through D into a and b
        z = rng.standard_normal(n)
        x_fake = a * z + b
        d = sig(feats(x_fake) @ w)
        dx = -(1 - d) * (w[1] + 2 * w[2] * x_fake)  # d loss / d x_fake
        a -= lr_g * np.mean(dx * z)
        b -= lr_g * np.mean(dx)
        if step % 500 == 0:
            history.append((step, b, abs(a), d.mean()))
    return history

for lr_d, lr_g in [(0.05, 0.02), (0.5, 0.05)]:
    print(f"lr_D = {lr_d}, lr_G = {lr_g}")
    for step, mean, std, d in train_gan(lr_d, lr_g):
        print(f"  step {step:4d}  generator mean {mean:6.3f}  std {std:.3f}  mean D(fake) {d:.3f}")
print("target: mean 1.000  std 0.500")
lr_D = 0.05, lr_G = 0.02
  step  500  generator mean  1.117  std 0.135  mean D(fake) 0.496
  step 1000  generator mean  1.126  std 0.062  mean D(fake) 0.488
  step 1500  generator mean  1.103  std 0.259  mean D(fake) 0.486
  step 2000  generator mean  0.722  std 0.792  mean D(fake) 0.519
  step 2500  generator mean  1.096  std 0.251  mean D(fake) 0.496
  step 3000  generator mean  1.080  std 0.311  mean D(fake) 0.488
  step 3500  generator mean  0.840  std 0.739  mean D(fake) 0.511
  step 4000  generator mean  1.050  std 0.373  mean D(fake) 0.498
lr_D = 0.5, lr_G = 0.05
  step  500  generator mean  1.093  std 0.295  mean D(fake) 0.496
  step 1000  generator mean  0.967  std 0.561  mean D(fake) 0.497
  step 1500  generator mean  0.996  std 0.506  mean D(fake) 0.501
  step 2000  generator mean  1.018  std 0.469  mean D(fake) 0.499
  step 2500  generator mean  1.000  std 0.516  mean D(fake) 0.499
  step 3000  generator mean  0.984  std 0.497  mean D(fake) 0.495
  step 3500  generator mean  0.996  std 0.492  mean D(fake) 0.496
  step 4000  generator mean  1.010  std 0.501  mean D(fake) 0.493
target: mean 1.000  std 0.500

With a slow discriminator (ηD=0.05\eta_D = 0.05), the generator finds the mean quickly but its spread swings from 0.062 to 0.792 and back. The mean of DD on fakes stays near 0.5 the whole time, because the discriminator is always a step behind. When the generator narrows, DD needs many steps to learn that "too narrow" is detectable. By then the generator has overshot, and the cycle repeats. With a discriminator ten times faster (ηD=0.5\eta_D = 0.5), the spread settles at 0.501 and the mean at 1.010. Neither loss curve would show you this. The discriminator's output was about 0.5 in both runs. Only a measurement of the samples themselves (here their mean and spread) tells the two runs apart. That is the general lesson about GAN monitoring.

A GAN on eight modes in PyTorch (recorded)

A ring of 8 Gaussian blobs (radius 2, standard deviation 0.05) is a standard test for mode collapse, where the generator covers only some of the data's modes. Coverage can be counted: a sample is "near a mode" if it lies within 0.15 (3 standard deviations) of a centre, and a mode is covered if it gets at least a quarter of its fair share of 2000 samples. Both networks are MLPs with two hidden layers of 128 units, with LeakyReLU in the discriminator. The generator uses the non-saturating loss, written as BCE against the label 1. The same GAN is trained twice, with Adam's β1=0.5\beta_1 = 0.5 (the DCGAN recommendation, Radford et al., 2015) and with the default 0.9. The example is recorded and ran on the CPU.

python · try it yourself
import math
import torch
from torch import nn

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
angles = torch.arange(8) * 2 * math.pi / 8
centres = torch.stack([2 * torch.cos(angles), 2 * torch.sin(angles)], dim=1)   # 8 modes on a ring of radius 2

def real_batch(n):
    return centres[torch.randint(0, 8, (n,))] + 0.05 * torch.randn(n, 2)

def report(G, n=2000):
    with torch.no_grad():
        x = G(torch.randn(n, 2, device=device)).cpu()
    dist, mode = torch.cdist(x, centres).min(dim=1)
    good = dist < 0.15                                   # within 3 standard deviations of a mode
    counts = torch.bincount(mode[good], minlength=8)
    covered = int((counts > 0.25 * n / 8).sum())         # a mode counts if it gets 1/4 of its fair share
    return covered, good.float().mean().item(), counts.tolist()

def train(beta1, steps=3000, seed=0):
    torch.manual_seed(seed)
    G = nn.Sequential(nn.Linear(2, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 2)).to(device)
    D = nn.Sequential(nn.Linear(2, 128), nn.LeakyReLU(0.2), nn.Linear(128, 128), nn.LeakyReLU(0.2),
                      nn.Linear(128, 1)).to(device)
    opt_g = torch.optim.Adam(G.parameters(), lr=1e-3, betas=(beta1, 0.999))
    opt_d = torch.optim.Adam(D.parameters(), lr=1e-3, betas=(beta1, 0.999))
    bce = nn.BCEWithLogitsLoss()
    ones, zeros = torch.ones(256, 1, device=device), torch.zeros(256, 1, device=device)
    for step in range(1, steps + 1):
        # discriminator: real -> 1, fake -> 0; detach() so this step does not update G
        x_real = real_batch(256).to(device)
        x_fake = G(torch.randn(256, 2, device=device)).detach()
        loss_d = bce(D(x_real), ones) + bce(D(x_fake), zeros)
        opt_d.zero_grad(); loss_d.backward(); opt_d.step()
        # generator
        loss_g = bce(D(G(torch.randn(256, 2, device=device))), ones)   # non-saturating: -log D(G(z))
        opt_g.zero_grad(); loss_g.backward(); opt_g.step()
        if step in (500, 1500, 3000):
            covered, quality, counts = report(G)
            print(f"  step {step:4d}  D loss {loss_d.item():.3f}  modes covered {covered}/8  "
                  f"samples near a mode {quality:.2f}  per mode {counts}")

print("device:", device)
for beta1 in (0.5, 0.9):
    print(f"Adam betas ({beta1}, 0.999)")
    train(beta1)
device: cpu
Adam betas (0.5, 0.999)
  step  500  D loss 1.220  modes covered 2/8  samples near a mode 0.19  per mode [45, 150, 44, 36, 5, 65, 6, 31]
  step 1500  D loss 1.303  modes covered 8/8  samples near a mode 0.83  per mode [208, 216, 202, 217, 168, 241, 228, 182]
  step 3000  D loss 1.369  modes covered 8/8  samples near a mode 0.92  per mode [239, 235, 230, 242, 215, 263, 216, 208]
Adam betas (0.9, 0.999)
  step  500  D loss 0.778  modes covered 0/8  samples near a mode 0.04  per mode [0, 0, 0, 0, 44, 2, 0, 28]
  step 1500  D loss 0.972  modes covered 3/8  samples near a mode 0.25  per mode [177, 75, 38, 68, 25, 36, 54, 24]
  step 3000  D loss 1.054  modes covered 5/8  samples near a mode 0.76  per mode [436, 295, 10, 188, 324, 229, 39, 0]

With β1=0.5\beta_1 = 0.5, the generator covers all 8 modes by step 1500, with 92 % of its samples near a mode at step 3000 and between 208 and 263 samples per mode. The discriminator's loss rises towards 2log⁡2=1.3862 \log 2 = 1.386, the value of two BCE terms when D=12D = \tfrac{1}{2} everywhere. With β1=0.9\beta_1 = 0.9, the discriminator is stronger early (loss 0.778), and at step 1500 only 25 % of the generator's samples are near a mode. At step 3000 it covers 5 of 8 modes, and the counts are badly uneven: 436 samples at one mode, 10 and 0 at others. That is partial mode collapse, and 76 % of samples near a mode hides it. Precision-like numbers (are samples realistic?) and recall-like numbers (is every mode reached?) must be reported separately. While writing this lesson, the minimax loss was also tried on this easy task with β1=0.5\beta_1 = 0.5: it covered all 8 modes too. Its advantage shows when the discriminator wins early, as in the gradient table above.

Why GANs are hard to train, and what helps

  • No single loss to watch. The generator's loss depends on a moving discriminator. Monitor sample statistics: coverage as here, or FID (Fréchet Inception Distance) for images, which compares feature statistics of real and generated images.
  • Mode collapse. The generator finds a few outputs that fool the current DD. DD learns to reject them, and the generator jumps to others. Gradient steps on a game do not have to converge.
  • Vanishing gradients. If DD separates the two distributions perfectly, the JSD is constant at log⁡2\log 2 and its gradient is zero. When the supports of real and generated data do not overlap, which is common in high dimensions, the JSD gives the generator nothing to follow.

Common fixes, roughly from cheapest to most involved:

Technique What it does
Adam with β1=0.5\beta_1 = 0.5, lr around 2×10−42 \times 10^{-4} less momentum, so the players react to each other's current state (DCGAN)
one-sided label smoothing real labels 0.9 instead of 1, so DD is not rewarded for extreme confidence
spectral normalisation divides each weight matrix of DD by its largest singular value, making DD about 1-Lipschitz (torch.nn.utils.parametrizations.spectral_norm)
WGAN-GP DD becomes a "critic" that outputs any real number. The loss estimates the Wasserstein-1 distance, E[D(xreal)]−E[D(xfake)]\mathbb{E}[D(\mathbf{x}_{\text{real}})] - \mathbb{E}[D(\mathbf{x}_{\text{fake}})], plus a penalty λ(∥∇x^D(x^)∥−1)2\lambda (\lVert \nabla_{\hat{\mathbf{x}}} D(\hat{\mathbf{x}}) \rVert - 1)^2 on points between real and fake samples. Its gradient stays informative even when the distributions do not overlap
two time-scale updates different learning rates (or several DD steps per GG step) for the two players, as in the NumPy example

Conditional GANs feed a label yy to both players, G(z,y)G(\mathbf{z}, y) and D(x,y)D(\mathbf{x}, y), usually through an embedding concatenated to the input (Embedding Layers). You then choose the class to generate, and the discriminator rejects a sharp 3 that was asked to be a 7. Image-to-image models such as pix2pix condition on a whole input image instead of a label. Diffusion models (Diffusion Models: Training and Sampling) have replaced GANs for most image generation because they train stably. GANs are still used where one fast forward pass matters, and adversarial losses survive as parts of other systems, for example in the decoders of image tokenizers and in super-resolution.

Pitfalls

  • Forgetting detach() in the discriminator step. Without it, loss_d.backward() also computes gradients for GG, and the next generator step uses those stale gradients unless opt_g.zero_grad() clears them. It wastes compute at best and corrupts the generator's update at worst.
  • Judging by losses. A discriminator loss near 2log⁡22 \log 2 means DD is confused, which can also happen when both players are bad. Measure the samples.
  • Batch norm in DD with separate real and fake batches. The batch statistics then differ between real and fake batches, which leaks the label. Use spectral norm or layer norm in DD, or mix real and fake samples in one batch.
  • One seed, one run. GAN results vary a lot between runs. Report several seeds before claiming that a trick helps.

Practice

  1. From the integrand pdata(x)log⁡D+pg(x)log⁡(1−D)p_{\text{data}}(\mathbf{x}) \log D + p_g(\mathbf{x}) \log(1 - D), derive D∗D^*.
Answer

For fixed x\mathbf{x}, write a=pdata(x)a = p_{\text{data}}(\mathbf{x}), b=pg(x)b = p_g(\mathbf{x}) and maximise alog⁡D+blog⁡(1−D)a \log D + b \log(1 - D) over D∈(0,1)D \in (0, 1). The derivative is a/D−b/(1−D)=0a/D - b/(1 - D) = 0, so D=a/(a+b)D = a/(a + b). The second derivative is negative, so this is a maximum.

  1. In the NumPy GAN with ηD=0.05\eta_D = 0.05, the discriminator's mean output on fakes stayed between 0.486 and 0.519, while the generator's spread ranged from 0.062 to 0.792. Explain why a mean output near 0.5 does not mean the generator is good.
Answer

The discriminator is a quadratic classifier that adapts slowly. When the fake distribution changes, DD has not yet learned the new difference, so it outputs about 0.5 on fakes and on reals alike. A confused discriminator is a statement about DD, not about the samples. The sample spread, measured directly, shows that the generator was wrong most of the time.

  1. The β1=0.9\beta_1 = 0.9 run had 76 % of its samples near a mode but covered only 5 of 8 modes. Which of the two numbers would an FID-like metric penalise, and which would a "realism" score that only checks individual samples miss?
Answer

A realism score that checks samples one at a time sees 76 % good samples and misses the missing modes. FID compares the statistics of the whole sample set with the real set (means and covariances of features), so missing modes and uneven mode weights raise it. Report coverage (recall) and quality (precision) separately.

Test yourself

Why do practitioners train the generator on −log⁡D(G(z))-\log D(G(\mathbf{z})) instead of minimising log⁡(1−D(G(z)))\log(1 - D(G(\mathbf{z})))?

  1. It has a different optimum
  2. When the discriminator confidently rejects fakes (D≈0D \approx 0), the minimax loss has a gradient near 0 while the non-saturating loss has a gradient near −1-1
  3. It removes the need for a discriminator
  4. It is cheaper to compute

For a fixed generator, what is the optimal discriminator?

  1. D∗(x)=0.5D^*(\mathbf{x}) = 0.5 everywhere
  2. D∗(x)=pdata(x)/(pdata(x)+pg(x))D^*(\mathbf{x}) = p_{\text{data}}(\mathbf{x}) / (p_{\text{data}}(\mathbf{x}) + p_g(\mathbf{x}))
  3. D∗(x)=pg(x)/pdata(x)D^*(\mathbf{x}) = p_g(\mathbf{x}) / p_{\text{data}}(\mathbf{x})
  4. D∗(x)=1D^*(\mathbf{x}) = 1 for every real sample

A GAN on 8 modes puts 436 of 2000 samples at one mode and 0 at another. What is this called?

  1. Posterior collapse
  2. Overfitting
  3. (Partial) mode collapse
  4. Vanishing gradients

What does the gradient penalty in WGAN-GP constrain?

  1. The generator's weights to norm 1
  2. The critic's gradient norm with respect to its input to stay near 1, so the critic is approximately 1-Lipschitz
  3. The learning rate
  4. The number of discriminator steps