Generative Adversarial Networks
After this lesson, you will be able to:
- Explain the contest: one network makes fakes, the other tries to catch them
- Read the GAN objective as a two-player game and explain why a too-strong checker leaves the maker with no signal to learn from
- Recognize the common training problems (mode collapse, vanishing gradients, oscillation) and what causes each
- Follow the main fixes, from the original GAN to Wasserstein GAN and StyleGAN, and the key idea behind each
Before you start
The network that turns random numbers into fake samples, such as images. It is the picture maker.
The network that looks at a sample and says how likely it is to be real. It is the picture checker.
Two networks with opposite goals trained together: G wants to fool D, and D wants to catch G.
The generator makes only a few kinds of output and ignores the rest of what the real data contains.
The learning signal for the generator shrinks to almost nothing, so it stops improving.
The Wasserstein GAN's name for the discriminator. It gives a score, not a probability.
The random numbers fed into the generator. Each different z gives a different fake.
#The Counterfeiter and the Detective
Most models are graded by a formula. A GAN is graded by a second network. Instead of writing down what a good picture is, you train a checker to judge pictures, and the competition pushes both networks to improve. If you have ever got better at a game because your opponent kept pushing you, you already know the idea.
#The Architecture: Two Networks at War
A GAN consists of two neural networks trained simultaneously:
The two arrows leaving the verdict are the feedback. When D is right, D keeps its method and G must change. When G fools D, G keeps its method and D must change.
Try it! Play the "real or AI?" game at whichfaceisreal.com. You are the discriminator: you must spot the fake. If it is hard, the generator is winning. Notice what gives the fakes away (ears, backgrounds, teeth). Those are the flaws a discriminator learns to detect.
#The Minimax Game: The GAN Objective
Picture first. The game has one score, and the two players pull it in opposite directions. D wants the score high. G wants it low. A small example, with natural logs: if D says 0.9 for a real picture and 0.2 for a fake, the score is log 0.9 + log (1 - 0.2) = -0.105 - 0.223 = -0.33, which is close to 0, the best D can do. If G improves and D now says 0.8 for the fake, the score is -0.105 + log 0.2 = -0.105 - 1.609 = -1.71. The score fell, so G gained and D lost.
Here is how each player reads it.
Discriminator's perspective (maximize)
- First term: for real data x, D(x) should be close to 1, which makes log D(x) close to 0, its largest value.
- Second term: for fake data G(z), D(G(z)) should be close to 0, which makes log(1 - D(G(z))) close to 0, its largest value.
Generator's perspective (minimize)
- The generator only controls the second term, through G(z).
- It wants D(G(z)) close to 1 (fool the discriminator), which makes log(1 - D(G(z))) very negative, its smallest value.
What happens if the discriminator becomes perfect (always correctly identifies real vs fake)?
Where the minimax value function comes from, why the best discriminator is p_data over (p_data + p_g), how the value becomes a Jensen-Shannon divergence (a number for how different two distributions are), and why the non-saturating loss helps are all derived in Generative Models: GANs & VAEs. What that lesson leaves open is the worst case for the generator: two distributions that do not overlap at all. That is where a generator starts, because its samples sit on a thin sheet far from the real images. For two such distributions the Jensen-Shannon value is a constant, and a constant has no slope.
#Training Dynamics: Walking a Tightrope
- Do: Press play, then raise the G learning rate far above the D learning rate and restart.
- Notice: With balanced rates the generated dots spread over the real dots. With a very large ratio they bunch together.
- Why: If one player changes too fast, the other cannot keep up. Drawn stand-in, not a trained model: the motion is scripted.
The picture above is scripted. This one is really trained: two tiny networks learn from scratch in your browser, so whatever happens is what training does.
Do: Press Run and let it train for about 4000 rounds with 1 D update per G update, then press Restart, move the slider to 5, and run again.Notice: With 1 update G usually ends up covering all 8 bumps. With 5, G usually stops at 4 to 6 bumps while D scores real points well above fake ones. Across 20 random starts trained for 4000 rounds, 17 covered all 8 bumps with 1 update and 1 covered all 8 with 5.Why: D draws a line that says real is on this side, G moves its points across it, and D redraws the line. A stronger D draws a harsher line each round, and G tends to chase the nearest spot D accepts instead of all eight bumps. Really trained but a toy ring, not a real image GAN.
#Step 1: Sample Noise z
A random vector z is drawn from a simple bell-curve distribution. These random numbers are the raw material the generator will turn into an image. Each z produces a different output.
#Step 2: Generator Produces Fake Image
The generator G transforms z into a synthetic image G(z). Early in training, this output is garbage — random pixel noise with no structure. The generator has not yet learned what real images look like.
#Step 3: Mix with Real Images
A batch of real images from the training set is combined with the generator's fakes. The discriminator will see both, but it does not know which are which. This mixed batch is the discriminator's exam.
#Step 4: Discriminator Classifies Real vs Fake
The discriminator D evaluates each image and outputs a probability: close to 1.0 for "real" and close to 0.0 for "fake." Early on, the discriminator quickly learns to spot the generator's crude fakes. It assigns high scores to real images and low scores to fakes.
#Step 5: D Loss — Penalize Wrong Classifications
The discriminator loss measures its classification errors: it is penalized for assigning low probability to real images and high probability to fakes. The loss D_loss = -[log D(real) + log(1 - D(fake))] is minimized by correctly identifying both real and fake samples.
#Step 6: G Loss — Penalize Detected Fakes
The generator loss measures how well its fakes fooled the discriminator. If D(G(z)) is low (discriminator caught the fake), the generator is penalized. The generator minimizes -log D(G(z)), pushing its outputs toward images the discriminator believes are real.
#Step 7: Update Both Networks
Gradients flow and both networks update their weights. The discriminator sharpens its detection of fakes. The generator adjusts to produce more convincing outputs. Crucially, each update only touches one network at a time — the other stays frozen. Typically 1-5 discriminator steps per generator step.
#Step 8: Repeat (Equilibrium or Mode Collapse)
The loop repeats for thousands of iterations. If training goes well, both networks approach a Nash equilibrium (a point where neither can gain by changing alone): G produces outputs that look real and D outputs 0.5 for everything. If training goes poorly, the generator may mode-collapse (make only a few safe outputs) or gradients may vanish (discriminator too strong). Watch sample diversity and discriminator scores.
- Do: Scroll through the eight steps and follow one batch from random numbers to the update.
- Notice: Only one network is updated at a time; the other stays frozen for that step.
- Why: Each network needs a fixed opponent to learn against. The steps talk about images, but the picture shows dots. Drawn stand-in, not a trained model.
#The Training Nightmares
GAN training is notoriously unstable. These are the three most common failure modes.
#Mode Collapse
Mode collapse happens because the generator finds one output that fools the current discriminator and exploits it, instead of learning the whole data distribution. The value of the game against a perfect discriminator is the Jensen-Shannon divergence, which would punish a missing mode. But training alternates between the players: the generator chases whatever the current discriminator likes, and the loss has no term that rewards variety.
To see this exactly, freeze the discriminator at its current weakness, a single point where it says "real" most strongly, and ask what the best generator is for that frozen discriminator.
The lab below uses a standard test: real data is eight bell-shaped clumps (modes) around a ring. A healthy generator puts samples on all eight.
- Do: Press Play with no fixes, then switch the four fixes on one at a time.
- Notice: With no fixes, the samples sit on one or two of the eight clumps and hop between them. Each fix brings more clumps back, and the covered-modes counter rises toward 8.
- Why: The loss scores each sample alone, so nothing rewards variety. Fixes add that signal. Drawn stand-in, not a trained model: the pattern is scripted.
#Vanishing Gradients
#Oscillation and Non-Convergence
In ordinary training the loss falls steadily. GAN training is a game between two players, so the loss can go up and down without ever settling. The discriminator improves, then the generator improves, then the discriminator's earlier gains stop being enough, and so on in circles.
#Stabilizing GAN Training: Key Innovations
Researchers spent years developing ways to steady GAN training.
#Wasserstein GAN (WGAN)
Replaces the binary cross-entropy loss with the Wasserstein distance (also called Earth Mover's distance: the least work needed to move one pile of sand into the shape of another). It keeps giving the generator a useful direction even when the real and fake distributions do not overlap.
This loss is not an arbitrary choice. The Wasserstein-1 distance (the minimum average distance mass must travel to turn one distribution into the other) has a dual form, the Kantorovich-Rubinstein duality: it equals the largest possible gap E_p[f] - E_q[f] over functions f that are 1-Lipschitz, which means f changes by at most the distance moved. The critic D plays f, and that is why it must be kept 1-Lipschitz. In one dimension the distance has a closed form you can check by hand, and the derivation proves the duality in that case.
#Spectral Normalization
Limits how fast the discriminator's output can change (its Lipschitz constant) by dividing each weight matrix by its spectral norm, its largest singular value. A discriminator that cannot change too sharply steadies the game. The singular value decomposition is introduced in Eigenvalues & SVD.
#Progressive Growing
Start by generating tiny 4x4 images. Once training is steady, add layers to both G and D to reach 8x8, then 16x16, and so on up to 1024x1024. Each stage adds finer detail. This was the key idea behind ProGAN and its successor StyleGAN.
#StyleGAN: The Peak of GAN Art
StyleGAN's key innovations:
- Mapping network: z -> w through 8 fully-connected layers. This "untangles" the latent space, making it more disentangled.
- Style injection: w modulates each generator layer via AdaIN, giving fine-grained control.
- Noise injection: Per-pixel noise is added at each layer for stochastic variation (freckles, hair strands, pores).
- Style mixing: Different w vectors can be used at different layers, enabling "style transfer" between faces.
The result: photorealistic 1024x1024 faces with fine control over single attributes.
#CodePlayground: GAN Training Simulation
Below is a real GAN, small enough to run in the browser. The real data is a bell curve centered at 4. The generator has one knob, the center of its own bell curve, which starts at -4. The discriminator is a logistic curve (an S-shaped function from 0 to 1). Watch what its gradient does to the generator as the discriminator gets stronger.
Tests: Verify that the strong-discriminator saturating run has a smaller generator gradient than the weak-discriminator run, stays near its start, and that the non-saturating run reaches the real data. The cell asserts all three.
#GANs vs. Diffusion Models: The Succession
By 2020, GANs led image generation. StyleGAN2 produced photorealistic faces at 1024x1024. Then diffusion models arrived and overtook GANs step by step:
| Dimension | GANs | Diffusion Models |
|---|---|---|
| Image quality | Excellent (sharp) | Excellent (and more diverse) |
| Training stability | Fragile, many failure modes | Stable, straightforward |
| Mode coverage | Prone to mode collapse | Full distribution coverage |
| Controllability | StyleGAN: good. Others: limited | Classifier-free guidance: excellent |
| Speed | Fast (single forward pass) | Slow (many denoising steps) |
| Theory | Minimax game (tricky) | Variational bound (clean) |
Generative Adversarial Nets
Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, et al. (2014)
The paper that started it all. Clean formulation of the minimax game, theoretical convergence proof, and experimental results on MNIST and CIFAR-10.
A Style-Based Generator Architecture for Generative Adversarial Networks
Tero Karras, Samuli Laine, Timo Aila (2018)
StyleGAN: rethought the generator architecture with a mapping network and style injection. Produced photorealistic 1024x1024 faces and became the gold standard for GAN generation.
Wasserstein GAN
Martin Arjovsky, Soumith Chintala, Leon Bottou (2017)
Replaced the GAN loss with the Wasserstein distance, providing more stable training and meaningful loss curves. A theoretical breakthrough that made GAN training significantly more reliable.
#Key Takeaways
- GANs learn through competition. The generator makes fakes, the discriminator catches them, and the pressure drives both to improve until the fakes are convincing
- Mode collapse is the signature failure. The generator may learn only a few realistic samples that fool the discriminator and ignore the variety of the real data
- GAN training is unstable. The game can oscillate, diverge or collapse. Wasserstein loss, spectral normalization and progressive growing help but do not fully solve it
- StyleGAN gave fine control over generation. Style information injected at different layers controls pose, identity and lighting at different scales
#Quick Check
In the GAN minimax game, what does the discriminator try to maximize?