25.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(x)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 q~(x)=e−E(x)\tilde{q}(\mathbf{x}) = e^{-E(\mathbf{x})}. The sum over ten classes becomes an integral over all possible inputs, Z=∫q~(x) dxZ = \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=q~/Zq = \tilde{q}/Z. Sample-based methods, whether built from a critic (Section 25.3.4), a kernel, or a transport plan (Section 25.4), avoid ZZ, 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 26.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⁡q~\log \tilde{q} with respect to the input x\mathbf{x}, which measures the slope of the log-density, eliminates ZZ 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, PP denotes the data distribution, which we observe only through samples, and QQ denotes the model, which we now know only through its score sQs_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 26.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 23.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)

25.5.1 The Score and the Fisher Divergence#

25.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 PP with a differentiable density pp, the score is the gradient of the log-density with respect to the data point:

sP(x)=∇xlog⁡p(x).(25.5.1)s_P(\mathbf{x}) = \nabla_{\mathbf{x}} \log p(\mathbf{x}). \tag{25.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 24.6); here, we differentiate with respect to x\mathbf{x}. For a one-dimensional Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2), the score is simply

s(x)=−x−μσ2,s(x) = -\frac{x - \mu}{\sigma^2},

which acts like a spring pulling xx back toward the mean μ\mu with stiffness 1/σ21/\sigma^2. For a mixture p=∑kwk pkp = \sum_k w_k\, p_k, applying the chain rule gives s(x)=∑krk(x) sk(x)s(x) = \sum_k r_k(x)\, s_k(x), where rk(x)=wkpk(x)/p(x)r_k(x) = w_k p_k(x) / p(x) is the posterior probability, or responsibility, that xx came from component kk. Each point therefore feels a weighted combination of the component springs. Near any mode, that mode's responsibility is close to 11, 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 25.5.1. We implement this formula directly below, computing the responsibilities in log space for numerical stability.

Figure 25.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(x)=q~(x)/Zq(\mathbf{x}) = \tilde{q}(\mathbf{x}) / Z, then

∇xlog⁡q(x)=∇xlog⁡q~(x)−∇xlog⁡Z=∇xlog⁡q~(x),\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 ZZ does not depend on x\mathbf{x}. For example, the unnormalized quartic density q~(x)=e−x4/4\tilde{q}(x) = e^{-x^4/4} has the score −x3-x^3, and we can evaluate it everywhere without ever learning that Z≈2.56Z \approx 2.56.

25.5.1.2 The Fisher Divergence#

Because scores drop ZZ, 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:

DF(P∥Q)=12 Ex∼P ⁣[∥sP(x)−sQ(x)∥2].(25.5.2)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{25.5.2}

Clearly DF(P∥Q)≥0D_{\textrm{F}}(P\|Q) \geq 0, and it is a genuine divergence, zero if and only if P=QP = Q (Section 25.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\log p - \log q to be constant, and because both densities must integrate to 11, 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 σ2\sigma^2 and their means are a distance Δ\Delta apart, their scores differ by the constant Δ/σ2\Delta/\sigma^2 at every xx, so

DF=Δ22σ4whereasDKL=Δ22σ2,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 25.1. When σ=1\sigma = 1, the two values match. Now rescale the coordinate xx by a factor of 22, 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/x21/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.

25.5.1.3 Mixing Weights of Distant Modes#

The expectation in (25.5.2) averages a difference of slopes over the data distribution PP. 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:

Pw=w N(−m,1)+(1−w) N(m,1),w=0.7 against w=0.3.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)(0.7, 0.3) and (0.3,0.7)(0.3, 0.7), which is 0.7log⁡73+0.3log⁡37=0.3390.7 \log\tfrac{7}{3} + 0.3 \log\tfrac{3}{7} = 0.339 nats regardless of how large mm becomes.

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

sw(x)=−x+mtanh⁡(mx−cw),cw=12log⁡w1−w.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)-(x + m) far to the left, the spring −(x−m)-(x - m) far to the right, and transitions between them near x=cw/mx = c_w/m. Notice that the mixing weight ww enters only through the location of that transition. At m=5m = 5, the transition sits at x=0.085x = 0.085 for w=0.7w = 0.7 and at x=−0.085x = -0.085 for w=0.3w = 0.3, right in the middle of the empty valley between the two modes, where the density is e−m2/2/2π≈1.5×10−6e^{-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 mm increases; we expect the KL divergence to stay near 0.3390.339 nats while the Fisher divergence collapses roughly like e−m2/2e^{-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.3390.339 nats while the Fisher divergence plunges by more than four orders of magnitude, from about 0.10.1 down to roughly 4×10−64 \times 10^{-6}. At m=5m = 5 it is on the order of e−m2/2=e−12.5≈4×10−6e^{-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\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%30\% of its mass where the data place 70%70\% (Wenliang and Kanagawa, 2020).

Fortunately, adding noise fills the valley. If we add independent Gaussian noise of standard deviation 22 to both mixtures, each component's variance grows from 11 to 55. Modes that were ten standard deviations apart are now only 4.54.5 standard deviations apart, raising the density in the valley from 1.5×10−61.5 \times 10^{-6} to roughly 0.0150.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.

25.5.2 Stein's Identity#

The Fisher divergence suffers from a second, even more immediate obstacle: it depends on sPs_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 sPs_P enters, let us expand the square in one dimension:

DF(P∥Q)=12 EP[sP2]−EP[sP sQ]+12 EP[sQ2].(25.5.3)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{25.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 QQ 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 QQ.

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

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

Proof. By definition s=p′/ps = p'/p, so p′=s pp' = s\, p. Integrating by parts (Section 22.6.2.3) gives

∫g′ p dx=[g p]−∞∞−∫g p′ dx=−∫g s p dx,\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 gg. ■\blacksquare

For the standard normal distribution, s(x)=−xs(x) = -x, and Stein's identity reads E[g′(X)]=E[Xg(X)]\mathbb{E}[g'(X)] = \mathbb{E}[X g(X)]. Setting g(x)=xg(x) = x, for instance, immediately yields E[X2]=1\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.

25.5.2.1 Score Matching#

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

DF(P∥Q)=Ex∼P[12 sQ(x)2+sQ′(x)]+12 EP[sP2].(25.5.5)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{25.5.5}

Integration by parts has shifted the derivative off the data, which have none, and onto the model. Since the trailing term 12EP[sP2]\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 ZZ nor sPs_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 25.5.1 shows how cleanly this works in practice. Introduce a scale parameter θ>0\theta > 0 via q~θ(x)=e−θx4/4\tilde{q}_\theta(x) = e^{-\theta x^4/4}, which gives sQ(x)=−θx3s_Q(x) = -\theta x^3 and sQ′(x)=−3θx2s_Q'(x) = -3\theta x^2. Writing a bar for the sample average over the data, the model-dependent part of (25.5.5) is estimated by a simple quadratic in θ\theta:

12 sQ2+sQ′‾=12 θ2 x6‾−3 θ x2‾,which is minimized atθ^=3 x2‾x6‾.\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−θx4/4e^{-\theta x^4/4}. Maximum likelihood requires Z(θ)Z(\theta) and leads to a different estimator (Exercise 4), though for a Gaussian model the two estimators coincide (Exercise 3).

In one dimension, sQ′s_Q' is just a single extra derivative. In Rn\mathbb{R}^n, however, it becomes the trace of the Jacobian, a sum of nn second derivatives (one per coordinate), turning the single backward pass that computed the score into nn backward passes, which is far too expensive for images. Section 26.6.1 extends score matching to Rn\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.

25.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 QQ. Applied to the model itself, the identity states that for every valid test function gg, the quantity g′+g sQg' + g\, s_Q has mean zero under QQ. The linear operator mapping gg to g′+g sQg' + g\, s_Q is called the Stein operator of QQ. If the sample average of g′+g sQg' + g\, s_Q is far from zero for some gg, we have evidence that the sample was not drawn from QQ. Notice what this check needs: only the model's score evaluated at the sample points, with no normalizing constant ZZ and no samples from the model.

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

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.50, −0.25-0.25, and −0.15-0.15. The widened sample tells a different story: because its mean is still zero, g=1g = 1 reports a value near zero (within a hundredth or so), completely missing a fourfold error in variance. Only g(x)=xg(x) = x (near −3-3) and g(x)=sin⁡xg(x) = \sin x (near −0.4-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=1g = 1 catches the shift but misses the variance, note that any smooth data distribution PP satisfies its own Stein identity, EP[g′]=−EP[g sP]\mathbb{E}_P[g'] = -\mathbb{E}_P[g\, s_P]. Substituting this into the model's Stein expectation gives

EP[g′+g sQ]=EP[(sQ−sP) g].(25.5.6)\mathbb{E}_P\big[ g' + g\, s_Q \big] = \mathbb{E}_P\big[ (s_Q - s_P)\, g \big]. \tag{25.5.6}

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

25.5.3 The Kernel Stein Discrepancy#

Since one test function checks only one property, we do what Section 25.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 AQ\mathcal{A}_Q denote the Stein operator of QQ, defined by (AQg)(x)=g′(x)+sQ(x) g(x)(\mathcal{A}_Q g)(x) = g'(x) + s_Q(x)\, g(x). Stein's identity states that EQ[AQg]=0\mathbb{E}_Q[\mathcal{A}_Q g] = 0, so we measure how badly PP violates the model's identity by sup⁡gEP[AQg]\sup_g \mathbb{E}_P[\mathcal{A}_Q g].

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

⟨φ′(x),φ(x′)⟩=∂xk,⟨φ(x),φ′(x′)⟩=∂x′k,⟨φ′(x),φ′(x′)⟩=∂x∂x′k.\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 QQ:

kQ(x,x′)=sQ(x) sQ(x′) k(x,x′)+sQ(x) ∂x′k(x,x′)+∂xk(x,x′) sQ(x′)+∂x∂x′k(x,x′).(25.5.7)\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{25.5.7}

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

KSD2(P,Q)=Ex,x′∼P[kQ(x,x′)].(25.5.8)\mathrm{KSD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}\big[ k_Q(x, x') \big]. \tag{25.5.8}

Because this expectation depends only on PP, a sample x1,…,xNx_1, \ldots, x_N from PP yields the unbiased estimator

KSD^2=1N(N−1)∑i≠jkQ(xi,xj),\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 (25.5.6) to each coordinate of φ\boldsymbol{\varphi}. This yields EP[ψ]=EP[(sQ−sP) φ]\mathbb{E}_P[\boldsymbol{\psi}] = \mathbb{E}_P[(s_Q - s_P)\, \boldsymbol{\varphi}], and squaring the norm gives

KSD2(P,Q)=Ex,x′∼P[(sQ−sP)(x) k(x,x′) (sQ−sP)(x′)].(25.5.9)\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{25.5.9}

Thus KSD is a kernel-smoothed cousin of the Fisher divergence DF(P∥Q)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′)k(x, x'). Unfortunately, this means KSD inherits the mode-weight blind spot, and makes it even worse. For the separated mixtures of Section 25.5.1, both points in a pair must now land in the empty valley where the scores differ, so KSD2\mathrm{KSD}^2 decays roughly like e−m2e^{-m^2}, the square of the Fisher divergence rate (Exercise 2e).

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

Our third candidate is the unnormalized quartic q~(x)=e−x4/4\tilde{q}(x) = e^{-x^4/4} from Section 25.5.1, whose normalizing constant we never need. Its score is −x3-x^3, making the score gap x−x3x - x^3; the resulting double integral in (25.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 (25.5.7) are ∂x′k=x−x′ℓ2 k\partial_{x'} k = \frac{x - x'}{\ell^2}\, k, ∂xk=−x−x′ℓ2 k\partial_x k = -\frac{x - x'}{\ell^2}\, k, and ∂x∂x′k=(1ℓ2−(x−x′)2ℓ4) k\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 kQ(xi,xj)k_Q(x_i, x_j). We test a single sample of 2,0002{,}000 points from N(0,1)\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)

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/3≈0.581/\sqrt{3} \approx 0.58, typically within about 0.10.1. Against the quartic, it is several tenths, clearly far from zero. Here the population value is 0.320.32, though a single sample can easily miss it by 0.10.1 or more because the cubic score −x3-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≈2.56Z \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, KSD2(P,Q)=0\mathrm{KSD}^2(P, Q) = 0 if and only if P=QP = 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 Rn\mathbb{R}^n changes only the notation: gg becomes a vector field, the Stein operator becomes sQ⊤g+∇⋅gs_Q^\top g + \nabla \cdot g, the scalar products in (25.5.7) become vector inner products, and the last term becomes ∑i∂xi∂xi′k\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 QQ, an algorithm known as Stein variational gradient descent (Liu and Wang, 2016). None of the training objectives in this book use KSD directly.

25.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 25.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 QQ.

Figure 25.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 dH2d_{\mathrm{H}}^2 are squares of metrics.

Table 25.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 25.3.4). The fourth column revisits the diagnostic test case that opened Section 25.3: data concentrated at a single point P=δ0P = \delta_0 and model samples at Q=δdQ = \delta_d a distance dd away. Any comparison that stays constant as dd varies leaves such a model with no gradient pointing toward the data.

Table 25.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 δ0\delta_0 against δd\delta_d with d≠0d \neq 0; f(0)f(0) and f′(∞)f'(\infty) are the limits of f(u)f(u) at 00 and of f(u)/uf(u)/u at infinity, and the MMD entry uses the RBF kernel with length scale ℓ\ell.
What the objective needsObjectiveDivergenceTwo point masses dd apartTreated in
model density at data pointsmaximum likelihood (autoregressive models, flows)forward KL∞\inftySection 25.3.2
samples of both, through a criticoriginal GANJensen--Shannonlog⁡2\log 2, constantSection 25.3.4
samples of both, through a criticf-GANthe chosen DfD_ff(0)+f′(∞)f(0) + f'(\infty), constantSection 25.3.4
samples of both, no critic for a fixed kernelmoment matching, two-sample testsMMDMMD2=2−2e−d2/(2ℓ2)\textrm{MMD}^2 = 2 - 2e^{-d^2/(2\ell^2)}, flat beyond a few ℓ\ellSection 25.4.1
samples of both, a 1-Lipschitz criticWGANW1W_1ddSection 25.4.2
model samples, the model's density at them, the unnormalized targetvariational inference, VAE posteriorreverse KL∞\inftySection 25.3.2
model score, data samplesscore matching, diffusion modelsFisherundefined (a point mass has no score)Section 25.5.1
model score, data samplesgoodness-of-fit tests, sampler qualityKSDundefined (a point mass has no score)Section 25.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 25.3.4). The optimal 1-Lipschitz critic has no such flat stretch, because W1W_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 W1W_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)O(N^{-1/2}) estimation error in any dimension (Section 25.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, MMD2\textrm{MMD}^2, and KSD2\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 25.6 uses KL divergence to define how much one variable tells us about another, and Section 25.7 asks how much dependence a sample of nn pairs can actually certify.

25.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×10−64 \times 10^{-6} while the KL divergence remains 0.3390.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.

25.5.6 Exercises#

  1. Fisher divergence and Stein moments. Recall that the score of N(μ,σ2)\mathcal{N}(\mu, \sigma^2) is −(x−μ)/σ2-(x - \mu)/\sigma^2.

    1. Compute the Fisher divergence (25.5.2) between N(μ1,σ12)\mathcal{N}(\mu_1, \sigma_1^2) and N(μ2,σ22)\mathcal{N}(\mu_2, \sigma_2^2) in closed form, and verify that it reduces to (μ1−μ2)2/(2σ4)(\mu_1 - \mu_2)^2 / (2\sigma^4) when the variances are equal. Is the Fisher divergence symmetric?
    2. Apply Stein's identity (25.5.4) for N(0,1)\mathcal{N}(0, 1) to g(x)=xkg(x) = x^k to derive the recursion E[Xk+1]=k E[Xk−1]\mathbb{E}[X^{k+1}] = k\, \mathbb{E}[X^{k-1}], and use it to compute E[X4]\mathbb{E}[X^4] and E[X6]\mathbb{E}[X^6]. What does g(x)=1g(x) = 1 yield for any density satisfying the conditions of the identity?
    3. Suppose a distribution PP on R\mathbb{R} has finite moments of all orders and satisfies EP[g′(X)−Xg(X)]=0\mathbb{E}_P[g'(X) - X g(X)] = 0 for every polynomial gg. Using the fact that the normal distribution is uniquely determined by its moments, explain why P=N(0,1)P = \mathcal{N}(0, 1). Now let P(X=1)=P(X=−1)=12P(X = 1) = P(X = -1) = \tfrac{1}{2}, and show that it satisfies the identity for every polynomial gg of degree at most 22, yet fails for g(x)=x3g(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 Pw=w N(−m,1)+(1−w) N(m,1)P_w = w\, \mathcal{N}(-m, 1) + (1 - w)\, \mathcal{N}(m, 1).

    1. The text computes DF(P0.7∥P0.3)D_{\textrm{F}}(P_{0.7}\|P_{0.3}) and DKL(P0.7∥P0.3)D_{\textrm{KL}}(P_{0.7}\|P_{0.3}) for m∈{1,3,5}m \in \{1, 3, 5\}. Extend the computation to m∈{1,…,6}m \in \{1, \ldots, 6\}. Show that the KL divergence approaches 0.4log⁡73≈0.3390.4 \log\tfrac{7}{3} \approx 0.339, and determine the decay rate of the Fisher divergence by fitting log⁡DF\log D_{\textrm{F}} against m2m^2.
    2. Derive the score formula sw(x)=−x+mtanh⁡(mx−cw)s_w(x) = -x + m \tanh(m x - c_w) from the component responsibilities. Show that s0.7s_{0.7} and s0.3s_{0.3} differ most at x=0x = 0, by 0.8 m0.8\,m, and substitute u=mxu = m x into the Fisher divergence integral to show that it scales as C m e−m2/2C\, m\, e^{-m^2/2} for large mm, where CC 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 N(0,σ2)\mathcal{N}(0, \sigma^2) noise to samples of both mixtures, turning each component into N(±m,1+σ2)\mathcal{N}(\pm m, 1 + \sigma^2). Repeat (a) at m=5m = 5 for σ∈{0,0.5,1,2}\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 PtP_t and QtQ_t denote two distributions after adding independent N(0,t)\mathcal{N}(0, t) noise to both. For two Gaussians of equal variance σ2\sigma^2 (raised to σ2+t\sigma^2 + t by the noise), verify from the closed forms in the text that ddtDKL(Pt∥Qt)=−DF(Pt∥Qt)\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=5m = 5 and t∈{1,4,9}t \in \{1, 4, 9\}, and conclude that DKL(P∥Q)=∫0∞DF(Pt∥Qt) dtD_{\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 (25.5.9) for the two mixtures by quadrature on a grid, using the RBF kernel with ℓ=1\ell = 1 and m∈{1,3,5}m \in \{1, 3, 5\}, and compare with the Fisher divergences in the text (at m=5m = 5 you should find roughly 10−1110^{-11}). Adapt ksd2_population from the text, replacing N(0,1)\mathcal{N}(0, 1) with P0.7P_{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 KSD2\mathrm{KSD}^2 decays like e−m2e^{-m^2}. Would choosing a smaller length scale help?
  3. Score matching for a Gaussian model. Let the data distribution PP have mean aa and variance vv, take the model Q=N(μ,σ2)Q = \mathcal{N}(\mu, \sigma^2), and write J=EP[12sQ2+sQ′]J = \mathbb{E}_P\big[\tfrac{1}{2} s_Q^2 + s_Q'\big] for the model-dependent part of (25.5.5).

    1. Show that J=(v+(a−μ)2)/(2σ4)−1/σ2J = \big(v + (a - \mu)^2\big)/(2\sigma^4) - 1/\sigma^2, and verify that it is minimized at μ=a\mu = a and σ2=v\sigma^2 = v, regardless of the rest of PP. Compare this with the Gaussian that minimizes forward KL divergence (Section 25.3.2).
    2. At the minimum, J=−1/(2v)J = -1/(2v), so the Fisher divergence from PP to its best Gaussian approximation is 12(EP[sP2]−1/v)\tfrac{1}{2}\big(\mathbb{E}_P[s_P^2] - 1/v\big). Apply Stein's identity for PP to g(x)=x−ag(x) = x - a, followed by the Cauchy--Schwarz inequality, to prove that EP[sP2]≥1/v\mathbb{E}_P[s_P^2] \geq 1/v, with equality if and only if PP is Gaussian. Which density of a given variance has the smallest mean squared score?
    3. Reparameterize the model as q~θ(x)=exp⁡(θ1x+θ2x2)\tilde{q}_{\boldsymbol{\theta}}(x) = \exp(\theta_1 x + \theta_2 x^2). Show that JJ 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 q~θ(x)=exp⁡(θ⊤ϕ(x))\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 q~θ(x)=e−θx4/4\tilde{q}_\theta(x) = e^{-\theta x^4/4} with θ>0\theta > 0.

    1. Compute the score. Apply Stein's identity with g(x)=xg(x) = x and with g(x)=x3g(x) = x^3 to show that under the model E[X4]=1/θ\mathbb{E}[X^4] = 1/\theta and E[X6]=(3/θ) E[X2]\mathbb{E}[X^6] = (3/\theta)\, \mathbb{E}[X^2], without computing the normalizing constant. Can Stein's identity with a polynomial gg also determine E[X2]\mathbb{E}[X^2]?
    2. The text derives the score-matching estimator θ^=3 x2‾/x6‾\hat\theta = 3\, \overline{x^2} / \overline{x^6}, where a bar denotes the sample average. Show that the normalizing constant scales as Z(θ)=θ−1/4Z(1)Z(\theta) = \theta^{-1/4} Z(1) and that maximum likelihood yields θ^=1/x4‾\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 UU follows a Gamma distribution with shape 14\tfrac{1}{4} and scale 11, then (4U/θ)1/4(4U/\theta)^{1/4} with a random sign has density q~θ/Z(θ)\tilde{q}_\theta / Z(\theta). Draw 1,0001{,}000 points at θ=1\theta = 1, compute both estimates, and repeat 2,0002{,}000 times. Which estimator has the smaller standard deviation, and by what factor? What does score matching trade away in exchange for avoiding ZZ?
    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 E[X2]/E[X6]=153\, \mathbb{E}[X^2]/\mathbb{E}[X^6] = \tfrac{1}{5} and 1/E[X4]=131/\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=N(0,1)P = \mathcal{N}(0, 1), as in the KSD experiment, and use the RBF kernel with length scale ℓ\ell.

    1. For the model N(μ,1)\mathcal{N}(\mu, 1), use (25.5.9) to show that KSD2=μ2 (1+2/ℓ2)−1/2\mathrm{KSD}^2 = \mu^2\, (1 + 2/\ell^2)^{-1/2}. What is its limit as ℓ→∞\ell \to \infty? Which single test function gg produces that same limit as the square of EP[g′+g sQ]\mathbb{E}_P[g' + g\, s_Q]?
    2. For the model N(0,4)\mathcal{N}(0, 4), whose score is −x/4-x/4, show that KSD2=916 ℓ (ℓ2+2)−3/2\mathrm{KSD}^2 = \tfrac{9}{16}\, \ell\, (\ell^2 + 2)^{-3/2}. (Hint: rewrite XX′X X' in terms of the independent variables X+X′X + X' and X−X′X - X'.) Show that this value is maximized at ℓ=1\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 ℓ∈{0.25,1,4,16}\ell \in \{0.25, 1, 4, 16\}, and compute the corresponding four values for the quartic model with score −x3-x^3. Why can no single length scale be optimal against every wrong model?

Discussions