AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◐Image Generation
  1. Generative Models: The Big Picture
  2. Generative Adversarial Networks (GANs)
  3. Diffusion Models: From Noise to Image
  4. Stable Diffusion in Practice
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Image Generation

Generative Adversarial Networks (GANs)

The generator-vs-discriminator game, the DCGAN recipe, why GAN training is unstable (mode collapse, vanishing gradients), the fixes (WGAN-GP, spectral norm), StyleGAN, and how GANs are evaluated with FID.

Intermediate~24 min·6 references
Key terms
Generative adversarial network (GAN)Generative modelLatent spaceCNN (Convolutional Neural Network)Loss functionBatch normalization

From 2014 to about 2021, GANs were the state of the art for realistic images: the famous 'this person does not exist' faces came from StyleGAN. They still matter today for fast one-step generation, super-resolution, neural vocoders such as HiFi-GAN, and as an extra 'adversarial' loss used to distil slow diffusion models into fast ones. Understanding GANs also teaches you a lot about the training dynamics of competing objectives.

≈
The counterfeiter and the detective
A counterfeiter (the generator) prints fake banknotes; a detective (the discriminator) inspects notes and says 'real' or 'fake'. Each time the detective catches a fake, the counterfeiter learns what gave it away. Each time a fake slips through, the detective learns to look closer. If both keep improving, the fakes eventually become indistinguishable from real money.

The adversarial game

The generator G maps a random vector z (sampled from N(0, I), the Latent space) to an image G(z). The discriminator D maps an image to a probability that it is real. Goodfellow et al.[1] framed training as a two-player minimax game: D maximizes its classification accuracy, G minimizes it.

min_G max_D V(D, G) = E_{x~p_data}[ log D(x) ] + E_{z~p(z)}[ log(1 − D(G(z))) ]
The original GAN objective.
In words: V is the discriminator's score for telling real from fake: the average of log D on real images plus the average of log(1 − D) on fakes. D adjusts its weights to make V as large as possible, G adjusts its weights to make it as small as possible: a two-player game.
Symbols(hover a symbol in the formula)
min_G
G chooses its parameters to minimize what follows
max_D
D chooses its parameters to maximize what follows
V(D, G)
the value of the game: one number for the current pair of networks
E_{x~p_data}
average over real images x drawn from the dataset
E_{z~p(z)}
average over noise vectors z drawn from the prior p(z), e.g. N(0, I)
D(x)
the discriminator's probability that x is real (0 to 1)
G(z)
the image the generator makes from noise z
log
natural logarithm; log 1 = 0 and the log of a small number is very negative
p_data
the (unknown) distribution of real images
▸Worked example
Batch of 2 real and 2 fake images: D(x) = 0.9, 0.8 → mean of log D(x) = (−0.1054 − 0.2231)/2 = −0.1643 D(G(z)) = 0.3, 0.1 → mean of log(1 − D(G(z))) = (ln 0.7 + ln 0.9)/2 = (−0.3567 − 0.1054)/2 = −0.2310 V = −0.1643 − 0.2310 = −0.3953 D wants V → 0 (D(x) → 1, D(G(z)) → 0); G wants V lower (D(G(z)) → 1). At the equilibrium D = ½ everywhere: V = ln 0.5 + ln 0.5 = −1.3863 = −log 4.
  1. Sample a minibatch of real images x and a minibatch of noise vectors z.
  2. Update D: push D(x) towards 1 and D(G(z)) towards 0 (binary Cross-entropy (log loss)).
  3. Update G: change G so that D(G(z)) moves towards 1, using gradients that flow back through the (frozen for this step) discriminator.
  4. Repeat. Neither network ever sees a 'correct output'; G only learns through D's feedback.
Loading interactive…
Walk through one training round, then tap the two loss boxes. Notice that the generator's update arrow passes through D: G never sees a real image and learns only from the discriminator's gradient.
i
The non-saturating trick
Early in training D easily rejects fakes, so log(1 − D(G(z))) is flat and G gets almost no gradient. In practice G instead maximizes log D(G(z)) (equivalently: train G with 'real' labels on fake images). Same fixed point, much stronger gradients early on. The original paper already recommends this[1].
D*(x) = p_data(x) / (p_data(x) + p_g(x)) ⇒ V(D*, G) = −log 4 + 2 · JSD(p_data ‖ p_g)
The optimal discriminator, and what the generator is really minimizing.
In words: For a fixed generator, the best possible discriminator simply reports which fraction of the probability at x comes from real data. Plugging it into V shows that the generator is minimizing the Jensen–Shannon divergence between the real and generated distributions, which is zero only when they are identical.
Symbols(hover a symbol in the formula)
D*(x)
the optimal discriminator's output at image x
p_data(x)
density of real images at x
p_g(x)
density of generated images at x
⇒
'which implies'
V(D*, G)
the game value when D is optimal
−log 4
the minimum value ≈ −1.386, reached when p_g = p_data
JSD
Jensen–Shannon divergence: a symmetric, bounded (0 to ln 2) measure of how different two distributions are
‖
separates the two distributions being compared
▸Worked example
At one image x: p_data(x) = 0.03, p_g(x) = 0.01 → D*(x) = 0.03 / 0.04 = 0.75 If p_g(x) = p_data(x): D*(x) = 0.5 (it cannot tell). JSD for two 2-outcome distributions p_data = (0.5, 0.5), p_g = (0.9, 0.1), mixture M = (0.7, 0.3): KL(p_data ‖ M) = 0.5 · ln(0.5/0.7) + 0.5 · ln(0.5/0.3) = 0.0872 KL(p_g ‖ M) = 0.9 · ln(0.9/0.7) + 0.1 · ln(0.1/0.3) = 0.1163 2 · JSD = 0.0872 + 0.1163 = 0.2035 V(D*, G) = −1.3863 + 0.2035 = −1.1828: above the minimum, so G can still improve.

The DCGAN recipe

Early GANs used small fully-connected nets. Radford et al.'s DCGAN[2] found a set of convolutional design rules that made training reliable enough to become the default starting point:

  • Replace pooling with strided convolutions (D) and transposed convolutions (G).
  • Use Batch normalization in both networks (except G's output layer and D's input layer).
  • ReLU in G with a tanh output (images scaled to [−1, 1]); LeakyReLU (0.2) in D.
  • Adam with learning rate 2e-4 and β₁ = 0.5 (lower than the usual 0.9, to reduce oscillation).
  • Bonus finding: walking in z space gives smooth image changes, and vector arithmetic works (smiling woman − neutral woman + neutral man ≈ smiling man).
python
import torch
import torch.nn as nn

z_dim = 100
G = nn.Sequential(  # z: (B, 100, 1, 1) -> image: (B, 3, 64, 64)
    nn.ConvTranspose2d(z_dim, 512, 4, 1, 0, bias=False), nn.BatchNorm2d(512), nn.ReLU(True),  # 4x4
    nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False), nn.BatchNorm2d(256), nn.ReLU(True),    # 8x8
    nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(True),    # 16x16
    nn.ConvTranspose2d(128, 64, 4, 2, 1, bias=False), nn.BatchNorm2d(64), nn.ReLU(True),      # 32x32
    nn.ConvTranspose2d(64, 3, 4, 2, 1, bias=False), nn.Tanh(),                                # 64x64
)
D = nn.Sequential(  # image -> one real/fake logit
    nn.Conv2d(3, 64, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, True),
    nn.Conv2d(64, 128, 4, 2, 1, bias=False), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, True),
    nn.Conv2d(128, 256, 4, 2, 1, bias=False), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, True),
    nn.Conv2d(256, 512, 4, 2, 1, bias=False), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, True),
    nn.Conv2d(512, 1, 4, 1, 0, bias=False), nn.Flatten(),
)

bce = nn.BCEWithLogitsLoss()
opt_G = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_D = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))

def train_step(real):  # real: (B, 3, 64, 64), scaled to [-1, 1]
    B = real.size(0)
    ones, zeros = torch.ones(B, 1), torch.zeros(B, 1)
    fake = G(torch.randn(B, z_dim, 1, 1))

    # 1) Discriminator: real -> 1, fake -> 0 (detach: don't update G here)
    loss_D = bce(D(real), ones) + bce(D(fake.detach()), zeros)
    opt_D.zero_grad(); loss_D.backward(); opt_D.step()

    # 2) Generator: non-saturating loss, wants D(fake) -> 1
    loss_G = bce(D(fake), ones)
    opt_G.zero_grad(); loss_G.backward(); opt_G.step()
    return loss_D.item(), loss_G.item()
