Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 5 · Thu 2/15/2024 · Implicit Models — Generative Adversarial Networks, first part (slides 1–70): motivation (GAN progress, BigGAN, GAN art), what an implicit model is and why it departs from maximum likelihood, the original GAN (Goodfellow et al., 2014) and its pseudocode, evaluation (Parzen windows, Inception Score, Fréchet Inception Distance), some theory (the Bayes-optimal discriminator, Jensen–Shannon divergence, KL vs reverse KL, mode collapse, discriminator saturation and the non-saturating loss), DCGAN, the “improved techniques” of Salimans et al. (2016), and f-GAN. Homework 3, Question 1. Basis: The slides state the results; these notes derive them (the optimal discriminator, the JSD identity, the saturation of the minimax gradient, the f-divergence bound) and then check every one numerically on 1-D and 2-D distributions whose densities are known exactly. On ShapeWorld, where every sample can be judged exactly (valid, novel, how many pixels from a valid image), they test what the sample-based scores — Parzen windows, Inception Score, FID, and precision / recall (added by these notes) — actually measure. Code:
code/lecture09/(4 scripts +gan_tools.py; PyTorch (CPU); scripts 01–02 run in under a minute, 03 in ~2–5 minutes, 04 ~8 minutes the first time (models cached)) Reading time: 3.5 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Say what an implicit model is, how it differs from the flows and VAEs of Lectures 5–8, and what is gained and lost by giving up the likelihood.
- Write the GAN objective and its alternating training loop, and say what each player maximizes.
- Derive the Bayes-optimal discriminator and show that, against it, the generator minimizes .
- Explain mode covering vs mode seeking with KL, reverse KL and JSD, and why GANs drop modes.
- Explain discriminator saturation and why the non-saturating loss fixes it — and why Adam partly hides the problem.
- Describe DCGAN’s architecture rules and the improved techniques (minibatch discrimination, feature matching, historical averaging, virtual batch norm, one-sided label smoothing).
- State the f-GAN variational bound and use it to estimate a divergence with a trained critic.
- Compute Parzen-window likelihoods, the Inception Score, FID and precision / recall, and say what each of them can and cannot detect.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| KL divergence, maximum likelihood (Lectures 1–2) | implicit models, the GAN game, the optimal discriminator | Wasserstein GANs, gradient penalties, spectral normalization (Lecture 10) |
| reverse KL and mode seeking (Lecture 5’s distillation) | JSD, mode collapse, saturation, f-divergences | large GANs: BigGAN, StyleGAN, GigaGAN (Lecture 10) |
| ShapeWorld and its exact yardsticks (Lectures 1, 3) | sample-based evaluation: Parzen, IS, FID, precision / recall | adversarial losses inside tokenizers: VQGAN (Lecture 10); FID for diffusion models (Lectures 11–12) |
0.3 Map
§1 implicit models: what if all we want is samples?
§2 the GAN game and its training loop
§3 theory: the optimal discriminator, Jensen-Shannon, mode covering vs seeking, f-GAN ← code 01
§4 saturation and the non-saturating loss (homework 3 Q1) ← code 02
§5 mode collapse and the "improved techniques" ← code 03
§6 DCGAN, and a DCGAN on ShapeWorld ← code 04, Part 1
§7 evaluating samples without a likelihood: Parzen, IS, FID, precision / recall ← code 04, Parts 2-4
§8 summary §9 pitfalls §10 exercises §11 further reading §12 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| , | generator , ; the distribution of its samples (never written down) |
| discriminator: probability that is real; with logit | |
| the game’s value | |
| , ; between 0 and | |
| , | convex function of an f-divergence and its convex conjugate |
| IS, FID | Inception Score; Fréchet Inception Distance |
0.5 How the experiments are run
- 1-D and 2-D data with exact densities. Scripts 01–03 use a homework-3-like two-bump distribution on , Gaussians, and a ring of 8 narrow Gaussians (radius 2, standard deviation 0.02; Metz et al., 2016). Divergences are computed exactly by quadrature on a 60,001-point grid, so a trained discriminator can be compared with the truth.
- ShapeWorld. Script 04 trains a DCGAN on Lecture 1’s 10,000 binary 12 × 24 images and judges samples with the exact yardsticks of Lecture 3: valid (pixel-perfect ShapeWorld image), novel valid (valid and not a training image) and flips (pixel changes to the nearest valid image).
- Our “Inception network”. A small CNN trained on 50,000 fresh ShapeWorld images to recognize every latent factor (both shapes, sizes and positions; 99.8–100% accurate). Its 128-dimensional features stand in for Inception’s pool3 features, its left-shape head for the ImageNet classifier.
- Everything is seeded and single-threaded; reruns print identical numbers.
1. Implicit models: what if all we want is samples?
A generative model can be asked for four things: samples, likelihoods, training by some criterion, and a representation. Lectures 2–8 all trained by (a bound on) maximum likelihood — exactly for autoregressive models and flows, approximately for VAEs. This lecture asks the question the slides pose: what if all we care about is sampling?
A sampler that is not a model. The simplest sampler returns a random training image. Its samples are perfect — and useless: it cannot produce anything new, does not interpolate, and has learned nothing about the factors of variation (new stroke styles of a digit, new poses of a face, a square at a position the training set happened to miss). We want a sampler that understands the distribution well enough to produce similar but new samples. Keep this “copier” in mind: §7 shows that several popular scores cannot tell it apart from a real generative model.
Implicit models. Draw noise from a fixed simple distribution (uniform or Gaussian) and pass it through a deep network: . That sounds like a flow or a VAE decoder — and the sampling procedure is the same. What is different is how is trained: without evaluating any density. A flow needs invertible to compute ; a VAE needs an encoder and a noise model to bound it. An implicit model defines only through its sampling procedure — no inverse, no noise model, no likelihood. Training must therefore compare samples with samples.
Why give up the likelihood? Three reasons, each tested later:
- Freedom of architecture. Any network works — no invertibility, no tractable Jacobian, no per-pixel noise model.
- Fast sampling. One forward pass, like a flow or VAE (Lecture 3’s PixelCNN needed 288 passes per image).
- Optimizing what we care about. Maximum likelihood (KL from the data to the model) punishes a model hard for missing any data, so it spreads mass — and blurs (Lecture 7’s VAE samples: blobs). If the goal is samples that look right, a criterion that punishes unrealistic samples may be better (§3.3).
The price: no likelihood to report, compare, or use for compression; and — as we will see — a training procedure that is a game, not an optimization.
2. The GAN game
2.1 Two players
Goodfellow et al. (2014) train two networks against each other:
- The discriminator is a binary classifier: real data are labelled 1, generated samples 0. It maximizes the log-likelihood of this classification problem.
- The generator tries to make its samples be classified as real: it minimizes the log-probability that the discriminator calls them fake.
Together:
The intuition (the slides’ counterfeiter and police): the discriminator learns what is wrong with the current samples; its gradient tells the generator how to change them.
2.2 The training loop
The pseudocode of the paper, in words:
for each training iteration:
for k steps: # the inner "max over D", done approximately
draw a minibatch of noise z_1..z_m and a minibatch of data x_1..x_m
update D by ascending (1/m) Σ [log D(x_i) + log(1 − D(G(z_i)))]
draw a minibatch of noise z_1..z_m
update G by descending (1/m) Σ log(1 − D(G(z_i))) # (§4 replaces this by −log D(G(z_i)))
gan_tools.train_gan implements exactly this (with d_steps = k), with hooks for every variant in this lecture and the next. Two practical details:
- The discriminator works with logits , . Then and — never the log of 0.
- In the discriminator step the fake samples are detached: D’s update must not change G.
The 2014 samples (MNIST, TFD faces, CIFAR-10) were promising but rough; the slides then follow a decade of progress up to BigGAN. The online GAN Lab (poloclub.github.io/ganlab) shows the game on 2-D data live.
2.3 What makes this different from everything before
There is no single loss going down. ’s loss and ‘s loss pull against each other, and a good training run often shows the discriminator loss hovering around (the value of everywhere) while the samples still change. “Convergence” is a property of a game (a saddle point), not of a minimization — §4 and §5 show what this costs.
3. Some theory, checked numerically
3.1 The Bayes-optimal discriminator
Fix . Writing both expectations as integrals over ,
For each separately, is maximized at (set the derivative to 0). So
The optimal discriminator outputs the posterior probability that is real when real and fake are equally likely a priori — a density-ratio estimator: . (This is the root of “density ratio estimation by classification”, used again for noise-contrastive estimation and contrastive learning in Lectures 13–14.)
3.2 What the generator minimizes: Jensen–Shannon
Plug in, and write :
So if the discriminator were optimal at every step, the generator would minimize the Jensen–Shannon divergence, which is 0 exactly when . Two remarks:
- is never available; a trained gives , a lower bound on . Training D estimates the divergence; training G then descends the estimate.
- JSD is bounded: , with whenever the two distributions do not overlap. Hold that thought (§3.4).
Experiment (script 01, Part 1). Data: (homework-3-like); a fixed “generator” . A 3-layer MLP trained by logistic regression on fresh samples, 4,000 steps:
| quantity | trained network | exact |
|---|---|---|
| mean on | 0.014 | 0 |
| max (in the tails) | 0.105 | 0 |
| (by quadrature) | −0.9648 | −0.9627 |
| implied JSD | 0.2108 | 0.2118 |
The network finds closely (left panel of figures/01_gan_theory.png) and its value sits just below the exact one, as the bound says.

