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 turns noise into samples, and a discriminator learns to tell those samples from real data. The generator's only training signal is the discriminator's gradient. A sample is good when 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
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 . In step 2, the generator makes a fresh batch, the discriminator scores it, and the generator takes a step that makes call its samples real. The gradient passes through , but only 's optimiser steps.
The objective
Goodfellow et al. wrote the game as a minimax problem:
For a fixed generator with sample density , maximising the integrand pointwise gives the optimal discriminator
and putting it back gives . So, against a perfect discriminator, the generator minimises the Jensen-Shannon divergence, whose minimum is at , with everywhere (Entropy, Cross-Entropy and KL Divergence covers the divergences).
The non-saturating loss. Early in training the discriminator wins easily, , and is flat there. If , the gradient of with respect to the logit is , close to 0. In practice the generator therefore minimises instead, whose gradient is , close to 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 by training a logistic regression (the discriminator's own loss) to separate samples of from . The log-ratio of two Gaussian densities is quadratic in , so features can represent exactly. The last part checks the JSD identity by numerical integration.
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 , the minimax loss gives the generator a gradient of and the non-saturating loss gives , 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 , where real data is dense, and 0.075 at , where fakes dominate. The value at , , equals .
A two-parameter GAN in NumPy
The smallest GAN that shows the dynamics has a generator and a quadratic logistic discriminator, both updated by hand. The data is , so the right answer is , . The generator's gradient goes through the discriminator: , then the chain rule into and . The same game is played twice with different learning rates.
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 (), the generator finds the mean quickly but its spread swings from 0.062 to 0.792 and back. The mean of on fakes stays near 0.5 the whole time, because the discriminator is always a step behind. When the generator narrows, 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 (), 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 (the DCGAN recommendation, Radford et al., 2015) and with the default 0.9. The example is recorded and ran on the CPU.
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 , 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 , the value of two BCE terms when everywhere. With , 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 : 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 . learns to reject them, and the generator jumps to others. Gradient steps on a game do not have to converge.
- Vanishing gradients. If separates the two distributions perfectly, the JSD is constant at 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 , lr around | 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 is not rewarded for extreme confidence |
| spectral normalisation | divides each weight matrix of by its largest singular value, making about 1-Lipschitz (torch.nn.utils.parametrizations.spectral_norm) |
| WGAN-GP | becomes a "critic" that outputs any real number. The loss estimates the Wasserstein-1 distance, , plus a penalty 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 steps per step) for the two players, as in the NumPy example |
Conditional GANs feed a label to both players, and , 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 , and the next generator step uses those stale gradients unlessopt_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 means is confused, which can also happen when both players are bad. Measure the samples.
- Batch norm in 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 , 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
- From the integrand , derive .
Answer
For fixed , write , and maximise over . The derivative is , so . The second derivative is negative, so this is a maximum.
- In the NumPy GAN with , 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, 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 , not about the samples. The sample spread, measured directly, shows that the generator was wrong most of the time.
- The 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 instead of minimising ?
- It has a different optimum
- When the discriminator confidently rejects fakes (), the minimax loss has a gradient near 0 while the non-saturating loss has a gradient near
- It removes the need for a discriminator
- It is cheaper to compute
For a fixed generator, what is the optimal discriminator?
- everywhere
- 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?
- Posterior collapse
- Overfitting
- (Partial) mode collapse
- Vanishing gradients
What does the gradient penalty in WGAN-GP constrain?
- The generator's weights to norm 1
- The critic's gradient norm with respect to its input to stay near 1, so the critic is approximately 1-Lipschitz
- The learning rate
- The number of discriminator steps