Generative Models
GANs Deep Dive - Mastering Generative Adversarial Networks
GANs revolutionized generative modeling by pitting two neural networks against each other in a minimax game. The generator creates realistic samples while the discriminator tries to tell real from fake, driving both to improve until generated data is indistinguishable from reality.
- Key point 1 - Minimax game converges when generator matches data distribution (Nash equilibrium)
- Key point 2 - DCGAN, WGAN, and StyleGAN each solve different training challenges
- Key point 3 - FID score is the standard metric for evaluating generation quality
"In the battle between generator and discriminator, everyone wins."
GANs Deep Dive - Generative Adversarial Networks
What You'll Learn
- 1Derive the minimax objective and prove where the global optimum sits
- 2Compute the optimal discriminator and the Nash equilibrium value of the game
- 3Explain why the saturating generator loss fails and how the non-saturating loss fixes it
- 4Stabilize GAN training with DCGAN rules, WGAN-GP, and monitor quality with FID
GANs learn to generate realistic data by pitting two neural networks against each other in a minimax game: a generator creates fake samples, and a discriminator tries to distinguish real from fake.
The GAN Framework
How this diagram works: This diagram illustrates the adversarial game at the heart of GANs. The generator (green, left) takes random noise and produces fake data , attempting to mimic real data. The discriminator (red, right) receives both real data and fake samples , and outputs a probability indicating whether each input is real or generated. The dashed feedback arrows show the competing objectives: the generator loss pushes to fool (making ), while the discriminator loss pushes to correctly classify both real and fake inputs. Training reaches Nash equilibrium when the generator perfectly matches the real data distribution () and the discriminator can no longer tell them apart, outputting for all inputs.
Nash Equilibrium
The value of the game at that point is , and it splits into a constant plus the Jensen-Shannon divergence between the two distributions:
Jensen-Shannon divergence is non-negative and equals zero only when the two distributions coincide, so the generator is pushed hardest while is still far from :
Training Challenges
The saturating generator objective dies as soon as the discriminator becomes confident, so practice maximizes the non-saturating form instead. Both objectives share the same global optimum:
The gradient of the saturating form vanishes exactly when the generator is losing, which is the opposite of what training needs:
DCGAN (Deep Convolutional GAN)
With four 4x4 kernels at stride 2 and padding 1 each block doubles the resolution, which is the DCGAN ladder used in the implementation below:
Starting from a noise vector the generator climbs 4 -> 8 -> 16 -> 32 -> 64 pixels with no pooling layer anywhere.
WGAN (Wasserstein GAN)
Kantorovich-Rubinstein duality replaces the infimum over couplings with a supremum over 1-Lipschitz critics, which is exactly what a clipped or gradient-penalized network approximates:
StyleGAN
PyTorch Implementation
Training Tips
Measuring quality with FID
FID fits a Gaussian to the Inception pool3 features of the real and generated sets and reports the Frechet distance between them:
For CIFAR-10 a strong model sits near 2-3 while a collapsed one jumps past 40. Compute it on 50,000 samples with the same resize pipeline every run, because FID drifts by several points when the sample count or preprocessing changes.
Practice Exercises
-
Train DCGAN on CIFAR-10: Generate realistic images. Monitor FID over training.
-
WGAN-GP implementation: Replace BCE loss with Wasserstein loss + gradient penalty. Compare training stability.
-
Mode collapse experiment: Train a GAN on MNIST and observe mode collapse. Fix it with minibatch discrimination.
-
Style mixing: Implement StyleGAN and experiment with style mixing at different layers.
What to Learn Next
-> Variational Autoencoders Learn probabilistic latent representations with encoder-decoder architectures.
-> Diffusion Models Deep Dive Explore the math behind gradual noising and denoising for image generation.
-> Self-Supervised Learning Learn useful representations from unlabeled data without manual annotation.
-> DL Systems Design Master distributed training, monitoring, and production deployment of deep learning models.
-> Model Compression Make deep learning models fast and efficient for production deployment.
-> Graph Neural Networks Learn from graph-structured data with message passing and attention mechanisms.
Common Mistakes
Training with the saturating generator loss log(1 - D(G(z)))
Fix: Switch to the non-saturating loss -log D(G(z)), which keeps gradients large while D is winning
Letting the discriminator overpower the generator
Fix: Update D less often with TTUR, use 0.9 label smoothing, and add spectral normalization to D
Quoting FID from a few hundred samples
Fix: Score 50,000 samples against fixed feature statistics so runs stay comparable
Best Practices
- Follow the DCGAN rules: strided convolutions instead of pooling, batch norm in G, LeakyReLU in D, no fully connected layers
- Start with Adam at lr = 2e-4 and betas = (0.5, 0.999), then move to WGAN-GP with lambda = 10 when the loss oscillates
- Log FID every epoch on a fixed sample draw, and keep checkpoints with a fixed seed so a regression can be reproduced
Key Takeaways
- The game is min_G max_D V(D,G) = E[log D(x)] + E[log(1 - D(G(z)))], whose global optimum sits at p_G = p_data with V = -log 4
- The optimal discriminator D*(x) = p_data(x) / (p_data(x) + p_G(x)) collapses to 0.5 on every input at equilibrium
- The non-saturating loss -E[log D(G(z))] replaces log(1 - D(G(z))) so gradients survive once D gets confident
- WGAN-GP trades weight clipping for a gradient penalty, and FID measured on 50,000 samples is the metric to watch
Frequently Asked Questions
Why does a GAN collapse to a single output?
Mode collapse happens when the generator finds one sample that reliably fools the discriminator and stops exploring, because the discriminator only rewards that one region of latent space, so every maps to the same . Watch for it by tracking the diversity of embeddings across a fixed noise batch, and fix it with minibatch discrimination, an unrolled discriminator, or the Wasserstein objective, all of which penalize a generator that ignores most of .
What does the discriminator actually converge to?
Bayes' rule gives the optimal discriminator in closed form, . Substituting it into the value function yields , and only when does output 0.5 everywhere. That is the Nash equilibrium: neither network can improve by changing its strategy alone.
Is FID enough to judge a generator?
FID compresses images into 2048-dimensional Inception features, fits a Gaussian to each set, and reports the Frechet distance, so it captures quality and diversity in one number. It is sensitive to sample count, resizing, and feature extractor version, so always pair it with a fixed protocol and, where possible, a precision and recall metric that separates fidelity from coverage.
Interview Questions
Q1: Why does the original minimax loss stall in practice?
Once D reaches 1, the gradient of log(1 - D(G(z))) is proportional to 1 - D(G(z)) and collapses toward zero, so G stops learning exactly when it is losing. The non-saturating surrogate -log D(G(z)) keeps a gradient proportional to D's mistake and shares the same global optimum.
Q2: How does WGAN change the training objective?
It replaces the Jensen-Shannon divergence with the Wasserstein-1 distance, computed by a critic constrained to 1-Lipschitz via weight clipping or, better, the penalty lambda times E[(||grad D(x_hat)||_2 - 1)^2] with lambda = 10. The critic loss then stays informative even when the two supports do not overlap.
Q3: Walk me through computing FID for two checkpoints.
Extract Inception pool3 features for 50,000 real and 50,000 generated images, fit Gaussians (mu, Sigma) to each, then FID = ||mu_r - mu_g||^2 + Tr(Sigma_r + Sigma_g - 2(Sigma_r Sigma_g)^(1/2)). Keep sample count and preprocessing identical between runs or the number is not comparable.