Score Matching & Score-Based Generative Models

Learn the score, the gradient of log p(x), without the normalizing constant. Denoising score matching turns this into regression on the added noise, which is how diffusion models are trained.

Advanced · Graduate mathematics · about 21 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

If a probability distribution p(x)p(x) is a landscape, then log⁡p(x)\log p(x) is a height map, and the score

s(x)=∇xlog⁡p(x)s(x)=\nabla_x \log p(x)

is the vector field that points "uphill" toward higher density.

Score-based generative modeling is the idea: instead of learning p(x)p(x) directly (which requires a normalizing constant), learn the gradient of the log-density. Song and Ermon (2019) learned the score at many noise levels and sampled with Langevin dynamics, moving from coarse to fine noise; Song et al. (2021) cast the same idea as reversing a stochastic differential equation. Either way, estimated scores move points from noise toward data-like samples.

In Gaussian-noising diffusion parameterizations, predicting noise ϵ\epsilon at each noise level is often equivalent, up to a known scale, to estimating a score.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

The score function and score matching

For a non-normalized model pθ(x)=qθ(x)/Z(θ)p_\theta(x)=q_\theta(x)/Z(\theta), the data-gradient score ignores the constant Z(θ)Z(\theta):

sθ(x)=∇xlog⁡pθ(x)=∇xlog⁡qθ(x),LSM=Epdata[12∥sθ(x)∥2+tr(∇xsθ(x))].\begin{aligned} s_\theta(x) &=\nabla_x\log p_\theta(x) = \nabla_x\log q_\theta(x),\\ \mathcal{L}_{SM} &=\mathbb{E}_{p_{\text{data}}}\left[ \frac{1}{2}\|s_\theta(x)\|^2+\mathrm{tr}(\nabla_x s_\theta(x)) \right]. \end{aligned}

Hyvärinen (2005) showed that this objective, which needs only the model's score and its derivatives, has the same minimizer as matching the unknown data score. It avoids the normalizing constant, but the trace term needs every diagonal entry of the Jacobian of sθs_\theta, which costs about one backward pass per input dimension for a neural network.

Denoising score matching (diffusion-friendly)

Add Gaussian noise. The conditional target, noise-prediction scale, and reverse-time dynamics share the same learned score field:

x~=x+σϵ,ϵ∼N(0,I),∇x~log⁡qσ(x~∣x)=−x~−xσ2=−ϵσ,sθ(x~,σ)≈−ϵθ(x~,σ)σ,dxrev=[f(x,t)−g(t)2sθ(x,t)]dt+g(t)dwˉ,dxflow=[f(x,t)−12g(t)2sθ(x,t)]dt.\begin{aligned} \tilde x &= x+\sigma\epsilon,\qquad \epsilon\sim\mathcal{N}(0,I),\\ \nabla_{\tilde x}\log q_\sigma(\tilde x\mid x) &=-\frac{\tilde x-x}{\sigma^2}=-\frac{\epsilon}{\sigma},\\ s_\theta(\tilde x,\sigma)&\approx -\frac{\epsilon_\theta(\tilde x,\sigma)}{\sigma},\\ dx_{\text{rev}} &=\left[f(x,t)-g(t)^2s_\theta(x,t)\right]dt+g(t)d\bar w,\\ dx_{\text{flow}} &=\left[f(x,t)-\tfrac{1}{2}g(t)^2s_\theta(x,t)\right]dt. \end{aligned}

Denoising score matching trains:

LDSM=E ∥sθ(x~,σ)+ϵ/σ∥2.\mathcal{L}_{DSM}=\mathbb E\,\big\|s_\theta(\tilde x,\sigma) + \epsilon/\sigma\big\|^2.

So predicting noise ϵθ\epsilon_\theta is equivalent (up to scaling) to predicting the score:

sθ(x~,σ)≈−ϵθ(x~,σ)σ.s_\theta(\tilde x,\sigma) \approx -\frac{\epsilon_\theta(\tilde x,\sigma)}{\sigma}.

