Lecture 10 · Generative Adversarial Networks II: Wasserstein, Scale, and Adversarial Losses Everywhere

Deep Unsupervised Learning · Lecture 10。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 5 · Thu 2/15/2024 · Implicit Models — GANs, second part (slides 71–285): the Wasserstein distance and Kantorovich–Rubinstein duality, WGAN (weight clipping), WGAN-GP, Progressive GAN, spectral normalization and the projection discriminator, SAGAN, BigGAN (truncation), StyleGAN and StyleGAN2, the variational information bottleneck GAN, conditional GANs (pix2pix, vid2vid, GauGAN, learning to paint), InfoGAN, BiGAN and BigBiGAN, GANs as energy models, GANs and optimal transport, implicit maximum likelihood, moment matching (GMMN), adversarial losses for transfer and fairness, GAIL and VAIL, StyleGAN-XL, GigaGAN, VQGAN and ViT-VQGAN. Homework 3, Questions 2–3. Basis: The slides survey a decade of GAN engineering. These notes derive the pieces that carry the ideas — the dual form of the Wasserstein distance, why a critic must be Lipschitz and three ways to make it so, the projection discriminator, the InfoGAN bound, the energy-model view — and check them against exact Wasserstein distances on 1-D and 2-D data. On ShapeWorld they measure what the stabilized recipes, conditioning, InfoGAN, BiGAN and an adversarial tokenizer (VQGAN) actually change, with Lecture 9’s exact yardsticks and scores. Code: code/lecture10/ (5 scripts + adversarial.py; PyTorch (CPU); scripts 01–02 run in 2–5 minutes, 03–05 take 10–20 minutes the first time (models cached)) Reading time: 4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Define the Wasserstein-1 distance, compute it for simple cases, and explain why it gives a useful gradient where JSD does not.
  2. State the Kantorovich–Rubinstein duality and explain why a WGAN critic must be 1-Lipschitz.
  3. Compare weight clipping, the gradient penalty (two- and one-sided) and spectral normalization, and say what each gets wrong.
  4. Describe the engineering of the big GANs — Progressive GAN, SAGAN, BigGAN (truncation trick), StyleGAN (mapping network, AdaIN, noise), StyleGAN-XL, GigaGAN — and the idea behind each.
  5. Build a conditional GAN with input concatenation or a projection discriminator; explain pix2pix’s PatchGAN + L1 recipe.
  6. Explain InfoGAN’s mutual-information bound and BiGAN’s encoder, and measure what they learn when the true factors are known.
  7. Relate GANs to energy-based models, optimal transport and moment matching, and name uses of adversarial losses outside generation (domain adaptation, fairness, GAIL).
  8. Explain why adversarial losses survived inside image tokenizers (VQGAN, ViT-VQGAN).

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 9 (the GAN game, JSD and its saturation, mode collapse, IS / FID / precision / recall)Wasserstein distance, Lipschitz critics, the big-GAN toolboxdiffusion models, which replaced GANs for generation (Lectures 11–12)
Lecture 8 (VQ-VAE, dead codes, the Transformer prior)conditional GANs, InfoGAN, BiGAN, VQGANlatent diffusion on autoencoder latents (Lecture 12); CycleGAN (Lecture 19)
Lecture 6 (spectral norms of layers, Lipschitz maps in flows)energy models and GANs; GMMN; GAILcontrastive and representation learning (Lectures 13–15)

0.3 Map

§1  the Wasserstein distance and its dual                                        ← code 01, Part 1
§2  making a critic Lipschitz: clipping, gradient penalty, spectral norm          ← code 01, Parts 2-3; code 02
§3  GANs at scale: Progressive GAN, SAGAN, BigGAN, StyleGAN, GigaGAN               ← code 03
§4  conditional GANs                                                              ← code 04, Part 1
§5  GANs for representations: InfoGAN, BiGAN                                       ← code 04, Parts 2-3
§6  GANs, energy models, optimal transport and moment matching                    ← code 02 (GMMN)
§7  adversarial losses beyond generation: transfer, fairness, imitation
§8  adversarial losses inside tokenizers: VQGAN, ViT-VQGAN                         ← code 05
§9  summary   §10 pitfalls   §11 exercises   §12 further reading   §13 next lecture

0.4 Notation

SymbolMeaning
W1(p,q)W_1(p, q)Wasserstein-1 (earth mover’s) distance
Π(p,q)\Pi(p, q)couplings: joint distributions with marginals pp and qq
ffthe critic (WGAN’s discriminator), a real-valued function
∥f∥L\lVert f \rVert_LLipschitz constant: ∣f(x)−f(y)∣≤∥f∥L∥x−y∥\lvert f(x) - f(y) \rvert \le \lVert f \rVert_L \lVert x - y \rVert
σ(W)\sigma(W)spectral norm (largest singular value) of a weight matrix
λ\lambdagradient-penalty weight; γ\gamma the R1 weight
ccInfoGAN’s code; yy a class label

0.5 How the experiments are run

As in Lecture 9: 1-D and 2-D distributions with exact densities and exact Wasserstein distances (1-D: by quantiles; 2-D: the sliced Wasserstein distance as an independent quality measure), and binary ShapeWorld judged by Lecture 9’s exact yardsticks (valid, flips) and feature-network scores (IS, FID, precision / recall; FID between two real sets of 2,000 images is ~320–440). All ShapeWorld GANs share Lecture 9’s generator and discriminator and train for 4,000 generator steps. Everything is seeded and single-threaded; reruns print identical numbers.


1. The Wasserstein distance

1.1 Moving earth

Picture pp and qq as two piles of earth of equal mass. A transport plan γ(x,y)\gamma(x, y) says how much mass moves from xx to yy; it must take exactly pp away and deliver exactly qq, i.e. it is a joint distribution with marginals pp and qq (a coupling). The cost of a plan is the average distance travelled; the Wasserstein-1 (earth mover’s) distance is the cheapest plan’s cost:

W1(p,q)=inf⁡γ∈Π(p,q)E(x,y)∼γ[∥x−y∥].W_1(p, q) = \inf_{\gamma \in \Pi(p, q)} E_{(x, y) \sim \gamma}\big[\lVert x - y \rVert\big].

Unlike KL or JSD, it measures how far mass must move, not how much the densities overlap. Lecture 9 (§3.4) showed the consequence: as a narrow generator slides away from narrow data, JSD stops at log⁡2\log 2 with zero gradient while W1W_1 keeps growing with slope 1.

The slides’ example (Arjovsky et al., 2017). P0P_0 is the vertical segment {0}×[0,1]\{0\} \times [0, 1] with uniform mass, Pθ={θ}×[0,1]P_\theta = \{\theta\} \times [0, 1]. For every θ≠0\theta \ne 0: KL=∞\mathrm{KL} = \infty, JSD=log⁡2\mathrm{JSD} = \log 2, and W1=∣θ∣W_1 = \lvert\theta\rvert (Lecture 9, Exercise 3). A generator that controls θ\theta gets no signal from JSD and the right signal from W1W_1.

1.2 Kantorovich–Rubinstein duality

The infimum over couplings is intractable for high-dimensional distributions known only through samples. The duality theorem rewrites it as a supremum over functions:

W1(p,q)=sup⁡∥f∥L≤1  Ex∼p[f(x)]−Ex∼q[f(x)].W_1(p, q) = \sup_{\lVert f \rVert_L \le 1}\; E_{x \sim p}[f(x)] - E_{x \sim q}[f(x)].

