Score-Based Comparisons

Dive into Deep Learning · §37.5

Score-Based Comparisons
Stein score function · Fisher divergence · mode-weight blindness · Stein’s identity · score matching · KSD

The Intractable Normalizer of Energy-Based Models

Motivation: Unnormalized Densities

An energy-based model (EBM) defines q_{\boldsymbol{\theta}}(\mathbf{x}) = e^{-E_{\boldsymbol{\theta}}(\mathbf{x})} / Z(\boldsymbol{\theta}) with normalizing integral Z(\boldsymbol{\theta}) = \int_{\mathbb{R}^n} e^{-E_{\boldsymbol{\theta}}(\mathbf{x})}\,d\mathbf{x}:

s_Q(\mathbf{x}) = \nabla_{\mathbf{x}}\log q_{\boldsymbol{\theta}}(\mathbf{x}) = -\nabla_{\mathbf{x}} E_{\boldsymbol{\theta}}(\mathbf{x})

  • Why MLE & GANs struggle: MLE needs intractable \nabla_{\boldsymbol{\theta}}\log Z(\boldsymbol{\theta}), while GANs/MMD/W_1 need expensive Langevin MCMC samples from Q_{\boldsymbol{\theta}}.
  • Score escape hatch: Differentiating wrt input \mathbf{x} kills \log Z(\boldsymbol{\theta}) in one backward pass.

The Score Function Eliminates the Normalizer Z

Log-Density Gradients

At every point \mathbf{x} \in \mathbb{R}^n, the (Stein) score points in the direction of steepest log-density ascent:

  • Definition and Z-invariance: Since \nabla_{\mathbf{x}} \log Z = \mathbf{0}: s_Q(\mathbf{x}) = \nabla_{\mathbf{x}} \log q(\mathbf{x}) = -\nabla_{\mathbf{x}} E(\mathbf{x})
  • Gaussian restoring spring: For \mathcal{N}(\mu, \sigma^2), s(x) = -\frac{x - \mu}{\sigma^2} pulls x toward \mu with stiffness 1/\sigma^2.
  • Mixture hand-off: For p(x) = \sum_k w_k p_k(x), the chain rule weights each component’s score by its posterior responsibility r_k(x) = \frac{w_k p_k(x)}{p(x)}: s(x) = \sum_k r_k(x)\,s_k(x)
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Stable Mixture Scores in Code

Log-Domain Responsibility Weighting

Subtracting the top log-component c_{\max}(x) stops mixture log-densities and scores underflowing in the tails:

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)
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)

The Fisher Divergence Compares Score Fields

Mean Squared Score Discrepancy

The Fisher divergence measures the expected squared Euclidean distance between the data score s_P(\mathbf{x}) and model score s_Q(\mathbf{x}), averaged under the data distribution P:

D_{\textrm{F}}(P \| Q) = \frac{1}{2}\mathbb{E}_{\mathbf{x} \sim P}\Big[\big\|s_P(\mathbf{x}) - s_Q(\mathbf{x})\big\|_2^2\Big]

  • Identity of indiscernibles on connected supports: Clearly D_{\textrm{F}}(P \| Q) \ge 0. If p and q are strictly positive and smooth on a connected region, s_P = s_Q \implies \nabla(\log p - \log q) = \mathbf{0} \implies p(\mathbf{x}) = c\,q(\mathbf{x}), and \int p = \int q = 1 forces c = 1 (P = Q).
  • Coordinate scale dependence (1/x^2 units vs. dimensionless nats): For two Gaussians \mathcal{N}(\mu_1, \sigma^2) and \mathcal{N}(\mu_2, \sigma^2) separated by \Delta = |\mu_1 - \mu_2|, the score difference is identically \Delta/\sigma^2, giving: D_{\textrm{F}}(P \| Q) = \frac{\Delta^2}{2\sigma^4} \qquad \text{whereas} \qquad D_{\textrm{KL}}(P \| Q) = \frac{\Delta^2}{2\sigma^2} Doubling the coordinate scale (x \mapsto 2x) leaves D_{\textrm{KL}} invariant but divides D_{\textrm{F}} by 4.