3.3 KL, reverse KL, JSD: mode covering vs mode seeking
Three divergences, three behaviours when the model family is too small to fit the data exactly:
- — maximum likelihood. The penalty is huge wherever data exist but is small: the model must cover every mode, even at the cost of mass where there are no data. Good for compression (every data point gets probability); bad for samples (blurry averages between modes).
- — reverse KL. The penalty is huge wherever the model puts mass but data are absent: the model seeks one mode and ignores the rest. Samples look right; diversity is lost. (Lecture 5 met this in IAF distillation.)
- JSD is symmetric and bounded, and sits in between.
The slides’ caveat matters: a more expressive model (a mixture instead of one Gaussian) can place mass accurately and the difference shrinks. The behaviours appear when the model cannot fit the data — which, for a GAN generator on real images, is always.
Experiment (script 01, Part 3). Fit one Gaussian to by grid search over , for each divergence:
| bumps at | minimized | ‘s mass where < 5% of its peak | ||
|---|---|---|---|---|
| ±2 | KL() | −0.40 | 2.01 | 42.8% |
| ±2 | KL() | −2.00 | 0.50 | 1.4% |
| ±2 | JSD | −2.00 | 0.50 | 1.4% |
| ±1.5 | KL() | −0.30 | 1.57 | 24.7% |
| ±1.5 | KL() | −1.50 | 0.52 | 1.8% |
| ±1.5 | JSD | −0.30 | 1.57 | 24.7% |
Maximum likelihood always straddles both bumps and puts a quarter to almost half of its mass where there are no data. Reverse KL always locks onto the bigger bump. JSD seeks a mode when the bumps are far apart and covers both when they are close. That is the theoretical root of the GAN’s two famous properties: sharp samples and dropped modes.
3.4 The trouble with JSD: no signal when distributions do not overlap
Experiment (script 01, Part 2). Data , generator ; slide away and watch each divergence and its derivative (central differences):
| KL | JSD | ||||
|---|---|---|---|---|---|
| 0.10 | 0.5 | 0.111 | 2.0 | 0.10 | 1 |
| 0.20 | 2.0 | 0.337 | 2.3 | 0.20 | 1 |
| 0.50 | 12.5 | 0.676 | 0.24 | 0.50 | 1 |
| 0.75 | 28.1 | 0.693 | 0.005 | 0.75 | 1 |
| 1.00 | 50 | 0.693 | 0.00002 | 1.00 | 1 |
| 2.00 | 200 | 0.693 | 0 | 2.00 | 1 |
Once the generator’s samples stop overlapping the data (here about 7 standard deviations away), JSD sits at and its gradient is numerically zero: a perfect discriminator tells the generator nothing about which way to move. In high dimensions this is the normal situation at the start of training — real images and random samples occupy thin, essentially disjoint sets. KL is no better (infinite for disjoint supports). The Wasserstein distance (the “earth mover’s” cost of moving one distribution onto the other) keeps growing linearly with slope 1 at any distance; Lecture 10 builds a GAN on it.
3.5 f-GAN: a whole family of divergences
The JSD identity is one case of a general trick (Nguyen, Wainwright & Jordan, 2010; Nowozin et al., 2016). An f-divergence is for a convex with (KL: ; reverse KL: ). Every convex equals the supremum of its tangent lines, , with the convex conjugate. Substituting and moving the sup outside the integral (which can only lower it):
with equality at . A neural network (the critic) trained to maximize the right side estimates the divergence from samples only; a generator trained to minimize it gets an f-GAN. The original GAN is the case , whose value is .
Experiment (script 01, Part 4). Critics with the output activations of Nowozin et al. (Table 2), evaluated by quadrature:
| f-divergence | critic’s bound | exact | gap |
|---|---|---|---|
| GAN () | −0.9648 | −0.9627 | 0.0021 |
| Jensen–Shannon () | 0.4215 | 0.4236 | 0.0021 |
| KL() | 1.4823 | 1.4858 | 0.0034 |
| reverse KL() | 0.9378 | 0.9400 | 0.0023 |
All four bounds land within 0.004 nats of the truth. (The GAN and JS rows are the same critic: the two objectives differ only by the constant .) Lesson: a GAN’s discriminator is a divergence estimator; the choice of — or, in Lecture 10, of an integral probability metric — decides what the generator minimizes.
4. Saturation and the non-saturating loss
4.1 The slides’ mini-exercise
Is it feasible to run the inner maximization over D to completion? Would it create problems if we could? It is not feasible (a full optimization per generator step), and it would create problems: §3.4 showed that an optimal discriminator gives no useful gradient when the distributions are far apart. The same happens through the sigmoid, even before optimality.
4.2 Where the gradient goes
Write the generator’s loss through the logit , with :
- minimax: , so ;
- non-saturating: , so .
Both push the logit up. But when the discriminator confidently rejects a sample ( — the normal situation early in training) the minimax gradient is and the non-saturating gradient (script 02, Part 1: at the ratio is 999). The non-saturating loss keeps the same fixed point (both are minimized by making large) but is no longer zero-sum: G does not minimize the quantity D maximizes. The slides list the two remedies: alternate single steps (so D never gets too far ahead) and use the non-saturating loss.
4.3 Experiment: homework 3 Q1 (script 02)
Part 2 — an ordinary start. 20,000 points from the two-bump distribution; generator and discriminator are homework 3’s 3-layer MLPs (128 units, LeakyReLU 0.2); Adam , batch 128, 3,000 steps. JSD between the exact and a kernel density estimate of 200,000 generator samples (the measurement’s noise floor is 0.0000):
| generator loss | evaluated | JSD @ 500 | 1,000 | 1,500 | 2,000 | 2,500 | 3,000 |
|---|---|---|---|---|---|---|---|
| minimax | G | 0.092 | 0.078 | 0.067 | 0.130 | 0.059 | 0.112 |
| EMA of G (0.99) | 0.011 | 0.061 | 0.061 | 0.033 | 0.055 | 0.068 | |
| non-saturating | G | 0.041 | 0.235 | 0.238 | 0.083 | 0.086 | 0.200 |
| EMA of G (0.99) | 0.320 | 0.136 | 0.144 | 0.092 | 0.075 | 0.089 |
From this easy start both losses work about equally well — and neither converges: the JSD jumps between 0.04 and 0.24 from one checkpoint to the next, while the discriminator outputs 0.48–0.50 everywhere and its loss sits at . does not mean ; it means this discriminator, at this moment, cannot tell them apart. The left panels of figures/02_hw3_q1.png show what the generator does instead: sharp spikes on the two bumps, without their tails — mode-seeking at the scale of a single bump. Averaging the generator’s weights over time (an exponential moving average, the idea behind the slides’ historical averaging and the EMA generators of later GANs) damps the oscillation: final JSD 0.07–0.09 instead of 0.11–0.20.