The search over joint distributions has become a search over 1-Lipschitz functions ff — the critic. Searching over KK-Lipschitz functions gives K⋅W1K \cdot W_1 (scale ff by KK), so any fixed Lipschitz bound is fine for the generator’s gradient direction.

Why Lipschitz? Without a bound, ff could be made arbitrarily large where pp has more mass than qq — the supremum would be infinite. A bound on the slope means ff can only rise as fast as distance allows: the value Epf−EqfE_p f - E_q f then measures distance, not overlap. Intuition from the dual of a transport problem: ff is the “price” of earth at each location, and prices cannot differ by more than the transport cost between two places.

1.3 The Wasserstein GAN

Arjovsky et al. replace the discriminator by a critic fwf_w (no sigmoid) and play

min⁡Gmax⁡w: ∥fw∥L≤K  Epdata[fw(x)]−Ez[fw(G(z))].\min_G \max_{w:\, \lVert f_w \rVert_L \le K}\; E_{p_{\text{data}}}[f_w(x)] - E_{z}[f_w(G(z))].

Their pseudocode trains the critic for ncritic=5n_{\text{critic}} = 5 steps per generator step (RMSProp, learning rate 5×10−55 \times 10^{-5}) and clips every weight to [−c,c][-c, c] (c=0.01c = 0.01) after each critic update — a crude way to bound KK. Because the critic estimates a distance with useful gradients everywhere, it should be trained close to optimality — the opposite of Lecture 9’s advice for the standard GAN. The slides list the benefits: a new divergence; stability; robustness to architecture choices (WGAN trained without batch norm or with a fully connected generator where DCGAN failed); progress on mode collapse; a loss that correlates with sample quality; and the idea of using Lipschitzness to stabilize GANs. The negative: clipping is a terrible way to enforce it (§2).

1.4 Experiment: what each critic tells the generator (script 01, Part 1)

The parallel segments, θ∈{0.1,0.5,1,2}\theta \in \{0.1, 0.5, 1, 2\}. Each discriminator / critic is trained for 2,000 steps against fixed segments; then we differentiate the generator’s loss with respect to θ\theta through the samples (θ,u)(\theta, u):

criticθ\theta = 0.10.512
GAN discriminator: value VV0.00000.00000.00000.0000
— gradient of the minimax G loss3e-81.5e-94e-101.3e-10
— gradient of the non-saturating G loss44674.535.517.9
WGAN, clip 0.01: estimate / gradient0.0007 / 0.0070.0045 / 0.0090.0115 / 0.0120.0271 / 0.006
WGAN, clip 0.1: estimate / gradient0.84 / 8.44.64 / 7.88.58 / 6.913.84 / 4.3
WGAN-GP: estimate / gradient0.101 / 1.010.513 / 1.031.056 / 1.062.205 / 1.11
spectral norm: estimate / gradient0.095 / 0.950.477 / 0.950.953 / 0.951.908 / 0.96
exactW1=θW_1 = \theta, slope 1
  • The GAN discriminator is perfect at every θ\theta (value 0 = 2log⁡2−log⁡42\log 2 - \log 4), and the minimax generator’s gradient is 10−810^{-8} to 10−1010^{-10} — nothing. The non-saturating loss does give a gradient, but its size reflects how steep this discriminator’s logit happens to be, and it shrinks as the segments move apart: the farther from the data, the weaker the push.
  • The gradient-penalty and spectral-norm critics recover W1=θW_1 = \theta and give a slope of ~1 at every distance — the signal the theory promises. GP over-estimates a little at large θ\theta (the penalty is soft); SN under-estimates by 5% (the per-layer bound is loose).
  • Weight clipping gives K(c)⋅W1K(c) \cdot W_1 with an unknown, θ\theta-dependent KK: direction right, scale arbitrary.

2. Making a critic Lipschitz

2.1 Weight clipping and its problems

Clipping bounds every weight, hence every layer’s gain, hence the network’s Lipschitz constant — at an unknown value K(c)K(c). Gulrajani et al. (2017) showed what it does to a critic trained to optimality: the weights pile up at ±c\pm c (the optimizer pushes them as far as allowed), the critic can represent only very simple functions, and depending on cc the gradients through a deep critic vanish or explode layer by layer.

2.2 The gradient penalty (WGAN-GP)

A differentiable function is 1-Lipschitz iff its gradient norm is at most 1 everywhere. Moreover, the optimal critic has gradient norm exactly 1 along the straight lines between points matched by the optimal transport plan. WGAN-GP enforces this softly where it matters:

LD=Ex~∼pg[f(x~)]−Ex∼pdata[f(x)]+λ Ex^[(∥∇x^f(x^)∥−1)2],L_D = E_{\tilde x \sim p_g}[f(\tilde x)] - E_{x \sim p_{\text{data}}}[f(x)] + \lambda\, E_{\hat x}\big[(\lVert \nabla_{\hat x} f(\hat x) \rVert - 1)^2\big],

with x^=ϵx+(1−ϵ)x~\hat x = \epsilon x + (1 - \epsilon)\tilde x, ϵ∼U[0,1]\epsilon \sim U[0, 1], and λ=10\lambda = 10; Adam with β1=0.5\beta_1 = 0.5 (or 0), β2=0.9\beta_2 = 0.9. Practicalities from the slides: the penalty is per sample, so no batch normalization in the critic (it couples samples; layer norm is fine) — “since then no one uses batch norm in D anymore”; it costs an extra backward pass (“slow wall clock time”); and it is applied on a heuristic distribution (the interpolates), which can be unstable at high learning rates. It became the most-used GAN loss of its time (ProGAN, early StyleGAN).

A one-sided variant (Petzka et al., 2018) penalizes only norms above 1, λ E[max⁡(0,∥∇f∥−1)2]\lambda\,E[\max(0, \lVert\nabla f\rVert - 1)^2] — the Lipschitz constraint itself, without forcing the norm to equal 1.

2.3 Spectral normalization (SNGAN)

For a linear layer h↦Whh \mapsto Wh the Lipschitz constant is the spectral norm σ(W)\sigma(W), the largest singular value. LeakyReLU is 1-Lipschitz, and the constant of a composition is at most the product. So dividing every weight matrix by its spectral norm,

Wˉ=W/σ(W),\bar W = W / \sigma(W),

makes the whole network at most 1-Lipschitz. σ(W)\sigma(W) is estimated with one step of power iteration per forward pass, reusing the vector from the previous step — “a single power iteration and no need of a backward pass”, cheaper than the gradient penalty. Miyato et al. (2018) trained the first GAN on full ImageNet with it (with the hinge loss and the projection discriminator of §4). The bound is loose — the product of per-layer norms overestimates the true constant — so the network ends up less than 1-Lipschitz.

2.4 R1: penalize the gradient on real data

Mescheder et al. (2018) asked which regularizers make the GAN game converge. Their answer, γ2Epdata∥∇xD(x)∥2\frac{\gamma}{2} E_{p_{\text{data}}}\lVert\nabla_x D(x)\rVert^2 (R1), pushes the discriminator to be flat on the data — at equilibrium the best discriminator is constant, so this costs nothing there and damps the oscillation around it. StyleGAN 2 and most later GANs use it with the non-saturating loss.

