Session S24

GANs

A generative adversarial network (GAN) learns its loss: a second network is trained to tell real samples from generated ones. How do the two networks train each other, why does that training collapse and how do we see it, why can a winning discriminator stop teaching the generator, how do we judge samples without a likelihood, and what became of GANs?

Deep Learning · CS 4715/5715 · University of Idaho

The final report is the next project deadline

Two course items come first.

  • Final report: due at the end of the S27 week, after Fall Recess and before the recorded presentation. The required sections, the model card template and the rubric are in the project guide on the course site. A quantitative sanity check of your outputs strengthens the Results section: today's mode-coverage statistic is a model for one, a few lines of code that turn samples into a number you can check.
  • Quiz 4 (Module 4, S23–S26) is at S27, and today's material is on it.

Last time, S23 built a decoder that turns prior samples into data

S23, in its own words:

  • What generation needs: a known prior \(\mathcal N(0,I)\) to sample from, and a loss of reconstruction plus a KL term that pulls each \(q(z\mid x)\) toward that prior. The result is a smoother, more sampleable code space, not one free of holes.
  • The reparameterization: \(z=\mu+\sigma\varepsilon\) puts the randomness in \(\varepsilon\).
  • What the tiny VAE generated: both clusters, with 18% of samples in the gap.
  • On images, gap samples look like blends. VAE images are also blurry for a second reason: a pixelwise Gaussian loss averages several plausible sharp outputs into one.

S23's loss is a formula that we wrote down. Today trains such a decoder with no encoder, against a second network.

Today's route answers the five questions in order, then closes

Each part answers one clause of the title page's question.

partthe question it answers
1 · The gamehow do the two networks train each other? The objective, the best discriminator, and the training step in code
2 · Collapsewhy does training collapse, and how do we see it? A run you can watch, on two modes and then on eight
3 · Distancewhy can a winning discriminator stop teaching? The gradient vanishes, we measure it, and a different loss restores it
4 · Evaluationhow do we judge samples without a likelihood? Scores computed from samples, and what one number can hide
5 · Historywhat became of GANs? Diffusion took over; the adversarial loss stayed
6 · Closesix common mistakes, today's answer, next time

Each of Parts 1–5 ends on a self-check. First, why a learned loss.

A pixelwise squared loss is minimized by the average, which is blurry

Part 1 · The game. First, where the blur of VAE images comes from, computed on real images:

6 of the 100 images: each one is sharp… and 94 moretheir average: blurrypixelwiseaverageof all 100Data: MNIST training set, digit 3; 100 images drawn at random with seed 0.
  • There are many sharp ways to write a 3: take these \(N=100\) as \(y_1,\dots,y_N\). The one output \(\hat y\) with the least total squared error is their pixelwise average, \(\tfrac1N\sum_i y_i\). The gradient of the total squared error, \(2\sum_i(\hat y-y_i)\), is zero exactly there.
  • The right image is an average of sharp images, not a VAE's output. Averaging made the strokes wider and fainter. A VAE's decoder must give one image for a code that several sharp images fit, so its pixelwise squared loss blurs it in the same way.

From VAE blur to a learned loss

S23's VAE scores its samples with a loss written down, and a pixelwise squared (Gaussian) loss gives the blurry average just shown. A generative adversarial network (GAN; Goodfellow et al., 2014) trains the loss instead:

VAE (S23)decoderits samples: blurrya loss written down: a pixelwise squared loss,which averages plausible sharp outputslearn the loss itselfGANgeneratorits samples: sharpD: a second network, trainedto tell real from fake
  • Results: the sharpest images the field had seen, and GANs dominated image generation for about six years.
  • GAN training is also among the most unstable in deep learning, and the instability is built into the formulation.

Nobody writes down what a good sample looks like: a second network learns the difference.

\(D\) learns to tell real from fake, and \(G\) learns to fool it

D's gradients tell G in which direction its samples are detectably fake.z ∼ N(0, I)Generator Glike a VAE decoder,no encoderG(z): a fake samplex: a real sample, from the dataDiscriminator DD(G(z)): probability that G(z) is real01training D lowers ittraining G raises itD(x): probability that x is real01training D raises itThin black arrows show where the data goes; thick colored arrows show which way training moves D's output.Training D: it learns to tell real from fake, so D(x) moves toward 1 and D(G(z)) toward 0.Training G: it learns to fool D, so D(G(z)) moves toward 1, against D.

\(D\) and \(G\) push the same output, \(D(G(\mathbf{z}))\), in opposite directions: the adversarial game.

\(D\) and \(G\) want the same value to go opposite ways

  1. \(D\) is a binary classifier: label 1 on real samples \(\mathbf{x}\), drawn from the data's distribution \(p_{\text{data}}\), and label 0 on fakes. It wants the log-probability of the correct label to be large: \[V(D,G)=\mathbb{E}_{\mathbf{x}\sim p_{\text{data}}}[\log D(\mathbf{x})]+\mathbb{E}_{\mathbf{z}\sim\mathcal{N}(\mathbf{0},\mathbf{I})}[\log(1-D(G(\mathbf{z})))]\] Maximizing \(V\) is minimizing S03's binary cross-entropy (BCE); it pushes \(D(\mathbf{x})\) toward 1 and \(D(G(\mathbf{z}))\) toward 0.
  2. \(G\) wants \(D\) to be wrong, so it wants the same \(V\) small. The first term has no \(G\) in it; \(G\) can only change the second, by pushing \(D(G(\mathbf{z}))\) toward 1.
  3. Together (Goodfellow et al., 2014): \(\min_G\max_D V\). Read it from the inside: for each \(G\), \(D\) maximizes \(V\); \(G\) minimizes that maximum, so it is judged against the best \(D\).

