Module contents
Lesson 15 of 28Core 110 min

Score matching: learning the gradient of the log-density

Model the score rather than the partition function. Derive implicit score matching by integration by parts, its random-projection variant, denoising score matching and its equivalence to smoothed-density score matching, and Tweedie's formula connecting optimal denoisers to scores.

After this lesson you can

  • Prove that Fisher divergence can be rewritten without the data score by integration by parts.
  • Prove equivalence up to a constant between denoising score matching and score matching of the smoothed density.
  • Derive Tweedie's formula and use it to turn a denoiser into a score.
  • Implement implicit, sliced and denoising score matching and compare cost and variance.
  • Explain the bias-variance trade-off introduced by the noise level.

Before you start

A direction without knowing total height

Suppose you can compare density at nearby points but cannot calculate total mass. The gradient of log-density says where probability increases locally without requiring that mass. The field does not directly say how much each region weighs: sampling requires following it and checking chain mixing.

If pθ(x)=p~θ(x)/Zθp_\theta(x)=\tilde p_\theta(x)/Z_\theta and ZθZ_\theta does not depend on xx, then sθ(x)=∇xlog⁡p~θ(x)s_\theta(x)=\nabla_x\log\tilde p_\theta(x). In an EBM with differentiable energy and finite partition function, sθ=−∇xEθs_\theta=-\nabla_x E_\theta. A positive multiplicative constant changes p~\tilde p and ZZ by the same factor and leaves the field unchanged. Normalization is still needed to interpret the model as a probability.

InteractiveA field that does not know Z

Shading shows C p(x), arrows show the score direction, and points follow Langevin dynamics.

  • C p(x)
  • Editable means
  • Particles and trajectories
  • Score direction

The mixture weights are 1/2, and each component has covariance σ² I. When C ≠ 1, C p is unnormalized. The constant cancels in ∇log(C p). Opacity uses the fixed scale 0.6(1 − exp(−8 C p)), which saturates at high values. Arrow lengths are compressed to make the directions readable. The widget advances 40 chains with x′ = x + h score(x) + √(2h) ξ, h = 0.015, and seed 1515, and shows four trajectories. The finite time and discretization do not guarantee convergence. The plot clips points outside its axes.

0.70
0.0
20
log(C p) at the origin
−3.125
Score at the origin
(0.000, 0.000)
C
1.000
Change the mixture, scale and particles. The reference model is explicit; a finite chain does not certify equilibrium.

Langevin uses only the score:

xk+1=xk+h sθ(xk)+2h ξk,ξk∼N(0,I).x_{k+1}=x_k+h\,s_\theta(x_k)+\sqrt{2h}\,\xi_k,\qquad \xi_k\sim\Normal(0,I).

In continuous time and under suitable assumptions, the density associated with the field is invariant. Discrete steps are biased for finite hh; additionally, two modes separated by a low-density region can take a long time to communicate. Neither a correct field nor a large finite step count alone guarantees an independent equilibrium sample. See the energy lesson.

Fisher divergence and the unknown-data problem

Let pp be a data density and sθs_\theta a differentiable field. The Fisher divergence used here is half the squared distance between fields:

J(θ)=12Ep[∥sθ(X)−∇xlog⁡p(X)∥2].J(\theta)=\frac12\mathbb E_p\left[\|s_\theta(X)-\nabla_x\log p(X)\|^2\right].

Its name does not mean differentiation with respect to parameters. Although examples can be drawn from pp, ∇xlog⁡p\nabla_x\log p is usually unknown at those examples. Expanding the square eliminates it:

J(θ)=Ep[12∥sθ∥2−sθ⋅∇log⁡p]+Cp,Cp=12Ep∥∇log⁡p∥2.J(\theta)=\mathbb E_p\left[\frac12\|s_\theta\|^2-s_\theta\cdot\nabla\log p\right]+C_p,\qquad C_p=\frac12\mathbb E_p\|\nabla\log p\|^2.

Constant CpC_p does not depend on θ\theta. Assuming integrability, valid integration by parts and vanishing flux of p(x)sθ(x)p(x)s_\theta(x) through the boundary, each coordinate satisfies

∫p(x)sθ,i(x)∂ilog⁡p(x) dx=∫sθ,i(x)∂ip(x) dx=−∫p(x)∂isθ,i(x) dx.\int p(x)s_{\theta,i}(x)\partial_i\log p(x)\,dx =\int s_{\theta,i}(x)\partial_i p(x)\,dx =-\int p(x)\partial_i s_{\theta,i}(x)\,dx.

On RD\mathbb R^D, a sufficient condition is that the surface flux of psθp s_\theta over spheres of increasing radius tends to zero, together with necessary regularity and integrability. On a domain with boundary, omitting the surface term is insufficient: verify it or modify the objective. Summing coordinates:

J(θ)=Ep[12∥sθ(X)∥2+tr⁡Jsθ(X)]+Cp.J(\theta)=\mathbb E_p\left[\frac12\|s_\theta(X)\|^2+\operatorname{tr}J_{s_\theta}(X)\right]+C_p.

This is Hyvärinen’s implicit score matching form. The evaluable integrand requires the field and divergence, not the data score or ZθZ_\theta. Equality of objectives does not imply the chosen family contains the true score or finite optimization finds it.

Estimating trace with directions

Divergence is tr⁡Js=∑i∂isi\operatorname{tr}J_s=\sum_i\partial_i s_i. Calculating all diagonal entries by reverse differentiation may require one pass per output coordinate. For random vector VV independent of XX with E[VV⊤]=I\mathbb E[VV^\top]=I:

EV[V⊤JsV]=tr⁡Js,EV[(V⊤s)2]=∥s∥2.\mathbb E_V[V^\top J_s V]=\operatorname{tr}J_s,\qquad \mathbb E_V[(V^\top s)^2]=\|s\|^2.

The first identity also holds when the Jacobian is not symmetric. Sliced score matching uses projections to estimate the objective; Jacobian-vector products avoid materializing the full Jacobian. Song and colleagues propose this for higher-dimensional models. One direction can have high variance; with KK independent directions, conditional average variance divides by KK when second moments exist. Directions uniform on the unit sphere have second moment I/DI/D: multiply the estimate by DD or rescale directions.

