4.5.7Generative Models

Generator and discriminator dynamics

3,144 words14 min readdifficulty · medium

The Two-Player Game Setup

What are we optimizing?

GANs solve a minimax optimization problem. We're simultaneously:

  • Maximizing D's ability to classify real vs fake (D wants to be right)
  • Minimizing G's detectability (G wants to fool D)

Why this form? Let's derive it from first principles:

  1. What does D do? D is a binary classifier outputing probability that input is real.

    • For real data xx: D should output close to 1, so we want logD(x)\log D(x) large (log of high probability)
    • For fake data G(z)G(z): D should output close to 0, so we want log(1D(G(z)))\log(1 - D(G(z))) large (log of high probability it's fake)
  2. Why expectations? We average over all possible real samples from pdata(x)p_{data}(x) and all possible noise vectors zz from prior pz(z)p_z(z).

  3. Why log? Logarithm converts products to sums (easier optimization) and provides numerical stability. It's the natural choice from maximum likelihood estimation:

    • D's task: maximize likelihood of correct classification
    • MLE with binary outcomes → binary cross-entropy → log probabilities

Training Dynamics: The Alternating Dance

Figure — Generator and discriminator dynamics

Phase 1: D Optimization (k steps)

For k iterations (typically k=1 or k=5):

  1. Sample mini-batch of m real examples {x(1),,x(m)}\{x^{(1)}, \ldots, x^{(m)}\} from pdatap_{data}
  2. Sample mini-batch of m noise vectors {z(1),,z(m)}\{z^{(1)}, \ldots, z^{(m)}\} from pzp_z
  3. Generate fakes: x~(i)=G(z(i))\tilde{x}^{(i)} = G(z^{(i)})
  4. Update D by ascending gradient:

θd1mi=1m[logD(x(i))+log(1D(G(z(i))))]\nabla_{\theta_d} \frac{1}{m} \sum_{i=1}^{m} \left[ \log D(x^{(i)}) + \log(1 - D(G(z^{(i)}))) \right]

Why this step? We're giving D a supervised learning task: "Here are real images (label=1) and fake images (label=0). Learn to tell them apart." We ascend (not descend) because we're maximizing D's objective.

Phase 2: G Optimization (1 step)

  1. Sample new mini-batch of m noise vectors {z(1),,z(m)}\{z^{(1)}, \ldots, z^{(m)}\}
  2. Update G by descending gradient:

θg1mi=1mlog(1D(G(z(i))))\nabla_{\theta_g} \frac{1}{m} \sum_{i=1}^{m} \log(1 - D(G(z^{(i)})))

Why this step? G wants D to fail. When D(G(z))1D(G(z)) \to 1, that means D thinks the fake is real, so log(1D(G(z)))\log(1 - D(G(z))) \to -\infty, giving G low (good) loss.

The Nash Equilibrium: Optimal D*

Derivation from first principles:

For fixed G, we want to maximize: V(D,G)=xpdata(x)logD(x)dx+xpg(x)log(1D(x))dxV(D, G) = \int_x p_{data}(x) \log D(x) dx + \int_x p_g(x) \log(1 - D(x)) dx

(We converted expectations to integrals using definition E[f(x)]=f(x)p(x)dx\mathbb{E}[f(x)] = \int f(x)p(x)dx)

Combine integrals: V(D,G)=x[pdata(x)logD(x)+pg(x)log(1D(x))]dxV(D, G) = \int_x \left[ p_{data}(x) \log D(x) + p_g(x) \log(1 - D(x)) \right] dx

To maximize, take derivative w.r.t. D(x)D(x) and set to zero: D(x)[pdata(x)logD(x)+pg(x)log(1D(x))]=0\frac{\partial}{\partial D(x)} \left[ p_{data}(x) \log D(x) + p_g(x) \log(1 - D(x)) \right] = 0

pdata(x)D(x)pg(x)1D(x)=0\frac{p_{data}(x)}{D(x)} - \frac{p_g(x)}{1 - D(x)} = 0

Cross-multiply: pdata(x)(1D(x))=pg(x)D(x)p_{data}(x) (1 - D(x)) = p_g(x) D(x) pdata(x)=D(x)[pdata(x)+pg(x)]p_{data}(x) = D(x)[p_{data}(x) + p_g(x)]

Therefore: D(x)=pdata(x)pdata(x)+pg(x)D^*(x) = \frac{p_{data}(x)}{p_{data}(x) + p_g(x)}

What does this mean? D outputs the Bayes-optimal probability. It's the ratio of "how likely is this from real data" to "how likely is this from either source".

At perfect equilibrium: pg=pdatap_g = p_{data}, so D(x)=12D^*(x) = \frac{1}{2} everywhere. The discriminator cannot tell real from fake!

Training Stability and Collapse Modes

Mode Collapse

What happens: G discovers that producing a single type of output fools D, so it only produces that one mode, ignoring diversity in real data.

Why it occurs: G's objective is to fool D on expectation, not to cover all modes. If one mode always fools D, that's a local minimum.

Dynamics:

  1. G produces samples from multiple modes
  2. D learns to classify most modes correctly
  3. G notices one mode still fools D well
  4. G shifts all capacity to that mode
  5. D eventually learns that mode
  6. G switches to another mode (mode hopping)

Mathematical cause: The objective Ez[logD(G(z))]\mathbb{E}_z[\log D(G(z))] averages over z. If D is weak at one region, G can exploit it by mapping many z values to that region.

Oscillation and Non-Convergence

What happens: D and G chase each other without converging. Loss oscillates.

Why it occurs: The minimax game may not have good gradient dynamics. When D gets too strong, G's gradients vanish. When G gets too good, D's task becomes impossible, gradients explode.

Visualization: Imagine two players running around a circular track, each chasing the other's tail. Neither catches up, they just loop forever.

Practical Training Considerations

Choosing k (D steps per G step)

  • k = 1: Balanced training. D and G improve together. Risk: D might not stay strong enough to provide good gradients.
  • k > 1 (e.g., k=5): Keep D ahead of G. Ensures strong gradients for G. Risk: D might become too strong, causing vanishing G gradients.
  • Adaptive k: Increase k if D loss spikes (G is winning), decrease if G loss spikes (D is winning).

Why it matters: The quality of G's gradient depends on D's strength. Too weak D → G learns wrong things. Too strong D → G doesn't learn at all.

Learning Rates

Typical setup: αD=0.002\alpha_D = 0.002, αG=0.0001\alpha_G = 0.0001 (D learns slightly faster).

Why asymetric? D's task (classification) is easier than G's task (generation). If they learn at the same rate, D dominates.

Batch Normalization Pitfall

Issue: Batch norm in D creates correlation between samples in a batch. If entire batch is real or entire batch is fake, D learns to exploit batch statistics rather than individual sample features.

Solution: Use separate batches for real and fake samples when training D. Apply batch norm within each batch type separately.

Connections

  • 4.5.01-Introduction-to-Generative-Adversarial-Networks: This expands the two-player game concept
  • 4.5.06-GAN-training-algorithm: The practical implementation of these dynamics
  • 4.5.08-Mode-collapse-in-GANs: Deep dive into the collapse failure mode
  • 4.5.09-Waserstein-GAN: Alternative formulation that stabilizes training
  • 3.2.04-Binary-cross-entropy-loss: D's loss function is exactly this
  • 3.4.05-Vanishing-gradients: Why non-saturating loss is necessary
  • 5.3.02-Nash-equilibrium: Game theory foundation of GAN equilibrium
Recall Explain to a 12-Year-Old

Imagine you're trying to learn to draw realistic portraits, and your art teacher is checking your work.

At first, your drawings are terrible - stick figures with no detail. Your teacher instantly knows they're fake. She tells you: "Add shading, fix the proportions." You improve a little.

After practicing, your drawings get better. Now your teacher has to look more carefully. She might say: "The eyes are still wrong, and real people don't have perfectly smooth skin." You learn to add more detail.

This back-and-forth continues. You (the Generator) keep trying to fool your teacher. She (the Discriminator) keeps getting better at spotting mistakes. Each round, both of you improve.

Eventually, you get so good that even your expert teacher can only guess if a drawing is yours or a real photo - she's right only 50% of the time, like flipping a coin! That's when you've "won" the game. But sometimes, you might discover that drawing one specific pose always fools your teacher. So you only draw that one pose over and over. That's boring and not the goal - you should be able to draw many different things. That's called "mode collapse."

The key is: you need your teacher to be good (but not impossible to fool) so she can give you useful feedback on how to improve!

#flashcards/ai-ml

What are the two roles in a GAN and what does each one optimize? :: The Generator (G) tries to minimize the objective function by creating realistic fakes. The Discriminator (D) tries to maximize the objective function by correctly classifying real vs fake samples.

What is the GAN minimax objective function?
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)))] where D maximizes and G minimizes this value function.
Why does the Generator ignore the first term of the GAN objective?
The term Expdata[logD(x)]\mathbb{E}_{x \sim p_{data}}[\log D(x)] depends only on real data and D's parameters, not on G's parameters. It's a constant with respect to G, so it doesn't affect G's gradient.
What is the vanishing gradient problem in GAN training?
Early in training, D easily spots fakes so D(G(z))0D(G(z)) \approx 0. The gradient Glog(1D(G(z)))\nabla_G \log(1-D(G(z))) becomes very small, causing G to learn extremely slowly or not at all.
What is the non-saturating Generator loss and why is it used?
maxGEz[logD(G(z))]\max_G \mathbb{E}_z[\log D(G(z))] instead of minGEz[log(1D(G(z))]\min_G \mathbb{E}_z[\log(1-D(G(z))]. It provides stronger gradients when D easily identifies fakes (when G needs the most guidance), solving the vanishing gradient problem.
What is the optimal discriminator formula for a fixed generator?
D(x)=pdata(x)pdata(x)+pg(x)D^*(x) = \frac{p_{data}(x)}{p_{data}(x) + p_g(x)} which represents the Bayes-optimal probability that a sample comes from real data rather than the generator.

At GAN equilibrium when pg=pdatap_g = p_{data}, what is D(x)D^*(x)? :: D(x)=0.5D^*(x) = 0.5 for all x. The discriminator cannot distinguish real from fake samples since they come from the same distribution, effectively guessing randomly.

What is mode collapse in GANs?
When the Generator discovers one or few outputs that fool the Discriminator and produces only those, ignoring the diversity of the real data distribution. The Generator has collapsed to generating limited modes.
Why do we typically train D for k steps before each G step?
To keep the Discriminator strong enough to provide meaningful gradients to the Generator. If D becomes too weak, it gives poor feedback. If k=1, D might not maintain sufficient strength.
What is the typical relationship between D and G learning rates?
The Discriminator learning rate is typically slightly higher (e.g., 0.0002) than the Generator learning rate (e.g., 0.0001) because the classification task is easier than generation, preventing D from dominating too strongly.

Concept Map

input to

produces

classified by

classified by

maximizes

minimizes

defines

derived from MLE gives

converges to

counterfeiter role

detective role

Generator G

Discriminator D

Noise z from prior

Real data p_data

Fake samples G z

Value function V D,G

Minimax game

Equilibrium D outputs 0.5

Binary cross-entropy

Hinglish (regional understanding)

Intuition Hinglish mein samjho

GAN training ek interesting game hai jaise counterfeiter aur detective ka match. Generator (G) fake data banata hai jo real lagey, aur Discriminator (D) real aur fake ko identify karta hai. Dono ek-dusre ko improve karne mein help karte hain - jaise D better detection karta hai, toh G ko aur realistic fakes banana padta hai, aur jaise G improve hota hai, D ko aur sharp detector banna padta hai.

Iska objective function ek minimax game hai: D maximize karna chahta hai ki woh kitna sahi classify kar raha hai, jabki G minimize karna chahta hai ki D usko kitna easily pakad leta hai. Mathematically, yeh minGmaxDV(D,G)\min_G \max_D V(D,G) hai, jahan V mein real data pe D ki confidence aur fake data pe D ki rejection dono hai. Training mein pehle D ko k steps train karte hain (usually k=1 ya 5), phir G ko ek step train karte hain. Yeh alternating process tab tak chalta hai jab tak perfect equilibrium nahi mil jata - jab G itna acha ho jata hai ki D sirf guess kar sakta hai (50% accuracy).

Lekin practical training mein kai problems ate hain. Early training mein "vanishing gradient" problem hoti hai - jab D bahut strong ho aur G ke fakes ko easily spot kar le, toh G ko koi gradient nahi milta improve karne ke liye. Isko solve karne ke liye hum "non-saturating loss" use karte hain jo G ko strong gradients deta hai jab woh fail ho raha ho. Dusri badi problem "mode collapse" hai - jab G discover kar leta hai ki ek specific type ka output hamesha D ko fool kar deta hai, toh woh sirf wahi ek chez generate karta rehta hai, diversity khatam ho jati hai.

Theory mein optimal state woh hai jab p_g (generator ka distribution) exactly p_data (real data distribution) ke equal ho jaye. Us time pe D* koi fark nahi pata chalta aur woh har sample ke liye 0.5 probability output karta hai. Real-world mein yeh perfect equilibrium achieve karna mushkil hai, isliye careful tuning chahiye - learning rates adjust karna, k value sahi rakhna, aur batch normalization sahi tarike se use karna zaroori hai stability ke liye.

Go deeper — visual, from zero

Test yourself — Generative Models

Connections