Part 3 — a bad start. Shift the generator’s output to +2.5 (the data live in ) and pretrain the discriminator for 500 steps: . Then train with each loss:
| optimizer | loss | ‖∇ G loss‖ at the start | mean of G(z) @ 200 | @ 600 | @ 2,000 | JSD @ 2,000 |
|---|---|---|---|---|---|---|
| SGD 0.001 | minimax | 0.0022 | +2.47 | +2.47 | +2.46 | 0.693 |
| SGD 0.001 | non-saturating | 27 | −1.73 | −0.19 | −0.18 | 0.281 |
| SGD 0.01 | minimax | 0.0022 | +2.46 | +2.38 | −0.33 | 0.517 |
| SGD 0.01 | non-saturating | 27 | −0.19 | +0.18 | −0.52 | 0.334 |
| Adam 0.001 | minimax | 0.0022 | −0.68 | −0.25 | −0.06 | 0.517 |
| Adam 0.001 | non-saturating | 27 | −0.86 | +0.17 | −0.22 | 0.097 |
(data mean −0.17). With plain SGD — the optimizer of the original paper — the minimax generator does not move in 2,000 steps: its gradient is 10,000× smaller and the JSD stays at . With a 10× larger step it escapes after ~600 steps. The non-saturating generator reaches the data within 200 steps.
Plan vs reality. The plan was “minimax fails, non-saturating works”. With Adam, both move: Adam divides each gradient by a running estimate of its magnitude, so a consistently tiny gradient still produces steps of size ~learning rate. Saturation is then hidden rather than cured — the non-saturating run still ends far closer (JSD 0.10 vs 0.52). This is one reason the minimax loss is rarely seen failing in modern code: the optimizer masks it.
5. Mode collapse and the “improved techniques”
5.1 Mode collapse
The slides’ figure (Metz et al., 2016): a GAN trained on a mixture of Gaussians on a ring covers one mode at a time and rotates between them during training. Two causes we have already met:
- the divergence: JSD (and reverse KL) are mode-seeking (§3.3);
- the dynamics: for a fixed D, the best response of G is to put all its mass on the single point D likes most; D then learns to reject that point, and G moves on. Alternating gradient steps approximate this chase. Nothing in the per-sample objective rewards diversity — each generated sample is judged alone.
5.2 The improved techniques of Salimans et al. (2016)
| technique | idea |
|---|---|
| minibatch discrimination | let D see the whole batch: append to each sample’s features a measure of how close it is to the other samples, so a collapsed batch is easy to reject |
| feature matching | train G to match the mean of D’s intermediate features on real data, , instead of fooling D’s output |
| historical averaging | penalize each player’s parameters for straying from their running average (a damping term for the oscillations of §4.3) |
| virtual batch normalization | normalize each sample with statistics of a fixed reference batch, so outputs do not depend on the other samples in the batch |
| one-sided label smoothing | ask D for 0.9 instead of 1 on real data (never smooth the fake label: that would reward D for putting mass where ) |
| semi-supervised GAN | let D predict class labels in addition to real / fake; approximate without a conditional generator |
They also introduced the Inception Score (§7.2).
5.3 Experiment (script 03)
Ring of 8 Gaussians (radius 2, standard deviation 0.02); generator and discriminator MLPs as in homework 3; Adam , batch 256, 5,000 steps, 3 seeds. A sample is good if within 3 standard deviations of a mode (98.9% of exact samples); a mode is covered if it gets at least a fifth of its fair share; balance is the entropy of the good samples’ mode histogram (3 bits = perfectly even).
| variant | modes covered (3 seeds) | good samples | balance (bits) |
|---|---|---|---|
| standard GAN (non-saturating) | 2, 2, 4 | 54% | 1.54 |
| minimax loss | 2, 2, 2 | 12% | 2.17 |
| 5 D steps per G step | 1, 1, 1 | 81% | 0.00 |
| + one-sided label smoothing | 2, 4, 4 | 29% | 2.12 |
| + feature matching | 0, 0, 0 | 4% | 2.42 |
| + minibatch discrimination | 0, 1, 1 | 3% | 0.90 |
| 2,000 exact samples | 8 | 99% | 3.00 |