The Mode-Weight Blind Spot of Score Comparisons

Why Connected Support Matters

Compare P_{0.7} and P_{0.3} for P_w = w\,\mathcal{N}(-m, 1) + (1 - w)\,\mathcal{N}(m, 1) at separation m = 5:

s_w(x) = -x + m\tanh(mx - c_w), \qquad c_w = \tfrac12\log\frac{w}{1 - w}

  • Identical inside both modes: Near x \approx \pm m, \tanh(\pm m^2 - c_w) \approx \pm 1 for both w = 0.7 and w = 0.3, so s_{0.7}(x) \approx s_{0.3}(x) \approx -(x \mp m).
  • Disagreement hides in the empty valley: At x \approx 0, p(0) \approx 1.5 \times 10^{-6}, collapsing D_{\textrm{F}}(P_{0.7} \| P_{0.3}) \approx 4 \times 10^{-6} \approx 0.

Measuring Exponential Collapse of Fisher Divergence

Quadrature Demonstration

As mode separation m increases from 1 to 5, D_{\textrm{KL}}(P_{0.7} \| P_{0.3}) converges to the discrete weight divergence 0.7\ln\frac{7}{3} + 0.3\ln\frac{3}{7} = 0.339\text{ nats}, while D_{\textrm{F}}(P_{0.7} \| P_{0.3}) collapses by four orders of magnitude (\sim e^{-m^2/2}):

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

How Multi-Scale Noise Fixes Mode-Weight Blindness

Why Diffusion Models Perturb Data

  • Clean mixture (\sigma_{\textrm{noise}} = 0): Modes at \pm 5 are 10\sigma apart with valley density p(0) = 1.5 \times 10^{-6}, making D_{\textrm{F}} blind to mixing weights w.
  • Noised mixture (\sigma_{\textrm{noise}} = 2): Convolving with \mathcal{N}(0, 2^2) widens variance to \sigma_{\textrm{tot}}^2 = 5 (4.47\sigma separation) and boosts valley density 10{,}000\times to 1.5 \times 10^{-2}.
  • Multi-scale diffusion recipe (Song & Ermon, 2019): High noise bridges valleys to learn global mode weights; low noise resolves local shapes.

Expanding Fisher Divergence: The Unknown Data Score

The Sample-Estimation Obstacle

Even on a single connected mode, how can we minimize D_{\textrm{F}}(P \| Q) when we observe data P only as a finite sample \{x_i\}_{i=1}^N and have no formula for the data score s_P(x)?

  • Expand the squared score gap in 1D: D_{\textrm{F}}(P \| Q) = \underbrace{\frac{1}{2}\mathbb{E}_{x \sim P}\big[s_P(x)^2\big]}_{\text{constant independent of } Q} - \underbrace{\mathbb{E}_{x \sim P}\big[s_P(x)\,s_Q(x)\big]}_{\text{cross term containing unknown } s_P} + \underbrace{\frac{1}{2}\mathbb{E}_{x \sim P}\big[s_Q(x)^2\big]}_{\text{direct data average of model score}}
  • Isolating the obstacle: Only the middle cross term -\mathbb{E}_P[s_P(x)s_Q(x)] involves both the unknown data slope s_P(x) = p'(x)/p(x) and the model Q.
  • Key insight: Because p(x) s_P(x) = p'(x), the cross term is the integral -\int p'(x) s_Q(x)\,dx, inviting integration by parts.

Stein’s Identity: Integration by Parts on Densities

Eliminating Unknown Derivatives