In the reverse-time equations, the forward noising process is dx=f(x,t) dt+g(t) dwdx=f(x,t)\,dt+g(t)\,dw, wˉ\bar w is a Brownian motion run backwards in time, and dtdt is negative when integrating from t=Tt=T down to 00 (Song et al., 2021). The first is a stochastic sampler; the second, the probability-flow ODE, is deterministic and has the same marginal distributions at every tt.

The conditional DSM target ∇x~log⁡q(x~∣x)\nabla_{\tilde x}\log q(\tilde x\mid x) is the label for one known clean source; the marginal score field ∇x~log⁡pσ(x~)\nabla_{\tilde x}\log p_\sigma(\tilde x) averages over possible clean sources. Regression closes that gap. At each x~\tilde x the DSM loss is minimized by the average label, and that average is exactly the marginal score:

∇x~log⁡pσ(x~)=E[x∣x~]−x~σ2.\nabla_{\tilde x}\log p_\sigma(\tilde x)=\frac{\mathbb E[x\mid\tilde x]-\tilde x}{\sigma^2}.

This is Tweedie's formula (Efron, 2011). It is why training on noisy copies of known clean points (Vincent, 2011) recovers the score of the noisy data distribution, and why an optimal denoiser, which outputs E[x∣x~]\mathbb E[x\mid\tilde x], determines the score.

A one-dimensional check: explicit and implicit objectives

Take data X∼N(0,v)X\sim\mathcal N(0,v), where vv is the variance, and the unnormalized model qθ(x)=exp⁡(−θx2/2)q_\theta(x)=\exp(-\theta x^2/2) with θ>0\theta>0. Its normalizing constant Z(θ)=2π/θZ(\theta)=\sqrt{2\pi/\theta} drops out of the score, sθ(x)=−θxs_\theta(x)=-\theta x, while the data score is s∗(x)=−x/vs_*(x)=-x/v. Index both objectives by the variance:

Jv(θ)=12 E[(sθ(X)−s∗(X))2]=v2(θ−1v)2,Lv(θ)=E[12sθ(X)2+∂xsθ(X)]=v2θ2−θ.J_v(\theta)=\tfrac12\,\mathbb E\big[(s_\theta(X)-s_*(X))^2\big]=\frac v2\Big(\theta-\frac1v\Big)^2,\qquad L_v(\theta)=\mathbb E\Big[\tfrac12 s_\theta(X)^2+\partial_x s_\theta(X)\Big]=\frac v2\theta^2-\theta.

JvJ_v is half the Fisher divergence and needs the unknown data score; LvL_v is the objective LSM\mathcal L_{SM} above, which needs only the model. Expanding the square in JvJ_v leaves one term with s∗s_*, and integration by parts removes it: −E[sθs∗]=−∫sθ p∗′ dx=E[∂xsθ]-\mathbb E[s_\theta s_*]=-\int s_\theta\,p_*'\,dx=\mathbb E[\partial_x s_\theta], provided p∗(x)sθ(x)→0p_*(x)s_\theta(x)\to0 as ∣x∣→∞|x|\to\infty, as it does here (Hyvärinen, 2005). What is left over is a constant that depends on the data but not on θ\theta:

Jv(θ)−Lv(θ)=12 E[s∗(X)2]=12v.J_v(\theta)-L_v(\theta)=\tfrac12\,\mathbb E\big[s_*(X)^2\big]=\frac1{2v}.

Both objectives are minimized at θ=1/v\theta=1/v, where the model matches the data. There Jv=0J_v=0 but Lv=−1/(2v)L_v=-1/(2v): the implicit objective can be negative, and its value is not a distance. The two share a minimizer, not their values.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

rng = np.random.default_rng(0)
x = rng.normal(loc=1.5, scale=1.0, size=(5,))
sigma = 0.7
eps = rng.standard_normal(x.shape)
xt = x + sigma * eps

score_from_eps = -eps / sigma
score_from_xt = -(xt - x) / (sigma**2)  # same quantity

print("x:  ", np.round(x, 3))
print("xt: ", np.round(xt, 3))
print("max|diff|:", float(np.max(np.abs(score_from_eps - score_from_xt))))

