Skip to content
LearnAI
PART 8 · IMAGE & VIDEO GENERATION/ Foundations of generation

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.

⏱ 11 minIntermediate

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.

ANALOGY· The forger and the detective

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

Training alternates. Update DD to label real samples 1 and fakes 0. Then update GG so that DD 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: DD maximizes the classification objective, GG 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 DD would output ½ everywhere.

INTERACTIVEA 1D GAN, training live
Preset
-4-202400.51real datageneratedD(x) = P(real)
Mode history appears here once training starts.
training step
0
fake mass: left / right
69% / 31%
real data: 50% / 50%
mean D(fake)
0.55
0.5 = D can't tell
losses D / G
0.00 / 0.00
ideal: 1.39 / 0.69

Both networks are tiny MLPs trained live in your browser with Adam: one step = a batch of 64 real and 64 fake samples.

Real data has two modes at −2 and +2 (blue). The generator (orange histogram) and discriminator (black curve, D(x)) are tiny neural networks trained in your browser. Press Train, then try the Mode collapse preset.

Things to try:

  1. Balanced, Train. Early on, D(x)D(x) is high wherever real data lives and low where the fakes are. The generator’s samples slide uphill along DD toward the real modes. Within a few hundred steps, the orange histogram roughly matches the blue curve and D(x)D(x) flattens toward 0.5: the detective is reduced to guessing.
  2. Mode collapse preset. Now the generator learns 40× faster than the discriminator. It piles all its samples onto one mode, wherever DD currently says “real”. The discriminator slowly learns that this spot is suspicious, DD 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.
  3. 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, D(G(z))≈0D(G(z)) \approx 0 everywhere and the original minimax loss for GG goes flat. The original paper already recommended a fix that nearly everyone uses: train GG to maximize log⁡D(G(z))\log D(G(z)) instead of minimizing log⁡(1−D(G(z)))\log(1 - D(G(z))). Same fixed point, much stronger gradients early on. The demo uses this “non-saturating” loss.

Mode collapse. The generator is rewarded for fooling DD, 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 DD 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 zz 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 zz into an intermediate code ww, 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:

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

min⁡Gmax⁡D  V(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼p(z)[log⁡(1−D(G(z)))].\min_G \max_D \; V(D, G) = \mathbb{E}_{x \sim p_{\text{data}}}\big[\log D(x)\big] + \mathbb{E}_{z \sim p(z)}\big[\log\big(1 - D(G(z))\big)\big].

For a fixed generator with sample density pgp_g, maximize pointwise: alog⁡D+blog⁡(1−D)a \log D + b \log(1 - D) peaks at D=a/(a+b)D = a/(a+b). So the optimal discriminator is

D∗(x)=pdata(x)pdata(x)+pg(x).D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)} .

Substituting back gives V(D∗,G)=−log⁡4+2 JSD(pdata ∥ pg)V(D^*, G) = -\log 4 + 2\,\mathrm{JSD}(p_{\text{data}} \,\|\, p_g), where JSD is the Jensen–Shannon divergence. It is minimized exactly when pg=pdatap_g = p_{\text{data}}, at which point D∗=12D^* = \tfrac12.

Worked example. At three points xx, suppose:

xxpdata(x)p_{\text{data}}(x)pg(x)p_g(x)D∗(x)D^*(x)gradient signal for GG
near the left mode0.400.050.89“move fakes here”
near the right mode0.400.400.50balanced, no push
between the modes0.010.300.03“move fakes away”

The generator follows ∇xlog⁡D(x)\nabla_x \log D(x) at its samples, so fakes stranded between the modes are pushed toward xx where D∗D^* is higher. Mode collapse happens when GG moves faster than DD can update: all fakes rush to the currently highest point of DD, overshooting the “balanced” condition in the middle row.

Losses at equilibrium. With D=12D = \tfrac12, the discriminator’s loss is −log⁡12−log⁡12=2ln⁡2≈1.39-\log\tfrac12 - \log\tfrac12 = 2\ln 2 \approx 1.39 and the non-saturating generator loss is −log⁡12≈0.69-\log\tfrac12 \approx 0.69: 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()
COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. Q1.What signal does the generator learn from?

  2. Q2.At the theoretical equilibrium of a GAN, what does the discriminator output?

  3. Q3.In the demo's mode-collapse preset, the generator jumps between the two modes. What is happening?

  4. Q4.Why did diffusion models largely replace GANs for image generation?

  5. Q5.Where are adversarial (discriminator) losses still commonly used today?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.