Score SDEs: reverse time, probability flow and numerical error
分数随机微分方程
Compare a reverse SDE with its probability-flow ODE using an independent Gaussian solution.
score-sdeRemoving randomness does not mean deleting the noise term
Take a Gaussian data distribution, gradually mix it toward noise, then try to reverse the process. One reverse method injects fresh random increments; another follows a deterministic differential equation. They can share the same marginal distributions, but the deterministic equation needs a different drift.
In the example below, simply deleting noise from the full reverse-SDE drift produces output variance about .0024 instead of .36. The correct probability flow gives the desired variance in the continuous solution. The missing factor of one half is consequential, not a notation preference.
Song and colleagues’ SDE framework unifies continuous versions of noise-conditioned score models and diffusion models. The first preprint appeared in November 2020; the February 2021 version read here is associated with ICLR 2021. Read score matching, DDPM and normalizing flows first. This article isolates the differential equations, their time direction and numerical approximation.
A noisy forward path and its marginal score
Consider a state x(t) with a deterministic drift f and a diffusion coefficient g. We restrict g to a scalar depending on time, not on x. A Wiener process W has independent increments with variance equal to the elapsed time, so random increments scale with the square root of a time step:
The marginal density pt describes the distribution of x at one fixed time, not a distribution over whole paths. Its score is the spatial gradient of log pt. Under suitable smoothness and time-reversal conditions, the reverse SDE written in decreasing physical time is:
The reversed Wiener increment has covariance magnitude |dt|I. The minus sign inside the drift cannot be interpreted without the negative dt. The paper’s Section 3 explicitly uses decreasing time; the fixed author SDE implementation also distinguishes the reverse SDE from its probability-flow option. State-dependent diffusion requires additional terms and is outside our implementation.
To learn a time-dependent score, sample an original observation x0 and a corrupted xt from a known conditional kernel p0t. A positive weighting function λ specifies which time levels matter to the objective:
The conditional target is accessible when the corruption transition is tractable; its conditional average gives the marginal score. Finite model capacity, sampling and optimization introduce estimation error. The author loss code includes both a standard-deviation-scaled form and a diffusion-weighted form. These are declared weighting choices, not proof that every weighting trains the same finite network.
Why the probability-flow coefficient is one half
For the one-dimensional, state-independent diffusion coefficient considered here, the Fokker–Planck equation describes how probability density moves. Substituting ∂xp=p∂xlog p rewrites it as a deterministic continuity equation:
That density evolution is generated by the probability flow ODE. In vector notation with the same scalar, state-independent g:
With the exact score, a compatible terminal distribution and exact integration, this ODE and the reverse SDE share the specified marginal densities. Their paths need not match. Replacing the score with an approximation or using finite numerical steps can break the equality. “Same marginals” is not a guarantee that two arbitrary learned numerical samplers give identical output distributions.
An example with a solution outside the solver
Use a one-dimensional variance-preserving process with constant β=2, endpoint T=2 and x0∼N(.7,.36). Its forward drift is −βx/2 and diffusion coefficient √β. Solving its Gaussian moment equations gives:
The variance moves toward one; it is not constant for an arbitrary starting variance. At finite T our terminal mean is about .09473470 and variance .98827799, not exactly the standard-normal prior. We initialize from this true terminal Gaussian to isolate integration error.
For implementation, switch to an increasing reverse clock τ=T−t with step h>0. Reversing the time direction changes the drift sign. The two reverse-clock fields are:
Euler–Maruyama adds a Gaussian increment with variance βh, not βh². With independent standard-normal ξk:
The probability-flow solution has an independent affine formula. Starting from xT, its value at any earlier t is:
This map sends the correct terminal Gaussian to the correct earlier Gaussian. It lets us assess a numerical ODE solver without treating its own output as ground truth.
Density follows the divergence
Along a deterministic flow, local expansion reduces density. If bODE=Aτx+Bτ in our reverse clock, its spatial divergence is Aτ. The log-density therefore obeys:
The right-hand expression is the independent change-of-variables answer for this Gaussian example. The paper’s Appendix D.2 derives likelihood computation in the general framework. A tractable continuous formula still requires numerical integration in most implementations; it is not a promise of zero floating-point or score-model error.
Compare stochastic and deterministic solvers
Save as score_sde.py, using Python 3.12 and NumPy 1.26.4. This program supplies the exact Gaussian score; it does not train a neural score model. It uses Euler–Maruyama for the reverse SDE and fourth-order Runge–Kutta for the probability-flow position and log density. exact_flow supplies the independent affine solution, while reverse_moments propagates moments of the discrete stochastic update exactly.
The kind='sde' option in flow deliberately keeps the full reverse-SDE drift while removing its noise. That branch is an explicitly wrong probability-flow construction retained as a counterexample. Its deterministic map has its own density, but not the target density intended by the correct probability flow.
The author Euler–Maruyama code uses negative physical dt and √(−dt); our program uses positive reverse-clock h. Both conventions can be correct when the drift sign and noise variance agree. No upstream code is copied or executed.
For K steps and N scalar paths, Euler–Maruyama costs O(KN); RK4 also has O(KN) scaling but evaluates its field four times per step. Working memory is O(N) because trajectories are not retained. A learned high-dimensional score adds the network cost per evaluation, and likelihood computation adds the divergence calculation. This example computes that one-dimensional divergence exactly.
"""Original exact-score Gaussian VP example: reverse SDE, flow ODE and likelihood."""
import json
import numpy as np
MU,VAR,BETA,END=.7,.36,2.,2.
def marginal(time):
t=np.asarray(time,float)
if not np.all(np.isfinite(t)) or np.any((t<0)|(t>END)):
raise ValueError('Time must lie in[0,2].')
a=np.exp(-BETA*t)
return np.sqrt(a)*MU,1+(VAR-1)*a
def score(x,time):
mean,var=marginal(time)
return -(np.asarray(x,float)-mean)/var
def coefficients(time,kind):
mean,var=marginal(time)
if kind=='sde':factor=1.
elif kind=='ode':factor=.5
else:raise ValueError('kind must be sde or ode.')
# Positive reverse clock tau=END-time; signs differ from equations with dt<0.
return BETA*(.5-factor/var),factor*BETA*mean/var
def count_steps(steps):
if type(steps) is not int or not 2<=steps<=2048:raise ValueError('steps must be in[2,2048].')
return END/steps
def log_normal(x,mean,var):
return -.5*(np.asarray(x)-mean)**2/var-.5*np.log(2*np.pi*var)
def initial_values(x):
x=np.asarray(x,float)
if x.ndim!=1 or not 1<=len(x)<=65536 or not np.all(np.isfinite(x)) or np.max(abs(x))>100:
raise ValueError('Expected1..65536 finite values of magnitude<=100.')
return x.copy()
def exact_flow(x,time=0.):
x=initial_values(x);mean,var=marginal(time);mt,vt=marginal(END)
return mean+np.sqrt(var/vt)*(x-mt)
def flow(x,steps=32,kind='ode'):
x=initial_values(x);h=count_steps(steps);mt,vt=marginal(END);logp=log_normal(x,mt,vt)
# kind='sde' here intentionally removes noise from the full reverse drift:
# it is the WRONG probability flow, retained as a counterexample.
def rhs(y,tau):
a,b=coefficients(max(0.,END-tau),kind)
return a*y+b,-a
for i in range(steps):
tau=i*h;k1,l1=rhs(x,tau);k2,l2=rhs(x+.5*h*k1,tau+.5*h)
k3,l3=rhs(x+.5*h*k2,tau+.5*h);k4,l4=rhs(x+h*k3,tau+h)
x+=h*(k1+2*k2+2*k3+k4)/6
logp+=h*(l1+2*l2+2*l3+l4)/6
return x,logp
def reverse_moments(steps):
h=count_steps(steps);mean,var=marginal(END)
for i in range(steps):
a,b=coefficients(END-i*h,'sde');scale=1+h*a
mean,var=scale*mean+h*b,scale*scale*var+BETA*h
return np.array([mean,var])
def reverse_sample(initial,steps=128,seed=4):
x=initial_values(initial);h=count_steps(steps);rng=np.random.default_rng(seed)
for i in range(steps):
a,b=coefficients(END-i*h,'sde')
x+=h*(a*x+b)+np.sqrt(BETA*h)*rng.normal(size=x.shape)
return x
def demo():
mt,vt=marginal(END);z=np.random.default_rng(31).normal(size=16384);terminal=mt+np.sqrt(vt)*z
probes=mt+np.sqrt(vt)*np.array([-2.,0.,2.]);exact=exact_flow(probes)
convergence={}
for steps in [8,32,128,512]:
x,lp=flow(probes,steps)
convergence[str(steps)]=dict(sde_moments=reverse_moments(steps).tolist(),ode_max_error=float(np.max(abs(x-exact))),
log_density_error=float(np.max(abs(lp-log_normal(x,MU,VAR)))))
generated=reverse_sample(terminal);wrong,_=flow(probes,128,kind='sde')
wrong_variance=float(((wrong[-1]-wrong[0])/4)**2)
return dict(target=[MU,VAR],terminal=[float(mt),float(vt)],convergence=convergence,
sde_sample_moments=[float(generated.mean()),float(generated.var())],
wrong_noiseless_reverse_variance=wrong_variance,
exact_flow_jacobian=float(np.sqrt(VAR/vt)),
exact_log_density_at_mean=float(log_normal(MU,MU,VAR)))
if __name__=='__main__':print(json.dumps(demo(),indent=2))
Measure the error of the method you actually ran
For three terminal probes at the mean and two standard deviations on either side, the RK4 maximum position error decreases from .00153349705 at 8 steps to 7.92251322×10⁻⁶ at 32 and 3.09143972×10⁻⁸ at 128. At 128 steps, the maximum log-density error is about 7.81×10⁻⁸ compared with direct Gaussian density evaluation.
The reverse SDE has different finite-step errors. Its exact discrete output variance is .374328201996 at 128 Euler–Maruyama steps and .363518546397 at 512, approaching the target .36. With 16,384 initial points from seed 31 and transition seed 4, the 128-step sample variance is .372725824047. The sample should first be checked against .37432820, the discrete algorithm’s variance; the remaining difference from .36 includes discretization error.
Keeping the full reverse drift but deleting its noise produces variance .00240186149 at 128 RK4 steps. This is far from the target, even though the deterministic solver is numerically accurate for the wrong equation. Numerical accuracy cannot repair an incorrectly specified drift.
An oracle score isolates only part of the problem
The calculation uses smooth Gaussian marginals with nonzero variance, a constant scalar diffusion coefficient and the true terminal distribution. Real models must estimate the score, choose a practical prior, solve near low-noise endpoints and control numerical cost. Our example separates these issues rather than claiming that they have been solved for images.
The original framework also discusses predictor–corrector sampling, different SDE families and controllable generation. They are not implemented here. Our source reading covers the stated equations and selected methods, not the complete architecture, matrix-diffusion theory or image benchmarks. In higher dimensions, arbitrary state-dependent diffusion cannot be handled by blindly substituting it into the simplified formulas above.
Check the clock before the code
- Time direction. The paper writes a negative dt. May code use a positive step instead? Answer: Yes, after changing to τ=T−t and reversing the drift sign. The random increment still has variance proportional to the positive step magnitude. Merely replacing negative dt with positive h without changing the drift is wrong.
- Noise scale. With β=2 and h=.01, what is the random increment variance and standard deviation? Answer: Variance .02 and standard deviation √.02≈.14142136. Multiplying a standard normal by h√β instead would give variance .0002.
- Counterexample. Why does deleting the reverse SDE’s noise not give the probability flow? Answer: The score contribution in the ODE drift has coefficient one half. The diffusion and drift jointly govern the SDE’s density; removing only diffusion changes that evolution. The wrong branch here shrinks variance to about .0024.
- Evaluation. A stochastic sample agrees with the discrete sampler’s moments but not the target moments. Has that numerical method been verified as exact? Answer: No. This verifies the implementation of that discrete update. Compare its moments with an independent continuous solution and refine the step size to assess discretization error; an estimated score would add another error source.
Read equations, conventions and implementations together
Use Sections 3 and 4.3 plus Appendix D.2 for the forward/reverse equations, probability flow and likelihood relation. Compare the fixed reverse builder, loss weighting and Euler–Maruyama update. The paper was read through its official v2 HTML after the PDF failed bounded retrieval; this is not a claim of inspecting that PDF or reproducing image results.
Make a prediction, then check
Does deleting only the reverse SDE noise yield the probability-flow ODE?
Learning objectives
- Translate decreasing time into a positive reverse clock.
- Derive the probability-flow half factor.
- Check density through divergence and a Jacobian.
- Separate exact marginals from numerical samplers.
Prerequisites & connections
Explore related knowledge →References
- Score-Based Generative Modeling through Stochastic Differential Equations (v2 HTML)
Yang Song; Jascha Sohl-Dickstein; Diederik P. Kingma; Abhishek Kumar; Stefano Ermon; Ben Poole · 2021 - Score SDE reverse/ODE builder at0acb9e0
Yang Song and score_sde contributors · 2021 - Score SDE time-conditioned loss at0acb9e0
Yang Song and score_sde contributors · 2021 - Score SDE Euler–Maruyama predictor at0acb9e0
Yang Song and score_sde contributors · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Score SDE v2 official HTML selected sections3/4.3/D.2 and fixed author JAX reverse/loss/Euler files. Ten paired equations/four explained exercises; exact Gaussian score isolates reverse-clock signs, half-score probability flow, independent Jacobian/log density and EM/RK4 errors. State-independent scalar diffusion only; no neural-score training.
- Single AI author checked Score SDE v2 official HTML selected sections3/4.3/D.2 and fixed author JAX reverse/loss/Euler files. Ten paired equations/four explained exercises; exact Gaussian score isolates reverse-clock signs, half-score probability flow, independent Jacobian/log density and EM/RK4 errors. State-independent scalar diffusion only; no neural-score training.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and24 responsive cases passed; eight final Chinese-mobile/English-desktop screenshots actually inspected. Axis and evidence corrections retained. Full article-page acceptance recorded separately.
Source locations checked:
- Score-Based Generative Modeling through Stochastic Differential Equations (v2 HTML) · Read official HTML Sections3.1–3.3 Equations5–7,4.3 Equation13, partialD.1 andD.2 Equations38–39, including TeX math. First2020-11-26; v2 dated2021-02-10, ICLR2021. PDF failed bounded retrieval and OpenReview showed a verification page; no PDF inspection or full matrix-diffusion/benchmark review.
- Score SDE reverse/ODE builder at0acb9e0 · Read lines75–104: score multiplier1 versus0.5 and zero ODE diffusion. Commit2021-08-26, official JAX implementation. Apache2.0 opening definitions only; no full license audit, copied code or execution.
- Score SDE time-conditioned loss at0acb9e0 · Read lines86–124: random positive time, Gaussian corruption, std-scaled loss and diffusion-weighted alternative. Same2021-08-26 commit and scoped Apache2.0 reading. No upstream execution or copied code.
- Score SDE Euler–Maruyama predictor at0acb9e0 · Read lines184–198: negative physical dt, drift update and sqrt(-dt) noise. Same fixed commit; no complete predictor-corrector or architecture review. Original teaching code uses an explicitly positive reverse clock.
Related topics