The second block checks the one-dimensional identity by quadrature, for two data variances and three models: Jv−LvJ_v-L_v is 1/(2v)1/(2v) every time, and LvL_v is negative at the minimizer θ=1/v\theta=1/v.

import numpy as np

def objectives(v, theta, n=200_001):
    # Expectations over X ~ N(0, v) by quadrature on a wide grid
    x = np.linspace(-12 * np.sqrt(v), 12 * np.sqrt(v), n)
    p = np.exp(-x**2 / (2 * v)) / np.sqrt(2 * np.pi * v)
    s_model, s_data = -theta * x, -x / v
    J = np.trapezoid(0.5 * (s_model - s_data) ** 2 * p, x)   # needs the data score
    L = np.trapezoid((0.5 * s_model**2 - theta) * p, x)      # the model alone: d/dx s_model = -theta
    return J, L

for v in (0.5, 3.0):
    for theta in (0.2, 1 / v, 1.5):
        J, L = objectives(v, theta)
        print(f"v={v}, theta={theta:.3f}: J={J:.6f}  L={L:+.6f}  J-L={J - L:.6f}  1/(2v)={1 / (2 * v):.6f}")
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Score Matching & Score-Based Generative Models

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Score Matching & Score-Based Generative Models, then open its guide.

Use the demo to see the score field and how diffusion's noise prediction corresponds to a scaled score estimate.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Practice

For Gaussian data and a one-parameter model, compute the explicit and implicit score-matching objectives and see that they share a minimizer but not their values. Then change the data variance.

Loading the exercise…
In focus

Concept: Score Matching & Score-Based Generative Models

What is the smallest example of Score Matching & Score-Based Generative Models you can work through by hand, and what does it show?

BeforeMaximum LikelihoodNextFlow Matching & Rectified Flows
DetailsGenerative Models

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

Learn the score, the gradient of log p(x), without the normalizing constant. Denoising score matching turns this into regression on the added noise, which is how diffusion models are trained.

Choose what to look for (no demo yet)01 / Intuition
Illustration of noisy samples and score-vector fields pointing back toward high-density structure.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Score Matching & Score-Based Generative Models.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

Learn the score, the gradient of log p(x), without the normalizing constant. Denoising score matching turns this into regression on the added noise, which is how diffusion models are trained.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Score Matching & Score-Based Generative Models.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2005Estimation of Non-Normalized Statistical Models by Score MatchingHyvärinen
Why it is cited

Introduces score matching for models whose normalizing constant is intractable, with an objective that needs only the model's score and its derivatives (Journal of Machine Learning Research, 2005).

Open source
paper · 2011A Connection Between Score Matching and Denoising AutoencodersVincent
Why it is cited

Shows that regressing on the score of a Gaussian corruption of known clean points (denoising score matching) is equivalent to score matching on the noisy data distribution (Neural Computation, 2011; DOI 10.1162/NECO_a_00142).

Open source
paper · 2019Generative Modeling by Estimating Gradients of the Data DistributionSong and Ermon
Why it is cited

Learns the data score at many noise levels with denoising score matching and samples with annealed Langevin dynamics (NeurIPS 2019).

Open source
paper · 2021Score-Based Generative Modeling through Stochastic Differential EquationsSong et al.
Why it is cited

Connects learned time-dependent scores to the reverse-time SDE and the probability-flow ODE used for sampling (ICLR 2021).

Open source
paper · 2011Tweedie's Formula and Selection BiasEfron
Why it is cited

States Tweedie's formula: for Gaussian noise, the posterior mean of the clean value equals the observation plus the noise variance times the score of the observed density (Journal of the American Statistical Association, 2011).

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

Learn the score, the gradient of log p(x), without the normalizing constant. Denoising score matching turns this into regression on the added noise, which is how diffusion models are trained.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Score matching fits a model score grad_x log p_theta(x) while avoiding the normalizing constant; under Gaussian corruption x_tilde=x+sigma epsilon, the conditional denoising target is -(x_tilde-x)/sigma^2=-epsilon/sigma; estimated time-dependent scores can drive reverse-time SDE/ODE sampling dynamics.
What the sources support