Actual cost depends on model, automatic differentiation, device and projection count. Avoiding exact trace is not free: sliced introduces products and Monte Carlo noise. An unbiased objective estimator also does not guarantee every observed gradient is small or one direction reveals the field.

Corrupting data to learn the smoothed score

Gaussian noise transforms clean observation X∼pX\sim p into Y=X+σϵY=X+\sigma\epsilon, with independent ϵ∼N(0,I)\epsilon\sim\Normal(0,I) and σ>0\sigma>0. Denote its conditional density qσ(y∣x)q_\sigma(y\mid x) and marginal pσ(y)=∫qσ(y∣x)p(dx)p_\sigma(y)=\int q_\sigma(y\mid x)p(dx). The original distribution may even concentrate on a manifold without ambient density; Gaussian convolution has smooth positive density.

The conditional target is known:

∇ylog⁡qσ(y∣x)=−y−xσ2=−ϵσ.\nabla_y\log q_\sigma(y\mid x)=-\frac{y-x}{\sigma^2}=-\frac{\epsilon}{\sigma}.

Denoising score matching minimizes squared error against that target, which can be generated without knowing pp:

LDSM(θ)=12EX,Y[∥sθ(Y)−∇Ylog⁡qσ(Y∣X)∥2].L_{\mathrm{DSM}}(\theta)=\frac12\mathbb E_{X,Y} \left[\left\|s_\theta(Y)-\nabla_Y\log q_\sigma(Y\mid X)\right\|^2\right].

To justify its objective, differentiate under the integral where conditions permit:

∇ypσ(y)=∫qσ(y∣x)∇ylog⁡qσ(y∣x) p(dx).\nabla_y p_\sigma(y)=\int q_\sigma(y\mid x) \nabla_y\log q_\sigma(y\mid x)\,p(dx).

Dividing by pσ(y)>0p_\sigma(y)>0, Bayes gives the identity

E[∇ylog⁡qσ(Y∣X)∣Y=y]=∇ylog⁡pσ(y).\mathbb E[\nabla_y\log q_\sigma(Y\mid X)\mid Y=y]=\nabla_y\log p_\sigma(y).

Write T=∇Ylog⁡qσ(Y∣X)T=\nabla_Y\log q_\sigma(Y\mid X) and m(Y)=E[T∣Y]m(Y)=\mathbb E[T\mid Y]. Conditional-projection decomposition in conditional expectation eliminates the cross term:

E∥sθ(Y)−T∥2=E∥sθ(Y)−m(Y)∥2+E∥T−m(Y)∥2.\mathbb E\|s_\theta(Y)-T\|^2 =\mathbb E\|s_\theta(Y)-m(Y)\|^2+\mathbb E\|T-m(Y)\|^2.

The final term does not depend on θ\theta. DSM and Fisher distance to pσp_\sigma therefore have the same minimizer within one family, not necessarily the score of unsmoothed pp. This is Vincent’s connection. Learning multiple levels requires specifying weighting: target −ϵ/σ-\epsilon/\sigma typically grows in magnitude as σ\sigma decreases, so carelessly summing losses can overweight some levels.

InteractiveChoosing σ in denoising score matching

The top plot shows the smoothed density. The lower plot compares the exact score with the function fitted to noisy examples.

  • Exact density and score
  • Untrained score

The data are an equal-weight mixture N(±1.5, 0.4²). Adding Gaussian noise raises each component’s variance to 0.4² + σ². The model is a linear combination of 17 radial basis functions, a constant and x̃. Each training run starts from scratch with Adam, 2048 examples, batches of 64, 800 updates and seeds 1520/1522. Updates run in chunks to keep the interface responsive. The loss is the mean of (σ sθ(x̃) + ε)². Changing σ discards the previous model.

Both metrics use 512 independent noisy observations with seed 1521. The first gives the weighted DSM loss. The second compares against the analytic score and weights squared error by σ². Each noise level changes the target and evaluation distribution, so the metrics at different σ describe different tasks. The fit can be unreliable outside regions with data. A finite run cannot establish a general trend across σ.

0.50
Completed updates
0 / 800
Weighted evaluation DSM loss
0.9941
Weighted squared score error
0.4663
Compare the learned field with the exact score of the smoothed mixture. Quality depends on sample, model and optimization.

Smoothing changes the target distribution. With large noise, regions between modes receive more examples and may be easier, but fine structures are erased. With small noise the marginal resembles original data more closely under regularity, but targets are noisy and few examples lie far from support. There is no universal guarantee that estimated error decreases as σ\sigma increases: capacity, samples, weighting and optimization matter too. On a singular manifold there is generally no ordinary ambient score of pp to approach pointwise.

The distinction matters when increasing observation count nn too. Even if estimator and optimization are consistent with fixed σ>0\sigma>0, their limit is the score of pσp_\sigma: bias relative to the clean score does not disappear simply by adding data. To approach the score of pp one can study a sequence σn→0\sigma_n\to0, but statistical and approximation errors must be controlled simultaneously for a particular class and region; the limit can fail without enough regularity. Statistical efficiency depends on estimator variance and available information as well as computational cost: generally no common optimal rate or noise level exists for all problems.

Tweedie: from denoiser to direction

For the same Gaussian noise, substitute the conditional target in the preceding identity:

∇ylog⁡pσ(y)=E[X∣Y=y]−yσ2,E[X∣Y=y]=y+σ2∇ylog⁡pσ(y).\nabla_y\log p_\sigma(y) =\frac{\mathbb E[X\mid Y=y]-y}{\sigma^2}, \qquad \mathbb E[X\mid Y=y]=y+\sigma^2\nabla_y\log p_\sigma(y).

This is Tweedie’s formula. The posterior mean minimizes expected squared reconstruction error; it need not be a plausible sample or belong to data support. On a circle, for example, averaging possible directions can yield an interior point. The identity remains valid for an initial distribution on the circle because convolution is differentiated with respect to yy, not a supposed two-dimensional circle density. See Efron for the empirical-Bayes interpretation.