2.5 Experiments (script 01, Parts 2–3; script 02)

Script 01, Parts 2–3 — 1-D: the two-bump data of Lecture 9 vs N(0.3,0.32)N(0.3, 0.3^2), exact W1=0.4750W_1 = 0.4750 (by quadrature):

criticW1W_1 estimateestimate / exactmean ∥∇f∥\lVert\nabla f\rVert on interpolatesweights at ±c\pm c
WGAN, clip 0.010.00770.0160.016100%
WGAN, clip 0.13.226.787.0240%
WGAN-GP (two-sided)−0.4595−0.9670.975—
WGAN-GP, one-sided0.48391.0191.023—
spectral norm0.41960.8830.888—

Clipping at c=0.01c = 0.01 pins every weight at the boundary and scales the estimate by 0.016 (Gulrajani et al.’s capacity argument); at c=0.1c = 0.1 the critic is 7× too steep. Spectral normalization stays below 1-Lipschitz and under-estimates by 12%.

A surprise: the two-sided penalty can leave a critic upside down. The GP critic above is perfectly steep (0.975) and estimates −W1-W_1. Part 3 repeats it with five seeds:

seedEf(data)−Ef(gen)E f(\text{data}) - E f(\text{gen}) at initializationafter training, two-sided penaltyone-sided penalty
0−0.0952−0.4585+0.4842
1+0.0151+0.4833+0.4826
2−0.0079−0.4592+0.4863
3+0.0227+0.4812+0.4868
4−0.0322−0.4606+0.4839

The trained critic keeps the sign it had at initialization (3 of 5 seeds end upside down). In one dimension ∥∇f∥=∣f′∣\lVert\nabla f\rVert = \lvert f'\rvert: turning a critic with slope −1 into one with slope +1 means passing through slope 0, which the penalty charges λ=10\lambda = 10 for — far more than the ~1 the objective would gain. The one-sided penalty has no such barrier (slope 0 costs nothing) and finds +W1+W_1 for every seed. In two or more dimensions the gradient can rotate instead of shrinking, which is why Part 1 (2-D) has no trap. A small reminder that “the penalty is soft” also means “the penalty has its own landscape”.

Script 02 — the ring of 8 Gaussians of Lecture 9 (3 seeds, 4,000 generator steps). “Reached” is a new, loose count: a mode with at least a fifth of its fair share of samples within a quarter of the distance to the next mode (19 standard deviations):

methodmodes covered (3 seeds)modes reached (loose)good samplesbalance (bits)
standard GAN (Lecture 9)2, 2, 26, 5, 733%1.47
WGAN (clip 0.01, 5 critic steps, RMSprop 5e-5)0, 0, 02, 0, 00%2.15
WGAN-GP (λ\lambda = 10, 5 critic steps, Adam 1e-4)0, 0, 08, 8, 82%2.79
WGAN-GP, learning rate 1e-38, 0, 18, 8, 818%2.59
SNGAN (spectral norm, hinge)0, 0, 08, 8, 86%2.74
GMMN (MMD, no discriminator)6, 7, 68, 8, 835%2.74

Final samples on the ring

  • Every Lipschitz method reaches all 8 modes in every seed; the standard GAN reaches 5–7 and covers 2 sharply (its C-shaped curve). A Wasserstein-type critic pulls the generator towards all the data, however far.
  • Reaching is not sharpening. At the paper’s learning rate WGAN-GP’s ring is still blurry after 4,000 steps (2% good samples); at 1e-3 it is sharp on all 8 modes in seed 0 (the figure) but not in seeds 1–2. Weight clipping has not even found the ring: its critic is too weak to give much signal.
  • Does the critic’s number track quality? Correlation over 10 checkpoints between each discriminator’s own number and the sliced Wasserstein distance of its samples: WGAN-GP at 1e-3 +0.98 (its estimate falls 0.61 → 0.12 as the sliced W1W_1 falls 0.28 → 0.09); SNGAN +0.74; WGAN-GP at 1e-4 −0.32; clipping −0.84 (its estimate is ≈ 0 throughout); the standard GAN −0.75: its loss measures how well the current discriminator does, not how good the generator is.

3. GANs at scale

The slides then follow the progression that took GANs to photorealism. The recurring themes: stabilize the discriminator (Lipschitz constraints, normalization), grow capacity and batch size, inject conditioning and noise at every level.

  • Progressive GAN (Karras et al., 2018): train at 4×4, then add layers for 8×8, 16×16, … up to 1024×1024, fading each new layer in. Low resolutions learn the global structure fast; high resolutions only add detail. The first super-high-quality samples from any generative model (CelebA-HQ faces). Also: minibatch standard deviation (a cheap form of minibatch discrimination), equalized learning rate, pixel norm.
  • SAGAN (Zhang et al., 2019): self-attention layers in G and D, so that distant parts of an image can be consistent (a dog’s legs and body); spectral normalization in both G and D (counter to the belief that only D needs conditioning); the hinge loss; different learning rates for D and G (TTUR); conditional batch norm in G and a projection discriminator. The first good unconditional full-ImageNet samples.
  • BigGAN (Brock et al., 2019): “increase your batch size as much as you can” (2,048); cross-replica (synchronized) batch norm; wider helps as much as deeper; class information fused at all levels (shared embeddings feeding conditional batch norm); the hinge loss; orthogonal regularization of G’s weights, which makes G smooth enough for the truncation trick: sample zz from a truncated normal (redraw coordinates beyond a threshold). Smaller thresholds move samples towards the mode of the generator — higher fidelity (IS up), less variety (FID eventually up) — one knob trading precision for recall. BigGAN-deep: deeper, with bottleneck residual blocks.
  • StyleGAN (Karras et al., 2019): a mapping network turns zz into an intermediate latent ww, and ww controls each convolution layer through adaptive instance normalization — normalize each channel of each sample (instance norm), then scale and shift it with values computed from ww (the “style”, as in style transfer). Per-pixel noise inputs add stochastic detail (hair, freckles) without disturbing the global structure. StyleGAN 2 replaced AdaIN by weight modulation / demodulation (removing “droplet” artifacts), added path-length regularization and used R1.
  • VIB-GAN / variational discriminator bottleneck (Peng et al., 2019): an over-confident discriminator gives useless gradients (Lecture 9’s saturation); instance noise (blurring real and fake by adding noise to both) makes their distributions overlap so the discriminator cannot be perfect. The VDB instead squeezes D’s input through a stochastic encoder with a constraint on the mutual information I(x;z)≤IcI(x; z) \le I_c — an information bottleneck that adaptively limits how much the discriminator can know.
  • StyleGAN-XL (Sauer et al., 2022): StyleGAN3 scaled to ImageNet at 1024², using projected GANs (the discriminator works on features of pretrained networks such as EfficientNet), progressive growing again, pretrained class embeddings and classifier guidance.
  • GigaGAN (Kang et al., 2023): a 1-billion-parameter text-to-image GAN with lower FID than Stable Diffusion v1.5 at a fraction of the sampling time (0.13 s for 512²). Its generator selects sample-adaptive convolution kernels from a bank (more capacity per sample), uses self-attention with L2 distance instead of dot products and tied query/key weights (dot-product attention is not Lipschitz, and naive attention made training collapse), cross-attention to text features, and multi-scale outputs. Its discriminator adds a matching-aware loss (real images with mismatched captions count as fake) and CLIP-based losses. A disentangled latent space allows prompt mixing and style swapping.

