What this is
What is a GAN?
A GAN (generative adversarial network) is an AI method for making new images by training two neural networks against each other. One makes fakes; the other tries to tell them from real examples. Think of a forger printing banknotes and a detective inspecting them. Every fake that is caught teaches the forger what gave it away, until the detective can only guess. The pair is hard to train: the contest can go round in circles, settle on a few kinds of output, or stall when the detective wins too fast.
Why it matters: You need it when a decoder's output comes out blurry because a reconstruction loss rewards the average of many plausible images, or when a generator must make a sample in one pass for a real-time loop. Both are jobs for an adversarial loss, and its instability is why diffusion replaced GANs for most image generation.
At a glance
Key takeaways
- A GAN trains a generator (forger) to turn noise into samples and a discriminator (detective) to tell real samples from fakes, against each other. The forger learns only through the detective's gradient.
- The game: min over G of max over D of E[log D(x)] + E[log(1 − D(G(z)))]. The best detective says p_data / (p_data + p_g); at the equilibrium the forger matches the data and the detective says 1/2 everywhere.
- The non-saturating loss (maximise log D(G(z))) keeps the forger's gradient strong when the detective is confident, which is when the original loss goes quiet.
- Unstable because each player's target moves: plain gradient steps circle or spiral around the equilibrium, the forger hops between a few modes (mode collapse), and a detective that wins too fast freezes the forger in place.
- Fixes: balanced learning rates, gradient penalties (R1, WGAN-GP), spectral normalization, and the Wasserstein distance, which still points the way when real and fake don't overlap.
- Today: diffusion has overtaken GANs for generating images, but adversarial losses remain inside image and audio decoders and fast distilled samplers.
How it works, from scratch
A forger prints banknotes and a detective inspects them. At first the forger is hopeless, and the detective spots every note. Each rejected note shows the forger what gave it away, and each better note makes the detective look more closely. Neither is ever told what a real banknote looks like. The contest ends when the detective can do no better than guess, "real" half the time and "fake" the other half. By then the forger has learned to make banknotes without ever being given a rule for what a banknote is.
A generative adversarial network, or GAN, is that contest between two neural networks. The forger is called the generator, and the detective is called the discriminator. Trained against each other on photos of faces, the generator learns to produce new faces of people who never existed.
Chapter 1
The two players
To watch the two at work, make the banknotes small enough to see: points on a flat page. The real data is a ring of eight little clouds: eight centres evenly spaced on a circle of radius 2, each real point scattered a tiny amount (a spread of 0.05) around one centre, chosen at random. Researchers studying GAN failures use this picture because a glance shows whether the forger has found all eight clouds.
- The generator G takes two random numbers z, drawn from a bell curve, and returns one point on the page. Different random numbers give a different point. It is a small neural network: 2 numbers in, two layers of 32 tanh units, 2 numbers out.
- The discriminator D takes a point and returns a probability that it is real. It is another small network: 2 numbers in, 64 tanh units, one score out, then squashed into the range 0 to 1.
The squashing is the sigmoid, the same one Neural networks uses to turn a score into a probability:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| a point on the page, real or forged | ||
| the detective's raw score for (also called a logit): any number, large and positive for "surely real" | ||
| the first coordinate of | 2 | |
| Euler's number, about 2.718 (see Math notation, from zero) | ||
| the sigmoid: squashes any score into a probability between 0 and 1 | ||
| the detective's verdict: the probability that is real | 0.731 |
In words: "the detective computes a score for the point, and the sigmoid turns the score into a probability that the point is real."
With the numbers: take a detective with a single neuron whose score is . The point , one of the eight real centres, scores , and : probably real. The point in the middle of the ring scores and gets : probably fake.
In Python
import math
def sigma(a):
return 1 / (1 + math.exp(-a))
# a one-neuron detective: score a(x) = x_1 - 1
def a(x):
return x[0] - 1
round(sigma(a((2, 0))), 3) # → 0.731
round(sigma(a((0, 0))), 3) # → 0.269
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
Figure 1 · Diagram
flowchart LR Z["noise z<br/>2 random numbers"] --> G["Generator G<br/>the forger"] G --> F["fake point G(z)"] R["real point x<br/>from the ring"] --> D["Discriminator D<br/>the detective"] F --> D D --> P["D(point)<br/>probability it is real"] P -. "learns to call real real<br/>and fake fake" .-> D P -. "learns to make D say real<br/>about its fakes" .-> G
So a GAN never needs a description of what a face, a voice or a banknote is. The detective works out what separates real from fake, and its gradient (the direction that would make it less sure a fake is fake; see Neural networks for gradients) tells the forger how to improve.
In code: ring_of_gaussians draws the real points, MLP is both players, and sigmoid turns a score into a verdict. View source
Chapter 2
The game: one number both players fight over
Both players learn from a single score of how well the detective is doing. The detective earns points for confident, correct calls and loses points, heavily, for confident mistakes. It pushes the score up, and the forger pushes it down. A game in which two players pull one number in opposite directions is called a minimax game.
Say the detective looks at two real notes and two fakes. The score uses the logarithm (log): log 1 = 0, and the log of a small number is a large negative number, so a confident mistake costs far more than a hesitant one (see Math notation, from zero for logs from scratch).
| Note | Real? | Verdict D | What is scored | Value |
|---|---|---|---|---|
| 1 | real | 0.9 | log D = log 0.9 | −0.105 |
| 2 | real | 0.8 | log D = log 0.8 | −0.223 |
| 3 | fake | 0.2 | log (1 − D) = log 0.8 | −0.223 |
| 4 | fake | 0.4 | log (1 − D) = log 0.6 | −0.511 |
The average over the real notes is −0.164, over the fakes −0.367, and the total is −0.53. A perfect detective (1 on every real note, 0 on every fake) would score log 1 + log 1 = 0, the ceiling. A detective reduced to a coin flip (0.5 on everything) scores log 0.5 + log 0.5 = −1.386.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the value: the score both players fight over | −0.53 | |
| "the detective chooses its weights to make what follows as large as possible" | ||
| "the forger chooses its weights to make that best-case value as small as possible" | ||
| expectation: the average over many draws (see Math notation, from zero, probability notation) | an average over 2 notes | |
| " drawn from the real data" | notes 1 and 2 | |
| " drawn from the noise the forger starts from" | the random numbers behind notes 3 and 4 | |
| the verdict on a real point | 0.9, 0.8 | |
| a fake point made from noise | notes 3 and 4 | |
| the verdict on a fake | 0.2, 0.4 | |
| natural logarithm: 0 at 1, very negative near 0 |
In words: "average the log of the verdicts on real points, add the average log of one minus the verdicts on fakes; the detective pushes this number up, the forger pushes it down."
With the numbers: (log 0.9 + log 0.8) / 2 + (log 0.8 + log 0.6) / 2 = −0.164 + (−0.367) = −0.53.
In Python
import math
# D(x) on two real notes, D(G(z)) on two fakes
d_real, d_fake = [0.9, 0.8], [0.2, 0.4]
# E over real x of log D(x): an average
real_term = sum(math.log(d) for d in d_real) / len(d_real)
round(real_term, 3) # → -0.164
# E over noise z of log(1 - D(G(z)))
fake_term = sum(math.log(1 - d) for d in d_fake) / len(d_fake)
round(fake_term, 3) # → -0.367
round(real_term + fake_term, 2) # → -0.53
# a coin-flip detective, D = 1/2 on everything
round(math.log(0.5) + math.log(0.5), 3) # → -1.386
−V is the binary cross-entropy of a classifier that labels real points 1 and fakes 0 (see Loss functions), so the detective is an ordinary classifier. What is new is that its second class, the fakes, keeps changing underneath it.
There is no way to solve "min over G of max over D" in one go, so training alternates, with one small step for each player per round:
Figure 2 · Diagram
flowchart TB
S["sample a batch of real points<br/>and a batch of noise"] --> F["forger makes fakes G(z)"]
F --> DS["detective step:<br/>climb V, so D(real) rises<br/>and D(fake) falls"]
DS --> GS["forger step:<br/>change G so the new detective<br/>scores its fakes higher"]
GS --> CHK{"trained enough?"}
CHK -- no --> S
CHK -- yes --> OUT["keep G;<br/>throw D away"]
Each step on its own is ordinary training: an ordinary optimizer on an ordinary loss. The difference is that each player's loss changes every time the other player steps, and that moving target is where the instability of GAN training comes from.
In code: value_function computes V from a batch of verdicts, and train_gan runs the loop on the ring with Adam (primer.ml.optimizers.Adam). View source
Chapter 3
The best possible detective, and where the game ends
Before asking how training goes wrong, it helps to know where it should end. Start with the detective, and hold the forger fixed. Suppose that at one spot on the page real points turn up three times as often as fakes. The detective cannot tell two identical points apart, so the best it can do there is say "75% real", the local mix.
In numbers: at a point where the real data's density (how thickly its points cover that spot) is 0.3 and the forger's is 0.1, the best verdict is 0.3 / (0.3 + 0.1) = 0.75. Try its neighbours: the detective's expected score at that spot is 0.3 · log D + 0.1 · log(1 − D), which is −0.2274 at D = 0.7, −0.2249 at D = 0.75 and −0.2279 at D = 0.8. The middle one is the highest.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the best possible verdict at , for a forger that is held fixed | 0.75 | |
| how densely the real data covers the spot | 0.3 | |
| how densely the forger's fakes cover the spot | 0.1 |
In words: "the best verdict at each point is the share of the points found there that are real."
With the numbers: 0.3 / (0.3 + 0.1) = 0.75. If the forger matched the data exactly, everywhere, and every verdict would be 0.3 / (0.3 + 0.3) = 0.5.
In Python
import math
p_data, p_g = 0.3, 0.1
round(p_data / (p_data + p_g), 2) # → 0.75
# the detective's expected score at this spot, for a few verdicts D
def score(D):
return p_data * math.log(D) + p_g * math.log(1 - D)
[round(score(D), 4) for D in (0.7, 0.75, 0.8)] # → [-0.2274, -0.2249, -0.2279]
# a forger that matches the data exactly
round(0.3 / (0.3 + 0.3), 2) # → 0.5
The formula comes from the detective's choice at each point: one number D that maximises . The slope of that with respect to D is , and setting the slope to zero gives . Goodfellow and colleagues derived it in the original GAN paper, and it says where the game ends. At the equilibrium the forger's distribution equals the data's, and the best detective says 1/2 everywhere, scoring V = −log 4 ≈ −1.386, the coin-flip score from the table above. Plug back into V and what remains is −log 4 plus twice the Jensen-Shannon divergence between the real and forged distributions, a measure of how different two piles of probability are that is zero only when they are identical. So a forger facing a perfect detective is really minimising that divergence, which comes back as a problem among the fixes, below.
Figure 3 · Chart
Top: the real data has two bumps and the forger one wide bump; bottom: the best detective's verdict rises to about 0.8 on the real bumps, drops towards 0 where only fakes live, and would be flat at one half if the forger matched
Figure 4 · Chart
After training with balanced learning rates, the forger's green points sit on all eight clouds, and the detective's verdict on the ring is close to one half
The detective never has to model what real data looks like. It only estimates a ratio between two densities, so a GAN never has to write down how probable an image is.
In code: optimal_discriminator is the formula, fit_discriminator_table trains a detective with one free score per point and reaches the same verdicts, and detective_verdicts reads a trained detective's verdict anywhere on the page. View source
Chapter 4
Why the forger uses a different loss
The game ends with the forger matching the data, but it starts with a terrible forger and a detective that is sure every fake is fake. Take a fake the detective is 99% sure of: D(G(z)) = 0.01. Compare how hard each of two losses pushes the forger:
- The original loss, log(1 − D(G(z))), which the forger minimises: its slope with respect to the detective's score is −D = −0.01, almost nothing.
- The non-saturating loss, −log D(G(z)), which the forger also minimises: its slope is −(1 − D) = −0.99, ninety-nine times as much.
When the detective is undecided, D = 0.5, both slopes are −0.5. So the two losses agree while the detective is unsure and differ once it is confident.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the detective's score for a fake, before the sigmoid | ||
| the verdict D on that fake | 0.01 | |
| the derivative with respect to : how much the loss changes when the score is nudged up a tiny amount (see Math notation, from zero) | ||
| the original, "saturating" forger loss | ||
| the non-saturating forger loss |
In words: "the original loss changes by only D when the detective's score moves, so it goes quiet when D is near 0; the non-saturating loss changes by 1 − D, so it is loudest when the forger is doing worst."
With the numbers: at D = 0.01, the slopes are −0.01 and −0.99.
In Python
import math
def sigma(a):
return 1 / (1 + math.exp(-a))
# a score that makes the detective 99% sure the fake is fake
a = math.log(0.01 / 0.99)
round(sigma(a), 2) # → 0.01
# measure each slope by nudging the score a tiny bit either way
h = 1e-6
def slope(loss):
return (loss(a + h) - loss(a - h)) / (2 * h)
def saturating(a):
return math.log(1 - sigma(a))
def non_saturating(a):
return -math.log(sigma(a))
round(slope(saturating), 3) # → -0.01
round(slope(non_saturating), 3) # → -0.99
Both losses want the same thing, a higher verdict on the fakes, and they share the same equilibrium. Only the strength of the push differs. The original GAN paper already recommended the switch, and the GANs that followed use the non-saturating loss or a Wasserstein-style loss (below).
Figure 5 · Chart
Left: as the detective grows sure a fake is fake, the original loss flattens out while the non-saturating loss keeps a steady slope; right: giving the detective an 800-step head start shrinks the original loss's gradient to 0.09 while the non-saturating one grows to 15
A forger that gets no gradient does not learn, so the detective's lead only widens. Early in training the detective always has the easier job, so with the original loss this stall is what happens by default.
In code: generator_logit_gradient returns both slopes, and head_start_experiment measures them after a head start. View source
Chapter 5
Why training is unstable, part 1: the players chase each other in circles
The non-saturating loss gives the forger a gradient. Following it still does not lead to the equilibrium, because the detective moves too: the forger heads for where the detective says "real" today, and by the time it arrives, the detective has changed its mind.
The smallest GAN there is, the Dirac GAN, shows this with one number per player. The real data is a single point at x = 0. The forger has one number θ and always outputs x = θ. The detective has one number ψ and scores a point as ψ · x, so D(x) = σ(ψx). Start with the forger at θ = 1 and a detective with ψ = 0 (it cannot tell anything apart), and let both take steps of size 1 at the same time:
| Step | σ(ψθ) | θ (forger) | ψ (detective) | Distance from (0, 0) |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | |
| 1 | σ(0) = 0.5 | 1 | −0.5 | 1.118 |
| 2 | σ(−0.5) = 0.3775 | 0.811 | −0.878 | 1.195 |
After step 1 the detective has learned "bigger x means fake" (ψ turned negative), and after step 2 the forger has moved towards the data at 0. Both moves were sensible, yet the pair got further from the equilibrium, the point (0, 0) where the forger sits on the data and the detective is indifferent.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the forger's only number: where it puts its fake | 1 | |
| the detective's only number: the slope of its score | 0 | |
| the detective's score for the real data at : always 0, so | 0 | |
| the verdict on the fake | 0.5 | |
| the slope the detective climbs: | ||
| the slope the forger descends: | 0 | |
| the step size (learning rate) | 1 | |
| "is replaced by" |
In words: "the detective tilts its slope against wherever the fake sits; the forger slides along whichever way the slope says is more real; each reacts to the other's old position."
With the numbers: step 1: σ(0) = 0.5, so ψ becomes 0 − 1 · 0.5 · 1 = −0.5 and θ stays 1 + 1 · 0.5 · 0 = 1. Step 2: σ(−0.5) = 0.3775, so θ becomes 1 + 0.3775 · (−0.5) = 0.811 and ψ becomes −0.5 − 0.3775 · 1 = −0.878.
In Python
import math
def sigma(a):
return 1 / (1 + math.exp(-a))
theta, psi, lr = 1.0, 0.0, 1.0
s = sigma(psi * theta)
s # → 0.5
# both move at once, each using the other's old position
theta, psi = theta + lr * s * psi, psi - lr * s * theta
(theta, psi) # → (1.0, -0.5)
s = sigma(psi * theta)
round(s, 4) # → 0.3775
theta, psi = theta + lr * s * psi, psi - lr * s * theta
(round(theta, 3), round(psi, 3)) # → (0.811, -0.878)
# distance from the equilibrium (0, 0): 1, then 1.118, then 1.195
round(math.hypot(theta, psi), 3) # → 1.195
Figure 6 · Diagram
flowchart LR A["fake sits to the right<br/>of the data"] --> B["detective tilts:<br/>right means fake"] B --> C["forger slides left,<br/>overshoots past the data"] C --> D["detective tilts back:<br/>left means fake"] D --> E["forger slides right,<br/>overshoots again"] E --> A
Figure 7 · Chart
In the plane of the forger's theta against the detective's psi, simultaneous steps spiral outward from the start at (1, 0), and alternating steps circle the equilibrium without ever reaching it
In a real GAN, with millions of numbers per player, the same rotation happens in many directions at once. You see it as losses that swing up and down without trending, and samples that keep changing character instead of steadily improving.
In code: dirac_gan runs this two-number game with simultaneous or alternating steps. View source
Chapter 6
Why training is unstable, part 2: mode collapse
When the data comes in several distinct kinds, the same chase takes a form of its own. Say the forger finds that one particular note, the twenty, always fools the detective, so it prints nothing but twenties. The detective eventually learns that twenties are suspicious, and the forger switches to fifties, and so on. Each forgery is good, but the forger never produces the full variety of real money. Each distinct kind of real example is a mode, and settling on a few of them is mode collapse.
To measure variety on the ring, generate 1,000 points and count, for each of the eight clouds, how many land within 0.15 of its centre (3 spreads). A cloud is covered if it gets at least 20 of the 1,000 (2%; a perfect forger gives each about 125). A point that lands near any centre counts as high quality. After 2,500 rounds with equal learning rates for both players, the counts for the eight clouds are (0, 68, 0, 20, 0, 51, 0, 17). Clouds 2, 4 and 6 are covered, and cloud 8's 17 falls short, so 3 of 8 modes are covered. Only 156 of the 1,000 points are high quality; the rest are strung between clouds.
Figure 8 · Diagram
stateDiagram-v2 direction LR EvenClouds: forger piles onto clouds 1, 3, 5, 7 CatchEven: detective learns those clouds are suspicious OddClouds: forger jumps to clouds 2, 4, 6, 8 CatchOdd: detective learns these are suspicious EvenClouds --> CatchEven CatchEven --> OddClouds OddClouds --> CatchOdd CatchOdd --> EvenClouds
Figure 9 · Chart
Three rows of four snapshots between steps 1,750 and 2,500: with equal learning rates the green points hop between alternate clouds; with a detective three times faster they cover all eight; with a detective ten times faster they sit on six and never reach the other two
Figure 10 · Chart
Modes covered over training: equal learning rates wander between one and four; a three-times-faster detective reaches all eight by step 1,000 and stays; a ten-times-faster detective locks onto six at step 500
These runs use one fixed seed. With other seeds the equal-speed run sometimes finds all eight clouds late on, and the ten-times run sometimes escapes after a while, so trust the pattern rather than the exact counts.
On real data, a face generator that has collapsed produces convincing faces that all look like the same few people. A quality score that judges one sample at a time cannot see this. You have to measure coverage, as the cloud counts do here.
In code: mode_coverage counts covered clouds and high-quality points, and train_gan records it every 250 steps. View source
Chapter 7
Why training is unstable, part 3: a detective that wins too fast
The bottom row of the ring figure shows a third failure. A detective that learns much faster than the forger soon rejects, with total confidence, everything outside the few spots the forger has already mastered. Every small move the forger tries in a new direction comes back "more fake", so it retreats to what already works and stops exploring.
With the detective's learning rate ten times the forger's, after 2,500 steps the counts per cloud are (199, 181, 117, 0, 132, 160, 72, 0). The six covered clouds are served well: 86% of points are high quality, more than the 81% of the run with a detective three times faster. But clouds 4 and 8 get nothing, from step 500 until the end. Better-looking samples with less variety is a trade-off real image generators face too.
Figure 11 · Diagram
flowchart LR A["detective learns<br/>much faster"] --> B["gaps between the forger's clouds<br/>become confident fake zones"] B --> C["every small step towards them<br/>lowers the verdict"] C --> D["forger polishes the clouds<br/>it already has"] D --> E["empty clouds stay empty"]
Training the detective harder sounds as if it should give the forger a better teacher, but past a point it gives a worse one. The detective has to be good enough to point the way, but not so far ahead that all it can say is no.
In code: train_gan takes both learning rates as arguments; this run gives the detective ten times the forger's. View source
Chapter 8
Fixes that make the game trainable
In each failure so far, the detective has stopped being useful to the forger: it moves on while the forger chases it, or it wins so fast that it only says no. Each fix below changes the detective, or what it measures, so that it keeps pace with the forger and its verdicts point somewhere.
Figure 12 · Diagram
flowchart LR P1["players out of step"] --> F1["careful learning rates<br/>two time-scales"] P2["detective builds<br/>steep cliffs"] --> F2["gradient penalty"] P2 --> F3["spectral normalization"] P3["piles don't overlap,<br/>so the verdict gives no direction"] --> F4["Wasserstein distance"] F4 --> F2
Careful learning rates
The three rows of the ring figure differ only in the detective's learning rate, with the forger's fixed at 0.001:
| Detective's rate | Clouds covered at step 2,500 | High-quality points |
|---|---|---|
| 0.001 (equal) | 3, and hopping | 16% |
| 0.003 (three times) | 8, steady | 81% |
| 0.01 (ten times) | 6, stuck | 86% |
A modestly faster detective keeps its verdicts close to the best-detective formula for the forger it is facing now, so the forger follows a gradient that points at the data rather than at yesterday's detective. Heusel and colleagues called this the two time-scale update rule and proved it reaches an equilibrium under reasonable conditions. The right ratio depends on the problem, so it is worth tuning.
In code: train_gan with a detective learning rate of 0.003 is the balanced run; the other two rows are the same call with 0.001 and 0.01. View source
Gradient penalty: fine the detective for steep cliffs
A gradient penalty charges the detective a fee for how sharply its score changes right on top of the real data. A detective with gentle slopes still ranks real above fake, but it can no longer swing wildly, and the swinging is what fed the spiral in part 1.
In the Dirac GAN the detective's score is ψ · x, whose slope with respect to x is just ψ. The R1 gradient penalty adds (γ / 2) · ψ² to what the detective minimises. With γ = 1 and ψ = −0.5 the fee is 0.125, and its gradient, γψ = −0.5, pulls ψ back towards 0 on every step, like friction. With step size 0.2 that friction shrinks ψ by a factor 1 − 0.2 · 1 = 0.8 per step, on top of the game's own push.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the Dirac example |
|---|---|---|
| the penalty added to the detective's loss | 0.125 | |
| how heavily steepness is fined | 1 | |
| the detective's score at | ||
| the gradient of the score with respect to the input point: which way, and how steeply, the score rises as you move | ||
| the squared length of that gradient (see Math notation, from zero, the length of a vector) | 0.25 | |
| averaged over real points only | the single real point |
In words: "measure how steeply the detective's score changes at the real points, square it, average it, and charge the detective γ/2 times that."
With the numbers: (1 / 2) · (−0.5)² = 0.125.
In Python
gamma, psi = 1.0, -0.5
# slope of the score psi * x with respect to x, at the real point
slope = psi
gamma / 2 * slope ** 2 # → 0.125
# the penalty's pull on psi: its derivative, gamma * psi
gamma * psi # → -0.5
# one step of size 0.2 against that pull shrinks psi by a factor 0.8
round(psi - 0.2 * gamma * psi, 2) # → -0.4
Figure 13 · Chart
Distance from the equilibrium over 300 steps: simultaneous steps grow from 1 to 2.6, alternating steps hold near 1, and with the R1 penalty the distance falls to 0.08 within 50 steps and to zero after
In code: dirac_gan takes the penalty weight γ as an argument and adds the R1 penalty's pull, −γψ, to the detective's step. View source
Wasserstein distance: a yardstick that knows near from far
Facing the best detective, the forger minimises the Jensen-Shannon divergence, as the best-detective section showed. Picture the real data and the fakes as two piles of sand. That divergence asks only how much the piles overlap. The Wasserstein distance, also called the earth mover's distance, is the least work needed to reshape one pile into the other: the amount of sand moved times how far it travels.
Put all the real sand at x = 0 and all the fake sand at x = θ. If θ = 1, the piles don't overlap, and the Jensen-Shannon divergence is log 2 = 0.693. If θ = 5, they still don't overlap, and it is still 0.693. It cannot tell a near miss from a far one, so it gives the forger no direction. The Wasserstein distance is 1 for θ = 1 and 5 for θ = 5: it shrinks as the forger approaches, so it always points towards the data.
For two equally sized samples on a line, the cheapest way to move the sand is to pair the smallest with the smallest, the next with the next, and so on:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| the Wasserstein (earth mover's) distance between two piles on a line | 3 | |
| how many grains (samples) each pile has | 3 | |
| the -th smallest value in the first pile (the brackets mean "after sorting") | ||
| the -th smallest value in the second pile | sorts to | |
| the absolute value: the gap, ignoring direction |
In words: "sort both piles, pair them up in order, and average how far each grain has to travel."
With the numbers: pairs (0, 3), (1, 4), (2, 5), gaps 3, 3, 3, average 3.
In Python
a = [0, 1, 2]
b = [5, 3, 4]
# pair the smallest with the smallest, and so on
pairs = list(zip(sorted(a), sorted(b)))
pairs # → [(0, 3), (1, 4), (2, 5)]
sum(abs(x - y) for x, y in pairs) / len(pairs) # → 3.0
Figure 14 · Chart
As the forger's pile slides from minus 4 to plus 4, the Jensen-Shannon divergence is flat at log 2 everywhere except exactly 0, while the Wasserstein distance is a V shape pointing at 0
The Wasserstein GAN replaces the detective with a critic that outputs an unbounded score instead of a probability, and trains it so that the gap between its average score on real and on fake points estimates this distance. The estimate is only valid if the critic's slope is at most 1 everywhere. The original WGAN enforced that crudely by clipping every weight; WGAN-GP does it with a gradient penalty; spectral normalization, next, does it by capping each layer.
In code: wasserstein_1d is the sort-and-pair formula, and js_divergence computes the Jensen-Shannon divergence between two histograms. View source
Spectral normalization: a speed limit on every layer
Spectral normalization caps the detective's steepness layer by layer. A layer of a neural network is a matrix, and a matrix stretches some directions more than others. If no layer can stretch anything by more than 1, the whole detective can't change its score faster than the input changes: its cliffs have a speed limit.
The matrix W = [[3, 0], [0, 1]] stretches the horizontal direction by 3 and the vertical by 1. Its largest stretch is 3. Divide W by 3 and no direction is stretched by more than 1.
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| one layer's weight matrix (see Math notation, from zero for matrices) | [[3, 0], [0, 1]] | |
| an input direction: an arrow of length 1 | ||
| the length of | 1 | |
| the arrow after passing through the layer | ||
| "the largest value over every arrow of length 1" | ||
| the spectral norm: the most W lengthens any arrow | 3 | |
| the normalised layer used in the detective | [[1, 0], [0, 1/3]] |
In words: "find the direction the layer stretches most, and divide the whole layer by that stretch."
With the numbers: becomes , length 3; stays length 1; every other direction lands in between. So , and stretches by at most 1.
In Python
import math
W = [[3, 0], [0, 1]]
def stretch(v):
Wv = [sum(w * x for w, x in zip(row, v)) for row in W]
return math.hypot(*Wv) / math.hypot(*v)
# try unit arrows all the way round the circle, one per degree
angles = [2 * math.pi * k / 360 for k in range(360)]
round(max(stretch((math.cos(t), math.sin(t))) for t in angles), 3) # → 3.0
# divide W by its largest stretch
W = [[w / 3 for w in row] for row in W]
round(max(stretch((math.cos(t), math.sin(t))) for t in angles), 3) # → 1.0
Trying every direction is fine for a 2 × 2 matrix but not for a layer with a thousand inputs. Power iteration finds the most-stretched direction cheaply:
Figure 15 · Diagram
flowchart LR
V["start: any arrow v"] --> U["u = W v,<br/>rescaled to length 1"]
U --> B["v = W transpose u,<br/>rescaled to length 1"]
B --> Q{"repeat"}
Q -- again --> U
Q -- done --> S["largest stretch = length of W v"]
Miyato and colleagues introduced spectral normalization in 2018. It changes only the detective's layers. It made GAN training less sensitive to the choice of learning rates and architecture, and large image GANs such as BigGAN use it.
In code: largest_stretch is power iteration, and spectrally_normalize divides a matrix by it. View source
Chapter 9
Where GANs stand today
Stabilised this way, GANs had one clear advantage over what came next: speed. A GAN makes an image in one pass through the generator, while a diffusion model typically runs its network tens of times per image, removing a little noise each time (see Diffusion and flow matching). For a while that speed, and very sharp samples such as StyleGAN's faces from 2018, made GANs the best image generators. Then diffusion models overtook them on image quality and, above all, on coverage: they don't mode-collapse, and they train stably. Since around 2021 most new image and video generators have been diffusion or flow models.
GANs did not disappear. The adversarial loss lives on inside other systems, such as an autoencoder with a detective attached:
Figure 16 · Diagram
flowchart LR X["real image or audio"] --> E["encoder"] E --> C["compact code"] C --> DEC["decoder"] DEC --> Y["reconstruction"] Y --> L1["reconstruction loss<br/>pixel or perceptual"] X --> L1 Y --> DISC["detective:<br/>real or reconstructed?"] X --> DISC L1 --> T["total loss for<br/>encoder and decoder"] DISC --> T
So a modern image, audio or video system often has a GAN loss in its decoder or its fast sampling path, even when its headline method is diffusion. The non-saturating loss, gradient penalties, spectral normalization and careful learning rates are still how those detectives are kept stable.
Test yourself
8 questions
Answer each one out loud or on paper before you open it.
Question 1Explain a GAN to a non-engineer in 30 seconds.Think it through, then reveal
Two programs play a game. One makes fake pictures; the other looks at real and fake pictures and guesses which is which. Every time the guesser catches a fake, the faker learns what gave it away and improves. After enough rounds the fakes are good enough that the guesser is reduced to guessing, and the faker has learned to make realistic pictures without anyone ever describing what a picture should look like.
Question 2Why does the generator never need to see real data?Think it through, then reveal
It learns only from the discriminator's gradient with respect to its own outputs: which way to move each fake so the discriminator finds it more real. The discriminator has seen real data, so its verdicts carry that information to the generator.
Question 3What does the optimal discriminator compute, and what does it say at equilibrium?Think it through, then reveal
D*(x) = p_data(x) / (p_data(x) + p_g(x)): the share of points found at x that are real. When the generator matches the data, p_g = p_data and D* is 1/2 everywhere, the value is −log 4, and the discriminator can do no better than a coin flip.
Question 4Why do almost all GANs use the non-saturating generator loss?Think it through, then reveal
The original loss log(1 − D(G(z))) has a slope of −D with respect to the discriminator's score, which is near zero when the discriminator confidently rejects fakes, as it does early in training. The non-saturating loss −log D(G(z)) has slope −(1 − D), largest exactly then. Both have the same equilibrium.
Question 5What is mode collapse, and how would you detect it?Think it through, then reveal
The generator covers only some of the distinct kinds of data (modes), often hopping between them as the discriminator catches up. Per-sample quality can look excellent, so you detect it by measuring coverage: how many modes or classes receive samples, or a distribution-level metric such as FID on real data.
Question 6Why doesn't plain gradient descent find the GAN equilibrium?Think it through, then reveal
The game has no shared downhill direction. Near the equilibrium the two players' updates form a rotation, so simultaneous steps spiral outward and alternating steps orbit forever, as the two-number Dirac GAN shows. Damping the discriminator with a gradient penalty turns the spiral inward.
Question 7Why is the Wasserstein distance a better training signal than Jensen-Shannon divergence?Think it through, then reveal
When the real and generated distributions don't overlap, Jensen-Shannon is stuck at log 2 however far apart they are, so it gives no direction. Wasserstein measures how far the mass must move, so it shrinks steadily as the generator approaches the data. Estimating it needs a critic whose slope is capped, which is what weight clipping, gradient penalties and spectral normalization provide.
Question 8If diffusion models won, why learn GANs?Think it through, then reveal
Adversarial losses are still how many image and audio decoders get sharp output, and how some diffusion models are distilled into one-step generators. And the instabilities here, moving targets and collapsing variety, show up wherever two models are trained against each other.
Primary sources
The papers behind this lesson
Introduced the generator-discriminator game, derived the optimal discriminator and the equilibrium where the generator matches the data, and suggested the non-saturating loss.
Read on rumblr →The paperUsed the ring of eight Gaussians to show a generator hopping between modes, and reduced it by letting the generator look ahead at several discriminator steps.
The paperShowed that separate learning rates for the two players give provable convergence, and introduced the FID score for judging generated images.
The paperReplaced the Jensen-Shannon objective with the earth mover's distance, which still gives a direction when real and generated data don't overlap.
Read on rumblr →The paperEnforced the Wasserstein critic's slope limit with a gradient penalty instead of weight clipping.
The paperIntroduced the two-number Dirac GAN to show why plain GAN training circles instead of converging, and the R1 penalty that makes it converge.
The paperCapped every discriminator layer's largest stretch at 1 using one step of power iteration per training step.
The paperResearcher's shelf
Further reading
- Goodfellow, NIPS 2016 Tutorial: Generative Adversarial Networks: https://arxiv.org/abs/1701.00160
- Radford, Metz and Chintala, Unsupervised Representation Learning with Deep Convolutional GANs (DCGAN, 2015): https://arxiv.org/abs/1511.06434
- Karras, Laine and Aila, A Style-Based Generator Architecture for Generative Adversarial Networks (StyleGAN, 2018): https://arxiv.org/abs/1812.04948
- Dhariwal and Nichol, Diffusion Models Beat GANs on Image Synthesis (2021): https://arxiv.org/abs/2105.05233
- Esser, Rombach and Ommer, Taming Transformers for High-Resolution Image Synthesis (VQGAN, 2020): https://arxiv.org/abs/2012.09841
- Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models (2021): https://arxiv.org/abs/2112.10752
- Kong, Kim and Bae, HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis (2020): https://arxiv.org/abs/2010.05646
- Sauer et al., Adversarial Diffusion Distillation (2023): https://arxiv.org/abs/2311.17042
- PyTorch, DCGAN Tutorial: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.