8.2GANs (a brief history)
A forger and a detective, trained against each other. GANs produced the first photorealistic generated faces, then lost the crown to diffusion, but their adversarial trick lives on inside today's models.
Learning to generate without writing down a probability
In the previous lesson, VAEs learned to generate by maximizing a bound on the probability of the data, and paid for it with blurry samples. In 2014 Ian Goodfellow and colleagues proposed a radically different route. Don’t model probabilities at all. Instead, train a second network to judge whether a sample looks real, and use its judgment as the generator’s training signal.
That is the generative adversarial networkGenerative adversarial network (GAN)A generator and a discriminator trained against each other: the generator tries to fool the discriminator.. For about six years it was the state of the art for realistic images, and its most famous product, the uncannily real faces of StyleGAN, made “this person does not exist” a household phrase.
A forger is trying to produce fake banknotes; a detective inspects notes and declares each one real or fake. At first the forger is terrible and the detective’s job is easy. But every time a fake is caught, the forger learns which features gave it away and improves. The detective, facing better fakes, learns subtler tells. Each pushes the other forward.
The forger is the generator, the detective is the discriminator, and the detective’s verdicts, specifically how they would change if the note changed, are the gradients the generator learns from. If all goes well, the game ends when fakes are indistinguishable from real notes and the detective can only guess: 50/50.
The two players
- The generator takes a random vector (say, 100 numbers drawn from a Gaussian) and outputs a sample , such as an image. It never sees real data directly.
- The discriminatorDiscriminatorIn a GAN, the classifier that tries to tell real data from the generator's fakes; its feedback is the generator's training signal. takes a sample and outputs , the probability that is real. It’s an ordinary binary classifier trained with cross-entropyCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right..
Training alternates. Update to label real samples 1 and fakes 0. Then update so that labels its fakes closer to 1, by backpropagating through the discriminator into the generator’s weights. The discriminator is a learned, constantly changing loss function for the generator.
Goodfellow et al. wrote this as a minimax game: maximizes the classification objective, minimizes it. They proved that if both players had unlimited capacity and the game reached its equilibrium, the generator’s distribution would exactly equal the data distribution and would output ½ everywhere.
Both networks are tiny MLPs trained live in your browser with Adam: one step = a batch of 64 real and 64 fake samples.
Things to try:
- Balanced, Train. Early on, is high wherever real data lives and low where the fakes are. The generator’s samples slide uphill along toward the real modes. Within a few hundred steps, the orange histogram roughly matches the blue curve and flattens toward 0.5: the detective is reduced to guessing.
- Mode collapse preset. Now the generator learns 40× faster than the discriminator. It piles all its samples onto one mode, wherever currently says “real”. The discriminator slowly learns that this spot is suspicious, drops there, and the whole generator jumps to the other mode. The history strip shows it flipping between “all left” and “all right” instead of settling at 50/50.
- Break it yourself. From Balanced, raise the generator rate to the maximum, or set D steps to 5 with a tiny generator rate. Notice how sensitive the outcome is to these knobs. Practitioners spent years on tricks to tame exactly this.
Why GAN training is hard
It’s a game, not a descent. Ordinary training walks downhill on a fixed loss surface (see gradient descent). Here each player’s landscape changes whenever the other moves. Simultaneous gradient steps on a game can circle around the equilibrium forever or spiral away from it, which is the oscillation you can see in the demo.
Vanishing gradients. If the discriminator wins too decisively, everywhere and the original minimax loss for goes flat. The original paper already recommended a fix that nearly everyone uses: train to maximize instead of minimizing . Same fixed point, much stronger gradients early on. The demo uses this “non-saturating” loss.
Mode collapse. The generator is rewarded for fooling , not for covering the data. Producing one convincing kind of output is a perfectly good strategy against the current discriminator. Mode collapseMode collapseA GAN failure where the generator produces only a few kinds of output (one 'mode' of the data) instead of the full variety. ranges from total (every sample nearly identical) to partial (a GAN trained on many dog breeds only ever produces a handful). Remedies included minibatch discrimination (letting look at batch diversity), Wasserstein GANs (Arjovsky et al., 2017) with a smoother distance, spectral normalization, and careful learning-rate balancing.
Highlights from the GAN era
- DCGAN (Radford, Metz and Chintala, 2015) found an architecture that trained reliably: all-convolutional, batch normalization, no pooling, LeakyReLU in the discriminator. It also showed latent arithmetic on faces, like “man with glasses − man + woman ≈ woman with glasses”.
- Progressive GAN (Karras et al., 2017) grew both networks during training, from 4×4 to 1024×1024 pixels, producing the first convincing megapixel faces.
- BigGAN (Brock et al., 2018) scaled class-conditional GANs to ImageNet and popularized the “truncation trick”: sample from a narrowed distribution to trade diversity for quality, an early cousin of classifier-free guidance.
- StyleGAN (Karras, Laine and Aila, 2018) redesigned the generator. A mapping network turns into an intermediate code , which modulates every layer as a “style” (coarse layers control pose and face shape, fine layers control texture and color), with per-pixel noise inputs for details like hair strands. StyleGAN2 (2019) removed its characteristic blob artifacts and StyleGAN3 (2021) fixed texture “sticking” in animations. Its latent space was so well organized that it became a research tool for image editing.
Why diffusion took over
By 2021, Dhariwal and Nichol’s paper was titled, bluntly, Diffusion Models Beat GANs on Image Synthesis. Three reasons stand out:
- Stable training. Diffusion’s loss is plain regression on noise (see Diffusion: noising & denoising). No game, no balancing act. Scaling up is mostly a matter of compute.
- Coverage. Every training image contributes to the diffusion loss, so the model has no incentive to drop rare modes. GANs systematically under-represent the diversity of their data.
- Flexibility. Text conditioning, guidance, inpainting and editing fit naturally into iterative denoising. Large text-to-image GANs were attempted (GigaGAN in 2023 showed it can be done), but diffusion had already won the ecosystem.
GANs kept one big advantage: speed. A GAN generates in one forward pass; diffusion needs many.
MATH CORNER · optionalThe minimax objective and the optimal discriminator
The original GAN objective is
For a fixed generator with sample density , maximize pointwise: peaks at . So the optimal discriminator is
Substituting back gives , where JSD is the Jensen–Shannon divergence. It is minimized exactly when , at which point .
Worked example. At three points , suppose:
| gradient signal for | ||||
|---|---|---|---|---|
| near the left mode | 0.40 | 0.05 | 0.89 | “move fakes here” |
| near the right mode | 0.40 | 0.40 | 0.50 | balanced, no push |
| between the modes | 0.01 | 0.30 | 0.03 | “move fakes away” |
The generator follows at its samples, so fakes stranded between the modes are pushed toward where is higher. Mode collapse happens when moves faster than can update: all fakes rush to the currently highest point of , overshooting the “balanced” condition in the middle row.
Losses at equilibrium. With , the discriminator’s loss is and the non-saturating generator loss is : the “ideal” numbers in the demo’s readout.
In code
One training step of a GAN in PyTorch, with the non-saturating generator loss:
import torch, torch.nn.functional as F
def gan_step(G, D, opt_G, opt_D, real, z_dim=64):
b = real.shape[0]
ones, zeros = torch.ones(b, 1), torch.zeros(b, 1)
# 1) Discriminator: real -> 1, fake -> 0 (detach so G is not updated here)
fake = G(torch.randn(b, z_dim)).detach()
loss_D = F.binary_cross_entropy_with_logits(D(real), ones) + \
F.binary_cross_entropy_with_logits(D(fake), zeros)
opt_D.zero_grad(); loss_D.backward(); opt_D.step()
# 2) Generator: make D say "real" (non-saturating loss)
fake = G(torch.randn(b, z_dim))
loss_G = F.binary_cross_entropy_with_logits(D(fake), ones)
opt_G.zero_grad(); loss_G.backward(); opt_G.step() # gradients flow through D into G
return loss_D.item(), loss_G.item()
- “The generator copies or edits training images.” The generator never sees real images. It only receives gradients from the discriminator’s judgments of its own fakes.
- “Low generator loss means good samples.” GAN losses are notoriously uninformative: they measure how the two players are doing against each other right now, not sample quality. Practitioners use separate metrics like FID.
- “Mode collapse means training crashed.” Losses can look perfectly healthy while the generator produces only one kind of output. You have to look at the samples, as the demo’s histogram does.
- “GANs are obsolete.” As standalone image generators they’ve mostly been displaced, but adversarial losses are still standard in autoencoders, audio codecs and few-step diffusion distillation.
Check your understanding
Q1.What signal does the generator learn from?
Q2.At the theoretical equilibrium of a GAN, what does the discriminator output?
Q3.In the demo's mode-collapse preset, the generator jumps between the two modes. What is happening?
Q4.Why did diffusion models largely replace GANs for image generation?
Q5.Where are adversarial (discriminator) losses still commonly used today?
Further reading
- paperGenerative Adversarial Networks (Goodfellow et al., 2014) — The original paper: minimax game, optimal discriminator, non-saturating loss.
- paperUnsupervised Representation Learning with Deep Convolutional GANs (Radford et al., 2015) — DCGAN: the architecture that made GANs train reliably.
- paperA Style-Based Generator Architecture for GANs (Karras et al., 2018) — StyleGAN: mapping network, per-layer styles, FFHQ.
- paperDiffusion Models Beat GANs on Image Synthesis (Dhariwal & Nichol, 2021) — The paper that marked the handover.
- paperAdversarial Diffusion Distillation (Sauer et al., 2023) — SDXL Turbo: a discriminator helps diffusion generate in 1–4 steps.