DCGAN for 64×64 RGB images in PyTorch, with one training step.

Why GAN training is hard

FailureWhat you seeTypical fixes
Mode collapseG produces only a few near-identical outputs (e.g. the same face) regardless of z.Wasserstein loss, minibatch discrimination / minibatch std, larger batches, lower learning rate.
Vanishing generator gradientD's loss drops to ~0 and stays there; G's samples stop improving.Non-saturating loss, weaken D (fewer steps, dropout, label smoothing), WGAN-GP, spectral normalization.
Oscillation / non-convergenceLosses swing wildly; sample quality goes up and down between checkpoints.Lower learning rates, Adam β₁ = 0 or 0.5, two time-scale learning rates (TTUR), EMA of G's weights.
ArtifactsCheckerboard patterns, blob or 'droplet' artifacts.Resize-then-convolve upsampling instead of transposed conv; StyleGAN2's weight demodulation.
✓
GAN losses don't tell you much
Unlike ordinary training, a GAN's loss curves do not steadily go down: each network's loss depends on the other's skill. Monitor fixed-z sample grids every few hundred steps and compute FID on checkpoints instead of trusting the loss.
knobLearning rate (G and D)
What it is
Step size of each network's optimizer. G and D may use different values (the two time-scale update rule, TTUR[5]).
↑ If you increase it
Faster progress at first, but the game oscillates or explodes; mode collapse becomes more likely.
↓ If you decrease it
More stable but slow; if D's rate is much lower than G's, G can exploit a weak critic and produce artifacts.
Typical values
1e-4 to 2e-4 with Adam (DCGAN: 2e-4 for both). TTUR setups often give D a larger rate than G, e.g. D = 4e-4, G = 1e-4.
knobAdam β₁
What it is
The momentum coefficient of Adam: how much past gradients influence the current step.
↑ If you increase it
At the usual 0.9, momentum carries each network past the moving target set by the other, causing oscillations.
↓ If you decrease it
0.5 or even 0.0 lets each network react quickly to its opponent's latest state; more noise in each update.
Typical values
0.5 (DCGAN), 0.0 (WGAN-GP, StyleGAN); β₂ = 0.9–0.999.
knobz dimension
What it is
Length of the random input vector z fed to the generator.
↑ If you increase it
More room to express variation; beyond a point it adds little, because the generator only uses as many directions as the data needs.
↓ If you decrease it
Too few dimensions limit diversity and can encourage mode collapse.
Typical values
100 (DCGAN), 128 (BigGAN), 512 (StyleGAN).
knobn_critic (D steps per G step)
What it is
How many discriminator/critic updates you do before each generator update.
↑ If you increase it
The critic is closer to optimal, so its gradients are more informative; needed for WGAN-style critics. Too many with a standard GAN loss and D wins outright, starving G of gradient.
↓ If you decrease it
Faster wall-clock training; with Wasserstein losses the critic may be too inaccurate to guide G.
Typical values
1 for standard/non-saturating GANs; 5 for WGAN and WGAN-GP.

Conditional GANs and image-to-image translation

Feed extra information y (a class label, a sketch, a segmentation map) to both G and D and you get a conditional GAN that models p(x | y) (Mirza & Osindero, 2014). pix2pix (Isola et al., 2016) learns paired translations such as edges → photo or day → night with a U-Net generator plus an L1 loss. CycleGAN (Zhu et al., 2017) handles unpaired data (horses ↔ zebras) by requiring that translating there and back returns the original image (cycle consistency).

StyleGAN: control through style

StyleGAN (Karras et al., 2018)[3] redesigned the generator. A mapping network (an 8-layer MLP) turns z into an intermediate code w that is less entangled. The synthesis network starts from a learned constant 4×4 tensor and, at every resolution, injects w through AdaIN (adaptive instance normalization), plus per-pixel noise for stochastic details like hair strands and freckles. Feeding different w's to coarse vs. fine layers ('style mixing') lets you take pose from one face and colours from another. StyleGAN2 later replaced AdaIN with weight demodulation to remove droplet artifacts.