\(D\) raises \(V\) and \(G\) lowers it: one network's gain is the other's loss, so this is a game.

On a batch, \(D\)'s loss is \(-V\), computed as two BCE terms

Each expectation in \(V\) becomes a mean over a batch (the demo's two-term form):


d_loss = bce(D(x_real), ones) + bce(D(x_fake), zeros)
  
  • The first term is the mean of \(-\log D\) over the real batch (label 1), and the second the mean of \(-\log(1-D)\) over the fake batch (label 0): together, an estimate of \(-V\).
  • x_real is a batch of real samples, x_fake a batch of fakes from \(G\), and ones, zeros are their labels, all (128, 1).
  • The code's D returns a logit; bce = nn.BCEWithLogitsLoss() applies the sigmoid and returns the mean BCE, a scalar.

The code never writes min or max: it lowers two losses in turn. \(D\)'s loss is \(-V\); \(G\)'s loss uses only \(D(G(\mathbf{z}))\).

If \(V\) were optimized to the end, what would \(D\) and \(G\) learn?

  • The question: slide 5 asked what a pixelwise squared loss teaches when optimized to the end; the answer was the average, hence the blur. The next three slides ask the same of \(V\).
  • The answer: for a fixed \(G\), whose samples have the density \(p_g\), the best discriminator (slides 11–12) is \[D^{*}(\mathbf{x})=\frac{p_{\text{data}}(\mathbf{x})}{p_{\text{data}}(\mathbf{x})+p_g(\mathbf{x})}\] When \(G\)'s samples match the data, \(D^{*}=0.5\) everywhere and \(D\)'s loss is \(2\log2\approx1.386\) (slide 13). What \(G\) faces against \(D^{*}\) comes in Part 3.
  • What it is for: 1.386 is the reference that today's training curves are read against, and \(D^{*}\)'s formula explains the instability in Part 3.

For a fixed \(G\), the best \(D\) is found at each point \(\mathbf{x}\) separately

The first step: the best \(D\) for a fixed \(G\). From here on, \(\mathbf{x}\) is any point in data space, real or generated.

  1. Fix \(G\). Its samples \(\mathbf{x}=G(\mathbf{z})\) have a density \(p_g\), so \(\mathbb{E}_{\mathbf{z}\sim\mathcal{N}(\mathbf{0},\mathbf{I})}[\log(1-D(G(\mathbf{z})))]=\mathbb{E}_{\mathbf{x}\sim p_g}[\log(1-D(\mathbf{x}))]\).
  2. \(V=\int\big(p_{\text{data}}(\mathbf{x})\log D(\mathbf{x})+p_g(\mathbf{x})\log(1-D(\mathbf{x}))\big)\,d\mathbf{x}\): each expectation written as an integral against its density.
  3. \(V\) adds up one term per point \(\mathbf{x}\), and \(D\)'s value at one point appears in that term only (\(D\) may be any function), so each term can be maximized on its own. Fix \(\mathbf{x}\) and write \(a=p_{\text{data}}(\mathbf{x})\), \(b=p_g(\mathbf{x})\), \(y=D(\mathbf{x})\): maximize \(f(y)=a\log y+b\log(1-y)\) over \(0<y<1\).

At each \(\mathbf{x}\), the best \(D(\mathbf{x})\) is the \(y\) that maximizes \(f(y)\).

Setting \(f'(y)=0\) gives the best discriminator

The previous page's problem at one \(\mathbf{x}\): maximize \(f(y)=a\log y+b\log(1-y)\) over \(0<y<1\), with \(a=p_{\text{data}}(\mathbf{x})\), \(b=p_g(\mathbf{x})\), \(y=D(\mathbf{x})\):

  1. \(f'(y)=a/y-b/(1-y)=0\) gives \(a(1-y)=b\,y\), so \(y=a/(a+b)\). \(f''(y)=-a/y^2-b/(1-y)^2<0\), so it is a maximum.
  2. For a fixed \(G\), the best discriminator is \[D^{*}(\mathbf{x})=\frac{p_{\text{data}}(\mathbf{x})}{p_{\text{data}}(\mathbf{x})+p_g(\mathbf{x})}\]
  3. With as many fakes as real samples, that ratio is the probability that a sample found at \(\mathbf{x}\) is real: \(D^{*}(\mathbf{x})=P(\text{real}\mid\mathbf{x})\), the output of a perfect classifier.

\(D^*(\mathbf{x})\) is the probability that \(\mathbf{x}\) is real: the share of the density at \(\mathbf{x}\) that is real data.

At equilibrium \(D^*=0.5\) everywhere, and \(D\)'s loss is \(2\log2\approx1.386\)

D*(x) is the share of the density at x that is real data.only real data at xpdata(x)D* = 1equally densepdata(x)pg(x)D* = 0.5only fakes at xpg(x)D* = 0at equilibrium pg = pdata, so every x looks like this
  • At the game's equilibrium neither player can improve against the other. That needs \(p_g=p_{\text{data}}\): where they differ, \(D^{*}\ne0.5\), and both can still improve (Part 3 proves it).
  • So \(D^{*}=0.5\) everywhere.
  • \(D\)'s two-term loss is \(-\log D(\mathbf{x})-\log(1-D(G(\mathbf{z})))=-\log\tfrac12-\log\tfrac12=2\log2\approx1.386\).

Remember 1.386: it shows up in today's runs.

The non-saturating loss is the original paper's own practical fix

\(G\)'s term \(\log(1-D(G(\mathbf{z})))\) is flat exactly when \(G\) is losing (the loss saturates):

0−8−4048early in training: D rejects fakes with easeslope D − 1 ≈ −1: a strong gradientflat: gradient −D ≈ 0−log D(G(z)),the non-saturating losslog(1 − D(G(z))),the original lossℓ: D's logit on a fake, D(G(z)) = sigmoid(ℓ)G's loss (G minimizes it)Both curves are plotted from the formulas on this page.
  • Fix: \(G\) maximizes \(\log D(G(\mathbf{z}))\) instead, i.e. "make D say real". Implementations of this game use it, including the demo: g_loss = bce(D(x_fake), ones).

On the logit, the two losses have gradients \(-D\) and \(D-1\)

Write \(D\) for \(D(G(\mathbf{z}))=\operatorname{sigmoid}(\ell)\). S03 gave the sigmoid's derivative, \(\partial D/\partial\ell=D(1-D)\); the chain rule then gives:

\[\text{original loss:}\quad\frac{\partial\log(1-D)}{\partial\ell}=\frac{-1}{1-D}\,D(1-D)=-D\] \[\text{non-saturating loss:}\quad\frac{\partial(-\log D)}{\partial\ell}=\frac{-1}{D}\,D(1-D)=D-1\]
  • Where \(D\) rejects the fake, at \(D=0.01\), the original loss has gradient \(-0.01\) and the non-saturating loss \(-0.99\).
  • The equilibrium is the same: there \(D=0.5\), and the non-saturating loss is \(-\log\tfrac12=\log2\approx0.693\).

Where the original loss has almost no gradient, the non-saturating loss keeps one near \(-1\).

The demo: one-number samples near −2 or +2, and two small MLPs

Reading 4.2's demo (torch, torch.nn as nn, seed 0): the data are single numbers, half near −2 and half near +2.


torch.manual_seed(0)
# Real data: 1D mixture, half N(-2, 0.5^2), half N(+2, 0.5^2)
def real_batch(n):                                     # returns (n, 1)
    side = (torch.rand(n, 1) < 0.5).float() * 4 - 2    # each sample's center: -2 or +2, at random
    return side + 0.5 * torch.randn(n, 1)              # plus noise with standard deviation 0.5

G = nn.Sequential(nn.Linear(1, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1))
D = nn.Sequential(nn.Linear(1, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1))
  
object, for a batch of 128codeshape
noise \(z\sim\mathcal{N}(0,1)\), one number per sampletorch.randn(128, 1)(128, 1)
fake samples \(G(\mathbf{z})\); \(G\) a 1→32→32→1 MLPG(z)(128, 1)
real samples \(\mathbf{x}\), from the datareal_batch(128)(128, 1)
\(D\)'s logits \(\ell\), one per sampleD(x)(128, 1)

The code's D returns logits \(\ell\), and \(D(\mathbf{x})=\operatorname{sigmoid}(\ell)\) is the probability that \(\mathbf{x}\) is real.

In code, each training step updates \(D\), then \(G\)

The demo of the previous slide (seed 0), with G, D and real_batch as defined there; each network has its own Adam optimizer:


opt_g = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))  # beta1 = 0.5, below Adam's
opt_d = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))  # default 0.9: less momentum
bce = nn.BCEWithLogitsLoss()
ones, zeros = torch.ones(128, 1), torch.zeros(128, 1)