What the numbers and the figure say:
- The standard GAN covers 2–4 of 8 modes. The figure shows how: its samples lie on a C-shaped curve through about five modes, with much of the mass on the bridges between them. A generator is a continuous map from a connected noise space, so it cannot jump between islands — it can only stretch thin. During training (Part 2 of the script) almost no sample is good for 2,000 steps; then one mode sharpens, later a second. The right side of the ring is never reached.
- A stronger discriminator makes collapse worse: with 5 D steps per G step every seed ends on a single mode — with the sharpest samples (81% good). The generator chases whatever region the current D likes best.
- The minimax loss covers the ring loosely with few good samples: its weak gradients keep the generator blurry.
- The improved techniques did not fix collapse here. Label smoothing helps a little (2–4 modes). Feature matching spreads samples over the whole ring (balance 2.4) but almost none lands on a mode: matching a mean is too weak a target to sharpen samples (it is the technique Salimans et al. used for semi-supervised learning, not for sample quality). Minibatch discrimination (8 kernels of size 4, untuned) did not help at all in our runs.
Plan vs reality. The plan expected the Metz et al. picture (the generator rotating through single modes) and expected the improved techniques to cover more modes. We saw a curve through several modes rather than rotation, and of the techniques only label smoothing helped a little. Mode collapse is a property of the game, and these heuristics are not robust fixes. Lecture 10’s Wasserstein critics and gradient penalties are the next attempt.
6. DCGAN
6.1 Architecture rules
Radford et al. (2016) found a convolutional architecture that trains stably — “GANs could be made to work well with architecture details”:
- no pooling: strided convolutions to downsample in D, transposed convolutions to upsample in G;
- batch normalization in both networks, except at G’s output and D’s input;
- ReLU in G (tanh at the output), LeakyReLU(0.2) in D;
- Adam with a small learning rate () and momentum (instead of 0.9), batch 128.
The results: good samples from 3 million images of faces and bedrooms for the first time; smooth interpolations in (rooms morphing into rooms, not cross-fading); vector arithmetic (average of “smiling woman” − “neutral woman” + “neutral man” decodes to a smiling man); and D’s features as a representation for classification. The open problems the slides list: unstable training and brittle architectures / hyperparameters.
6.2 A DCGAN on ShapeWorld (script 04, Part 1)
Setup. The generator maps through a linear layer to a tensor, then two stages of (nearest-neighbour upsampling ×2, 3×3 convolution, batch norm, ReLU) and a final 3×3 convolution with a sigmoid: a 12 × 24 image in . The discriminator is two strided 4×4 convolutions with LeakyReLU(0.2) and a linear layer — no batch norm, so that Lecture 10’s gradient penalties can be added to the same network. Non-saturating loss, Adam with , batch 64, 8,000 steps (~5 minutes on one CPU thread). Samples are thresholded at 0.5 before the exact checks.
| step | valid | valid panels | flips to the nearest valid image |
|---|---|---|---|
| 2,000 | 0.0% | 0.0% | 24.8 |
| 4,000 | 0.0% | 0.0% | 28.4 |
| 6,000 | 0.0% | 0.0% | 25.8 |
| 8,000 | 0.0% | 0.0% | 25.3 |
The samples (bottom row of figures/04_samples.png) are sharp — 1.3% of their pixels are gray, against 15% for Lecture 7’s VAE — and have roughly the right sizes and positions, but the shapes are irregular blobs: not one of 2,000 samples is a valid ShapeWorld image, and on average 25 pixels must flip to reach one, as many as for the blurry VAE. The nearest training images are 22–53 pixels away: the generator is not copying.
Plan vs reality. The plan was a DCGAN with a fraction of valid samples, to be improved in Lecture 10. Calibration runs tried hard to get there, and none did:
- on the two-panel images, 14 recipes for 10,000–12,000 steps each: transposed vs upsampling generators, discriminators of different depth, batch norm in D, learning rates 1e-4 to 4e-4 (also two time-scale), batch 128, hinge loss with spectral normalization, the R1 penalty ( = 0.1 and 1), instance noise. The transposed-convolution DCGAN collapsed to a single image; all others ended at 0% valid with 23–32 flips;
- on single 12 × 12 panels (an easier problem: 960 configurations), fully connected GANs collapsed to one image, and the best convolutional GAN reached 0.3% valid panels (6.7 flips per panel) after 32,000 steps.
Exactness is a very high bar: one wrong pixel makes a shape invalid. Likelihood models reach it because every pixel is a term of their loss (Lecture 4’s Transformer: 90% valid); a GAN’s generator only gets the discriminator’s opinion, and a small convolutional discriminator does not care whether a diamond has one pixel too many. What GANs do deliver — sharpness — is exactly what the scores of §7 reward.
7. Evaluating samples without a likelihood
A GAN cannot report test bits. The slides call evaluation “still an open problem” and present three answers; these notes add a fourth (precision / recall) and check all of them against ShapeWorld’s exact truth.
7.1 Parzen windows
Put a kernel on every generated sample and use the resulting density as a stand-in for : , with the bandwidth chosen on a validation set; report of test images (Goodfellow et al., 2014, did this for MNIST and TFD). Theis, van den Oord & Bethge (2016) showed it is unreliable: in high dimensions the estimate is dominated by the bandwidth, far from the true log-likelihood, and can rank models in the wrong order.
For binary images we use the kernel that flips each pixel independently with probability : with the Hamming distance. Then is a proper distribution over all binary images, and is in bits per image — directly comparable with the exact 17.80.
7.2 Inception Score
Side-step density estimation: a good generator’s samples should each be recognizable (a classifier’s has low entropy) and collectively diverse (the marginal has high entropy). Salimans et al. (2016) combine both:
with from an Inception-v3 network trained on ImageNet. It is at most the number of classes. It never looks at real data, so — the slides’ criticism — a list of one perfect image per class gets a perfect score.
7.3 Fréchet Inception Distance
Heusel et al. (2017): embed real and generated images with Inception’s 2048-dimensional pool3 features, fit a Gaussian to each set, and compute the Fréchet (Wasserstein-2) distance between the Gaussians:
It compares with real data, so it notices missing diversity; it is a distance between two Gaussians, so it sees only first and second moments of the features.
7.4 Precision and recall (added by these notes)
One number cannot separate “bad samples” from “missing modes”. Kynkäänniemi et al. (2019) estimate the manifold of each feature set as the union of balls reaching each point’s -th nearest neighbour (): precision = fraction of generated samples inside the real manifold (quality); recall = fraction of real samples inside the generated manifold (coverage).
7.5 Experiment: what the scores see (script 04, Parts 2–4)
The sample sets. 2,000 images each, judged against 2,000 fresh real images (FID, precision / recall, and the test images of the Parzen window):
- real images (held-out) — the ideal;
- copies of training images — the “sampler” of §1;
- real, only 4 of 8 shape kinds — mode dropping;
- 8 real images, one per class, repeated — the slides’ Inception Score cheat;
- real + 3 random pixel flips — almost right, never valid;
- samples of Lecture 7’s VAE (decoder means), Lecture 8’s VQ-VAE + Transformer, Lecture 4’s Transformer on 2×2 patches, and this lecture’s DCGAN.
| sample set | valid | novel valid | flips | gray pixels | IS | FID | precision | recall | Parzen bits |
|---|---|---|---|---|---|---|---|---|---|
| real images (held-out) | 100% | 87.2% | 0.0 | 0% | 7.91 | 323 | 0.95 | 0.93 | 128.7 |
| copies of training images | 100% | 0.0% | 0.0 | 0% | 7.89 | 382 | 0.95 | 0.94 | 128.7 |
| real, only 4 of 8 shape kinds | 100% | 85.7% | 0.0 | 0% | 4.02 | 9,099 | 0.95 | 0.55 | 148.5 |
| 8 real images (1 per class), repeated | 100% | 75.0% | 0.0 | 0% | 8.00 | 65,069 | 1.00 | 0.00 | 228.5 |
| real + 3 random pixel flips | 0% | 0% | 3.0 | 0% | 7.68 | 563 | 0.94 | 0.93 | 135.6 |
| VAE, decoder means (L7) | 0% | 0% | 25.3 | 14.8% | 5.20 | 17,518 | 0.69 | 0.32 | 163.8 |
| Transformer, 2×2 patches (L4) | 89.6% | 81.0% | 0.7 | 0% | 7.82 | 590 | 0.93 | 0.95 | 130.6 |
| VQ-VAE + Transformer (L8) | 26.1% | 20.8% | 6.7 | 2.6% | 7.29 | 1,595 | 0.93 | 0.88 | 133.8 |
| DCGAN (this lecture) | 0% | 0% | 25.2 | 1.3% | 4.52 | 19,044 | 0.79 | 0.29 | 177.5 |
(IS: maximum 8 here. Exact entropy of the data: 17.80 bits; the Transformer’s exact test bits: 18.8.)

