Skip to main content
Generative Adversarial Networks - Generator vs Discriminator

Generative Adversarial Networks

The Counterfeiter vs Detective Game

Imagine a world with two players locked in an eternal battle:
  • The Counterfeiter (Generator): Creates fake money, trying to make it indistinguishable from real currency
  • The Detective (Discriminator): Examines bills and tries to identify which are real and which are fake
At first, the counterfeiter is terrible — their fake bills look obviously fake. But with each rejection, they learn and improve. Meanwhile, the detective gets better at spotting fakes, forcing the counterfeiter to up their game. This is exactly how GANs work. The Generator never sees real data directly — it only receives gradient signals from the Discriminator telling it “you’re getting warmer” or “you’re getting colder.” Think of it like learning to paint while blindfolded, where your only feedback is a critic’s score. Over time, the Generator learns to produce outputs so realistic that the Discriminator can’t do better than flipping a coin.
The key mathematical insight: at the Nash equilibrium of this game, the Generator’s output distribution pgp_g exactly matches the real data distribution pdatap_{data}, and the Discriminator outputs D(x)=0.5D(x) = 0.5 for all inputs. In practice, we rarely reach this equilibrium perfectly, which is why GAN training is notoriously finicky.

GAN Architecture Overview

GAN Architecture - Generator and Discriminator
A GAN consists of two neural networks trained simultaneously: The networks compete in a minimax game - the generator tries to fool the discriminator, while the discriminator tries to catch the generator.
Output:

The Minimax Loss Function

The GAN training objective is a minimax game: minGmaxDV(D,G)=Expdata[logD(x)]+Ezpz[log(1D(G(z)))]\min_G \max_D V(D, G) = \mathbb{E}_{x \sim p_{data}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))] Intuition behind the math: The Discriminator is playing a classification game — it wants to output 1 for real samples and 0 for fakes. The logarithm amplifies mistakes: log(D(x))\log(D(x)) punishes D heavily when it assigns low probability to a real sample (e.g., log(0.01)=4.6\log(0.01) = -4.6), but barely rewards it for being right (log(0.99)=0.01\log(0.99) = -0.01). This asymmetric penalty is what drives both networks to improve rapidly.
GAN Minimax Game Visualization
The Discriminator wants to maximize V(D,G)V(D,G):
  • Correctly classify real images → D(x)1D(x) \approx 1
  • Correctly classify fake images → D(G(z))0D(G(z)) \approx 0
The Generator wants to minimize V(D,G)V(D,G):
  • Fool the discriminator → D(G(z))1D(G(z)) \approx 1

Complete GAN Training Loop

Let’s train a GAN on MNIST digits:
Output:

Mode Collapse: The GAN’s Achilles Heel

Mode Collapse in GANs
Mode collapse occurs when the generator produces only a limited variety of outputs, essentially “memorizing” a few samples that fool the discriminator. Think of it this way: if you’re a student trying to pass an exam, and you discover the teacher always accepts the same essay, you’d stop writing anything else. The Generator does the same thing — it finds one “safe” output that consistently gets a high score from the Discriminator, then maps every noise vector to that output (or a small cluster of outputs). The result? A generator that can only produce three types of faces, or always generates the digit “1” regardless of input noise.

Why Does Mode Collapse Happen?


DCGAN: Deep Convolutional GAN

DCGAN Architecture with Convolutions
DCGANs use convolutional layers for better image generation. Key architectural guidelines:
Output:

Wasserstein GAN (WGAN)

Wasserstein Distance vs JS Divergence
WGAN addresses training instability by using the Wasserstein distance (Earth Mover’s Distance) instead of JS divergence.

Why Wasserstein Distance?

