37.5  Score-Based Comparisons

A softmax layer turns ten logits into probabilities by exponentiating them and dividing by their sum, and nobody gives that sum a second thought. Now imagine letting a neural network assign a score not to ten classes, but to every possible input. By convention the sign is reversed: the network outputs an energy \(E(\mathbf{x})\) that is low for plausible inputs (where a logit would be high) and high for implausible ones, defining a density proportional to \(\tilde{q}(\mathbf{x}) = e^{-E(\mathbf{x})}\). The sum over ten classes becomes an integral over all possible inputs, \(Z = \int \tilde{q}(\mathbf{x})\, d\mathbf{x}\), which in high dimensions is completely intractable. Such an energy-based model can tell us how plausible an input is relative to another, but not its actual probability.

None of the distribution comparisons we have developed so far can handle this situation. Maximum likelihood requires the normalized density \(q = \tilde{q}/Z\). Sample-based methods, whether built from a critic (Section 37.3.4), a kernel, or a transport plan (Section 37.4), avoid \(Z\), but they require drawing samples from the model, and an energy function does not hand out samples. Each sample must be generated by a long random walk taking many small noisy steps toward lower energy, with every step requiring a gradient through the network (Section 38.6.2).

Computing a single gradient, however, is cheap: it costs just one backward pass, and it turns out to be all we need. The gradient of \(\log \tilde{q}\) with respect to the input \(\mathbf{x}\), which measures the slope of the log-density, eliminates \(Z\) completely because a constant has zero slope. This gradient is called the score, and in this section we compare distributions using scores alone. The mean squared difference between two scores gives the objective of score matching, which underlies diffusion models (Chapter 17). Yet comparing slopes comes with an important blind spot that anyone training a score-based model should understand: because a slope is purely local, it cannot tell how probability mass is divided between modes that lie far apart. We will measure just how blind it is.

As in the previous sections, \(P\) denotes the data distribution, which we observe only through samples, and \(Q\) denotes the model, which we now know only through its score \(s_Q\). We ask two central questions: what does a difference of slopes tell us about two distributions (and what does it miss), and how can we compare slopes at all when the data, a finite set of points, have no slope? Section 38.6.1 builds directly on these two answers. We also explore a third question, how to test whether a sample came from a model we cannot sample from, which can be skipped on a first reading. Finally, we pull all the comparisons from this chapter together into a table of training objectives and practical guidance on choosing among them.

from scipy import integrate

Our running examples are one-dimensional Gaussians and mixtures of two Gaussians. We start with three small helpers: log_components and log_mix evaluate the log-density of a Gaussian mixture stably by factoring out the largest term so the tails do not underflow (Section 35.8.2), and kl computes the KL divergence between two densities on a grid in nats.

def log_components(x, w, mus, sigmas):
    """log(w_k N(x; mu_k, sigma_k^2)) for every component k; shape (k, len(x))."""
    return (np.log(w)[:, None] - 0.5 * np.log(2 * np.pi * sigmas[:, None] ** 2)
            - (x - mus[:, None]) ** 2 / (2 * sigmas[:, None] ** 2))

def log_mix(x, w, mus, sigmas):
    """Log-density of the mixture sum_k w_k N(mu_k, sigma_k^2), computed stably."""
    c = log_components(x, w, mus, sigmas)
    c_max = c.max(axis=0)
    return c_max + np.log(np.exp(c - c_max).sum(axis=0))

def kl(log_a, log_b, x):
    """D_KL(A||B) by quadrature on the grid x; in nats."""
    return integrate.trapezoid(np.exp(log_a) * (log_a - log_b), x)

37.5.1 The Score and the Fisher Divergence

37.5.1.1 The Score

At every point in space, the score answers a simple geometric question: in which direction does the density rise, and how steeply? Formally, for a distribution \(P\) with a differentiable density \(p\), the score is the gradient of the log-density with respect to the data point:

\[ s_P(\mathbf{x}) = \nabla_{\mathbf{x}} \log p(\mathbf{x}). \tag{37.5.1}\]

Be careful not to confuse this with classical statistics, where “score” refers to the gradient of the log-likelihood with respect to the parameters (Section 36.6); here, we differentiate with respect to \(\mathbf{x}\). For a one-dimensional Gaussian \(\mathcal{N}(\mu, \sigma^2)\), the score is simply

\[ s(x) = -\frac{x - \mu}{\sigma^2}, \]

which acts like a spring pulling \(x\) back toward the mean \(\mu\) with stiffness \(1/\sigma^2\). For a mixture \(p = \sum_k w_k\, p_k\), applying the chain rule gives \(s(x) = \sum_k r_k(x)\, s_k(x)\), where \(r_k(x) = w_k p_k(x) / p(x)\) is the posterior probability, or responsibility, that \(x\) came from component \(k\). Each point therefore feels a weighted combination of the component springs. Near any mode, that mode’s responsibility is close to \(1\), so the point feels that mode’s spring alone; along the valley between modes, the responsibilities smoothly hand control from one attractor to the next, as illustrated in Figure 37.5.1. We implement this formula directly below, computing the responsibilities in log space for numerical stability.

Figure 37.5.1: The score field of a two-component Gaussian mixture. Arrows show the gradient of the log-density: near each mode the field acts as a spring pulling toward that mode’s mean, and along the valley between modes the responsibilities hand points off from one attractor to the other. Density contours are underlaid for reference.
def mix_score(x, w, mus, sigmas):
    """Score of a Gaussian mixture: responsibility-weighted component scores."""
    r = np.exp(log_components(x, w, mus, sigmas) - log_mix(x, w, mus, sigmas))
    return np.sum(r * -(x - mus[:, None]) / sigmas[:, None] ** 2, axis=0)

What makes the score so useful for energy-based models is that it ignores any normalizing constant. If \(q(\mathbf{x}) = \tilde{q}(\mathbf{x}) / Z\), then

\[ \nabla_{\mathbf{x}} \log q(\mathbf{x}) = \nabla_{\mathbf{x}} \log \tilde{q}(\mathbf{x}) - \nabla_{\mathbf{x}} \log Z = \nabla_{\mathbf{x}} \log \tilde{q}(\mathbf{x}), \]

because \(Z\) does not depend on \(\mathbf{x}\). For example, the unnormalized quartic density \(\tilde{q}(x) = e^{-x^4/4}\) has the score \(-x^3\), and we can evaluate it everywhere without ever learning that \(Z \approx 2.56\).

37.5.1.2 The Fisher Divergence

Because scores drop \(Z\), any comparison built from scores applies directly to unnormalized models. The most natural choice is the mean squared difference between the two score fields averaged under the data, known as the Fisher divergence:

\[ D_{\textrm{F}}(P\|Q) = \frac{1}{2}\, \mathbb{E}_{\mathbf{x} \sim P}\!\left[ \big\| s_P(\mathbf{x}) - s_Q(\mathbf{x}) \big\|^2 \right]. \tag{37.5.2}\]

Clearly \(D_{\textrm{F}}(P\|Q) \geq 0\), and it is a genuine divergence, zero if and only if \(P = Q\) (Section 37.3.1.1), provided both densities are strictly positive on the same connected region. On a connected region, matching scores force \(\log p - \log q\) to be constant, and because both densities must integrate to \(1\), that constant must be zero.

Comparing two Gaussians reveals an important difference between the Fisher divergence and the KL divergence. When both distributions have variance \(\sigma^2\) and their means are a distance \(\Delta\) apart, their scores differ by the constant \(\Delta/\sigma^2\) at every \(x\), so

\[ D_{\textrm{F}} = \frac{\Delta^2}{2\sigma^4} \qquad \textrm{whereas} \qquad D_{\textrm{KL}} = \frac{\Delta^2}{2\sigma^2}, \]

using the Gaussian KL formula from Section 37.1. When \(\sigma = 1\), the two values match. Now rescale the coordinate \(x\) by a factor of \(2\), doubling both \(\Delta\) and \(\sigma\): the KL divergence stays unchanged, whereas the Fisher divergence drops to a quarter of its previous value. Unlike KL divergence, which is dimensionless (measured in nats), the Fisher divergence carries units of \(1/x^2\), as a squared slope must. Its numerical value therefore depends on how the data are scaled, so a score-matching loss on one dataset cannot be compared directly with the loss on another, nor interpreted as a coding budget in nats. Exercise 1a works out the case of unequal variances.

37.5.1.3 Mixing Weights of Distant Modes

The expectation in Equation 37.5.2 averages a difference of slopes over the data distribution \(P\). When the data have multiple well-separated modes, these two ingredients combine badly. Consider two mixtures built from the exact same Gaussian components, but with swapped mixing weights:

\[ P_w = w\,\mathcal{N}(-m, 1) + (1 - w)\,\mathcal{N}(m, 1), \qquad w = 0.7 \textrm{ against } w = 0.3. \]

As distributions, these two mixtures are far apart. Once the modes are well separated, their KL divergence approaches that of the discrete weight vectors \((0.7, 0.3)\) and \((0.3, 0.7)\), which is \(0.7 \log\tfrac{7}{3} + 0.3 \log\tfrac{3}{7} = 0.339\) nats regardless of how large \(m\) becomes.

Their scores, however, barely differ at all. Near either mode, that mode’s responsibility is close to \(1\) in both mixtures, so both score fields reduce to that mode’s spring. Explicitly (as derived in Exercise 2b), the score of \(P_w\) is

\[ s_w(x) = -x + m \tanh(m x - c_w), \qquad c_w = \tfrac{1}{2} \log\frac{w}{1 - w}. \]

This expression behaves like the spring \(-(x + m)\) far to the left, the spring \(-(x - m)\) far to the right, and transitions between them near \(x = c_w/m\). Notice that the mixing weight \(w\) enters only through the location of that transition. At \(m = 5\), the transition sits at \(x = 0.085\) for \(w = 0.7\) and at \(x = -0.085\) for \(w = 0.3\), right in the middle of the empty valley between the two modes, where the density is \(e^{-m^2/2}/\sqrt{2\pi} \approx 1.5 \times 10^{-6}\). The data almost never visit the one place where the two scores disagree. Let us compute both divergences by quadrature as \(m\) increases; we expect the KL divergence to stay near \(0.339\) nats while the Fisher divergence collapses roughly like \(e^{-m^2/2}\).

xs = np.linspace(-14.0, 14.0, 14001)
w_a, w_b, unit = np.array([0.7, 0.3]), np.array([0.3, 0.7]), np.ones(2)
for m in (1.0, 3.0, 5.0):
    mus_m = np.array([-m, m])
    log_a, log_b = log_mix(xs, w_a, mus_m, unit), log_mix(xs, w_b, mus_m, unit)
    score_gap = mix_score(xs, w_a, mus_m, unit) - mix_score(xs, w_b, mus_m, unit)
    fisher = 0.5 * integrate.trapezoid(np.exp(log_a) * score_gap ** 2, xs)
    print(f'm = {m:.0f}: KL = {kl(log_a, log_b, xs):.3f} nats, '
          f'Fisher = {fisher:.1e}')
m = 1: KL = 0.184 nats, Fisher = 1.1e-01
m = 3: KL = 0.337 nats, Fisher = 7.1e-03
m = 5: KL = 0.339 nats, Fisher = 4.0e-06

As expected, the KL divergence settles at \(0.339\) nats while the Fisher divergence plunges by more than four orders of magnitude, from about \(0.1\) down to roughly \(4 \times 10^{-6}\). At \(m = 5\) it is on the order of \(e^{-m^2/2} = e^{-12.5} \approx 4 \times 10^{-6}\), just as the nearly empty valley predicted. A loss built purely from scores cannot see how probability mass is divided between distant modes. That is why we insisted on a connected region earlier: on two disconnected regions, identical scores allow \(\log p - \log q\) to take a different constant on each region. Consequently, a model trained by minimizing the Fisher divergence can get the location and shape of every mode right and still place \(30\%\) of its mass where the data place \(70\%\) (Wenliang and Kanagawa 2020).

Fortunately, adding noise fills the valley. If we add independent Gaussian noise of standard deviation \(2\) to both mixtures, each component’s variance grows from \(1\) to \(5\). Modes that were ten standard deviations apart are now only \(4.5\) standard deviations apart, raising the density in the valley from \(1.5 \times 10^{-6}\) to roughly \(0.015\). Now the data actually visit the region where the two scores disagree (Exercise 2c quantifies the gain). This is a major reason why diffusion models perturb data with noise across many scales before matching scores; Section 17.1 measures this exact blind spot on trained neural networks.

37.5.2 Stein’s Identity

The Fisher divergence suffers from a second, even more immediate obstacle: it depends on \(s_P\), the score of the data distribution, yet we only observe data as samples. A finite set of points has no slope. To see where \(s_P\) enters, let us expand the square in one dimension:

\[ D_{\textrm{F}}(P\|Q) = \tfrac{1}{2}\, \mathbb{E}_P\big[s_P^2\big] - \mathbb{E}_P\big[s_P\, s_Q\big] + \tfrac{1}{2}\, \mathbb{E}_P\big[s_Q^2\big]. \tag{37.5.3}\]

The third term is an expectation over the data of a function supplied by the model, so we can estimate it directly from samples. The first term does not depend on \(Q\) at all, so it is an irrelevant constant when fitting or ranking models. All the trouble sits in the middle cross term, where the unknown data score multiplies the model score. Remarkably, a single identity satisfied by every smooth density eliminates that cross term completely. We state and prove it for a one-dimensional density, and then put it to work twice: first on the data distribution to remove the cross term, and second on the model distribution to test whether a sample came from \(Q\).

Proposition (Stein’s identity). Let \(p > 0\) be a differentiable density on \(\mathbb{R}\) with score \(s = (\log p)'\), and let \(g\) be differentiable with \(g(x)\, p(x) \to 0\) as \(x \to \pm\infty\), \(\mathbb{E}_p|g'| < \infty\), and \(\mathbb{E}_p|g\, s| < \infty\). Then

\[ \mathbb{E}_{x \sim p}\big[ g'(x) + g(x)\, s(x) \big] = 0. \tag{37.5.4}\]

Proof. By definition \(s = p'/p\), so \(p' = s\, p\). Integrating by parts (Section 34.6.2.3) gives

\[ \int g'\, p\, dx = \big[ g\, p \big]_{-\infty}^{\infty} - \int g\, p'\, dx = -\int g\, s\, p\, dx, \]

where the boundary term vanishes and both integrals converge by the assumptions on \(g\). \(\blacksquare\)

For the standard normal distribution, \(s(x) = -x\), and Stein’s identity reads \(\mathbb{E}[g'(X)] = \mathbb{E}[X g(X)]\). Setting \(g(x) = x\), for instance, immediately yields \(\mathbb{E}[X^2] = 1\). This Gaussian case is Stein’s lemma (Stein 1981), and the general form is due to (Stein 1986). What makes the identity so powerful is that it converts knowledge of a slope into an equation about expectations, and expectations are what samples can estimate.

37.5.2.1 Score Matching

Suppose the data distribution \(P\) has a smooth density, even though we only see samples from it. Applying Stein’s identity to \(P\) (with \(s = s_P\)) and choosing the model’s score as the test function (\(g = s_Q\)) gives \(\mathbb{E}_P[s_Q' + s_Q\, s_P] = 0\). The cross term in Equation 37.5.3 therefore becomes \(-\mathbb{E}_P[s_Q']\), eliminating \(s_P\) entirely:

\[ D_{\textrm{F}}(P\|Q) = \mathbb{E}_{x \sim P}\Big[ \tfrac{1}{2}\, s_Q(x)^2 + s_Q'(x) \Big] + \tfrac{1}{2}\, \mathbb{E}_P\big[s_P^2\big]. \tag{37.5.5}\]

Integration by parts has shifted the derivative off the data, which have none, and onto the model. Since the trailing term \(\tfrac{1}{2}\mathbb{E}_P[s_P^2]\) is the same for every model, minimizing the Fisher divergence is equivalent to minimizing the first expectation: an average over data points of quantities the model itself supplies, requiring neither \(Z\) nor \(s_P\). This procedure is called score matching; Hyvärinen (2005) introduced it specifically to fit unnormalized models, demonstrating it on natural image patches.

Our unnormalized quartic from Section 37.5.1 shows how cleanly this works in practice. Introduce a scale parameter \(\theta > 0\) via \(\tilde{q}_\theta(x) = e^{-\theta x^4/4}\), which gives \(s_Q(x) = -\theta x^3\) and \(s_Q'(x) = -3\theta x^2\). Writing a bar for the sample average over the data, the model-dependent part of Equation 37.5.5 is estimated by a simple quadratic in \(\theta\):

\[ \overline{\tfrac{1}{2}\, s_Q^2 + s_Q'} = \tfrac{1}{2}\, \theta^2\, \overline{x^6} - 3\, \theta\, \overline{x^2}, \qquad \textrm{which is minimized at} \qquad \hat\theta = \frac{3\, \overline{x^2}}{\overline{x^6}}. \]

Just two sample moments fit the parameter, without ever integrating \(e^{-\theta x^4/4}\). Maximum likelihood requires \(Z(\theta)\) and leads to a different estimator (Exercise 4), though for a Gaussian model the two estimators coincide (Exercise 3).

In one dimension, \(s_Q'\) is just a single extra derivative. In \(\mathbb{R}^n\), however, it becomes the trace of the Jacobian, a sum of \(n\) second derivatives (one per coordinate), turning the single backward pass that computed the score into \(n\) backward passes, which is far too expensive for images. Section 38.6.1 extends score matching to \(\mathbb{R}^n\), shows how adding noise to the data avoids computing these second derivatives, and derives the training loss of diffusion models from the result.

37.5.2.2 A Test for Samples

Stein’s identity also works in the opposite direction: to test whether a given sample came from a model \(Q\). Applied to the model itself, the identity states that for every valid test function \(g\), the quantity \(g' + g\, s_Q\) has mean zero under \(Q\). The linear operator mapping \(g\) to \(g' + g\, s_Q\) is called the Stein operator of \(Q\). If the sample average of \(g' + g\, s_Q\) is far from zero for some \(g\), we have evidence that the sample was not drawn from \(Q\). Notice what this check needs: only the model’s score evaluated at the sample points, with no normalizing constant \(Z\) and no samples from the model.

How much can a single test function catch? Let the model be \(Q = \mathcal{N}(0, 1)\), whose score is \(-x\), so the Stein operator maps \(g\) to \(g'(x) - x\, g(x)\). Choosing \(g(x) = 1\) yields \(-x\), which checks the sample mean; choosing \(g(x) = x\) yields \(1 - x^2\), which checks the second moment against \(1\). As a third choice without a simple moment interpretation, let us try \(g(x) = \sin x\). Below we draw \(200{,}000\) points from three sources: the true model \(\mathcal{N}(0, 1)\), a shifted distribution \(\mathcal{N}(0.5, 1)\), and a widened distribution \(\mathcal{N}(0, 4)\), and print each test average alongside its standard error. From the first two moments alone, we expect \(-0.5\) and \(1 - 1.25 = -0.25\) on the shifted sample, and \(0\) and \(1 - 4 = -3\) on the widened one.

rng = np.random.default_rng()
n = 200_000
# Stein operator of the model Q = N(0, 1), whose score is -x:  g'(x) - x g(x)
tests = [('g = 1', np.ones_like, np.zeros_like),
         ('g = x', lambda t: t, np.ones_like),
         ('g = sin x', np.sin, np.cos)]
samples = [('N(0, 1)', rng.normal(0.0, 1.0, n)),
           ('N(0.5, 1)', rng.normal(0.5, 1.0, n)),
           ('N(0, 4)', rng.normal(0.0, 2.0, n))]
print(f'{"sample":10s}' + ''.join(f'{name:>18s}' for name, _, _ in tests))
for s_name, x in samples:
    vals = [g_prime(x) - x * g(x) for _, g, g_prime in tests]
    print(f'{s_name:10s}' + ''.join(f'{v.mean():+10.3f} ± {v.std() / np.sqrt(n):.3f}'
                                    for v in vals))
sample                 g = 1             g = x         g = sin x
N(0, 1)       -0.001 ± 0.002    -0.002 ± 0.003    -0.001 ± 0.002
N(0.5, 1)     -0.503 ± 0.002    -0.249 ± 0.004    -0.145 ± 0.002
N(0, 4)       +0.002 ± 0.004    -3.006 ± 0.013    -0.410 ± 0.003
sample                 g = 1             g = x         g = sin x
N(0, 1)       -0.002 ± 0.002    +0.001 ± 0.003    +0.003 ± 0.002
N(0.5, 1)     -0.501 ± 0.002    -0.250 ± 0.004    -0.146 ± 0.002
N(0, 4)       +0.002 ± 0.004    -3.008 ± 0.013    -0.410 ± 0.003
sample                 g = 1             g = x         g = sin x
N(0, 1)       -0.000 ± 0.002    -0.001 ± 0.003    +0.000 ± 0.002
N(0.5, 1)     -0.501 ± 0.002    -0.253 ± 0.004    -0.147 ± 0.002
N(0, 4)       -0.002 ± 0.004    -3.005 ± 0.013    -0.404 ± 0.003
sample                 g = 1             g = x         g = sin x
N(0, 1)       +0.001 ± 0.002    +0.005 ± 0.003    +0.004 ± 0.002
N(0.5, 1)     -0.499 ± 0.002    -0.245 ± 0.004    -0.145 ± 0.002
N(0, 4)       -0.004 ± 0.004    -3.008 ± 0.013    -0.402 ± 0.003

On the model’s own sample, every average lands within a couple of standard errors of zero. All three test functions readily catch the shifted sample, reporting about \(-0.50\), \(-0.25\), and \(-0.15\). The widened sample tells a different story: because its mean is still zero, \(g = 1\) reports a value near zero (within a hundredth or so), completely missing a fourfold error in variance. Only \(g(x) = x\) (near \(-3\)) and \(g(x) = \sin x\) (near \(-0.4\)) flag the mismatch. Any individual test function probes only one aspect of the sample, and a wrong distribution can easily agree with the model on that aspect.

To see why \(g = 1\) catches the shift but misses the variance, note that any smooth data distribution \(P\) satisfies its own Stein identity, \(\mathbb{E}_P[g'] = -\mathbb{E}_P[g\, s_P]\). Substituting this into the model’s Stein expectation gives

\[ \mathbb{E}_P\big[ g' + g\, s_Q \big] = \mathbb{E}_P\big[ (s_Q - s_P)\, g \big]. \tag{37.5.6}\]

Thus the test average is simply the difference between the two scores, weighted by \(g\). For the shifted sample, that score gap is the constant \(-x + (x - 0.5) = -0.5\), which \(g = 1\) captures completely. For the widened sample, the score gap is \(-x + x/4 = -\tfrac{3}{4}x\), an odd function whose integral against any symmetric density is zero when weighted by \(g = 1\). No single test function can be correlated with every possible score difference.

37.5.3 The Kernel Stein Discrepancy

Since one test function checks only one property, we do what Section 37.4.1 did for the maximum mean discrepancy (MMD): we test over an entire family of functions at once, namely all functions in the unit ball of a reproducing kernel feature space, and take the largest violation. Remarkably, this supremum over infinitely many test functions once again reduces to a closed form built from kernel evaluations on pairs of data points.

Let \(\mathcal{A}_Q\) denote the Stein operator of \(Q\), defined by \((\mathcal{A}_Q g)(x) = g'(x) + s_Q(x)\, g(x)\). Stein’s identity states that \(\mathbb{E}_Q[\mathcal{A}_Q g] = 0\), so we measure how badly \(P\) violates the model’s identity by \(\sup_g \mathbb{E}_P[\mathcal{A}_Q g]\).

Consider test functions of the form \(g(x) = \langle \mathbf{w}, \boldsymbol{\varphi}(x) \rangle\) with feature map \(\boldsymbol{\varphi}\) and \(\|\mathbf{w}\| \leq 1\). By linearity, the Stein operator acts directly on the features: \((\mathcal{A}_Q g)(x) = \langle \mathbf{w}, \boldsymbol{\psi}(x) \rangle\), where \(\boldsymbol{\psi} = \boldsymbol{\varphi}' + s_Q\, \boldsymbol{\varphi}\). By the Cauchy–Schwarz inequality, the supremum of \(\langle \mathbf{w}, \mathbb{E}_P[\boldsymbol{\psi}] \rangle\) over the unit ball is simply \(\big\| \mathbb{E}_P[\boldsymbol{\psi}] \big\|\). Squaring this norm gives \(\mathbb{E}\langle \boldsymbol{\psi}(x), \boldsymbol{\psi}(x') \rangle\) for two independent draws \(x, x' \sim P\). Expanding the inner product produces four terms, each expressed in terms of the kernel \(k(x, x') = \langle \boldsymbol{\varphi}(x), \boldsymbol{\varphi}(x') \rangle\) and its partial derivatives:

\[ \begin{aligned} \langle \boldsymbol{\varphi}'(x), \boldsymbol{\varphi}(x') \rangle &= \partial_x k, \qquad \langle \boldsymbol{\varphi}(x), \boldsymbol{\varphi}'(x') \rangle = \partial_{x'} k, \\ \langle \boldsymbol{\varphi}'(x), \boldsymbol{\varphi}'(x') \rangle &= \partial_x \partial_{x'} k. \end{aligned} \]

Collecting these four terms with the score weights defines the Stein kernel of \(Q\):

\[ \begin{aligned} k_Q(x, x') &= s_Q(x)\, s_Q(x')\, k(x, x') + s_Q(x)\, \partial_{x'} k(x, x') \\ &\quad + \partial_x k(x, x')\, s_Q(x') + \partial_x \partial_{x'} k(x, x'). \end{aligned} \tag{37.5.7}\]

The squared kernel Stein discrepancy (KSD) is then the expectation of the Stein kernel over two independent draws from the data:

\[ \mathrm{KSD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}\big[ k_Q(x, x') \big]. \tag{37.5.8}\]

Because this expectation depends only on \(P\), a sample \(x_1, \ldots, x_N\) from \(P\) yields the unbiased estimator

\[ \widehat{\mathrm{KSD}}^2 = \frac{1}{N(N-1)} \sum_{i \neq j} k_Q(x_i, x_j), \]

the same off-diagonal pairwise average used for MMD. In statistics, an average of this form over distinct tuples is called a U-statistic, hence the function name ksd2_ustat below.

To understand what KSD actually measures, apply Equation 37.5.6 to each coordinate of \(\boldsymbol{\varphi}\). This yields \(\mathbb{E}_P[\boldsymbol{\psi}] = \mathbb{E}_P[(s_Q - s_P)\, \boldsymbol{\varphi}]\), and squaring the norm gives

\[ \mathrm{KSD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}\big[ (s_Q - s_P)(x)\, k(x, x')\, (s_Q - s_P)(x') \big]. \tag{37.5.9}\]

Thus KSD is a kernel-smoothed cousin of the Fisher divergence \(D_{\textrm{F}}(P\|Q)\): instead of squaring the score gap at each point individually, it multiplies the score gap across pairs of data points weighted by \(k(x, x')\). Unfortunately, this means KSD inherits the mode-weight blind spot, and makes it even worse. For the separated mixtures of Section 37.5.1, both points in a pair must now land in the empty valley where the scores differ, so \(\mathrm{KSD}^2\) decays roughly like \(e^{-m^2}\), the square of the Fisher divergence rate (Exercise 2e).

When both scores are known, Equation 37.5.9 lets us predict the exact population value. Let the data be \(P = \mathcal{N}(0, 1)\), and test it against three candidate models. Against the true model \(\mathcal{N}(0, 1)\), the score gap vanishes and \(\mathrm{KSD}^2 = 0\). Against the shifted model \(\mathcal{N}(1, 1)\), the score gap is \(-(x - 1) - (-x) = 1\) everywhere, so \(\mathrm{KSD}^2 = \mathbb{E}[k(X, X')]\). For the RBF kernel \(k(x, x') = e^{-(x - x')^2/(2\ell^2)}\) with length scale \(\ell\), this is the same Gaussian integral we met in Section 37.4.1: since \(X - X' \sim \mathcal{N}(0, 2)\), the expectation equals \((1 + 2/\ell^2)^{-1/2}\), which at \(\ell = 1\) gives \(\mathrm{KSD}^2 = 1/\sqrt{3} \approx 0.577\).

Our third candidate is the unnormalized quartic \(\tilde{q}(x) = e^{-x^4/4}\) from Section 37.5.1, whose normalizing constant we never need. Its score is \(-x^3\), making the score gap \(x - x^3\); the resulting double integral in Equation 37.5.9 has no elementary closed form, so ksd2_population below evaluates it by quadrature on a grid (which we can do here only because we know the true data density for our synthetic benchmark).

For the one-dimensional RBF kernel, the derivatives in Equation 37.5.7 are \(\partial_{x'} k = \frac{x - x'}{\ell^2}\, k\), \(\partial_x k = -\frac{x - x'}{\ell^2}\, k\), and \(\partial_x \partial_{x'} k = \big(\frac{1}{\ell^2} - \frac{(x - x')^2}{\ell^4}\big)\, k\). In the code below, dk_dy is the derivative with respect to the second argument and kappa stores the matrix of values \(k_Q(x_i, x_j)\). We test a single sample of \(2{,}000\) points from \(\mathcal{N}(0, 1)\) against all three models, passing ksd2_ustat nothing more than each model’s score function.

def ksd2_ustat(x, score, ell=1.0):
    """U-statistic KSD^2 with the RBF kernel exp(-(a-b)^2 / (2 ell^2))."""
    d = x[:, None] - x[None, :]
    k = np.exp(-d ** 2 / (2 * ell ** 2))
    dk_dx = -d / ell ** 2 * k
    dk_dy = d / ell ** 2 * k
    d2k = (1 / ell ** 2 - d ** 2 / ell ** 4) * k
    s = score(x)
    kappa = (s[:, None] * s[None, :] * k + s[:, None] * dk_dy
             + dk_dx * s[None, :] + d2k)
    n = len(x)
    return (kappa.sum() - np.trace(kappa)) / (n * (n - 1))

def ksd2_population(score, ell=1.0):
    """KSD^2 of the data P = N(0, 1) against a model with this score, from
    the score difference s_Q - s_P weighted by the kernel, by quadrature."""
    t = np.linspace(-10.0, 10.0, 2001)
    h = np.exp(-t ** 2 / 2) / np.sqrt(2 * np.pi) * (score(t) + t)
    k = np.exp(-(t[:, None] - t[None, :]) ** 2 / (2 * ell ** 2))
    return h @ k @ h * (t[1] - t[0]) ** 2

x_p = rng.standard_normal(2000)          # the data sample, P = N(0, 1)
for name, s in [('true model  N(0,1)', lambda t: -t),
                ('wrong model N(1,1)', lambda t: -(t - 1)),
                ('quartic exp(-x^4/4)', lambda t: -t ** 3)]:
    print(f'KSD^2 vs the {name:19s}: {ksd2_ustat(x_p, s):+.4f}  '
          f'(population {ksd2_population(s):.4f})')
KSD^2 vs the true model  N(0,1) : +0.0010  (population 0.0000)
KSD^2 vs the wrong model N(1,1) : +0.5274  (population 0.5774)
KSD^2 vs the quartic exp(-x^4/4): +0.2835  (population 0.3208)
KSD^2 vs the true model  N(0,1) : -0.0008  (population 0.0000)
KSD^2 vs the wrong model N(1,1) : +0.5869  (population 0.5774)
KSD^2 vs the quartic exp(-x^4/4): +0.2893  (population 0.3208)
KSD^2 vs the true model  N(0,1) : +0.0015  (population 0.0000)
KSD^2 vs the wrong model N(1,1) : +0.5681  (population 0.5774)
KSD^2 vs the quartic exp(-x^4/4): +0.4494  (population 0.3208)
KSD^2 vs the true model  N(0,1) : -0.0004  (population 0.0000)
KSD^2 vs the wrong model N(1,1) : +0.6155  (population 0.5774)
KSD^2 vs the quartic exp(-x^4/4): +0.2739  (population 0.3208)

Against the true model, the estimate falls within a few thousandths of zero (and may even be slightly negative, as any unbiased estimator of zero can be). Against the shifted model, it lands close to our predicted \(1/\sqrt{3} \approx 0.58\), typically within about \(0.1\). Against the quartic, it is several tenths, clearly far from zero. Here the population value is \(0.32\), though a single sample can easily miss it by \(0.1\) or more because the cubic score \(-x^3\) grows rapidly in the tails, letting a handful of extreme points dominate the average.

Notice that across all three tests, only the score function changed. The data sample was fixed, we never sampled from any model, and the quartic’s normalizing constant \(Z \approx 2.56\) never appeared in the code.

With the RBF kernel, a population value of zero is trustworthy: for smooth data densities under mild regularity conditions on the scores, \(\mathrm{KSD}^2(P, Q) = 0\) if and only if \(P = Q\) (Liu et al. 2016; Chwialkowski et al. 2016). Still, our two-mixture example is a useful caution: “nonzero in theory” does not prevent the value from being astronomically small for distributions that are far apart.

Extending KSD to \(\mathbb{R}^n\) changes only the notation: \(g\) becomes a vector field, the Stein operator becomes \(s_Q^\top g + \nabla \cdot g\), the scalar products in Equation 37.5.7 become vector inner products, and the last term becomes \(\sum_i \partial_{x_i} \partial_{x'_i} k\). In practice, KSD serves as a goodness-of-fit test for unnormalized models and as a diagnostic for MCMC samplers. Applying the Stein operator to the kernel itself also gives a deterministic update direction that nudges particles toward \(Q\), an algorithm known as Stein variational gradient descent (Liu and Wang 2016). None of the training objectives in this book use KSD directly.

37.5.4 Training Objectives and Their Divergences

Across the previous two sections we built three major families of distribution comparisons, and this section added two score-based comparisons. Figure 37.5.2 maps out the three families and the divergences they share. It omits the Fisher divergence, which lies outside all three families, as well as KSD: although KSD has the form of an integral probability metric (a supremum over test functions), its test class depends on the model’s score and therefore changes with \(Q\).

Figure 37.5.2: The ratio, test-function, and transport families and their shared members. f-divergences average a convex function of the density ratio, integral probability metrics maximize mean differences over a class of test functions, and optimal-transport distances measure the minimum cost of moving mass. Total variation belongs to the first two families and Wasserstein-1 to the last two. (Total variation is also a transport cost that charges 1 for moving mass by any nonzero distance, omitted from the diagram for clarity.) Boxed names are metrics; JS and the squared Hellinger divergence \(d_{\mathrm{H}}^2\) are squares of metrics.

Table 37.5.1 organizes the training objectives built on these comparisons. For each objective, the table lists what it requires from the model and the data, along with the divergence it minimizes in the ideal limit of exact expectations and, for adversarial objectives, an optimal critic (the auxiliary network trained to tell real and generated samples apart in Section 37.3.4). The fourth column revisits the diagnostic test case that opened Section 37.3: data concentrated at a single point \(P = \delta_0\) and model samples at \(Q = \delta_d\) a distance \(d\) away. Any comparison that stays constant as \(d\) varies leaves such a model with no gradient pointing toward the data.

Table 37.5.1: Training objectives, ordered by what they need, and the divergences they minimize when averages are exact and the critic is optimal. The column on point masses is the value for \(\delta_0\) against \(\delta_d\) with \(d \neq 0\); \(f(0)\) and \(f'(\infty)\) are the limits of \(f(u)\) at \(0\) and of \(f(u)/u\) at infinity, and the MMD entry uses the RBF kernel with length scale \(\ell\).
What the objective needs Objective Divergence Two point masses \(d\) apart Treated in
model density at data points maximum likelihood (autoregressive models, flows) forward KL \(\infty\) Section 37.3.2
samples of both, through a critic original GAN Jensen–Shannon \(\log 2\), constant Section 37.3.4
samples of both, through a critic f-GAN the chosen \(D_f\) \(f(0) + f'(\infty)\), constant Section 37.3.4
samples of both, no critic for a fixed kernel moment matching, two-sample tests MMD \(\textrm{MMD}^2 = 2 - 2e^{-d^2/(2\ell^2)}\), flat beyond a few \(\ell\) Section 37.4.1
samples of both, a 1-Lipschitz critic WGAN \(W_1\) \(d\) Section 37.4.2
model samples, the model’s density at them, the unnormalized target variational inference, VAE posterior reverse KL \(\infty\) Section 37.3.2
model score, data samples score matching, diffusion models Fisher undefined (a point mass has no score) Section 37.5.1
model score, data samples goodness-of-fit tests, sampler quality KSD undefined (a point mass has no score) Section 37.5.3

Read from top to bottom, the table serves as a practical decision guide because its rows are ordered by what a model can provide. Whenever you can evaluate the model’s normalized density, and it stays positive wherever data may appear, train by maximum likelihood: forward KL needs only the data, gives an unbiased sample estimate, and penalizes leaving any data mode uncovered. When a model can only generate samples, you have three options. Training a learned critic as in a GAN (Section 16.1) is the standard choice for sample-only models of complex data like images, where we do not know ahead of time which features distinguish real samples from generated ones. Today these are mostly one-step generators distilled from diffusion models and the decoders of latent autoencoders. The drawbacks of a learned critic are that the estimated divergence is biased downward and flattens out when the model is far from the data (Section 37.3.4). The optimal 1-Lipschitz critic has no such flat stretch, because \(W_1\) keeps a constant slope at every distance. Trained critics need not behave like their optimal versions, though: in the experiment of Section 16.2.4.2 a trained logistic critic still slopes at far generated samples, and a \(W_1\) critic held near unit slope by the usual two-sided gradient penalty carries its generator to the data and then past it. A fixed kernel avoids training a second network altogether and achieves \(O(N^{-1/2})\) estimation error in any dimension (Section 37.4.1), making it ideal for two-sample tests and sample evaluation. It is usually applied to learned features, because the MMD of a fixed kernel weakens as the dimension of raw data grows, and its gradient vanishes beyond a few length scales.

The final three rows cover settings where a normalizing constant is unknown. When the target density is unnormalized while the model provides both samples and a tractable density (as in variational inference), reverse KL applies, at the risk of collapsing onto a single mode. When the model itself is known only through its score, the Fisher divergence (via score matching) is the natural choice, provided we add noise across scales so it does not lose sight of distant mode weights, just as diffusion models do (Section 17.1).

This table tells us which comparison each objective targets, but not how reliably we can estimate it from finite data. Every sample-based estimator from the last three sections (the critic bound, \(\textrm{MMD}^2\), and \(\mathrm{KSD}^2\)) carries estimation error, and the critic bound is biased low to boot. The next two sections shift from comparing two distributions to measuring dependence between two random variables: Section 37.6 uses KL divergence to define how much one variable tells us about another, and Section 37.7 asks how much dependence a sample of \(n\) pairs can actually certify.

37.5.5 Summary

Even when a model’s normalizing constant is intractable, we can compare it to data through its score, the gradient of the log-density with respect to the input, because the constant disappears upon differentiation. The Fisher divergence averages the squared gap between the data and model scores, and Stein’s identity eliminates the unknown data score via a single integration by parts, yielding score matching. Because scores are purely local, however, they cannot see how probability mass is split between distant modes: for two mixtures separated by ten standard deviations, the Fisher divergence drops to \(4 \times 10^{-6}\) while the KL divergence remains \(0.339\) nats. Applying Stein’s identity to the model instead gives the kernel Stein discrepancy, which tests samples using only the model’s score. Ultimately, the right training objective is determined by what your model can supply: a normalized density, samples, or a score.

37.5.6 Exercises

  1. Fisher divergence and Stein moments. Recall that the score of \(\mathcal{N}(\mu, \sigma^2)\) is \(-(x - \mu)/\sigma^2\).
    1. Compute the Fisher divergence Equation 37.5.2 between \(\mathcal{N}(\mu_1, \sigma_1^2)\) and \(\mathcal{N}(\mu_2, \sigma_2^2)\) in closed form, and verify that it reduces to \((\mu_1 - \mu_2)^2 / (2\sigma^4)\) when the variances are equal. Is the Fisher divergence symmetric?
    2. Apply Stein’s identity Equation 37.5.4 for \(\mathcal{N}(0, 1)\) to \(g(x) = x^k\) to derive the recursion \(\mathbb{E}[X^{k+1}] = k\, \mathbb{E}[X^{k-1}]\), and use it to compute \(\mathbb{E}[X^4]\) and \(\mathbb{E}[X^6]\). What does \(g(x) = 1\) yield for any density satisfying the conditions of the identity?
    3. Suppose a distribution \(P\) on \(\mathbb{R}\) has finite moments of all orders and satisfies \(\mathbb{E}_P[g'(X) - X g(X)] = 0\) for every polynomial \(g\). Using the fact that the normal distribution is uniquely determined by its moments, explain why \(P = \mathcal{N}(0, 1)\). Now let \(P(X = 1) = P(X = -1) = \tfrac{1}{2}\), and show that it satisfies the identity for every polynomial \(g\) of degree at most \(2\), yet fails for \(g(x) = x^3\). What does this imply for a goodness-of-fit test that checks Stein’s identity only on polynomials up to a fixed degree?
  2. [code] Score blindness to mixing weights. ● Let \(P_w = w\, \mathcal{N}(-m, 1) + (1 - w)\, \mathcal{N}(m, 1)\).
    1. The text computes \(D_{\textrm{F}}(P_{0.7}\|P_{0.3})\) and \(D_{\textrm{KL}}(P_{0.7}\|P_{0.3})\) for \(m \in \{1, 3, 5\}\). Extend the computation to \(m \in \{1, \ldots, 6\}\). Show that the KL divergence approaches \(0.4 \log\tfrac{7}{3} \approx 0.339\), and determine the decay rate of the Fisher divergence by fitting \(\log D_{\textrm{F}}\) against \(m^2\).
    2. Derive the score formula \(s_w(x) = -x + m \tanh(m x - c_w)\) from the component responsibilities. Show that \(s_{0.7}\) and \(s_{0.3}\) differ most at \(x = 0\), by \(0.8\,m\), and substitute \(u = m x\) into the Fisher divergence integral to show that it scales as \(C\, m\, e^{-m^2/2}\) for large \(m\), where \(C\) depends only on the weights. Compare this with your fitted rate in (a). What does this imply for the mixing weights learned by score matching (Wenliang and Kanagawa 2020)?
    3. Add independent \(\mathcal{N}(0, \sigma^2)\) noise to samples of both mixtures, turning each component into \(\mathcal{N}(\pm m, 1 + \sigma^2)\). Repeat (a) at \(m = 5\) for \(\sigma \in \{0, 0.5, 1, 2\}\). How does adding noise affect each divergence? Heavy noise reveals the mixing weights but blurs each mode’s shape, whereas light noise does the reverse. Why can a model that matches scores across multiple noise levels recover both (Song and Ermon 2019)?
    4. Let \(P_t\) and \(Q_t\) denote two distributions after adding independent \(\mathcal{N}(0, t)\) noise to both. For two Gaussians of equal variance \(\sigma^2\) (raised to \(\sigma^2 + t\) by the noise), verify from the closed forms in the text that \(\frac{d}{dt} D_{\textrm{KL}}(P_t\|Q_t) = -D_{\textrm{F}}(P_t\|Q_t)\). This identity holds for every pair of smooth densities. Confirm it using a finite difference for the two mixtures at \(m = 5\) and \(t \in \{1, 4, 9\}\), and conclude that \(D_{\textrm{KL}}(P\|Q) = \int_0^\infty D_{\textrm{F}}(P_t\|Q_t)\, dt\). At which noise level is the Fisher divergence largest? What does this integral tell us about matching scores at a single noise level versus across all noise levels (Song et al. 2021)?
    5. The kernel Stein discrepancy shares the same blind spot. Evaluate Equation 37.5.9 for the two mixtures by quadrature on a grid, using the RBF kernel with \(\ell = 1\) and \(m \in \{1, 3, 5\}\), and compare with the Fisher divergences in the text (at \(m = 5\) you should find roughly \(10^{-11}\)). Adapt ksd2_population from the text, replacing \(\mathcal{N}(0, 1)\) with \(P_{0.7}\) as the data distribution. Where must both points of a pair fall to contribute, and how wide is that region relative to \(\ell\)? Conclude that \(\mathrm{KSD}^2\) decays like \(e^{-m^2}\). Would choosing a smaller length scale help?
  3. Score matching for a Gaussian model. Let the data distribution \(P\) have mean \(a\) and variance \(v\), take the model \(Q = \mathcal{N}(\mu, \sigma^2)\), and write \(J = \mathbb{E}_P\big[\tfrac{1}{2} s_Q^2 + s_Q'\big]\) for the model-dependent part of Equation 37.5.5.
    1. Show that \(J = \big(v + (a - \mu)^2\big)/(2\sigma^4) - 1/\sigma^2\), and verify that it is minimized at \(\mu = a\) and \(\sigma^2 = v\), regardless of the rest of \(P\). Compare this with the Gaussian that minimizes forward KL divergence (Section 37.3.2).
    2. At the minimum, \(J = -1/(2v)\), so the Fisher divergence from \(P\) to its best Gaussian approximation is \(\tfrac{1}{2}\big(\mathbb{E}_P[s_P^2] - 1/v\big)\). Apply Stein’s identity for \(P\) to \(g(x) = x - a\), followed by the Cauchy–Schwarz inequality, to prove that \(\mathbb{E}_P[s_P^2] \geq 1/v\), with equality if and only if \(P\) is Gaussian. Which density of a given variance has the smallest mean squared score?
    3. Reparameterize the model as \(\tilde{q}_{\boldsymbol{\theta}}(x) = \exp(\theta_1 x + \theta_2 x^2)\). Show that \(J\) is a quadratic function of \(\boldsymbol{\theta}\), so score matching reduces to solving two linear equations in the data moments. Show that the same holds for any exponential-family model \(\tilde{q}_{\boldsymbol{\theta}}(x) = \exp\big(\boldsymbol{\theta}^\top \boldsymbol{\phi}(x)\big)\). What would maximum likelihood need to compute instead?
  4. [code] An unnormalized quartic. Let \(\tilde{q}_\theta(x) = e^{-\theta x^4/4}\) with \(\theta > 0\).
    1. Compute the score. Apply Stein’s identity with \(g(x) = x\) and with \(g(x) = x^3\) to show that under the model \(\mathbb{E}[X^4] = 1/\theta\) and \(\mathbb{E}[X^6] = (3/\theta)\, \mathbb{E}[X^2]\), without computing the normalizing constant. Can Stein’s identity with a polynomial \(g\) also determine \(\mathbb{E}[X^2]\)?
    2. The text derives the score-matching estimator \(\hat\theta = 3\, \overline{x^2} / \overline{x^6}\), where a bar denotes the sample average. Show that the normalizing constant scales as \(Z(\theta) = \theta^{-1/4} Z(1)\) and that maximum likelihood yields \(\hat\theta = 1 / \overline{x^4}\). Use part (a) to argue that both estimators converge to the true \(\theta\) on a large sample from the model, even though they are different functions of the data.
    3. If \(U\) follows a Gamma distribution with shape \(\tfrac{1}{4}\) and scale \(1\), then \((4U/\theta)^{1/4}\) with a random sign has density \(\tilde{q}_\theta / Z(\theta)\). Draw \(1{,}000\) points at \(\theta = 1\), compute both estimates, and repeat \(2{,}000\) times. Which estimator has the smaller standard deviation, and by what factor? What does score matching trade away in exchange for avoiding \(Z\)?
    4. Now suppose the data are standard normal (as in the KSD experiment), so no quartic model is exact. On a large sample, the two estimators in (b) converge to \(3\, \mathbb{E}[X^2]/\mathbb{E}[X^6] = \tfrac{1}{5}\) and \(1/\mathbb{E}[X^4] = \tfrac{1}{3}\). Evaluate ksd2_population at the scores of both fits, and find the \(\theta\) that minimizes it. Three criteria have selected three different quartics. Why is this not a contradiction, and under what condition would all three agree?
  5. [code] The length scale of the Stein kernel. Let the data be \(P = \mathcal{N}(0, 1)\), as in the KSD experiment, and use the RBF kernel with length scale \(\ell\).
    1. For the model \(\mathcal{N}(\mu, 1)\), use Equation 37.5.9 to show that \(\mathrm{KSD}^2 = \mu^2\, (1 + 2/\ell^2)^{-1/2}\). What is its limit as \(\ell \to \infty\)? Which single test function \(g\) produces that same limit as the square of \(\mathbb{E}_P[g' + g\, s_Q]\)?
    2. For the model \(\mathcal{N}(0, 4)\), whose score is \(-x/4\), show that \(\mathrm{KSD}^2 = \tfrac{9}{16}\, \ell\, (\ell^2 + 2)^{-3/2}\). (Hint: rewrite \(X X'\) in terms of the independent variables \(X + X'\) and \(X - X'\).) Show that this value is maximized at \(\ell = 1\), the standard deviation of the data, and approaches zero as \(\ell \to \infty\). Explain this limit using your answer to (a).
    3. Check both formulas with ksd2_population at \(\ell \in \{0.25, 1, 4, 16\}\), and compute the corresponding four values for the quartic model with score \(-x^3\). Why can no single length scale be optimal against every wrong model?

Discussions