for step in range(2001):                 # 2001, so that step 2000 is printed too
    # --- discriminator step ---
    x_real = real_batch(128)
    x_fake = G(torch.randn(128, 1)).detach()
    d_loss = bce(D(x_real), ones) + bce(D(x_fake), zeros)
    opt_d.zero_grad(); d_loss.backward(); opt_d.step()
    # --- generator step (non-saturating loss) ---
    x_fake = G(torch.randn(128, 1))
    g_loss = bce(D(x_fake), ones)
    opt_g.zero_grad(); g_loss.backward(); opt_g.step()
  

Each step draws fresh batches; each optimizer updates only its own network.

Without .detach(), \(D\)'s loss also sends gradients into \(G\)

In the discriminator step, the fake batch should be detached: G(z).detach().

discriminator stepx_realzGG(z).detach()Dd_lossWith .detach(), the backward pass stops here.Without it, d_loss.backward() also fills G's .grad.order in the training loopd_loss.backward()G's .gradopt_d.step()opt_g.zero_grad()clearedg_loss.backward(); opt_g.step()G's own gradientIn this order those gradients are cleared before G's update, so this run is unchanged;the cost is a wasted backward pass through G.
  • Nothing crashes either way; if opt_g.zero_grad() ran before the discriminator step, those gradients would be added to \(G\)'s update and training would be silently worse.
  • General discipline for any two-network setup: decide which parameters each loss may touch, cut the graph everywhere else.

Self-check on the best discriminator, two gradients and a missing detach

Three questions on Part 1.

(a) At some \(\mathbf{x}\), \(p_{\text{data}}(\mathbf{x})=0.3\) and \(p_g(\mathbf{x})=0.1\). What is \(D^*(\mathbf{x})\)?

(b) \(D(G(\mathbf{z}))=0.02\) on a fake. How large is the gradient on the logit under the original loss, and under the non-saturating loss?

(c) Without .detach(), who gets gradients from d_loss.backward()? Does \(G\)'s update change in the demo's loop?

(a) \(0.3/(0.3+0.1)=0.75\).

(b) \(D=0.02\) against \(1-D=0.98\), about 50 times stronger.