3.1 Experiment: stabilized recipes and the truncation trick on ShapeWorld (script 03)

Same generator, same discriminator architecture (spectral norm for SNGAN), 4,000 generator steps each, binary ShapeWorld:

recipevalidflipsgray pixelsISFIDprecisionrecalltraining time
DCGAN (Lecture 9’s recipe)0%28.53.0%4.7621,3440.790.24~4 min
WGAN-GP0%31.08.4%4.8315,0430.720.3726.2 min
SNGAN (hinge)0%29.35.5%4.6120,1790.730.285.7 min
non-saturating + R10%29.97.7%4.9514,8930.750.378.5 min

(The training times are from the first run, with several other jobs sharing the CPU.)

  • No recipe produces a valid image; the stabilizers do not fix what Lecture 9 found. They improve the distribution-level scores: WGAN-GP and R1 reach FID ~15,000 and recall 0.37 against the DCGAN’s 21,344 / 0.24 — more coverage, at the cost of slightly more gray pixels.
  • WGAN-GP is expensive (five critic steps and a double backward per generator step); R1 gets the same scores in a third of the time — one reason later GANs (StyleGAN 2) use the non-saturating loss with R1.
  • Only WGAN-GP’s own number tracks quality: its Wasserstein estimate falls together with the FID of its samples (correlation +0.98 over five checkpoints); the hinge loss (+0.24) and the R1 discriminator’s loss (−0.67) do not. (These curves are recorded when the GANs are trained; a rerun from the cached checkpoints skips this part.)

The truncation trick on the R1 GAN:

truncationflipsgray pixelsISFIDprecisionrecalldistinct images (of 2,000)
none29.97.7%4.9514,8930.750.372,000
∣zi∣≤2\lvert z_i\rvert \le 227.77.5%4.9316,3100.760.342,000
∣zi∣≤1\lvert z_i\rvert \le 117.65.6%3.5843,4330.880.241,994
∣zi∣≤0.5\lvert z_i\rvert \le 0.515.62.3%1.79119,3400.920.151,222
∣zi∣≤0.25\lvert z_i\rvert \le 0.2517.70.3%1.05169,8481.000.00139
z=0z = 018.00.0%1.00177,8721.000.001

Truncation moves samples towards the generator’s most typical outputs. At ∣zi∣≤1\lvert z_i\rvert \le 1 the blobs are cleaner (flips 29.9 → 17.6, precision 0.88); recall, the number of distinct images and the Inception Score fall and FID rises — the trade-off BigGAN reports. Pushed further, the figure shows what “typical” means for this generator: an almost empty canvas. At ∣zi∣≤0.25\lvert z_i\rvert \le 0.25 and at z=0z = 0 precision is a perfect 1.00 and the image is only ~18 flips from a valid one (a tiny shape) — two more scores fooled by a degenerate sample, which recall (0.00), FID and the number of distinct images (1) do expose. (BigGAN’s IS rises with truncation because ImageNet’s classifier likes prototypical class members; here the IS classifier reads the left shape, and our prototypes are blobs of no particular kind.)

Samples of the four recipes and the truncation sweep


4. Conditional GANs

Give both players a condition yy: G(z,y)G(z, y), D(x,y)D(x, y), and train on (image, label) pairs. Two ways for the discriminator to use yy:

  • Input concatenation (Mirza & Osindero, 2014): append yy (one-hot planes for images) to D’s input.
  • Projection (Miyato & Koyama, 2018): D(x,y)=ψ(ϕ(x))+embed(y)⊤ϕ(x)D(x, y) = \psi(\phi(x)) + \mathrm{embed}(y)^\top \phi(x). If the conditional log-density ratio log⁡pdata(y∣x)/pg(y∣x)\log p_{\text{data}}(y \mid x) / p_g(y \mid x) is log-linear in the features ϕ(x)\phi(x) — as for a softmax classifier — the optimal discriminator has exactly this form. It is what SNGAN, SAGAN and BigGAN use.

Image-to-image translation conditions on a whole image. pix2pix (Isola et al., 2017) learns maps such as labels → photo, edges → photo, day → night from paired examples, with two losses: an L1 loss to the target (which alone gives blurry outputs — the mean of the plausible answers) and an adversarial loss from a PatchGAN discriminator that judges local patches (it enforces sharp, realistic texture; L1 takes care of the low frequencies). The same recipe drives vid2vid (video with temporal consistency), Everybody Dance Now (pose → dancer), GauGAN / SPADE (semantic layout → landscape, with spatially-adaptive normalization) and the GAN + reinforcement-learning painter “learning to paint”. Unpaired translation (CycleGAN) is Lecture 19’s subject.

4.1 Experiment (script 04, Part 1)

Class = the kind of the left shape; Lecture 9’s feature network reads the shape kinds of every sample:

discriminator sees the class byrequested shape seen (left)right panel = requestedvalidflipsFIDprecisionrecall
input concatenation30.9%25.1%0%31.747,8140.720.00
projection20.7%17.2%0%25.127,4590.780.34

(chance: 12.5%; in the data the right shape equals the left one 56% of the time.) Conditioning barely took — unsurprising when no sample is a valid shape. The projection discriminator gives the better GAN (FID 27,459 vs 47,814; the concatenation GAN collapsed, recall 0.00) but follows the label less. Lecture 11 returns to conditional generation with diffusion models, where it works.


5. GANs for representations

A GAN’s generator maps zz to images, but nothing makes zz interpretable, and there is no encoder.

InfoGAN (Chen et al., 2016) splits the input into noise zz and a code cc (e.g. a categorical variable with 10 values) and asks that cc stay recoverable from the image: maximize the mutual information I(c;G(z,c))I(c; G(z, c)). It is intractable, but for any auxiliary distribution Q(c∣x)Q(c \mid x),

I(c;G(z,c))≥Ec∼p(c), x∼G(z,c)[log⁡Q(c∣x)]+H(c),I(c; G(z, c)) \ge E_{c \sim p(c),\, x \sim G(z, c)}[\log Q(c \mid x)] + H(c),

so a network QQ (a head on D’s features) trained by cross-entropy to predict cc gives a lower bound, and the generator is trained to make cc predictable. On MNIST, the categorical code discovered the digit classes without labels; continuous codes captured rotation and width. Whether a code captures a true factor is not guaranteed — any visible, consistent effect raises the bound.

BiGAN / ALI (Donahue et al., 2017; Dumoulin et al., 2017) add an encoder E:x→zE: x \to z and let the discriminator judge pairs: real pairs (x,E(x))(x, E(x)) against fake pairs (G(z),z)(G(z), z). At the optimum the two joint distributions match, which forces E=G−1E = G^{-1} on the support — an encoder learned without any reconstruction loss. BigBiGAN (Donahue & Simonyan, 2019) scaled this with BigGAN’s generator and showed competitive ImageNet representations from the encoder (linear probes), and reconstructions G(E(x))G(E(x)) that preserve semantics rather than pixels. The slides also show BigGAN discovering categories unsupervised.

5.1 Experiment (script 04, Parts 2–3)

InfoGAN with an 8-valued code and no labels. QQ recovers the code from generated images 99% of the time — the mutual-information bound is nearly tight — but what does the code control? Mutual information (bits) between the code and each factor as read by the feature network:

factorleft shaperight shapeleft sizeright sizeleft xxleft yyright xxright yy
I(c; factor)I(c;\ \text{factor})0.300.180.660.590.800.610.580.71

The code did not discover the eight shape kinds; it controls a mixture of sizes and positions. The InfoGAN bound only asks for a visible, consistent effect — on MNIST the most visible one happens to be the digit class; here, where and how big the (invalid) blobs are. Disentanglement, again (Lecture 8), is not guaranteed by an objective that does not know the factors.

BiGAN: a linear probe for the left shape kind (8 classes; 4,000 training images, 2,000 test images):

representationprobe accuracy
BiGAN encoder E(x)E(x) (64 dimensions)54.3%
the same encoder, untrained53.3%
raw pixels (288)63.3%
Lecture 7’s VAE encoder mean (16)80.0%

The BiGAN encoder learned nothing useful for the shape kind — no better than random weights. Its “reconstructions” G(E(x))G(E(x)) keep the rough size and place of each shape (92 of 288 pixels wrong, vs 97 between two random test images) and nothing else: the joint game matches the distribution of pairs, and with a generator that never draws a valid shape, there is little for the encoder to invert. BigBiGAN’s results needed BigGAN-scale models and data.

Conditional samples, InfoGAN codes, BiGAN reconstructions


6. GANs, energy models, optimal transport and moment matching

Energy models. An energy model pE(x)=e−E(x)/Zp_E(x) = e^{-E(x)}/Z assigns low energy to likely xx; maximum likelihood needs log⁡Z\log Z, intractable when xx ranges over all images. For any distribution qq, Jensen’s inequality gives the variational bound

log⁡Z=log⁡Eq[e−E(x)q(x)]≥Eq[−E(x)]+H(q),\log Z = \log E_{q}\Big[\frac{e^{-E(x)}}{q(x)}\Big] \ge E_q[-E(x)] + H(q),

with equality at q=pEq = p_E. Substituting into the log-likelihood,

max⁡E(Epdata[−E(x)]−log⁡Z)=max⁡Emin⁡q(Epdata[−E(x)]−Eq[−E(x)]−H(q)):\max_E \Big( E_{p_{\text{data}}}[-E(x)] - \log Z \Big) = \max_E \min_q \Big( E_{p_{\text{data}}}[-E(x)] - E_q[-E(x)] - H(q) \Big):

a game in which "D=−ED = -E" separates data from samples of qq and the “generator” qq minimizes Eq[E(x)]−H(q)E_q[E(x)] - H(q). This is a Wasserstein-GAN objective with an entropy regularizer on the generator (the slides, after Schulman’s notes; Kim & Bengio, 2016; Zhao et al., 2017). The entropy term is what keeps qq from collapsing onto the lowest-energy point — exactly the mode collapse a GAN generator has no protection against. Entropy is hard to compute for a GAN generator, easy for flows, autoregressive models or VAEs (Flow-GAN, Prescribed GANs).

Optimal transport. WGAN optimizes the dual of W1W_1. The primal can be attacked directly on minibatches: entropy-regularized OT (Sinkhorn iterations) gives differentiable distances between two batches (Genevay et al., 2018; OT-GAN, Salimans et al., 2018); the Cramér distance fixes the biased sample gradients of the Wasserstein distance (Bellemare et al., 2017).

Implicit maximum likelihood (IMLE; Li & Malik, 2018): maximum likelihood makes sure every data point is near some probability mass. IMLE imposes that directly — for each training example, find the nearest of many generated samples and pull it closer — which cannot drop modes (every data point gets its own sample), the opposite failure mode of a GAN.

Moment matching. Two distributions are equal if all their moments are equal; the maximum mean discrepancy compares all moments at once through a kernel: MMD2=E k(x,x′)+E k(y,y′)−2E k(x,y)\mathrm{MMD}^2 = E\,k(x, x') + E\,k(y, y') - 2E\,k(x, y) (Gretton et al., 2012), which is zero iff the distributions match for a characteristic kernel such as a Gaussian. A generative moment-matching network (GMMN; Li, Swersky & Zemel, 2015) simply trains a generator to minimize MMD² between minibatches — no discriminator, no game. The slides’ verdict: it needs a good kernel and did not scale beyond MNIST / TFD (later CIFAR with an autoencoder, large minibatches and a mixture of bandwidths). Script 02 includes a GMMN on the ring: with no discriminator at all it was the best method on the 2-D ring (6–7 sharp modes of 8, 35% good samples; §2.5). In two dimensions a Gaussian-kernel MMD is an excellent two-sample test; it is the high dimension of images, where kernels on raw pixels say little, that made GMMNs lose to GANs.


7. Adversarial losses beyond generation

The adversarial game is a general tool for making one distribution indistinguishable from another.

  • Transfer / domain adaptation (deep domain confusion, Tzeng et al., 2014; domain-adversarial training): learn features from which a domain classifier cannot tell source images from target images, while a task head still classifies the labelled source — the features then transfer.
  • Fairness: learn a representation (or a predictor) from which an adversary cannot predict a protected attribute, while it still predicts the target (adversarial debiasing). The slides list it as one more instance of “fool a discriminator” — the same mathematics, applied to a societal constraint.
  • Imitation learning — GAIL (Ho & Ermon, 2016): a discriminator separates the (state, action) pairs of an expert from those of the learner’s policy; the policy is trained by reinforcement learning to make its pairs indistinguishable (its reward is the discriminator’s output). This matches the energy-model view of §6 (the discriminator plays the role of a learned cost). VAIL (Peng et al., 2019) adds the variational discriminator bottleneck of §3, which keeps the discriminator from becoming too sharp to provide a learning signal — improving imitation of motion-capture skills.

(No experiments here: these settings need data we do not have in ShapeWorld.)


8. Adversarial losses inside tokenizers: VQGAN

After diffusion models took over image generation (Lectures 11–12), GANs survived in one place: the tokenizer that turns an image into a short sequence of codes for a Transformer (or a latent for a diffusion model).

VQGAN (Esser et al., 2021) starts from a VQ-VAE (Lecture 8), whose reconstructions are blurry — the pixel loss is minimized by the conditional mean of what the decoder could output. Three additions:

  1. a perceptual loss (LPIPS: distances between features of a pretrained network) instead of / in addition to pixels;
  2. a patch-based adversarial loss (a PatchGAN discriminator), which punishes blurry, unrealistic local texture; its weight is set adaptively by the ratio of gradient norms at the decoder’s last layer, λ=∥∇Lrec∥/(∥∇LGAN∥+δ)\lambda = \lVert\nabla L_{\text{rec}}\rVert / (\lVert\nabla L_{\text{GAN}}\rVert + \delta);
  3. a Transformer prior over the codes (as in Lecture 8).

Because details are now produced by the decoder, the code can be much shorter — higher compression, fewer tokens, a cheaper second stage. ViT-VQGAN (Yu et al., 2022) replaces the CNN encoder / decoder by Vision Transformers, uses a StyleGAN discriminator, a logit-Laplace reconstruction loss (a distribution on (0,1)(0, 1)), and a factorized codebook: project encoder outputs to a low-dimensional space and l2-normalize both outputs and codes (codes on a sphere), which improves codebook usage — the dead-code problem of Lecture 8 — and reconstruction. Homework 3 Q3 trains both with L=LVQ+0.1 LGAN+0.5 Lperceptual+L2L = L_{VQ} + 0.1\,L_{GAN} + 0.5\,L_{\text{perceptual}} + L_2.

