◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

Generative Adversarial Networks

A GAN trains two networks against each other. A generator turns random noise into fake samples, and a discriminator tries to tell fakes from real data. Each improves by beating the other, until the fakes are hard to tell from the real thing.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

What Generative Models DoConvolutional Neural Networks

This leads to

—
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Convolutional Neural Networks
  17. What Generative Models Do
  18. Generative Adversarial Networks

Read them roughly in this order. See it on the concept map →

Why it matters

From 2014 to about 2021, generative adversarial networks (GANs) were the way to make realistic images. In 2019 the website This Person Does Not Exist showed a new, photorealistic face on every reload. Every face was invented by NVIDIA's StyleGAN, trained on 70,000 photos. GANs powered the first wave of "deepfakes", photo apps that aged or restyled faces, image-to-image translation (turning sketches into photos, horses into zebras), and super-resolution.

Diffusion models have since taken over most image and video generation. GANs still matter, for three reasons:

  • The adversarial idea is everywhere. A learned critic that says "this looks fake" is used as an extra loss inside the autoencoders of Stable Diffusion, in most neural audio vocoders and codecs (Music and Voice Generation), in super-resolution, and in methods that distil slow diffusion models into fast one-step generators.
  • They are fast. A GAN makes an image in one network pass, while a diffusion model needs many.
  • They teach a lesson about training two models against each other: it can be powerful and very unstable.

The intuition

Picture an art forger and a detective.

  • The forger paints fake masterpieces. At first they are terrible.
  • The detective looks at a mix of real paintings and the forger's fakes, and learns to spot the fakes.
  • The forger finds out which fakes were caught and why, and adjusts.
  • The detective, facing better fakes, has to look more carefully.

Round after round, both get better. If all goes well, the forger ends up producing paintings the detective can only guess about, 50-50. At that point the fakes have the same statistics as the real paintings.

In a GAN the forger is a neural network called the generator, GG. It turns a vector of random numbers z\mathbf{z} into a sample G(z)G(\mathbf{z}), such as an image. The detective is a second network called the discriminator, DD. It looks at a sample and outputs the probability that it is real. The two are trained in alternation. This is adversarial training.

Noise z random numbers Generator G the forger Fake G(z) generated sample Real x training data Discriminator D the detective D(·) P(real) Generator update: change G so that D(G(z)) → 1 the gradient flows back through D (frozen) into G Discriminator update: D(real) → 1, D(fake) → 0 an ordinary binary classifier, retrained on every batch The two steps alternate, thousands of times. G never sees real data: it learns only from D's gradients.
Fig. 1 The GAN training loop. The generator turns noise into fakes. The discriminator sees real and fake samples and outputs the probability that each is real. The discriminator is trained to classify correctly. The generator is trained, through the discriminator's gradients, to make its fakes classified as real. The generator never sees a real example directly.

One detail surprises most people: the generator never sees the training data. Everything it learns about real data arrives as gradients passed back through the discriminator. The discriminator acts as a learned, constantly improving loss function. It tells the generator, pixel by pixel, which direction would make its output look more real.

Key idea A GAN is a two-player game. The discriminator learns to tell real from fake, and the generator learns to fool it. The discriminator works as a learned loss function, which is why GAN samples can be sharp where reconstruction-based models are blurry.

How it works

The game in one equation

Goodfellow and colleagues wrote the game as a single value VV that the discriminator tries to make large and the generator tries to make small, a minimax game:

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}_{\mathbf{x} \sim p_{\text{data}}}\big[\log D(\mathbf{x})\big] + \mathbb{E}_{\mathbf{z} \sim p(\mathbf{z})}\big[\log\big(1 - D(G(\mathbf{z}))\big)\big]

Symbol by symbol:

  • pdatap_{\text{data}} is the real data distribution. x∼pdata\mathbf{x} \sim p_{\text{data}} means "a real training example".
  • p(z)p(\mathbf{z}) is a simple noise distribution, usually a standard Gaussian. z∼p(z)\mathbf{z} \sim p(\mathbf{z}) means "a random noise vector".
  • D(⋅)D(\cdot) is a number between 0 and 1: the discriminator's probability that its input is real.
  • E[⋅]\mathbb{E}[\cdot] means "average over many draws".
  • The first term is large when DD says "real" (near 1) for real data. The second is large when DD says "fake" (near 0) for generated data, because then 1−D(G(z))1 - D(G(\mathbf{z})) is near 1.