The analogy: Imagine you have two piles of sand (the real and generated distributions) and you want to measure how different they are. The Wasserstein distance measures the minimum amount of “work” (mass times distance) needed to reshape one pile into the other. Unlike JS divergence, which jumps between 0 and log2\log 2 when distributions don’t overlap, the Wasserstein distance changes smoothly — giving the generator useful gradient signal even when the discriminator can perfectly separate real from fake. W(Pr,Pg)=infγΠ(Pr,Pg)E(x,y)γ[xy]W(P_r, P_g) = \inf_{\gamma \in \Pi(P_r, P_g)} \mathbb{E}_{(x, y) \sim \gamma}[\|x - y\|]
Training tip: The Wasserstein distance is computed via the Kantorovich-Rubinstein duality, which requires the critic to be 1-Lipschitz (its gradients bounded by 1 everywhere). The original WGAN enforced this with weight clipping, but WGAN-GP (gradient penalty) is strictly better — it doesn’t suffer from capacity underuse or exploding/vanishing weights.

Conditional GANs (cGAN)

Conditional GAN Architecture
Conditional GANs allow us to control what we generate by conditioning on additional information (class labels, text, images). minGmaxDV(D,G)=Expdata[logD(xy)]+Ezpz[log(1D(G(zy)y))]\min_G \max_D V(D, G) = \mathbb{E}_{x \sim p_{data}}[\log D(x|y)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z|y)|y))]

GAN Evaluation Metrics

Evaluating GANs is Hard! Unlike supervised learning, there’s no clear “correct answer” to compare against. The generator loss alone is almost meaningless — it can decrease while image quality gets worse, or increase while images improve. Always use sample-based metrics alongside visual inspection.

Exercises

Label smoothing can stabilize GAN training. Instead of using hard labels (0 and 1), use soft labels (e.g., 0.1 and 0.9).
Implement a training schedule that gradually increases image resolution.
Spectral normalization constrains the Lipschitz constant of discriminator layers.

Key Takeaways

What You Learned:
  • GAN Fundamentals - Generator creates, Discriminator classifies in a minimax game
  • Minimax Loss - Adversarial training objective and its components
  • Mode Collapse - Common failure mode and solutions (minibatch discrimination, feature matching)
  • DCGAN - Convolutional architecture guidelines for stable training
  • WGAN - Wasserstein distance for improved training stability
  • Conditional GANs - Control generation with class labels or other conditioning
  • Evaluation - FID, Inception Score, and diversity metrics

Training Tips from the Trenches

GAN Training Mistakes to Avoid:
  1. Imbalanced training — Don’t let D or G become too strong too quickly. Monitor the ratio of D accuracy on real vs fake: if D accuracy hits 100% early, G will get vanishing gradients. A healthy D accuracy hovers around 60-80%.
  2. Ignoring mode collapse — Monitor sample diversity throughout training. Generate a grid of 64+ images every N epochs and visually inspect. If all outputs look nearly identical, you have mode collapse.
  3. Wrong learning rates — GANs are sensitive; start with the DCGAN defaults (lr=0.0002, betas=(0.5, 0.999)) and only deviate with reason.
  4. Batch size too small — BatchNorm needs sufficient batch size (at least 16, ideally 64+). Small batches cause noisy BN statistics that destabilize training.
  5. Not using proper initialization — DCGAN weight init (Normal(0, 0.02)) matters significantly. Xavier or He init, which work great for classifiers, can cause GAN training to diverge.
Practical training checklist a senior engineer would follow:
  • Start with a known-working architecture (DCGAN or StyleGAN2) before experimenting
  • Log both G and D losses AND generated samples — losses alone are misleading
  • Use torch.no_grad() when generating samples for visualization to avoid memory leaks
  • If training with mixed precision (fp16), keep the discriminator in fp32 — the sigmoid output is numerically sensitive
  • Save checkpoints frequently: GAN training is non-monotonic, and the best checkpoint is often not the last one
  • Use FID on a held-out set as your primary quality metric, not visual inspection alone

Interview Deep-Dive

