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.
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 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
- 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
- Sample a minibatch of real images x and a minibatch of noise vectors z.
- Update D: push D(x) towards 1 and D(G(z)) towards 0 (binary Cross-entropy (log loss)).
- Update G: change G so that D(G(z)) moves towards 1, using gradients that flow back through the (frozen for this step) discriminator.
- Repeat. Neither network ever sees a 'correct output'; G only learns through D's feedback.
- 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
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).
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()Why GAN training is hard
| Failure | What you see | Typical fixes |
|---|---|---|
| Mode collapse | G 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 gradient | D'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-convergence | Losses 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. |
| Artifacts | Checkerboard patterns, blob or 'droplet' artifacts. | Resize-then-convolve upsampling instead of transposed conv; StyleGAN2's weight demodulation. |
- 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.
- 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.
- 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).
- 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
- 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
- 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
- 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
▸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
- 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
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
References
- [1]Generative Adversarial NetworksPaperGoodfellow et al.2014arxiv.org
- [2]Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks (DCGAN)PaperRadford et al.2015arxiv.org
- [3]A Style-Based Generator Architecture for Generative Adversarial Networks (StyleGAN)PaperKarras et al.2018arxiv.org
- [4]Wasserstein GANPaperArjovsky et al.2017arxiv.org
- [5]GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium (FID, TTUR)PaperHeusel et al.2017arxiv.org
- [6]Improved Training of Wasserstein GANs (WGAN-GP)PaperGulrajani et al.2017arxiv.org