15 / 34 · GANs
Wasserstein GANs and Lipschitz constraints
Why the Wasserstein distance gives the generator a slope where Jensen–Shannon goes flat, what it demands of the discriminator, and the practical approximations used by gradient penalties and spectral normalization.
On this page 5
Put all the data at one point, , and let the generator put all its samples at . For and the Jensen–Shannon divergence is the same, , because the distributions do not overlap in either case. The exact JS objective cannot tell that the second model is closer. This is a limitation of that objective in this example, not a claim that every finite GAN discriminator or non-saturating generator loss has zero gradient. The GAN note distinguishes those training losses.
What we want is a distance that measures how far the generated samples are from the data, and keeps shrinking as they approach. The Wasserstein GAN uses the Wasserstein-1 distance (Arjovsky, Chintala and Bottou, 2017). It brings a new demand: the discriminator, now called the critic, must not change faster than distance.
Wasserstein-1 distance#
Think of the data distribution and the generator’s distribution as two piles of earth of equal mass. A transport plan says how much mass moves from to ; its marginals must be and , and is the set of all such plans (Peyré and Cuturi, 2019). Moving mass a distance costs . The Wasserstein-1 distance, or earth mover’s distance, is the cheapest total cost:
For the two point masses of the opening with , there is one plan, moving everything a distance :
These JS and KL values assume . The mixture then puts mass on each atom. At , all three discrepancies are zero. Away from zero, JS is flat while has slope : descending it moves the model toward the data. Arjovsky et al. illustrate the related support issue with parallel line segments; here we compute the scalar point-mass case directly.
D_JS is flat for disjoint supports; W₁ keeps a slope
The example generalizes under regularity assumptions. Write for the distribution of . On the compact data space of Arjovsky, Chintala and Bottou (2017), local Lipschitz continuity in , with integrable local constants over , gives continuity and almost-everywhere differentiability of (Theorem 1 and Assumption 1). Corollary 1 covers finite feedforward compositions of affine maps and smooth Lipschitz activations when ; the authors also state the result for rectifiers. An arbitrary network is not covered merely because it is feedforward. On a compact space, convergence in KL or JS implies convergence in , but the converse fails (Theorem 2). Our nonzero point masses approaching zero demonstrate that distinction.
The dual form#
Directly optimizing a transport plan can be costly for large distributions. The Kantorovich–Rubinstein duality instead expresses the cost through scalar functions that we can approximate by a critic. For probability distributions on a compact set, with distance as the transport cost,
where means is 1-Lipschitz: for all . The function scores real samples high and fakes low, like a discriminator, but its score may not change faster than distance. Without that constraint and with , any separating could be scaled up and the supremum would be . The same formula holds on for distributions with finite first moments, with the Lipschitz functions normalized at one point (Peyré, 2025, Section 6.5).
One direction is three lines. Take any plan and any 1-Lipschitz :
The first line holds because the marginals of are and , the second because is 1-Lipschitz. The supremum over on the left and the infimum over on the right give . Read as a price of earth at : a price list that never differs by more than the distance cannot charge more than the cheapest plan. That the best price list matches the plan exactly is the theorem, proved for compact spaces in Peyré (2025), Proposition 5.5 (Kantorovich duality) with Proposition 6.17 and Eq. (6.23), which specialize it to the cost .
For the point masses, is 1-Lipschitz and gives , attaining the supremum. Its slope at a fake sample is when ; at zero it is not differentiable and the distance is already minimized. A perfect binary discriminator only has to separate the two occupied points. Its classification objective does not prescribe a useful slope between them.
WGAN losses#
The critic is a network with a real-valued output and no sigmoid. It maximizes the dual objective; the generator appears only in the second expectation and wants the critic’s score on fakes to be high:
What does measure? If the critic family is -Lipschitz, even its best member gives , with equality only when the family contains times an optimal 1-Lipschitz critic; in training, is a minibatch estimate of it. The dual motivates training the critic close to optimality, and Theorem 3 of Arjovsky, Chintala and Bottou (2017) says why. On a compact space, with latent noise having a density and locally Lipschitz in with constants of finite mean over , an optimal 1-Lipschitz critic exists and wherever both sides are defined. The generator’s gradient, , is the gradient of when the critic is optimal: the derivative of a maximum is the partial derivative at the maximizer, an envelope argument. This idealized statement does not guarantee that finite critic optimization finds that maximizer. The original algorithm takes critic steps per generator step.
The original paper observed a correlation between a falling critic estimate and improving samples in its experiments. This is not a quality certificate: capacity, optimization, minibatch noise and the Lipschitz scale all affect the value. Comparing models requires a shared evaluation protocol; FID is one feature-based statistic with its own limitations, not an exact substitute for .
Where it breaks: clipping the weights#
The losses alone do not keep Lipschitz. The original WGAN clipped every critic weight to , with , after each step. Bounded weights give a -Lipschitz critic when it is built from linear layers and 1-Lipschitz activations. A layer’s matrix of size with entries in has rows with , so by Cauchy–Schwarz on each row . A convolution on images of fixed size is such a matrix too, with kernel weights or zeros as entries. Biases do not change a Lipschitz constant, and the product rule below gives , so the bound above holds. The authors identified clipping as a crude way to enforce the constraint (Arjovsky, Chintala and Bottou, 2017): a large can slow critic optimization, while a small can produce vanishing gradients.
The WGAN-GP paper reports two failure mechanisms in its experiments (Gulrajani et al., 2017, Section 3): clipping concentrated weights near the bounds and limited the critic’s fitted structure; a 12-layer critic also showed growing or decaying layerwise gradient norms for the tested . These are empirical demonstrations, not inevitable behavior of every clipped network. The two methods below replace clipping.
WGAN-GP: gradient penalty#
For differentiable on , being 1-Lipschitz is equivalent to everywhere. The reverse implication integrates the directional derivative along the segment between two points; the same argument works on an open convex domain. This motivates controlling gradients directly. WGAN-GP keeps the WGAN losses and adds a penalty to the critic (Gulrajani et al., 2017):
with in all the paper’s experiments. The generator’s loss is unchanged.
Why two-sided. The literal inequality suggests penalizing only norms above 1, . WGAN-GP instead pulls the norm toward 1. Proposition 1 of Gulrajani et al. (2017) motivates this using an optimal transport coupling: under its compactness and differentiability assumptions, with no mass coupled to itself, an optimal critic has unit gradient along the coupled segments. This does not say that every randomly paired segment must have unit gradient, nor that a two-sided penalty preserves every optimal critic. For our point masses, has except at zero.
Where comes from. The proposition is about segments between coupled points, and the optimal coupling is unknown. WGAN-GP pairs each real sample with a random fake, draws and takes the point
on the segment between them.
The random pairing is a heuristic, not the unknown optimal coupling. A finite soft penalty at sampled points does not certify a global Lipschitz bound. In code, draw one per image and broadcast it over pixels. torch.autograd.grad(..., create_graph=True) retains a derivative graph so that the critic parameters can receive a gradient through the penalty (PyTorch documentation). Sum independent per-image scores when taking this vector–Jacobian product, then flatten each input gradient before taking its norm. During a critic update, detach generated samples from the generator; the generator update uses its separate loss without this penalty.
The gradient penalty is evaluated between real and fake samples
No batch normalization in the critic. The penalty treats the critic as a function of one image. With batch normalization each output depends on the whole minibatch, and the per-input gradient no longer describes the function being constrained. WGAN-GP therefore drops batch normalization from the critic and recommends layer normalization. Instance normalization, which normalizes each image’s channels separately, also avoids cross-image dependence; neither choice by itself guarantees a 1-Lipschitz critic.
With the penalty, is the raw score gap minus the weighted penalty. Log both terms separately. Neither the raw gap nor the penalized objective is guaranteed to be a lower bound on : the synthetic calculation below has distance 0.65 but a penalized optimum 0.67640625. Soft regularization is not the hard dual constraint.
SN-GAN: spectral normalization#
The second approach constrains the weights instead of the gradients (Miyato et al., 2018). Divide each layer’s weight matrix by its spectral norm, its largest singular value, assuming :
A linear map sends the unit circle to an ellipse. The singular values are its semi-axes, and the largest one is the most any vector can be stretched: the Lipschitz constant of . After the division no direction is stretched by more than 1.
A matrix stretches the unit circle into an ellipse; its largest singular value is the longest semi-axis
ReLU is 1-Lipschitz; LeakyReLU is too when the absolute value of its negative slope is at most 1. Constants multiply under composition: . For a chain of linear layers and such activations,
which is at most 1 after division by the exact nonzero norms. This is a global bound for this chain architecture. A residual sum has the sum of its branches’ bounds, so normalizing each branch alone does not make the whole network 1-Lipschitz. An identically zero weight matrix already has norm zero and needs separate handling rather than division by zero.
Computing . A full SVD per update can be expensive. The practical method estimates it by a short power iteration, retaining vectors between updates. One update pair, starting from a right vector , is
For the matrix of the figure, with , starting from :
| Step | Estimate of |
|---|---|
| 1 | 1.601 |
| 2 | 1.656 |
| 3 | 1.657 |
Here , so two iterations already give error below 0.001. Reusing vectors can make short iterations effective when weights change slowly and the leading singular direction is separated. One iteration is a computational choice, not a universal accuracy guarantee; a poor initialization or a small spectral gap can make convergence slow.
The estimate is from below because for unit . Dividing by an underestimate can therefore leave a norm above 1, potentially by much more than a small rounding error. For convolution, flattening the kernel is also only a proxy for the full convolution operator; input size, stride and padding matter (Gouk et al., 2021, Section 3.2). Exact norms of a simple chain give a valid product bound, but that bound need not be tight. If a critic has a known bound , its population gap is at most ; equality requires sufficient capacity and optimality. Practical spectral normalization alone does not make its score an exact or calibrated Wasserstein estimate.
Miyato et al. used standard non-saturating GAN training and the hinge loss, comparing against WGAN-GP. Spectral normalization can be used with these different objectives. In PyTorch, torch.nn.utils.parametrizations.spectral_norm(nn.Conv2d(...)) registers a parametrization: the documented default is one power iteration when the weight is accessed in training mode, which need not mean exactly once per forward pass. The scaling note discusses its use in both networks.
What changed#
Both f-GAN in the GAN note and WGAN train a function inside a supremum. An f-divergence is built from density ratios; its behavior at disjoint supports depends on the chosen divergence. The point-mass example shows the specific JS/KL limitation here. Wasserstein-1 uses the ground distance, so it distinguishes nearby and distant disjoint supports. Its dual imposes a Lipschitz constraint that ties critic scores to that geometry.
What you should remember#
- is the cheapest cost of moving onto ; for point masses at 0 and it is , while JS is when and zero when .
- Dual: ; the critic plays and is trained close to optimal.
- Weight clipping gives an architecture-dependent bound and can limit critic capacity or damage gradients.
- WGAN-GP: on random real–fake interpolates, , no batch norm in the critic.
- Spectral normalization divides weights by an estimated norm. Exact chain bounds and practical power/convolution approximations must be distinguished.
Notebook#
Run python3 scripts/notes/generative-practice.py wgan from the repository checkout. The standard-library script creates 129 scalar samples and a second empirical distribution translated by 0.65. The saved output comes from this calculation; no image dataset or pretrained generator is needed.
- Sort the two equally weighted samples and average the absolute paired distances. Their empirical Wasserstein distance is 0.65. A linear critic with slopes 1, 3 and 9 gives gaps 0.65, 1.95 and 5.85: increasing an unconstrained critic can inflate its score without changing either distribution.
- Restrict the slope to absolute value at most 1. The optimum reaches the exact distance. Then replace that constraint with a gradient penalty of weight 4. For a positive slope , the objective is ; its optimum is , with raw gap 0.7028125 and penalized objective 0.67640625.
- The soft penalty permits a slope above 1, so neither of those latter values is the exact Wasserstein distance. This checks the critic constraint and its approximation in a family whose optimum is known. It does not train an image WGAN or establish image quality.
The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.
The numerical verifier also checks the point-mass boundary, the figure interpolation points and the spectral-norm table; its saved results include an explicit example of power iteration underestimating a norm. Run it with python3 scripts/notes/check-wgan-renewal.py. These are finite calculations, not an image-training benchmark.
Next#
Wasserstein-1 supplies a geometric training objective, while gradient penalties and spectral normalization approximate constraints on the critic. These tools do not by themselves guarantee image quality or stable optimization. The next note follows the move toward larger and more varied images through progressive growth, attention and scaling.
References#
- M. Arjovsky, S. Chintala, L. Bottou. Wasserstein GAN. arXiv:1701.07875, 2017; ICML 2017. Section 2 and Example 1 (parallel lines), Theorem 1 and Corollary 1 (continuity), Theorem 2 (strength of the distances), Theorem 3 (the gradient through an optimal critic), Section 3 and Algorithm 1 (critic, clipping, ), Section 4 (an observed correlation with sample quality).
- I. Gulrajani, F. Ahmed, M. Arjovsky, V. Dumoulin, A. Courville. Improved training of Wasserstein GANs. NeurIPS, 2017. Section 3 (failures of clipping), Proposition 1 (on a compact space), Section 4 and Algorithm 1 (the penalty, , no batch normalization in the critic).
- T. Miyato, T. Kataoka, M. Koyama, Y. Yoshida. Spectral normalization for generative adversarial networks. ICLR, 2018. Section 2 (the bound, Eq. 7); Section 4 (objectives); Appendix A (power iteration).
- G. Peyré. Optimal transport for machine learners. arXiv:2505.06589, 2025; version 3, 2026. Proposition 5.5 (Kantorovich duality on compact spaces, with proof), Section 6.5: Proposition 6.17 and Eq. (6.23) (the Kantorovich–Rubinstein formula) and the case of non-compact spaces.
- G. Peyré, M. Cuturi. Computational optimal transport. Foundations and Trends in Machine Learning, 11(5–6), 2019. Chapter 2; Section 6.1 and Eq. (6.1): on metric spaces.
- H. Gouk, E. Frank, B. Pfahringer, M. J. Cree. Regularisation of neural networks by enforcing Lipschitz continuity. Machine Learning, 110, 2021. Section 3.2: the operator norm of a convolution.
- R. Isachenko. Deep Generative Models, MIPT and YSDA, 2025. Lecture 5: the Wasserstein distance, Kantorovich–Rubinstein duality, weight clipping.
- PyTorch 2.15 documentation:
autograd.grad,parametrizations.spectral_norm. API behavior only; no training run is claimed. - A. Ryzhikov, S. Ali, A. Akhmatova, T. Ramazyan, K. Aithadzhaev, A. Khizhik. GenAI, Lecture 3: WGAN and the optimal transport problem, HSE, 25 January 2025. Background course reference; the local examples and checks use no lecture images, dataset or notebook code.