Strong Answer:
  • The minimax objective is minGmaxDE[logD(x)]+E[log(1D(G(z)))]\min_G \max_D \mathbb{E}[\log D(x)] + \mathbb{E}[\log(1 - D(G(z)))]. The Discriminator maximizes this expression (correctly classifying real and fake), while the Generator minimizes it (fooling D).
  • Vanishing gradient problem: Early in training, the Generator produces obviously fake outputs. The Discriminator quickly learns to reject them with D(G(z))0D(G(z)) \approx 0. The Generator’s gradient comes from log(1D(G(z)))\log(1 - D(G(z))), which is log(10)=log(1)=0\log(1 - 0) = \log(1) = 0 — the gradient is essentially zero. The Generator receives almost no learning signal precisely when it needs the most guidance.
  • Non-saturating fix: Instead of minimizing log(1D(G(z)))\log(1 - D(G(z))), the Generator maximizes log(D(G(z)))\log(D(G(z))). When D(G(z))0D(G(z)) \approx 0, this gives log(0)\log(0) \rightarrow -\infty, producing a very large gradient. The Generator now receives strong signal to improve even when the Discriminator easily rejects its outputs.
  • A senior engineer would note: the non-saturating loss changes the optimization landscape but doesn’t change the theoretical equilibrium point. Both formulations converge to pg=pdatap_g = p_{data} at the Nash equilibrium. The practical difference is entirely about gradient magnitude during early training.
Follow-up: Does the non-saturating loss introduce any new problems?Yes. It can cause training instability through mode-seeking behavior. The original loss is mode-covering (G tries to spread mass over all of pdatap_{data}), while the non-saturating loss is mode-seeking (G concentrates on modes that currently fool D the most). This is one mechanism behind mode collapse. WGAN’s Wasserstein distance addresses both problems simultaneously.
Strong Answer:
  • Mode collapse is when the Generator maps many different noise vectors to a small set of outputs, producing limited diversity. In the extreme case (“complete collapse”), every input produces the same image. Partial collapse is more common: a GAN trained on MNIST might only generate digits 1, 7, and 9, ignoring the other seven classes.
  • Technique 1: Minibatch Discrimination. The Discriminator receives additional features computed across the batch, allowing it to detect when all generated samples look too similar. Trade-off: adds computational overhead and couples predictions within a batch, which complicates distributed training.
  • Technique 2: Wasserstein loss (WGAN-GP). By replacing the JS divergence with the Wasserstein distance, the critic provides meaningful gradients even when distributions don’t overlap, reducing the “shortcut incentive” that causes collapse. Trade-off: requires training the critic for multiple steps per generator step (typically 5), increasing wall-clock time by 3-5x. Also requires removing BatchNorm from the critic when using gradient penalty.
  • Technique 3: Unrolled GANs. The Generator anticipates future Discriminator updates by unrolling K steps of D’s optimization. This prevents G from over-exploiting D’s current weaknesses. Trade-off: memory-intensive (must store K computation graphs) and adds significant complexity. Rarely used in production — more of a research technique.
  • A senior engineer would add: in practice, monitoring for mode collapse matters more than any single technique. Track the diversity of generated samples using FID, the number of distinct modes in generated class distributions, or simply visual inspection grids. If collapse is detected, the most pragmatic fix is often reducing the learning rate of G relative to D, or switching to a progressive training schedule.
Strong Answer:
  • Original GAN loss (BCE): Simple to implement, works well with DCGAN architecture and careful hyperparameter tuning. Choose this when you want a quick prototype and your dataset is well-behaved (balanced, sufficient data). The main risk is training instability and mode collapse.
  • WGAN-GP: Uses the Wasserstein distance approximated via a gradient penalty on the critic. The critic loss directly correlates with sample quality (unlike BCE loss), making it a useful training diagnostic. Choose WGAN-GP when training stability is paramount or when the original GAN loss diverges. The cost is 3-5x slower training due to multiple critic updates per generator step, plus the gradient penalty computation doubles backward-pass cost.
  • Spectral Normalization (SN-GAN): Constrains the Lipschitz constant of the Discriminator by normalizing each weight matrix by its spectral norm (largest singular value). Unlike WGAN-GP, it requires only one D update per G update and adds negligible computational overhead (one power iteration step per forward pass). Choose SN when you want WGAN-level stability without the training cost. In practice, SN-GAN has become the default for many architectures including BigGAN and StyleGAN.
  • Decision framework: for production image generation, start with SN-GAN. If quality plateaus, try WGAN-GP. Only fall back to vanilla BCE loss for simple datasets (MNIST, CIFAR) where you know the hyperparameters work. For large-scale generation (ImageNet, faces), modern architectures like StyleGAN2 use a combination of SN plus R1 gradient penalty, which is another flavor of the same Lipschitz-constraint idea.