(c) \(D\) and \(G\). No: opt_g.zero_grad() clears those gradients before \(G\)'s update; the cost is a wasted backward pass.

\(D\) classifies; \(G\) learns from \(D\)'s gradient; each optimizer updates only its own network.

Training is unstable because each loss moves with the other network

Part 2 · Collapse. Every network before today trained on one loss, with a descent direction on it (reading 4.2):

  • A GAN has two losses, each defined relative to the other player's current parameters: \(G\)'s loss changes every time \(D\) updates, and the reverse. Each step answers the other player's current state; the best such answer is called a best response.
  • Gradient descent on a game, simultaneous or alternating as in the demo, is not guaranteed to converge: the players can orbit the equilibrium, overshoot it, or fall into degenerate strategies.
  • Mode collapse (a mode is one peak of the data distribution): nothing in \(G\)'s objective says "cover the whole distribution", only "produce samples \(D\) currently accepts". If one region fools \(D\) now, the cheapest move is to put all the mass there.

This instability is a structural failure of best-response dynamics, not of bad hyperparameters; hyperparameters decide how severe it is.

Two players, each following its own gradient, can circle the equilibrium

Two numbers, not a GAN: \(x\) wants \(V=xy\) small, \(y\) wants it large (\(\partial V/\partial x=y\), \(\partial V/\partial y=x\)). Equilibrium \((0,0)\), learning rate 0.1, start \((1,0)\).