For any smooth density p(x) > 0 and test function g(x) with g(x)p(x) \to 0 at \pm\infty:

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

  • One-line IBP proof: Since p'(x) = p(x)s_p(x), \int g'(x)p(x)\,dx = [gp]_{-\infty}^\infty - \int g(x)p'(x)\,dx = -\mathbb{E}_p[g(x)s_p(x)].
  • Gaussian Stein lemma (s_p(x) = -x): \mathbb{E}[g'(X)] = \mathbb{E}[Xg(X)] for X \sim \mathcal{N}(0, 1).

Hyvärinen Score Matching via Stein’s Identity

Training Unnormalized Models

Setting g(x) = s_Q(x) in Stein’s identity replaces the unknown cross term -\mathbb{E}_P[s_P s_Q] with +\mathbb{E}_P[s_Q'(x)]:

J(Q) = \mathbb{E}_{\mathbf{x} \sim P}\!\left[\tfrac12\|s_Q(\mathbf{x})\|_2^2 + \textrm{tr}(\nabla_{\mathbf{x}} s_Q(\mathbf{x}))\right]

  • Neither Z nor s_P required: Minimizing J(Q) = D_{\textrm{F}}(P \| Q) - \tfrac12\mathbb{E}_P\|s_P\|^2 trains unnormalized models directly on data samples.
  • Two-term geometry: \tfrac12\|s_Q\|^2 pulls the slope to \mathbf{0} at data points, while \textrm{tr}(\nabla s_Q) < 0 bends the log-density downward into a peak.

Worked Example: Fitting an Unnormalized Quartic

Closed-Form Score Matching

Consider fitting the unnormalized quartic density \tilde{q}_\theta(x) = e^{-\theta x^4/4} (\theta > 0) to data x_1, \ldots, x_N without ever computing Z(\theta) = \int_{-\infty}^\infty e^{-\theta x^4/4}\,dx:

  • Step 1 (Compute model score and its derivative): s_Q(x) = \frac{d}{dx}\!\left(-\frac{\theta x^4}{4}\right) = -\theta x^3, \qquad s_Q'(x) = -3\theta x^2
  • Step 2 (Form the empirical score-matching objective): Writing \overline{f(x)} = \frac{1}{N}\sum_{i=1}^N f(x_i): \hat{J}(\theta) = \overline{\frac{1}{2}s_Q(x)^2 + s_Q'(x)} = \frac{1}{2}\theta^2\,\overline{x^6} - 3\theta\,\overline{x^2}
  • Step 3 (Solve the quadratic in \theta): Setting \hat{J}'(\theta) = \theta\,\overline{x^6} - 3\overline{x^2} = 0 yields the closed-form estimator \hat{\theta}_{\textrm{SM}} = \frac{3\overline{x^2}}{\overline{x^6}} from two empirical moments. (Note: In \mathbb{R}^n, computing \textrm{tr}(\nabla_{\mathbf{x}} s_Q(\mathbf{x})) = \sum_{i=1}^n \partial_{x_i} s_{Q,i}(\mathbf{x}) requires n backward passes, motivating sliced and denoising score matching in Chapter 17 and §38.6.)

Stein’s Operator as a Goodness-of-Fit Diagnostic

Testing Samples Against a Score

What if we reverse the roles and apply Stein’s identity to the model Q instead of the data P? Define the linear Stein operator \mathcal{A}_Q of model Q:

(\mathcal{A}_Q g)(x) = g'(x) + s_Q(x)\,g(x) \implies \mathbb{E}_{x \sim Q}\big[(\mathcal{A}_Q g)(x)\big] = 0 \quad \text{for all test functions } g

  • Goodness-of-fit testing without Z or model samples: Given data samples x_1, \ldots, x_N \sim P, if the empirical average \frac{1}{N}\sum_{i=1}^N (\mathcal{A}_Q g)(x_i) deviates significantly from 0, we can reject P = Q using only s_Q(x_i).
  • What \mathbb{E}_P[\mathcal{A}_Q g] actually measures: Because P satisfies its own Stein identity \mathbb{E}_P[g'(x)] = -\mathbb{E}_P[s_P(x)g(x)], substituting into \mathbb{E}_P[g' + s_Q g] yields: \mathbb{E}_{x \sim P}\big[(\mathcal{A}_Q g)(x)\big] = \mathbb{E}_{x \sim P}\Big[\big(s_Q(x) - s_P(x)\big)\,g(x)\Big] Each test function g(x) probes the projection of the score gap s_Q - s_P onto g.

Probing Shifted and Widened Samples in Code

Single Test Functions Have Blind Spots

Testing Q = \mathcal{N}(0, 1) (s_Q(x) = -x, so (\mathcal{A}_Q g)(x) = g'(x) - x g(x)) on 200{,}000 draws from \mathcal{N}(0, 1), \mathcal{N}(0.5, 1), and \mathcal{N}(0, 4) shows why no single test function g suffices:

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
  • Because P = \mathcal{N}(0, 4) has an odd score gap s_Q(x) - s_P(x) = -x - (-x/4) = -\tfrac34 x, the even function g(x) = 1 integrates to 0 and completely misses a 4\times variance error.

Kernel Stein Discrepancy (KSD) and Stein Kernel

Supremum Over an RKHS Ball

Maximizing \mathbb{E}_P[(\mathcal{A}_Q g)(x)] over the RKHS unit ball \|\mathbf{w}\|_2 \le 1 yields the Kernel Stein Discrepancy:

\mathrm{KSD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}\big[k_Q(x, x')\big] = \mathbb{E}_{x, x' \sim P}\big[\Delta s(x)\,k(x, x')\,\Delta s(x')\big]

  • Stein kernel k_Q(x, x'): Uses only the model score s_Q(x) and derivatives of k(x, x')—testing goodness of fit from data samples alone without Z or sampling Q.

Evaluating Unbiased KSD U-Statistics in Code

Goodness-of-Fit Without Sampling Q

Using a single sample of N = 2{,}000 data points from P = \mathcal{N}(0, 1), the off-diagonal U-statistic \widehat{\mathrm{KSD}}^2 = \frac{1}{N(N-1)}\sum_{i \neq j} k_Q(x_i, x_j) cleanly separates the true model from shifted and quartic models using only their scores s_Q:

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)

Taxonomy of Distribution Comparison Families

Ratio, Test-Function, Transport, Score

Across §§37.3–37.5 we have constructed four families of distribution comparisons:

  • f-Divergences (\mathbb{E}_Q[f(p/q)]): KL, Reverse KL, \chi^2, Hellinger, JS, TV. Scale-invariant, but freeze on disjoint supports.
  • Integral Probability Metrics (\sup_{g \in \mathcal{G}}(\mathbb{E}_P g - \mathbb{E}_Q g)): TV (|g| \le 1/2), MMD (RKHS ball), W_1 (\textrm{Lip}_1). Estimable directly from samples.
  • Optimal Transport (\inf_\gamma \mathbb{E}_\gamma[c(x, y)]): W_1, W_2 (FID), Sinkhorn. Geometry-aware at all distances.
  • Score-Based (D_{\textrm{F}}, \mathrm{KSD}): Compare \nabla_{\mathbf{x}} \log q without normalizer Z, but blind to distant mode weights.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Master Decision Guide: Choosing a Training Loss

Matching Objectives to Model Capabilities

  • Explicit normalized density q_{\boldsymbol{\theta}} > 0: Maximum likelihood minimizes Forward KL (mode-covering).
  • Tractable q_{\boldsymbol{\theta}} + unnormalized target \tilde{p}: Variational inference (ELBO) minimizes Reverse KL (mode-seeking).
  • Implicit sample generator or EBM: Use MMD (closed-form two-sample tests), WGAN / Sinkhorn W_1 (non-vanishing tail gradients), or Score Matching / KSD (no normalizer Z).

Concept Check: Fisher Scaling, KSD, Normalizers

Check Your Understanding

Test your understanding of score-based comparisons:

  1. Coordinate rescaling (D_{\textrm{F}} vs. D_{\textrm{KL}}): Compute D_{\textrm{F}}(P \| Q) = \frac{\Delta^2}{2\sigma^4} and D_{\textrm{KL}}(P \| Q) = \frac{\Delta^2}{2\sigma^2} for P = \mathcal{N}(0, 1) vs. Q = \mathcal{N}(1, 1), and then for the doubled-coordinate pair P = \mathcal{N}(0, 4) vs. Q = \mathcal{N}(2, 4). Why does one change and not the other?
  2. Closed-form KSD prediction: Using \mathrm{KSD}^2(P, Q) = \mathbb{E}_{x, x' \sim P}[(s_Q - s_P)(x)k(x, x')(s_Q - s_P)(x')], compute the exact population \mathrm{KSD}^2 between data P = \mathcal{N}(0, 1) and shifted model Q = \mathcal{N}(1, 1) under the RBF kernel k(x, x') = e^{-(x-x')^2/2} (\ell = 1).
  3. Energy-based model audit: Given an EBM \tilde{q}(\mathbf{x}) = e^{-E(\mathbf{x})} with intractable Z and no MCMC sampler, plus a dataset \{\mathbf{x}_i\}_{i=1}^N \sim P, which of D_{\textrm{KL}}(P \| Q), \textrm{JS}, \textrm{MMD}, W_1, D_{\textrm{F}}, and \mathrm{KSD} can you compute or optimize?

Concept Check: Fisher Scaling, KSD, Normalizers (cont.)

Check Your Understanding

Answers:

  1. Rescaling: On \mathcal{N}(0,1)\|\mathcal{N}(1,1) (\Delta=1, \sigma^2=1), both equal 1/2. On \mathcal{N}(0,4)\|\mathcal{N}(2,4) (\Delta=2, \sigma^2=4), D_{\textrm{KL}} = \frac{4}{2(4)} = 1/2 is invariant, whereas D_{\textrm{F}} = \frac{4}{2(16)} = 1/8 drops 4\times because scores carry units of 1/x.
  2. Shifted KSD: Since s_P(x) = -x and s_Q(x) = -(x-1), the score gap is s_Q(x) - s_P(x) = 1 everywhere. Thus \mathrm{KSD}^2 = \mathbb{E}_{X, X' \sim \mathcal{N}(0,1)}[e^{-(X-X')^2/2}] = (1 + 2/1)^{-1/2} = 1/\sqrt{3} \approx 0.577 (since X - X' \sim \mathcal{N}(0, 2)).
  3. EBM audit: \mathrm{KSD}^2(P, Q) can be computed directly, and D_{\textrm{F}}(P \| Q) can be optimized up to the data constant \tfrac12\mathbb{E}_P[s_P^2] via Hyvärinen score matching. Forward KL requires Z, while JS, MMD, and W_1 require samples from Q.

Summary: Score-Based Comparisons and Objectives

Key Takeaways

Concept / Method Mathematical Formula Key Property / Requirement Deep Learning Role & Limitation
Stein Score s_Q(\mathbf{x}) = \nabla_{\mathbf{x}} \log q(\mathbf{x}) = -\nabla_{\mathbf{x}} E(\mathbf{x}) Drops normalizing constant Z = \int e^{-E(\mathbf{x})}\,d\mathbf{x} Vector field of restoring forces toward high-density modes
Fisher Divergence D_{\textrm{F}}(P \| Q) = \tfrac12\mathbb{E}_P[\|s_P(\mathbf{x}) - s_Q(\mathbf{x})\|_2^2] Units 1/x^2; 0 \iff P = Q on connected support Decays as \sim e^{-m^2/2} on isolated modes with swapped weights
Stein’s Identity \mathbb{E}_{x \sim p}[g'(x) + g(x)s_p(x)] = 0 Integration by parts assuming g(x)p(x) \to 0 Converts unknown density derivatives into sample expectations
Score Matching J(Q) = \mathbb{E}_P[\tfrac12\|s_Q(\mathbf{x})\|_2^2 + \textrm{tr}(\nabla_{\mathbf{x}} s_Q(\mathbf{x}))] Equals D_{\textrm{F}}(P \| Q) - \tfrac12\mathbb{E}_P[\|s_P\|^2] Trains EBMs & diffusion models (with multi-scale noise) without Z
Kernel Stein (KSD) \mathrm{KSD}^2(P, Q) = \mathbb{E}_{x,x' \sim P}[k_Q(x, x')] Kernel-smoothed score gap \mathbb{E}_P[\Delta s(x) k(x,x') \Delta s(x')] Nonparametric goodness-of-fit test requiring only s_Q and data samples