import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import logsumexp, ndtr
rng = np.random.default_rng(20260930)
started = time.perf_counter()
beta = 8.0
t_min = 0.01
means = np.array([-2., 2.])
V0 = 0.25
def alpha(t):
return np.exp(-beta * np.asarray(t) / 2)
def parameters(t):
a = alpha(t)
return a * means, a*a*V0 + 1-a*a
def sample_data(n):
return rng.choice(means, n) + np.sqrt(V0)*rng.normal(size=n)
def sample_marginal(n, t):
a = alpha(t)
return a*sample_data(n) + np.sqrt(1-a*a)*rng.normal(size=n)
def component_weights(x, t):
m, V = parameters(t)
logw = -(np.asarray(x)[..., None]-m)**2/(2*V)
return np.exp(logw-logsumexp(logw, axis=-1, keepdims=True))
def density(x, t):
m, V = parameters(t)
return np.mean(np.exp(-(np.asarray(x)[...,None]-m)**2/(2*V))/np.sqrt(2*np.pi*V), axis=-1)
def cdf(x, t):
m, V = parameters(t)
return np.mean(ndtr((np.asarray(x)[...,None]-m)/np.sqrt(V)), axis=-1)
def score(x, t):
m, V = parameters(t)
return np.sum(component_weights(x,t)*(m-np.asarray(x)[...,None])/V, axis=-1)
def ecdf_error(x, t):
x = np.sort(x)
F = cdf(x,t)
n = len(x)
return max(np.max(np.arange(1,n+1)/n-F), np.max(F-np.arange(n)/n))
2. Sampling with an exact score (Draft)
The question
If the score of every intermediate density is known, can we construct a vector field and generate samples by solving its ODE? What changes if we use a stochastic reverse process instead?
We answer these questions for a one-dimensional Gaussian mixture with an analytic score. This removes neural-network estimation error and lets us examine the mathematical construction and numerical solver separately.
Background: Gaussian densities, conditional probabilities, and Euler’s method. Brownian increments are explained below. Setup: NumPy, SciPy, and Matplotlib on a CPU; no data download. Run all cells in order.
1. Specify data and a forward density path
Our clean data density is
\[p_0(x)=\tfrac12\mathcal N(x;-2,0.25)+\tfrac12\mathcal N(x;2,0.25).\]
Write the component means as \(m_1=-2\), \(m_2=2\), with common variance \(V_0=0.25\). Data time is \(t=0\), terminal time is \(t=1\), and generation runs from 1 toward 0.
Choose \(\beta=8\) and \(\alpha_t=e^{-\beta t/2}\). A draw from the forward marginal is obtained from
\[X_t=\alpha_tX_0+\sqrt{1-\alpha_t^2}\,\varepsilon, \qquad\varepsilon\sim\mathcal N(0,1),\]
independently of \(X_0\). Each mixture component therefore has mean \(\alpha_t m_j\) and variance
\[V_t=\alpha_t^2V_0+1-\alpha_t^2.\]
Thus \(p_t\) is known explicitly at every time. At \(t=1\) it is close to, but not exactly, standard normal.
2. Derive the mixture score
Define the noisy component densities \(p_{t,j}(x)=\mathcal N(x;\alpha_t m_j,V_t)\) and their responsibilities
\[w_j(x,t)=\frac{\tfrac12p_{t,j}(x)}{p_t(x)}.\]
Differentiate the mixture and divide by its density:
\[s_t(x)=\frac{\partial_xp_t(x)}{p_t(x)} =\sum_{j=1}^2w_j(x,t)\frac{\partial_xp_{t,j}(x)}{p_{t,j}(x)} =\sum_{j=1}^2w_j(x,t)\frac{\alpha_tm_j-x}{V_t}.\]
The mixture score is a position-dependent weighted average of component scores, not an unweighted average. The next cell implements these densities, CDFs, and scores. Log-sum-exp normalization keeps the responsibility calculation stable in the tails.
3. Inspect the density path and check the score
The following cell plots \(p_t(x)\) and \(s_t(x)\) at several times. It also checks the score against a finite difference of \(\log p_t(x)\):
\[s_t(x)\approx\frac{\log p_t(x+\delta)-\log p_t(x-\delta)}{2\delta}.\]
Here \(\delta\) is only a small numerical differentiation increment, not a diffusion noise level. The check is independent of the analytic mixture-score calculation.
grid=np.linspace(-5,5,600)
fig,axes=plt.subplots(1,2,figsize=(11,4))
for t in [0.,.1,.3,1.]:
axes[0].plot(grid,density(grid,t),label=f"t={t:g}")
axes[1].plot(grid,score(grid,t),label=f"t={t:g}")
axes[0].set(xlabel="x",ylabel="density"); axes[1].set(xlabel="x",ylabel="score")
for ax in axes: ax.legend()
plt.tight_layout(); plt.show()
# Finite-difference check of the analytic score.
dx=1e-5
assert np.max(np.abs(score(grid,.2)-(np.log(density(grid+dx,.2))-np.log(density(grid-dx,.2)))/(2*dx)))<1e-7Reading the plots
At low noise, the density has two separated modes. At high noise, they overlap and the score approaches the standard-normal score \(-x\). A positive score means density locally increases toward larger \(x\); it does not alone specify the probability-flow velocity.
4. Construct the deterministic and stochastic samplers
The forward VP SDE is
\[dX_t=-\frac\beta2X_t\,dt+\sqrt\beta\,dW_t.\]
For this notebook, the essential fact about Brownian motion is that an increment over duration \(h\) is independent of past increments and has law \(\mathcal N(0,h)\). It can be simulated as \(\sqrt h\,\varepsilon\). The square root is necessary because variances of independent increments add.
The deterministic probability-flow field is
\[v(x,t)=-\frac\beta2[x+s_t(x)].\]
For a positive reverse step \(h\), explicit Euler gives
\[x_{t-h}=x_t+\frac{\beta h}{2}[x_t+s_t(x_t)].\]
The reverse SDE, written with increasing generation time \(\tau=1-t\), has drift \(\beta x/2+\beta s_t(x)\) and noise coefficient \(\sqrt\beta\). Euler–Maruyama therefore gives
\[x_{t-h}=x_t+h\left[\frac\beta2x_t+\beta s_t(x_t)\right] +\sqrt{\beta h}\,\varepsilon_k,\]
using fresh independent Gaussian noise at each step. Notice the different score coefficients. Dropping the stochastic term from this SDE would not produce the probability-flow ODE.
The construction is justified by density evolution. The forward SDE has Fokker–Planck equation
\[\partial_t p_t=\frac\beta2\partial_x(xp_t)+\frac\beta2\partial_{xx}p_t =-\partial_x(p_tv),\]
where \(\partial_xp_t=p_ts_t\) gives the displayed velocity. Thus the exact ODE and SDE share marginal densities under the usual regularity assumptions. Their individual trajectories do not agree.
We stop at \(t_{\min}=0.01\). The reference output law is therefore \(p_{0.01}\), not \(p_0\). The helper below implements both numerical samplers with this endpoint.
def sample_reverse(x1, steps=400, stochastic=False, score_fn=score, end=t_min, keep=8):
x = np.asarray(x1).copy()
times = np.linspace(1.,end,steps+1)
traces = [x[:keep].copy()]
for t, next_t in zip(times[:-1],times[1:]):
h = t-next_t
s = score_fn(x,t)
# Increasing reverse clock: -f + g^2*s for SDE; half score for ODE.
x += h*beta*(0.5*x+(1. if stochastic else 0.5)*s)
if stochastic:
x += np.sqrt(beta*h)*rng.normal(size=x.shape)
traces.append(x[:keep].copy())
return x, times, np.asarray(traces)5. Compare generated distributions and trajectories
Initialize from the exact terminal mixture \(p_1\) in this first experiment. That removes the error caused by substituting a standard-normal prior. Use the same initial particles for both samplers and compare their output histograms with the analytic \(p_{0.01}\).
We report the empirical CDF discrepancy
\[D=\sup_x\left|\widehat F(x)-F_{0.01}(x)\right|,\]
where \(\widehat F\) is the empirical CDF of the generated sample. It includes finite-sample fluctuation and numerical error. It is not a pure measure of solver error.
x1=sample_marginal(12000,1.)
ode,times,ode_paths=sample_reverse(x1)
sde,_,sde_paths=sample_reverse(x1,stochastic=True)
fig,axes=plt.subplots(1,3,figsize=(14,4))
for x,label in [(ode,"ODE"),(sde,"reverse SDE")]:
axes[0].hist(x,bins=90,density=True,alpha=.35,label=label)
print(label,"ECDF error vs p(t_min):",round(ecdf_error(x,t_min),4))
axes[0].plot(grid,density(grid,t_min),'k',label="exact marginal"); axes[0].legend()
axes[0].set(xlabel="position",ylabel="density")
for ax,paths,title in zip(axes[1:],[ode_paths,sde_paths],["ODE trajectories","reverse SDE trajectories"]):
ax.plot(times,paths); ax.set(xlabel="diffusion time (generation runs right to left)",ylabel="position",title=title)
plt.tight_layout(); plt.show()ODE ECDF error vs p(t_min): 0.0053
reverse SDE ECDF error vs p(t_min): 0.0059
Reading the sampling results
In the recorded run, the discrepancies are about 0.0053 for the ODE and 0.0059 for the reverse SDE, with 12,000 particles. The histograms are close to the reference density. The smooth ODE paths and fluctuating SDE paths illustrate that matching marginal distributions does not mean matching trajectories. Read the trajectory plots from right to left, because their horizontal axis is forward diffusion time.
6. Isolate numerical error using quantiles
In one dimension, a smooth order-preserving probability flow preserves percentile ranks:
\[F_t(x_t)=u,\qquad x_t=F_t^{-1}(u).\]
Choose evenly spaced ranks \(u_i=(i+1/2)/M\). The exact initial positions are \(F_1^{-1}(u_i)\) and their exact target positions are \(F_{0.01}^{-1}(u_i)\). Numerical root finding supplies these reference quantiles. Comparing Euler outputs with them avoids random histogram fluctuations.
We then repeat with standard-normal initial quantiles \(\Phi^{-1}(u_i)\), holding the solver fixed. Comparing these outputs with the exact-terminal outputs isolates the consequence of the Gaussian-prior substitution.
# Deterministic quantiles remove Monte Carlo noise from the ODE convergence check.
from scipy.optimize import brentq
u=(np.arange(1500)+.5)/1500
initial=np.array([brentq(lambda x: cdf(x,1.)-v,-10,10) for v in u])
reference=np.array([brentq(lambda x: cdf(x,t_min)-v,-10,10) for v in u])
errors=[]
for steps in [50,100,200,400]:
out,_,_=sample_reverse(initial,steps=steps)
err=np.mean(np.abs(out-reference)); errors.append(err)
print(f"{steps=} mean quantile-position error={err:.6f}")
assert errors[-1]<errors[0]/4
# Same numerical solver, different terminal law. Matched quantiles isolate initialization.
from scipy.special import ndtri
normal_out,_,_=sample_reverse(ndtri(u),steps=400)
exact_out,_,_=sample_reverse(initial,steps=400)
print("Mean output difference caused by Gaussian prior:",np.mean(abs(normal_out-exact_out)))steps=50 mean quantile-position error=0.073474
steps=100 mean quantile-position error=0.035981
steps=200 mean quantile-position error=0.017771
steps=400 mean quantile-position error=0.008827
Mean output difference caused by Gaussian prior: 0.0003598121425229904
Reading the error comparison
The mean position error decreases from roughly 0.0735 at 50 steps to 0.00883 at 400 steps. This is the expected first-order convergence pattern for Euler in this experiment. The separate terminal-prior comparison is much smaller here because \(\alpha_1=e^{-4}\) is already small. A weaker corruption rate makes that approximation less accurate.
7. An additional solved Gaussian check
For clean data \(X_0\sim\mathcal N(m_0,V_0)\),
\[m_t=\alpha_tm_0,\qquad V_t=\alpha_t^2V_0+1-\alpha_t^2, \qquad s_t(x)=-\frac{x-m_t}{V_t}.\]
A fixed standard-normal draw \(\varepsilon\) defines the exact probability-flow trajectory
\[x(t)=m_t+\sqrt{V_t}\,\varepsilon.\]
The final check starts at its exact terminal position and compares numerical reverse integration with this known trajectory endpoint for \(m_0=2\), \(V_0=4\).
# Gaussian-data check: p0=N(2,4), analytic deterministic transport.
m0,V_gauss=2.,4.
def gaussian_score(x,t):
a=alpha(t); return -(x-a*m0)/(a*a*V_gauss+1-a*a)
z=rng.normal(size=4000)
a1,ae=alpha(1.),alpha(t_min)
x1g=a1*m0+np.sqrt(a1*a1*V_gauss+1-a1*a1)*z
exactg=ae*m0+np.sqrt(ae*ae*V_gauss+1-ae*ae)*z
numericg,_,_=sample_reverse(x1g,steps=800,score_fn=gaussian_score)
assert np.mean(abs(numericg-exactg))<0.02
print("Gaussian mean trajectory error:",np.mean(abs(numericg-exactg)))
print(f"Runtime: {time.perf_counter()-started:.1f} s")Gaussian mean trajectory error: 0.0072098052677378914
Runtime: 1.3 s
Exercises
- Lower \(\beta\) while keeping all other settings fixed. Which comparison reveals a larger terminal-prior error?
- Halve the step size. Which experiment most cleanly reveals the improvement in numerical accuracy?
- Change the stopping time. Why must the reference density change too?
- Explain why following the score field \(\dot x=s_t(x)\) is a different algorithm from the probability-flow ODE above.
This notebook supplied an analytic score. The next one keeps the same data and sampling algorithm but estimates the score through noise prediction.