8.1 Experiment (script 05)

The homework’s recipe on ShapeWorld: a VQ autoencoder with only 8 tokens of 64 codes per image (48 bits of code; Lecture 8 used 18 tokens of 128 codes), trained 3,000 steps with each combination of losses; the perceptual loss uses a second feature network (different seed and data), with LPIPS-style unit-normalized features, so that FID’s network is not optimized directly:

tokenizerMSEpixel-perfect reconstructionsvalidflipsgray pixelsFIDprecisionrecall
VQ-VAE (L2 only)0.003957.1%59.1%1.01.7%6280.950.92
+ perceptual (0.5)0.005148.6%49.8%1.42.3%6120.960.93
+ adversarial (0.1)0.013819.6%21.5%3.20.6%7250.940.92
VQGAN: + perceptual + adversarial0.013720.6%21.4%3.20.7%4650.950.94

Stage two, a Transformer prior over the 8 tokens (Lecture 4’s model, 2,000 steps):

tokens fromcode bits per imagevalid samplesnovel validflipsgray pixelsFID
VQ-VAE (L2 only)21.147.8%38.9%3.12.5%1,360
VQGAN21.319.9%14.0%4.90.9%958

Reconstructions and samples of the four tokenizers

  • Plan vs reality. The plan expected blurry L2 reconstructions for VQGAN to fix. On binary images, with data-initialized codes and dead-code restarts (Lecture 8’s lessons), the L2-only model is already sharp (1.7% gray pixels) and exact on 57% of test images; its tokens plus a Transformer give 48% valid samples with 21 bits of code — the best latent-variable result so far (Lecture 8: 23% with 36 bits).
  • The adversarial loss does what VQGAN promises — crisper outputs and the best FID, for reconstructions (465 vs 628) and samples (958 vs 1,360) — by drawing locally realistic strokes whether or not they form the right shape: rings come back as arcs and “C”s. Exact reconstructions fall from 57% to 21%, valid samples from 48% to 20%. By FID, VQGAN wins; by exactness, it loses — Lecture 9’s lesson about what scores reward, inside a tokenizer. On natural images, where “the exact pixels” matter far less than plausible texture, the trade is worth it, which is why VQGAN-style tokenizers (and the VAE of Stable Diffusion, trained with the same losses) are everywhere.
  • The perceptual loss alone changes little here (48.6% exact, FID 612). An earlier version of the code used raw classifier features, whose squared differences were ~4,000× the pixel loss: the decoder then produced noisy textures that fooled the feature network (0% exact). Unit-normalizing the features, as LPIPS does, fixed it — a perceptual loss is only as good as its features and their scaling.

9. Summary

  1. The Wasserstein-1 distance measures how far mass must move; unlike JSD it keeps a slope of 1 when distributions do not overlap. Its Kantorovich–Rubinstein dual is a supremum over 1-Lipschitz critics, which makes it estimable from samples.
  2. Weight clipping (WGAN) bounds the Lipschitz constant crudely: estimates are scaled by an unknown factor (0.016× or 6.8× here) and the weights pile up at ±c\pm c. The gradient penalty (WGAN-GP) recovers W1W_1 to a few percent and a slope of ~1 everywhere — but in 1-D its two-sided form can trap the critic upside down; the one-sided penalty does not. Spectral normalization is cheap and slightly under-estimates. R1 penalizes the discriminator’s gradient on real data and stabilizes the non-saturating GAN.
  3. Lipschitz critics reach every mode of the ring (all 8 in every seed, vs 5–7 for the standard GAN) and WGAN-GP’s estimate tracks sample quality (correlation +0.98 in 2-D and on ShapeWorld); the standard GAN’s loss does not. A discriminator-free GMMN was the best method in 2-D.
  4. GANs reached photorealism through engineering: progressive growing, self-attention and spectral norm in both networks (SAGAN), scale, class embeddings everywhere, orthogonal regularization and the truncation trick (BigGAN), a mapping network + AdaIN + noise (StyleGAN), information bottlenecks for the discriminator (VIB-GAN), projected discriminators (StyleGAN-XL) and Lipschitz attention + adaptive kernels (GigaGAN).
  5. On ShapeWorld none of four stabilized recipes gives a valid image; WGAN-GP and R1 improve FID (21,344 → ~15,000) and recall (0.24 → 0.37). Truncation trades recall for precision (0.37 → 0.15 vs 0.75 → 0.92) — and taken to the limit yields near-empty canvases with perfect precision.
  6. Conditional GANs see the label by concatenation or projection; pix2pix pairs an L1 loss with a PatchGAN. On ShapeWorld, conditioning barely took.
  7. InfoGAN’s code is recoverable (99%) but controlled sizes and positions, not shape kinds; the BiGAN encoder was no better than random weights for the shape label.
  8. A GAN is a Wasserstein game plus a missing entropy term away from maximum likelihood for an energy model; OT GANs attack the primal; IMLE and moment matching avoid the game.
  9. Adversarial losses also serve domain adaptation, fairness and imitation (GAIL, VAIL).
  10. VQGAN adds perceptual and patch-adversarial losses to a VQ-VAE: sharper outputs and better FID (465 vs 628) — and, on exact ShapeWorld, far fewer correct reconstructions (21% vs 57%). Tokenizers with 8 tokens + a Transformer gave 48% valid samples with 21 bits of code.

10. Common pitfalls

  1. Reading a WGAN critic’s value as W1W_1 without checking its Lipschitz constant. With clipping it is K⋅W1K \cdot W_1 for an unknown KK; with spectral norm it is below W1W_1; with a penalty it can exceed it.
  2. Batch normalization in a critic with a gradient penalty. The penalty is defined per sample; batch norm makes each output depend on the whole batch. Use layer norm or none.
  3. Forgetting create_graph=True when computing a gradient penalty: without it the penalty’s gradient with respect to the critic’s weights is silently missing.
  4. Comparing GAN recipes at equal generator steps only. WGAN-GP’s step is 3–5× more expensive; compare at equal compute too.
  5. Trusting the truncation trick’s IS. Truncation raises precision and (on ImageNet) IS while destroying diversity; report recall or FID next to it.
  6. Assuming InfoGAN’s code finds the “true” factors. It finds some visible, consistent variation; check what it controls.
  7. A perceptual loss with unnormalized features. Raw feature distances can dwarf the pixel loss by orders of magnitude, and the decoder learns to fool the feature network instead of reconstructing.
  8. Judging a tokenizer by FID alone. VQGAN improved FID and halved exact reconstructions; what you need depends on the downstream use.
  9. Running the adversarial loss from step 0 in VQGAN. Like the reference implementation, start the discriminator after the autoencoder has learned something (here after 500 steps); an early discriminator only sees noise.

11. Exercises

Exercise 1 (W1W_1 in one dimension — derivation). Show that for distributions on the real line W1(p,q)=∫∣Fp(x)−Fq(x)∣ dxW_1(p, q) = \int \lvert F_p(x) - F_q(x)\rvert\,dx, and that the optimal coupling matches quantiles. Use it to compute W1(N(0,s2),N(θ,s2))W_1(N(0, s^2), N(\theta, s^2)).

Answer