InteractiveTweedie on a circle

Marker size on the circle shows relative posterior probability. The arrow goes from the observation to the posterior mean.

  • Posterior on the circle
  • Draggable observation
  • Mean and displacement σ² score

The prior is uniform on a circle of radius 1.5, and the noise is isotropic Gaussian with standard deviation σ. The continuous posterior is approximated with 256 evenly spaced angles and likelihood weights normalized in log space. The plot shows every other marker. The mean is an average and can lie inside the circle even though prior samples lie on it. The score is the posterior average of (x − x̃)/σ² over the quadrature points. The arrow satisfies Tweedie’s identity for this discrete approximation of the continuous integral.

0.55
Observation x̃
(1.900, 0.700)
Posterior mean
(1.335, 0.492)
σ² score
(−0.565, −0.208)
Drag the noisy observation and compare the posterior on the circle, its mean and the correction given by the score.

For X∼N(2,1)X\sim\Normal(2,1) and σ=1\sigma=1, the observation has distribution N(2,2)\Normal(2,2). At y=4y=4 its score is −(4−2)/2=−1-(4-2)/2=-1, so posterior mean is 4−1=34-1=3. This uses the noisy density’s score, not the clean density’s score at the same point. A squared-error-trained network approximates the mean only up to capacity, sample and optimization errors; converting output to score preserves those errors and divides them by σ2\sigma^2.

Lab: three score-matching objectives

Cells share variables and must run in order. First, a known three-dimensional Gaussian is corrupted with noise of standard deviation 0.5. Fit an affine field to the smoothed-distribution score in three ways: implicit objective with exact trace, sliced objective with one Rademacher projection per point, and denoising with the conditional noise score. Test data use another seed. Compare with the analytical smoothed score, not the noiseless score, and verify normal equations and a numerical derivative.

The second cell fixes data and parameters and estimates, across 50 replicates, the sum of gradient variances with 1, 4 or 16 independent projections. Another experiment regenerates the same noise for all three methods and an additional sliced probe, with original points fixed, and compares gradient variability. It also times objective evaluation on this small batch: this excludes training and projection generation and can vary between runs. In this linear model trace is directly known; the result does not prove an alternative is faster for high-dimensional networks.

The third uses a symmetric two-Gaussian mixture. To put the true score in the fitted family, its basis includes a hyperbolic tangent calculated from known mixture and noise parameters; those parameters are unknown in real data. Compare all three objectives against the analytical score of the smoothed mixture on test. Then observe conditional-target magnitude and the difference between original and smoothed scores for two noise levels on that distribution. This illustrates a trade-off, not a universal law or fixed estimator ranking.

[ ]Score matching on a GaussianBrowser
"""Score matching sobre una gaussiana suavizada, con NumPy y semillas fijas."""
import numpy as np

DIM = 3
SIGMA = 0.5
MEAN = np.array([0.6, -0.7, 0.25])
COV = np.array([[1.2, 0.35, 0.1], [0.35, 0.9, 0.15], [0.1, 0.15, 0.7]])
assert np.linalg.eigvalsh(COV).min() > 0
SMOOTH_COV = COV + SIGMA ** 2 * np.eye(DIM)
TRUE_A = -np.linalg.inv(SMOOTH_COV)
TRUE_B = -TRUE_A @ MEAN


def score_linear(x, A, b):
    return x @ A.T + b


def implicit_linear(y):
    # Minimiza E[||Ay+b||²/2 + tr(A)] con divisor N, no N−1.
    mean = y.mean(axis=0)
    centered = y - mean
    covariance = centered.T @ centered / len(y)
    A = -np.linalg.inv(covariance)
    return A, -A @ mean


def projection_features(y, v):
    return np.concatenate(((v[:, :, None] * y[:, None, :]).reshape(len(y), -1), v), axis=1)


def trace_features(v):
    return np.concatenate(((v[:, :, None] * v[:, None, :]).reshape(len(v), -1),
                           np.zeros_like(v)), axis=1)


def sliced_linear(y, v):
    # E_v[vvᵀ]=I: el cuadrado proyectado estima ||s||² y vᵀAv estima tr(A).
    features = projection_features(y, v)
    quadratic = features.T @ features / len(y)
    linear = trace_features(v).mean(axis=0)
    theta = np.linalg.solve(quadratic, -linear)
    return theta[:DIM * DIM].reshape(DIM, DIM), theta[DIM * DIM:]


def denoising_linear(y, x, sigma):
    conditional_score = (x - y) / sigma ** 2
    design = np.column_stack((y, np.ones(len(y))))
    coefficient = np.linalg.solve(design.T @ design, design.T @ conditional_score)
    return coefficient[:DIM].T, coefficient[DIM]


def fisher_error(x, A, b):
    delta = score_linear(x, A, b) - score_linear(x, TRUE_A, TRUE_B)
    return float(np.mean(np.sum(delta ** 2, axis=1)))


rng = np.random.default_rng(1501)
x_train = rng.multivariate_normal(MEAN, COV, 4096)
noise = rng.normal(size=x_train.shape)
y_train = x_train + SIGMA * noise
v_train = 2 * rng.integers(0, 2, size=y_train.shape) - 1
rng_test = np.random.default_rng(1502)
x_test = rng_test.multivariate_normal(MEAN, COV, 2048)
y_test = x_test + SIGMA * rng_test.normal(size=x_test.shape)

implicit_A, implicit_b = implicit_linear(y_train)
sliced_A, sliced_b = sliced_linear(y_train, v_train)
dsm_A, dsm_b = denoising_linear(y_train, x_train, SIGMA)

