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
- Builds on
- 17 concepts →
- Quiz
- 4 questions ↓
This leads to
—The full path from zero — 17 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- What Generative Models Do
- 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, . It turns a vector of random numbers into a sample , such as an image. The detective is a second network called the discriminator, . It looks at a sample and outputs the probability that it is real. The two are trained in alternation. This is adversarial training.
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 that the discriminator tries to make large and the generator tries to make small, a minimax game:
Symbol by symbol:
- is the real data distribution. means "a real training example".
- is a simple noise distribution, usually a standard Gaussian. means "a random noise vector".
- is a number between 0 and 1: the discriminator's probability that its input is real.
- means "average over many draws".
- The first term is large when says "real" (near 1) for real data. The second is large when says "fake" (near 0) for generated data, because then is near 1.
means the discriminator adjusts its weights to make as large as possible. This is just the binary cross-entropy objective of a real-versus-fake classifier. means the generator adjusts its weights to make as small as possible. The generator only appears in the second term, so it tries to push towards 1.
The non-saturating trick
Early in training the fakes are obviously fake, , and the curve is almost flat there. The generator gets almost no gradient exactly when it most needs one. So in practice the generator maximises 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): . It is doing well.
- Generator loss (non-saturating, wants label 1 for its fake): . It is being caught, so its loss is high, and the gradient tells it how to change that fake to raise 's score.
Where the game should end
For a fixed generator, the best possible discriminator can be worked out exactly. At each point :
where is the distribution of the generator's samples. It is the fraction of probability at that comes from real data. If the generator is perfect, , then everywhere: the detective can only guess. Goodfellow showed that, against this best discriminator, the generator is minimising a measure of the difference between and (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 , and the generator loss is . 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.
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 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 (, 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 , only '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 becomes perfect, 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 , 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
- Change the learning rate of the discriminator only to
5e-3, and then the generator's only to5e-3. Does training still cover 8/8 blobs? What do the losses do?- Remove
betas=(0.5, 0.999)from both optimizers (so Adam uses its default ). Run a few seeds. Is training less stable?- 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()afterloss_G.backward().
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Generative Adversarial Networks (Google ML course)
A short course on GAN structure, loss functions, common problems and variants.
GAN Lab
Train a small GAN on 2-D data in your browser and watch the generator and discriminator evolve step by step.
From GAN to WGAN
Why GAN training is hard (vanishing gradients, mode collapse) and how the Wasserstein GAN addresses it, step by step.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Generative Adversarial Networks
The original GAN paper: a generator and a discriminator trained against each other.
Unsupervised Representation Learning with Deep Convolutional GANs (DCGAN)
The architecture guidelines that first made convolutional GANs train reliably.
A Style-Based Generator Architecture for GANs (StyleGAN)
The generator that made photorealistic, controllable faces and the FFHQ dataset.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/gans.md