26.5 The Fokker--Planck Equation and Probability Flow
The previous section simulated the Ornstein--Uhlenbeck process, the stochastic differential equation that pulls a particle toward the origin while kicking it with noise. Every run drew different paths, and no single path can be predicted. Yet something repeats from run to run. Start a hundred thousand particles at and look at their histogram at time : on every run it is the same bell curve, centered near with a standard deviation near . The randomness of the paths averages out, and the density of the cloud moves deterministically. Which equation moves it?
Adriaan Fokker and Max Planck wrote that equation for particles that feel a steady force and random kicks (Fokker, 1914; Planck, 1917), and Andrey Kolmogorov showed that it governs the density of every diffusion (Kolmogorov, 1931). It has two terms: the drift carries the density along, and the noise smooths it. The smoothing can also be written as transport, a flow that moves probability from where the density is high toward where it is low. Seen at the level of the density, noise acts like a deterministic velocity.
This matters for generative models. A diffusion model generates data by running a noising process backward. No map takes the endpoint of a noisy path back to its start, since many starts lead to the same endpoint. But we know how the density of the whole cloud changed, and we can build processes whose density changes the other way. One is an ordinary differential equation, obtained by replacing the noise with the outward flow; its particles have the same histogram as the stochastic process at every time. The other is again a stochastic process, and it turns noise into data. In both, the drift and the amount of noise are ours to choose. One quantity is not: the direction in which the log-density increases, at every point and time.
We check each step on the Ornstein--Uhlenbeck process and on a two-mode "data" density for which that direction has a closed form. For real data it is unknown, and this is the question we leave open. If the derivations fade, three displays should stay: the Fokker--Planck equation (26.5.7), the identity (26.5.18) that turns its smoothing term into transport, and the family of reverse processes (26.5.26). A reader at home with the divergence theorem can skip Section 26.5.2.1, and the likelihood formula and the bias computation at the end can wait for a second reading.
26.5.1 From Paths to Densities#
26.5.1.1 Paths and Marginals#
Every SDE in this section is
with a drift , a scalar noise amplitude , a -dimensional Brownian motion , and a random start . Over a short step the particle moves by plus an independent Gaussian kick of variance in each coordinate.
One realization of the Brownian motion produces one path , different on every run. The object of this section is instead the density of the random variable , called the time-marginal. It averages over both sources of randomness, the draw of and the noise along the way, and this averaging makes it deterministic.
Our running process is the Ornstein--Uhlenbeck (OU) process of Section 26.4.3, . Started from a point , its marginal is the Gaussian kernel, which we write as
We take and throughout, so the variance saturates at and the stationary law is . The drift moves the center of the cloud and the noise widens it; the Fokker--Planck equation will turn both actions into operators on .
26.5.1.2 Simulated Marginals#
The SDE section compared the moments of such a cloud with the kernel. Here we look at the whole histogram: particles start at and move by Euler--Maruyama steps of size (Section 26.4.4.1), and at , and the cloud is drawn against its exact Gaussian density.
theta, g = 1.0, np.sqrt(2.0) # OU: dX = -theta X dt + g dW
def ou_mean_var(x0, t, theta=theta, g=g):
"""Mean and variance of X_t started at x0: N(alpha_t x0, sigma_t^2)."""
alpha = np.exp(-theta * t)
return alpha * x0, g**2 / (2 * theta) * (1 - alpha**2)
rng = np.random.default_rng()
n, dt, snap_at = 100_000, 0.002, {50: 0.1, 250: 0.5, 1000: 2.0} # step -> t
x, snaps = np.full(n, 2.0), {} # every particle starts at x0 = 2
for k in range(1, max(snap_at) + 1): # Euler--Maruyama
x += -theta * x * dt + g * np.sqrt(dt) * rng.standard_normal(n)
if k in snap_at:
snaps[snap_at[k]] = x.copy()
grid = np.linspace(-3.5, 4.5, 400)
d2l.set_figsize((6, 2.5))
for (t, cloud), c in zip(snaps.items(), ('C0', 'C1', 'C2')):
m, v = ou_mean_var(2.0, t)
d2l.plt.hist(cloud, bins=80, density=True, alpha=0.35, color=c)
d2l.plt.plot(grid, np.exp(-(grid - m)**2 / (2 * v)) / np.sqrt(2 * np.pi * v),
color=c, label=f't = {t}')
d2l.plt.xlabel('x'); d2l.plt.ylabel('density'); d2l.plt.legend();At each of the three times the histogram lies on its curve. By (26.5.1) the curves have mean and standard deviation ; they are drawn from the formula, not fitted to the cloud. At the mean is still , about a quarter of a standard deviation away from the stationary : forgetting a start takes time. This is one run, but the three curves it matches contain no randomness. A second run would differ in every path and match the same curves. It is time to find the equation that moves them.
26.5.2 The Fokker--Planck Equation#
A path cannot be differentiated in time, but the average of a smooth function of over all paths can. Turning a statement about averages into a statement about the density requires moving derivatives from the function onto the density, and that needs three facts about fields in .
26.5.2.1 Divergence, Laplacian, and Integration by Parts#
All three are built from the gradient of Section 22.2, and each has a physical meaning that we will need again. Let be a smooth vector field, which we picture as the velocity of a fluid, and a smooth scalar field.
Divergence. We want to know how much fluid leaves a small box per unit time. The divergence of is the scalar field
It is the net rate at which fluid leaves an infinitesimal box around , divided by the volume of the box: positive at a source, negative at a sink. Two plane fields show the range. The expanding field has , so every box of area loses fluid at the rate , wherever it sits. The rotation has : fluid circulates, and no box gains or loses any. A zero divergence therefore does not mean a zero field. Figure 26.5.1 checks both statements on one box.
The divergence as net outflow, on the box of side centered at . Each green arrow is the normal component of the field at the midpoint of a side, drawn away from the side for outflow and onto it for inflow. (a) For fluid enters through the left and bottom sides and leaves through the right and top; the outflow exceeds the inflow by the area. (b) For the rotation the inflow through the right and bottom sides equals the outflow through the other two.
Summing the outflow of many small boxes cancels every interior face, which leaves the flux through the outer boundary. This is the divergence theorem: for a bounded region with outward unit normal ,
The total divergence inside a region equals the net flow out through its boundary. In one dimension it is the fundamental theorem of calculus, . We use the theorem without proof; it is proved in any text on multivariable calculus.
Laplacian. We want a measure of how a function compares with its surroundings. The Laplacian is the divergence of the gradient (in front of a function, is this operator and not an increment as in ),
It compares at a point with its average over a small sphere of radius around the point: that average is , which Exercise 1 proves. In one dimension, with , the "sphere" is the pair of points , the average is , and , so the formula holds with no remainder (at , the average is ). So means that lies below its neighborhood average. A zero Laplacian does not mean a constant function: has and equals its average over every circle.
Integration by parts. This is the -dimensional form of the one-dimensional rule of Section 22.6.2.3, and it is the tool that moves a derivative from one factor onto the other. If and are smooth and decays fast enough at infinity (in this section, because vanishes outside a bounded set or because both factors have Gaussian tails), then
The derivative moves from onto , and the sign flips.
Proof. The product rule gives . Integrate both sides over a ball of radius and let . By the divergence theorem the left side is the flux of through the sphere of radius , which tends to zero under the decay assumption.
Applied twice, first with and then with the roles exchanged, it moves a whole Laplacian across the integral sign, and the two signs cancel: .
26.5.2.2 From Itô's Lemma to the PDE#
We now derive the equation for . Throughout we assume that is continuously differentiable in and continuous in , that is continuous, that is smooth and positive, and that derivatives in may be taken under the integral sign.
The idea is to look at the cloud through averages. If is a smooth bump equal to on a small box and outside a slightly larger one, then is roughly the probability of the box. Knowing how every such average changes over time determines how the density changes. So take any smooth test function that vanishes outside a bounded set.
Itô's lemma (Section 26.4.2.4) is the chain rule for SDE paths. For it adds to the ordinary chain rule the second-order term , because the squared Brownian increment is of size rather than negligible. With that term is times the Laplacian of :
The function changes by a drift part, the chain rule plus the Laplacian correction, and a noise part. Now take expectations. The Itô integral of has mean zero, because each Brownian increment is independent of the integrand at the start of that increment (Section 26.4.2.2). The noise part drops out:
The average of changes at the average of the rate that Itô's lemma gave. Both sides are integrals against the marginal density. Writing and moving under the integral,
The derivatives on the right still act on ; we move them onto with integration by parts (26.5.5). Because vanishes outside a bounded set, no boundary terms appear and no decay of is needed. The drift term needs one move, with and ; the diffusion term needs two, and its signs cancel:
Substituting both gives one integral against :
This holds for every test function . The bracket is continuous, and a continuous function that integrates to zero against every bump is zero (a bump placed where it is positive would give a positive integral). So the bracket vanishes pointwise, and solves the Fokker--Planck equation, also called the Kolmogorov forward equation:
The first term is the drift's contribution, the second the noise's. For a matrix noise the second term becomes with ; Exercise 5 works out what changes. Risken (1996) collects the many variants of the equation used in physics.
The derivation gives one direction only: the marginal of the SDE solves the equation. Later we need the converse, that a solution which starts from is the marginal, and for this the equation must have only one solution. It does under mild conditions, which every drift we use satisfies: , and a drift that is Lipschitz in uniformly in , that is, with a slope in bounded by one constant for all . Among probability densities with a given initial law the solution is then unique (Bogachev et al. (2015) give precise statements). We use this uniqueness without proof, and say so where we do.
26.5.2.3 The Heat Equation and the Two Terms#
Switch the drift off. The Fokker--Planck equation is then the heat equation,
The density rises wherever it lies below its neighborhood average. Before any general statement, we check it at one point. Take , and , the law of Brownian motion started at . With , direct differentiation gives and . At , : , and . The peak sinks at the rate the Laplacian predicts.
More generally, a Gaussian solves the heat equation when its variance grows as for constant , or as when changes with time. This is the law of Brownian motion. Noise alone is the variance-exploding family of Section 26.4.1.1, which diffusion models use with a growing .
Now read the two terms of (26.5.7). The first, , is advection: it removes density wherever the drift carries more mass out of a small box than in. The second, , is diffusion: it raises the density where it lies below its neighborhood average and lowers it where it lies above. It is Itô's correction, seen at the level of the density.
26.5.2.4 Gaussian Solutions of the OU Equation#
For the OU process we know the answer in closed form, which lets us test the equation on a whole family of solutions. With in one dimension, (26.5.7) reads
The unknown of a partial differential equation is a whole function, and one rarely finds it by hand. Here we are lucky. It turns out that for a Gaussian the equation collapses to two ordinary differential equations, one for the mean and one for the variance.
Proposition (Gaussian solutions of the OU equation). Let be a Gaussian density with differentiable mean and variance . Then solves the OU Fokker--Planck equation if and only if
Proof. For a Gaussian, . Direct differentiation turns each side of the PDE into times a quadratic polynomial in :
while, writing in the drift term,
The functions are linearly independent, so the two sides agree for all only when the coefficients match: from the linear term and from the quadratic term (the constant term repeats the latter).
The mean decays and the variance relaxes toward . Solving the two ODEs from , gives
For a point start, , this is the kernel (26.5.1) at every , so the transition density of Section 26.4.3 solves the Fokker--Planck equation.
The fixed point is , : the stationary Gaussian is the steady state of the PDE (Exercise 3 derives it without assuming a Gaussian form). Setting recovers the heat equation's .
The luck has a cause, and a limit. The drift is linear, so a Gaussian stays Gaussian and its first two moments form a closed system. For the double-well drift of the same exercise, the equation for contains , the one for contains , and the chain never closes.
26.5.2.5 Linearity and Mixtures#
Real data are not Gaussian either, so we need a density with more structure that we can still follow in closed form. With a linear drift a Gaussian mixture is one. Our running "data" density is
two well-separated modes of standard deviation . A draw from picks a component and then a point from it. By the kernel (26.5.1), is plus an independent variable. Given the component, it is therefore a sum of two independent Gaussians, with mean and variance , and averaging over the component gives the marginal: the mixture of the evolved components. With , it is the mixture of , in closed form at every time.
The same fact can be read off the Fokker--Planck equation, which is linear in . A mixture of solutions is therefore a solution, and by the uniqueness stated after (26.5.7) it is the marginal for the mixed start. Under OU each Gaussian component follows the moment ODEs (26.5.9) on its own.
Every experiment from here on uses this marginal, so we define it once, together with its CDF and a sampler. The parameters are explicit arguments, so the exercises can change them.
ws, mus, v0s = np.array([0.5, 0.5]), np.array([-2.0, 2.0]), np.array([0.25, 0.25])
erf = np.vectorize(math.erf) # the error function, on arrays
def mixture_params(t, mus=mus, v0s=v0s, theta=theta, g=g):
"""Means and variances of the OU-evolved components (moment ODEs)."""
alpha = np.exp(-theta * t)
return alpha * mus, alpha**2 * v0s + g**2 / (2 * theta) * (1 - alpha**2)
def gauss(x, m, v):
return np.exp(-(x - m)**2 / (2 * v)) / np.sqrt(2 * np.pi * v)
def p_t(x, t, ws=ws, mus=mus, v0s=v0s):
"""Exact marginal density of the mixture at time t."""
m, v = mixture_params(t, mus, v0s)
return sum(w * gauss(x, mk, vk) for w, mk, vk in zip(ws, m, v))
def mixture_cdf(x, t, ws=ws, mus=mus, v0s=v0s):
m, v = mixture_params(t, mus, v0s)
return sum(w * 0.5 * (1 + erf((x - mk) / np.sqrt(2 * vk)))
for w, mk, vk in zip(ws, m, v))
def sample_p0(n, rng, ws=ws, mus=mus, v0s=v0s):
k = rng.choice(len(ws), size=n, p=ws) # component of each draw
return mus[k] + np.sqrt(v0s[k]) * rng.standard_normal(n)
With the closed form in code, we can put it into the PDE directly. Both sides
are evaluated on a grid at , and , with by a
centered difference in time and the -derivatives by np.gradient. Finite
differences leave a residual even for an exact solution, so the cell uses two
grids, the second twice as fine: the truncation error of these second-order
stencils must fall by a factor of four.
def fp_residual(t, points, eps=1e-5):
"""Largest Fokker--Planck residual on a grid of `points`, and max|dp/dt|."""
xs = np.linspace(-5.0, 5.0, points)
dx = xs[1] - xs[0]
dpdt = (p_t(xs, t + eps) - p_t(xs, t - eps)) / (2 * eps)
p = p_t(xs, t)
rhs = (np.gradient(theta * xs * p, dx) # -d/dx(f p)
+ 0.5 * g**2 * np.gradient(np.gradient(p, dx), dx))
res = (dpdt - rhs)[5:-5] # trim the one-sided edge stencils
return np.abs(res).max(), np.abs(dpdt).max()
for t in (0.25, 1.0, 3.0):
(r1, dpdt), (r2, _) = fp_residual(t, 4001), fp_residual(t, 8001)
print(f't={t}: max|dp/dt| = {dpdt:.1e}; max|residual| at 4001, 8001 points: '
f'{r1:.1e}, {r2:.1e} (ratio {r1 / r2:.1f})')
t=0.25: max|dp/dt| = 4.4e-01; max|residual| at 4001, 8001 points: 4.4e-06, 1.1e-06 (ratio 4.0)
t=1.0: max|dp/dt| = 1.7e-01; max|residual| at 4001, 8001 points: 6.3e-07, 1.6e-07 (ratio 4.0)
t=3.0: max|dp/dt| = 3.2e-03; max|residual| at 4001, 8001 points: 1.2e-06, 3.0e-07 (ratio 4.0)
The residual is three to five orders of magnitude below at each time ( against at ; at the density barely moves, and stands against ), and the finer grid divides it by four at all three times. What is left is truncation error. The argument did not need this computation; the cell guards against a slip in the code on which all later experiments rely.
26.5.3 The Score Function#
The smoothing term of the Fokker--Planck equation will turn out to be transport in disguise, and the velocity of that transport is built from one field, the gradient of . The identity puts it inside the Laplacian (Section 26.5.4). Every construction from there on needs this field, so we look at it first, with the mixture as the main example.
26.5.3.1 Definition and Geometry#
The question is which direction, from a point , leads most quickly toward more probable points. The score of a density answers it:
The score is a vector field over data space that points uphill on the log-density. The gradient is with respect to the input , not the parameters of a model; Section 25.5.1 introduced this data score and contrasted it with the parameter score of maximum likelihood.
The length of is the rate at which increases, . It is therefore large where the density is small but changing, in the tails and in the valleys between modes, and not where the density is large. The score vanishes at the critical points of : modes, minima and saddles, which its derivative tells apart.
Take a Gaussian first. For the log-density is , so
This is the linear spring of Section 25.5.1: it pulls toward the mean, and it is stiffer for smaller variance. With , and it is , four times the pull at unit variance. For a general covariance the spring is . Figure 26.5.2 shows the score field of a two-mode density in two dimensions.
The score of a two-component Gaussian mixture, drawn over density contours. The arrows point uphill and vanish at critical points; the orange points mark the two modes, and the symmetry point between them is another zero, with different curvature. Arrows have the true length , capped at in the far tails, where it grows without bound; they are short near the modes and the saddle.
26.5.3.2 The Score of a Gaussian Mixture#
Our data density is a mixture, so we need its score in a form we can evaluate and read. For with weights and components , differentiate directly:
The mixture's score is a weighted average of the component springs. The weight is the responsibility of component , the posterior probability that a point at came from it, as in Section 25.5.1. For two components with equal weights, means and a common variance , the responsibilities reduce to a logistic function of and the score has the closed form
Near each mode and the score is the local spring . For the running mixture, and , it is . At the score vanishes, the third critical point, and it grows from zero with slope
A positive slope means that is a minimum of the density, a repeller of the uphill flow . The mixture has two modes exactly when ; for they merge into one (Exercise 4).
In code we use the general formula (26.5.12), with a numerically stable softmax for the responsibilities, because the later experiments need the score of at every time. The tanh form, the zeros and the slope serve as checks on the implementation.
def score_t(x, t, ws=ws, mus=mus, v0s=v0s):
"""Exact score of p_t: responsibility-weighted component springs."""
m, v = mixture_params(t, mus, v0s)
logw = np.stack([np.log(w) - 0.5 * np.log(2 * np.pi * vk)
- (x - mk)**2 / (2 * vk) for w, mk, vk in zip(ws, m, v)])
r = np.exp(logw - logw.max(axis=0))
r /= r.sum(axis=0) # responsibilities, a stable softmax
return sum(rk * -(x - mk) / vk for rk, mk, vk in zip(r, m, v))
gs = np.linspace(-3.5, 3.5, 1400)
mu, v0 = mus[1], v0s[1]
s = score_t(gs, 0.0)
s_tanh = (mu * np.tanh(mu * gs / v0) - gs) / v0
print(f'max|responsibility form - tanh form| = {np.abs(s - s_tanh).max():.1e}')
mid = (gs[:-1] + gs[1:]) / 2
print('score changes sign near', np.round(mid[s[:-1] * s[1:] < 0], 2) + 0.0)
delta = 1e-5 # centered difference at x = 0
print(f'slope at 0: {(score_t(delta, 0.0) - score_t(-delta, 0.0)) / (2 * delta):.2f}, '
f'formula (mu^2 - v0) / v0^2 = {(mu**2 - v0) / v0**2:.2f}')
dens = p_t(gs, 0.0)
d2l.plot(gs, [s, dens * np.abs(s).max() / dens.max()], 'x', '',
legend=['score s(x)', 'density (rescaled)'], figsize=(5.5, 3))max|responsibility form - tanh form| = 7.3e-15
score changes sign near [-2. 0. 2.]
slope at 0: 60.00, formula (mu^2 - v0) / v0^2 = 60.00
The checks pass: the two formulas agree to machine precision, and the zeros and the slope are where we computed them. What the plot adds is where the score is large: in the valley between the modes, where the density is nearly zero but its logarithm climbs steeply toward either mode, and in the tails.
26.5.4 The Continuity Equation and the Probability-Flow ODE#
The Fokker--Planck equation describes particles that move at random. Which law governs particles that move deterministically? It turns out that the two laws coincide once the noise is written as a velocity.
26.5.4.1 Conservation of Probability#
Forget noise for a moment. Suppose every particle follows a velocity field, . What PDE does their density obey? Probability is neither created nor destroyed, so the mass inside a fixed region can change only by flowing across its boundary. Particles cross a small patch of boundary at the rate density times velocity. We call this flux density the probability current, : at each point it gives the rate, per unit area, at which probability crosses a surface placed there. The mass balance of the region is
where the divergence theorem (26.5.3) turned the boundary flux into a volume integral. The mass inside changes at minus the net outflow. Since is arbitrary, the integrands agree pointwise, which gives the continuity equation:
The density at a point falls at the rate at which the current diverges there. In one dimension the balance reads : what flows in at minus what flows out at . Figure 26.5.3 draws it.
The continuity equation as a flux balance. The velocity is here a constant drift and the density is written : the density (blue) is carried by , giving the probability current . On the window from to on the right flank of the bump, the mass inside (orange) grows at the rate , the net inflow: more current enters at than leaves at because the density is higher at .
The balance also says what happens at the edges of the domain. On all of we assume that the current decays at infinity. For the Fokker--Planck equation this means that and decay, which Gaussian tails ensure even though the OU drift grows linearly. Integrating (26.5.15) over then gives : total probability is conserved. On a bounded domain a reflecting boundary imposes , so mass is conserved there too, while an absorbing boundary imposes , and mass can leave.
Two small cases show the equation at work in one dimension. For a translation, , the equation is , solved by : the profile slides without changing shape. For a contraction, , every particle moves as , the cloud shrinks by the factor , and since the mass of each interval is preserved, the density carried along each trajectory rises by .
The contraction suggests a general rule for the density seen by a moving particle. Expanding the divergence with the product rule,
the continuity equation becomes . The left side is the rate of change of along a trajectory of , by the chain rule. Dividing by ,
Along a trajectory the log-density falls at the rate of the local expansion. For the contraction, and the log-density rises at rate , as computed above. The trajectories of are called the characteristics of the continuity equation. The rule is the instantaneous change of variables of Section 26.3.3, proved there along trajectories.
26.5.4.2 Diffusion as Transport#
The Fokker--Planck equation (26.5.7) is not yet a continuity equation: next to the transport term it has a Laplacian. The chain rule turns the Laplacian into a transport term. It is a one-line calculation, and the most consequential one of the section. Wherever ,
which is the derivative of written backward, and therefore
The diffusion term is the divergence of a current, the density times . Moved to the left side of a continuity equation it appears with a minus sign, as a velocity .
Proposition (Fokker--Planck is a continuity equation). Wherever , the Fokker--Planck equation (26.5.7) is equivalent to
Proof. Substitute (26.5.18) into (26.5.7) and merge the two divergences:
At the level of densities, the SDE moves probability as if each particle followed the velocity : the drift plus a push down the log-density gradient. The corresponding current is
The heat equation shows what this velocity looks like. Take and in one dimension with . The score is , so
The velocity points away from the center and is proportional to the distance from it, and it weakens as the density widens. The ODE separates: , so
Every particle is stretched by the same factor, and a Gaussian stretched by has variance , which is the variance that Brownian motion produces. With and every particle doubles its distance from the center. A Brownian particle started at instead lands at plus a draw of standard deviation . The two processes agree on the histogram at every time but move individual particles differently (Figure 26.5.4).
The heat equation from , solved as a flow. (a) The density at and at , with the velocity drawn as arrows on the axis: outward and proportional to distance. The particle at moves to by , and the density it carries halves. (b) Flow trajectories , smooth and never crossing, against three Brownian paths from and their one-standard-deviation envelope .
There is a limit to this construction. As the velocity at small times is , which is unbounded as . A deterministic flow can spread a point mass into a Gaussian only through a field that blows up at the start, because a Lipschitz flow maps one point to one point.
The next cell runs this example. From one draw of points of it forms a Brownian cloud at (adding an independent increment) and a flow cloud by integrating with Heun's method (Section 26.2). It prints the two standard deviations, and how far the flow cloud is from the starting sample doubled.
def heat_velocity(x, t, v0=1.0, g=1.0): # u_t = -(1/2) g^2 score = g^2 x / (2 v_t)
return g**2 * x / (2 * (v0 + g**2 * t))
n, T, steps = 20_000, 3.0, 600
dt = T / steps
z = rng.standard_normal(n) # p_0 = N(0, 1)
x_bm = z + np.sqrt(T) * rng.standard_normal(n) # Brownian motion to time T
x_ode = z.copy()
for k in range(steps): # Heun steps for the probability flow
k1 = heat_velocity(x_ode, k * dt)
k2 = heat_velocity(x_ode + dt * k1, (k + 1) * dt)
x_ode += 0.5 * dt * (k1 + k2)
print(f'std at t={T}: Brownian {x_bm.std():.3f}, flow {x_ode.std():.3f}, '
f'exact {np.sqrt(1 + T):.3f}')
print(f'max|x_ode - 2 z| = {np.abs(x_ode - 2 * z).max():.1e}')std at t=3.0: Brownian 1.995, flow 1.994, exact 2.000
max|x_ode - 2 z| = 5.8e-06
Both clouds have standard deviation up to a sampling error of order , and the flow map equals up to a Heun error below . Random kicks and a deterministic stretch have produced the same histogram.
26.5.4.3 The Probability-Flow ODE#
The heat equation was one example. The proposition above says that the same construction works for every SDE of our form: following the velocity gives an ODE,
the probability-flow ODE (Song et al., 2021). The next proposition is the first of the two results that generative models take from this section.
Proposition (the deterministic twin). Let be the marginal density of , , assumed smooth and positive, so that it solves the Fokker--Planck equation. Suppose that is continuous in , continuously differentiable in , and Lipschitz in with a constant that does not depend on . Let solve (26.5.22) with . Then for every : the ODE and the SDE share all time-marginals.
Proof. By the existence and uniqueness theorem of Section 26.1.1.3, a field that is Lipschitz with a constant independent of has exactly one trajectory through every point, forward and backward, so its time- map is a bijection of . Let be the density of the ODE's state. There is no circle here: the field is built from , not from , so it is a known velocity and obeys the continuity equation . By the previous proposition solves the same equation, and both start from . The derivation of the log-density rule (26.5.16) used only this PDE, so along each characteristic and change at the same rate , and they start equal. Since the characteristics reach every point, everywhere.
The Lipschitz hypothesis holds for the OU drift and for the score of a Gaussian or a Gaussian mixture with positive component variances, whose slope is bounded for in .
The marginals agree; the paths do not. An SDE path is jagged and crosses other paths. An ODE trajectory is smooth, and two trajectories never meet at the same point at the same time, by uniqueness (panel (b) of Figure 26.5.4).
The ODE also gives a likelihood. Integrating the log-density rule (26.5.16) with along a trajectory from to gives
The log-density of a data point is the log-density of its image at time , which is nearly Gaussian and easy to evaluate, plus the accumulated expansion along the way. With a learned score in place of the exact one this is, up to solver error, the log-density of the model defined by that field (Song et al., 2021). It is one of the two numbers by which the likelihood of a diffusion model is reported; the other is a variational bound (Section 17.6).
26.5.4.4 SDE and ODE Marginals Compared#
The heat flow was a stretch of one Gaussian. On the mixture the proposition has more to do: the density changes shape, from two modes to one, and the jagged and the smooth process must still agree on it at every time. From one sample of we launch two clouds of particles: one follows the SDE with Euler--Maruyama steps, the other the probability-flow ODE with Heun steps and the exact score. As a yardstick we compute the one-sample Kolmogorov--Smirnov distance of each cloud to the exact CDF of , the largest gap between the empirical and the exact CDF. For an exact sample of size this distance exceeds only of the time. Before looking at the output, guess which cloud's distance changes more from one snapshot to the next.
def pf_velocity(x, t, score=score_t, theta=theta, g=g):
return -theta * x - 0.5 * g**2 * score(x, t) # u_t = f - (1/2) g^2 s_t
def ks_exact(sample, t, **mixture):
"""One-sample Kolmogorov--Smirnov distance to the exact p_t."""
xs_sorted, n = np.sort(sample), len(sample)
F = mixture_cdf(xs_sorted, t, **mixture)
return max((np.arange(1, n + 1) / n - F).max(), (F - np.arange(n) / n).max())
n, T, steps = 20_000, 3.0, 600
dt = T / steps
x_sde = sample_p0(n, rng)
x_ode = x_sde.copy() # both clouds start from one sample
snaps = {}
for k in range(steps):
t = k * dt
x_sde += -theta * x_sde * dt + g * np.sqrt(dt) * rng.standard_normal(n)
k1 = pf_velocity(x_ode, t) # Heun steps for the ODE
k2 = pf_velocity(x_ode + dt * k1, t + dt)
x_ode += 0.5 * dt * (k1 + k2)
if k + 1 in (50, 200, 600): # t = 0.25, 1, 3
snaps[(k + 1) * dt] = (x_sde.copy(), x_ode.copy())
print(f'95% band for n = {n}: {1.36 / np.sqrt(n):.4f}')
for t, (a, b) in snaps.items():
print(f't={t:.2f}: KS(SDE) = {ks_exact(a, t):.4f}, KS(ODE) = {ks_exact(b, t):.4f}')
gx = np.linspace(-3.5, 3.5, 400)
d2l.set_figsize((5.5, 3))
d2l.plt.hist(snaps[0.25][0], bins=80, density=True, alpha=0.4, label='SDE')
d2l.plt.hist(snaps[0.25][1], bins=80, density=True, alpha=0.4, label='PF-ODE')
d2l.plt.plot(gx, p_t(gx, 0.25), 'k', label='exact $p_t$, t = 0.25')
d2l.plt.xlabel('x'); d2l.plt.legend(loc='upper center', fontsize=8);95% band for n = 20000: 0.0096
t=0.25: KS(SDE) = 0.0051, KS(ODE) = 0.0074
t=1.00: KS(SDE) = 0.0088, KS(ODE) = 0.0074
t=3.00: KS(SDE) = 0.0044, KS(ODE) = 0.0074
In most runs both clouds stay within the band at all three times, with distances between about and . A value just above the band is no alarm: the band is a threshold, and an exact sample crosses it one time in twenty. At the marginal is still bimodal, and both histograms reproduce its two modes; by it has a single mode (the merging time is , Exercise 4).
Now the guess. The ODE's distance is the same at all three times, to every digit printed. A strictly increasing map that carries to carries the sample's empirical CDF along with it, so the ODE cloud keeps the distance its starting sample had and adds only solver error. The SDE cloud is redrawn by the noise at every step, and its distance fluctuates.
26.5.5 Time Reversal#
The forward SDE turns data into noise. Generation needs the process played backward, from noise to data. This may sound impossible: the heat equation cannot be solved backward from an arbitrary final density, because smoothing destroys detail that nothing can restore. We do not solve it backward. The forward family is given, and we ask only for a process that visits it in reverse order (Figure 26.5.5); its drift will contain , which carries the destroyed detail. The probability-flow ODE is one such process, integrated backward. For the SDE the answer is less obvious: the backward process is again a diffusion, and its drift carries twice the score correction of the ODE.
The forward marginals of the running mixture under OU with , , exact at every time. The reverse processes of this section run the same marginals from right to left. The flat top at is where the two modes merge.
26.5.5.1 Bayes' Rule on an Infinitesimal Step#
To reverse one small step we use Bayes' rule to ask where a particle came from. Over a short interval the forward step is the Euler--Maruyama Gaussian (Section 26.4.4.1):
Now condition on the endpoint . Bayes' rule gives the probable starting points as the forward kernel reweighted by the marginal at time :
A starting point is likely if it could have reached and if it was likely to begin with. Take logarithms and expand around the endpoint: . The step is of size , so the neglected quadratic term is of order and changes the posterior only at higher order. To the same order we may evaluate at instead of , since is of size and is multiplied by . Now a linear term added to a Gaussian exponent shifts the mean by the variance times the slope and leaves the variance alone (complete the square). The exponent is , the variance is and the slope is :
A backward step is a Gaussian kick of the same variance , whose drift is the forward drift corrected by the full times the score. The marginal acts as a prior that bends the reversed step toward where the data density was.
26.5.5.2 The Reverse-Time SDE#
The one-step calculation is a heuristic: it expands to first order and starts from an approximate kernel. Anderson (1982) proved that it gives the right answer for the whole process. We state his theorem without proof: the time reversal of the diffusion is the reverse-time SDE
integrated from down to . Here is a Brownian motion that runs backward in time; in a simulation it means a fresh Gaussian increment at each backward step. Started from , the process has marginal at every intermediate time, and at it delivers the data density. The theorem identifies the reversed process as a whole; below we prove only the statement about marginals, which is the part that sampling needs.
Read as steps, the display is the calculation of the previous subsection. Going from down to is a step with , so the particle moves by plus a kick of variance , and this is the Gaussian (26.5.24). A clock that runs forward is easier to compute with. In the reversed clock the same process is an ordinary SDE with drift and noise : the drift changes sign with the direction of time, and the noise does not care.
The smallest case can be checked by hand. Take OU at stationarity, for all , with , and score . The probability-flow velocity is : the ODE particles do not move, so the cloud stays . In the reversed clock the reverse SDE has drift and noise , which is the same OU process. Stationary OU is its own reverse.
With in place of the reverse drift would be , and the cloud would spread like Brownian motion instead of staying put. So the reverse SDE needs the full factor , twice the correction of the ODE. A family of samplers explains the factor.
Proposition (one family, marginals fixed). Let be the marginal density of the forward SDE, under the hypotheses of the deterministic-twin proposition and with Lipschitz in . For any , the reverse-time SDE with noise amplitude and drift
has marginals when started from . The choice is Anderson's reverse SDE (26.5.25); the choice is the probability-flow ODE (26.5.22).
The more noise a sampler injects, the larger its score correction.
Proof. Work in the reversed clock and let , the density evolution played in reverse, so that , with and evaluated at forward time . A process in the reversed clock has its own Fokker--Planck equation . For the two to agree we need
where both Laplacians were converted to transport form with (26.5.18). The equation holds for . A drift in the reversed clock is a drift in forward time, which gives (26.5.26). It remains to pass from equal evolution equations and the equal start to equal marginals, and this is the step that needs uniqueness. For it is the argument along characteristics of the deterministic twin. For it is the uniqueness stated after (26.5.7), which we did not prove; it applies because is Lipschitz when and are.
The proof also explains the factor of two. A reverse process with noise smooths its own density, so its drift must undo two smoothings. One cancels the forward smoothing; that is the whole correction of the probability-flow ODE, which injects no noise. A further compensates the smoothing by the reverse process's own noise. Anderson's contains both halves. The marginals do not determine the drift, though: any other drift with the same marginals differs from by a field with , and Exercise 7 builds such fields.
What is the freedom good for? Noise lets a sampler forget. An error in the distribution of the state, from a start that is not quite or from an earlier step, is carried by the ODE all the way to : its map is a bijection and loses nothing. The noise of an SDE washes part of the error out (Exercise 10 makes both statements exact). In exchange the score term is larger, and a long noisy step adds error of its own. Diffusion-model samplers choose with this in mind (Section 17.5). Whatever the choice, the sampler needs the same field , so one estimate of the score serves the whole family.
Figure 26.5.6 shows three values of on the running mixture. The deterministic paths split toward the two modes near , that is, near forward time , where the marginal stops being bimodal.
Reverse-time trajectories from the same four starting points at , using the exact score of the running mixture with drift and noise . The probability-flow ODE () is deterministic; and Anderson's reverse SDE () add noise and a larger score correction. The three histograms at , of particles each (right), agree with the data density .
26.5.5.3 Reverse-Time Sampling#
Let us generate data, with the exact score in place of a trained network. For this one experiment we make the data lopsided. The modes keep their places and widths, but four fifths of the mass go to the left: . A sampler that starts from symmetric noise must then get the proportions right as well as the modes, and that is a test it can fail.
We draw points from , which stands in for at , and integrate Anderson's reverse SDE down to with Euler--Maruyama steps in the reversed clock. The cell first measures how far is from , then compares the sample with the data: the mass to the left of the origin, the means and widths of the modes, and the KS distance to beside that of an exact sample of the same size.
uneven = dict(ws=np.array([0.8, 0.2])) # four fifths of the data on the left
pT = p_t(gs, 3.0, **uneven)
print(f'max|p_T - N(0,1)| at T=3: {np.abs(pT - gauss(gs, 0.0, 1.0)).max():.4f} '
f'(peak {pT.max():.2f})')
x = rng.standard_normal(n) # N(0, 1) stands in for p_T
for k in range(steps): # reversed clock: t_bar = k dt
t = T - k * dt # forward time
x += (theta * x + g**2 * score_t(x, t, **uneven)) * dt \
+ g * np.sqrt(dt) * rng.standard_normal(n)
left, right = x[x < 0], x[x >= 0]
print(f'mass on the left: {len(left) / n:.3f} (data 0.800)')
print(f'means {left.mean():+.3f}, {right.mean():+.3f} (data -2, +2)')
print(f'widths {left.std():.3f}, {right.std():.3f} (data 0.5)')
x_ref = sample_p0(n, rng, **uneven) # an exact sample of the same size
print(f'KS to the exact p_0: sampler {ks_exact(x, 0.0, **uneven):.4f}, '
f'exact sample {ks_exact(x_ref, 0.0, **uneven):.4f}')
d2l.set_figsize((5.5, 3))
d2l.plt.hist(x, bins=80, density=True, alpha=0.4, color='C1',
label='reverse-SDE samples')
d2l.plt.plot(gs, p_t(gs, 0.0, **uneven), 'k', lw=1, label='data density $p_0$')
d2l.plt.xlabel('x'); d2l.plt.ylabel('density'); d2l.plt.legend();max|p_T - N(0,1)| at T=3: 0.0145 (peak 0.40)
mass on the left: 0.800 (data 0.800)
means -1.993, +1.998 (data -2, +2)
widths 0.504, 0.509 (data 0.5)
KS to the exact p_0: sampler 0.0068, exact sample 0.0054
The sampler recovers the data. Its modes sit within about of , their widths are close to , and four fifths of the particles end on the left, to within a hundredth. This last number is the one to look at. Half of the particles started to the right of the origin, and nothing in the sampler mentions the weights except the score. Where does the score keep them? Not near . There the responsibilities in (26.5.12) are or wherever the density is not negligible, and the score is one of the two springs , whatever the weights. This is the blindness of the score to the weights of distant modes that Section 25.5.1 found. Not at either. There the two components are almost the same Gaussian, and the responsibility of the left one is close to its weight, , wherever a particle sits. But the two springs nearly coincide as well: they differ by , for component means and variance , which is at against at . Averaging two almost equal springs with the weights and gives a small steady push to the left and decides no particle's mode.
The weights act in between, while the modes separate. The two components are equally responsible at the point . A particle to the left of this point more probably came from the left component, and under the reverse process it will more probably end there. At the watershed lies at , far to the right of every particle. At it has come in to , so a particle at is still more likely to end on the left than on the right. At it sits at , in the valley, and by then the valley is empty. At high noise the weights are everywhere and decide nothing; at low noise they would decide, and no particle is there.
The start was not quite right, and it hardly mattered. With unequal weights has not forgotten the data altogether: its mean is , and the first line shows a gap of up to to , against a peak of . The noise of the reverse SDE washes most of this mismatch out: it costs about of the left mode's mass, less than the binomial noise of the printed fraction. The probability-flow ODE, which forgets nothing, would lose several times as much (Exercise 10).
The sampler is not exact, and the KS line gives no more than a hint of it. Both distances are of the order of the band. The sampler's is usually the larger, and it lands above the band in about one run in six, where an exact sample does so in one run in twenty. A single run of this size cannot tell such a sampler from an exact one. Besides the start there is a second source of error, the discretization. Euler--Maruyama has weak order one (Section 26.4.4.1), so its output carries a bias proportional to the step. The bias sits in the widths, but one run cannot measure it there: the Monte Carlo error of a width estimated from samples is the width divided by , about for the left mode with its samples and for the right mode with .
The bias can be isolated without sampling. For Gaussian data , the right mode alone, the marginal is a Gaussian with score , so every reverse step is affine in , and the mean and the variance of the sampler's state follow an exact recursion. With the slope of the reverse drift, it reads and . Started from the exact , the recursion has no error but the discretization. The cell evaluates it on uniform grids of to steps, and then spends steps in two ways: uniformly, and with of them on .
def em_reverse_width(ts, mu=2.0, v0=0.25):
"""Exact output width of reverse Euler--Maruyama on data N(mu, v0),
stepping down the time grid ts = (0, t_1, ..., T) from T to 0."""
mu, v0 = np.array([mu]), np.array([v0])
(m,), (V,) = mixture_params(ts[-1], mu, v0) # start from the exact p_T
for t, dt in zip(ts[:0:-1], np.diff(ts)[::-1]):
(mt,), (vt,) = mixture_params(t, mu, v0)
kappa = theta - g**2 / vt # slope of the reverse drift in x
m, V = (m + dt * (kappa * m + g**2 * mt / vt),
(1 + kappa * dt)**2 * V + g**2 * dt)
return np.sqrt(V)
grids = {f'{N} uniform steps': np.linspace(0, T, N + 1)
for N in (300, 600, 1200, 2400, 1500)}
grids['1500 steps, 1000 on t <= 0.5'] = np.concatenate(
[np.linspace(0, 0.5, 1001), np.linspace(0.5, T, 501)[1:]])
for name, ts in grids.items():
print(f'{name:>28}: width excess {em_reverse_width(ts) - 0.5:.4f}')
300 uniform steps: width excess 0.0096
600 uniform steps: width excess 0.0047
1200 uniform steps: width excess 0.0024
2400 uniform steps: width excess 0.0012
1500 uniform steps: width excess 0.0019
1500 steps, 1000 on t <= 0.5: width excess 0.0006
On the first four grids the width excess over is , , and : it halves when the step halves, as a first-order bias must. At steps, the grid of the sampling run, it is . This is about the excess to expect in the printed widths, and it is the size of their Monte Carlo errors: one sampling run cannot resolve it, and the recursion can.
The last two lines ask where the steps should go. Spending steps uniformly removes six tenths of the -step bias. Making the steps ten times finer on only, also steps in all, removes nearly nine tenths. A tenfold refinement divides the bias from the refined part by ten, so the drop from to says that almost all of the output's bias comes from the steps on , the last sixth of the reverse run.
Two things combine. The reverse drift is steepest there, with slope at against near , so each step errs more. And an error made early in the reverse run is contracted by every later step, through the factor of the recursion, while an error made in the last steps reaches the output as it is. For narrower data the slope grows without bound, and the step then meets the stability limit of Section 26.2.3; here we are far from it. Exercise 9 measures both effects and looks for the best placement.
All of this rested on a score we could write down. The data were a two-component mixture, and the only errors left were Euler--Maruyama's bias and the small gap between and . Real data offer no such formula, and computing from the Fokker--Planck equation is out of the question: a grid with cells per axis has unknowns, and counts pixels. The score has to be learned (Section 26.6). For images we have samples of and nothing else.
26.5.6 Summary#
The density of an SDE obeys the Fokker--Planck equation : the drift transports the density and the noise smooths it. Because , the smoothing is itself transport, with velocity , so the same density is moved by an ordinary differential equation, the probability-flow ODE . This ODE has the SDE's marginals at every time, smooth trajectories that never cross, and a likelihood. The same densities can be visited in reverse order, by a family of processes with noise and drift . One half of the score correction undoes the forward smoothing and the rest compensates the sampler's own noise, which is why Anderson's reverse SDE () carries twice the correction of the ODE (). We proved this for the marginals, given uniqueness for the Fokker--Planck equation; Anderson's theorem for the whole process is cited. Driven by the exact score, the reverse SDE turned symmetric noise into a mixture with weights and , modes and proportions alike; the proportions are decided at intermediate noise, while the modes separate. In all of these samplers the only unknown is the score .
26.5.7 Exercises#
-
Laplacian as averaging. Averaging a smooth over the sphere of radius centered at gives , as stated in Section 26.5.2.1.
- Let be uniformly distributed on the unit sphere of . Show by symmetry that , and . Use these moments in a Taylor expansion of to prove the averaging formula. Why does no term appear?
- In one dimension the sphere is the pair of points . Show that one forward-Euler step of the heat equation , with replaced by the centered difference , sets each new to a weighted combination of , and whose weights sum to one. Find the largest step for which all three weights are nonnegative. Why can the iteration then never create a new maximum?
-
Moments from the weak form. The evolution law (26.5.6) was derived for test functions that vanish outside a bounded set. Assume that it also holds for polynomial , which the Gaussian tails of this section's densities justify.
- For the one-dimensional OU process, insert and
and derive ODEs for the mean and the variance
of . Show that they are the moment ODEs
(26.5.9) for every initial law , Gaussian
or not. Check this against
mixture_paramsby computing the mean and the variance of the two-mode mixture at time . - For the linear SDE in with a constant matrix , use and to show that the mean and the covariance satisfy and . Which matrix equation must a stationary covariance solve?
- For the one-dimensional OU process, insert and
and derive ODEs for the mean and the variance
of . Show that they are the moment ODEs
(26.5.9) for every initial law , Gaussian
or not. Check this against
-
Stationary density from zero current.
- Set in the OU Fokker--Planck equation, . Integrate once in and argue from decay at infinity that the constant of integration, which is minus the probability current (26.5.20), vanishes. Solve the resulting first-order ODE and show that without assuming a Gaussian form.
- Repeat the argument for a general drift with constant , and express through a potential with . Conversely, given a density , find the drift that makes stationary and write it through the score of .
- Apply the result to the double-well drift with and find the modes of . What goes wrong for the unstable drift with ?
-
Mode merging. Consider the symmetric two-component mixture with the score (26.5.13).
- Derive (26.5.13) from the responsibility formula (26.5.12).
- Show that the score has three zeros when and only the zero when . Classify each zero as a local maximum or a local minimum of the density. (Hint: the slope at is .)
- Under the OU process the mixture stays symmetric, with component
means and the component variance computed by
mixture_params. Find the time at which stops being bimodal for the section's parameters, , , and . - What does the change at mean for a reverse-time sampler that starts from noise? (Biroli et al. (2024) analyze the high-dimensional counterpart of this symmetry breaking and call it speciation.)
-
[code] State-dependent noise. ● For an SDE with a matrix noise, write . Itô's correction is then , and two integrations by parts, , give with the current
and, dividing by , the probability-flow velocity
A constant matrix only replaces by in the score term; a state-dependent adds the last term. Now let with no drift and a smooth positive , on the circle with periodic boundaries.
- Specialize the matrix current and the general velocity above to this SDE. Show that a stationary density has constant current, that periodicity forces the constant to vanish, and find .
- Replacing the constant of (26.5.7) by gives the PDE . Which stationary density does this PDE predict?
- Simulate particles started from the uniform distribution with Euler--Maruyama, and up to , wrapping positions modulo . Compare the histogram with both predictions. Where do the particles accumulate, and why?
- [code] Fokker--Planck on a grid. ● Divide into cells of width with centers , and let approximate the density in cell . A conservative discretization of the OU equation assigns to each interior face the current
sets the current through the two outer faces to zero, and evolves . This is a linear system .
- Show that is conserved for every , the discrete counterpart of the divergence theorem (26.5.3), and say which boundary condition of Section 26.5.4 the zero outer currents impose.
- Build for , and
. Start from the two-mode mixture
p_t(x, 0.0)on the cell centers and integrate to with forward Euler at step and with backward Euler at step (onenp.linalg.solveper step). Compare both results withp_t(x, 0.5). - Increase the forward-Euler step from and find the largest step that stays stable on a run to , long enough for an unstable mode seeded by rounding error to grow. Relate this step to the most negative eigenvalue of through the bound of Section 26.2.3. How does the limit change when is halved? Compare it with the condition of Exercise 1b.
- A grid with cells per axis in dimensions has unknowns. Evaluate this count for and for , the pixel count of a image. What does it imply for how diffusion models use the Fokker--Planck equation?
Adapted from Särkkä and Solin (2019), Exercise 5.3.
-
Divergence-free velocity fields. ● Let be a constant antisymmetric matrix.
- Show that for every smooth positive density . Conclude that for every the ODE , with from (26.5.19), has the same marginals as the probability-flow ODE.
- Take the two-dimensional OU process at stationarity, for all , and . Show that the probability-flow velocity vanishes, and describe the trajectories of the modified ODE.
- Now put the rotation into the SDE itself: in . Use the covariance equation of Exercise 2b to show that is a stationary covariance for every , so that the SDE has the same stationary density as in (b). Compute its stationary current, the current (26.5.20) of this SDE. Why does the argument of Exercise 3a, which forces a stationary current to vanish, fail in two dimensions?
- Suppose that , so that is a gradient field. Among all velocity fields whose continuity equation (26.5.15) is solved by , show that has the smallest kinetic energy . The Benamou--Brenier formulation (Benamou and Brenier, 2000) minimizes the same energy over the path as well.
-
Exact Gaussian reverse step. ● Let be a Gaussian OU marginal. Over a step , the exact forward transition is with and , by the kernel (26.5.1).
- Use Gaussian conditioning to show that
Here is the marginal variance at time .
- Expand the mean and the variance to first order in , and recover the reverse step (26.5.24), including the full factor in front of the score.
-
[code] Placing the steps. ● The function
em_reverse_widthreturns the exact output width of reverse Euler--Maruyama on the data for any time grid. The text compared two grids of steps.- Start from the uniform grid of steps and make the steps ten times finer on only, for . Record the number of steps and the width excess. A tenfold refinement divides the bias from the refined part by ten. Use this to compute the share of the -step bias that comes from the steps on . How many extra steps on do the work of the extra uniform steps of the text? The text names two reasons why these steps dominate. Measure each on the uniform grid: for the single step that leaves , compute the error in that it commits when it starts from the exact , and the factor by which the later steps multiply this error before .
- With a budget of steps, try the grids for . Which gives the smallest excess? Why does a large do worse again?
- Is the bias on the squared grid, , still of first order in ? Check with , and . What has the grid changed, the order or the constant?
- Repeat (b) for narrower data, , where the slope of the reverse drift at is , and compare each excess with the target width . How does the best move? What does this suggest for data whose variance is small in some directions? (Section 17.5 crowds the steps of image samplers toward low noise with a power-law grid in the noise level.)
-
[extended] Prior mismatch, ODE versus SDE. ●● Samplers start from the reference instead of the exact . This project compares how the reverse SDE and the reverse probability-flow ODE carry that mismatch to . Use the unequal weights of the reverse sampler in Section 26.5.5, which make differ visibly from for small : pass
**uneventop_t,score_t,mixture_cdfandsample_p0, andscore=lambda x, t: score_t(x, t, **uneven)topf_velocity.- Run Anderson's reverse SDE as in the text and the reverse-time probability-flow ODE with Heun steps, both from , for with step . Record the fraction of samples with , whose target is . The SDE at is the run of the text.
- Anderson's theorem holds for the whole process: started at , the reverse SDE produces . Use this to predict the SDE's left-mode mass as an expectation over of a responsibility of ((26.5.12)). For the ODE, use that its map from to is increasing and carries to , and predict the left-mode mass from the standard normal CDF and the CDFs of and . Evaluate both predictions by quadrature and compare them with the measurements.
- Let be the law of a sampler's output. Use the data-processing inequality of Section 25.3.3 to prove that the ODE output satisfies , while the SDE output satisfies .
- Compute and the SDE's by quadrature for each . The posterior is a two-component Gaussian mixture whose components follow from Exercise 8a, so is a one-dimensional integral over . By what factor does the SDE shrink the mismatch at ?
- Repeat the measurement of (a) at for the samplers of the family (26.5.26) with . Which sampler would you use when the forward horizon must be short? What limits how large can be at a fixed step size?