# La solución exacta del objetivo implícito cumple las ecuaciones normales.
mean_y = y_train.mean(axis=0)
cov_y = (y_train - mean_y).T @ (y_train - mean_y) / len(y_train)
assert np.allclose(implicit_A @ cov_y, -np.eye(DIM), atol=1e-10, rtol=0)
assert np.allclose(implicit_b, -implicit_A @ mean_y, atol=1e-10, rtol=0)
features = projection_features(y_train, v_train)
sliced_theta = np.concatenate((sliced_A.reshape(-1), sliced_b))
sliced_gradient = features.T @ (features @ sliced_theta) / len(y_train) + trace_features(v_train).mean(axis=0)
assert np.max(np.abs(sliced_gradient)) < 1e-9
design = np.column_stack((y_train, np.ones(len(y_train))))
dsm_target = (x_train - y_train) / SIGMA ** 2
dsm_coefficient = np.vstack((dsm_A.T, dsm_b))
dsm_gradient = design.T @ (design @ dsm_coefficient - dsm_target) / len(y_train)
assert np.max(np.abs(dsm_gradient)) < 1e-9

# Comprueba el score gaussiano por diferencias centrales de log p, sin usar Z.
point = y_test[0]
precision = np.linalg.inv(SMOOTH_COV)
def log_density_unnormalized(z):
    difference = z - MEAN
    return -0.5 * difference @ precision @ difference
eps = 1e-5
numeric = np.array([(log_density_unnormalized(point + np.eye(DIM)[i] * eps) -
                     log_density_unnormalized(point - np.eye(DIM)[i] * eps)) / (2 * eps)
                    for i in range(DIM)])
gradient_error = float(np.max(np.abs(numeric - score_linear(point[None], TRUE_A, TRUE_B)[0])))
assert gradient_error < 1e-8

for name, A, b in (('implícito', implicit_A, implicit_b), ('sliced', sliced_A, sliced_b),
                   ('denoising', dsm_A, dsm_b)):
    print(f'Gaussiana {name}: error cuadrático total de score en test = {fisher_error(y_test, A, b):.6f}')
print(f'Score verdadero gaussiano frente a diferencias finitas: {gradient_error:.2e}')
[ ]Projection variance and measured costBrowser
"""Varianza de sondas con datos fijos y coste medido de tres objetivos."""
import time

fixed_y = y_train[:256]
fixed_x = x_train[:256]
theta = np.concatenate((TRUE_A.reshape(-1), TRUE_B))


def one_projected_gradient(y, probe, theta):
    features = projection_features(y, probe)
    return features.T @ (features @ theta) / len(y) + trace_features(probe).mean(axis=0)


probe_rng = np.random.default_rng(1503)
projection_variances = {}
for count in (1, 4, 16):
    estimates = []
    for _ in range(50):
        gradients = []
        for _ in range(count):
            probe = 2 * probe_rng.integers(0, 2, size=fixed_y.shape) - 1
            gradients.append(one_projected_gradient(fixed_y, probe, theta))
        estimates.append(np.mean(gradients, axis=0))
    estimates = np.asarray(estimates)
    variance = float(np.mean(np.sum((estimates - estimates.mean(axis=0)) ** 2, axis=1)))
    projection_variances[count] = variance
    print(f'{count} proyección(es): suma de varianzas de gradiente = {variance:.6f} (50 réplicas)')

# Comparamos además los tres gradientes sobre los mismos datos originales.
# En cada réplica se regenera el ruido; sliced usa una sonda independiente.
method_rng = np.random.default_rng(1504)
method_gradients = {'implícito': [], 'sliced': [], 'denoising': []}
for _ in range(50):
    eps = method_rng.normal(size=fixed_x.shape)
    noisy = fixed_x + SIGMA * eps
    probe = 2 * method_rng.integers(0, 2, size=fixed_x.shape) - 1
    score = score_linear(noisy, TRUE_A, TRUE_B)
    implicit_A_grad = score.T @ noisy / len(noisy) + np.eye(DIM)
    method_gradients['implícito'].append(np.concatenate((implicit_A_grad.reshape(-1), score.mean(axis=0))))
    method_gradients['sliced'].append(one_projected_gradient(noisy, probe, theta))
    error = score + eps / SIGMA
    dsm_A_grad = error.T @ noisy / len(noisy)
    method_gradients['denoising'].append(np.concatenate((dsm_A_grad.reshape(-1), error.mean(axis=0))))
for name, values in method_gradients.items():
    values = np.asarray(values)
    variance = float(np.mean(np.sum((values - values.mean(axis=0)) ** 2, axis=1)))
    print(f'{name}: suma de varianzas de gradiente con ruido nuevo = {variance:.6f} (50 réplicas)')

# Tiempo de evaluación del objetivo para este modelo y este lote. No incluye
# entrenamiento ni construcción de sondas; son tiempos variables de esta máquina.
probe = 2 * probe_rng.integers(0, 2, size=fixed_y.shape) - 1
conditional = (fixed_x - fixed_y) / SIGMA ** 2

def implicit_value():
    score = score_linear(fixed_y, TRUE_A, TRUE_B)
    return np.mean(0.5 * np.sum(score ** 2, axis=1)) + np.trace(TRUE_A)

def sliced_value():
    score = score_linear(fixed_y, TRUE_A, TRUE_B)
    projected = np.sum(probe * score, axis=1)
    trace_estimate = np.sum((probe @ TRUE_A.T) * probe, axis=1)
    return np.mean(0.5 * projected ** 2 + trace_estimate)

def denoising_value():
    error = score_linear(fixed_y, TRUE_A, TRUE_B) - conditional
    return np.mean(0.5 * np.sum(error ** 2, axis=1))

timings = {}
for name, fn in (('implícito', implicit_value), ('sliced', sliced_value), ('denoising', denoising_value)):
    begin = time.perf_counter()
    for _ in range(150):
        fn()
    timings[name] = time.perf_counter() - begin
    print(f'{name}: {timings[name]:.4f} s para 150 evaluaciones del objetivo en este lote')
print('La comparación de tiempos corresponde a esta ejecución y a una traza lineal analítica; no generaliza a redes.')
[ ]Mixture score and the effect of noiseBrowser
"""Tres objetivos para una mezcla cuyo score verdadero es conocido."""
MIX_A = 1.5
BASE_STD = 0.6
MIX_SIGMA = 0.5
MIX_VAR = BASE_STD ** 2 + MIX_SIGMA ** 2
MIX_K = MIX_A / MIX_VAR


def mixture_sample(n, seed):
    random = np.random.default_rng(seed)
    means = MIX_A * (2 * random.integers(0, 2, size=n) - 1)
    x = BASE_STD * random.normal(size=(n, 2))
    x[:, 0] += means
    return x


def mixture_score(y, variance):
    return np.column_stack(((-y[:, 0] + MIX_A * np.tanh(MIX_A * y[:, 0] / variance)) / variance,
                            -y[:, 1] / variance))


def mixture_log_density(y, variance):
    # Constante incluida para claridad; logaddexp evita pérdida de precisión.
    left = -((y[:, 0] + MIX_A) ** 2 + y[:, 1] ** 2) / (2 * variance)
    right = -((y[:, 0] - MIX_A) ** 2 + y[:, 1] ** 2) / (2 * variance)
    return np.logaddexp(left, right) - np.log(2) - np.log(2 * np.pi * variance)


def mixture_features(y):
    tangent = np.tanh(MIX_K * y[:, 0])
    zeros = np.zeros(len(y))
    horizontal = np.column_stack((y[:, 0], tangent, zeros))
    vertical = np.column_stack((zeros, zeros, y[:, 1]))
    divergence = np.column_stack((np.ones(len(y)), MIX_K * (1 - tangent ** 2), np.ones(len(y))))
    return horizontal, vertical, divergence


def mixture_model(y, beta):
    horizontal, vertical, _ = mixture_features(y)
    return np.column_stack((horizontal @ beta, vertical @ beta))


mix_train_x = mixture_sample(4096, 1510)
mix_rng = np.random.default_rng(1511)
mix_train_y = mix_train_x + MIX_SIGMA * mix_rng.normal(size=mix_train_x.shape)
mix_v = 2 * mix_rng.integers(0, 2, size=mix_train_x.shape) - 1
mix_test_x = mixture_sample(2048, 1512)
mix_test_y = mix_test_x + MIX_SIGMA * np.random.default_rng(1513).normal(size=mix_test_x.shape)
h, v, div = mixture_features(mix_train_y)
gram = (h.T @ h + v.T @ v) / len(h)
beta_implicit = np.linalg.solve(gram, -div.mean(axis=0))
projected = mix_v[:, :1] * h + mix_v[:, 1:] * v
projected_div = div * np.column_stack((mix_v[:, 0] ** 2, mix_v[:, 0] ** 2, mix_v[:, 1] ** 2))
beta_sliced = np.linalg.solve(projected.T @ projected / len(h), -projected_div.mean(axis=0))
conditional_score = (mix_train_x - mix_train_y) / MIX_SIGMA ** 2
beta_dsm = np.linalg.solve(gram, (h.T @ conditional_score[:, 0] + v.T @ conditional_score[:, 1]) / len(h))
beta_true = np.array([-1 / MIX_VAR, MIX_A / MIX_VAR, -1 / MIX_VAR])
assert np.allclose(mixture_model(mix_test_y, beta_true), mixture_score(mix_test_y, MIX_VAR), atol=1e-12, rtol=0)

point = mix_test_y[:1]
finite = np.column_stack([(mixture_log_density(point + np.eye(2)[i] * 1e-5, MIX_VAR) -
                            mixture_log_density(point - np.eye(2)[i] * 1e-5, MIX_VAR)) / 2e-5
                           for i in range(2)])
mixture_gradient_error = float(np.max(np.abs(finite - mixture_score(point, MIX_VAR))))
assert mixture_gradient_error < 1e-8
divergence_numeric = sum((mixture_model(point + np.eye(2)[i] * 1e-5, beta_true)[0, i] -
                          mixture_model(point - np.eye(2)[i] * 1e-5, beta_true)[0, i]) / 2e-5
                         for i in range(2))
assert abs(divergence_numeric - (mixture_features(point)[2] @ beta_true)[0]) < 1e-8
true_test = mixture_score(mix_test_y, MIX_VAR)
for name, beta in (('implícito', beta_implicit), ('sliced', beta_sliced), ('denoising', beta_dsm)):
    error = float(np.mean(np.sum((mixture_model(mix_test_y, beta) - true_test) ** 2, axis=1)))
    print(f'Mezcla {name}: error cuadrático total de score en test = {error:.6f}')
print(f'Score verdadero de la mezcla frente a diferencias finitas: {mixture_gradient_error:.2e}')

# El mismo conjunto de puntos y ruido para ilustrar el compromiso de dos σ.
eps = np.random.default_rng(1514).normal(size=mix_test_x.shape)
for sigma in (0.15, 0.6):
    y = mix_test_x + sigma * eps
    conditional = -eps / sigma
    smooth = mixture_score(y, BASE_STD ** 2 + sigma ** 2)
    raw = mixture_score(y, BASE_STD ** 2)
    target_energy = float(np.mean(np.sum(conditional ** 2, axis=1)))
    smoothing_difference = float(np.mean(np.sum((smooth - raw) ** 2, axis=1)))
    print(f'σ={sigma:.2f}: E empírica ||score condicional||²={target_energy:.4f}; '
          f'diferencia cuadrática score suavizado/original={smoothing_difference:.4f}')
print('Los coeficientes del modelo usan los parámetros de esta mezcla conocida; en datos reales no se conocen.')

Exercises

ProofEliminating the unknown score
Prove: Prove the implicit form of Fisher distance without the factor one half.
0
Assume positive differentiable p, integrable terms and zero boundary flux of p sθ.

Step 1 of 3. What is the cross term of the square?

ProofConditioning the target
Prove: Prove that the DSM objective and error against the smoothed-density score differ by a constant independent of θ.
0
Write T = ∇_y log qσ(Y | X) and assume differentiation under the integral and expectations are justified.

Step 1 of 3. What is E[T | Y=y]?

ProofPosterior mean from convolution
Prove: Derive Tweedie’s formula for additive Gaussian noise.
0
Let Y = X + σ ε, with independent standard normal ε and positive σ. Justify exchanging derivative and integral.

Step 1 of 3. What is the Gaussian kernel score with respect to y?

