Repository navigation
Module 19
⬅️ Module 18 · 🗺️ Curriculum · 🏠 Home · Module 20 ➡️
Level: Advanced · Prerequisites: Modules 03, 08, 11 · Time: about 9–10 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
A generative adversarial network (GAN) trains two networks against each other: a generator
After this module you should be able to:
- write the minimax objective and derive the optimal discriminator and the Jensen–Shannon connection;
- explain the non-saturating generator loss, vanishing gradients and mode collapse;
- explain why the Wasserstein distance helps and derive WGAN/WGAN-GP;
- describe stabilisation tricks and conditional/architectural variants, and evaluate GANs (FID, IS).
Picture a forger (generator) and a detective (discriminator). The detective learns to spot fakes; the forger uses the detective's feedback to make better fakes; at equilibrium the fakes are indistinguishable and the detective can only guess (output
flowchart LR
Z["Noise z ~ N(0,I)"] --> G["Generator G"] --> F["Fake sample G(z)"]
R["Real data x"] --> D["Discriminator D"]
F --> D
D --> P["P(real)"]
P -- "update D: tell real from fake" --> D
P -- "update G: fool D" --> G
For a fixed
Substituting,
The global minimum is

Figure 19.1 — For figures/make_figs_2.py).
Early in training
The Earth-Mover/Wasserstein-1 distance
so WGAN trains a critic
Spectral normalisation (Miyato et al. 2018) constrains each layer's largest singular value to 1 (Module 01).
DCGAN guidelines (Radford et al. 2016): strided/transposed convolutions instead of pooling, BatchNorm in
cGAN (Mirza & Osindero 2014) feeds labels/conditions to
Inception Score
At a point where
JS for disjoint supports:
Rotation of simultaneous GDA on
import torch, torch.nn as nn, torch.nn.functional as F
def d_loss(D, G, x, z): # standard GAN discriminator loss
fake = G(z).detach()
return F.binary_cross_entropy_with_logits(D(x), torch.ones(len(x), 1)) + \
F.binary_cross_entropy_with_logits(D(fake), torch.zeros(len(x), 1))
def g_loss_nonsat(D, G, z): # maximise log D(G(z))
return F.binary_cross_entropy_with_logits(D(G(z)), torch.ones(len(z), 1))
def gradient_penalty(critic, real, fake, lam=10.0): # WGAN-GP
eps = torch.rand(real.size(0), 1, 1, 1, device=real.device)
xh = (eps * real + (1 - eps) * fake).requires_grad_(True)
g, = torch.autograd.grad(critic(xh).sum(), xh, create_graph=True)
return lam * ((g.flatten(1).norm(dim=1) - 1) ** 2).mean()Optimiser: Adam(lr=2e-4, betas=(0.5, 0.999)) is the DCGAN default; WGAN-GP typically uses
-
$f$ -GAN generalises GANs to any$f$ -divergence; LSGAN, hinge and relativistic losses. - Game-theoretic dynamics: local convergence conditions, optimistic/extragradient methods, consensus optimisation (Mescheder et al. 2017/2018).
- Implicit models & likelihood-free inference: GANs give no density; diffusion and VAEs trade sample sharpness vs coverage differently (Module 20).
- Inversion and editing: projecting real images into StyleGAN latent space (GAN inversion), latent-direction editing.
- Why diffusion largely overtook GANs: more stable training, better mode coverage, easier scaling and conditioning; GANs remain fast one-step samplers and are used as adversarial losses in decoders and distillation.
- Ethics: deepfakes, provenance and watermarking (Module 24).
- A perfectly trained
$D$ is bad for$G$ (no gradient); balance training. - Detaching incorrectly (fake samples must be detached for the
$D$ step). - Reading discriminator loss as quality; use FID/inspection.
- BatchNorm in WGAN-GP critics (breaks per-sample gradient penalty); use LayerNorm or none.
- Reporting FID with different sample counts/preprocessing.
Q1. Derive the optimal discriminator.
Show answer
Maximise
Q2. What does the generator minimise when
Show answer
Q3. Why use the non-saturating generator loss?
Show answer
Q4. What is mode collapse?
Show answer
The generator outputs only a few distinct modes of the data distribution, losing diversity because it only needs to fool the current discriminator.
Q5. Why does the Wasserstein distance help?
Show answer
It remains continuous and has useful gradients even when distributions have disjoint support, and the critic loss correlates with sample quality.
Q6. How does the gradient penalty enforce Lipschitzness?
Show answer
It penalises deviations of
Q7. Why might GAN training oscillate rather than converge?
Show answer
It is a game, not minimisation; simultaneous gradient dynamics can rotate around equilibria (as on
Q8. What does FID measure and what are its weaknesses?
Show answer
Distance between Gaussian fits of Inception features of real and generated data; it is sensitive to sample size, feature extractor and assumes Gaussianity.
- Goodfellow, I., et al. (2014). Generative adversarial nets. NeurIPS. arXiv:1406.2661.
- Radford, A., Metz, L., & Chintala, S. (2016). Unsupervised representation learning with deep convolutional GANs. ICLR. arXiv:1511.06434.
- Arjovsky, M., & Bottou, L. (2017). Towards principled methods for training GANs. ICLR. arXiv:1701.04862.
- Arjovsky, M., Chintala, S., & Bottou, L. (2017). Wasserstein GAN. ICML. arXiv:1701.07875.
- Gulrajani, I., et al. (2017). Improved training of Wasserstein GANs. NeurIPS. arXiv:1704.00028.
- Miyato, T., et al. (2018). Spectral normalization for GANs. ICLR. arXiv:1802.05957.
- Mescheder, L., Geiger, A., & Nowozin, S. (2018). Which training methods for GANs do actually converge? ICML.
- Mirza, M., & Osindero, S. (2014). Conditional generative adversarial nets. arXiv:1411.1784.
- Karras, T., Laine, S., & Aila, T. (2019). A style-based generator architecture for GANs. CVPR. arXiv:1812.04948.
- Salimans, T., et al. (2016). Improved techniques for training GANs. NeurIPS.
- Heusel, M., et al. (2017). GANs trained by a two time-scale update rule converge to a local Nash equilibrium. NeurIPS. arXiv:1706.08500.
- Zhu, J.-Y., et al. (2017). Unpaired image-to-image translation using cycle-consistent adversarial networks. ICCV. Isola, P., et al. (2017). Image-to-image translation with conditional adversarial networks. CVPR.
⬅️ Module 18 · 🗺️ Curriculum · 🏠 Home · Module 20 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24