25.4 Test Functions and Transport

A model whose samples miss the data learns nothing from an f-divergence: on disjoint supports, every member of that family reduces to a constant (Section 25.3.1.2), and a constant has zero gradient. That diagnosis came from an extreme example, two point masses. Real distributions usually have spread: two Gaussians overlap everywhere because their tails never reach zero. Does a little overlap bring the gradient back? The f-divergences also left us with a practical burden: because they depend on the density ratio p/qp/q, which raw samples do not provide, we had to train a critic network just to estimate the divergence (Section 25.3.4). Can we compare two distributions from samples alone, with no critic at all?

To answer the first question with numbers, let the data distribution be P=N(0,1)P = \mathcal{N}(0, 1) and the model be Q=N(d,1)Q = \mathcal{N}(d, 1), the same bell curve shifted by dd standard deviations, where dd is the model's single parameter. Below, after importing the libraries we need, we evaluate the five comparisons from Table 25.3.1 on this pair along with their slopes in dd, which are the gradients the model would receive during training. The formulas used in the code are derived in the previous section and this one; for now, focus only on the printed numbers, which we will refer to as the opening table.

from scipy import optimize
from scipy.stats import norm
def js(d, x=np.linspace(-12, 20, 6401)):
    """JS divergence of N(0, 1) and N(d, 1) by quadrature on the grid x."""
    log_p, log_q = norm.logpdf(x), norm.logpdf(x, loc=d)
    log_m = np.logaddexp(log_p, log_q) - math.log(2)    # log of the mixture
    terms = np.exp(log_p) * (log_p - log_m) + np.exp(log_q) * (log_q - log_m)
    return terms.sum() * (x[1] - x[0]) / 2

comparisons = {                       # N(0, 1) against N(d, 1), RBF ell = 1
    'KL': lambda d: d ** 2 / 2,
    'JS': js,
    'TV': lambda d: 2 * norm.cdf(d / 2) - 1,
    'MMD^2': lambda d: 2 / math.sqrt(3) * (1 - math.exp(-d ** 2 / 6)),
    'W1': lambda d: d}
h = 1e-3                              # step of the central difference
print('   d' + ''.join(f'{name:>8s} {"slope":>7s}' for name in comparisons))
for d in (0.5, 1.0, 2.0, 4.0, 8.0):
    print(f'{d:4.1f}' + ''.join(
        f'{f(d):8.3f} {(f(d + h) - f(d - h)) / (2 * h):7.1e}'
        for f in comparisons.values()))
   d      KL   slope      JS   slope      TV   slope   MMD^2   slope      W1   slope
 0.5   0.125 5.0e-01   0.030 1.2e-01   0.197 3.9e-01   0.047 1.8e-01   0.500 1.0e+00
 1.0   0.500 1.0e+00   0.111 2.0e-01   0.383 3.5e-01   0.177 3.3e-01   1.000 1.0e+00
 2.0   2.000 2.0e+00   0.337 2.2e-01   0.683 2.4e-01   0.562 4.0e-01   2.000 1.0e+00
 4.0   8.000 4.0e+00   0.633 6.9e-02   0.954 5.4e-02   1.074 1.1e-01   4.000 1.0e+00
 8.0  32.000 8.0e+00   0.693 2.0e-04   1.000 1.3e-04   1.155 7.2e-05   8.000 1.0e+00

When the two Gaussians are half a standard deviation apart, all five slopes lie between 0.10.1 and 11, so any of these objectives would train the model effectively. By d=8d = 8, however, the Jensen--Shannon divergence has saturated at 0.6930.693 and total variation at 1.0001.000 (the same constants log⁡2\log 2 and 11 we saw for disjoint point masses), and both slopes have fallen to roughly 10−410^{-4}. Overlapping tails do not rescue them. The KL divergence still has a healthy slope equal to dd itself, but only because a Gaussian model assigns positive density to every data point; an implicit generator whose samples lie on a low-dimensional surface has no such density. That leaves the two distances that remained informative for point masses. MMD2\textrm{MMD}^2 grows initially but stalls by d=8d = 8, reaching 1.1551.155 with a slope below 10−410^{-4}. Only W1W_1 stays linear, equaling dd with a slope of 11 at every separation.

Neither MMD nor W1W_1 relies on the density ratio p/qp/q. Instead, MMD compares how PP and QQ average a class of functions: averages can be estimated directly from samples, and the choice of function class governs how far apart two distributions can be and still produce a useful signal. W1W_1 begins from a geometric question: how far must probability mass travel to reshape one distribution into the other? Surprisingly, it turns out to be a comparison of averages as well. Two results organize the rest of this section. Over a fixed set of features, the comparison of averages admits a closed form with no auxiliary network to train. Meanwhile, the minimum cost of moving mass equals the largest gap in averages over functions of slope at most one, which is the duality behind the Wasserstein GAN (Section 16.2). Throughout, PP denotes the data and QQ the model, and we work with concrete examples on the real line.

25.4.1 Integral Probability Metrics and MMD#

25.4.1.1 Classes of Test Functions#

Total variation is a proper metric, yet it still flattened out in the opening table. Its variational form explains both why that happened and how to fix it: total variation is the largest disagreement between PP and QQ over the probability of any event AA (Section 25.3.3), namely TV(P,Q)=sup⁡A∣P(A)−Q(A)∣\textrm{TV}(P, Q) = \sup_A |P(A) - Q(A)|. Since the probability of an event is simply the expectation of its indicator function, total variation is a supremum, taken over a class of functions, of the difference between two averages. Nothing forces us to restrict ourselves to indicator functions. Given any class G\mathcal{G} of test functions gg, the integral probability metric (IPM) (Müller, 1997) is defined as

IPMG(P,Q)=sup⁡g∈G (Ex∼P[g(x)]−Ex∼Q[g(x)]).(25.4.1)\textrm{IPM}_{\mathcal{G}}(P, Q) = \sup_{g \in \mathcal{G}} \,\big( \mathbb{E}_{x \sim P}[g(x)] - \mathbb{E}_{x \sim Q}[g(x)] \big). \tag{25.4.1}

Think of G\mathcal{G} as a panel of auditors, each scoring points in the space; the IPM reports the largest gap in average score that any auditor on the panel can uncover. Every class we consider is symmetric, meaning −g-g belongs to G\mathcal{G} whenever gg does, so the gap is always non-negative and symmetric in PP and QQ. Whether the IPM vanishes only when P=QP = Q, as the word "metric" promises, depends on whether G\mathcal{G} is rich enough to distinguish any two distinct distributions. The critic of Section 25.3.4 played a similar auditing role, but with a crucial difference: in the variational bound Df(P∥Q)≥EP[T]−EQ[f∗(T)]D_f(P\|Q) \geq \mathbb{E}_P[T] - \mathbb{E}_Q[f^*(T)], the convex conjugate f∗f^* automatically keeps an unconstrained critic TT in check. In an IPM, gg is averaged directly under both PP and QQ, so nothing constrains gg except membership in G\mathcal{G}. Everything therefore hinges on choosing the right class.

Three function classes take center stage here:

  • Bounded functions with ∣g∣≤12|g| \leq \tfrac{1}{2} recover total variation. An indicator function minus 12\tfrac{1}{2} satisfies this bound, the constant cancels in the difference of averages, and g=12 sign(p−q)g = \tfrac{1}{2}\,\textrm{sign}(p - q) attains the supremum.
  • Functions that are linear in a fixed set of features yield the maximum mean discrepancy (MMD) (Gretton et al., 2012), which we construct next.
  • Functions with slope at most one yield the Wasserstein distance, covered in detail in Section 25.4.2.

Why not simply choose the largest possible class G\mathcal{G} every time? A useful class must satisfy two competing requirements, and making G\mathcal{G} too large breaks the first. First, sample averages must track true expectations. While samples let us estimate expectations directly without a density ratio, an overly rich panel of auditors will always find spurious gaps between finite samples. For example, two independent samples of 1,0001{,}000 points drawn from the same continuous distribution share no points at all. The indicator function of the first sample averages to 11 on the first sample and 00 on the second, so the empirical total variation is 11 regardless of whether PP and QQ are identical. To avoid this, G\mathcal{G} must be small or smooth enough to exclude such spiky functions.