NumericA Bayesian correction
X is normal with mean 2 and variance 1. You observe Y = X + ε = 4, with independent standard normal ε. What is E[X | Y=4]?
CodeTwo objectives with autograd
Implement dsm_loss(score_net, x, sigma, noise) and sliced_sm_loss(score_net, x, projections). x and noise have shape [B,D]; projections has shape [K,B,D]. The model acts independently per row. DSM returns mean ½‖s(x+σ·noise)+noise/σ‖². Sliced returns the mean over projections and examples of ½(v·s)² + vᵀJ_s v. Preserve the graph needed to differentiate loss with respect to parameters; do not modify x.
import torch

def dsm_loss(score_net, x, sigma, noise):
  pass

def sliced_sm_loss(score_net, x, projections):
  pass
Shift+Enter to run

The estimated trace uses v⊤Js⊤v=v⊤Jsvv^\top J_s^\top v=v^\top J_s v; JsJ_s need not be symmetric. The test fixes two directions with identity empirical covariance and checks both value and parameter gradient without depending on a statistical approximation.

QuizWhich score is learned
DSM is trained with Gaussian noise of positive standard deviation σ. The family contains the exact minimizer and optimization converges. Which field does the objective identify?

Local lab: 2D scores and Tweedie on MNIST

Train two independent MLPs on a uniform mixture of eight planar Gaussians, with centers on a radius-2 circle and covariance 0,42I0,4^2 I. Sliced score matching learns on original data with one Rademacher projection per example and update. Denoising score matching uses noise standard deviation σ=0,4\sigma=0,4 and learns the smoothed mixture score, whose components have covariance (0,42+σ2)I(0,4^2+\sigma^2)I. Calculate exact scores for both mixtures and measure error on held-out data and points more than 2 units from every center. The MLP field need not be conservative and discretized Langevin sampling does not guarantee reaching a target distribution. Sample counts within 0.8 of each center are a diagnostic, not proof of convergence or quality.

Then train a residual convolutional denoiser on MNIST training images in [0,1][0,1] with Gaussian noise of standard deviation 0.35. Images and predictions remain unclipped during optimization and evaluation; clipping applies only to the PNG. Compare squared errors of noisy input and output against held-out official test images. Weights, 2D samples, history and a grid are saved in ORYON_OUTPUT_DIR. Dependencies are torch, torchvision, numpy and pillow; ORYON_DATA_ROOT controls MNIST location, downloaded if absent.

The independent Tweedie check uses the uniform empirical prior formed by the same denoiser training images, with the same noise. For four held-out queries calculate the mixture posterior mean by Bayes and estimate derivatives of its log-density by finite differences in six pixels. Check that the identity reproduces that mean and measure distance between it and network output. This compares against the empirical-prior optimum, not a proof for MNIST’s unknown distribution. A finite network and finite training do not guarantee reaching that optimum. Comparing against all prototypes requires additional memory and time; training can also run on CPU.

Normal mode uses 5000 updates per 2D score, 60,000 MNIST images and five epochs. For a quick functional check set ORYON_QUICK=1: it uses smaller networks, 24 updates per score, 128 training images and one epoch. In our short run, denoiser MSE on 32 test images was 0.129222 versus 0.121694 for noisy input: it had not yet learned to improve it. The identity for the 128-image prior was checked with maximum error 1.8e-10 on tested pixels; MSE between network and posterior on four held-out queries was 0.176686. These numbers describe only this short check, not full training or a published result.

[ ]Score matching and Tweedie on MNISTLocal GPU
"""Score matching y Tweedie. ORYON_QUICK=1 comprueba el recorrido completo.

ORYON_DATA_ROOT define la caché de torchvision y ORYON_OUTPUT_DIR la salida.
El entrenamiento normal es deliberadamente mayor que la comprobación rápida.
"""
import csv
import math
import os
from pathlib import Path

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image

torch.set_num_threads(2)
SIGMA_2D = 0.4
SIGMA_IMAGE = 0.35


class ScoreMLP(nn.Module):
    def __init__(self, width=128):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(2, width), nn.SiLU(), nn.Linear(width, width),
                                 nn.SiLU(), nn.Linear(width, 2))

    def forward(self, x):
        return self.net(x)


class Denoiser(nn.Module):
    def __init__(self, width=32):
        super().__init__()
        self.net = nn.Sequential(nn.Conv2d(1, width, 3, padding=1), nn.SiLU(),
                                 nn.Conv2d(width, width, 3, padding=1), nn.SiLU(),
                                 nn.Conv2d(width, width, 3, padding=1), nn.SiLU(),
                                 nn.Conv2d(width, 1, 3, padding=1))

    def forward(self, noisy):
        # Sin recorte: la media condicional se estima por MSE, también fuera de [0, 1].
        return noisy + self.net(noisy)


def sliced_loss(net, data, n_projections=1):
    if n_projections < 1:
        raise ValueError('Se necesita al menos una proyección')
    x = data.detach().requires_grad_(True)
    score = net(x)
    terms = []
    for _ in range(n_projections):
        # E[v vᵀ] = I. La traza se estima con una VJP por proyección.
        v = torch.empty_like(x).bernoulli_(0.5).mul_(2).sub_(1)
        jtv = torch.autograd.grad((score * v).sum(), x, create_graph=True, retain_graph=True)[0]
        terms.append((jtv * v).sum(dim=1))
    return (0.5 * score.square().sum(dim=1) + torch.stack(terms).mean(dim=0)).mean()


def dsm_loss(net, data, sigma):
    if sigma <= 0:
        raise ValueError('sigma debe ser positiva')
    epsilon = torch.randn_like(data)
    score = net(data + sigma * epsilon)
    # Equivale a σ² ||s + ε/σ||²: escala bien al cambiar σ.
    return (sigma * score + epsilon).square().sum(dim=1).mean()


def means(device, dtype=torch.float32):
    angle = torch.arange(8, device=device, dtype=dtype) * (2 * math.pi / 8)
    return 2 * torch.stack((torch.cos(angle), torch.sin(angle)), dim=1)


def sample_mixture(n, device, generator):
    components = torch.randint(8, (n,), device=device, generator=generator)
    return means(device)[components] + 0.4 * torch.randn((n, 2), device=device, generator=generator)