Reading the table score by score:
- Inception Score is fooled exactly as the slides warn: eight images, one per class, get 8.00 — more than real data (7.91). It catches class dropping (4.02 for 4 of 8 kinds) and unrecognizable samples (VAE 5.20, DCGAN 4.52), but it never compares with real images, so it cannot catch anything else.
- FID catches mode dropping (9,099) and blur (VAE 17,518), but not memorization — training copies score like held-out real images (382 vs 323; Part 3 shows this difference is sampling noise) — and not exact validity: real images with 3 flipped pixels, none of them valid, get 563, better than the Transformer whose samples are 90% valid (590). FID lives in feature space, and the features (like Inception’s) are deliberately insensitive to a few pixels.
- Precision and recall separate the two failure modes FID mixes: the 4-of-8 set keeps precision 0.95 and loses recall (0.55); the 8-image set has precision 1.00 and recall 0.00. The DCGAN has higher precision than the VAE (0.79 vs 0.69: sharper, more realistic-looking samples) and lower recall (0.29 vs 0.32: less coverage) — the mode-seeking story of §3.3, measured. Like FID, neither sees memorization or invalidity.
- Parzen windows give 129 bits for real samples when the truth is 17.8, give training copies exactly the score of real samples (both are 2,000 draws from ), and their ranking of the generative models (Transformer < VQ-VAE < VAE < DCGAN) is roughly right but their values say nothing about bits. Part 4 of the script: the same samples score anywhere from 129 to 208 bits depending on the bandwidth.
- FID is biased by the sample size (Part 3, two sets of real images): 3,169 at 250 images, 1,418 at 500, 765 at 1,000, 437 at 2,000, 147 at 4,000. A FID is only comparable with FIDs computed with the same number of images and the same feature network.
Lesson. Every sample-based score is a projection: IS onto class confidence and diversity, FID onto two moments of a feature space, precision / recall onto feature-space neighbourhoods, Parzen onto a kernel’s view of distance. None of them sees memorization; none of them sees exactness. On real data there is no ShapeWorld oracle, which is why papers report several scores, check nearest training neighbours, and — when a likelihood exists — report it too. The DCGAN in the bottom row is the honest summary of this lecture’s GAN: sharper than the VAE, no more correct.
8. Summary
- An implicit model defines only through a sampler ; training compares samples with samples. It gains architectural freedom and fast sampling and loses the likelihood.
- The GAN is a two-player game: D classifies real vs fake, G tries to be classified real; training alternates gradient steps.
- For a fixed G the optimal discriminator is , a density-ratio estimator; against it G minimizes . A trained D gives a lower bound (script 01: within 0.002 nats).
- Maximum likelihood covers modes, reverse KL seeks one, JSD seeks when modes are far apart (script 01). Mode seeking is why GAN samples are sharp — and why GANs drop modes.
- JSD saturates at when distributions do not overlap, and its gradient vanishes (script 01: at 10 standard deviations); the Wasserstein distance keeps a slope of 1 (Lecture 10).
- f-GAN: every f-divergence has a variational lower bound ; a trained critic reaches it within 0.004 nats for KL, reverse KL and JSD.
- The minimax loss saturates: its gradient is , tiny when D rejects samples. The non-saturating loss has gradient . With SGD the minimax generator did not move in 2,000 steps from a bad start; Adam hides the problem by rescaling gradients.
- GAN training does not converge in the usual sense: the JSD oscillated between 0.04 and 0.24 while D sat at . Averaging the generator’s weights damps the oscillation.
- Mode collapse on the 8-Gaussian ring: 2–4 modes covered, samples on a continuous curve between islands; more discriminator steps made it worse (1 mode); the “improved techniques” did not fix it.
- DCGAN made GANs work on real images with architecture rules (strided convolutions, batch norm, LeakyReLU, Adam with ). On ShapeWorld our DCGAN gives sharp samples, none of them valid — after 14 calibration recipes.
- IS, FID, precision / recall and Parzen windows each project the samples onto something partial: none sees memorization or exactness; IS can be cheated with one image per class; FID depends on the sample size; Parzen values are 110 bits from the truth.
9. Common pitfalls
- Reading “D outputs 1/2” or “D loss = log 4” as convergence. It means the current discriminator cannot tell the distributions apart, not that they are equal (script 02: JSD up to 0.24 at that point).
- Using the minimax generator loss. It saturates exactly when the generator is bad. Use the non-saturating loss; and do not conclude from an Adam run that saturation is harmless.
- Smoothing the fake labels. One-sided label smoothing only softens the real target. Smoothing fake labels too rewards D for assigning “real” probability to generated samples, which pushes G to stay where it is.
- Batch norm couples samples. A generator with batch norm behaves differently in train and eval mode; sample in eval mode, after training. A discriminator with batch norm cannot be combined with per-sample gradient penalties (Lecture 10).
- Comparing FIDs computed with different numbers of samples or different feature networks. FID at 250 images is 20× FID at 4,000 for the same distribution.
- Trusting the Inception Score alone. It never looks at real data; a handful of class prototypes beats real data.
- Reporting Parzen-window log-likelihoods for implicit models. They are dominated by the bandwidth and orders of magnitude off.
- Treating sharp samples as correct samples. The DCGAN’s samples are crisp and 0% valid; check nearest training neighbours and, where possible, an exact criterion.
- One seed. GAN outcomes vary strongly between seeds (script 03: 2 vs 4 modes for the same recipe). Report several.
10. Exercises
Exercise 1 (the optimal discriminator — derivation). Show that for fixed , is maximized by , and that . What is when , and what is then?
Answer
with , ; for each the integrand is concave in with derivative , zero at . Substituting: ; write and split off twice: . At : everywhere and , the global minimum over (JSD ≥ 0).
Exercise 2 (saturation — derivation). With , compute of and of . Show that both generator losses are minimized by the same , and explain why only one of them is useful when .
Answer
, derivative . , derivative . Both decrease monotonically as grows, so both are minimized by pushing . At the first derivative is (no signal) while the second is (full signal). The gradient with respect to G’s parameters is this factor times , which is the same for both.
Exercise 3 (JSD of disjoint distributions). Show that whenever and have disjoint supports. Then compute the Wasserstein-1 distance between and (point masses) and between the segments and .
Answer
Where , and , so ; likewise ; , independent of how far apart the supports are. (move the unit mass a distance ); for the segments, move every point to : cost , and no plan can do better since every point must move at least horizontally. So , with derivative — the motivation of Lecture 10.
Exercise 4 (f-GAN for KL — derivation). For compute the convex conjugate , the optimal critic , and check that .
Answer
at , giving . , so . Then and ; the difference is .
Exercise 5 (mode covering). Fit to any by minimizing . Show that the optimum matches the mean and variance of . Use it to explain the first row of script 01’s Part 3 table ().
Answer
. Setting derivatives to zero: , . For the mixture: mean ; variance , — the table’s −0.40 and 2.01 (grid resolution).
Exercise 6 (Inception Score bounds). Show that under the joint , that for classes, and which sample sets reach the maximum.
Answer
. Mutual information is between 0 and . The maximum needs (every image classified with certainty) and (classes equally often) — satisfied by prototype images repeated equally often, whatever else is wrong with the set. Script 04: 8.00.
Exercise 7 (FID in one dimension). For two 1-D Gaussians show that FID . Why does a finite-sample FID between two samples of the same distribution come out positive, and how does it scale with the sample size ?
Answer
In 1-D, . With finite samples the estimated means and covariances differ by sampling noise of size ; their squares are and always non-negative, so the expected FID of two equal distributions is with growing with the feature dimension — script 04’s 3,169 → 147 from = 250 to 4,000 (roughly ).
Exercise 8 (why Parzen windows cannot see memorization). Explain why a Parzen window built from 2,000 training images gives the same estimate as one built from 2,000 fresh samples of , in expectation. What would detect the memorizer?
Answer
The training images are a sample of , independent of the (fresh) test images, so the two windows are identically distributed estimators — the score cannot distinguish “this model copies its training set” from “this model samples ”. A test that compares samples with the training set detects it: nearest-neighbour distances to training images, or the novelty rate (script 04: 0% novel valid for the copier).
Exercise 9 (feature matching). Feature matching minimizes for D’s features . Give a generator distribution that achieves zero loss without resembling the data. Relate this to script 03 (balance 2.4 bits, 4% good samples).
Answer
Any with the same feature mean: e.g. if were linear, any distribution with the data’s mean — a Gaussian blob at the center of the ring has the same mean as the ring. Matching one moment of a fixed feature map leaves almost everything else free; the generator spreads samples so that the average matches, without putting them on the modes. Hence a well-balanced but blurry ring.
Exercise 10 (coding). In script 03, change the ring’s standard deviation to 0.1 and rerun. Does the standard GAN cover more modes? Does the “curve between islands” picture change? Why?
Answer
(Run it.) Wider modes overlap the bridges the generator draws between them, so more samples count as good and more modes reach a fifth of their fair share; the connected-curve structure remains, but it now costs less because the islands are closer to touching.
11. Further reading
From the slides
- I. Goodfellow et al. Generative Adversarial Nets, NeurIPS 2014; I. Goodfellow. NIPS 2016 Tutorial: Generative Adversarial Networks, 2016.
- A. Radford, L. Metz, S. Chintala. Unsupervised Representation Learning with Deep Convolutional GANs (DCGAN), ICLR 2016.
- T. Salimans et al. Improved Techniques for Training GANs (minibatch discrimination, feature matching, historical averaging, virtual batch norm, label smoothing, Inception Score), NeurIPS 2016.
- M. Heusel et al. GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium (FID), NeurIPS 2017.
- L. Theis, A. van den Oord, M. Bethge. A Note on the Evaluation of Generative Models, ICLR 2016.
- L. Metz, B. Poole, D. Pfau, J. Sohl-Dickstein. Unrolled Generative Adversarial Networks (the mode-collapse figure), ICLR 2017.
- S. Nowozin, B. Cseke, R. Tomioka. f-GAN: Training Generative Neural Samplers using Variational Divergence Minimization, NeurIPS 2016.
- A. Brock, J. Donahue, K. Simonyan. Large Scale GAN Training for High Fidelity Natural Image Synthesis (BigGAN), ICLR 2019 — Lecture 10.
Added by these notes
- X. Nguyen, M. Wainwright, M. Jordan. Estimating Divergence Functionals and the Likelihood Ratio by Convex Risk Minimization, IEEE Trans. Inf. Theory 2010 — the variational bound behind f-GAN.
- T. Kynkäänniemi et al. Improved Precision and Recall Metric for Assessing Generative Models, NeurIPS 2019; M. S. M. Sajjadi et al. Assessing Generative Models via Precision and Recall, NeurIPS 2018.
- M. Lucic et al. Are GANs Created Equal? A Large-Scale Study, NeurIPS 2018 — most GAN variants reach similar scores given enough tuning; report several seeds.
- A. Odena, V. Dumoulin, C. Olah. Deconvolution and Checkerboard Artifacts, Distill 2016 — why script 04’s generator upsamples and then convolves.
- L. Mescheder, A. Geiger, S. Nowozin. Which Training Methods for GANs Do Actually Converge?, ICML 2018 — the R1 penalty (Lecture 10).
12. Next lecture
Lecture 9’s GAN minimizes a divergence that gives no gradient when distributions do not overlap, oscillates instead of converging, drops modes, and — on ShapeWorld — produces sharp but invalid images. Lecture 10 follows the field’s answers: the Wasserstein distance and the Kantorovich–Rubinstein duality (a critic that must be 1-Lipschitz), and three ways to enforce that — weight clipping, the gradient penalty, spectral normalization — checked against exact Wasserstein distances; then the large GANs (Progressive GAN, SAGAN, BigGAN with its truncation trick, StyleGAN, GigaGAN), conditional GANs, GANs for representations (InfoGAN, BiGAN), GANs as energy models, moment matching, adversarial losses outside generation (GAIL, fairness), and the place where GANs survived the diffusion era: the adversarial loss inside image tokenizers (VQGAN).