max⁡D\max_D means the discriminator adjusts its weights to make VV as large as possible. This is just the binary cross-entropy objective of a real-versus-fake classifier. min⁡G\min_G means the generator adjusts its weights to make VV as small as possible. The generator only appears in the second term, so it tries to push D(G(z))D(G(\mathbf{z})) towards 1.

The non-saturating trick

Early in training the fakes are obviously fake, D(G(z))≈0D(G(\mathbf{z})) \approx 0, and the curve log⁡(1−D)\log(1 - D) is almost flat there. The generator gets almost no gradient exactly when it most needs one. So in practice the generator maximises log⁡D(G(z))\log D(G(\mathbf{z})) instead, which is steep near 0. This "non-saturating" loss has the same goal, making D say "real", but gives strong gradients early. Every implementation, including the code below, uses it.

A worked example

Suppose that on one real image the discriminator outputs 0.9, and on one fake it outputs 0.2.

  • Discriminator loss (binary cross-entropy, label 1 for real, 0 for fake): −ln⁡0.9−ln⁡(1−0.2)=0.105+0.223=0.328-\ln 0.9 - \ln(1 - 0.2) = 0.105 + 0.223 = 0.328. It is doing well.
  • Generator loss (non-saturating, wants label 1 for its fake): −ln⁡0.2=1.609-\ln 0.2 = 1.609. It is being caught, so its loss is high, and the gradient tells it how to change that fake to raise DD's score.

Where the game should end

For a fixed generator, the best possible discriminator can be worked out exactly. At each point x\mathbf{x}:

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

where pgp_g is the distribution of the generator's samples. It is the fraction of probability at x\mathbf{x} that comes from real data. If the generator is perfect, pg=pdatap_g = p_{\text{data}}, then D∗=12D^* = \tfrac{1}{2} everywhere: the detective can only guess. Goodfellow showed that, against this best discriminator, the generator is minimising a measure of the difference between pgp_g and pdatap_{\text{data}} (the Jensen–Shannon divergence), which is zero only when they match. The resulting balance, where neither player can improve by changing on its own, is a Nash equilibrium.

At that balance, the discriminator loss is −ln⁡12−ln⁡12=2ln⁡2≈1.386-\ln\tfrac12 - \ln\tfrac12 = 2\ln 2 \approx 1.386, and the generator loss is ln⁡2≈0.693\ln 2 \approx 0.693. Unlike most training, the losses don't go to zero when a GAN works. They hover around these values, as in the run below (1.27 and 0.90 at the end).

A real run on 2-D data

The code trains a GAN on points from 8 small Gaussian blobs arranged on a circle, a classic test because it is easy to see whether every blob is produced.

Step 0random generator Step 300spreading out Step 1,000all 8 blobs found Step 3,000points pulled tight real data: 8 Gaussian blobs400 generated points
Fig. 2 Snapshots of a GAN learning eight Gaussian blobs (blue rings). At first the generator outputs a tight cluster near the centre. It then spreads out, finds all eight blobs by step 1,000, and pulls its points ever more tightly onto them. The thin bridges between blobs are a typical GAN artefact: a continuous generator has to pass through the gaps.

The run's log reports, at each checkpoint, how many of the 8 blobs have at least one generated point within 0.25 of their centre, and what share of points land that close:

Step D loss G loss Blobs covered Points near a blob
0 1.323 0.709 0/8 0%
1,000 1.246 0.824 8/8 54%
2,000 1.290 0.908 8/8 81%
3,000 1.275 0.902 8/8 88%

Mode collapse

The most famous GAN failure is mode collapse. The generator finds a few outputs that fool the current discriminator and produces only those, such as only 3 of the 8 blobs, or only one kind of face. The discriminator then learns to reject those, the generator jumps to a different few, and the two chase each other round without ever covering everything. Nothing in the generator's loss rewards variety. It only rewards fooling DD on each sample.

This is why GANs score high on sample quality but often poorly on mode coverage (What Generative Models Do). Fixes include feeding the discriminator statistics of a whole batch (minibatch discrimination), the Wasserstein loss below, and careful architecture choices.