def exact_score(x, sigma=0):
    variance = 0.4 ** 2 + sigma ** 2
    delta = means(x.device, x.dtype)[None, :, :] - x[:, None, :]
    probs = torch.softmax(-delta.square().sum(dim=-1) / (2 * variance), dim=1)
    return (probs[..., None] * delta).sum(dim=1) / variance


def langevin(net, initial, n_steps, h, generator):
    if n_steps < 0 or h <= 0:
        raise ValueError('Pasos o tamaño de paso inválidos')
    x = initial.clone()
    with torch.no_grad():
        for _ in range(n_steps):
            x = x + 0.5 * h * net(x) + math.sqrt(h) * torch.randn(
                x.shape, dtype=x.dtype, device=x.device, generator=generator)
            if not torch.isfinite(x).all():
                raise FloatingPointError('Langevin produjo valores no finitos')
    return x


def empirical_logits(query, prototypes, sigma):
    q = np.asarray(query, dtype=np.float64).reshape(-1)
    x = np.asarray(prototypes, dtype=np.float64).reshape(len(prototypes), -1)
    # La expansión evita crear una matriz adicional de diferencias de tamaño N × 784.
    squared = np.einsum('ij,ij->i', x, x) - 2 * (x @ q) + q @ q
    return -squared / (2 * sigma ** 2)


def empirical_posterior_numpy(query, prototypes, sigma):
    """Mezcla empírica con masas iguales: pesos de Bayes, sin usar la red."""
    q = np.asarray(query, dtype=np.float64).reshape(-1)
    x = np.asarray(prototypes, dtype=np.float64).reshape(len(prototypes), -1)
    logits = empirical_logits(q, x, sigma)
    peak = logits.max()
    weights = np.exp(logits - peak)
    weights /= weights.sum()
    return weights @ x, float(peak + np.log(np.exp(logits - peak).sum()) - np.log(len(x)))


def check_tweedie_numpy(query, prototypes, sigma, coordinates, step=1e-4):
    """Diferencias finitas del log de la mezcla, no de la identidad de Tweedie."""
    q = np.asarray(query, dtype=np.float64).reshape(-1).copy()
    posterior, _ = empirical_posterior_numpy(q, prototypes, sigma)
    x = np.asarray(prototypes, dtype=np.float64).reshape(len(prototypes), -1)
    logits = empirical_logits(q, x, sigma)
    def logsum(values):
        peak = values.max()
        return peak + np.log(np.exp(values - peak).sum()) - np.log(len(values))
    errors = []
    for j in coordinates:
        # Se recalcula la log-densidad en q ± h e_j mediante su expansión cuadrática exacta.
        perturb = step * (x[:, j] - q[j]) / sigma ** 2
        common = step ** 2 / (2 * sigma ** 2)
        lp = logsum(logits + perturb - common)
        lm = logsum(logits - perturb - common)
        grad_fd = (lp - lm) / (2 * step)
        errors.append(abs(posterior[j] - (q[j] + sigma ** 2 * grad_fd)))
    return max(errors)


def checks(device):
    torch.manual_seed(1501)
    class Linear(nn.Module):
        def forward(self, x):
            return -x
    x = torch.tensor([[1., 2.], [-1., .5]], device=device)
    # En -I, la traza es -2 para cualquier vector Rademacher.
    actual = sliced_loss(Linear(), x, 2).item()
    expected = (0.5 * x.square().sum(1) - 2).mean().item()
    assert abs(actual - expected) < 1e-6
    pts = torch.tensor([[0.3, -0.7]], device=device, dtype=torch.float64, requires_grad=True)
    delta = pts[:, None, :] - means(device, torch.float64)[None]
    logp = torch.logsumexp(-delta.square().sum(-1) / (2 * .16), dim=1)
    automatic = torch.autograd.grad(logp.sum(), pts)[0]
    assert torch.allclose(automatic, exact_score(pts), atol=1e-10, rtol=1e-10)
    prototypes = np.array([[0., 1., -1.], [1., 0., 1.], [-1., .5, 0.]])
    err = check_tweedie_numpy(np.array([.2, -.1, .4]), prototypes, .7, [0, 1, 2])
    assert err < 1e-7
    print(f'Controles: traza exacta, score de mezcla y Tweedie por diferencias finitas; error máximo {err:.3g}', flush=True)


def train_2d(device, quick, output):
    steps, width, batch = (24, 32, 64) if quick else (5000, 128, 512)
    models = {}
    for method in ('sliced', 'dsm'):
        torch.manual_seed(1510)
        gen = torch.Generator(device=device).manual_seed(1511)
        net = ScoreMLP(width).to(device)
        opt = torch.optim.Adam(net.parameters(), lr=0.001)
        for step in range(steps):
            data = sample_mixture(batch, device, gen)
            loss = sliced_loss(net, data) if method == 'sliced' else dsm_loss(net, data, SIGMA_2D)
            opt.zero_grad(set_to_none=True)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(net.parameters(), 10, error_if_nonfinite=True)
            opt.step()
        print(f'2D {method}: pasos {steps}, última pérdida {loss.item():.6f}', flush=True)
        models[method] = net.eval()
        torch.save({'method': method, 'model': net.state_dict(), 'width': width,
                    'steps': steps, 'sigma': SIGMA_2D if method == 'dsm' else 0}, output / f'{method}.pt')
    eval_gen = torch.Generator(device=device).manual_seed(1512)
    near = sample_mixture(2048, device, eval_gen)
    far = (torch.rand((2048, 2), device=device, generator=eval_gen) * 2 - 1) * 5
    # El score DSM se compara con la densidad suavizada, no con la original.
    with torch.no_grad():
        for method, net in models.items():
            sigma = SIGMA_2D if method == 'dsm' else 0
            data_eval = near + sigma * torch.randn(near.shape, device=device, generator=eval_gen)
            in_error = (net(data_eval) - exact_score(data_eval, sigma)).square().sum(1).mean().item()
            # Región alejada de TODOS los centros: comparación condicional, no promedio global.
            away = far[torch.cdist(far, means(device)).min(dim=1).values > 2]
            far_error = (net(away) - exact_score(away, sigma)).square().sum(1).mean().item()
            starts = torch.randn((512, 2), device=device, generator=eval_gen) * 3
            samples = langevin(net, starts, 100 if quick else 1500, .01, eval_gen)
            np.save(output / f'{method}-samples.npy', samples.cpu().numpy())
            assigned = torch.cdist(samples, means(device)).min(dim=1)
            coverage = torch.bincount(assigned.indices[assigned.values < .8], minlength=8)
            print(f'{method}: MSE score en datos {in_error:.4f}, lejos {far_error:.4f}; '
                  f'cuentas cerca de cada centro {coverage.tolist()}', flush=True)
    print('MSE del score se mide por suma de componentes. La cobertura no prueba convergencia; ULA tiene sesgo de paso.', flush=True)


