Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.A speed limit instead of a cage
The Wasserstein critic must be ‘Lipschitz’: its output may not change faster than its input. The original WGAN enforced this by clamping every weight inside a small box, which is like caging the critic; it works, but the critic ends up too timid to measure distances well. WGAN-GP gives the critic a speed limit instead. At random points between real and fake samples it checks how steep the critic is, and charges a fine whenever the steepness is not 1. The demo plots the fine as a function of steepness, for the usual two-sided version and a one-sided version that only fines speeding.
Gradient penalties keep learned critics and discriminators well behaved in many settings beyond images, such as GAN-based simulators of radar or particle detectors, and the adversarial regularisers used in imitation learning for robots.
- 1. WGAN-GP replaces weight clipping with…
- 2. The penalty is checked at…
- 3. The target gradient norm is…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Loss. L = E over fakes of f(x̃) − E over reals of f(x) + λ E over x̂ of (‖∇_x̂ f(x̂)‖₂ − 1)², with x̂ = εx + (1 − ε)x̃, ε ~ U[0, 1] per pair, λ = 10.
- Motivation (Proposition 1 of the paper). If f* is an optimal 1-Lipschitz critic and (x, y) is drawn from the optimal coupling, then on the segment between y and x the gradient of f* exists and has unit norm, pointing toward x.
- Settings. n_critic = 5, Adam with learning rate 10⁻⁴, β1 = 0, β2 = 0.9. No batch norm in the critic: the penalty is per sample, and batch norm couples samples (layer norm is the usual replacement).
- Two-sided versus one-sided. max(0, ‖∇f‖ − 1)² only penalises slopes above 1, which matches the Lipschitz constraint exactly; the paper found the two-sided form worked slightly better in practice, and Petzka et al. (2018) later argued for the one-sided form.
- Implementation. The penalty contains ∇_x f, so its gradient with respect to the parameters needs a second backward pass (‘double backprop’): torch.autograd.grad(…, create_graph=True).
- Descendants. DRAGAN (Kodali et al. 2017) penalises around real data; R1 (Mescheder et al. 2018) penalises ‖∇f‖² on real data only and is used in StyleGAN; ProGAN adds a drift term 0.001·E f(x)².
- Reported results. Stable training of very different architectures (MLP generators, no batch norm, 101-layer ResNets, character-level language models) with default settings.
- 1. WGAN-GP's λ is usually…
- 2. Batch norm is avoided in the critic because…
- 3. R1 penalises the gradient on…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Penalties and double backprop
Exercise 1.
- Random interpolates between paired real and fake samples.
- Two-sided and one-sided gradient penalties.
- The full critic loss.
- The input gradient of a tanh critic, checked against finite differences.
Practice.
- Default: λ = 10, n_critic = 5, Adam(1e-4, β1 = 0, β2 = 0.9), layer norm or no normalisation in the critic.
- Use create_graph=True when computing the input gradient so that the penalty can be backpropagated.
- Mixed precision: compute the penalty in float32, since squared gradient norms overflow easily in float16.
- Cheaper alternatives: spectral normalisation (no second backward pass) or lazy R1 regularisation applied every 16 steps as in StyleGAN2.
- Watch the gradient norm: log the mean ‖∇f‖ on interpolates; values far from 1 mean λ is too small or the critic is under-trained.
import torch
def gradient_penalty(critic, real, fake, lam=10.0):
eps = torch.rand(real.size(0), *[1] * (real.dim() - 1), device=real.device)
x_hat = (eps * real + (1 - eps) * fake).requires_grad_(True)
g, = torch.autograd.grad(critic(x_hat).sum(), x_hat, create_graph=True)
return lam * ((g.flatten(1).norm(dim=1) - 1) ** 2).mean()
loss_c = critic(fake.detach()).mean() - critic(real).mean() + gradient_penalty(critic, real, fake.detach())- 1. create_graph=True is needed because…
- 2. StyleGAN2 makes R1 cheaper by…
- 3. A mean gradient norm far from 1 suggests…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Unit gradients of the optimal critic. Let γ* be an optimal coupling and f* an optimal critic, so that f*(x) − f*(y) = ‖x − y‖ for (x, y) in the support of γ* (complementary slackness in Kantorovich–Rubinstein duality). For the point x_t = tx + (1 − t)y, the 1-Lipschitz bound gives f*(x) − f*(x_t) ≤ (1 − t)‖x − y‖ and f*(x_t) − f*(y) ≤ t‖x − y‖. Both must hold with equality because they add up to ‖x − y‖, so f* increases at unit rate along the segment. A 1-Lipschitz function with unit directional derivative in some direction has gradient norm exactly 1 there, pointing along x − y.
Why random interpolates. Enforcing the constraint everywhere is intractable. The interpolates cover the region between the data and the samples, which is where the generator’s gradients come from and where the optimal critic has unit gradients. It is a heuristic: for an imperfect generator the pairs are not the optimal coupling.
Soft constraint. The penalty trades the Wasserstein term against λ(‖∇f‖ − 1)². Raising slopes slightly above 1 gains more in E f(real) − E f(fake) than it costs in penalty, so trained critics typically show gradient norms a little above 1 and overestimate W1.
The 1-D trap. In one dimension the gradient is a signed slope, and the set of unit-norm slopes is two points, +1 and −1. A critic that starts with the wrong sign must pass through slope 0 to fix it, paying λ along the way: a barrier that can trap gradient descent. In d ≥ 2 the unit sphere is connected and the gradient direction can rotate without its norm passing through 0.
- 1. Along optimal transport segments the optimal critic's gradient norm is…
- 2. A soft penalty typically yields gradient norms…
- 3. In 1-D a critic with the wrong slope sign must…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How well do clipped and gradient-penalised critics estimate a known Wasserstein distance?
History.
- I. Gulrajani, F. Ahmed, M. Arjovsky, V. Dumoulin and A. Courville, “Improved training of Wasserstein GANs” (NeurIPS 2017).
- H. Petzka, A. Fischer and D. Lukovnikov, “On the regularization of Wasserstein GANs” (ICLR 2018).
- L. Mescheder, A. Geiger and S. Nowozin, “Which training methods for GANs do actually converge?” (ICML 2018): R1.
Exercise 2. The fakes are the real data shifted by 1.5 along the first axis, so the true W1 is exactly 1.5 (the shift is the optimal transport map).
- Data: in 2-D a ring of 8 Gaussians (radius 2, std 0.1); in 1-D two Gaussians at ±2 (std 0.3).
- Critics: f(x) = tanh(xW + b)v + c with 32 hidden units, trained for 500 steps with Adam (lr 0.003, β1 = 0.5, β2 = 0.9), batch 128. In 2-D: clipping at 0.01, clipping at 0.1, and 4 independently initialised critics with a gradient penalty (λ = 10). In 1-D: 4 penalty critics. The penalty’s parameter gradient is computed by hand (double backprop).
- Measures on 4000 fresh samples: E f(real) − E f(fake), mean gradient norm on interpolates, share of weights on the clipping bound.
| critic | seed 0 | seed 1 | seed 2 |
|---|---|---|---|
| clip 0.01: estimate (gradient norm) | 0.0047 (0.0045) | 0.0049 (0.0037) | 0.0047 (0.0033) |
| clip 0.1: estimate (gradient norm) | 0.461 (0.316) | 0.476 (0.317) | 0.474 (0.316) |
| clip 0.1: weights on the bound | 0.5 | 0.5 | 0.5 |
| penalty, 2-D: estimates | 1.666, 1.666, 1.686, 1.634 | 1.654, 1.676, 1.705, 1.728 | 1.712, 1.735, 1.67, 1.691 |
| penalty, 2-D: gradient norms | 1.077, 1.072, 1.062, 1.075 | 1.057, 1.082, 1.084, 1.07 | 1.067, 1.089, 1.071, 1.079 |
| penalty, 1-D: estimates | −1.289, 0.323, 1.651, 1.55 | −1.311, 1.605, 1.619, 0.157 | −1.367, 1.675, 0.181, 0.063 |
- Clipping: estimates are a c-dependent fraction of W1 (0.3% at c = 0.01, 31% at c = 0.1), and half or more of all weights sit exactly on ±c (at c = 0.1: every output weight and every input weight on the shift axis).
- Gradient penalty in 2-D: all 12 critics recovered W1 within 9–16% with gradient norms 1.06–1.09; the overestimate matches the soft-constraint argument.
- Gradient penalty in 1-D: only 5 of 12 critics succeeded; the others stalled near slope 0 or at slope −1 (estimates about −1.3). This is consistent with the sign-flip barrier, a 1-D artifact that does not arise in higher dimensions.
Gradient penalties in AI, robotics and aerospace
- Stable adversarial training: ProGAN and many scientific GANs (detector simulation, cosmology emulators) used WGAN-GP; StyleGAN uses its descendant R1.
- Imitation learning: adversarial imitation methods (GAIL and successors) for robot control often add gradient penalties to the discriminator to keep rewards smooth.
- Distribution distances as metrics: penalised critics are used as learned Wasserstein estimates to compare simulated and real sensor data.
References
- I. Gulrajani, F. Ahmed, M. Arjovsky, V. Dumoulin and A. Courville (2017). “Improved training of Wasserstein GANs.” NeurIPS.
- H. Petzka, A. Fischer and D. Lukovnikov (2018). “On the regularization of Wasserstein GANs.” ICLR.
- L. Mescheder, A. Geiger and S. Nowozin (2018). “Which training methods for GANs do actually converge?” ICML.
- N. Kodali, J. Abernethy, J. Hays and Z. Kira (2017). “On convergence and stability of GANs.” arXiv (DRAGAN).
- T. Karras, T. Aila, S. Laine and J. Lehtinen (2018). “Progressive growing of GANs for improved quality, stability, and variation.” ICLR.