Making GANs train: DCGAN, WGAN, StyleGAN

  • DCGAN (Radford, Metz and Chintala, 2015) set out architecture rules that made convolutional GANs train reliably: strided convolutions instead of pooling, Normalization Layers: BatchNorm and LayerNorm, ReLU in the generator, LeakyReLU in the discriminator, and Adam with a reduced momentum term (β1=0.5\beta_1 = 0.5, as in the code). It also showed meaningful arithmetic on latent vectors, such as "smiling woman − neutral woman + neutral man ≈ smiling man".
  • WGAN (Arjovsky, Chintala and Bottou, 2017) replaced the classifier with a critic that estimates the Wasserstein ("earth mover's") distance between real and fake distributions. Its gradients stay useful even when the two distributions don't overlap. Later improvements added a gradient penalty (WGAN-GP) and spectral normalisation.
  • Progressive GAN (2017) and StyleGAN (2018, 2019, 2021) from NVIDIA grew images from low to high resolution. StyleGAN injects the latent code into every layer as a "style", which separates coarse features (pose, face shape) from fine ones (hair texture, freckles). It reached 1024×1024 photorealistic faces.
  • Conditional GANs add a label or an image as input to both networks. pix2pix (paired image translation) and CycleGAN (unpaired, such as horses into zebras) are well-known examples.

Why diffusion overtook GANs

By 2021, Diffusion Models were matching and then beating the best GANs on image benchmarks. They won for practical reasons:

  • Stable training. A diffusion model minimises a simple regression loss. There is no two-player balance to break, so it scales smoothly to billions of parameters and images.
  • Coverage. Diffusion's likelihood-based objective rewards covering all of the data. It does not suffer mode collapse.
  • Conditioning. Steering by text prompts at scale proved far easier.

The price is speed. Much recent work brings GANs back to make diffusion fast, for example adversarial diffusion distillation (used for SDXL Turbo, 2023), which trains a one-step or few-step student with a discriminator.

In code

A complete GAN in PyTorch on the 8-blob data. It trains in about 5 seconds on a CPU.

import math, torch, torch.nn as nn

torch.manual_seed(0)
# Real data: 8 small Gaussian blobs arranged on a circle of radius 2
centers = torch.tensor([[2 * math.cos(2 * math.pi * k / 8), 2 * math.sin(2 * math.pi * k / 8)] for k in range(8)])
def real_batch(n):
    return centers[torch.randint(0, 8, (n,))] + 0.05 * torch.randn(n, 2)

G = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))   # noise -> point
D = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(0.2), nn.Linear(64, 64), nn.LeakyReLU(0.2), nn.Linear(64, 1))  # point -> logit
opt_G = torch.optim.Adam(G.parameters(), lr=1e-3, betas=(0.5, 0.999))
opt_D = torch.optim.Adam(D.parameters(), lr=1e-3, betas=(0.5, 0.999))
bce = nn.BCEWithLogitsLoss()
ones, zeros = torch.ones(256, 1), torch.zeros(256, 1)

for step in range(3001):
    # 1. Discriminator: label real points 1, generated points 0
    fake = G(torch.randn(256, 2)).detach()
    loss_D = bce(D(real_batch(256)), ones) + bce(D(fake), zeros)
    opt_D.zero_grad(); loss_D.backward(); opt_D.step()
    # 2. Generator: try to make D say 1 for its fakes (non-saturating loss)
    loss_G = bce(D(G(torch.randn(256, 2))), ones)
    opt_G.zero_grad(); loss_G.backward(); opt_G.step()
    if step % 1000 == 0:
        with torch.no_grad():
            pts = G(torch.randn(2000, 2))
            dist = torch.cdist(pts, centers)
            close = dist.min(1).values < 0.25
            modes = len(dist.argmin(1)[close].unique())
        print(f"step {step:4d}  loss_D {loss_D.item():.3f}  loss_G {loss_G.item():.3f}  "
              f"blobs covered {modes}/8  points near a blob {close.float().mean():.0%}")

# step    0  loss_D 1.323  loss_G 0.709  blobs covered 0/8  points near a blob 0%
# step 1000  loss_D 1.246  loss_G 0.824  blobs covered 8/8  points near a blob 54%
# step 2000  loss_D 1.290  loss_G 0.908  blobs covered 8/8  points near a blob 81%
# step 3000  loss_D 1.275  loss_G 0.902  blobs covered 8/8  points near a blob 88%

