Session S24
A generative adversarial network (GAN) learns its loss: a second network is trained to tell real samples from generated ones. How do the two networks train each other, why does that training collapse and how do we see it, why can a winning discriminator stop teaching the generator, how do we judge samples without a likelihood, and what became of GANs?
Deep Learning · CS 4715/5715 · University of Idaho
Two course items come first.
S23, in its own words:
S23's loss is a formula that we wrote down. Today trains such a decoder with no encoder, against a second network.
Each part answers one clause of the title page's question.
| part | the question it answers |
|---|---|
| 1 · The game | how do the two networks train each other? The objective, the best discriminator, and the training step in code |
| 2 · Collapse | why does training collapse, and how do we see it? A run you can watch, on two modes and then on eight |
| 3 · Distance | why can a winning discriminator stop teaching? The gradient vanishes, we measure it, and a different loss restores it |
| 4 · Evaluation | how do we judge samples without a likelihood? Scores computed from samples, and what one number can hide |
| 5 · History | what became of GANs? Diffusion took over; the adversarial loss stayed |
| 6 · Close | six common mistakes, today's answer, next time |
Each of Parts 1–5 ends on a self-check. First, why a learned loss.
Part 1 · The game. First, where the blur of VAE images comes from, computed on real images:
S23's VAE scores its samples with a loss written down, and a pixelwise squared (Gaussian) loss gives the blurry average just shown. A generative adversarial network (GAN; Goodfellow et al., 2014) trains the loss instead:
Nobody writes down what a good sample looks like: a second network learns the difference.
\(D\) and \(G\) push the same output, \(D(G(\mathbf{z}))\), in opposite directions: the adversarial game.
\(D\) raises \(V\) and \(G\) lowers it: one network's gain is the other's loss, so this is a game.
Each expectation in \(V\) becomes a mean over a batch (the demo's two-term form):
d_loss = bce(D(x_real), ones) + bce(D(x_fake), zeros)
x_real is a batch of real samples, x_fake a batch of fakes from \(G\), and ones, zeros are their labels, all (128, 1).D returns a logit; bce = nn.BCEWithLogitsLoss() applies the sigmoid and returns the mean BCE, a scalar.The code never writes min or max: it lowers two losses in turn. \(D\)'s loss is \(-V\); \(G\)'s loss uses only \(D(G(\mathbf{z}))\).
The first step: the best \(D\) for a fixed \(G\). From here on, \(\mathbf{x}\) is any point in data space, real or generated.
At each \(\mathbf{x}\), the best \(D(\mathbf{x})\) is the \(y\) that maximizes \(f(y)\).
The previous page's problem at one \(\mathbf{x}\): maximize \(f(y)=a\log y+b\log(1-y)\) over \(0<y<1\), with \(a=p_{\text{data}}(\mathbf{x})\), \(b=p_g(\mathbf{x})\), \(y=D(\mathbf{x})\):
\(D^*(\mathbf{x})\) is the probability that \(\mathbf{x}\) is real: the share of the density at \(\mathbf{x}\) that is real data.
Remember 1.386: it shows up in today's runs.
\(G\)'s term \(\log(1-D(G(\mathbf{z})))\) is flat exactly when \(G\) is losing (the loss saturates):
g_loss = bce(D(x_fake), ones).Write \(D\) for \(D(G(\mathbf{z}))=\operatorname{sigmoid}(\ell)\). S03 gave the sigmoid's derivative, \(\partial D/\partial\ell=D(1-D)\); the chain rule then gives:
\[\text{original loss:}\quad\frac{\partial\log(1-D)}{\partial\ell}=\frac{-1}{1-D}\,D(1-D)=-D\] \[\text{non-saturating loss:}\quad\frac{\partial(-\log D)}{\partial\ell}=\frac{-1}{D}\,D(1-D)=D-1\]Where the original loss has almost no gradient, the non-saturating loss keeps one near \(-1\).
Reading 4.2's demo (torch, torch.nn as nn, seed 0): the data are single numbers, half near −2 and half near +2.
torch.manual_seed(0)
# Real data: 1D mixture, half N(-2, 0.5^2), half N(+2, 0.5^2)
def real_batch(n): # returns (n, 1)
side = (torch.rand(n, 1) < 0.5).float() * 4 - 2 # each sample's center: -2 or +2, at random
return side + 0.5 * torch.randn(n, 1) # plus noise with standard deviation 0.5
G = nn.Sequential(nn.Linear(1, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1))
D = nn.Sequential(nn.Linear(1, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1))
| object, for a batch of 128 | code | shape |
|---|---|---|
| noise \(z\sim\mathcal{N}(0,1)\), one number per sample | torch.randn(128, 1) | (128, 1) |
| fake samples \(G(\mathbf{z})\); \(G\) a 1→32→32→1 MLP | G(z) | (128, 1) |
| real samples \(\mathbf{x}\), from the data | real_batch(128) | (128, 1) |
| \(D\)'s logits \(\ell\), one per sample | D(x) | (128, 1) |
The code's D returns logits \(\ell\), and \(D(\mathbf{x})=\operatorname{sigmoid}(\ell)\) is the probability that \(\mathbf{x}\) is real.
The demo of the previous slide (seed 0), with G, D and real_batch as defined there; each network has its own Adam optimizer:
opt_g = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999)) # beta1 = 0.5, below Adam's
opt_d = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999)) # default 0.9: less momentum
bce = nn.BCEWithLogitsLoss()
ones, zeros = torch.ones(128, 1), torch.zeros(128, 1)
for step in range(2001): # 2001, so that step 2000 is printed too
# --- discriminator step ---
x_real = real_batch(128)
x_fake = G(torch.randn(128, 1)).detach()
d_loss = bce(D(x_real), ones) + bce(D(x_fake), zeros)
opt_d.zero_grad(); d_loss.backward(); opt_d.step()
# --- generator step (non-saturating loss) ---
x_fake = G(torch.randn(128, 1))
g_loss = bce(D(x_fake), ones)
opt_g.zero_grad(); g_loss.backward(); opt_g.step()
Each step draws fresh batches; each optimizer updates only its own network.
.detach(), \(D\)'s loss also sends gradients into \(G\)In the discriminator step, the fake batch should be detached: G(z).detach().
opt_g.zero_grad() ran before the discriminator step, those gradients would be added to \(G\)'s update and training would be silently worse.Three questions on Part 1.
(a) At some \(\mathbf{x}\), \(p_{\text{data}}(\mathbf{x})=0.3\) and \(p_g(\mathbf{x})=0.1\). What is \(D^*(\mathbf{x})\)?
(b) \(D(G(\mathbf{z}))=0.02\) on a fake. How large is the gradient on the logit under the original loss, and under the non-saturating loss?
(c) Without .detach(), who gets gradients from d_loss.backward()? Does \(G\)'s update change in the demo's loop?
(a) \(0.3/(0.3+0.1)=0.75\).
(b) \(D=0.02\) against \(1-D=0.98\), about 50 times stronger.
(c) \(D\) and \(G\). No: opt_g.zero_grad() clears those gradients before \(G\)'s update; the cost is a wasted backward pass.
\(D\) classifies; \(G\) learns from \(D\)'s gradient; each optimizer updates only its own network.
Part 2 · Collapse. Every network before today trained on one loss, with a descent direction on it (reading 4.2):
This instability is a structural failure of best-response dynamics, not of bad hyperparameters; hyperparameters decide how severe it is.
Two numbers, not a GAN: \(x\) wants \(V=xy\) small, \(y\) wants it large (\(\partial V/\partial x=y\), \(\partial V/\partial y=x\)). Equilibrium \((0,0)\), learning rate 0.1, start \((1,0)\).
| distance to \((0,0)\) after step | 1 | 50 | 100 | 200 |
|---|---|---|---|---|
| simultaneous | 1.005 | 1.28 | 1.64 | 2.70 |
| alternating | 1.005 | 0.99 | 1.02 | 1.02 |
Neither order reaches \((0,0)\): the two players keep circling the equilibrium.
The demo's data has two modes, at −2 and +2. What best responses predict (a schematic, not a run):
Prediction. The demo trains for 2,000 steps and prints its progress every 250. At step 250, will \(G\) cover both modes? Could you tell from the two losses?
Coverage: what share of \(G\)'s samples lies near each mode. real_batch (the setup slide) draws half its points near −2 and half near +2; these lines print the coverage every 250 steps of the training loop:
for step in range(2001):
# ... the two updates of each step (the training-step slide), then:
if step % 250 == 0:
with torch.no_grad():
s = G(torch.randn(4000, 1)) # (4000, 1)
left = ((s + 2).abs() < 1).float().mean().item() # share within 1 of -2
right = ((s - 2).abs() < 1).float().mean().item() # share within 1 of +2
print(f"step {step:4d} D loss {d_loss.item():.4f} G loss {g_loss.item():.4f} "
f"near -2: {left:.3f} near +2: {right:.3f}")
left and right: the share of 4,000 fresh samples within 1 of −2 and of +2. Real data in the same windows: 48% and 48% (each mode holds half the data and puts 95% of its points within 2 sd (1.0) of its center). The two shares need not add to 1: the rest of the samples lie near neither mode.d_loss and g_loss are that step's batch losses.Answer: no, and the losses do not show it. Reading 4.2's printout (seed 0):
step 0 D loss 1.3810 G loss 0.8556 near -2: 0.000 near +2: 0.000
step 250 D loss 1.0758 G loss 1.0564 near -2: 0.949 near +2: 0.000
step 500 D loss 0.9873 G loss 1.1501 near -2: 0.870 near +2: 0.000
step 750 D loss 1.3852 G loss 0.8334 near -2: 0.223 near +2: 0.331
step 1000 D loss 1.3553 G loss 0.7481 near -2: 0.433 near +2: 0.211
step 1250 D loss 1.3392 G loss 0.7115 near -2: 0.474 near +2: 0.329
step 1500 D loss 1.3392 G loss 0.7200 near -2: 0.468 near +2: 0.377
step 1750 D loss 1.3759 G loss 0.7092 near -2: 0.453 near +2: 0.426
step 2000 D loss 1.3621 G loss 0.7391 near -2: 0.464 near +2: 0.435
Coverage, not the losses, shows the collapse at step 250 and the recovery by step 2000.
The two right-hand columns, plotted against the step:
The predicted cycle happened: collapse by step 250, \(D\) ahead by 500, \(G\) moved by 750.
The two loss columns, on the same steps:
The losses show which network is ahead, not whether the samples cover the data.
modes_covered counts the samples near each centerThe measurement on the ring, and what the run prints:
angles = torch.arange(8) * (2 * torch.pi / 8)
centers = torch.stack([2 * torch.cos(angles), 2 * torch.sin(angles)], dim=1) # (8, 2)
def modes_covered(samples): # samples: (n, 2)
d = torch.cdist(samples, centers) # (n, 8): distance from each sample to each center
nearest = d.argmin(dim=1) # (n,): index of the nearest center
hit = d.min(dim=1).values < 0.45 # (n,) True where that center is within 0.45
# nearest[hit] keeps the hits' center indices; bincount counts each index 0..7: (8,)
counts = torch.bincount(nearest[hit], minlength=8) # minlength=8: an empty mode counts 0
return (counts.float() / len(samples) >= 0.02).sum().item(), counts.tolist()
# the demo's loop (2-number noise, 3,001 steps) prints modes_covered every 500 steps
step 0 D loss 1.3226 G loss 0.6931 modes covered: 0/8
step 500 D loss 1.4362 G loss 0.6343 modes covered: 2/8
step 1000 D loss 1.0848 G loss 0.9441 modes covered: 4/8
step 1500 D loss 1.3097 G loss 0.8107 modes covered: 6/8
step 2000 D loss 1.3044 G loss 0.7653 modes covered: 7/8
step 2500 D loss 1.3096 G loss 0.7395 modes covered: 8/8
step 3000 D loss 1.3032 G loss 0.7528 modes covered: 8/8
final per-mode sample counts (of 4000): [223, 315, 410, 387, 300, 249, 384, 361]
\(G\)'s samples after training, over the data:
Counting samples per mode, like modes_covered, is a check worth adding to your report.
Three questions on Part 2.
(a) From step 250 to 500, \(D\)'s loss fell from 1.08 to 0.99 while 87% of the samples still sat near −2. Is the falling \(D\) loss a sign that training is failing?
(b) Another run ends with \(D\) loss 1.38 and \(G\) loss 0.70. Is its generator good?
(c) On the ring, a model puts 500 samples in each of 4 windows and none in the other 4 (of 4,000 samples). How many modes are covered, and what share of the samples is inside a window?
(a) No: \(D\) caught the overpopulated left mode, and its rejection pushed \(G\)'s mass toward +2 by step 750.
(b) Not shown: an undertrained \(D\) gives values near \(2\log2\) and \(\log2\) too. Measure the samples.
(c) 4/8 (each holds 12.5%, above 2%); 50% in all.
Coverage counts caught a collapse that the losses did not show.
Part 3 · Distance. Put Part 1's \(D^*\) into \(V\):
\[V(D^*,G)=-\log4+2\,\mathrm{JS}(p_{\text{data}}\,\|\,p_g)\]\(\mathrm{JS}(p\,\|\,q)=\tfrac12\mathrm{KL}(p\,\|\,m)+\tfrac12\mathrm{KL}(q\,\|\,m)\) with \(m=(p+q)/2\), the average of \(p\) and \(q\).
Under the original loss, training \(G\) against the best \(D\) lowers a JS divergence.
Arjovsky and Bottou (ICLR 2017): if the two distributions do not overlap, then on the data \(m=p_{\text{data}}/2\), so \(\mathrm{KL}(p_{\text{data}}\,\|\,m)=\log2\); likewise for \(p_g\):
Reading 4.2's test (seed 0): the "generator" is a cloud at a trainable offset \(\mu\), so its whole update is one number, \(\partial L/\partial\mu\). For each offset mu_val (the printout's mu; distance \(=2-\mu\)), \(D\) is trained for 500 steps, then:
real = 2.0 + 0.25 * torch.randn(512, 1) # real data: a cluster at +2, (512, 1)
eps = 0.25 * torch.randn(512, 1) # fixed noise for the fake cloud
# D: a 1→64→64→1 MLP, Adam lr 1e-3, 500 steps on real against mu_val + eps
mu = torch.tensor(mu_val, requires_grad=True)
sat = torch.log(1 - torch.sigmoid(D(mu + eps)) + 1e-12).mean() # 1e-12: avoids log(0) if D = 1
sat.backward()
g_sat = mu.grad.abs().item() # saturating: minimize log(1 - D(fake))
mu = torch.tensor(mu_val, requires_grad=True)
bce(D(mu + eps), torch.ones(512, 1)).backward()
g_nonsat = mu.grad.abs().item() # non-saturating: minimize -log D(fake)
# |W grad|: |d(-C(fake).mean())/d mu| for a WGAN-GP critic C trained the same way
# (WGAN-GP: Wasserstein GAN with gradient penalty; no sigmoid, slope held near 1; two pages on)
mu distance D(fake) |sat grad| |non-sat grad| |W grad|
1.5 0.5 0.2175 1.738256 5.7076 0.9699
0.0 2.0 0.0006 0.005676 4.2828 1.0837
-2.0 4.0 0.0002 0.000913 4.0846 1.0729
-5.0 7.0 0.0002 0.000324 1.5993 1.2986
-8.0 10.0 0.0001 0.000137 1.0781 1.4658
The previous page's three gradient columns on a log scale (the third is a WGAN-GP critic's, next page):
The Wasserstein GAN (Arjovsky, Chintala & Bottou, ICML 2017) replaces JS with the Wasserstein-1 distance, the least cost of moving \(G\)'s probability mass onto the data's (moving mass twice as far costs twice as much; for two clouds of the same shape it is the distance between them). It changes smoothly with the gap, so its gradient stays informative at any distance (the previous page's green line):
The critic must stay 1-Lipschitz (previous page). Two ways to enforce it:
# real: the cluster at +2; fake = mu_val + eps; C: the critic, an MLP without a sigmoid
a = torch.rand(512, 1) # (512, 1), uniform in [0, 1)
x_hat = (a * real + (1 - a) * fake).requires_grad_(True) # between real and fake
# create_graph=True keeps this gradient differentiable: loss.backward() must reach it
# .sum(): each score depends only on its own row, so the gradient holds each row's slope
# autograd.grad returns a tuple, one gradient per input; [0] is the one for x_hat
grad = torch.autograd.grad(C(x_hat).sum(), x_hat, create_graph=True)[0] # (512, 1)
gp = ((grad.norm(2, dim=1) - 1) ** 2).mean() # norms: (512,)
loss = C(fake).mean() - C(real).mean() + 10.0 * gp
loss: the previous page's objective with its sign flipped, plus 10 times the penalty.Another way to bound the slope (Miyato et al., ICLR 2018): divide each weight matrix by an estimate of its top singular value \(\sigma_{\max}\), the most it can stretch an input. Reading 4.2 on the two-mode demo (seed 0), after 2,000 steps of Part 1's loop (near −2, near +2: the shares of \(G\)'s samples):
# layers: the demo D's five layers; spectral: True for the second run
if spectral:
layers = [nn.utils.spectral_norm(l) if isinstance(l, nn.Linear) else l
for l in layers]
| discriminator | near −2 | near +2 | \(\sigma_{\max}\) of its three weights | steepest slope of \(D\)'s logit on a grid from −6 to 6 |
|---|---|---|---|---|
| plain | 0.471 | 0.434 | 3.58, 2.03, 0.97 | 1.657 |
| spectral-norm | 0.445 | 0.463 | 1.00, 1.00, 1.00 | 0.323 |
(32, 1), (32, 32), (1, 32). ReLU never steepens a slope, so stacked layers multiply at most their \(\sigma_{\max}\): \(3.58\cdot2.03\cdot0.97\approx7.0\); normalized, at most 1. \(\sigma_{\max}\) is estimated by power iteration (repeated multiplication).Two questions on Part 3.
(a) The fake samples and the real data do not overlap. What is the JS divergence between them? The fakes then move halfway toward the data and still do not overlap. What is JS now?
(b) In slide 33's experiment, moving the fakes from distance 0.5 to distance 10 changes the saturating loss's gradient from 1.738256 to 0.000137, and the critic's gradient from 0.9699 to 1.4658. How many times smaller does the first become? How many times larger the second?
(a) \(\log2\) both times: JS does not change, so it gives \(G\) no direction.
(b) About 12,700 times smaller (\(1.738256/0.000137\)), four orders of magnitude. About 1.5 times larger (\(1.4658/0.9699\)).
A perfect \(D\) stops teaching under the original loss; a slope-bounded critic does not.
Part 4 · Evaluation. The losses do not measure sample quality (Part 2), and a held-out likelihood is not available:
Each feature set is summarized by its mean and its covariance:
| \(n\) samples | features, \(d\) each | mean | covariance |
|---|---|---|---|
| real | (n, d) | \(\boldsymbol{\mu}_r\), (d,) | \(\Sigma_r\), (d, d) |
| generated | (n, d) | \(\boldsymbol{\mu}_g\), (d,) | \(\Sigma_g\), (d, d) |
Lower is better; 0 when the two fitted Gaussians match. FID 0 means the fitted Gaussians have the same mean and covariance; it does not prove the distributions are identical.
Reading 4.2's caveats: FID is biased at small sample counts (the convention is 50,000), depends on the embedding network, and puts two failures into one number:
Three questions on Part 4.
(a) Why can't you report a GAN's held-out log-likelihood, as you would a VAE's bound?
(b) Checkpoint A scores FID 12.4 and checkpoint B 12.1, one sample draw each. Is B better?
(c) The ring at step 3000: all 8 modes covered, a third of the samples between modes. Which is lower, precision or recall?
(a) It is an implicit model: it samples, but gives no \(p_g(\mathbf{x})\) to evaluate.
(b) Not shown: the difference may be inside FID's run-to-run variance. Recompute on several draws at the same sample count.
(c) Precision: the samples between modes look like no real data, while every mode is reached.
Judge samples, not losses, and check a small FID gain against FID's spread over draws.
Part 5 · History. For about six years, GANs led image generation (reading 4.2):
Where a plain per-pixel loss gives plausible but soft output, an adversarial term adds the sharpness (reading 4.2). A conditional GAN (Mirza & Osindero, 2014) first gave both networks a label: \(G(\mathbf{z},y)\) makes class \(y\), \(D\) judges (sample, label) pairs. pix2pix (2017) does image-to-image translation (an edge map to a photo, say) from paired images:
| later work | what the adversarial loss is used for |
|---|---|
| CycleGAN (2017) | translation without pairs, with a round-trip (cycle-consistency) loss |
| SRGAN (super-resolution GAN, 2017) | super-resolution, for the texture that MSE-trained models blur |
| HiFi-GAN (2020) | speech: spectrograms to waveforms in real time |
| adversarial diffusion distillation (2023) | a diffusion sampler cut from many steps to one to four |
The adversarial loss survives as a sharpness term inside larger losses.
Two questions on Part 5.
(a) A product needs super-resolution in real time. Would you use a GAN or a naive diffusion sampler, and why?
(b) pix2pix trains with L1 plus an adversarial loss. What does each term supply?
(a) A GAN: one forward pass, against hundreds of steps.
(b) L1: the target's content. Adversarial: the sharpness that per-pixel regression averages away.
GANs survive where one forward pass or a sharpness term matters.
Part 6 · Close. Reading 4.2's common pitfalls:
| symptom | cause | fix |
|---|---|---|
| ordinary-looking losses taken as good training | losses measure the game state, not sample quality (steps 0 and 250) | track a sample statistic (mode counts, FID) at regular intervals |
| samples all near-identical | mode collapse: \(G\) wins by sending every sample where \(D\) is weakest (Part 2) | no single fix: lower learning rates, more \(D\) steps per \(G\) step, a Wasserstein objective; detect it with coverage |
| \(G\)'s loss climbs, samples stop improving | \(D\) too strong; under the saturating loss \(G\)'s gradient vanishes | the non-saturating loss; a smaller or slower \(D\); label smoothing (real labels 0.9) |
| losses blow up in the first few hundred steps | learning rates tuned for one loss; Adam's beta1 = 0.9 adds momentum that destabilizes the game | about 2e-4 with betas = (0.5, 0.999), as in the demo |
| no progress from the first steps, \(G\)'s loss flat | the saturating loss against a \(D\) that already wins (Part 3's 0.0001) | the non-saturating loss, or a WGAN-GP critic kept well trained |
| a checkpoint called better for a slightly lower FID | FID's run-to-run variance | fix the sample count; recompute over independent draws |
Back to the title page's question.