Hyvärinen supports score matching for continuous non-normalized models because the data score removes Z(theta). Vincent supports the Gaussian DSM target (x-x_tilde)/sigma^2 and its equivalence to score match...

Where to see it on this page
Equation 1
sθ(x)=∇xlog⁡pθ(x)=∇xlog⁡qθ(x),LSM=Epdata[12∥sθ(x)∥2+tr(∇xsθ(x))].\begin{aligned} s_\theta(x) &=\nabla_x\log p_\theta(x) = \nabla_x\log q_\theta(x),\\ \mathcal{L}_{SM} &=\mathbb{E}_{p_{\text{data}}}\left[ \frac{1}{2}\|s_\theta(x)\|^2+\mathrm{tr}(\nabla_x s_\theta(x)) \right]. \end{aligned}
Equation 2
x~=x+σϵ,ϵ∼N(0,I),∇x~log⁡qσ(x~∣x)=−x~−xσ2=−ϵσ,sθ(x~,σ)≈−ϵθ(x~,σ)σ,dxrev=[f(x,t)−g(t)2sθ(x,t)]dt+g(t)dwˉ,dxflow=[f(x,t)−12g(t)2sθ(x,t)]dt.\begin{aligned} \tilde x &= x+\sigma\epsilon,\qquad \epsilon\sim\mathcal{N}(0,I),\\ \nabla_{\tilde x}\log q_\sigma(\tilde x\mid x) &=-\frac{\tilde x-x}{\sigma^2}=-\frac{\epsilon}{\sigma},\\ s_\theta(\tilde x,\sigma)&\approx -\frac{\epsilon_\theta(\tilde x,\sigma)}{\sigma},\\ dx_{\text{rev}} &=\left[f(x,t)-g(t)^2s_\theta(x,t)\right]dt+g(t)d\bar w,\\ dx_{\text{flow}} &=\left[f(x,t)-\tfrac{1}{2}g(t)^2s_\theta(x,t)\right]dt. \end{aligned}
Caveat

A conditional DSM label is not the marginal score; only its average over clean sources is. The page does not run a solver, train a high-dimensional model or measure sample quality, and it does not cover full...

StatusChecked against the cited passages.

Hyvärinen supports score matching for non-normalized models: the score, a data gradient, does not involve Z(theta), and the implicit objective uses squared-score and divergence terms. Vincent supports the Gaussian conditional denoising target (x-x_tilde)/sigma^2 = -epsilon/sigma and its equivalence to score matching. Song et al. support estimated time-dependent scores in reverse-SDE sampling and probability-flow ODEs. The page's equations, code and demo follow these steps; the target appears only after you predict.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Score Matching & Score-Based Generative Models

Try the idea in your own words

Learn the score, the gradient of log p(x), without the normalizing constant. Denoising score matching turns this into regression on the added noise, which is how diffusion models are trained.

Concept · Selected for practice

Score Matching & Score-Based Generative Models

What it rests on: Sources: Estimation of Non-Normalized Statistical Models by Score Matching; A Connection Between Score Matching and Denoising Autoencoders; Generat...

Context and links
Choose a task

Explain the mechanism

For Score Matching & Score-Based Generative Models: What is the smallest example of Score Matching & Score-Based Generative Models you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptScore Matching & Score-Based Generative ModelsSources: Estimation of Non-Normalized Statistical Models by Score Matching; A Connection Between Score Matching and Denoising Autoencoders; Generat...rng = np.random.default_rng(0)

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptGenerative Models

    Score Matching & Score-Based Generative Models

    Starting question

    What is the smallest example of Score Matching & Score-Based Generative Models you can work through by hand, and what does it show?

    SourcesCheck the 5 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Score Matching & Score-Based Generative Models" feel predictable rather than familiar.
    Assumption

    The 5 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 5 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 5 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/generative-models/score-matching concept:generative-models/score-matching