A score-based model learns an arrow for every point in space. The arrow points towards where real data is more likely. Follow the arrows, with a little random shaking, and you walk from noise to a realistic sample. This lesson builds that idea from scratch. Part 2 then grows it into the stochastic differential equations behind diffusion.
This lesson has two parts. Part 1 (the score, Langevin dynamics, denoising score matching, annealing and a runnable cell) stands alone. Part 2 (the SDE view and the probability-flow ODE) is advanced and self-contained, so you can read it later.
Words you need8 terms
A number for each point that says how likely data is there. High density means data lives there.
The arrow at each point that points toward higher density. It is the gradient of log p(x).
Walking along the score arrows while adding a small random kick at each step. It produces samples.
How much random noise was added to the data. Large σ smears the data. Small σ keeps it sharp.
Training a network to point from a noisy sample back to its clean one. The target is known exactly, so training is easy.
Sampling from high noise down to low noise in stages, like going from a blurry picture to a sharp one.
A rule for how a point moves under a steady push plus random kicks. Part 2 uses it to describe noising.
A noise-free path that gives the same overall result as the SDE. Part 2 shows why.
After this lesson, you will be able to:
Define the score function ∇_x log p(x) and explain why knowing the score is enough to sample from the distribution — even when you can't compute p(x) directly
Use Langevin dynamics to walk noisy gradient steps toward high-density regions, and recognize why a single noise level fails on real-world data
Train a noise-conditioned score network with denoising score matching, then sample with annealed Langevin from high noise down to low noise
Connect score-based models to diffusion (DDPM) and flow matching through the SDE framework — they are different parameterizations of the same underlying idea
Picture a hilly map where the height at each spot says how likely real data is there. The scoreScore MatchingScore matching trains a model to estimate the gradient of the data distribution's log-probability, guiding the reverse diffusion process.Learn more is a small arrow on every spot that points uphill. Langevin dynamicsLangevin DynamicsLangevin dynamics draws samples by repeatedly stepping along the score (the gradient of the log density) and adding a small amount of Gaussian noise.Learn more walks along those arrows while adding a little random shaking, and the walker ends up where data lives.
Change the noise level and watch how far the score arrows can see, then follow them with a crowd of walkers.
Loading visualization...
Do: Slide the noise level from 0.00 up to 0.40, then press Run Langevin once with One noise level and once with Annealed.
Notice: At tiny noise the arrows exist only near the two bumps. At large noise they fill the square and point to the middle. One large level leaves most of the 200 walkers outside the bumps, while the annealed run ends inside them, split close to 70 to 30.
Why: The arrows are blind far from data, and noise lets them see farther, so the run starts with big noise and shrinks it, like hearing a song as a beat, then notes. Drawn stand-in, not a trained model: the arrows are exact for a known two-bump density.
The score function is defined as:
sθ(x)=∇xlogp(x)
Why the gradient and not the density? Computing p(x) directly requires the partition function Z = ∫ exp(-E(x)) dx — the normalizing constant that makes p(x) integrate to 1. In high dimensions, Z is intractable. But when you take the gradient of log p(x), Z disappears (it is a constant in x). The score is partition-function-free.
If you know the score, how do you turn it into samples? The answer comes from physics: Langevin dynamics, originally a model of molecular motion in fluids. The discrete update rule is:
xt+1=xt+2η∇xlogp(xt)+ηzt,zt∼N(0,I)
The factors eta/2 and sqrt(eta) in this update are derived in the Math-track lesson "Stochastic Calculus & SDEs (Advanced)" (there the step is called epsilon). It is derived in that lesson, so we do not repeat it here.
This is beautiful in theory, but on real data it fails for one critical reason: the score is unreliable in low-density regions. Most of high-dimensional space is empty (the manifold hypothesis). In those empty regions, the training data gives the network almost no signal about where to go. Langevin starting from random noise wanders aimlessly because the score it sees is junk.
The fix: add noise to the data and train the score network on noisy versions across many noise levels.
Vincent (2011) showed an elegant trick: if you take a clean data point x, perturb it with Gaussian noise to get x̃ = x + σz, then the score of the perturbed distribution has a closed form:
∇x~logpσ(x~∣x)=−σ2x~−x
This conditional score, and the fact that regressing on it learns the score of the noisy data, are derived in the Math-track lesson "Noise, Scores & Diffusion Models".
The denoising score matching loss is then:
LDSM(θ)=Ex,σ,ϵ[λ(σ)sθ(x+σϵ,σ)−σ−ϵ2]
The crucial detail: train on multiple noise levels σ, from large (σ_max ≈ 50) down to tiny (σ_min ≈ 0.01). This is the noise-conditional score network (NCSN) of Song & Ermon 2019. The network learns the score of progressively noisier versions of the data, giving it dense supervision across the entire input space — even in regions far from the data manifold, where high noise reaches.
Now to sample. Start from pure noise. Run Langevin dynamics conditioned on σ_max for a few steps. Then drop to a smaller σ. Run more Langevin steps. Keep dropping σ until you reach σ_min. By the end, the samples have moved from "noise" through "blurry data" to "sharp data."
What Do You Think?
You train a score network with denoising score matching but only on a single noise level σ=0.1. You then try to sample with annealed Langevin from σ=10 down to σ=0.01. What goes wrong?
The right answer is the second option. The whole point of NCSN is that the score network needs to know what to do at every noise level the sampler will encounter. If you trained only at σ=0.1, the σ=10 forward pass is wildly out-of-distribution; the score outputs are garbage and Langevin walks off into nowhere. You must train across the same noise schedule the sampler uses.
Annealed Langevin: for σi∈[σmax,…,σmin]:ηi=ϵ⋅(σi/σmin)2
The cell below runs in your browser: it is a numpy-only twin with a small hand-written network. The PyTorch original that follows does not run here, so copy it to Colab if you want a GPU and a bigger network.
pythonplayground.py · Pyodide
This exercise calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
Tests: The four target modes should each receive a roughly equal share of samples (around 100 of 400), and the mean distance to the nearest mode should be close to the data's own 0.38. If one mode hogs everything, the sampler step size is too small. If samples are scattered, the score network has not learned the modes.
Copy to Colab: the PyTorch version. This block is for reading and for Colab. It is not a runnable cell on this site.
PythonRunnable cell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Score-based generative modeling on a 2D mixture of Gaussians
import torch
import torch.nn as nn
import math
torch.manual_seed(0)
# --- Generate target distribution: mixture of 4 Gaussians ---
def sample_target(n):
centers = torch.tensor([[2., 2.], [-2., 2.], [2., -2.], [-2., -2.]])
idx = torch.randint(0, 4, (n,))
return centers[idx] + 0.3 * torch.randn(n, 2)
# --- A tiny noise-conditioned score network ---
class ScoreNet(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(3, 64), nn.SiLU(),
nn.Linear(64, 64), nn.SiLU(),
nn.Linear(64, 2),
)
def forward(self, x, sigma):
# Concatenate sigma as an extra feature
s = sigma.view(-1, 1) if sigma.dim() == 1 else sigma
inp = torch.cat([x, s.expand(x.shape[0], 1)], dim=1)
return self.net(inp) / sigma.view(-1, 1) # scale by 1/sigma is a common trick
# --- Train with denoising score matching across many noise levels ---
score_net = ScoreNet()
opt = torch.optim.Adam(score_net.parameters(), lr=2e-3)
# Geometric schedule of noise levels: from sigma_max=5.0 to sigma_min=0.05
L = 10
sigmas = torch.tensor([5.0 * (0.05 / 5.0) ** (i / (L-1)) for i in range(L)])
print(f"Training across {L} noise levels: {[f'{s:.2f}' for s in sigmas]}")
for step in range(2000):
x = sample_target(256)
# Pick a random noise level for each sample
idx = torch.randint(0, L, (x.shape[0],))
sigma = sigmas[idx]
eps = torch.randn_like(x)
x_tilde = x + sigma.view(-1, 1) * eps
target = -eps / sigma.view(-1, 1)
pred = score_net(x_tilde, sigma)
loss = ((pred - target) ** 2 * (sigma ** 2).view(-1, 1)).mean()
opt.zero_grad(); loss.backward(); opt.step()
if step % 500 == 0:
print(f"step {step:4d} loss {loss.item():.3f}")
# --- Annealed Langevin sampling ---
@torch.no_grad()
def sample(n=400, T=100, eps=2e-5):
x = torch.randn(n, 2) * sigmas[0]
for sigma in sigmas:
step_size = eps * (sigma / sigmas[-1]) ** 2
for _ in range(T):
score = score_net(x, sigma * torch.ones(n))
x = x + (step_size / 2) * score + (step_size.sqrt()) * torch.randn_like(x)
return x
samples = sample()
print()
print(f"Sampled {samples.shape[0]} points.")
print(f"Mean of generated samples: ({samples[:,0].mean():.2f}, {samples[:,1].mean():.2f})")
print(f"Cluster check: How many fell near each of the 4 target modes?")
centers = torch.tensor([[2., 2.], [-2., 2.], [2., -2.], [-2., -2.]])
dists = torch.cdist(samples, centers)
nearest = dists.argmin(dim=1)
for c in range(4):
cx, cy = centers[c]
count = (nearest == c).sum().item()
print(f" ({cx:+.0f}, {cy:+.0f}): {count} samples")
print()
print("CHALLENGE: Try training on a SINGLE noise level (e.g. sigma=0.1 only).")
print("Then sample with the same annealed schedule.")
print("Watch the samples diverge or stay stuck near the origin.")
Part 2 starts here: the SDE view and the probability-flow ODE. Part 1 above is complete without it. Part 2 is advanced and self-contained. It builds on stochastic calculus, and every derivation is collapsed so you can read the results first.
Picture a drop of ink in a glass of water. The ink spreads until the whole glass is one colour. The forward SDE is that spreading, applied to data: it destroys the picture a little at a time. The reverse SDE undoes it. At each point it needs one extra piece of information, the score, and that is what the network learns.
The 2021 paper of Song et al. made the leap: instead of discrete noise levels, treat the noise schedule as a continuous time variable t ∈ [0, T] and model the corruption as a stochastic differential equation (SDE) — see the math-track lesson on stochastic calculus and SDEsStochastic CalculusStochastic calculus extends derivatives to random processes — Brownian motion, Itô integrals, and stochastic differential equations. The math diffusion models, flow matching, and score-based generative models all live in.Learn more for the Brownian-motion and Itô machinery this rests on:
This is the punchline: DDPM, NCSN, and continuous-time diffusion are instances of one framework, written in different parameterizations. DDPM predicts the noise ε; the score view predicts ∇log p, which equals −ε/σ_t. The factor 1/σ_t changes with the noise level, so it is not a constant. Once you grasp this, every diffusion paper becomes readable.
The SDE view also unlocks the probability flow ODE — a deterministic counterpart to the reverse SDE that gives the same marginal distributions but is easier to integrate with adaptive solvers. This is what enables fast samplers like DDIM and DPM-Solver that can produce high-quality samples in 10-50 steps instead of 1000.
The section above stated the forward SDE, the reverse SDE and the probability-flow ODE. This section shows where they come from. The forward process is chosen by us. The reverse process is derived: it follows from the Fokker–Planck equation and a 1982 result of Brian Anderson. Each derivation sits in a collapsed block and the results stay in the main text. The math-track lesson on stochastic calculus and SDEsStochastic CalculusStochastic calculus extends derivatives to random processes — Brownian motion, Itô integrals, and stochastic differential equations. The math diffusion models, flow matching, and score-based generative models all live in.Learn more covers the Brownian motion and Itô formula we rely on.
A stochastic differential equation in our setting has the general form:
dx=f(x,t)dt+g(t)dw,t∈[0,T]
Score-based literature uses two canonical choices for f and g:
Variance-Exploding (VE) SDE. Set f(x, t) = 0 and g(t) = σ(t) · √(2 log(σ_max / σ_min)), where σ(t) = σ_min · (σ_max / σ_min)^t. There is no drift, so the SDE is pure noise injection. The marginal variance grows unboundedly with t: the marginal at time t is N(x_0, (σ²(t) − σ_min²) I), which is about σ²(t) I once σ(t) is well above σ_min. This is the continuous-time limit of the NCSN noise schedule. The derivation below shows where g and the variance come from.
Variance-Preserving (VP) SDE / DDPM. Set f(x, t) = -½ β(t) x and g(t) = √β(t) for some noise schedule β(t) > 0. The drift pulls x toward the origin while the diffusion injects noise; the two balance so that the marginal variance stays bounded. A first-order Euler–Maruyama step of this SDE matches DDPM (Ho et al. 2020) to first order in β. If you sample t = 1, 2, …, N instead of continuous t, you get the discrete forward chain x_n = √(1 - β_n) x_{n-1} + √β_n ε.
What Do You Think?
You train two diffusion models — one on the VE SDE (no drift, exploding variance), one on the VP SDE (drift pulls toward zero, bounded variance). You inspect the marginal p_T at the final time T. What do you see?
Every SDE induces a partial differential equation that governs how its marginal density p_t(x) evolves over time. For the forward SDE above, the marginal satisfies the Fokker–Planck equation (also called the Kolmogorov forward equation):
∂t∂pt(x)=−∇x⋅[f(x,t)pt(x)]+21g(t)2∇x2pt(x)
The Fokker–Planck equation is derived in the Math-track lesson "Stochastic Calculus & SDEs (Advanced)": apply Itô's formula to a test function, take the expectation, and integrate by parts. We use it here as a known result.
In 1982, Brian D. O. Anderson ("Reverse-time diffusion equation models", Stochastic Processes and their Applications 12) proved a remarkable theorem: any diffusion process with smooth marginals has a time-reversed counterpart that is also a diffusion process, and the reversed drift is determined by the score of the marginal density. Concretely, if x_t solves the forward SDE above with marginal p_t, then the time-reversed process satisfies:
dx=[f(x,t)−g(t)2∇xlogpt(x)]dt+g(t)dwˉ
The reverse SDE is derived step by step in the Math-track lesson "Stochastic Calculus & SDEs (Advanced)": flip one small forward step with Bayes' rule, and the score appears with the factor g squared. The fully rigorous proof needs care with the reverse Wiener process; see Anderson 1982 or Haussmann and Pardoux (1986). Yang Song et al. 2021 ("Score-Based Generative Modeling through SDEs", ICLR) rediscovered this for the generative-modeling community and showed that the score ∇log p_t is the only missing ingredient.
The reverse SDE is stochastic — every reverse trajectory is different. There is a beautiful deterministic alternative that shares the same marginal at every t. Start again from Fokker–Planck and write the diffusion term as a divergence in a different way:
dtdx=f(x,t)−21g(t)2∇xlogpt(x)
The derivation shows that the ODE with velocity v(x,t) = f(x,t) − ½ g(t)² ∇log p_t(x) produces the same marginals p_t as the SDE, with no randomness: same marginals, different sample paths.
Deterministic generation. Fix the initial noise; you always get the same image. Useful for editing, interpolation between samples, and reproducibility.
Exact log-likelihoods. Because it is an ODE, you can apply the instantaneous change-of-variables formula (Chen et al. 2018, Neural ODEs) to compute log p_0(x_0) from log p_T(x_T) and the divergence of the velocity field integrated along the trajectory. SDE-based diffusion only gives a variational lower bound; the probability-flow ODE gives the exact number.
Faster sampling. Off-the-shelf high-order ODE solvers (Heun, RK45, DPM-Solver, DEIS, UniPC) can hit comparable sample quality in 10–50 steps that the SDE needs 1000 to match. DPM-Solver (Lu et al. 2022) and DEIS (Zhang & Chen 2022) are specifically designed exponential-integrator solvers for this ODE.
The exact likelihood in item 2 deserves its own derivation: along the ODE, the log-density changes at a rate set by the divergence of the velocity field.
Everything in the reverse SDE and the probability-flow ODE is known except one quantity: the time-conditioned score ∇_x log p_t(x). Train a network s_θ(x, t) to approximate it. The objective is denoising score matching (Vincent 2011, building on Hyvärinen 2005):
The trick is that the conditional score ∇log q(x_t | x_0) has a closed form whenever q(x_t | x_0) is Gaussian, which it is for both VE and VP. So the regression target is computable in one line, even though the marginal score ∇log p_t(x_t) is intractable. Vincent's theorem says the minimizer of this loss is exactly the marginal score we want.
The weight λ is a design choice. NCSN uses λ(σ) = σ², which evens out the loss across noise levels. The weight that turns the loss into a bound on maximum likelihood is λ(t) = g(t)², in score space.
#Another route to the score: sliced score matching
Hyvärinen's objective (derived in "Noise, Scores & Diffusion Models") needs the trace of the network's d-by-d Jacobian, which costs d backward passes. Sliced score matching compares the score only along a random direction, and the same integration by parts removes the unknown score again.
A predictor-corrector sampler alternates a predictor (one step of the reverse SDE, from t to a slightly smaller t) with a corrector (a few Langevin steps at the new time, using the same score network). The corrector needs a step size; Song et al. choose it from a target signal-to-noise ratio.
How many steps does a sampler need? That depends on how fast its error shrinks as the step h shrinks. Karras et al. (2022) use the second-order Heun method for the probability-flow ODE, and the two derivations below show why a higher order pays off.
That's the whole framework. Forward SDE = choice of corruption process. Fokker–Planck = how the marginal evolves. Anderson 1982 = reverse-time SDE exists, and the score is its only unknown. Probability-flow ODE = deterministic sibling, same marginals, exact likelihoods. Denoising score matching = how to train the network without ever touching p_t directly.
The score is the gradient of the log-density. A vector field that points uphill on the data distribution. Knowing the score is enough to sample from p(x) without ever computing p(x) directly, because the partition function vanishes after taking the gradient.
Langevin dynamics turns the score into samples. Noisy gradient ascent: walk in the direction of the score, add Gaussian noise to avoid getting stuck, and after many steps the trajectory follows p(x). Single-noise-level Langevin fails on real data because the score is unreliable in low-density regions.
Denoising score matching gives you a tractable training target. The conditional score of x̃ = x + σε has the closed form -(x̃-x)/σ². Train a noise-conditional score network on this regression target across many σ, and you get a network that knows the score of the noisy data at every level.
Annealed Langevin samples from coarse to fine. Start from pure noise. Run Langevin at σ_max for a few steps. Drop σ. Repeat. By the end, samples have moved from noise through blurry to sharp data. Step size scales with σ².
Score-based ≡ diffusion. DDPM (predict the noise) and NCSN (predict the score) are related by a noise-level-dependent factor (−1/σ_t) and are the same model class under the SDE framework. The reverse SDE is denoising; the only thing it needs is the score; that is what every modern diffusion model is.
Why does the score function avoid the partition function Z, the integral of the unnormalised density p̃(x)?
Where to next. Read Normalizing Flows to see the other way to get exact likelihoods, then Flow Matching, which replaces the score with a velocity along straight paths. For the practical sampler built on this lesson, see Diffusion Models.
An architecture diagram: boxes are components, arrows show the direction data flows, and moving dots mark the live flow.
Architecture diagram "Annealed sampling, from noise to sample" with 5 components (Pure noise at the largest σ, Score network at this σ, Small step uphill plus a shake, Lower σ one notch, Sample at the smallest σ) joined by 5 arrows showing how data flows between them.