Strong Answer:
  • Inception Score (IS): measures two things: (1) quality — high-quality images should have confident, peaked class predictions p(yx)p(y|x), and (2) diversity — the marginal distribution p(y)=p(yx)pg(x)dxp(y) = \int p(y|x)p_g(x)dx should be uniform across all classes. IS = exp(E[DKL(p(yx)p(y))])\exp(\mathbb{E}[D_{KL}(p(y|x) \| p(y))]). Higher is better.
  • IS limitations: it uses InceptionV3 trained on ImageNet, so it’s biased toward ImageNet-like images. A GAN generating perfect medical images would get a low IS. It also can’t detect intra-class mode collapse (generating only one type of dog still gets high IS if different breeds are represented). And critically, IS doesn’t compare against real data at all — a GAN could generate images from a completely different distribution and still get high IS.
  • Frechet Inception Distance (FID): computes the Frechet distance between two multivariate Gaussians fitted to InceptionV3 features of real and generated images: FID=μrμg2+Tr(Σr+Σg2(ΣrΣg)1/2)FID = \|\mu_r - \mu_g\|^2 + \text{Tr}(\Sigma_r + \Sigma_g - 2(\Sigma_r\Sigma_g)^{1/2}). Lower is better. FID captures both quality and diversity and compares against the actual data distribution.
  • FID limitations: assumes Gaussian feature distributions (which is a rough approximation), sensitive to sample size (need at least 10,000 samples for reliable estimates, ideally 50,000), and still depends on InceptionV3 features. For domains far from natural images, consider domain-specific metrics or Kernel Inception Distance (KID), which has an unbiased estimator and is less sensitive to sample size.
  • A senior engineer would add: never rely on a single metric. Use FID as the primary quantitative measure, but always supplement with visual inspection (grid plots), precision/recall curves (to separate quality from diversity failures), and domain-specific metrics where applicable.
Strong Answer:
  • Architecture choice: StyleGAN2 or StyleGAN3 as the backbone. These architectures produce the highest-quality images for structured objects and offer fine-grained control via the style-based generator. The mapping network transforms the latent code zz into an intermediate space ww, which controls different aspects of the image at different resolutions (coarse features like shape at low resolutions, fine details like texture at high resolutions).
  • Data pipeline: collect at least 50,000 product images per category (shoes, bags, electronics). Clean the dataset rigorously — remove duplicates, watermarks, and low-quality images. Apply standardized backgrounds (white or transparent). Resize to a consistent resolution (512x512 or 1024x1024). Augment with horizontal flips only (not rotations — product orientation matters).
  • Training strategy: progressive growing is unnecessary for StyleGAN2+ (the architecture handles it internally). Train with R1 gradient penalty (γ=10\gamma = 10), non-saturating logistic loss, and path length regularization every 16 minibatches. Use 4-8 GPUs with a total batch size of 32-64. Train for 25M+ images seen (not epochs) and track FID against a held-out validation set. Early stopping when FID plateaus.
  • Quality assurance pipeline: (1) automated FID/KID checks against the real dataset, (2) LPIPS-based diversity check (reject batches with mean pairwise LPIPS below a threshold), (3) human evaluation panel rating realism on a 1-5 scale for a random sample of 200 images, (4) A/B testing on the platform — do generated images lead to similar click-through and conversion rates as real product photos?
  • Production considerations: serve the generator with ONNX Runtime or TensorRT for 10-50ms inference latency. Cache generated images rather than generating on-the-fly. Implement a moderation pipeline to catch any artifacts or inappropriate content before serving. Version the model and track FID over time to detect quality regression.

Next: Autoencoders & VAEs

Learn about variational autoencoders and latent space representations