rumblr Work in progressWIP

● The AI Primer · Lesson 35 · Part 5: other kinds of model, and generating media

GANs

a forger against a detective

This lesson covers How two neural networks trained against each other learn to make realistic samples, and why the training is unstable

Members · open during launch 52 min16 figures and diagrams

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

Reading it: start at the far left. Noise goes into the generator and comes out as a fake point. Real points come in from the data. Both kinds of point go through the same detective, which gives each one a probability. The two dotted arrows are the learning signals, and they pull in opposite directions: the detective adjusts itself to score real points high and fakes low, and the generator adjusts itself to make the detective score its points high. The generator never sees a real point. Everything it learns about the data arrives through the detective's verdicts.

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

Reading it: follow one lap from the top. A fresh batch of real points and noise comes in, the forger turns the noise into fakes, and then the two players move in turn: first the detective takes one step of gradient ascent on V (it wants V higher), then the forger takes one step of gradient descent (it wants V lower), judged by the detective as it is after its step. The loop repeats thousands of times. When it stops, only the generator is kept, and the detective is thrown 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

0.0 0.1 0.2 0.3 0.4 density Where each distribution puts its points real data p_data forger p_g −4 −2 0 2 4 position x 0.0 0.2 0.4 0.6 0.8 1.0 D*(x) The best detective: the share of points at x that are real best verdict D* D* once the forger matches the data

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