2−22−2xyequilibrium (0, 0)start (1, 0)simultaneous: spirals outwardalternating: circles near distance 1
  • One gradient step: \(x\leftarrow x-0.1\,y\), \(y\leftarrow y+0.1\,x\).
  • Simultaneous: both use the old values. The distance grows by \(\sqrt{1.01}\) per step, and \(1.01^{100}\approx2.70\).
  • Alternating (the demo's order): \(y\) uses the new \(x\).
distance to \((0,0)\) after step150100200
simultaneous1.0051.281.642.70
alternating1.0050.991.021.02

Neither order reaches \((0,0)\): the two players keep circling the equilibrium.

Best responses predict a collapse cycle on two modes

The demo's data has two modes, at −2 and +2. What best responses predict (a schematic, not a run):

−2+2−2+2−2+2G's samplesreal dataG puts all its samples in oneregion that D accepts now.fakerealD's outputD learns to rejectthat region.G moves to another region.and the cycle can repeat

Prediction. The demo trains for 2,000 steps and prints its progress every 250. At step 250, will \(G\) cover both modes? Could you tell from the two losses?

The demo measures coverage by counting the samples near each mode

Coverage: what share of \(G\)'s samples lies near each mode. real_batch (the setup slide) draws half its points near −2 and half near +2; these lines print the coverage every 250 steps of the training loop:


for step in range(2001):
    # ... the two updates of each step (the training-step slide), then:
    if step % 250 == 0:
        with torch.no_grad():
            s = G(torch.randn(4000, 1))                   # (4000, 1)
        left = ((s + 2).abs() < 1).float().mean().item()   # share within 1 of -2
        right = ((s - 2).abs() < 1).float().mean().item()  # share within 1 of +2
        print(f"step {step:4d}  D loss {d_loss.item():.4f}  G loss {g_loss.item():.4f}  "
              f"near -2: {left:.3f}  near +2: {right:.3f}")
  
  • left and right: the share of 4,000 fresh samples within 1 of −2 and of +2. Real data in the same windows: 48% and 48% (each mode holds half the data and puts 95% of its points within 2 sd (1.0) of its center). The two shares need not add to 1: the rest of the samples lie near neither mode.
  • d_loss and g_loss are that step's batch losses.

The run collapses by step 250 and recovers by step 2000

Answer: no, and the losses do not show it. Reading 4.2's printout (seed 0):


step    0  D loss 1.3810  G loss 0.8556  near -2: 0.000  near +2: 0.000
step  250  D loss 1.0758  G loss 1.0564  near -2: 0.949  near +2: 0.000
step  500  D loss 0.9873  G loss 1.1501  near -2: 0.870  near +2: 0.000
step  750  D loss 1.3852  G loss 0.8334  near -2: 0.223  near +2: 0.331
step 1000  D loss 1.3553  G loss 0.7481  near -2: 0.433  near +2: 0.211
step 1250  D loss 1.3392  G loss 0.7115  near -2: 0.474  near +2: 0.329
step 1500  D loss 1.3392  G loss 0.7200  near -2: 0.468  near +2: 0.377
step 1750  D loss 1.3759  G loss 0.7092  near -2: 0.453  near +2: 0.426
step 2000  D loss 1.3621  G loss 0.7391  near -2: 0.464  near +2: 0.435
  
  • Step 250: 94.9% of the samples near −2, none near +2. The losses, 1.08 and 1.06, show \(D\) ahead (\(D\)'s is below its equilibrium 1.386, \(G\)'s above 0.693), not that a mode is missing.
  • Step 500: \(D\)'s loss falls to 0.99. \(D\) is winning near −2, where only fakes pile up, and that pressure moves \(G\) toward +2 by step 750.

Coverage, not the losses, shows the collapse at step 250 and the recovery by step 2000.

The coverage columns show the collapse and the recovery

The two right-hand columns, plotted against the step:

0500100015002000step00.51share of 4,000 samplesreal data: 48% in each window0.949 / 0.000: collapsedD loss 0.99: D is winning;it rejects the crowded mode at −2G's samples move toward +2near −2: 0.464near +2: 0.435The chart plots all nine printed rows.
  • Recovery is not guaranteed: on harder data (more modes, images) \(G\) can collapse, move, and collapse again without settling.

The predicted cycle happened: collapse by step 250, \(D\) ahead by 500, \(G\) moved by 750.

What the losses do not tell you

The two loss columns, on the same steps:

0500100015002000step0.61.01.4loss2 log 2 ≈ 1.386log 2 ≈ 0.693D lossG lossstep 250, fully collapsed: losses 1.08 (D) and 1.06 (G)coverage there: 0.949 / 0.000final stretch: D near 1.386, G near 0.693Losses from the same nine printed rows as the coverage chart.
  • Near-equilibrium losses are not proof: at step 0, with no sample in either window, \(D\)'s loss was 1.381, closer to 1.386 than the end's 1.362.
  • So measure the samples directly: coverage here, Inception Score and FID (Fréchet Inception Distance, Part 4) for images.

The losses show which network is ahead, not whether the samples cover the data.

A harder test puts 8 Gaussians on a ring

  • The data are 2D points: 8 Gaussians (\(\sigma=0.15\)) on a ring of radius 2.
  • The same training loop (seed 0): \(G\) and \(D\) are MLPs with two hidden layers of 64, and the batch size is 256.
  • A mode is "covered" if at least 2% of 4,000 samples land within \(3\sigma=0.45\) of its center.
−2−20022Grey circles: the 8 windows of radius 0.45, to scale.Dots: 1,000 real samples.

modes_covered counts the samples near each center

The measurement on the ring, and what the run prints:


angles = torch.arange(8) * (2 * torch.pi / 8)
centers = torch.stack([2 * torch.cos(angles), 2 * torch.sin(angles)], dim=1)  # (8, 2)
def modes_covered(samples):                     # samples: (n, 2)
    d = torch.cdist(samples, centers)           # (n, 8): distance from each sample to each center
    nearest = d.argmin(dim=1)                   # (n,): index of the nearest center
    hit = d.min(dim=1).values < 0.45            # (n,) True where that center is within 0.45
    # nearest[hit] keeps the hits' center indices; bincount counts each index 0..7: (8,)
    counts = torch.bincount(nearest[hit], minlength=8)   # minlength=8: an empty mode counts 0
    return (counts.float() / len(samples) >= 0.02).sum().item(), counts.tolist()
# the demo's loop (2-number noise, 3,001 steps) prints modes_covered every 500 steps
  

step    0  D loss 1.3226  G loss 0.6931  modes covered: 0/8
step  500  D loss 1.4362  G loss 0.6343  modes covered: 2/8
step 1000  D loss 1.0848  G loss 0.9441  modes covered: 4/8
step 1500  D loss 1.3097  G loss 0.8107  modes covered: 6/8
step 2000  D loss 1.3044  G loss 0.7653  modes covered: 7/8
step 2500  D loss 1.3096  G loss 0.7395  modes covered: 8/8
step 3000  D loss 1.3032  G loss 0.7528  modes covered: 8/8
final per-mode sample counts (of 4000): [223, 315, 410, 387, 300, 249, 384, 361]
  

All eight modes are covered, and the distribution is still not matched

  • Coverage grows mode by mode (2, 4, 6, 7, then 8 by step 2500): \(G\) adds mass where \(D\) currently separates real from fake least well.
  • A perfect model puts about 500 samples on each mode; these counts sum to 2,629 of 4,000, so about a third fell outside every mode, mostly between them (reading 4.2).
  • "All modes covered" is a much weaker statement than "distribution matched"; most later GAN work went into closing that gap.

\(G\)'s samples after training, over the data:

223315410387300249384361real data (1,000 samples)G's samples after trainingBlue: 1,000 of G's 4,000 samples, every 4th one(reading 4.2's script, seed 0). The numbers count thesamples in each window: 2,629 of 4,000 inside a window.

Counting samples per mode, like modes_covered, is a check worth adding to your report.

Self-check on a falling loss, a healthy-looking end and four modes

Three questions on Part 2.

(a) From step 250 to 500, \(D\)'s loss fell from 1.08 to 0.99 while 87% of the samples still sat near −2. Is the falling \(D\) loss a sign that training is failing?

(b) Another run ends with \(D\) loss 1.38 and \(G\) loss 0.70. Is its generator good?

(c) On the ring, a model puts 500 samples in each of 4 windows and none in the other 4 (of 4,000 samples). How many modes are covered, and what share of the samples is inside a window?

(a) No: \(D\) caught the overpopulated left mode, and its rejection pushed \(G\)'s mass toward +2 by step 750.

(b) Not shown: an undertrained \(D\) gives values near \(2\log2\) and \(\log2\) too. Measure the samples.

(c) 4/8 (each holds 12.5%, above 2%); 50% in all.

Coverage counts caught a collapse that the losses did not show.

Against the best \(D\), \(G\) lowers a Jensen–Shannon divergence

Part 3 · Distance. Put Part 1's \(D^*\) into \(V\):

\[V(D^*,G)=-\log4+2\,\mathrm{JS}(p_{\text{data}}\,\|\,p_g)\]

\(\mathrm{JS}(p\,\|\,q)=\tfrac12\mathrm{KL}(p\,\|\,m)+\tfrac12\mathrm{KL}(q\,\|\,m)\) with \(m=(p+q)/2\), the average of \(p\) and \(q\).

  1. \(V(D^*,G)=\mathbb{E}_{p_{\text{data}}}\big[\log\big(p_{\text{data}}/2m\big)\big]+\mathbb{E}_{p_g}\big[\log\big(p_g/2m\big)\big]\), where \(m=(p_{\text{data}}+p_g)/2\), so that \(D^*=p_{\text{data}}/(2m)\) and \(1-D^*=p_g/(2m)\).
  2. \(=-\log4+\mathrm{KL}(p_{\text{data}}\,\|\,m)+\mathrm{KL}(p_g\,\|\,m)=-\log4+2\,\mathrm{JS}(p_{\text{data}}\,\|\,p_g)\), since \(\log(p/2m)=\log(p/m)-\log2\) in each term; S23's \(\mathrm{KL}(p\,\|\,q)=\mathbb{E}_p[\log(p/q)]\).
  3. \(\mathrm{JS}\ge0\), and 0 only when \(p_g=p_{\text{data}}\). There \(D\)'s loss is \(-V=\log4=2\log2\approx1.386\), Part 1's number.

Under the original loss, training \(G\) against the best \(D\) lowers a JS divergence.

Without overlap, JS is stuck at \(\log2\) and gives \(G\) no direction

Arjovsky and Bottou (ICLR 2017): if the two distributions do not overlap, then on the data \(m=p_{\text{data}}/2\), so \(\mathrm{KL}(p_{\text{data}}\,\|\,m)=\log2\); likewise for \(p_g\):

0+2realfakeD* = 1D* = 0distance 2: JS = log 2−8+2realfakeD* = 1D* = 0distance 10: JS = log 2Schematic, drawn without overlap; orange: D*. With D = 0 on every fake, Part 1's gradient −D on the logit is 0.
  • JS is \(\log2\) whether the fakes are close to the data or far from it, so it gives no direction.
  • No overlap is the usual case: real data lies near a low-dimensional surface, an untrained generator's output on another, and two such surfaces in a high-dimensional space typically do not meet.
  • There a well-trained \(D\) becomes perfect, and under the original loss it hands \(G\) a gradient of zero: the better \(D\) does its job, the less it teaches \(G\).

The experiment moves a fake cloud at offset \(\mu\) against a real cluster at +2

Reading 4.2's test (seed 0): the "generator" is a cloud at a trainable offset \(\mu\), so its whole update is one number, \(\partial L/\partial\mu\). For each offset mu_val (the printout's mu; distance \(=2-\mu\)), \(D\) is trained for 500 steps, then:


real = 2.0 + 0.25 * torch.randn(512, 1)   # real data: a cluster at +2, (512, 1)
eps = 0.25 * torch.randn(512, 1)          # fixed noise for the fake cloud
# D: a 1→64→64→1 MLP, Adam lr 1e-3, 500 steps on real against mu_val + eps
mu = torch.tensor(mu_val, requires_grad=True)
sat = torch.log(1 - torch.sigmoid(D(mu + eps)) + 1e-12).mean()  # 1e-12: avoids log(0) if D = 1
sat.backward()
g_sat = mu.grad.abs().item()             # saturating: minimize log(1 - D(fake))
mu = torch.tensor(mu_val, requires_grad=True)
bce(D(mu + eps), torch.ones(512, 1)).backward()
g_nonsat = mu.grad.abs().item()          # non-saturating: minimize -log D(fake)
# |W grad|: |d(-C(fake).mean())/d mu| for a WGAN-GP critic C trained the same way
#   (WGAN-GP: Wasserstein GAN with gradient penalty; no sigmoid, slope held near 1; two pages on)
  

    mu  distance  D(fake)  |sat grad|  |non-sat grad|  |W grad|
   1.5       0.5   0.2175    1.738256          5.7076    0.9699
   0.0       2.0   0.0006    0.005676          4.2828    1.0837
  -2.0       4.0   0.0002    0.000913          4.0846    1.0729
  -5.0       7.0   0.0002    0.000324          1.5993    1.2986
  -8.0      10.0   0.0001    0.000137          1.0781    1.4658
  

One gradient vanishes, one is arbitrary, one stays near 1

The previous page's three gradient columns on a log scale (the third is a WGAN-GP critic's, next page):

