Lesson 5.4 — Score-based Generative Models
Previous lesson · 5.3 Denoising Diffusion Probabilistic Models · Course overview · Next lesson · 5.5 Flow Matching
Density and the Score Vector Field
A noisy state is one realization of a random system. Its time-indexed density describes the whole population. The score is the gradient of that log-density with respect to the data coordinates at a fixed time.

This is the same noisy population as the two-source example in Lesson 5.3. Read vertically through the midpoint. The density above is low, but the slope below is zero. The two sources pull equally in opposite directions. A peak also has zero slope. The neighboring arrows tell them apart. Near the valley they point away from its center. Near a peak they point toward it.
This matters for generation. Repeated uphill steps alone would collect points at the peaks and empty the shoulders of the distribution. Langevin sampling also injects noise, which spreads particles while the score draws them uphill. Later in this lesson the probability-flow ODE uses a time-dependent velocity to transport an entire distribution.
A density's normalizing constant disappears under this derivative. The score points locally toward increasing log-density. Follow it without random motion and points can concentrate at stationary points instead of preserving the target distribution's spread.
In a Gaussian mixture, each component contributes a direction weighted by its posterior responsibility given the current point. Responsibilities can be computed by normalizing the component log-densities using log-sum-exp. Between symmetric modes, directions can cancel even in low-density regions.
Inspect the same cancellation in a two-dimensional mixture
Density & Score Vector Field
Denoising Score Matching
Classical score matching uses integration by parts to replace the unknown density gradient in the loss. The identity requires differentiability and appropriate decay or boundary conditions. The constant is independent of the model.
Denoising score matching instead constructs a Gaussian conditional distribution from known noise. Write the noisy point as , where and .
Differentiate the marginal density under the integral where the regularity conditions permit. The ratio becomes a conditional expectation, so squared-error regression on the conditional score targets the marginal score at each time. Positive time-only weights preserve the pointwise population minimizer, but can weight finite-capacity training differently.
The minus sign has a geometric meaning. To the right of the midpoint, near the valley, the right-hand source is more plausible. It typically needed a leftward noise displacement to arrive here. Negating the expected noise gives a rightward score, as in the lower panel.
Thus a variance-weighted score loss equals the noise prediction loss with the stated parameterization. The experiment samples times in to keep the conditional target well defined. The lab compares draws of the random conditional target with the analytical marginal score.
Denoising Score Matching
| Quantity | First, second |
|---|---|
| Clean x₀ | -1.370, -1.758 |
| Drawn noise ε | -1.107, -1.056 |
| Noisy xₜ | -1.744, -1.972 |
| Conditional score label | 1.515, 1.445 |
| Marginal score | 1.138, 1.529 |
| Optimal noise prediction | -0.831, -1.117 |
Langevin Dynamics
Langevin dynamics adds random exploration to the score drift. For a smooth positive target density and suitable boundary behavior, the continuous dynamics admits the target as a stationary density. Convergence also depends on ergodicity and mixing.
The update is the unadjusted Langevin algorithm. A fixed nonzero step size can bias the stationary distribution, and a large step can be unstable. Separated modes can mix slowly even with the exact score. The time coordinate here counts sampling progress for a fixed target, while diffusion time changes the target density itself.
Langevin Sampling Dynamics
Stochastic Differential Equations
An Itô SDE combines a drift with Brownian increments. Each increment is mean-zero, independent of earlier increments, and has covariance proportional to elapsed time. Its standard deviation therefore scales with the square root of the step size. The example uses one scalar diffusion coefficient for all coordinates.
For an Ornstein–Uhlenbeck process with drift , constant diffusion coefficient , and initial state zero, the exact moments follow by integrating the squared exponential decay of each noise contribution.
As tends to zero, the variance tends to , the Brownian variance. Apply the same random increments to the two simulations to see how the restoring drift changes the spread. The numerical paths are Euler–Maruyama approximations and their empirical moments vary across draws.
Brownian Motion & SDE Simulator
Forward SDE and Density Evolution
The Fokker–Planck equation evolves the density. The drift term transports probability mass. The diffusion term spreads it. Under suitable boundary conditions their spatial integrals vanish, preserving total probability.
The variance-preserving SDE is a continuous counterpart to DDPM with time increasing from data to noise.
The conditional variance satisfies , with . This yields the continuous exponential retention in place of the discrete product. The standard Gaussian is invariant under the forward dynamics. Starting from the teaching mixture, the terminal distribution is only approximately standard Gaussian at finite time. A variance-exploding SDE with zero drift instead preserves the conditional mean and increases perturbation variance by .
Probability Density Evolution
Reverse-time SDE
For a smooth forward diffusion with state-independent diffusion coefficient , reverse time introduces a correction from the marginal score. The differential equation below uses the original time coordinate, integrated from one to zero.
The time increment is negative and the reverse Brownian variance is its absolute value. With a positive step magnitude , the update is
In a generation clock , the drift is . The reverse process reproduces the forward marginals in reverse order in the ideal continuous case with the exact score and terminal distribution. The paths are fresh random realizations. A finite grid and an approximate terminal distribution can change the resulting marginals.
Reverse-time SDE Explorer
Probability-flow ODE
Rewrite the diffusion term using . The same marginal density satisfies a continuity equation, with a deterministic velocity that contains half the score correction of the reverse SDE.
An ODE started from the same distribution has the same ideal time marginals under the appropriate regularity and uniqueness assumptions. Its trajectories differ from the stochastic trajectories. The source of randomness in ODE sampling is the initial point.
Euler uses one function evaluation per step. Heun predicts a provisional point and evaluates the field again before averaging the slopes. Compare 40 Euler steps with 20 Heun steps to match evaluations. Along a sufficiently regular deterministic flow, the log-density changes by the negative divergence of the velocity, which is used for likelihood evaluation in continuous normalizing flows.
Probability Flow ODE vs. SDE
| Sampler | Evaluations | Position |
|---|---|---|
| Reverse SDE | 0 | -1.475, -1.453 |
| ODE Euler | 0 | -1.475, -1.453 |
| ODE Heun | 0 | -1.475, -1.453 |
Engineering Experiment · Continuous-time Score Model
Reuse the four-mode mixture and matched splits from Lessons 5.2 and 5.3. The 5–24–24–2 tanh MLP takes the point, time, and the two diffusion coefficients. It has 794 parameters and predicts noise so its output can be converted to the score. The default setup uses 32 examples per training batch, seed 3, 1000 Adam updates, and learning rate 0.005.
For evaluation, reuse fixed corruption draws and start all samplers from the same 256 standard Gaussian points. The analytical-score reference also uses the same paths' random increments for reverse SDE. Sampling stops at time 0.01 without a final denoising step. Report the same 24-direction sliced Wasserstein-2 and mode diagnostics as the other mixture experiments.
Live Score Network Training
Results on the default split
The validation noise MSE decreases from 1.026758 to 0.375747. Match the number of function evaluations across sampler rows.
| Sampler | NFE | Learned SW₂ | Oracle SW₂ | Learned coverage | Within radius |
|---|---|---|---|---|---|
| Reverse SDE 40 | 40 | 0.658253 | 0.263428 | 4/4 | 80.08% |
| Euler ODE 40 | 40 | 1.586502 | 0.341324 | 4/4 | 78.52% |
| Heun ODE 20 | 40 | 1.629762 | 0.340368 | 4/4 | 79.30% |
For the learned Euler ODE, the four mode counts are 106, 21, 46, and 28. The analytical-score ODE has more even counts on this evaluation. That comparison helps distinguish what happens when replacing the learned field with the exact field. The analytical-score sampler still uses a finite grid, an approximate terminal distribution, and a nonzero stopping time. These are single-run measurements on synthetic data.
Reproducible PyTorch implementation
The script uses PyTorch CPU float64 and includes the analytical mixture score, noise-to-score conversion, three samplers, and the matched distribution metrics. The score identity can be checked by taking central differences of the mixture log-density at fixed coordinates and time.
import math, torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
def rng(seed):
def r():
nonlocal seed
seed=(1664525*seed+1013904223)&0xffffffff
return seed/4294967296
return r
def normal(r):return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def noise(r,n):return torch.tensor([[normal(r),normal(r)] for _ in range(n)])
CENTERS=torch.tensor([[-1.6,-1.6],[-1.6,1.6],[1.6,-1.6],[1.6,1.6]])
def data(seed,n=256):
r=rng(seed);return torch.tensor([[float(c)+.30*normal(r) for c in CENTERS[int(4*r())]] for _ in range(n)])
def beta(t):return .1+11.9*t
def abar(t):return torch.exp(-.1*t-5.95*t*t)
def feats(x,t):
a=abar(t);return torch.cat([x,t.unsqueeze(-1),a.sqrt().unsqueeze(-1),(1-a).sqrt().unsqueeze(-1)],-1)
class Net(nn.Module):
def __init__(self,r):
super().__init__();self.layers=nn.ModuleList()
for ni,no in [(5,24),(24,24),(24,2)]:
l=nn.Linear(ni,no);l.weight.data.copy_(torch.tensor([.8*(r()-.5) for _ in range(ni*no)]).reshape(no,ni));l.bias.data.zero_();self.layers.append(l)
def forward(self,x,t):
h=feats(x,t);return self.layers[2](self.layers[1](self.layers[0](h).tanh()).tanh())
def flat(self):return torch.cat([p.flatten() for p in self.parameters()]).tolist()
def batch(r,X,n=32):
idx=[int(r()*len(X)) for _ in range(n)];t=torch.tensor([.01+.99*r() for _ in range(n)]);e=noise(r,n);a=abar(t[:,None]);return a.sqrt()*X[idx]+(1-a).sqrt()*e,t,e
def score(x,t):
a=abar(t);v=.09*a+1-a;m=a.sqrt()*CENTERS;d=x[:,None,:]-m;w=torch.softmax(-d.square().sum(-1)/(2*v),dim=1);return -(w[:,:,None]*d).sum(1)/v
def metrics(x,y):
a=torch.arange(24)*math.pi/24;d=torch.stack([a.cos(),a.sin()],1);sw=(torch.sort(x@d.T,dim=0).values-torch.sort(y@d.T,dim=0).values).square().mean().sqrt().item();dist=torch.cdist(x,CENTERS);v,i=dist.min(1);counts=torch.bincount(i[v<=.75],minlength=4);return dict(swd=sw,counts=counts.tolist(),valid=(v<=.75).double().mean().item(),coverage=int((counts>=13).sum()))
@torch.no_grad()
def sample(m,z,steps=40,method='sde',seed=99):
x=z.clone();r=rng(seed);h=.99/steps
def drift(x,t,k):
tt=torch.tensor(t);s=score(x,tt) if m is None else -m(x,tt.expand(len(x)))/(1-abar(tt)).sqrt()
return -.5*beta(t)*x-k*beta(t)*s
for i in range(steps):
t=1-i*h
if method=='sde':x=x-h*drift(x,t,1)+math.sqrt(beta(t)*h)*noise(r,len(x))
else:
d=drift(x,t,.5)
x=x-h*d if method=='euler' else x-h/2*(d+drift(x-h*d,t-h,.5))
return x
def run(seed=3,steps=1000,lr=.005):
tr,va=data(seed),data(seed+1000);z=noise(rng(seed+2000),256);val=batch(rng(seed+5000),va,256);m=Net(rng(seed+3000));opt=torch.optim.Adam(m.parameters(),lr=lr);r=rng(seed+4000);hist=[]
for i in range(steps+1):
if i%100==0 or i==steps:
with torch.no_grad():
x,t,e=val;loss=(m(x,t)-e).square().mean().item();hist.append(dict(i=i,loss=loss,p=m.flat()))
if i==steps:break
x,t,e=batch(r,tr);opt.zero_grad();loss=(m(x,t)-e).square().mean();loss.backward();opt.step()
for name,n,method in [('sde',40,'sde'),('ode',40,'euler'),('heun',20,'heun')]:
hist[-1][name]=metrics(sample(m,z,n,method,seed+6000),va);hist[-1]['oracle_'+name]=metrics(sample(None,z,n,method,seed+6000),va)
return hist
if __name__=='__main__':
import json
h=run();print(json.dumps([{k:v for k,v in a.items() if k!='p'} for a in (h[0],h[-1])],indent=2))
References and Chapter Connection
| Mechanism | Reverse SDE | Probability-flow ODE |
|---|---|---|
| Drift in original time | f − g²s | f − g²s/2 |
| Random increment | g√h z | None |
| Ideal marginals | Forward marginals in reverse order | Forward marginals in reverse order |
| Numerical method | Euler–Maruyama | Euler or Heun |
- Hyvärinen derives the integration-by-parts objective. Score Matching
- Vincent relates denoising and score matching. Denoising Score Matching
- Song et al. derive the reverse SDE and the probability-flow ODE. Score-Based Generative Modeling through Stochastic Differential Equations
- The original project contains the corresponding model and solver implementations. Score SDE source code
- The course connects scores, SDEs, and continuous probability transport. MIT 6.S184
Lesson 5.5 learns the transport velocity directly and uses time zero for noise and time one for data.
Previous lesson · 5.3 Denoising Diffusion Probabilistic Models · Course overview · Next lesson · 5.5 Flow Matching