Reading it: the top panel shows two distributions on a line: the real data (blue) has two narrow bumps at −2 and +2, and the forger (red) spreads one wide bump over the middle. The bottom panel is the best verdict at every position. Over the real bumps it rises to about 0.8, because most points found there are real (the forger's wide bump still reaches them). In the middle and at the far edges it falls towards 0, because only fakes live there. The grey dashed line at 0.5 is what becomes once the forger matches the data: the detective has nothing left to go on. The bottom curve is what the forger learns from: it shows which way to move its mass.

Figure 4 · Chart

−3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3 The detective's verdict after 2,500 steps real forger 0.0 0.2 0.4 0.6 0.8 1.0 D(x): probability real

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

Reading it: this is the real ring after 2,500 rounds of training. The background colour is the trained detective's verdict at every spot: blue for "real", red for "fake", white for 0.5. Black dots are real points, green dots are the forger's. The green points sit on all eight clouds, and the background there is pale, close to white: at the eight centres the verdict is between 0.46 and 0.58: where the forgery is good, the detective is reduced to guessing. Away from the ring, where neither real nor fake points ever appear, the formula says nothing, and the detective's colouring there is arbitrary (deep red in the empty middle).

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

−6 −4 −2 0 2 detective's score a for a fake (left: sure it is fake) −2 0 2 4 6 forger's loss The original loss goes flat when the detective is sure D = 0.01 original: log(1 - D) non-saturating: -log D 0 100 200 300 400 500 600 700 800 detective's head start (training steps) 1 0 − 1 1 0 0 1 0 1 size of the forger's gradient Measured on the ring: a head start starves one loss D=0.484 D=0.268 D=0.029 D=0.006 original loss non-saturating loss

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

Reading it: on the left, the x-axis is the detective's score for a fake: far left means "certainly fake". The red curve, the original loss, goes flat as you move left, and a flat curve has no slope, so no gradient. The blue curve, the non-saturating loss, keeps a steady downhill slope all the way. On the right is a measurement from our ring: the detective trains alone against a frozen, untrained forger for more and more steps, and we measure how big a gradient each loss would hand the forger (log scale). At the start both are about 0.5 to 0.6. After 800 detective steps its verdict on fakes is 0.003, the original loss's gradient has shrunk to 0.09, and the non-saturating one has grown to 15: over a hundred times larger.

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

Reading it: the boxes form a loop because the game has no downhill direction that both players share. Each arrow is a sensible move for the player making it, but each player only reacts to the other's current position, so the forger arrives just after the detective has changed its mind. The loop is a rotation around the equilibrium, not a descent into it.

Figure 7 · Chart

−2 −1 0 1 2 forger's theta (where the fake sits) −2 −1 0 1 2 detective's psi (its slope) The Dirac GAN never settles start (1, 0) equilibrium simultaneous steps: spiral out alternating steps: endless orbit

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

Reading it: the horizontal axis is the forger's θ, the vertical axis the detective's ψ, and the black cross at (0, 0) is the equilibrium. Both paths start at the dot, (1, 0), and take 300 steps of size 0.2. The red path, where both players step at once, spirals outwards: after 300 steps it is 2.6 away from the equilibrium, where it started 1 away. The blue path, where the forger waits to see the detective's new ψ before it moves, stays on a closed loop about 1 away forever. Neither path arrives: plain gradient steps fail to solve this game even with one number per player.

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

Reading it: each box is a phase of training, and the arrows go round in a circle. The forger does not have to cover every cloud to fool the detective today; it only has to put its points where the detective currently says "real". The detective then learns those spots are over-supplied with fakes, the verdict there drops, and the forger's gradient pushes the whole pile somewhere else. It is the chase from part 1, played out across the clouds. The run on the ring does alternate between odd and even clouds, as the next figure shows.

Figure 9 · Chart

equal speeds (0.001) step 1,750 X.X...X. step 2,000 .X.X.X.X step 2,250 X.X.X... step 2,500 .X.X.X.. detective 3x faster (0.003) step 1,750 XXXXXXXX step 2,000 XXXXXXXX step 2,250 XXXXXXXX step 2,500 XXXXXXXX detective 10x faster (0.01) step 1,750 XXX.XXX. step 2,000 XXX.XXX. step 2,250 XXX.XXX. step 2,500 XXX.XXX. The forger's points (green) against the eight real clouds (grey)

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

Reading it: each panel is the page, grey circles mark the eight real clouds, and green dots are 1,000 points from the forger at that step (always made from the same noise, so the panels are comparable). The panel titles spell the coverage with X for a covered cloud, counting anticlockwise from the cloud on the right. Top row, equal learning rates: the green points hop from clouds 1, 3 and 7 at step 1,750 to 2, 4, 6 and 8 at step 2,000, back to 1, 3 and 5, then to 2, 4 and 6, never holding more than half the ring. Middle row, a detective that learns three times faster than the forger: all eight clouds, every snapshot. Bottom row, a detective ten times faster: six clouds, and the same six at every snapshot. Two clouds stay empty for good.

Figure 10 · Chart

0 500 1000 1500 2000 2500 training step 0 1 2 3 4 5 6 7 8 clouds covered (of 8) How much of the ring the forger covers equal speeds (0.001) detective 3x faster (0.003) detective 10x faster (0.01)

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

Reading it: the x-axis is the training step, the y-axis the number of clouds covered out of eight. The blue line (detective three times faster) climbs to 8 by step 1,000 and stays there. The red line (equal speeds) zigzags between 1 and 4, the hopping from the top row above. The amber line (detective ten times faster) jumps to 6 by step 500 and never moves again. The same code and the same data give three very different outcomes, and the only thing that changed is how fast the detective learns.

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

Reading it: read it as a chain of causes. A fast detective turns every region the forger isn't already covering into a wall of confident "fake" verdicts. To reach an empty cloud the forger would have to move points through such a wall. But a gradient only sees the next small step, and every small step into the wall makes the verdict worse, so the gradient pushes the points back onto the clouds they already occupy. The forger spends its effort sharpening those, and the missing ones are never discovered.

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

Reading it: failures are on the left and the fixes that target them on the right. Players moving out of step are fixed by choosing their speeds. A detective whose verdict jumps from 0 to 1 across a narrow cliff is fixed by penalising or capping its steepness. A yardstick that can't tell "near miss" from "far miss" is replaced by the Wasserstein distance, which in practice needs one of the steepness fixes to compute, hence the last arrow.

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

0 50 100 150 200 250 300 step 0.0 0.5 1.0 1.5 2.0 2.5 distance from equilibrium A gradient penalty damps the chase simultaneous steps alternating steps simultaneous + R1 penalty (gamma = 1)

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

Reading it: the x-axis is the step, the y-axis the distance of (θ, ψ) from the equilibrium (0, 0). The red line (plain simultaneous steps) climbs in steps, one per lap: the outward spiral. The blue line (alternating steps) hovers near 1 forever: the endless orbit. The green line adds the R1 penalty with γ = 1 to the simultaneous steps and dives: 0.08 after 50 steps, essentially 0 by 100. The friction turns the rotation into a spiral inwards. This is the result of Mescheder, Geiger and Nowozin, shown with two numbers. StyleGAN and many later GANs train with an R1 penalty. The Wasserstein GAN with gradient penalty (WGAN-GP) uses the same idea with a different target: it keeps the slope near 1 at points between real and fake.

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

−4 −3 −2 −1 0 1 2 3 4 where the forger's pile sits (the real pile is at 0) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 distance between the piles Only one yardstick says which way to move log 2 = 0.693 Jensen-Shannon divergence Wasserstein distance

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

Reading it: the x-axis is where the forger's pile sits; the real pile is at 0. The red line (Jensen-Shannon) is flat at 0.693 everywhere except the single point θ = 0, where it drops to 0: a flat line has no slope, so nothing tells the forger which way to move. The blue V (Wasserstein) slopes down towards 0 from both sides: wherever the forger is, the slope points at the data. That matters for images, where real photos and early fakes barely overlap.

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

Reading it: push an arrow through the layer and back through its transpose, over and over. Each round trip multiplies the arrow's most-stretched component by more than any other, so the arrow swings round to point along that direction, and the stretch is read off at the end. Spectral normalization keeps one arrow per layer and runs a single round trip per training step: the weights change slowly, so the arrow stays nearly right, and the cost is a couple of extra matrix-vector products.

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

Reading it: this is an autoencoder (see Autoencoders and VAEs) with a detective bolted on. The top path squeezes the input into a compact code and rebuilds it. A reconstruction loss alone rewards averages, and the average of many plausible textures is a blur. The detective on the lower path looks at the reconstruction and the original and asks "which is real?", which punishes blur and rewards crisp detail. The decoder is trained on both losses together. This design is how the image autoencoders inside latent diffusion models are trained, how VQGAN's image tokenizer is trained, and how neural audio decoders such as HiFi-GAN produce clean waveforms. GAN-style losses are also used to distil a slow many-step diffusion model into a fast one- or few-step generator.

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

Goodfellow et al., Generative Adversarial Nets (2014)

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 paper
Metz, Poole, Pfau and Sohl-Dickstein, Unrolled Generative Adversarial Networks (2016)

Used 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 paper
Heusel et al., GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium (2017)

Showed that separate learning rates for the two players give provable convergence, and introduced the FID score for judging generated images.

The paper
Arjovsky, Chintala and Bottou, Wasserstein GAN (2017)

Replaced 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 paper
Gulrajani et al., Improved Training of Wasserstein GANs (2017)

Enforced the Wasserstein critic's slope limit with a gradient penalty instead of weight clipping.

The paper
Mescheder, Geiger and Nowozin, Which Training Methods for GANs do actually Converge? (2018)

Introduced the two-number Dirac GAN to show why plain GAN training circles instead of converging, and the R1 penalty that makes it converge.

The paper
Miyato et al., Spectral Normalization for Generative Adversarial Networks (2018)

Capped every discriminator layer's largest stretch at 1 using one step of power iteration per training step.

The paper

Researcher'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.