Skip to content

Module 19

Anurag Prasad edited this page Nov 9, 2026 · 8 revisions

Module 19 — Generative Adversarial Networks and Variants

⬅️ 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


Overview and learning goals

A generative adversarial network (GAN) trains two networks against each other: a generator $G$ turns noise into samples, and a discriminator $D$ tries to tell real from generated. Without ever writing down a likelihood, the generator learns to produce samples that the discriminator cannot distinguish from data. GANs gave the first photorealistic image synthesis; they are also notoriously hard to train, which motivated a rich theory of divergences and stabilisation techniques.

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).

Beginner: the big picture

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 $\frac12$).

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
Loading

Core concepts and derivations

Generator, discriminator and the minimax objective

$$ \min_G\max_D\ V(D,G)=\mathbb{E}_{\mathbf{x}\sim p_{data}}\bigl[\ln D(\mathbf{x})\bigr]+\mathbb{E}_{\mathbf{z}\sim p_z}\bigl[\ln\bigl(1-D(G(\mathbf{z}))\bigr)\bigr]. $$

$D$ is a binary classifier (cross-entropy); $G$ is trained to make $D$ misclassify its outputs. Training alternates gradient steps on $D$ and $G$.

Optimal discriminator and Jensen–Shannon divergence

For a fixed $G$ with induced distribution $p_g$, $V=\int\bigl[p_{data}(x)\ln D(x)+p_g(x)\ln(1-D(x))\bigr]dx$. Pointwise, $a\ln y+b\ln(1-y)$ is maximised at $y=\frac a{a+b}$, so

$$ D^\star(x)=\frac{p_{data}(x)}{p_{data}(x)+p_g(x)} . $$

Substituting,

$$ V(D^\star,G)=-\ln4+D_{KL}\Bigl(p_{data}\Big\Vert\frac{p_{data}+p_g}2\Bigr)+D_{KL}\Bigl(p_g\Big\Vert\frac{p_{data}+p_g}2\Bigr)=-\ln4+2,\mathrm{JS}(p_{data}\Vert p_g). $$

The global minimum is $-\ln4$, attained iff $p_g=p_{data}$ (where $D^\star\equiv\frac12$). (Goodfellow et al. 2014.)

Optimal discriminator between two 1-D Gaussians

Figure 19.1 — For $p_{data}=\mathcal{N}(0,1)$ and $p_g=\mathcal{N}(2.5,1.4^2)$ the optimal discriminator (dashed) is high where data dominate and falls to 0 where only the generator has mass. Original figure (figures/make_figs_2.py).

Non-saturating generator loss and vanishing gradients

Early in training $D$ easily rejects fakes, $D(G(z))\approx0$, and $\ln(1-D(G(z)))$ is flat (saturated) with vanishing gradient. The practical fix: $G$ maximises $\ln D(G(\mathbf{z}))$ instead — same fixed point, much stronger gradients early. A deeper problem (Arjovsky & Bottou 2017): if $p_{data}$ and $p_g$ lie on low-dimensional manifolds with (almost surely) disjoint support, $\mathrm{JS}=\ln2$ is constant and a perfect $D$ gives no useful gradient.

Mode collapse and instability

$G$ may map all noise to a few outputs that fool the current $D$ (mode collapse); $D$ then adapts and $G$ jumps to another mode — oscillation. Simultaneous gradient dynamics on a minimax game need not converge: for $V=xy$ gradient descent–ascent rotates around the saddle (or spirals outward). Remedies: minibatch discrimination, unrolled GANs, regularisers, better divergences.

Wasserstein GAN and gradient penalty

The Earth-Mover/Wasserstein-1 distance $W_1(p,q)=\inf_{\gamma}\mathbb{E}_{(x,y)\sim\gamma}\lVert x-y\rVert$ stays meaningful (and has gradients) even for disjoint supports. By Kantorovich–Rubinstein duality,

$$ W_1(p_{data},p_g)=\sup_{\lVert f\rVert_L\le1}\ \mathbb{E}_{p_{data}}[f(x)]-\mathbb{E}_{p_g}[f(x)], $$

so WGAN trains a critic $f_w$ (no sigmoid, no log) restricted to 1-Lipschitz functions; Arjovsky et al. (2017) enforced this by weight clipping (crude). WGAN-GP (Gulrajani et al. 2017) penalises the critic's gradient norm at interpolates $\hat x=\epsilon x+(1-\epsilon)\tilde x$:

$$ L_{critic}=\mathbb{E}_{\tilde x\sim p_g}[f(\tilde x)]-\mathbb{E}_{x\sim p_{data}}[f(x)]+\lambda,\mathbb{E}_{\hat x}\bigl[(\lVert\nabla_{\hat x}f(\hat x)\rVert_2-1)^2\bigr],\quad\lambda=10 . $$

Spectral normalisation (Miyato et al. 2018) constrains each layer's largest singular value to 1 (Module 01).

Stabilisation techniques

DCGAN guidelines (Radford et al. 2016): strided/transposed convolutions instead of pooling, BatchNorm in $G$ and $D$ (not at $G$ output/$D$ input), ReLU in $G$ with Tanh output, LeakyReLU in $D$. Plus: label smoothing, instance noise, two-timescale update rule (TTUR, different learning rates), Adam with $\beta_1=0.5$, historical averaging, EMA of generator weights, R1 gradient penalty (Mescheder et al. 2018), progressive growing.

Conditional and image-to-image GANs

cGAN (Mirza & Osindero 2014) feeds labels/conditions to $G$ and $D$. Pix2pix and CycleGAN translate images (paired / unpaired via cycle-consistency); StyleGAN (Karras et al. 2019) controls style at each resolution through a mapping network and adaptive normalisation; BigGAN scales class-conditional synthesis.

Evaluation

Inception Score $\exp(\mathbb{E}x D{KL}(p(y|x)\Vert p(y)))$ rewards confident, diverse class predictions. FID (Heusel et al. 2017) fits Gaussians to Inception features of real and generated images: $\mathrm{FID}=\lVert\mu_r-\mu_g\rVert^2+\mathrm{tr}\bigl(\Sigma_r+\Sigma_g-2(\Sigma_r\Sigma_g)^{1/2}\bigr)$ (lower is better). Also precision/recall for fidelity vs coverage, and human evaluation.

Worked example

At a point where $p_{data}(x)=0.3$ and $p_g(x)=0.1$, $D^\star(x)=0.3/0.4=0.75$.

JS for disjoint supports: $p=\delta_0$, $q=\delta_\theta$ ($\theta\ne0$): $\mathrm{JS}=\ln2$ for every $\theta\ne0$ (no gradient), while $W_1=\lvert\theta\rvert$ decreases smoothly as $\theta\to0$.

Rotation of simultaneous GDA on $V=xy$ ($x$ minimises, $y$ maximises): $\dot x=-y$, $\dot y=x$ — circles around the saddle $(0,0)$, no convergence. Discrete steps with learning rate $\eta$ spiral outward: $\lVert(x,y)\rVert^2$ grows by $(1+\eta^2)$ per step.

Implementation

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 $\beta_1=0$–$0.5$ and 5 critic steps per generator step.

Advanced topics

  • $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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

Q1. Derive the optimal discriminator.

Maximise $p_{data}\ln D+p_g\ln(1-D)$ pointwise: setting the derivative $\frac{p_{data}}{D}-\frac{p_g}{1-D}=0$ gives $D^\star=p_{data}/(p_{data}+p_g)$.

Q2. What does the generator minimise when $D$ is optimal?

$2,\mathrm{JS}(p_{data}\Vert p_g)-\ln4$; zero JS iff the distributions match.

Q3. Why use the non-saturating generator loss?

$\ln(1-D(G(z)))$ has tiny gradient when $D$ confidently rejects fakes; maximising $\ln D(G(z))$ provides strong gradients while keeping the same optimum.

Q4. What is mode collapse?

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?

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?

It penalises deviations of $\lVert\nabla_{\hat x}f(\hat x)\rVert$ from 1 at points between real and fake samples, softly enforcing the 1-Lipschitz constraint required by the duality.

Q7. Why might GAN training oscillate rather than converge?

It is a game, not minimisation; simultaneous gradient dynamics can rotate around equilibria (as on $V=xy$), requiring regularisation or extragradient-type updates.

Q8. What does FID measure and what are its weaknesses?

Distance between Gaussian fits of Inception features of real and generated data; it is sensitive to sample size, feature extractor and assumes Gaussianity.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally