GANs and Wasserstein GANs: the optimal discriminator, training dynamics and
Before this lesson: lesson 01 (maximum likelihood as a KL divergence) and lesson 04 (models with an exact likelihood; a GAN gives that up). From other tracks: the KL divergence and f-divergences, the convex conjugate and critics (information theory), duality and stochastic gradient descent (optimization), and the spectral norm (linear algebra). Time: about 95 minutes, plus the notebook.
Why this matters #
A GAN learns to sample without a density. This made GANs the leading image generators from 2014 to about 2021 (DCGAN, StyleGAN, BigGAN). They are still in use. The autoencoder of latent diffusion models (Stable Diffusion) is trained with an adversarial loss, so the latent space of lesson 13 is shaped by a GAN. Few-step diffusion samplers use discriminators (lesson 12). In science, GANs were used for precipitation nowcasting and for seismic ground-motion synthesis before diffusion models.
The ideas of this lesson also go far beyond GANs. "Train a classifier and read off the density ratio" is the basis of neural ratio estimation in physics. The Wasserstein distance and Lipschitz critics come back in optimal transport and flow matching (lesson 10). The questions "what does the discriminator learn?", "why does the gradient vanish?" and "why does WGAN help?" are standard interview questions.
1. Predict first #
2. The picture #
The simplest case: three outcomes. A sample can take three values. The data distribution is . The generator currently produces . Real and fake samples come in equal numbers. A discriminator sees one sample and must say "real" or "fake". The best it can do is to compare the two probabilities of :
- outcome 1 is three times more likely under the data, so it says "real" with probability ;
- outcome 2 is equally likely under both, so it says ;
- outcome 3 never occurs in the data, so it says .
In odds, . A perfect discriminator is a density-ratio estimator. The generator reads this ratio and moves probability from outcome 3 (ratio 0) toward outcome 1 (ratio 3).
The same in 1D. In the figure, the data are the track's two Gaussians and the generator is one Gaussian. The lower panel shows the best discriminator at every point.
Drag the orange peak (or use the sliders) to move and widen the generator density . The data density is fixed. The black curve is the optimal discriminator : it is where the two densities are equal, close to 1 where only the data have mass, and close to 0 where only the generator has mass. Move the yellow probe and compare with . Choose "far generator": JSD gets close to and is flat near the generator.
The generator only sees the slope of at its own samples. A sample is . The generator changes to raise at . By the chain rule,
is the Jacobian of the sample with respect to the generator weights. So each sample moves in the direction where increases. If is flat at the sample, and the generator learns nothing from it.
When the supports do not overlap. Real images lie near a thin, low-dimensional set in pixel space. A generator with a low-dimensional input produces another thin set. Two thin sets in a high-dimensional space almost never overlap. Then a discriminator can separate them perfectly: on the data, on the fakes, and is flat near both. No gradient.
A distance that sees how far apart. Think of and as two piles of sand. The Wasserstein-1 distance is the least total work (mass times distance moved) needed to turn one pile into the other. If the generator's pile is 0.1 away, ; if it is 1 away, . The Jensen–Shannon divergence is in both cases, because it only asks whether the piles overlap.
The data are and the generator gives . What is the optimal discriminator on the three outcomes?
at each outcome: , , . Outcome 2 is only produced by the data, so a sample there is surely real. The first option ignores that compares the two densities point by point.
3. Definitions and main results #
The GAN game #
Notation. Noise (for example ) goes through the generator . The distribution of is . We can sample from it, but we cannot evaluate it (for it has no density at all). The discriminator outputs a logit and , the probability that is real, where is the logistic sigmoid. The value function is
The game is .
is the binary cross-entropy of a classifier with label 1 for real and 0 for fake, so the step is logistic regression. Because for any function , the second term is .
The Jensen–Shannon divergence (JSD) of and uses their average :
It is symmetric, always finite, between and , and only when .
Theorem (optimal discriminator; Goodfellow et al. 2014). For a fixed ,
The global minimum of is , reached only at .
Why this is true, in one sentence. The discriminator can choose its answer separately at every point, and at each point the best answer is the share of real samples there; putting that answer back into gives two KL divergences to the average density.
Proof.
- Write as one integral. can be chosen separately at every , so we maximize the integrand point by point:
- For , not both 0, the function is concave on (with ). For its derivative is zero at . For the maximum is at , for at ; the same formula. With and this is .
- Let . Then and . Substitute:
- By the definition of JSD, .
- , with equality only if . There everywhere and .
Assumptions. can be any function (infinite capacity), both distributions have densities, and the inner maximization is solved for each . In practice none of these holds exactly: is a network trained for a few steps per generator step. So the theorem describes the target of the game, not what each training step does.
Saturating and non-saturating generator losses #
Write for the logit of a fake sample. Use the softplus function and the identities and . These forms stay finite for any .
| Generator minimizes | As a function of | Derivative in | At |
|---|---|---|---|
| saturating (minimax): | |||
| non-saturating: |
Both derivatives are negative, so both losses push up. But when confidently rejects the fakes (), the saturating gradient is about : it vanishes exactly when the generator is worst. The non-saturating loss "flips the label instead of the sign" and keeps a gradient near . The ratio of the two gradients is , which is at .
Move the logit of a fake sample. Top: the saturating and the non-saturating generator losses. Bottom: the size of their gradients on a log scale. At (the discriminator is sure the sample is fake) the saturating gradient is and the non-saturating one is almost 1. At the two are equal.
The non-saturating game is no longer zero-sum, but it has the same fixed point (, ). With the optimal , its expected generator gradient equals (Arjovsky and Bottou 2017, Theorem 2.5). The reverse KL in it is mode-seeking: it punishes fakes where there are no data, but it barely punishes a missing mode (see forward and reverse KL).
The discriminator gives a fake sample . What is the ratio of the non-saturating gradient to the saturating gradient, both with respect to the logit?
. The saturating gradient is and the non-saturating one is . The ratio is . The same fixed point does not mean the same gradient away from it; 4.6 is , not .
Disjoint supports: why JSD gives no gradient #
If and live on disjoint sets, then on the data's set , so . The same holds for . Hence for every such : the loss is constant, and its gradient is zero.
This is the normal case, not a corner case. lives on , a set of dimension at most . If both sets have lower dimension than and do not line up exactly, their intersection has probability zero under both distributions. Then a perfect discriminator exists that is smooth and constant near both sets (Arjovsky and Bottou 2017, Theorems 2.1–2.2). As approaches it, the saturating gradient goes to zero, and the non-saturating gradient becomes unstable.
Training dynamics: the Dirac-GAN #
Even when the gradients do not vanish, gradient play on a game is not gradient descent on one function. The cleanest example is the Dirac-GAN (Mescheder, Geiger and Nowozin 2018):
- the data are a point mass at ;
- the generator is a point mass at (one number);
- the discriminator is linear, with logit (one number).
The value function is . The unique equilibrium is (the generator matches the data), (the discriminator cannot tell). The generator descends in , the discriminator ascends in . The game vector field is
Step 1: linearize at the equilibrium. At , , so the Jacobian of the field is
Purely imaginary eigenvalues mean rotation: the continuous field circles the equilibrium and never comes closer.
Step 2: simultaneous steps. Both players step from the old point: . Near the step matrix is , with eigenvalues and modulus . Every step makes the distance to the equilibrium a little larger: the iterates spiral out, for every step size.
Step 3: alternating steps. The generator steps first, and the discriminator then uses the new . The linearized step matrix is . Its determinant is exactly 1, and for its eigenvalues lie on the unit circle. The iterates go around a closed curve: they do not diverge, but they never converge.
Step 4: a gradient penalty. The R1 penalty (Mescheder et al. 2018) adds to the discriminator loss. Here , so the discriminator now maximizes and . The Jacobian becomes , with eigenvalues . Their real part is negative, so small enough steps converge.
Numbers (checked in section 5): from with , after 2000 steps the distance to is for simultaneous steps, stays near for alternating steps, and is below with R1 and .
Press "Run 1000 steps" and watch the iterates spiral out from the start point along the game vector field. Then switch to "alternating": the path closes on itself. Then choose "simultaneous + R1": the path spirals in. The readouts give the eigenvalues of and the growth factor per step near ; the chart below shows the distance to on a log scale. Drag the start point to try other starts.
In the Dirac-GAN without a penalty, you halve the step size of simultaneous gradient steps. What happens?
The growth factor per step near is , which is larger than 1 for every . Small steps follow the continuous field, and the continuous field only rotates (eigenvalues ); the discretization adds a small outward push at every step. Convergence needs a change to the game, such as a gradient penalty.
Mode collapse #
Mode collapse means that the generator maps many values of to one or a few modes of the data: samples look good, but they have low diversity. Partial collapse (the same texture or the same pose again and again) is common.
Why it happens: fix . The generator's best response is to send every to , a point mass. The discriminator then learns to reject that point, and the generator jumps to the next maximum: mode hopping. Gradient steps on both players do not clearly solve ; they often behave like , whose inner problem is exactly this point mass (Goodfellow 2016, §5.1.1). The Dirac-GAN shows the same kind of cycling in one dimension.
Press Play. The real data are the track's 8 Gaussians. Each generator sample moves along of the discriminator logit, the only signal a generator gets. The background shows where says "real" (blue) or "fake" (orange). Then choose the "Gaussian" generator , which is too simple for 8 modes: it collapses to a small blob that travels around the ring. "Freeze D" lets the generator answer a fixed discriminator: the samples pile up at a few maxima of .
Remedies: let see batch statistics (minibatch discrimination, the minibatch standard-deviation feature), unrolled GANs, smoother critics (WGAN-GP, spectral normalization, the R1 penalty), two time-scale learning rates, and class conditioning. Measure coverage with recall (lesson 14), not with the loss.
f-GAN: a variational bound for any f-divergence #
For a convex function with , the f-divergence is (KL is ). The convex conjugate of is .
Theorem (f-GAN bound; Nguyen, Wainwright and Jordan 2010; Nowozin et al. 2016). Assume wherever . For every function ,
For differentiable , equality holds at .
Proof.
- From the definition of : for all , so (the Fenchel–Young inequality). Equality holds when .
- Use it at each with and , and multiply by : .
- Integrate over : for every . A sup over a critic network gives a lower bound; it is tight if the network can represent .
- Step 1 is an equality at every when .
KL. For , setting the derivative of to zero gives , so and . The bound is , with .
The GAN. With and , the bound becomes , and . This has , not 0; the proof above never uses , so the bound still holds. The message: every such critic estimates a function of the density ratio . The details for all common are in information theory, lesson 08.
Wasserstein-1 and the Kantorovich–Rubinstein dual #
A coupling is a joint distribution of whose marginals are and : a plan that says how much mass moves from each to each . The Wasserstein-1 distance is the cost of the cheapest plan:
In 1D, with the cumulative distribution functions ; for point masses at 0 and this is . A function is 1-Lipschitz () if for all .
Theorem (Kantorovich–Rubinstein duality). For with finite first moments,
Proof of the easy half ().
- Take any coupling and any 1-Lipschitz . Because has marginals and , .
- The Lipschitz condition gives , so this is at most .
- Take the sup over on the left and the inf over on the right.
Equality is the Kantorovich–Rubinstein theorem: strong duality of the transport linear program (see duality).
Why 1-Lipschitz. Without a constraint the sup is for any : multiply a good by 100. The Lipschitz bound says the critic can charge at most for mass moved from to , which ties its value to the transport cost. A -Lipschitz bound gives , which is fine for training.
WGAN (Arjovsky, Chintala and Bottou 2017). The critic (no sigmoid, no log) maximizes ; the generator minimizes . Under mild conditions, with the optimal critic (their Theorem 3).
The parallel-lines example #
Let , let be the law of and the law of : two parallel segments at horizontal distance .
- . Upper bound: the coupling moves every point by . Lower bound: the 1-Lipschitz critic gives .
- For the supports are disjoint: , (both directions), and the total variation distance is 1. All three are 0 at .
Only is continuous in . Its derivative points to the answer. The others are flat (or infinite) and then jump at .
Move the shift . The data segment stays at ; the model segment moves. The magenta arrows are the transport plan. In the chart, JSD stays at for every , while shrinks as the segments get closer. Add instance noise : the supports now overlap and JSD becomes smooth too, but it is still almost flat far from .
For the parallel segments, what are JSD and at ?
For any the two segments do not overlap, so JSD takes its maximum , the same as at . is the transport cost: every point moves by . Only tells the generator that it got closer.
Making the critic 1-Lipschitz #
| Method | What it does | Weak points |
|---|---|---|
| Weight clipping (WGAN: , RMSProp, ) | clip every weight to ; a bounded weight set gives some unknown constant | the critic uses its capacity badly (too simple functions); gradients vanish or explode depending on |
| Gradient penalty (WGAN-GP) | add at , , real, fake | soft and local only; needs double backpropagation; invalid with batch norm in the critic |
| Spectral normalization | divide each weight matrix by its largest singular value (one power-iteration step per update) | the bound is loose, so the critic can be far below 1-Lipschitz |
- Why interpolates. A differentiable is 1-Lipschitz exactly when everywhere, and that cannot be enforced everywhere. The optimal critic has gradient norm 1 along the straight lines between points coupled by the optimal transport plan (Gulrajani et al. 2017, Proposition 1), so the penalty samples points on lines between real and fake samples.
- WGAN-GP defaults: , , Adam with learning rate , , . The penalty is per sample and batch norm mixes samples, so use layer norm or no normalization in the critic.
- Double backpropagation. The penalty contains , so its gradient with respect to the
critic weights differentiates a gradient (in PyTorch:
torch.autograd.grad(..., create_graph=True)). - Why spectral normalization works. The spectral norm is the Lipschitz constant of . With 1-Lipschitz activations (ReLU, leaky ReLU), . It is cheap, and it also stabilizes ordinary discriminators.
Why the R1 penalty and WGAN-GP are different
R1 penalizes on real data only and pushes it toward 0. Near the equilibrium, where the generator matches the data, a discriminator with zero slope on the data is exactly what we want, so R1 does not move the equilibrium; it only damps the rotation of the game (the in the Jacobian above). WGAN-GP pushes the gradient norm toward 1 on interpolates, because the optimal Wasserstein critic has slope 1 along transport lines. StyleGAN2 and many modern GANs use the non-saturating loss with R1.
Answers to section 1. (1) The gradient is : almost zero. This is why the non-saturating loss is used. (2) for both and ; and . Only tells the generator that it got closer. (3) They move away: simultaneous steps multiply the distance by per step near the equilibrium. Alternating steps circle, and only a penalty such as R1 makes them converge.
4. Worked example #
(a) Optimal discriminator. and .
- on each outcome: , and .
- is plus . The term counts as 0:
- The average is . Then and (the terms with ratio 1 are 0).
- JSD is the mean of the two KL values: .
- Check: and . The sum is . ✓
(b) f-GAN bound for KL on the same pair (, ).
- (the second term is ).
- The optimal critic is . On the three outcomes: , and . On outcome 3 it must be , because never visits it.
- A real network outputs a finite value there. Take . Then .
- , which is .
- The bound is . It is below KL. The gap is exactly the term that the finite value adds.
(c) A Wasserstein critic for two Gaussians. and with and .
- Translation by is a coupling that moves every point by , so .
- The linear critic with is 1-Lipschitz and has value (Cauchy–Schwarz), with equality at . So .
- Now use the gradient penalty with instead of the hard constraint, and let the critic be . Its gradient norm is everywhere, so the penalized objective is .
- Set the derivative to zero: , so , and the value is .
- In general, for a linear critic and two distributions that differ by a shift of length , and the value is . A soft penalty lets the gradient norm go above 1 and overestimates a little. An unconstrained would pay the penalty .
In example (c), the shift has length and you use instead of 10. What is the penalized value at the best ?
and the value is . A larger moves the soft constraint closer to the hard one, but never makes it exact. is the value for .
5. In code #
NumPy and SciPy check the numbers of sections 3 and 4: the optimal discriminator, the logit gradients (against finite differences), the Dirac-GAN, and the exact of the parallel segments (an optimal assignment between equal-size samples is an optimal transport plan).
import numpy as np
from scipy.special import expit as sigmoid, rel_entr
from scipy.spatial.distance import jensenshannon
from scipy.optimize import linear_sum_assignment
# (a) optimal discriminator, V(D*) and JSD for the three-outcome example
p = np.array([0.6, 0.4, 0.0]) # p_data
q = np.array([0.2, 0.4, 0.4]) # p_g
D = p / (p + q)
V = rel_entr(p, p + q).sum() + rel_entr(q, p + q).sum() # sum p log D* + sum q log(1 - D*)
jsd = jensenshannon(p, q) ** 2 # SciPy returns the square root of JSD
print(D, round(V, 6), round(-np.log(4) + 2 * jsd, 6))
# [0.75 0.5 0. ] -1.004386 -1.004386
# (b) generator-loss gradients with respect to the logit l, checked by finite differences
softplus = lambda u: np.logaddexp(0.0, u)
sat = lambda l: -softplus(l) # log(1 - sigmoid(l))
ns = lambda l: softplus(-l) # -log sigmoid(l)
l, h = -8.0, 1e-6
for f, exact in [(sat, -sigmoid(l)), (ns, -sigmoid(-l))]:
print(f"{exact:.6f} {(f(l + h) - f(l - h)) / (2 * h):.6f}")
# -0.000335 -0.000335
# -0.999665 -0.999665
# (c) Dirac-GAN: simultaneous vs alternating gradient steps from (theta, psi) = (1, 0)
def dirac(eta=0.1, n=2000, alternating=False, gamma=0.0):
th, ps = 1.0, 0.0
for _ in range(n):
g_th = ps * sigmoid(ps * th) # -dV/dtheta (generator descends V)
if alternating:
th = th + eta * g_th
g_ps = -th * sigmoid(ps * th) - gamma * ps # dV/dpsi minus the R1 term (discriminator ascends)
if not alternating:
th = th + eta * g_th
ps = ps + eta * g_ps
return np.hypot(th, ps)
print(round(dirac(), 2), round(dirac(alternating=True), 2), dirac(gamma=1.0) < 1e-10)
# 3.05 0.99 True
# (d) parallel lines: exact W1 between 200 + 200 samples (optimal assignment)
u = (np.arange(200) + 0.5) / 200
for theta in [1.0, 0.1]:
a = np.stack([np.zeros(200), u], 1)
b = np.stack([np.full(200, theta), u], 1)
C = np.linalg.norm(a[:, None] - b[None], axis=2)
r, c = linear_sum_assignment(C)
print(theta, round(C[r, c].mean(), 4))
# 1.0 1.0
# 0.1 0.1
The notebook adds the continuous version of (a) by quadrature, of 1D samples by sorting, a WGAN-GP critic trained by gradient ascent, and an optional tiny GAN on the 8 Gaussians in PyTorch.
6. Where it shows up #
- Adversarial losses inside other generators. The autoencoder of latent diffusion is trained with a perceptual loss plus a patch-based adversarial loss (Rombach et al. 2022, §3.1), so the latent space of lesson 13 was shaped by a GAN loss. Adversarial diffusion distillation uses a discriminator to get samplers with 1–4 steps (lesson 12). StyleGAN-type models use the non-saturating loss with the R1 penalty.
- Super-resolution and image-to-image translation. SRGAN, pix2pix and CycleGAN add an adversarial loss to a reconstruction loss. The adversarial part makes the output sharp; the reconstruction part keeps it faithful to the input.
- Weather and climate. DGMR (Ravuri et al., Nature 2021) nowcasts precipitation with a conditional GAN that has a spatial and a temporal discriminator. In an ensemble, mode collapse means an under-dispersed ensemble: the spread is too small, and the CRPS and the rank histogram show it (lesson 14). This is one reason recent ensemble weather models use diffusion.
- Seismology. Florez et al. (BSSA 2022) generate three-component accelerograms with a conditional Wasserstein GAN, conditioned on magnitude, distance and . The same task is now also done with (latent) diffusion and flow models.
- Density ratios in science. "Train a classifier, read off " also drives neural ratio estimation for likelihood-free inference in particle physics and cosmology.
7. Common mistakes #
log(sigmoid(l))in code. It gives or NaN for large . Use the softplus forms or a fused "binary cross-entropy with logits" function.- Not detaching the fakes in the discriminator step. Then the loss also sends gradients into : wasted compute, and wrong updates if those gradients are not zeroed before the step.
- Reading as what training minimizes. It holds only for the optimal , and the non-saturating loss is a different game with the same fixed point.
- Expecting gradient play to converge like gradient descent. A game has a vector field, not a loss surface. Its Jacobian can have imaginary eigenvalues (the Dirac-GAN), and then plain gradient steps rotate or spiral out. A smaller learning rate does not fix this.
- A sigmoid or a log on the WGAN critic. The critic outputs unbounded scores; the losses are plain means.
- Gradient-penalty slips. The penalty uses (with respect to the inputs, not the weights), and batch norm in the critic breaks the per-sample penalty.
- Using the GAN loss as a quality metric. Discriminator and generator losses oscillate and say little about sample quality or coverage. Use FID, precision and recall (lesson 14).
- Blaming mode collapse only on JSD. GANs that approximate collapse too (Goodfellow 2016, §5.1.1); the game dynamics matter as much as the divergence.
8. Check yourself #
- and have disjoint supports. Give , , and the generator gradient
of the saturating loss near the samples.
Answer
on the data support and on the generator support. , so , the same for every disjoint . is constant near the samples, so and the generator gets no gradient. - The data are three equal modes, , and the generator
collapses to the first: . Compute JSD, and
. Which one punishes the collapse most?
Answer
; , which is , , so . Reverse KL: (finite). Forward KL: , because where the data have mass. Forward KL (maximum likelihood) punishes the collapse most; reverse KL and JSD give finite penalties (JSD is at most ). - In the Dirac-GAN with simultaneous steps, compute the growth factor per step near for
, and estimate the distance after 100 steps from a start at distance .
Answer
. Near the linearization is accurate, so after 100 steps the distance is about . Far from the sigmoid factor changes and the growth slows down (the full nonlinear run from distance 1 reaches only 3.05 after 2000 steps). - In the KL bound, use the critic for a constant . Show that the bound equals
, and conclude where it is tight.
Answer
, because . And . So the bound is . Since , it is at most KL, with equality only at . - A ReLU critic has three layers with spectral norms 2, 0.5 and 3. Give a Lipschitz bound before and
after spectral normalization. Can the true constant be smaller?
Answer
Before: . After: . Yes: the bound is tight only if the top singular directions of consecutive layers line up and the ReLUs pass them unchanged. Usually neither holds, so the true constant is often much smaller than the product. - Why is the WGAN-GP penalty evaluated on random interpolates between real and fake samples, and not
only on real data or on a fixed grid?
Answer
The optimal critic has unit gradient norm along the straight lines between optimally coupled real and fake points (Gulrajani et al., Proposition 1). Enforcing everywhere is impossible in high dimension. Lines between real and fake samples are a cheap proxy for the region where the constraint is active (the pairs are random, not optimally coupled), and they move with the generator during training. Real data alone would leave the region between the two distributions unconstrained.
What is the optimal discriminator of the original GAN game for a fixed generator?
. Its odds are the density ratio .
What is in terms of a divergence, and its minimum?
; the minimum is reached only at .
What are the gradients of the saturating and the non-saturating generator loss with respect to the logit of a fake?
Saturating : . Non-saturating : . At : vs .
Why does JSD give no gradient when the data and the generator have disjoint supports?
Then on each support, so JSD for every such generator; the loss is constant and is flat near the samples.
What is mode collapse?
The generator maps many noise values to one or a few modes of the data, so samples look good but have low diversity.
Why do simultaneous gradient steps not converge in the Dirac-GAN?
The Jacobian at the equilibrium has eigenvalues (pure rotation); the step matrix has modulus , so the iterates spiral out.
State the f-GAN lower bound and its optimal critic.
for every , with equality at ; it follows from Fenchel–Young.
State the Kantorovich–Rubinstein dual of .
, a sup over 1-Lipschitz critics.
What is the WGAN-GP penalty, and where is it evaluated?
with , at random interpolates between real and fake samples.
For two parallel segments at distance , what are JSD and ?
for every ; .
9. Interview angle #
- "What does the discriminator learn at the optimum?" , so is the density ratio. The game then minimizes .
- "Why the non-saturating loss?" The minimax gradient with respect to the logit is when rejects fakes; the non-saturating one is . Same fixed point.
- "Why is GAN training unstable?" Three reasons: the divergence can be flat (disjoint supports), the game dynamics rotate (imaginary eigenvalues; the Dirac-GAN), and the best response to a fixed is a point mass (mode collapse).
- "Why does WGAN help?" is continuous in the generator parameters even for disjoint supports (parallel lines), so the critic gives a useful gradient and a loss that tracks progress.
- "How do you enforce the Lipschitz constraint?" Clipping (crude), a gradient penalty on interpolates (, no batch norm), spectral normalization (cheap, loose bound).
- "GAN or diffusion for an ensemble forecast?" A GAN needs one network pass per sample, but it can collapse modes and give an under-dispersed ensemble. Diffusion trains by stable regression and covers modes better, at the cost of many network evaluations per sample.
- "How do you detect mode collapse?" Recall or coverage metrics, nearest training neighbors, counting modes on a toy mixture, class histograms with a pretrained classifier.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution, and an optional PyTorch demonstration:
- , the value and JSD for discrete distributions; then the same identity for two 1D densities by quadrature.
- Saturating and non-saturating losses and their gradients in the logit, written in a stable form.
- The Dirac-GAN: simultaneous, alternating and R1 steps; plot the three trajectories.
- The f-GAN bound for KL: write the bound for a critic vector and find the critic that makes it equal to KL.
- of two 1D samples by sorting, and the WGAN-GP optimum of a linear critic, .
- Optional (PyTorch): a tiny GAN on the 8 Gaussians; count the covered modes during training.
11. Watch and read #
- Goodfellow et al., Generative Adversarial Networks (2014), §4.1: Proposition 1 and Theorem 1 ( and ).
- Goodfellow, NIPS 2016 Tutorial: Generative Adversarial Networks: §3.2 (cost functions, the non-saturating game), §5.1 (non-convergence and mode collapse), §8.2 (gradient descent on ).
- Mescheder, Geiger and Nowozin, Which Training Methods for GANs do actually Converge? (ICML 2018): the Dirac-GAN and the R1 penalty.
- Nowozin, Cseke and Tomioka, f-GAN: Training Generative Neural Samplers using Variational Divergence Minimization (2016).
- Arjovsky, Chintala and Bottou, Wasserstein GAN (2017): Example 1 (parallel lines) and Theorem 3; Gulrajani et al., Improved Training of Wasserstein GANs (2017): Proposition 1 and Algorithm 1; Miyato et al., Spectral Normalization for Generative Adversarial Networks (2018).
- Murphy, Probabilistic Machine Learning: Advanced Topics, free PDF: chapter 26 (§26.2 density ratios and divergences, §26.3 training challenges).
- Lilian Weng, From GAN to WGAN: a readable overview.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.