Any coupling moves mass across each point xx; at least ∣Fp(x)−Fq(x)∣\lvert F_p(x) - F_q(x)\rvert must cross it (the excess of mass to the left in one distribution), and crossing costs dxdx per unit, so the cost is at least ∫∣Fp−Fq∣dx\int \lvert F_p - F_q\rvert dx. The monotone (quantile) coupling x↦Fq−1(Fp(x))x \mapsto F_q^{-1}(F_p(x)) never moves mass across a point in both directions, so it achieves the bound. For two Gaussians differing by a shift, Fq(x)=Fp(x−θ)F_q(x) = F_p(x - \theta) and every quantile moves by θ\theta: W1=∣θ∣W_1 = \lvert\theta\rvert, independent of ss — Lecture 9’s script 01, Part 2.

Exercise 2 (K-Lipschitz critics). Show that sup⁡∥f∥L≤KEpf−Eqf=K W1(p,q)\sup_{\lVert f\rVert_L \le K} E_p f - E_q f = K\,W_1(p, q). Why is a fixed, unknown KK harmless for the generator but harmful for monitoring?

Answer

ff is KK-Lipschitz iff f/Kf/K is 1-Lipschitz, and the objective is linear in ff, so the supremum scales by KK. The generator’s gradient is then KK times the gradient of W1W_1: the same direction, a rescaled step size (absorbed by the learning rate). But the number itself is meaningless across runs or architectures unless KK is known — and with clipping, KK depends on cc and on how many weights sit at the boundary (script 01: 0.016× and 6.8×).

Exercise 3 (why the optimal critic has unit gradient — derivation). Let π∗\pi^* be an optimal coupling and f∗f^* an optimal critic. Show that for (x,y)∼π∗(x, y) \sim \pi^* with x≠yx \ne y, f∗f^* increases with slope exactly 1 along the segment from yy to xx. (This is the WGAN-GP paper’s motivation for penalizing (∥∇f∥−1)2(\lVert\nabla f\rVert - 1)^2 on interpolates.)

Answer

Duality gives Eπ∗[∥x−y∥]=W1=Epf∗−Eqf∗=Eπ∗[f∗(x)−f∗(y)]E_{\pi^*}[\lVert x - y\rVert] = W_1 = E_p f^* - E_q f^* = E_{\pi^*}[f^*(x) - f^*(y)]. Lipschitz: f∗(x)−f∗(y)≤∥x−y∥f^*(x) - f^*(y) \le \lVert x - y \rVert for every pair, so equality must hold π∗\pi^*-almost surely. Along the straight segment from yy to xx, f∗f^* therefore rises by exactly ∥x−y∥\lVert x - y\rVert over a path of length ∥x−y∥\lVert x - y\rVert, while its slope can never exceed 1 — so the slope along the segment is exactly 1 at every point of it, and where f∗f^* is differentiable, ∇f∗\nabla f^* points along x−yx - y with norm 1.

Exercise 4 (spectral norm of a network). For f(x)=W2 LeakyReLU(W1x)f(x) = W_2\,\mathrm{LeakyReLU}(W_1 x), show ∥f∥L≤σ(W2)σ(W1)\lVert f\rVert_L \le \sigma(W_2)\sigma(W_1), and give an example where the bound is not tight.

Answer

LeakyReLU is 1-Lipschitz (slopes 1 and 0.2), and for linear maps ∥Wu−Wv∥≤σ(W)∥u−v∥\lVert Wu - Wv\rVert \le \sigma(W)\lVert u - v\rVert; compose. Not tight: W1=diag(1,0)W_1 = \mathrm{diag}(1, 0), W2=diag(0,1)W_2 = \mathrm{diag}(0, 1): each has spectral norm 1, but W2⋅W_2 \cdot anything⋅W1\cdot W_1 is zero, so ff is constant (Lipschitz constant 0). In general the top singular directions of consecutive layers need not align, so spectrally normalized networks are less than 1-Lipschitz — script 01’s 5–12% under-estimates.

Exercise 5 (the 1-D gradient-penalty trap). A 1-D critic has slope −1-1 everywhere and the data are to the right of the generator’s samples. Write the WGAN-GP loss for slopes a∈[−1,1]a \in [-1, 1] (assume ff linear with slope aa) and show it has two local minima. Which penalty removes the spurious one?

Answer

With f(x)=axf(x) = ax: L(a)=−a(μdata−μg)+λ(∣a∣−1)2L(a) = -a(\mu_{\text{data}} - \mu_g) + \lambda(\lvert a\rvert - 1)^2. With d=μdata−μg>0d = \mu_{\text{data}} - \mu_g > 0: for a>0a > 0, minimum at a=1+d/(2λ)a = 1 + d/(2\lambda); for a<0a < 0, L=−ad+λ(−a−1)2L = -ad + \lambda(-a - 1)^2, minimized at a=−1+d/(2λ)a = -1 + d/(2\lambda) if that is negative — a second local minimum whenever d<2λd < 2\lambda, separated from the first by the barrier at a=0a = 0 of height λ\lambda. The one-sided penalty λmax⁡(0,∣a∣−1)2\lambda\max(0, \lvert a\rvert - 1)^2 is flat on [−1,1][-1, 1], so LL decreases monotonically from a=−1a = -1 to a=1a = 1: a single minimum.

Exercise 6 (projection discriminator — derivation). Suppose pdata(y∣x)p_{\text{data}}(y \mid x) and pg(y∣x)p_g(y \mid x) are softmax models on the same features, log⁡p(y∣x)=vy⊤ϕ(x)−log⁡Z(x)\log p(y \mid x) = v_y^\top\phi(x) - \log Z(x), with different class vectors. Show that the log density ratio log⁡pdata(x,y)pg(x,y)\log\frac{p_{\text{data}}(x, y)}{p_g(x, y)} — the optimal conditional discriminator’s logit — has the form (vydata−vyg)⊤ϕ(x)+ψ(ϕ(x))(v^{\text{data}}_y - v^g_y)^\top \phi(x) + \psi(\phi(x)).

Answer

log⁡pdata(x,y)pg(x,y)=log⁡pdata(y∣x)pg(y∣x)+log⁡pdata(x)pg(x)=(vydata−vyg)⊤ϕ(x)−log⁡Zdata(x)Zg(x)+log⁡pdata(x)pg(x)\log\frac{p_{\text{data}}(x, y)}{p_g(x, y)} = \log\frac{p_{\text{data}}(y \mid x)}{p_g(y \mid x)} + \log\frac{p_{\text{data}}(x)}{p_g(x)} = (v^{\text{data}}_y - v^g_y)^\top\phi(x) - \log\frac{Z_{\text{data}}(x)}{Z_g(x)} + \log\frac{p_{\text{data}}(x)}{p_g(x)}. The last two terms do not depend on yy: call them ψ(ϕ(x))\psi(\phi(x)). The first is an inner product between a class embedding and the features — the projection term.

Exercise 7 (the InfoGAN bound — derivation). Prove I(c;x)≥E[log⁡Q(c∣x)]+H(c)I(c; x) \ge E[\log Q(c \mid x)] + H(c) for any QQ, with equality iff Q(c∣x)=p(c∣x)Q(c \mid x) = p(c \mid x).

Answer