1010.10.010.0010.00010246810distance between the cloudssize of the gradient on μnon-saturating, −log DWGAN-GP criticsaturating, log(1 − D)about four orders of magnitude
  • Saturating: once \(D(\text{fake})\) drops to 0.0006, the gradient collapses, four orders of magnitude from overlap to separation.
  • Non-saturating: rescues the size (1.1 to 5.7), but the size is set by \(D\)'s logit slope at the fakes, which is not a measure of the distance.
  • WGAN-GP critic: within a factor of 1.5 of 1 at every distance.

WGAN trains a critic whose slope is at most 1

The Wasserstein GAN (Arjovsky, Chintala & Bottou, ICML 2017) replaces JS with the Wasserstein-1 distance, the least cost of moving \(G\)'s probability mass onto the data's (moving mass twice as far costs twice as much; for two clouds of the same shape it is the distance between them). It changes smoothly with the gap, so its gradient stays informative at any distance (the previous page's green line):

  • \(D\) becomes a critic \(C\): no sigmoid, real-valued scores, trained to maximize \(\mathbb{E}[C(\text{real})]-\mathbb{E}[C(\text{fake})]\) over 1-Lipschitz functions (slope never above 1); without that constraint the maximization diverges. \(G\) then minimizes \(-\mathbb{E}[C(G(\mathbf{z}))]\).
sigmoid Dcritic C, slope 1fakes, −8data, +2fakes, −8data, +2flat at the fakes:slope near 0D = 1slope 1 atthe fakes tooSchematic, not trained networks: the fakes 10 from the data, as in the gradient table.

WGAN-GP holds the critic's slope near 1 with a gradient penalty

The critic must stay 1-Lipschitz (previous page). Two ways to enforce it:

  • The paper clipped every weight into a small range \([-c, c]\). WGAN-GP (Gulrajani et al., NeurIPS 2017) adds a gradient penalty: the critic's gradient norm is pushed toward 1 at points between real and fake:

# real: the cluster at +2; fake = mu_val + eps; C: the critic, an MLP without a sigmoid
a = torch.rand(512, 1)                                       # (512, 1), uniform in [0, 1)
x_hat = (a * real + (1 - a) * fake).requires_grad_(True)     # between real and fake
# create_graph=True keeps this gradient differentiable: loss.backward() must reach it
# .sum(): each score depends only on its own row, so the gradient holds each row's slope
# autograd.grad returns a tuple, one gradient per input; [0] is the one for x_hat
grad = torch.autograd.grad(C(x_hat).sum(), x_hat, create_graph=True)[0]  # (512, 1)
gp = ((grad.norm(2, dim=1) - 1) ** 2).mean()                 # norms: (512,)
loss = C(fake).mean() - C(real).mean() + 10.0 * gp
  
  • The critic minimizes loss: the previous page's objective with its sign flipped, plus 10 times the penalty.

Spectral normalization sets every layer's top singular value to 1

Another way to bound the slope (Miyato et al., ICLR 2018): divide each weight matrix by an estimate of its top singular value \(\sigma_{\max}\), the most it can stretch an input. Reading 4.2 on the two-mode demo (seed 0), after 2,000 steps of Part 1's loop (near −2, near +2: the shares of \(G\)'s samples):