AdaIN(xᵢ, w) = y_{s,i} · (xᵢ − μ(xᵢ)) / σ(xᵢ) + y_{b,i} (y_s, y_b) = A(w)
Each feature map xᵢ is normalized, then rescaled and shifted by a 'style' computed from w through a learned affine layer A.
In words: Normalize each feature channel to mean 0 and standard deviation 1 (erasing its old 'style'), then give it a new scale and offset computed from the style code w. A different w gives different contrast, colour and texture statistics in that layer while the spatial pattern stays.
Symbols(hover a symbol in the formula)
AdaIN
adaptive instance normalization
xᵢ
the i-th feature map (channel) of one image: an H × W grid of activations
w
the intermediate 'style' vector from the mapping network (512-d in StyleGAN)
μ(xᵢ)
mean of channel i over its spatial positions
σ(xᵢ)
standard deviation of channel i over its spatial positions
y_{s,i}
style scale for channel i
y_{b,i}
style bias (shift) for channel i
A(w)
a learned affine (linear) layer that turns w into the scale and bias vectors (y_s, y_b)
▸Worked example
One channel with 4 activations: xᵢ = (2, 4, 6, 8) μ = 5, σ = √((9 + 1 + 1 + 9)/4) = √5 = 2.236 Normalized: (−1.342, −0.447, 0.447, 1.342) Style from A(w): y_s = 2, y_b = 1 AdaIN output: 2 · (−1.342) + 1 = −1.683, then 0.106, 1.894, 3.683 Another w with y_s = 0.5, y_b = 0 would give a low-contrast version of the same pattern.
knobTruncation ψ (psi)
What it is
At sampling time, pull each code towards the average: w′ = w̄ + ψ · (w − w̄).
↑ If you increase it
ψ → 1: full diversity, including unusual and sometimes broken samples (odd backgrounds, artifacts).
↓ If you decrease it
ψ → 0: every sample approaches the 'average face': very clean but boring and repetitive. It is the GAN analogue of a high guidance scale in diffusion: quality up, diversity down.
Typical values
0.5–0.7 for showcase images; 1.0 when measuring FID.

Measuring GANs: FID

The Fréchet Inception Distance (Heusel et al., 2017)[5] embeds thousands of real and generated images with an Inception-v3 network, fits a Gaussian to each set of 2048-d features, and measures the distance between the two Gaussians. Lower is better; mode collapse raises FID because the generated covariance shrinks.