Three details matter. .detach() in step 1 stops the discriminator's update from changing the generator. In step 2 only opt_G.step() is called, so although gradients flow through DD, only GG's weights change. And the generator's loss uses label 1 for its fakes: that is the non-saturating trick. For images, swap the nn.Linear stacks for convolutional networks, following the DCGAN rules.

Common pitfalls

  • The discriminator wins too easily. If DD becomes perfect, D(G(z))≈0D(G(\mathbf{z})) \approx 0 everywhere and the generator's gradients carry little information. Signs: D loss near 0 and G loss climbing. Remedies: a smaller or regularised D, label smoothing (train D on targets of 0.9 instead of 1), spectral normalisation, or a Wasserstein loss.
  • Mode collapse. Count the modes, as the code does. On images, look at a large grid of samples for repeats.
  • Reading the losses like ordinary losses. GAN losses don't fall steadily. Both hover around their balance values. Track sample quality with metrics such as FID and by looking at samples.
  • Oscillation. The two players can circle each other forever. Lower learning rates, Adam with β1=0.5\beta_1 = 0.5, and keeping an exponential moving average of the generator's weights all help.
  • Hyperparameter sensitivity. A GAN that trains well can fail completely with a slightly different learning rate or seed. Change one thing at a time.

Watch out GAN-made faces and voices were the first convincing deepfakes. Generating realistic images of real people without consent can be illegal and harmful, whatever the method. See Deepfakes and Misinformation.

Where it leads

  • Diffusion Models: the more stable successor for most generation tasks.
  • Latent Diffusion and Stable Diffusion: the Stable Diffusion autoencoder is trained with an adversarial loss to keep its reconstructions sharp.
  • Music and Voice Generation: GAN vocoders such as HiFi-GAN and the adversarial losses inside neural audio codecs.
  • Adversarial Examples share the word "adversarial" but are a different idea: tiny input changes that fool a classifier.
  • Few-step image generators that distil diffusion models with a discriminator.

A bit of history

Ian Goodfellow proposed GANs in 2014. He later said the idea came to him during an argument with friends in a Montreal bar and that he coded the first version that night. The paper, with co-authors including Yoshua Bengio, appeared at NeurIPS 2014. Early GAN images were small and blurry. DCGAN (2015) made convolutional GANs trainable. Progressive GAN (2017), BigGAN (2018, class-conditional ImageNet at 512×512) and NVIDIA's StyleGAN series (2018–2021) made them photorealistic.

In 2021 Dhariwal and Nichol's paper Diffusion Models Beat GANs on Image Synthesis marked the turning point. In 2022, DALL·E 2, Imagen and Stable Diffusion, all diffusion-based, moved image generation away from GANs. Large GANs such as GigaGAN (2023) showed that GANs can scale with enough care, but the field had moved on. The adversarial loss survives as a component inside other systems.

Try it

  1. Change the learning rate of the discriminator only to 5e-3, and then the generator's only to 5e-3. Does training still cover 8/8 blobs? What do the losses do?
  2. Remove betas=(0.5, 0.999) from both optimizers (so Adam uses its default β1=0.9\beta_1 = 0.9). Run a few seeds. Is training less stable?
  3. Replace the non-saturating generator loss with the original minimax form: loss_G = -bce(D(G(z)), zeros). Compare the first 500 steps.

Hint for 3: look at the size of the generator's gradients early on. Print G[0].weight.grad.norm() after loss_G.backward().

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a GAN, how does the generator learn what real data looks like?

  2. On one real image the discriminator outputs 0.9 and on one fake it outputs 0.2. What is the non-saturating generator loss for that fake?

  3. A GAN trained on 8 blobs produces sharp points, but only on 3 of the blobs, and the set of blobs keeps changing over training. What is this?

  4. Your GAN's discriminator loss hovers around 1.3 and the generator loss around 0.9 and they are not falling. A teammate wants to stop training as broken. What do you say?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

GAN Lab

Georgia Tech Polo Club & Google · Beginner · Free

Train a small GAN on 2-D data in your browser and watch the generator and discriminator evolve step by step.

Article

From GAN to WGAN

Lilian Weng · 2017 · Advanced · Free

Why GAN training is hard (vanishing gradients, mode collapse) and how the Wasserstein GAN addresses it, step by step.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Paper

Generative Adversarial Networks

Goodfellow et al. · 2014 · Advanced · Free

The original GAN paper: a generator and a discriminator trained against each other.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/gans.md