Wasserstein GAN: distance, critics and constraints
Wasserstein GAN
Compute transport and a dual certificate, then expose the limits of linear critics and soft penalties.
wganHow far must the mass move?
Put all real probability mass at zero and all generated mass at θ. If θ is small but nonzero, their supports remain disjoint. A divergence based only on distinguishing these point masses may not reflect how close their positions are. Transport asks a different question: how much probability must move, and how far?
The Wasserstein-1 distance in this example is |θ|. It approaches zero continuously as θ approaches zero, though it has a cusp at zero. The WGAN paper gives a related parallel-line example and proposes a trainable critic based on a transport duality. A critic returns a real score, not a real/fake probability. Read GANs and expectation first.
A distance and its dual
A coupling is a joint distribution whose two marginals equal the distributions being compared. For finite supports, its matrix specifies how much mass moves from each real location to each generated location. Minimize total distance-weighted mass:
For probability measures on Euclidean space with finite first moments, Kantorovich–Rubinstein duality expresses the same distance through 1-Lipschitz functions. A function is 1-Lipschitz when its score difference never exceeds input distance.
WGAN approximates this optimization with a parameterized critic. A restricted function family or an incompletely optimized critic need not attain the supremum. Replacing the bound one by K scales the unrestricted supremum by K. These qualifications are explicit in Section 3; an observed neural score difference should not automatically be labeled the exact Wasserstein distance.
Build a certificate in one dimension
For finite one-dimensional measures, sort the support points and match the leftmost remaining masses. Crossed transport paths can be uncrossed without increasing absolute-distance cost. Repeating this exchange gives a monotone optimal coupling. Our first algorithm constructs that coupling directly and checks its marginals.
An independent calculation uses cumulative mass differences. Merge the supports into ordered locations t, define the difference d at each location, and let S be its prefix sum. Across each interval, net mass S must pass. Its distance-weighted absolute value yields the cost:
To prove that this cost can also be achieved by a dual function, start f0=0 and choose each interval’s slope opposite to the sign of S. Summation by parts gives matching primal and dual values:
Piecewise-linear interpolation has slopes of magnitude at most one; constant extension beyond the endpoints makes a globally 1-Lipschitz function. This is an exact certificate for the finite one-dimensional teaching problem. It is not an exact solver for a high-dimensional neural critic.
Now compare a two-mode distribution with a point mass at the same mean. Every linear critic gives zero difference, even though transport costs one:
The bottleneck here is critic capacity. Training that linear critic longer cannot create the missing nonlinear function.
Transport, critic updates and a penalty counterexample
Save as wgan.py; use Python 3.12 and NumPy 1.26.4. Sorting costs O(n log n+m log m), and monotone matching then costs O(n+m). The program stores an O(nm) coupling matrix for inspection; an implementation that only accumulates the cost need not store that matrix. The dual calculation is linear after sorting.
The final experiment actually updates a linear critic and a point-mass generator: P is at zero and Q is at θ. It projects the critic weight into [−1,1], makes five critic steps per generator step and uses plain gradient updates with rate 0.05. This is a teaching optimizer, not the original paper’s RMSProp implementation. Keeping both the lagging critic gap and the exact |θ| reveals why a training loss can mislead.
"""Original 1D transport/dual certificate and hard-versus-soft linear critic examples."""
import json
import numpy as np
def measure(support, weights):
x, p = np.asarray(support, float), np.asarray(weights, float)
if (x.ndim != 1 or not 1 <= x.size <= 64 or p.shape != x.shape
or not np.isfinite(x).all() or not np.isfinite(p).all()
or np.max(abs(x)) > 10 or np.any(p < 0) or abs(float(p.sum())-1) > 1e-12):
raise ValueError('1..64 support points in [-10,10] and probability weights required.')
unique, inverse = np.unique(x, return_inverse=True)
merged = np.bincount(inverse, weights=p, minlength=len(unique))
return unique, merged/p.sum()
def transport(x, p, y, q):
"""Greedy monotone coupling. Rows/columns refer to sorted, merged supports."""
x, p = measure(x, p)
y, q = measure(y, q)
remaining_p, remaining_q = p.copy(), q.copy()
coupling = np.zeros((len(p), len(q)))
i = j = 0
while i < len(p) and j < len(q):
mass = min(remaining_p[i], remaining_q[j])
coupling[i, j] += mass
remaining_p[i] -= mass
remaining_q[j] -= mass
if remaining_p[i] <= 0:
i += 1
if remaining_q[j] <= 0:
j += 1
cost = float(np.sum(coupling*abs(x[:, None]-y)))
return cost, coupling
def dual_certificate(x, p, y, q):
x, p = measure(x, p)
y, q = measure(y, q)
grid = np.union1d(x, y)
difference = np.zeros(len(grid))
np.add.at(difference, np.searchsorted(grid, x), p)
np.add.at(difference, np.searchsorted(grid, y), -q)
cumulative = np.cumsum(difference)[:-1]
intervals = np.diff(grid)
potential = np.r_[0., np.cumsum(-np.sign(cumulative)*intervals)]
return dict(grid=grid, potential=potential, cumulative=cumulative,
cdf_cost=float(abs(cumulative)@intervals), dual=float(difference@potential))
def soft_linear_critic(theta=2., penalty=10.):
"""Exact optimum of -w*theta-lambda*(abs(w)-1)^2; theta must be positive."""
if (not np.isfinite(theta) or not 0 < theta <= 10
or not np.isfinite(penalty) or not .01 <= penalty <= 100):
raise ValueError('Theta in (0,10] and penalty in [.01,100] required.')
w = -(1+theta/(2*penalty))
gap = -w*theta
penalized = gap-penalty*(abs(w)-1)**2
return dict(weight=float(w), gap=float(gap), penalized=float(penalized), true_w1=float(theta))
def train_linear(steps=100, rate=.05, critic_steps=5):
if (isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 1000
or not np.isfinite(rate) or not 0 < rate <= .1
or isinstance(critic_steps, bool) or not isinstance(critic_steps, int)
or not 1 <= critic_steps <= 20):
raise ValueError('Bounded integer iteration counts and rate in (0,.1] required.')
theta, w = 2., 0.
history = [[0, theta, w, -w*theta, abs(theta)]]
for step in range(1, steps+1):
for _ in range(critic_steps):
w = float(np.clip(w-rate*theta, -1, 1))
theta += rate*w # generator minimizes -w*theta with w fixed
history.append([step, theta, w, -w*theta, abs(theta)])
return history
def demo():
x, p, y, q = [-1., 1.], [.5, .5], [0.], [1.]
cost, coupling = transport(x, p, y, q)
certificate = dual_certificate(x, p, y, q)
certificate = {k: v.tolist() if isinstance(v, np.ndarray) else v for k, v in certificate.items()}
history = train_linear()
return dict(same_mean_example=dict(w1=cost, coupling=coupling.tolist(), linear_gap=0., **certificate),
soft_penalty=soft_linear_critic(),
checkpoints=history[::10], minimum_lagging_gap=min(r[3] for r in history))
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, allow_nan=False))
A soft penalty is not a hard constraint
The original WGAN constrains network weights to a bounded box. For a fixed suitable architecture, this yields a common Lipschitz bound, but that bound is not automatically one. The paper also discusses problems with overly tight or loose clipping. The fixed author training code uses variable numbers of critic updates and clips before the optimizer step; do not assume every implementation line has the same timing as the paper’s pseudocode.
WGAN-GP replaces clipping with a penalty on the input-gradient norm at interpolated real/fake points. With the following convention, both displayed losses are minimized:
The derivative is with respect to the input, not the critic’s weights. The paper omits critic batch normalization because it couples outputs across samples, conflicting with this per-input penalty interpretation. Its stated default λ is 10; the fixed toy implementation uses 0.1. These are different configurations, not interchangeable reproduction instructions.
A finite penalty can prefer a slope magnitude greater than one. For P at zero, Q at θ>0 and f(x)=wx, maximize the real-minus-fake gap minus the penalty:
At θ=2 and λ=10, the optimum has w=−1.1. Its raw gap is 2.2; its penalized maximization value is 2.1; the true W1 is 2. The maximization value is the negative of the corresponding minimized critic loss. This exact linear counterexample already rules out a general claim that finite gradient penalties enforce 1-Lipschitzness or return the exact distance. Sampling only selected inputs adds another limit.
In the projected linear training run, |w| never exceeds one, but the lagging critic gap reaches about −0.236000 while the exact distance stays nonnegative. A particular feasible function’s expectation difference can be negative; the supremum defining W1 cannot. This gap, the full penalized loss and the exact transport distance are three different quantities. Neither clipping nor gradient penalties by themselves establish universal convergence or complete mode coverage.
Audit a distance claim
- Move a unit point mass from zero to two. Give a coupling and its cost.
Answer: The only coupling transports mass one from 0 to 2, at cost 2. The function f(x)=−x attains the dual gap 2 for real mass at zero and generated mass at two.
- Two distributions have equal means. Must W1 be zero?
Answer: No. The ±1 mixture and the point mass at zero have equal means but W1=1. Linear critics miss this distinction; the piecewise-linear certificate detects it.
- For θ=2 and λ=10 in the linear soft-penalty example, calculate the optimal slope, gap and penalty.
Answer: The slope is −1.1, the gap is 2.2, and the penalty is 10×0.1²=0.1. The penalized maximization value is 2.1, not the true distance 2.
- A training log reports a negative real-minus-fake gap. Has the Wasserstein metric become negative?
Answer: No. The current critic may be poorly optimized or lag behind G. A feasible critic’s gap can be negative; the optimal supremum is nonnegative. First identify whether the log shows a raw gap or a signed, penalized loss.
Reading the papers as separate claims
Both WGAN and WGAN-GP first appeared in 2017, but the inspected files are WGAN v3 dated December 6 and WGAN-GP v1 dated March 31. Compare WGAN Sections 2–3 with WGAN-GP Algorithm 1 and Section 4. Keep the version, sign convention, optimizer and clipping or penalty settings beside any reported loss. The fixed author implementations provide concrete comparisons, including a toy penalty weight different from the paper default; no upstream training is represented here as having been rerun.
Make a prediction, then check
Does a finite WGAN-GP penalty guarantee a globally 1-Lipschitz critic?
Learning objectives
- Compute a finite one-dimensional transport plan.
- Construct a Lipschitz dual certificate.
- Separate critic estimates from exact distance.
- Explain clipping and sampled gradient penalties.
Prerequisites & connections
Explore related knowledge →References
- Wasserstein GAN (v3): transport, dual critic and clipping
Martin Arjovsky; Soumith Chintala; Léon Bottou · 2017 - Improved Training of Wasserstein GANs (v1): sampled gradient penalty
Ishaan Gulrajani; Faruk Ahmed; Martin Arjovsky; Vincent Dumoulin; Aaron Courville · 2017 - WassersteinGAN author training code at f7a01e8
Martin Arjovsky; Soumith Chintala; Léon Bottou and contributors · 2018 - Improved WGAN toy implementation at fa66c57
Ishaan Gulrajani and contributors · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked WGAN v3 selected transport/dual/clipping sections, WGAN-GP v1 method and fixed author code. Seven paired equations, four explained exercises; original finite one-dimensional transport/dual certificate, linear soft-penalty counterexample and actual lagging-critic updates. No high-dimensional exact solver or image benchmark.
- Checked monotone coupling marginals/cost against independent CDF and dual calculations, global piecewise-linear Lipschitz certificate, equal-mean critic-capacity counterexample, soft penalty slope/gap and projected finite critic updates with negative lagging gap.
- Four computed SVGs bind each actual bilingual program. Group passed16 numerical/geometry checks and24 isolated responsive cases at390/768/1536 with four fallback fonts. Eight final representative screenshots actually viewed. Added VQ numeric labels and equal-unit phase axes with preserved originals; data unchanged. Full article-page acceptance is separate, not independent human review.
- Post-freeze wording correction: the displayed optimum is -1.1, whose magnitude exceeds one. Both language sentences and figure headings now explicitly refer to magnitude; equations/program/data are unchanged, immutable frozen originals retained. Exact delta and renewed validation are recorded under editorial/corrections/012b-wgan-slope-magnitude.
Source locations checked:
- Wasserstein GAN (v3): transport, dual critic and clipping · Read Section2 transport/parallel-line example and Section3 selected duality, K scaling, optimality assumptions, clipping/algorithm and fixed-D collapse discussion. Inspected PDF page7. First2017-01-26; v3 dated2017-12-06. No appendix proof or benchmark replication.
- Improved Training of Wasserstein GANs (v1): sampled gradient penalty · Read selected Section3 clipping failures, Algorithm1 and Section4 penalty/interpolates/default lambda/no critic batch normalization. Inspected PDF page5. Explicit v1 dated2017-03-31, not latest v3. No full experiments or appendix review.
- WassersteinGAN author training code at f7a01e8 · Read lines150–225, RMSProp/Adam choice, dynamic critic counts and clipping placement. Commit2018-12-26; full root BSD3-Clause license read. Reference only; no upstream execution or copied code.
- Improved WGAN toy implementation at fa66c57 · Read lines20–90, lambda=.1 in toy code versus10 in paper, losses/interpolation/input-gradient penalty. Commit2017-06-22; full root MIT license read. No upstream execution or copied code.
Related topics