I(c;x)=H(c)−H(c∣x)=H(c)+E[log⁡p(c∣x)]I(c; x) = H(c) - H(c \mid x) = H(c) + E[\log p(c \mid x)]. And E[log⁡p(c∣x)]−E[log⁡Q(c∣x)]=Ex[KL(p(c∣x)∥Q(c∣x))]≥0E[\log p(c \mid x)] - E[\log Q(c \mid x)] = E_x[\mathrm{KL}(p(c \mid x) \Vert Q(c \mid x))] \ge 0. So I(c;x)≥H(c)+E[log⁡Q(c∣x)]I(c; x) \ge H(c) + E[\log Q(c \mid x)], with equality iff the KL is zero. Maximizing the bound over QQ is fitting a classifier; over GG, making the code recoverable.

Exercise 8 (energy models and GANs — derivation). Starting from log⁡Z=log⁡Eq[e−E(x)/q(x)]\log Z = \log E_q[e^{-E(x)}/q(x)], derive the variational bound and the min-max objective of §6. What does dropping H(q)H(q) do to the inner minimization over qq?

Answer

Jensen: log⁡Eq[e−E/q]≥Eq[−E−log⁡q]=Eq[−E]+H(q)\log E_q[e^{-E}/q] \ge E_q[-E - \log q] = E_q[-E] + H(q), equality at q∝e−Eq \propto e^{-E}. Hence log⁡pE(x)=−E(x)−log⁡Z≤−E(x)−Eq[−E]−H(q)\log p_E(x) = -E(x) - \log Z \le -E(x) - E_q[-E] - H(q) for every qq, and maximum likelihood is max⁡Emin⁡q(Edata[−E]−Eq[−E]−H(q))\max_E \min_q (E_{\text{data}}[-E] - E_q[-E] - H(q)). Without H(q)H(q), the best qq for a fixed energy puts all its mass at the minimum of EE — a point mass: mode collapse, the default behaviour of a GAN generator.

Exercise 9 (MMD). For the linear kernel k(x,y)=x⊤yk(x, y) = x^\top y show MMD2=∥Ex−Ey∥2\mathrm{MMD}^2 = \lVert E x - E y\rVert^2. Why does a GMMN need a characteristic kernel such as a Gaussian?

Answer

E[x⊤x′]+E[y⊤y′]−2E[x⊤y]=∥μx∥2+∥μy∥2−2μx⊤μy=∥μx−μy∥2E[x^\top x'] + E[y^\top y'] - 2E[x^\top y] = \lVert\mu_x\rVert^2 + \lVert\mu_y\rVert^2 - 2\mu_x^\top\mu_y = \lVert\mu_x - \mu_y\rVert^2: only the means are compared, so any distribution with the right mean scores 0. A characteristic kernel’s feature map is rich enough that equal mean embeddings imply equal distributions.

Exercise 10 (coding). In script 03, train the R1 GAN for 12,000 steps (change STEPS) and compare FID, recall and validity. Does longer training help more than the choice of loss did?

Answer

(Run it; the first-run cost is ~25 minutes.) Expect FID and recall to keep improving slowly; validity, which needs every pixel right, is unlikely to move from 0% at this scale (Lecture 9’s single-panel run reached 0.3% after 32,000 steps).


12. Further reading

From the slides

  • M. Arjovsky, S. Chintala, L. Bottou. Wasserstein GAN, ICML 2017; M. Arjovsky, L. Bottou. Towards Principled Methods for Training GANs, ICLR 2017 (instance noise).
  • I. Gulrajani et al. Improved Training of Wasserstein GANs (WGAN-GP), NeurIPS 2017.
  • T. Miyato et al. Spectral Normalization for GANs, ICLR 2018; T. Miyato, M. Koyama. cGANs with Projection Discriminator, ICLR 2018.
  • T. Karras et al. Progressive Growing of GANs, ICLR 2018; A Style-Based Generator Architecture for GANs (StyleGAN), CVPR 2019; Analyzing and Improving the Image Quality of StyleGAN (StyleGAN2), CVPR 2020.
  • H. Zhang et al. Self-Attention GANs, ICML 2019; A. Brock, J. Donahue, K. Simonyan. Large Scale GAN Training (BigGAN), ICLR 2019.
  • X. B. Peng et al. Variational Discriminator Bottleneck (VIB-GAN, VAIL), ICLR 2019; A. Alemi et al. Deep Variational Information Bottleneck, ICLR 2017.
  • P. Isola et al. Image-to-Image Translation with Conditional Adversarial Networks (pix2pix), CVPR 2017; T.-C. Wang et al. Video-to-Video Synthesis, NeurIPS 2018; T. Park et al. Semantic Image Synthesis with Spatially-Adaptive Normalization (GauGAN), CVPR 2019.
  • X. Chen et al. InfoGAN, NeurIPS 2016; J. Donahue, P. Krähenbühl, T. Darrell. Adversarial Feature Learning (BiGAN), ICLR 2017; J. Donahue, K. Simonyan. Large Scale Adversarial Representation Learning (BigBiGAN), NeurIPS 2019.
  • J. Schulman. Notes on GANs, Energy-Based Models, and Saddle Points, 2016; T. Kim, Y. Bengio, 2016; J. Zhao, M. Mathieu, Y. LeCun. Energy-based GAN, ICLR 2017.
  • T. Salimans et al. Improving GANs Using Optimal Transport, ICLR 2018; A. Genevay, G. Peyré, M. Cuturi. Sinkhorn AutoDiff, AISTATS 2018; M. Bellemare et al. The Cramér Distance, 2017; K. Li, J. Malik. Implicit Maximum Likelihood Estimation, 2018.
  • Y. Li, K. Swersky, R. Zemel. Generative Moment Matching Networks, ICML 2015; A. Gretton et al. A Kernel Two-Sample Test, JMLR 2012.
  • E. Tzeng et al. Deep Domain Confusion, 2014; J. Ho, S. Ermon. Generative Adversarial Imitation Learning, NeurIPS 2016.
  • A. Sauer, K. Schwarz, A. Geiger. StyleGAN-XL, SIGGRAPH 2022; M. Kang et al. Scaling up GANs for Text-to-Image Synthesis (GigaGAN), CVPR 2023.
  • P. Esser, R. Rombach, B. Ommer. Taming Transformers for High-Resolution Image Synthesis (VQGAN), CVPR 2021; J. Yu et al. Vector-Quantized Image Modeling with Improved VQGAN (ViT-VQGAN), ICLR 2022.

Added by these notes

  • H. Petzka, A. Fischer, D. Lukovnikov. On the Regularization of Wasserstein GANs (the one-sided penalty), ICLR 2018.
  • L. Mescheder, A. Geiger, S. Nowozin. Which Training Methods for GANs Do Actually Converge? (R1), ICML 2018.
  • R. Zhang et al. The Unreasonable Effectiveness of Deep Features as a Perceptual Metric (LPIPS), CVPR 2018.
  • G. Peyré, M. Cuturi. Computational Optimal Transport, 2019 — the primal and dual problems behind §1 and §6.

13. Next lecture

GANs gave sharp samples but no likelihood, unstable games, and — on ShapeWorld — never a valid image. Lecture 11 turns to the models that replaced them: diffusion models, trained by a likelihood bound like a VAE, sampling by many small denoising steps. ShapeWorld’s exact distribution makes it possible to compute the optimal denoiser — so we can see exactly what a trained network gets right, what the samplers lose, and what guidance does to a conditional distribution.

← 返回课程目录