# layers: the demo D's five layers; spectral: True for the second run
if spectral:
    layers = [nn.utils.spectral_norm(l) if isinstance(l, nn.Linear) else l
              for l in layers]
  
discriminatornear −2near +2\(\sigma_{\max}\) of its three weightssteepest slope of \(D\)'s logit on a grid from −6 to 6
plain0.4710.4343.58, 2.03, 0.971.657
spectral-norm0.4450.4631.00, 1.00, 1.000.323
  • Per layer: weights (32, 1), (32, 32), (1, 32). ReLU never steepens a slope, so stacked layers multiply at most their \(\sigma_{\max}\): \(3.58\cdot2.03\cdot0.97\approx7.0\); normalized, at most 1. \(\sigma_{\max}\) is estimated by power iteration (repeated multiplication).
  • Coverage is about the same: two modes are too easy to show a stability difference.

Self-check on two separated clouds and the gradient table

Two questions on Part 3.

(a) The fake samples and the real data do not overlap. What is the JS divergence between them? The fakes then move halfway toward the data and still do not overlap. What is JS now?

(b) In slide 33's experiment, moving the fakes from distance 0.5 to distance 10 changes the saturating loss's gradient from 1.738256 to 0.000137, and the critic's gradient from 0.9699 to 1.4658. How many times smaller does the first become? How many times larger the second?

(a) \(\log2\) both times: JS does not change, so it gives \(G\) no direction.

(b) About 12,700 times smaller (\(1.738256/0.000137\)), four orders of magnitude. About 1.5 times larger (\(1.4658/0.9699\)).

A perfect \(D\) stops teaching under the original loss; a slope-bounded critic does not.

No likelihood to report, so the samples are scored

Part 4 · Evaluation. The losses do not measure sample quality (Part 2), and a held-out likelihood is not available:

  • A GAN is an implicit model: it samples, but gives no tractable likelihood \(p_g(\mathbf{x})\). S23's VAE optimizes a likelihood bound.
  • Inception Score (Salimans et al., 2016): a pretrained ImageNet classifier (the Inception network, which gives both scores their name) rewards samples that are each confidently classified and diverse as a set. It never looks at the real data. Higher is better.
  • FID (Heusel et al., 2017) does: embed real and generated samples with a pretrained network, fit a Gaussian to each feature set, and compare the two Gaussians.

FID is a distance between the two fitted Gaussians

Each feature set is summarized by its mean and its covariance:

\(n\) samplesfeatures, \(d\) eachmeancovariance
real(n, d)\(\boldsymbol{\mu}_r\), (d,)\(\Sigma_r\), (d, d)
generated(n, d)\(\boldsymbol{\mu}_g\), (d,)\(\Sigma_g\), (d, d)
\[\mathrm{FID}=\lVert\boldsymbol{\mu}_r-\boldsymbol{\mu}_g\rVert^2+\operatorname{tr}\big(\Sigma_r+\Sigma_g-2(\Sigma_r\Sigma_g)^{1/2}\big)\]
  • The first term is the squared distance between the means. \(\operatorname{tr}\) is the trace, the sum of a matrix's diagonal, and \((\cdot)^{1/2}\) the matrix square root.
  • With one feature (\(d=1\)): \(\mathrm{FID}=(\mu_r-\mu_g)^2+(\sigma_r-\sigma_g)^2\), the two means compared and the two standard deviations compared.

Lower is better; 0 when the two fitted Gaussians match. FID 0 means the fitted Gaussians have the same mean and covariance; it does not prove the distributions are identical.

Precision and recall show what one FID number can hide

Reading 4.2's caveats: FID is biased at small sample counts (the convention is 50,000), depends on the embedding network, and puts two failures into one number:

collapsed (like step 250)−2+2looks real: high precisionmisses +2: low recallblurry−2+2reaches both modes: higher recallbetween them: lower precisionGrey outline: real data; blue: G's samples.
  • Kynkäänniemi et al. (NeurIPS 2019) measure the two failures separately: precision, are the generated samples realistic? Recall, is all of the data covered?
  • FID has run-to-run variance: recompute it on other sample draws before believing a small improvement (S27).