Second, the gap should keep growing as PP and QQ move farther apart, which requires G\mathcal{G} to contain functions that grow with distance. Total variation has none: because its test functions are bounded by 12\tfrac{1}{2}, its gap can never exceed 11. The largest disagreement occurs on the event {p>q}\{p > q\}, which for the two Gaussians in the opening table is the half-line x<d/2x \lt d/2. Computing the probability of that half-line under both Gaussians gives TV=Φ(d/2)−Φ(−d/2)=2Φ(d/2)−1\textrm{TV} = \Phi(d/2) - \Phi(-d/2) = 2\Phi(d/2) - 1, where Φ\Phi is the standard normal cumulative distribution function (CDF). That value reaches 0.9540.954 at d=4d = 4 and lies within 10−410^{-4} of 11 at d=8d = 8. Once a step function separates the two bell curves almost completely, pushing them farther apart changes the score by virtually nothing. Total variation fails both requirements, and we will judge our next two classes against both.

25.4.1.2 Mean Features and Kernels#

Let us build a better class from the ground up, starting from the smallest possible panel of auditors and testing each step on a single pair: P=N(0,1)P = \mathcal{N}(0, 1) against Q=N(0,4)Q = \mathcal{N}(0, 4), which share the same mean but differ in variance.

Start with the simplest choice, linear test functions g(x)=w xg(x) = w\, x with ∣w∣≤1|w| \leq 1. Here EPg−EQg=w (EPX−EQX)\mathbb{E}_P g - \mathbb{E}_Q g = w\,(\mathbb{E}_P X - \mathbb{E}_Q X), so taking the supremum over ∣w∣≤1|w| \leq 1 gives ∣EPX−EQX∣|\mathbb{E}_P X - \mathbb{E}_Q X|, the distance between the two means. That panel is blind to variance, and on our test pair it reports 00.

To see spread as well as location, add a second feature. Define the feature map φ(x)=(x,x2)\boldsymbol{\varphi}(x) = (x, x^2) and take linear combinations g(x)=w⊤φ(x)g(x) = \mathbf{w}^\top \boldsymbol{\varphi}(x) with ∥w∥≤1\|\mathbf{w}\| \leq 1. Writing mP=EP[φ(x)]\mathbf{m}_P = \mathbb{E}_P[\boldsymbol{\varphi}(x)] for the mean feature of PP (and similarly mQ\mathbf{m}_Q for QQ), the gap in averages is EPg−EQg=w⊤(mP−mQ)\mathbb{E}_P g - \mathbb{E}_Q g = \mathbf{w}^\top(\mathbf{m}_P - \mathbf{m}_Q). By the Cauchy--Schwarz inequality, the maximum of a linear function over the unit ball is simply the Euclidean norm of its coefficient vector:

MMD(P,Q)=sup⁡∥w∥≤1w⊤(mP−mQ)=∥mP−mQ∥.(25.4.2)\textrm{MMD}(P, Q) = \sup_{\|\mathbf{w}\| \leq 1} \mathbf{w}^\top(\mathbf{m}_P - \mathbf{m}_Q) = \|\mathbf{m}_P - \mathbf{m}_Q\|. \tag{25.4.2}

Thus MMD is the distance between the mean feature vectors of PP and QQ, and the supremum has disappeared altogether. On our test pair, the mean features are mP=(0,1)\mathbf{m}_P = (0, 1) and mQ=(0,4)\mathbf{m}_Q = (0, 4), giving MMD2=02+32=9\textrm{MMD}^2 = 0^2 + 3^2 = 9: the comparison now detects differences in both means and second moments.

Next, expand the squared norm. Because the product of two expectations equals the expectation of a product over independent draws, we can write ∥mP∥2=E⟨φ(x),φ(x′)⟩\|\mathbf{m}_P\|^2 = \mathbb{E}\langle\boldsymbol{\varphi}(x), \boldsymbol{\varphi}(x')\rangle for independent x,x′∼Px, x' \sim P. Doing the same for independent y,y′∼Qy, y' \sim Q and the cross term gives ∥mP−mQ∥2=E⟨φ(x),φ(x′)⟩+E⟨φ(y),φ(y′)⟩−2 E⟨φ(x),φ(y)⟩\|\mathbf{m}_P - \mathbf{m}_Q\|^2 = \mathbb{E}\langle\boldsymbol{\varphi}(x), \boldsymbol{\varphi}(x')\rangle + \mathbb{E}\langle\boldsymbol{\varphi}(y), \boldsymbol{\varphi}(y')\rangle - 2\,\mathbb{E}\langle\boldsymbol{\varphi}(x), \boldsymbol{\varphi}(y)\rangle. Notice that the features φ(x)\boldsymbol{\varphi}(x) never appear alone; only their inner products do. Defining the kernel k(x,x′)=⟨φ(x),φ(x′)⟩k(x, x') = \langle \boldsymbol{\varphi}(x), \boldsymbol{\varphi}(x')\rangle, we obtain

MMD2(P,Q)=Ex,x′∼P[k(x,x′)]+Ey,y′∼Q[k(y,y′)]−2 Ex∼P,y∼Q[k(x,y)].(25.4.3)\textrm{MMD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}[k(x, x')] + \mathbb{E}_{y, y' \sim Q}[k(y, y')] - 2\, \mathbb{E}_{x \sim P, y \sim Q}[k(x, y)]. \tag{25.4.3}

This expression has an immediate geometric reading: the first two terms measure average similarity within PP and within QQ, while the third measures similarity across them. When draws from PP and QQ intermingle, within-sample and cross-sample similarities match and the three terms cancel; when they separate into distinct clusters, the within terms dominate. Our first step corresponds to the linear kernel k(x,x′)=xx′k(x, x') = x x', and our second to the quadratic kernel k(x,x′)=xx′+x2x′2k(x, x') = x x' + x^2 x'^2.

Even the quadratic kernel still has a blind spot: any two distributions with the same mean and variance have distance zero. Adding x3x^3, then x4x^4, and so on would never end. The decisive step is therefore to choose the kernel directly as a similarity measure, without ever writing down a finite list of features. The RBF kernel k(x,x′)=e−(x−x′)2/(2ℓ2)k(x, x') = e^{-(x - x')^2/(2\ell^2)} treats two points as similar when they lie within roughly a length scale ℓ\ell of each other. Although we chose it directly, it is still an inner product of features: factoring it as e−x2/(2ℓ2) e−x′2/(2ℓ2) exx′/ℓ2e^{-x^2/(2\ell^2)}\, e^{-x'^2/(2\ell^2)}\, e^{x x'/\ell^2} and expanding the last factor as a power series reveals an inner product over infinitely many features φj(x)=xje−x2/(2ℓ2)/(ℓjj!)\varphi_j(x) = x^j e^{-x^2/(2\ell^2)} / (\ell^j \sqrt{j!}) for j=0,1,2,…j = 0, 1, 2, \ldots, which are damped monomials of every order with rapidly decaying weights. Our panel now contains infinitely many auditors, yet evaluating its verdict still requires only the three averages in (25.4.3). In Rn\mathbb{R}^n, we simply replace (x−x′)2(x - x')^2 with ∥x−x′∥2\|x - x'\|^2 and nothing else changes.

With this kernel, no blind spot remains: MMD(P,Q)=0\textrm{MMD}(P, Q) = 0 if and only if P=QP = Q (Gretton et al., 2012), making RBF-MMD a true metric. Kernels with this property are called characteristic; the linear and quadratic kernels are not.

For Gaussians, we can evaluate the RBF expectations in closed form. If Z∼N(μ,s2)Z \sim \mathcal{N}(\mu, s^2), a standard Gaussian integral gives

E[e−Z2/(2ℓ2)]=(1+s2ℓ2)−1/2exp⁡ ⁣(−μ22(ℓ2+s2)).(25.4.4)\mathbb{E}\big[e^{-Z^2/(2\ell^2)}\big] = \Big(1 + \frac{s^2}{\ell^2}\Big)^{-1/2} \exp\!\Big(-\frac{\mu^2}{2(\ell^2 + s^2)}\Big). \tag{25.4.4}

Because the difference of two independent Gaussians is again Gaussian with the sum of their variances, we can read off all three terms of (25.4.3) immediately. On our test pair N(0,1)\mathcal{N}(0, 1) versus N(0,4)\mathcal{N}(0, 4) at ℓ=1\ell = 1, the differences x−x′x - x', y−y′y - y', and x−yx - y all have mean zero and variances 22, 88, and 55, yielding MMD2=3−1/2+9−1/2−2⋅6−1/2≈0.094\textrm{MMD}^2 = 3^{-1/2} + 9^{-1/2} - 2 \cdot 6^{-1/2} \approx 0.094. For the two shifted Gaussians of the opening table, the same integral gives 23(1−e−d2/6)\tfrac{2}{\sqrt{3}}\big(1 - e^{-d^2/6}\big) (Exercise 1a). For the point masses of Table 25.3.1, there is no averaging to do at all, and (25.4.3) immediately gives 1+1−2k(0,d)=2−2e−d2/21 + 1 - 2k(0, d) = 2 - 2e^{-d^2/2}, matching the fourth row of that table. In both cases, only the cross term depends on dd, and it decays rapidly once dd exceeds a few length scales. The gap therefore flattens out, failing our second requirement: an RBF auditor is smooth, but nearsighted.

25.4.1.3 Estimation from Samples#

Where a kernel shines is our first requirement: reliable estimation from samples. Given finite samples from PP and QQ, each expectation in (25.4.3) becomes an average over pairs of points. To obtain an unbiased estimator (Gretton et al., 2012), we omit the diagonal terms pairing a point with itself, which would otherwise bias the within-sample averages upward. Below, we evaluate this estimator on N=1,000N = 1{,}000 draws from N(0,1)\mathcal{N}(0, 1) and 1,0001{,}000 draws from N(0,4)\mathcal{N}(0, 4) under the linear, quadratic, and RBF kernels, whose population values we just computed as 00, 99, and 0.0940.094. For the RBF kernel, we also test two additional pairs: a second independent sample from N(0,1)\mathcal{N}(0, 1) (population value 00), and a shifted sample from N(0.5,1)\mathcal{N}(0.5, 1) (population value 0.0470.047 in the opening table). The goal is to see how tightly the sample estimates track these population values.

def mmd2_unbiased(x, y, k):
    """Unbiased MMD^2 between samples x and y for the kernel k(a, b)."""
    kxx = k(x[:, None], x[None, :])
    kyy = k(y[:, None], y[None, :])
    n, m = len(x), len(y)
    return ((kxx.sum() - np.trace(kxx)) / (n * (n - 1))
            + (kyy.sum() - np.trace(kyy)) / (m * (m - 1))
            - 2 * k(x[:, None], y[None, :]).mean())

linear = lambda a, b: a * b                         # features phi(x) = x
quadratic = lambda a, b: a * b + a ** 2 * b ** 2    # features (x, x^2)
rbf = lambda a, b: np.exp(-(a - b) ** 2 / 2)        # RBF kernel, ell = 1

rng = np.random.default_rng()
n = 1000
x_p = rng.standard_normal(n)                # P = N(0, 1)
y_var = 2 * rng.standard_normal(n)          # N(0, 4)
y_same = rng.standard_normal(n)             # N(0, 1) again
y_shift = rng.standard_normal(n) + 0.5      # N(0.5, 1)
for name, y, k, pop in [
        ('linear,    N(0,1) vs N(0,4)', y_var, linear, 0.0),
        ('quadratic, N(0,1) vs N(0,4)', y_var, quadratic, 9.0),
        ('RBF,       N(0,1) vs N(0,4)', y_var, rbf,
         3 ** -0.5 + 9 ** -0.5 - 2 * 6 ** -0.5),
        ('RBF,       N(0,1) vs N(0,1)', y_same, rbf, 0.0),
        ('RBF,       N(0,1) vs N(0.5,1)', y_shift, rbf,
         2 / np.sqrt(3) * (1 - np.exp(-1 / 24)))]:
    print(f'{name:30s} MMD^2 = {mmd2_unbiased(x_p, y, k):+.4f}  '
          f'(population {pop:.4f})')
linear,    N(0,1) vs N(0,4)    MMD^2 = -0.0033  (population 0.0000)
quadratic, N(0,1) vs N(0,4)    MMD^2 = +10.2618  (population 9.0000)
RBF,       N(0,1) vs N(0,4)    MMD^2 = +0.1180  (population 0.0942)
RBF,       N(0,1) vs N(0,1)    MMD^2 = +0.0001  (population 0.0000)
RBF,       N(0,1) vs N(0.5,1)  MMD^2 = +0.0351  (population 0.0471)

The linear kernel returns a number close to zero because the two means match. Specifically, its unbiased estimate equals the squared difference of the two sample means minus an estimate of that difference's variance, roughly (1+4)/1,000=0.005(1 + 4)/1{,}000 = 0.005; as a result, it rarely dips much below −0.005-0.005, while about one run in twenty exceeds +0.015+0.015. The quadratic kernel lands near 99, give or take 33, because fourth powers amplify sampling noise. Under the RBF kernel, the estimate is roughly 0.094±0.030.094 \pm 0.03 for the variance-shifted pair and 0.047±0.020.047 \pm 0.02 for the mean-shifted pair, so the sampling error can be a noticeable fraction of the signal. Between two independent samples from the same N(0,1)\mathcal{N}(0, 1) distribution, however, the RBF estimate is remarkably tight, staying within a few thousandths of zero (and occasionally dipping slightly below it) because the first-order sampling errors in the three averages cancel out. Where total variation reported a spurious gap of 11 between two samples from the same distribution, the RBF kernel sees none.

In short, the RBF estimator has relatively large error when measuring a non-zero gap, yet extraordinary precision when P=QP = Q. That makes it a powerful two-sample test: with 1,0001{,}000 points per sample, an RBF MMD2\textrm{MMD}^2 of even a few hundredths is strong evidence that the two distributions differ, obtained without training a critic or evaluating a single density.

25.4.1.4 The Witness#

Because an IPM is defined as a supremum, it is natural to ask which test function actually achieved the maximum gap. For MMD, the supremum in (25.4.2) is attained by w⋆∝mP−mQ\mathbf{w}^\star \propto \mathbf{m}_P - \mathbf{m}_Q. The resulting test function, known as the witness, is g⋆(x)∝⟨mP−mQ,φ(x)⟩=EP[k(x,X)]−EQ[k(x,Y)]g^\star(x) \propto \langle \mathbf{m}_P - \mathbf{m}_Q, \boldsymbol{\varphi}(x)\rangle = \mathbb{E}_P[k(x, X)] - \mathbb{E}_Q[k(x, Y)], which again requires only kernel evaluations. For our shifted Gaussians N(0,1)\mathcal{N}(0, 1) and N(0.5,1)\mathcal{N}(0.5, 1), the two densities are mirror images across x=0.25x = 0.25, so the population witness changes sign right at 0.250.25. Below, we estimate the witness from our samples on a grid and plot it alongside the two densities. We also print EPg−EQg\mathbb{E}_P g - \mathbb{E}_Q g for the unscaled witness g=⟨mP−mQ,φ⟩g = \langle \mathbf{m}_P - \mathbf{m}_Q, \boldsymbol{\varphi}\rangle, which equals ∥mP−mQ∥2=MMD2\|\mathbf{m}_P - \mathbf{m}_Q\|^2 = \textrm{MMD}^2, estimated here with the self-pairs included.

g = lambda s: (rbf(s[:, None], x_p[None, :]).mean(axis=1)    # the unscaled
               - rbf(s[:, None], y_shift[None, :]).mean(axis=1))  # witness
grid = np.linspace(-4.0, 4.5, 400)
witness = g(grid)
print(f'witness changes sign at x = {grid[np.argmax(witness < 0)]:.2f}')
print(f'E_P g - E_Q g = {g(x_p).mean() - g(y_shift).mean():.4f}')
d2l.plot(grid, [witness / np.abs(witness).max(), norm.pdf(grid),
                norm.pdf(grid, loc=0.5)], 'x', '',
         legend=['witness (scaled)', 'p = N(0, 1)', 'q = N(0.5, 1)'],
         figsize=(5, 3))
witness changes sign at x = 0.35
E_P g - E_Q g = 0.0360

As expected, the witness is positive where PP has higher density and negative where QQ has higher density, crossing zero near x=0.25x = 0.25 (with 1,0001{,}000 points per sample, the crossing fluctuates by a tenth or two across runs). The printed gap matches the unbiased estimate from the previous cell to within about 0.0010.001, with the small discrepancy coming from the self-pairs.

The tails of the witness plot reveal something even more important than the crossing. To shrink the gap EP[g]−EQ[g]\mathbb{E}_P[g] - \mathbb{E}_Q[g], a generative model must push each of its samples uphill along gg, so the slope of the witness at a model sample is the gradient signal that sample receives. Between the two bell curves, the witness is steep and provides a strong pull toward the data. A few length scales out in the tails, however, the witness flattens to zero, leaving any distant model sample with almost no gradient. We are seeing the MMD2\textrm{MMD}^2 column of the opening table from the vantage point of a single sample.

Fixed-kernel MMD therefore plays two distinct roles in practice: as a non-parametric two-sample test, and as a training objective for generative models that avoids adversarial optimization (Li et al., 2015). For instance, the kernel inception distance used to evaluate image generators (Section 16.5) is simply the unbiased MMD estimator applied to deep image features with a cubic kernel. Choosing the length scale ℓ\ell carefully is essential: at ℓ=1\ell = 1, the slope at d=8d = 8 collapsed to 7×10−57 \times 10^{-5} (Exercise 1b explores larger scales). In practice, one often sets ℓ\ell to the median pairwise distance between samples or sums RBF kernels across multiple length scales, the strategy used when training a GAN generator with MMD in Section 16.2.

25.4.2 Optimal Transport and the Wasserstein Distance#

One column of the opening table never flattened out. W1W_1 kept a constant slope of 11 because it incorporates the geometry of the underlying space, which f-divergences ignore and a fixed kernel sees only locally. Under W1W_1, the point mass δ0.01\delta_{0.01} is close to δ0\delta_0 simply because its mass need only travel a distance of 0.010.01. The idea goes back to 1781, when Gaspard Monge asked how to move a pile of earth into a pit of equal volume with the least total work. That minimum work is a natural measure of how far apart two distributions are.

25.4.2.1 Transport Plans#

Consider two discrete distributions supported on the six points 0,1,…,50, 1, \ldots, 5 of the real line, with PP concentrated on the left and QQ on the right, as shown in the top left panel of Figure 25.4.1. To reshape PP into QQ, we must specify how much mass moves from each source xx to each destination yy. Such a transport plan is a joint distribution γ\gamma over pairs (x,y)(x, y) whose marginals are PP and QQ: the total mass leaving each xx equals P(x)P(x), and the total mass arriving at each yy equals Q(y)Q(y). In probability theory, a transport plan is also called a coupling of PP and QQ. The Wasserstein-1 distance (also known as the earth mover's distance) is the minimum expected distance traveled over all valid plans. Writing Π(P,Q)\Pi(P, Q) for the set of all couplings of PP and QQ on Rn\mathbb{R}^n with finite first moments,

W1(P,Q)=inf⁡γ∈Π(P,Q)E(x,y)∼γ[∥x−y∥].(25.4.5)W_1(P, Q) = \inf_{\gamma \in \Pi(P, Q)} \mathbb{E}_{(x, y) \sim \gamma}\big[ \|x - y\| \big]. \tag{25.4.5}

The subscript 11 refers to the first power of the distance; we will meet the squared-distance version W2W_2 shortly. Between two point masses δ0\delta_0 and δd\delta_d, there is only one possible plan, moving all mass from 00 to dd, so W1(δ0,δd)=∣d∣W_1(\delta_0, \delta_d) = |d|, with gradient ±1\pm 1 for d≠0d \neq 0. For the two shifted Gaussians of the opening table, translating every point by dd is a valid plan of cost dd, and no plan can do better because Eγ∣x−y∣≥∣Eγ[x−y]∣=d\mathbb{E}_\gamma|x - y| \geq |\mathbb{E}_\gamma[x - y]| = d for every coupling γ\gamma. In both cases, W1W_1 recovers the separation dd itself, providing the clean gradient signal that f-divergences lack.

Figure 25.4.1:

Transport on the line. Top left: a transport plan between two distributions on six points; each ribbon carries mass from a point of PP (top) to a point of QQ (bottom), with width proportional to the mass moved. Bottom left: the CDFs of PP and QQ; the shaded area between them is 1.71.7. Right: for two point masses separated by dd, the Jensen--Shannon divergence (in nats) stays flat at log⁡2\log 2, whereas W1W_1 (in units of xx) grows linearly with dd.

25.4.2.2 Kantorovich--Rubinstein Duality#

As a computational recipe, (25.4.5) looks intimidating: it minimizes over joint distributions γ\gamma, which are awkward even to parameterize from samples. On finite point sets, however, it is a familiar optimization problem: a linear program. The unknowns are the entries of the plan, and both the transport cost and the marginal constraints are linear in those entries. Every linear program has a dual problem that maximizes over multipliers for its constraints (Section 23.7.1). For optimal transport, the dual replaces the search over joint distributions with a maximization over a single function, and that reformulation is what makes W1W_1 practical in deep learning.

Proposition (Kantorovich--Rubinstein duality). For distributions PP and QQ on Rn\mathbb{R}^n with finite first moments,

W1(P,Q)=sup⁡∥g∥Lip≤1(Ex∼P[g(x)]−Ey∼Q[g(y)]),(25.4.6)W_1(P, Q) = \sup_{\|g\|_{\textrm{Lip}} \leq 1} \big( \mathbb{E}_{x \sim P}[g(x)] - \mathbb{E}_{y \sim Q}[g(y)] \big), \tag{25.4.6}

where the supremum runs over all 1-Lipschitz functions gg, meaning ∣g(x)−g(y)∣≤∥x−y∥|g(x) - g(y)| \leq \|x - y\| for all x,yx, y.

An infimum over couplings has turned into a supremum over a single test function: W1W_1 is precisely the IPM (25.4.1) over functions with slope at most 11, the third class we promised earlier. A 1-Lipschitz auditor cannot make sudden jumps, so it cannot memorize individual sample points the way an indicator function does. Yet unlike bounded functions or RBF kernels, it can grow without limit, satisfying our second requirement. On the two shifted Gaussians of the opening table, for example, g(x)=−xg(x) = -x is 1-Lipschitz and has expectations 00 under PP and −d-d under QQ, achieving a gap of d=W1(P,Q)d = W_1(P, Q). Better still, its gradient points toward the data with magnitude 11 everywhere, no matter how far a model sample lies from the data.

Because a neural network can approximate such a test function, the WGAN (Arjovsky et al., 2017) trains the dual objective (25.4.6) directly, using a neural critic constrained to be approximately 1-Lipschitz in the role of gg. Section 16.2 compares this objective with other adversarial losses and trains such a critic, whose slope a gradient penalty pulls toward one. Section 16.4 shows why later recipes center their penalties at zero instead: a penalty that prefers unit slope keeps pushing a generator that already matches the data, while one centered at zero only keeps the critic's gradient small at the samples and enforces no Lipschitz constraint. Keep in mind that when a critic is only approximately Lipschitz and restricted to a neural architecture, the score it reports is no longer exact W1W_1.

25.4.2.3 Transport on the Line#

We prove Kantorovich--Rubinstein duality in one dimension, where the argument also delivers a closed-form formula requiring no optimization at all; Peyré and Cuturi (2019) give the proof in higher dimensions. The intuition is simply to count how much mass crosses each point t∈Rt \in \mathbb{R}. To the left of tt (including tt), PP holds mass FP(t)F_P(t) and QQ holds mass FQ(t)F_Q(t), so any valid transport plan must move at least ∣FP(t)−FQ(t)∣|F_P(t) - F_Q(t)| of mass across tt. Moreover, a parcel moved from xx to yy crosses every tt between xx and yy, so its distance ∣x−y∣|x - y| equals the length of the interval of points it crosses. Summing over all parcels, the total transport cost is the integral over tt of the total mass crossing tt.

Proposition (W1W_1 on the line). For distributions PP and QQ on R\mathbb{R} with CDFs FPF_P, FQF_Q and finite first moments,

W1(P,Q)=∫−∞∞∣FP(t)−FQ(t)∣ dt=sup⁡∥g∥Lip≤1(EP[g]−EQ[g]),(25.4.7)W_1(P, Q) = \int_{-\infty}^{\infty} \lvert F_P(t) - F_Q(t) \rvert \, dt = \sup_{\|g\|_{\textrm{Lip}} \leq 1} \big( \mathbb{E}_P[g] - \mathbb{E}_Q[g] \big), \tag{25.4.7}

so Kantorovich--Rubinstein duality holds on the real line.

Proof. Step 1: Every plan costs at least the area between the CDFs. For (X,Y)∼γ(X, Y) \sim \gamma, write ∣X−Y∣=∫1(t lies between X and Y) dt|X - Y| = \int \mathbf{1}(t \textrm{ lies between } X \textrm{ and } Y)\, dt. Because the integrand is non-negative, we may exchange expectation and integration:

Eγ∣X−Y∣=∫(γ(X≤t<Y)+γ(Y≤t<X)) dt≥∫∣γ(X≤t<Y)−γ(Y≤t<X)∣ dt.\begin{aligned} \mathbb{E}_\gamma|X - Y| &= \int \Big( \gamma(X \leq t \lt Y) + \gamma(Y \leq t \lt X) \Big)\, dt \\ &\geq \int \big| \gamma(X \leq t \lt Y) - \gamma(Y \leq t \lt X) \big|\, dt. \end{aligned}

The key step is simplifying the difference inside the last integral. Adding and subtracting γ(X≤t,Y≤t)\gamma(X \leq t, Y \leq t) gives γ(X≤t<Y)−γ(Y≤t<X)=γ(X≤t)−γ(Y≤t)=FP(t)−FQ(t)\gamma(X \leq t \lt Y) - \gamma(Y \leq t \lt X) = \gamma(X \leq t) - \gamma(Y \leq t) = F_P(t) - F_Q(t), since γ\gamma has marginals PP and QQ. Thus every transport plan costs at least ∫∣FP−FQ∣\int |F_P - F_Q|.

Step 2: One plan achieves this lower bound. Match quantiles directly: send the lowest tenth of PP to the lowest tenth of QQ, and so on up the line. Formally, let UU be uniform on (0,1)(0, 1) and set X=FP−1(U)X = F_P^{-1}(U) and Y=FQ−1(U)Y = F_Q^{-1}(U), where the quantile function F−1(λ)=inf⁡{x:F(x)≥λ}F^{-1}(\lambda) = \inf\{x : F(x) \geq \lambda\} for λ∈(0,1)\lambda \in (0, 1) satisfies F−1(λ)≤tF^{-1}(\lambda) \leq t if and only if λ≤F(t)\lambda \leq F(t). This defines a valid coupling because Pr⁡(X≤t)=Pr⁡(U≤FP(t))=FP(t)\Pr(X \leq t) = \Pr(U \leq F_P(t)) = F_P(t) and similarly for YY. We call it the monotone plan, since XX and YY increase together. Under this coupling, γ(X≤t<Y)=Pr⁡(FQ(t)<U≤FP(t))\gamma(X \leq t \lt Y) = \Pr\big(F_Q(t) \lt U \leq F_P(t)\big) and γ(Y≤t<X)=Pr⁡(FP(t)<U≤FQ(t))\gamma(Y \leq t \lt X) = \Pr\big(F_P(t) \lt U \leq F_Q(t)\big). At every tt, at least one of these two probabilities is zero, meaning the monotone plan never sends mass in both directions across the same point. The inequality in Step 1 therefore holds with equality, so the minimum transport cost equals the area between the CDFs.

Step 3: No 1-Lipschitz test function beats any plan. This weak duality argument holds in every dimension. For any 1-Lipschitz function gg and any coupling γ\gamma, we have g(x)−g(y)≤∥x−y∥g(x) - g(y) \leq \|x - y\| pointwise; taking the expectation under γ\gamma immediately gives EP[g]−EQ[g]≤Eγ∥x−y∥\mathbb{E}_P[g] - \mathbb{E}_Q[g] \leq \mathbb{E}_\gamma\|x - y\| (compare the weak duality of Section 23.7.1).

Step 4: One 1-Lipschitz test function achieves the area. It suffices to consider functions of the form g(x)=g(0)+∫0xg′(t) dtg(x) = g(0) + \int_0^x g'(t)\, dt with ∣g′∣≤1|g'| \leq 1: every such gg is 1-Lipschitz, and Step 3 already bounds all others. The constant g(0)g(0) cancels in EP[g]−EQ[g]\mathbb{E}_P[g] - \mathbb{E}_Q[g]. Rewriting ∫0Xg′(t) dt=∫0∞g′(t) 1(X>t) dt−∫−∞0g′(t) 1(X≤t) dt\int_0^X g'(t)\,dt = \int_0^{\infty} g'(t)\, \mathbf{1}(X > t)\, dt - \int_{-\infty}^0 g'(t)\, \mathbf{1}(X \leq t)\, dt and exchanging expectation and integration (justified by Fubini's theorem from Section 22.6, given the finite first moments) yields

EP[g]−EQ[g]=∫−∞∞g′(t) (FQ(t)−FP(t)) dt.\mathbb{E}_P[g] - \mathbb{E}_Q[g] = \int_{-\infty}^{\infty} g'(t)\, \big( F_Q(t) - F_P(t) \big)\, dt.

Choosing g′(t)=sign(FQ(t)−FP(t))g'(t) = \textrm{sign}\big(F_Q(t) - F_P(t)\big) turns the right-hand side into ∫∣FP(t)−FQ(t)∣ dt\int |F_P(t) - F_Q(t)|\, dt. Combining all four steps, the supremum over 1-Lipschitz functions is at least the area (Step 4) and at most the minimum plan cost (Step 3), which equals the area (Steps 1 and 2). ■\blacksquare

On the real line, then, W1W_1 is simply the area between the two CDFs, and for two equal-sized samples it reduces to the mean absolute difference of the sorted values (Exercise 2a). It is remarkable that a full linear program collapses so cleanly. Let us verify this collapse on the six-point example from Figure 25.4.1. Across the five intervals between adjacent atoms, the CDF gaps are 0.250.25, 0.350.35, 0.50.5, 0.350.35, and 0.250.25, summing to 1.71.7, the shaded area in the figure. The code below computes W1W_1 in three ways: by summing the five CDF gaps, by solving the 3636-variable linear program over 6×66 \times 6 transport matrices with row sums pp and column sums qq, and by constructing the monotone plan of Step 2 (where each route carries the overlap of the corresponding quantile intervals) and evaluating its cost. Finally, it checks whether the linear program returned the monotone plan.

atoms = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
p_w = np.array([0.30, 0.20, 0.25, 0.10, 0.10, 0.05])
q_w = np.array([0.05, 0.10, 0.10, 0.25, 0.20, 0.30])

F_p, F_q = np.cumsum(p_w), np.cumsum(q_w)
w1_cdf = np.sum(np.abs(F_p - F_q)[:-1] * np.diff(atoms))

C = np.abs(atoms[:, None] - atoms[None, :])      # cost matrix |x_i - y_j|
n_atoms = len(atoms)
A_eq = np.zeros((2 * n_atoms, n_atoms * n_atoms))
for i in range(n_atoms):
    A_eq[i, i * n_atoms:(i + 1) * n_atoms] = 1   # row sums    = p
    A_eq[n_atoms + i, i::n_atoms] = 1            # column sums = q
res = optimize.linprog(C.ravel(), A_eq=A_eq,
                       b_eq=np.concatenate([p_w, q_w]), method='highs')
plan_lp = res.x.reshape(n_atoms, n_atoms)
# Monotone plan (Step 2): source i holds the quantiles (F_p[i-1], F_p[i]],
# destination j holds (F_q[j-1], F_q[j]]; route i -> j carries their overlap
lo_p, lo_q = F_p - p_w, F_q - q_w
mono = np.clip(np.minimum(F_p[:, None], F_q[None, :])
               - np.maximum(lo_p[:, None], lo_q[None, :]), 0, None)
print(f'W1 from the CDF gaps     : {w1_cdf:.4f}')
print(f'W1 from the LP           : {res.fun:.4f}')
print(f'cost of the monotone plan: {np.sum(mono * C):.4f}')
print(f'LP plan = monotone plan  : {np.allclose(plan_lp, mono)}, '
      f'mass the LP plan moves leftward: {np.tril(plan_lp, -1).sum():.2f}')
W1 from the CDF gaps     : 1.7000
W1 from the LP           : 1.7000
cost of the monotone plan: 1.7000
LP plan = monotone plan  : False, mass the LP plan moves leftward: 0.00

All three methods agree on W1=1.7W_1 = 1.7: summing five CDF gaps gives the exact same answer as solving a 3636-variable linear program. The last line, however, holds a small surprise: the linear program did not return the monotone plan. Instead, it found a different plan with the exact same cost, which likewise moves zero mass to the left.

The optimal W1W_1 plan is therefore not unique here, and the reason is easy to spot. Because FP≥FQF_P \geq F_Q everywhere, no mass ever needs to move leftward. For any plan that moves mass strictly rightward (y≥xy \geq x), we have ∣x−y∣=y−x|x - y| = y - x, so its total cost equals the difference of the two means, 3.35−1.65=1.73.35 - 1.65 = 1.7, regardless of how the routes cross. The monotone plan drawn in the figure is simply one of many equally good plans.

Two tools that appear elsewhere in the book replace the absolute distance with its square: the Fréchet inception distance for evaluating image generators (Section 16.5), and minibatch optimal transport in flow matching, which pairs noise with data by minimizing squared distance (Section 26.7). The Wasserstein-2 distance averages the squared distance and takes the square root afterwards: W2(P,Q)=(inf⁡γEγ∥x−y∥2)1/2W_2(P, Q) = \big(\inf_{\gamma} \mathbb{E}_\gamma \|x - y\|^2\big)^{1/2}. Under a squared cost, crossing two transport ribbons always costs strictly more than uncrossing them, so on the line the monotone plan becomes the unique optimum (Exercise 2d). Between two one-dimensional Gaussians with means μ1,μ2\mu_1, \mu_2 and standard deviations σ1,σ2\sigma_1, \sigma_2, it evaluates cleanly to W22=(μ1−μ2)2+(σ1−σ2)2W_2^2 = (\mu_1 - \mu_2)^2 + (\sigma_1 - \sigma_2)^2 (Exercise 4a). The Fréchet inception distance is the multivariate counterpart of this formula applied to Gaussians fitted to image features, with covariance matrices replacing the variances.

25.4.2.4 Entropic Regularization and Sinkhorn Iterations#

This subsection may be skipped on a first reading. Beyond one dimension, there is in general no closed-form CDF formula, and the linear program over NN points on each side has N2N^2 variables. The standard way to make optimal transport fast and differentiable is entropic regularization (Cuturi, 2013): given a cost matrix C\mathbf{C} and a regularization strength ε>0\varepsilon > 0, we add ε∑ijγij(log⁡γij−1)\varepsilon \sum_{ij} \gamma_{ij} (\log \gamma_{ij} - 1) to the transport cost ∑ijγijCij\sum_{ij} \gamma_{ij} C_{ij}. Because any valid plan satisfies ∑ijγij=1\sum_{ij}\gamma_{ij} = 1, this extra term equals −ε-\varepsilon times the entropy of γ\gamma plus a constant; it discourages plans that concentrate all their mass on a few sharp routes. Entropic regularization is what turned optimal transport into a practical loss function for deep learning, enabling generative models to be trained directly on regularized transport costs (Genevay et al., 2018).

Remarkably, the regularized problem solves almost in closed form. Forming the Lagrangian (Section 23.7.1) with a multiplier ξi\xi_i for each row-sum constraint ∑jγij=pi\sum_j \gamma_{ij} = p_i and a multiplier ζj\zeta_j for each column-sum constraint ∑iγij=qj\sum_i \gamma_{ij} = q_j, and setting the derivative with respect to γij\gamma_{ij} to zero, we obtain Cij+εlog⁡γij−ξi−ζj=0C_{ij} + \varepsilon \log \gamma_{ij} - \xi_i - \zeta_j = 0, or γij=e−(Cij−ξi−ζj)/ε\gamma_{ij} = e^{-(C_{ij} - \xi_i - \zeta_j)/\varepsilon}. Each route carries mass decaying exponentially in how far its cost CijC_{ij} exceeds ξi+ζj\xi_i + \zeta_j, measured in units of ε\varepsilon. In matrix form,

γε=diag(a) K diag(b),K=e−C/ε (entrywise),(25.4.8)\boldsymbol{\gamma}_\varepsilon = \textrm{diag}(\mathbf{a})\, \mathbf{K}\, \textrm{diag}(\mathbf{b}), \qquad \mathbf{K} = e^{-\mathbf{C}/\varepsilon} \textrm{ (entrywise)}, \tag{25.4.8}

where a=eξ/ε\mathbf{a} = e^{\boldsymbol{\xi}/\varepsilon} and b=eζ/ε\mathbf{b} = e^{\boldsymbol{\zeta}/\varepsilon} are positive scaling vectors. The regularized plan is simply the Gibbs kernel K\mathbf{K} (a matrix of positive weights, unrelated to the kernels of MMD), rescaled row by row and column by column. Only a\mathbf{a} and b\mathbf{b} remain to be found, and each set of marginal constraints determines one of them: with b\mathbf{b} fixed, setting a=p/(Kb)\mathbf{a} = \mathbf{p} / (\mathbf{K}\mathbf{b}) (entrywise) enforces the row sums p\mathbf{p}; with a\mathbf{a} fixed, setting b=q/(K⊤a)\mathbf{b} = \mathbf{q} / (\mathbf{K}^\top \mathbf{a}) enforces the column sums q\mathbf{q}.

The Sinkhorn iterations alternate these two updates, updating b\mathbf{b} and then a\mathbf{a} until both marginals match. After the a\mathbf{a} update the row sums are exact, so we stop once the column sums match q\mathbf{q} within 10−910^{-9}. Every step requires only two matrix-vector products, making the algorithm fast on GPUs and trivial to differentiate through. Below we report the entropic cost, meaning the transport cost ∑ij(γε)ijCij\sum_{ij} (\gamma_\varepsilon)_{ij} C_{ij} of the regularized plan (without the entropy penalty). As ε→0\varepsilon \to 0, this cost approaches the exact unregularized optimum, but convergence slows dramatically (Peyré and Cuturi, 2019) and the entries of K\mathbf{K} can underflow; production implementations therefore work in log-space on log⁡a\log \mathbf{a} and log⁡b\log \mathbf{b} (Exercise 5b).

To see how small ε\varepsilon must be, and how expensive a small ε\varepsilon becomes, we apply Sinkhorn to the six-point example with the squared cost Cij=(xi−xj)2C_{ij} = (x_i - x_j)^2, where the monotone plan of Figure 25.4.1 is the unique optimum and its ten active routes cost W22=3.5W_2^2 = 3.5. The cell below verifies this optimum with a linear program and runs Sinkhorn at three values of ε\varepsilon, reporting the iteration count, entropic cost, and number of routes carrying mass above 10−310^{-3}.

def sinkhorn(p, q, C, eps, tol=1e-9, max_iters=10 ** 6):
    """Entropic OT by Sinkhorn iterations, stopped once the column sums are
    within tol of q (L1); returns the plan, its cost and the iterations."""
    K = np.exp(-C / eps)                         # the Gibbs kernel
    a = np.ones_like(p)
    for it in range(1, max_iters + 1):
        b = q / (K.T @ a)                        # match the column sums
        a = p / (K @ b)                          # match the row sums ...
        if np.abs(b * (K.T @ a) - q).sum() < tol:  # ... columns still right?
            break
    plan = a[:, None] * K * b[None, :]
    return plan, np.sum(plan * C), it

C2 = (atoms[:, None] - atoms[None, :]) ** 2      # squared cost (x_i - y_j)^2
res2 = optimize.linprog(C2.ravel(), A_eq=A_eq,
                        b_eq=np.concatenate([p_w, q_w]), method='highs')
print(f'squared cost, LP optimum : {res2.fun:.5f}')
plans, eps_values = [], (2.0, 0.5, 0.1)
for eps in eps_values:
    plan, cost, iters = sinkhorn(p_w, q_w, C2, eps)
    plans.append(plan)
    print(f'epsilon = {eps}: {iters:6d} iterations, entropic cost = '
          f'{cost:.5f}, routes above 1e-3 = {(plan > 1e-3).sum()}')
d2l.show_heatmaps(d2l.tensor(np.stack(plans)[None]), 'destination j',
                  'source i', titles=[f'epsilon = {e}' for e in eps_values],
                  figsize=(9, 2.8), cmap='Blues')
squared cost, LP optimum : 3.50000
epsilon = 2.0:     47 iterations, entropic cost = 4.06489, routes above 1e-3 = 25
epsilon = 0.5:    186 iterations, entropic cost = 3.56963, routes above 1e-3 = 14
epsilon = 0.1: 154325 iterations, entropic cost = 3.50002, routes above 1e-3 = 10

The linear program confirms W22=3.5W_2^2 = 3.5. At ε=2\varepsilon = 2, the regularized plan smears each source's mass across many destinations (2525 of the 3636 routes carry more than 10−310^{-3}), pushing the cost up to 4.064.06. At ε=0.5\varepsilon = 0.5, the plan tightens to 1414 active routes with cost 3.573.57. By ε=0.1\varepsilon = 0.1, only the ten routes of the monotone plan survive, and the cost reaches 3.500023.50002, within 2×10−52 \times 10^{-5} of the exact optimum. In the heatmaps, a blurry band sharpens into a clean staircase. The natural scale for ε\varepsilon is the cost gap between competing routes, which is of order 11 on this grid; setting ε\varepsilon to a tenth of that scale recovers the optimum accurately.

The iteration counts reveal the catch. Sinkhorn needed about 5050 iterations at ε=2\varepsilon = 2 and about 190190 at ε=0.5\varepsilon = 0.5, but roughly 150,000150{,}000 at ε=0.1\varepsilon = 0.1. Cutting ε\varepsilon by a factor of five increased the work by a factor of more than 800800. Sinkhorn iterations are fast only when you can afford a blurred transport plan (Exercise 6b tracks this growth quantitatively).

25.4.3 Fixed Kernels and Trained Critics#

MMD and W1W_1 split our two requirements right down the middle. A fixed kernel defines a small, smooth function class: MMD reduces to three sample averages, and its estimation error from NN points decays as O(N−1/2)O(N^{-1/2}) in any dimension (Gretton et al., 2012). Kernels do not escape the curse of dimension that way, unfortunately. The error rate is dimension-free, but the size of the signal is not: with a fixed kernel, the population MMD between two given distributions typically shrinks as the dimension grows (Ramdas et al., 2015), which is why the kernel inception distance and MMD losses are computed on learned features, not on raw pixels. A fixed kernel also loses sight of the data beyond a few length scales. By contrast, 1-Lipschitz functions provide a steady gradient at every separation, which is exactly what a model far from its data needs. However, even though they cannot jump like indicators, the class of all 1-Lipschitz functions is still enormous in high dimensions: for two samples in dimension n>2n > 2, the empirical W1W_1 error decays only as O(N−1/n)O(N^{-1/n}) (Weed and Bach, 2019). In 100100 dimensions, halving that estimation error would require 21002^{100} times as much data. Nobody estimates W1W_1 directly from high-dimensional samples that way. Instead, a WGAN critic searches over a much smaller class of neural networks, while Sinkhorn iterations handle smaller discrete matching problems.

Both kernels and adversarial critics start by drawing samples from the model. For some generative models, sampling itself is the bottleneck, and Section 25.5 asks how we can compare two distributions without drawing model samples at all.

25.4.4 Summary#

Overlapping tails do not rescue f-divergences: when two unit Gaussians sit eight standard deviations apart, both the Jensen--Shannon divergence and total variation have slopes near 10−410^{-4}. Integral probability metrics sidestep density ratios by comparing how PP and QQ average a class of test functions, and the choice of class determines both sample efficiency and how far the metric can see. Test functions linear in fixed features yield MMD, the distance between mean feature vectors: it evaluates in closed form as three kernel averages with no critic to train, and estimates at rate O(N−1/2)O(N^{-1/2}) regardless of dimension, though the MMD itself tends to shrink as the dimension grows and an RBF kernel goes blind beyond a few length scales. Functions of slope at most one yield W1W_1, the minimum mass-times-distance cost of transporting PP into QQ, which maintains slope one at every separation and underpins the Wasserstein GAN critic. In one dimension, W1W_1 collapses to the area between the two CDFs; in higher dimensions, it requires either a trained critic or, on small discrete problems, Sinkhorn iterations with entropic regularization.

25.4.5 Exercises#

  1. [code] MMD in closed form. Use the Gaussian integral (25.4.4) for the RBF kernel with length scale ℓ\ell, with P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(d,1)Q = \mathcal{N}(d, 1).

    1. Show that MMD2=2ℓℓ2+2(1−e−d2/(2(ℓ2+2)))\textrm{MMD}^2 = \frac{2\ell}{\sqrt{\ell^2 + 2}} \big(1 - e^{-d^2/(2(\ell^2 + 2))}\big), and check that ℓ=1\ell = 1 gives the MMD2\textrm{MMD}^2 column of the opening table. Which length scale maximizes MMD2\textrm{MMD}^2 for small shifts dd? What happens as ℓ→0\ell \to 0 and as ℓ→∞\ell \to \infty?
    2. Evaluate the slope in dd at d=8d = 8 for ℓ=1\ell = 1, 44 and 1616. What do the three values say about the length scale for a model that starts far from its data?
  2. [code] One-dimensional transport. ● On the real line, W1W_1 is the area between the CDFs (25.4.7).

    1. For two empirical distributions on samples x1,…,xNx_1, \ldots, x_N and y1,…,yNy_1, \ldots, y_N of equal size, use the monotone plan of the proof to show that W1=1N∑i∣x(i)−y(i)∣W_1 = \tfrac{1}{N} \sum_i |x_{(i)} - y_{(i)}|, the mean absolute difference of the sorted values. Check this against the linear program of the six-point example on two random samples of size 77.
    2. Compute the sorted-sample W1W_1 between x_p and y_shift and between x_p and y_same of the MMD experiment. Then average it over 2020 pairs of independent samples of size NN from N(0,1)\mathcal{N}(0, 1), for N∈{102,103,104}N \in \{10^2, 10^3, 10^4\}, and find the rate at which it decreases. The estimate is never negative. Why does this rule out unbiasedness when P=QP = Q?
    3. Change q_w to (0.40,0.05,0.05,0.10,0.10,0.30)(0.40, 0.05, 0.05, 0.10, 0.10, 0.30), so that the two CDFs cross, and rerun the cell that computes W1W_1. Build the test function gg with g(0)=0g(0) = 0 and slope sign(FQ(t)−FP(t))\textrm{sign}\big(F_Q(t) - F_P(t)\big) between neighboring atoms, as in Step 4 of the proof, and check that EP[g]−EQ[g]\mathbb{E}_P[g] - \mathbb{E}_Q[g] equals the LP value. For every route (i,j)(i, j) that carries mass in the LP solution plan_lp, compare g(xi)−g(xj)g(x_i) - g(x_j) with ∣xi−xj∣|x_i - x_j|. Why must the two agree on every such route for any optimal plan and any optimal test function?
    4. Uniqueness under the squared cost. Suppose a plan moves mass from xx to y′y' and from x′x' to yy, with x<x′x \lt x' and y<y′y \lt y', so that the two ribbons cross. Show that under the squared cost, sending the same mass from xx to yy and from x′x' to y′y' saves 2(x′−x)(y′−y)2(x' - x)(y' - y) per unit of mass, and deduce that the monotone plan is the only optimal one. What does the same exchange save under the cost ∣x−y∣|x - y| when all four moves go rightward? Find two ribbons that cross in plan_lp, the plan that the linear program returned for the six-point example, and check your answer on them.
  3. Optimal critics on the line. Step 4 of the proof of (25.4.7) shows that a test function with slope g′(t)=sign(FQ(t)−FP(t))g'(t) = \textrm{sign}\big(F_Q(t) - F_P(t)\big) attains W1W_1.

    1. For P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(d,1)Q = \mathcal{N}(d, 1) with d>0d > 0, show that FP>FQF_P > F_Q everywhere, so that Step 4 returns g(x)=−xg(x) = -x, the critic that the text found by inspection.
    2. For P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(0,4)Q = \mathcal{N}(0, 4), show that the two CDFs cross only at 00, that g(x)=−∣x∣g(x) = -|x| is optimal, and that W1=2/π≈0.80W_1 = \sqrt{2/\pi} \approx 0.80. (For X∼N(0,σ2)X \sim \mathcal{N}(0, \sigma^2), E∣X∣=σ2/π\mathbb{E}|X| = \sigma\sqrt{2/\pi}.) The linear kernel reported 00 on this pair. Which way does the critic move the samples of QQ?
    3. Let P=12δ0+12δ3P = \tfrac12 \delta_0 + \tfrac12 \delta_3 and Q=12δ1+12δ3Q = \tfrac12 \delta_1 + \tfrac12 \delta_3. Find W1(P,Q)W_1(P, Q) and describe every optimal critic of the form used in Step 4. Then show in general that such a critic is optimal if and only if g′(t)=sign(FQ(t)−FP(t))g'(t) = \textrm{sign}\big(F_Q(t) - F_P(t)\big) at almost every tt with FP(t)≠FQ(t)F_P(t) \neq F_Q(t), the points that mass has to cross, while its slope elsewhere is free.
    4. A WGAN critic is often trained with a penalty on (∣g′(x)∣−1)2(|g'(x)| - 1)^2 at points xx between the data and the generated samples (Gulrajani et al., 2017). Explain this choice by (c). Which critics are optimal when P=QP = Q, and which of them does the penalty prefer? Section 16.4 shows what follows for training.
  4. [code] W2W_2 between Gaussians and the Fréchet distance. On the line the monotone plan X=FP−1(U)X = F_P^{-1}(U), Y=FQ−1(U)Y = F_Q^{-1}(U) is optimal for the squared cost.

    1. Show that for P=N(μ1,σ12)P = \mathcal{N}(\mu_1, \sigma_1^2) and Q=N(μ2,σ22)Q = \mathcal{N}(\mu_2, \sigma_2^2) the monotone plan is Y=μ2+(σ2/σ1)(X−μ1)Y = \mu_2 + (\sigma_2/\sigma_1)(X - \mu_1), and deduce that W22(P,Q)=(μ1−μ2)2+(σ1−σ2)2W_2^2(P, Q) = (\mu_1 - \mu_2)^2 + (\sigma_1 - \sigma_2)^2. With the same plan, recover W1=∣μ1−μ2∣W_1 = |\mu_1 - \mu_2| for equal variances, the W1W_1 column of the opening table.
    2. Let both standard deviations be σ\sigma and the means dd apart. Then W22=d2W_2^2 = d^2 for every σ\sigma, while the KL divergence between the two Gaussians is d2/(2σ2)d^2/(2\sigma^2). What do the two report as σ→0\sigma \to 0, when the Gaussians become the point masses of Table 25.3.1?
    3. In Rn\mathbb{R}^n the squared W2W_2 between N(μ1,Σ1)\mathcal{N}(\boldsymbol{\mu}_1, \boldsymbol{\Sigma}_1) and N(μ2,Σ2)\mathcal{N}(\boldsymbol{\mu}_2, \boldsymbol{\Sigma}_2) is the squared Fréchet distance ∥μ1−μ2∥2+tr(Σ1+Σ2−2 (Σ11/2Σ2Σ11/2)1/2)\|\boldsymbol{\mu}_1 - \boldsymbol{\mu}_2\|^2 + \textrm{tr}\big(\boldsymbol{\Sigma}_1 + \boldsymbol{\Sigma}_2 - 2\,(\boldsymbol{\Sigma}_1^{1/2} \boldsymbol{\Sigma}_2 \boldsymbol{\Sigma}_1^{1/2})^{1/2}\big) (Dowson and Landau, 1982). Check that it reduces to (a) for n=1n = 1 and, for diagonal covariance matrices, to the sum of (a) over the coordinates. Prove the diagonal case directly: the squared cost is a sum over coordinates, so no plan costs less than the sum of the coordinatewise optima, and the monotone plans of the coordinates together attain it.
    4. The Fréchet inception distance fits a Gaussian to each of two feature distributions and reports the squared Fréchet distance between the fits. Let PP be the mixture 0.7 N(−2,0.62)+0.3 N(2,0.62)0.7\,\mathcal{N}(-2, 0.6^2) + 0.3\,\mathcal{N}(2, 0.6^2) and Q=N(−0.8,3.72)Q = \mathcal{N}(-0.8, 3.72), which has the same mean and variance. What is the Fréchet distance between the two fits? Estimate W22(P,Q)W_2^2(P, Q) from 10510^5 sorted draws of each (you should find about 0.630.63). What does a Fréchet distance of zero certify, and what does it not?
  5. [code] Entropic transport and Sinkhorn divergences. ●● Regularize the transport LP of the six-point example by the divergence from the independent plan,

OTε(P,Q)=min⁡γ ∑i,jγijCij+ε DKL(γ ∥ p q⊤),\textrm{OT}_\varepsilon(P, Q) = \min_{\gamma}\, \sum_{i, j} \gamma_{ij} C_{ij} + \varepsilon\, D_{\textrm{KL}}\big(\gamma \,\|\, p\, q^\top\big),

where γ\gamma ranges over the plans with row sums pp and column sums qq.

  1. Show that DKL(γ ∥ p q⊤)=−H(γ)+H(P)+H(Q)D_{\textrm{KL}}(\gamma \,\|\, p\, q^\top) = -H(\gamma) + H(P) + H(Q) for every such plan, where HH denotes the entropy, so that sinkhorn returns the minimizer. Show that OTε(P,Q)→∑i,jpiqjCij\textrm{OT}_\varepsilon(P, Q) \to \sum_{i, j} p_i q_j C_{ij} as ε→∞\varepsilon \to \infty, and that OTε(P,P)>0\textrm{OT}_\varepsilon(P, P) > 0 for every ε>0\varepsilon > 0 unless PP is a point mass. With Cij=∣xi−xj∣C_{ij} = |x_i - x_j|, show that the distributions PP on the atoms that minimize the limit ∑i,jpiqjCij\sum_{i, j} p_i q_j C_{ij} put all their mass on medians of QQ, for q_w the atoms 33 and 44. What would a model trained on OTε\textrm{OT}_\varepsilon with a large ε\varepsilon learn?
  2. The Sinkhorn divergence Sε(P,Q)=OTε(P,Q)−12OTε(P,P)−12OTε(Q,Q)S_\varepsilon(P, Q) = \textrm{OT}_\varepsilon(P, Q) - \tfrac{1}{2} \textrm{OT}_\varepsilon(P, P) - \tfrac{1}{2} \textrm{OT}_\varepsilon(Q, Q) removes this bias (Genevay et al., 2018; Feydy et al., 2019). Compute Sε(P,Q)S_\varepsilon(P, Q) for p_w and q_w with the absolute cost C at ε∈{10−3,10−2,…,103}\varepsilon \in \{10^{-3}, 10^{-2}, \ldots, 10^3\}. At ε=10−3\varepsilon = 10^{-3} the entries of K\mathbf{K} underflow, so carry out the Sinkhorn updates on log⁡a\log \mathbf{a} and log⁡b\log \mathbf{b} there, with scipy.special.logsumexp. Check that SεS_\varepsilon approaches W1W_1 as ε→0\varepsilon \to 0 and 12E(P,Q)\tfrac{1}{2} \mathcal{E}(P, Q) as ε→∞\varepsilon \to \infty, where E(P,Q)=2E∣X−Y∣−E∣X−X′∣−E∣Y−Y′∣\mathcal{E}(P, Q) = 2\mathbb{E}|X - Y| - \mathbb{E}|X - X'| - \mathbb{E}|Y - Y'| is the energy distance (Székely and Rizzo, 2013), the expression (25.4.3) with −∣x−y∣-|x - y| in place of the kernel. Derive the second limit from (a).
  1. [code] Sinkhorn iterations at small ε\varepsilon. ● Use sinkhorn, p_w and q_w of the six-point example.
    1. Stopping early. Call sinkhorn with the squared cost C2 at ε=0.1\varepsilon = 0.1 and max_iters=5000, so that the loop ends before the column sums have settled. The cost that it returns is below the optimum 3.53.5. Print the column sums of the returned matrix minus q_w. Which destinations receive too little, and why does that lower the cost? Why can no matrix with row sums p_w and column sums q_w cost less than 3.53.5?
    2. The number of iterations. Count the iterations that sinkhorn needs with C2 at ε∈{2,1,0.5,0.3,0.2,0.15,0.1}\varepsilon \in \{2, 1, 0.5, 0.3, 0.2, 0.15, 0.1\}, and plot the logarithm of the count against 1/ε1/\varepsilon. What kind of growth do the points at small ε\varepsilon show, and what count does it predict for ε=0.05\varepsilon = 0.05?
    3. Ties. Under the absolute cost C every plan that moves mass only rightward is optimal for p_w and q_w. Run sinkhorn with C at ε=0.1\varepsilon = 0.1 and 0.020.02. How many routes carry mass? Show that the limit plan has the form γij=aibj\gamma_{ij} = a_i b_j for j≥ij \geq i and 00 otherwise. On plans the regularizer is −ε-\varepsilon times the entropy plus a constant. Use this to explain why the limit is the plan of largest entropy among the optimal plans.

Discussions