def train_images(device, quick, output, root):
    raw_train = datasets.MNIST(root, train=True, download=True, transform=transforms.ToTensor())
    raw_test = datasets.MNIST(root, train=False, download=True, transform=transforms.ToTensor())
    ntrain, ntest, width, epochs = (128, 32, 8, 1) if quick else (60000, 10000, 32, 5)
    indices = torch.randperm(len(raw_train), generator=torch.Generator().manual_seed(1520))[:ntrain].tolist()
    train = Subset(raw_train, indices)
    test = Subset(raw_test, range(ntest))
    train_loader = DataLoader(train, batch_size=32 if quick else 128, shuffle=True, num_workers=0,
                              generator=torch.Generator().manual_seed(1521))
    test_loader = DataLoader(test, batch_size=32 if quick else 128, shuffle=False, num_workers=0)
    torch.manual_seed(1522)
    gen = torch.Generator(device=device).manual_seed(1523)
    model = Denoiser(width).to(device)
    opt = torch.optim.Adam(model.parameters(), lr=0.001)
    history = []
    for epoch in range(1, epochs + 1):
        model.train()
        total, count = 0., 0
        for clean, _ in train_loader:
            clean = clean.to(device)
            noisy = clean + SIGMA_IMAGE * torch.randn(clean.shape, device=device, generator=gen)
            loss = (model(noisy) - clean).square().mean()
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
            total += loss.item() * len(clean)
            count += len(clean)
        history.append((epoch, total / count))
        print(f'MNIST época {epoch}: MSE de entrenamiento {total / count:.6f}', flush=True)
    with (output / 'denoiser-history.csv').open('w', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(('epoch', 'mse_train'))
        writer.writerows(history)
    torch.save({'model': model.state_dict(), 'width': width, 'sigma': SIGMA_IMAGE,
                'epochs': epochs, 'quick': quick}, output / 'denoiser.pt')
    model.eval()
    evaluation_gen = torch.Generator(device=device).manual_seed(1524)
    network_total, noisy_total, count = 0., 0., 0
    first = None
    with torch.no_grad():
        for clean, _ in test_loader:
            clean = clean.to(device)
            noisy = clean + SIGMA_IMAGE * torch.randn(clean.shape, device=device, generator=evaluation_gen)
            denoised = model(noisy)
            network_total += (denoised - clean).square().sum().item()
            noisy_total += (noisy - clean).square().sum().item()
            count += clean.numel()
            if first is None:
                first = (clean[:4].cpu(), noisy[:4].cpu(), denoised[:4].cpu())
    print(f'MNIST test: MSE ruidoso {noisy_total/count:.6f}, denoiser {network_total/count:.6f}', flush=True)
    save_image(torch.cat(first).clamp(0, 1), output / 'mnist-clean-noisy-denoised.png', nrow=4)
    # El prior empírico contiene exactamente las imágenes de entrenamiento de la red.
    # Las consultas son test, y el prior no pretende ser la distribución real de MNIST.
    prototype_count = len(train)
    # Igual conversión float32 que ToTensor; se eleva después a float64 para Bayes.
    prototypes = (raw_train.data[indices].reshape(prototype_count, -1)
                  .to(dtype=torch.float32).div_(255).numpy().astype(np.float64))
    clean, noisy, prediction = first
    coords = [0, 100, 250, 400, 600, 783]
    errs, posterior_mse, network_mse, approximation_mse = [], [], [], []
    for i in range(len(noisy)):
        q = noisy[i].numpy().reshape(-1)
        posterior, _ = empirical_posterior_numpy(q, prototypes, SIGMA_IMAGE)
        errs.append(check_tweedie_numpy(q, prototypes, SIGMA_IMAGE, coords))
        posterior_mse.append(np.mean((posterior - clean[i].numpy().reshape(-1)) ** 2))
        network_mse.append(np.mean((prediction[i].numpy().reshape(-1) - clean[i].numpy().reshape(-1)) ** 2))
        approximation_mse.append(np.mean((prediction[i].numpy().reshape(-1) - posterior) ** 2))
    assert max(errs) < 1e-6
    print(f'Tweedie, prior empírico de {prototype_count} imágenes de train y {len(noisy)} consultas test: '
          f'error máximo diferencias finitas {max(errs):.3g}; MSE posterior {np.mean(posterior_mse):.6f}, '
          f'red {np.mean(network_mse):.6f}; MSE red respecto a posterior {np.mean(approximation_mse):.6f}', flush=True)
    print('El posterior usa el prior finito indicado. La red es una aproximación entrenada: no se supone que coincida con ese posterior.', flush=True)


def main():
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    quick = os.environ.get('ORYON_QUICK') == '1'
    output = Path(os.environ.get('ORYON_OUTPUT_DIR', './score-results'))
    output.mkdir(parents=True, exist_ok=True)
    root = os.environ.get('ORYON_DATA_ROOT', './data')
    print(f'dispositivo {device}; verificación corta {quick}', flush=True)
    checks(device)
    train_2d(device, quick, output)
    train_images(device, quick, output, root)
    if device.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

The score removes a multiplicative constant when differentiating with respect to data. The implicit objective replaces an unknown score with divergence under boundary conditions; DSM learns a smoothed-distribution score and Tweedie connects that field to a posterior mean.