Self-check on a missing likelihood, two FIDs and step 250

Three questions on Part 4.

(a) Why can't you report a GAN's held-out log-likelihood, as you would a VAE's bound?

(b) Checkpoint A scores FID 12.4 and checkpoint B 12.1, one sample draw each. Is B better?

(c) The ring at step 3000: all 8 modes covered, a third of the samples between modes. Which is lower, precision or recall?

(a) It is an implicit model: it samples, but gives no \(p_g(\mathbf{x})\) to evaluate.

(b) Not shown: the difference may be inside FID's run-to-run variance. Recompute on several draws at the same sample count.

(c) Precision: the samples between modes look like no real data, while every mode is reached.

Judge samples, not losses, and check a small FID gain against FID's spread over draws.

What became of GANs

Part 5 · History. For about six years, GANs led image generation (reading 4.2):

20142016201720192021GAN (NeurIPS)DCGAN (deep convolutional GAN, ICLR):conv guidelines, reproducible trainingWGAN (ICML):smoother objectiveStyleGAN (CVPR): faceshard to tell from photosBigGAN (ICLR): class-conditional ImageNetstill used where one forward passmatters: real-time super-resolution(upscaling a low-resolution image),restoration, speech, distillationinside diffusion pipelines“Diffusion Models Beat GANs on Image Synthesis”(Dhariwal & Nichol, NeurIPS 2021)flagship generatorssince: diffusionGAN: one forward passnaive diffusion: hundreds…
  • Each milestone was engineering against the instability you just watched.
  • Diffusion trains with a plain regression loss and no game, so it is stable, and its objective gives more pressure than the GAN game to cover every mode, though no guarantee.
  • A GAN generates in one forward pass, while naive diffusion removes noise step by step and needs hundreds (S25).

The adversarial loss survives as one term of a larger loss

Where a plain per-pixel loss gives plausible but soft output, an adversarial term adds the sharpness (reading 4.2). A conditional GAN (Mirza & Osindero, 2014) first gave both networks a label: \(G(\mathbf{z},y)\) makes class \(y\), \(D\) judges (sample, label) pairs. pix2pix (2017) does image-to-image translation (an edge map to a photo, say) from paired images:

input xGoutput ŷL1: mean absolute pixel errorpaired target ythe pair (x, ŷ)Djudges it against the real pair (x, y)G's loss: the adversarial loss + λ · L1, λ a fixed weight
later workwhat the adversarial loss is used for
CycleGAN (2017)translation without pairs, with a round-trip (cycle-consistency) loss
SRGAN (super-resolution GAN, 2017)super-resolution, for the texture that MSE-trained models blur
HiFi-GAN (2020)speech: spectrograms to waveforms in real time
adversarial diffusion distillation (2023)a diffusion sampler cut from many steps to one to four

The adversarial loss survives as a sharpness term inside larger losses.

Self-check on fast super-resolution and two loss terms

Two questions on Part 5.

(a) A product needs super-resolution in real time. Would you use a GAN or a naive diffusion sampler, and why?

(b) pix2pix trains with L1 plus an adversarial loss. What does each term supply?

(a) A GAN: one forward pass, against hundreds of steps.

(b) L1: the target's content. Adversarial: the sharpness that per-pixel regression averages away.

GANs survive where one forward pass or a sharpness term matters.

Six mistakes in your own GAN runs, each with its cause and its fix

Part 6 · Close. Reading 4.2's common pitfalls:

symptomcausefix
ordinary-looking losses taken as good traininglosses measure the game state, not sample quality (steps 0 and 250)track a sample statistic (mode counts, FID) at regular intervals
samples all near-identicalmode collapse: \(G\) wins by sending every sample where \(D\) is weakest (Part 2)no single fix: lower learning rates, more \(D\) steps per \(G\) step, a Wasserstein objective; detect it with coverage
\(G\)'s loss climbs, samples stop improving\(D\) too strong; under the saturating loss \(G\)'s gradient vanishesthe non-saturating loss; a smaller or slower \(D\); label smoothing (real labels 0.9)
losses blow up in the first few hundred stepslearning rates tuned for one loss; Adam's beta1 = 0.9 adds momentum that destabilizes the gameabout 2e-4 with betas = (0.5, 0.999), as in the demo
no progress from the first steps, \(G\)'s loss flatthe saturating loss against a \(D\) that already wins (Part 3's 0.0001)the non-saturating loss, or a WGAN-GP critic kept well trained
a checkpoint called better for a slightly lower FIDFID's run-to-run variancefix the sample count; recompute over independent draws

Today's answer, clause by clause

Back to the title page's question.

  • How they train each other: \(D\) classifies real against fake; \(G\) is trained to make \(D\) say real. For a fixed \(G\), \(D^*=p_{\text{data}}/(p_{\text{data}}+p_g)\); at equilibrium \(D\)'s loss is \(2\log2\).
  • Why it collapses: each player answers the other's current state, so \(G\) can put all its mass where \(D\) accepts it now. Coverage counts show it; the losses do not.
  • Why a winning \(D\) stops teaching: against the best \(D\), \(G\)'s original loss is a JS divergence, stuck at \(\log2\) without overlap. A critic with bounded slope keeps the gradient informative.
  • How to judge samples: sample statistics such as FID, or precision and recall.
  • What became of GANs: diffusion took over; the adversarial loss stays as a component.

For next time

  • Next session (S25), Wednesday: diffusion models, trained with a plain regression loss and no game.
  • Read: 4.3 Diffusion Models.
  • Then Fall Recess: no class next week; we resume at S26.