FID = ‖μ_r − μ_g‖² + Tr( Σ_r + Σ_g − 2 (Σ_r Σ_g)^½ )
μ, Σ: mean and covariance of Inception features for real (r) and generated (g) images.
In words: Run real and generated images through an Inception network, fit a Gaussian (mean and covariance) to each set of 2048-d features, and measure the distance between the two Gaussians. The first term compares the averages, the second the spreads; lower is better and 0 means identical statistics.
Symbols(hover a symbol in the formula)
FID
Fréchet Inception Distance
μ_r
mean Inception feature vector of real images (2048-d)
μ_g
mean feature vector of generated images
‖μ_r − μ_g‖²
squared Euclidean distance between the two means
Tr
trace: the sum of a matrix's diagonal entries
Σ_r
covariance matrix of the real features (2048 × 2048)
Σ_g
covariance matrix of the generated features
(Σ_r Σ_g)^½
matrix square root of the product of the two covariances
▸Worked example
2-D toy features with diagonal covariances: μ_r = (0, 0), μ_g = (1, 2) → ‖μ_r − μ_g‖² = 1² + 2² = 5 Σ_r = diag(1, 4), Σ_g = diag(1, 1) → (Σ_r Σ_g)^½ = diag(√1, √4) = diag(1, 2) Tr(Σ_r + Σ_g − 2(Σ_r Σ_g)^½) = (1 + 1 − 2 · 1) + (4 + 1 − 2 · 2) = 0 + 1 = 1 FID = 5 + 1 = 6 Identical statistics give FID = 0; strong face generators reach single digits.
!
Common pitfalls
Forgetting `.detach()` on fakes during the D update (G gets updated by D's loss). Mismatched value ranges: tanh outputs are in [−1, 1], so real images must be scaled the same way. Comparing FID across setups: FID depends on sample count (use 50k), resizing and the exact Inception weights, so only compare numbers computed the same way. Declaring victory from one pretty grid: check diversity with many random seeds.
▸Go deeper: Wasserstein GANs and gradient penalty

When the real and generated distributions barely overlap (typical early on, since images live on thin manifolds), the JS divergence is constant and gives no useful gradient. Arjovsky et al.[4] proposed the Wasserstein-1 (earth mover's) distance instead, which still measures 'how far' the distributions are when they don't overlap. The discriminator becomes a critic that outputs an unbounded score and must be 1-Lipschitz. The original WGAN enforced this by clipping weights; WGAN-GP (Gulrajani et al.)[6] adds a gradient penalty instead, and spectral normalization (Miyato et al., 2018) is another popular way to constrain D.

L_critic = E[ D(x̃) ] − E[ D(x) ] + λ · E_{x̂}[ ( ‖∇_{x̂} D(x̂)‖₂ − 1 )² ] λ = 10
WGAN-GP critic loss; x̃ = G(z), x̂ = random interpolation between real and fake samples. The generator minimizes −E[D(G(z))].
In words: The critic wants high scores on real images and low scores on fakes, so it minimizes (fake score − real score); a penalty keeps the length of the critic's gradient close to 1 at points between real and fake samples. That penalty softly enforces the 1-Lipschitz constraint the Wasserstein distance needs.
Symbols(hover a symbol in the formula)
L_critic
the loss the critic minimizes
E
expectation: in practice the average over a batch
D(x̃)
critic score (any real number) on a generated image
x̃
a generated sample, x̃ = G(z)
D(x)
critic score on a real image
λ
lambda: weight of the gradient penalty (10 in the paper)
E_{x̂}
average over interpolated points
x̂
a random point on the straight line between a real and a fake sample
‖∇_{x̂} D(x̂)‖₂
length (L2 norm) of the critic's gradient with respect to its input at x̂
▸Worked example
Batch averages: E[D(x̃)] = −0.4 (fakes), E[D(x)] = 1.2 (reals) Gradient lengths at two interpolated points: 1.3 and 0.8 Penalty: ((1.3 − 1)² + (0.8 − 1)²)/2 = (0.09 + 0.04)/2 = 0.065 L_critic = −0.4 − 1.2 + 10 · 0.065 = −1.6 + 0.65 = −0.95 With gradient lengths exactly 1 the penalty is 0 and the critic is free to widen the real–fake score gap.

Why diffusion took over: GANs optimize a moving adversarial target and tend to drop modes; diffusion models optimize a simple regression loss that covers the whole distribution. Dhariwal & Nichol showed in 2021 that diffusion models beat the best GANs on ImageNet FID (arXiv 2105.05233).

Quiz

1.
In a GAN, what does the generator receive as a training signal?
2.
Your GAN outputs the same face for every z. What is this called, and what is a reasonable fix?
3.
Why do practitioners use the 'non-saturating' generator loss (maximize log D(G(z)))?
4.
In StyleGAN, what happens if you lower the truncation ψ from 1.0 to 0.3?
5.
Which statement about FID is correct?
Score: 0/5

References

  1. [1]
    Generative Adversarial Networks
    PaperGoodfellow et al.2014arxiv.org
  2. [2]
    Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks (DCGAN)
    PaperRadford et al.2015arxiv.org
  3. [3]
    A Style-Based Generator Architecture for Generative Adversarial Networks (StyleGAN)
    PaperKarras et al.2018arxiv.org
  4. [4]
    Wasserstein GAN
    PaperArjovsky et al.2017arxiv.org
  5. [5]
    GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium (FID, TTUR)
    PaperHeusel et al.2017arxiv.org
  6. [6]
    Improved Training of Wasserstein GANs (WGAN-GP)
    PaperGulrajani et al.2017arxiv.org
← Previous
Generative Models: The Big Picture
Next →
Diffusion Models: From Noise to Image