29 / 34 · Diffusion Models
Continuous-time diffusion and flow matching
Let DDPM's steps shrink to zero and the noising chain becomes a stochastic differential equation. Its density equation gives a reverse-time sampler, a deterministic ODE with the same marginals, and flow matching.
On this page 7
DDPM trains with steps whose noise variances grow linearly from to . Halve every and double , and the chain destroys an image at almost the same pace. What matters is how much noise has been added by a given fraction of the way, not how that way is cut into steps.
Make this precise. Treat the schedule as a rate, on , and cut it into steps of variance . The signal coefficient halfway through is:
| Steps | at |
|---|---|
| 50 | 0.0585 |
| 200 | 0.0738 |
| 1000 | 0.0780 |
| limit | 0.0791 |
The chains converge to one continuous process. A network trained on any of them learns the score of the noised data at a noise level, as the score matching note showed, and nothing in that function refers to the step size. So why should generation use the training steps? If we knew the continuous process and how to run it backwards, any method that integrates it could generate, with a thousand small steps or twenty large ones.
Time runs from , the data, to , almost pure noise, as in the DDPM notes. We write for the density of the noised data at time , which those notes call .
From DDPM steps to a stochastic differential equation#
Write , so that the step at time has variance . One DDPM step is
where is fresh noise. The Taylor expansion turns it into an increment:
The drift is proportional to , the noise to . The square root is forced. Over a unit of time there are independent steps, and their variances add; for the total to stay finite and nonzero as , each step must have variance proportional to , hence a standard deviation proportional to .
A Wiener process (Brownian motion) is defined by exactly this: , continuous paths, and increments independent of the past. So is one increment , and the limit of DDPM’s chain is the variance-preserving SDE (Song et al., 2021, §3.4 and App. B):
The general form is , with a drift and a diffusion coefficient . Read it as shorthand for the limit of Euler–Maruyama steps, ; DDPM’s chain is such a discretization up to per step. The rigorous meaning, through Itô integrals, is in Särkkä and Solin (2019), chapter 4; Murphy (2023, §25.4.1) takes the same limit. NCSN’s chain of growing noise levels gives, since , the variance-exploding SDE .
The jump from . Take the expectation of the step given . The noise has mean zero, so the mean obeys . The variance of one coordinate is scaled by the square of the same factor and gains . Dropping terms of order and dividing by :
With , and , the solutions are and , as differentiating with confirms. Each step is linear in plus independent Gaussian noise, so given stays Gaussian:
This is DDPM’s jump to any step. The discrete product converges to the exponential because , and is a Riemann sum for . For the linear schedule , which gives , the limit in the table, and .
How densities move: the Fokker–Planck equation#
A sampler needs the density of the whole cloud of noised points, not one path. Its equation follows from one Euler–Maruyama step and a Taylor expansion. We work in one dimension.
Take any smooth test function that vanishes far away, together with its derivatives. One step moves to . Expand around to second order:
The other second-order terms carry or . Average over , which is independent of , with and , then over , and let :
Move the derivatives from to the other factor by integrating by parts, once for the first term and twice for the second; the boundary terms vanish because does. The result is for every test function, so the bracket is zero. In dimensions the same steps per coordinate give the Fokker–Planck equation:
Here is the divergence and the Laplacian. The derivation assumes a smooth density that decays at infinity with its derivatives; the rigorous version replaces the Taylor step by Itô’s formula and is Theorem 5.4 of Särkkä and Solin (2019), proved by the same test-function argument.
The first term moves probability: is a flux, mass times velocity, and its divergence is the net outflow. The second term spreads probability at the rate , as heat spreads. The Code section checks equation (2) at one point for the VP SDE: both sides are .
Two special cases are used below. With the drift the right side of (2) vanishes, because : Langevin dynamics leaves unchanged, the balance the MCMC note used. With the equation becomes the continuity equation of the ODE :
Along one trajectory of that ODE, the chain rule gives
The log-density changes at the rate minus the trace of the Jacobian of . This is the density of a neural ODE, or continuous normalizing flow: a flow whose layers have become infinitely thin, as in the flow architectures note.
The probability-flow ODE#
The diffusion term of (2) can be written as a transport term. Since ,
and the Fokker–Planck equation becomes a continuity equation:
It is the equation of the deterministic ODE
called the probability-flow ODE (Song et al., 2021, §4.3 and App. D.1). Start the ODE from the same as the SDE. The velocity is now a fixed field, built from the SDE’s densities. The density of the ODE’s points and the SDE’s both solve the continuity equation of this one field from the same initial condition, so they coincide at every if that equation has only one solution. It does when is smooth and Lipschitz in ; the argument runs through the trajectories and is folded below. The paths differ completely: the SDE moves each point at random, the ODE moves each point with the local average flow of probability, flux divided by density.
Why the continuity equation has only one solution
The tool is the Picard–Lindelöf theorem (Teschl, 2012, Theorem 2.2). Let be continuous and Lipschitz in , uniformly in : . Then the ODE started at any point has exactly one solution on some interval around the start; if the bound holds on all of , the solution exists on the whole of (Corollary 2.6 there). The intuition: two solutions from one point drift apart at most at the rate times their distance, and a distance that starts at zero and grows no faster than times itself stays zero.
So every starting point has one trajectory, and running the ODE backwards from any point at time gives one starting point: every point at time lies on exactly one trajectory. Now take any smooth solution of the continuity equation . The chain rule along a trajectory, as in the previous section, gives a linear equation for one number, which integrates in closed form:
The second line expands . The last line depends only on and the trajectory, not on which solution we took, so any two solutions agree at every point. For Gaussian data the score is affine in , so is Lipschitz; for a learned score the condition is an assumption on the network.
For the VP SDE, and ; with the score written through DDPM’s noise predictor, :
Gaussian data. Let the data be in one dimension. The noised density is Gaussian with mean and variance , and its score is . The claim is that the ODE keeps every point’s -score, . Differentiate, using and , which follow from :
The third line collects the terms in and in . For data the point , one standard deviation above the mean, travels to , one standard deviation above the noise mean . Run backwards, the ODE returns it to exactly.
What the ODE buys follows from it being deterministic. It is a bijection between noise and data, so an image can be encoded into its noise by integrating forward. Its log-likelihood is computable with the trace formula of the previous section. And any ODE solver can integrate it, with as few steps as its accuracy allows: DDIM is Euler’s method for (3) in rescaled coordinates, derived in the latent diffusion note.
Running the SDE backwards#
Generation starts at and must reach . The ODE (3) can simply be integrated from down to . Is there also a stochastic way back? Build one from the reversed ODE in two moves, with the reversed time , following Isachenko (2025, lecture 10).
- In the ODE has velocity and carries backwards along the same path of densities.
- Add a Langevin pair, the drift and the noise . By the first special case of the Fokker–Planck equation, its two terms cancel in (2), so at every moment it leaves the density where it is.
The sum is an SDE in with drift and the same densities. Written in the original time, with , it is the reverse-time SDE:
where is a Wiener process running backwards. The derivation shows that the marginals agree, which is all a sampler needs. Anderson (1982) proved more: under regularity conditions the time-reversed process itself solves (4), so its joint distributions at several times also match those of the forward process. Song et al. (2021, §3.2) state this result and build their sampler on it.
The score drift in (4) is twice the one in (3). Half of it reverses the forward spreading, as in the ODE; the other half cancels the spreading caused by the fresh noise that the reverse step adds itself.
DDPM’s sampler is this SDE. One Euler–Maruyama step of (4) for the VP SDE, from to , is . DDPM’s step in score form is (score matching note). With , and , the two agree up to .
The two samplers on a mixture. Take the data of the score matching note, , where Langevin dynamics at a single noise level put only of the chains in the left mode. Under the VP SDE each component keeps variance and only its mean shrinks, so the exact score of every is available. Start from , use Euler steps and 200,000 samples:
| Steps | SDE: share left | SDE: sd in left mode | ODE: share left | ODE: sd in left mode |
|---|---|---|---|---|
| 10 | 0.782 | 1.122 | 0.782 | 1.071 |
| 100 | 0.799 | 1.012 | 0.793 | 1.007 |
| 1000 | 0.799 | 0.999 | 0.795 | 0.994 |
Both recover the weights that a single noise level lost; the targets are and .
Where the ODE breaks: it remembers its start. The ODE stalls at however many steps it takes. The start is to blame: has component means , not exactly . The ODE is a bijection, so it carries that small error all the way to ; started from the exact , it gives . The SDE reaches from the same wrong start.
By its construction above, the reverse SDE contains a Langevin pair, which leaves in place and, run long enough at one fixed density, draws other distributions toward it under the conditions stated in the MCMC note. Here each gets only a short stretch of time, so this is a tendency, not a guarantee, and the table checks it only for an error in the start. Song et al. (2021, §4.2) use the same idea on purpose: their predictor–corrector samplers add Langevin steps after each solver step to correct the distribution of the samples. The ODE in exchange is deterministic and invertible.
Flow matching#
Diffusion fixes the path of densities through an SDE and then learns the score that drives it. Why not choose a path from data to noise directly and learn the velocity of an ODE that follows it? A network defines the ODE . If some velocity moves the density along the chosen path , the natural loss is
with uniform on . Neither nor is known in closed form. Lipman et al. (2023) build both from simple pieces.
The straight-line path. Draw an image and a noise , and move between them on a straight line:
Given , the point is , a conditional path that starts at the image and ends at noise. Averaged over images, it gives the marginal path , which is the data at and exactly at . Each point moves with constant velocity; substituting writes it as a function of the position:
Lipman et al. run time the other way, from noise at to data at , and their straight path (their Eq. 20–23) stops short of the image: it ends at with a small , so that the path has a positive density everywhere, which their Theorem 2 below assumes. With and their formulas become ours; this limit is the path of rectified flow below.
The averaged velocity moves the average path. Define the marginal velocity as the conditional one averaged over the images that could have produced , . It moves (Lipman et al., 2023, Theorem 1). The particles of each conditional path follow the ODE with velocity , so its density satisfies the continuity equation. Then:
The first line differentiates under the integral, the second uses the continuity equation of each conditional path, and the third the linearity of the divergence. The last uses Bayes’ rule, , so the integral is times the posterior average of , which is .
The conditional loss has the same gradient. The marginal velocity is still an intractable average. The conditional flow matching loss regresses on the per-sample velocity instead:
Fix and expand both squares. The terms are equal, since has the density in both. The cross terms are equal by the tower property of conditional expectation:
The remaining terms, and , do not contain . So , and the two have the same gradient and the same minimizer (Lipman et al., 2023, Theorem 2, which assumes everywhere so that is defined). The constant is the average conditional variance of given , the part of the per-sample target that no function of can predict. It is the same trick as denoising score matching: a conditional target whose regression has the marginal quantity as its minimizer.
On the mixture at , with four million samples, the two losses differ by the same amount for any :
| difference | |||
|---|---|---|---|
| the exact | 2.09 | 0 | 2.09 |
| 27.13 | 25.03 | 2.10 | |
| 18.01 | 15.91 | 2.10 |
Training is one line: draw , and , form , and regress onto . Generation draws and integrates from down to .
The same network as diffusion. The per-sample target can be written through the image alone, , so . The score of the path is an average too, , by the identity of denoising score matching. With the Gaussian conditional path:
Both are affine in the same denoiser . A flow-matching network and a diffusion network learn one function in different coordinates, and the straight line is one Gaussian path among many; the VP path of diffusion is another (Lipman et al., 2023, §4).
Where few steps break. The conditional paths are straight, the marginal ones are not: lines from different images cross, and an ODE’s trajectories cannot cross, so the averaged velocity bends them. Euler steps with the exact on the mixture:
| Steps | share left | sd in left mode | mean |
|---|---|---|---|
| 1 | 1.000 | 0.000 | −2.40 |
| 2 | 0.997 | 0.536 | −3.17 |
| 10 | 0.834 | 0.977 | −2.60 |
| 100 | 0.802 | 0.999 | −2.41 |
One step from gives . At the point is pure noise, independent of the image, so this is the data mean for every sample: one first-order step collapses the distribution, exactly as one DDIM step does.
Rectified flow (Liu, Gong and Liu, 2023) trains with the same straight-line loss and then straightens the marginal paths. Generate pairs by running the trained ODE, noise to sample , and train a new flow on these pairs in place of independent ones; this is the reflow step. The pairs are already matched by a deterministic map, so the lines between them cross less. Liu et al. prove three things. Reflow never increases convex transport costs, by Jensen’s inequality (their Theorem 3.5). A coupling is left unchanged by reflow exactly when its straight lines do not cross (Theorem 3.6). After reflows, the straightest flow so far is within of straight, in a measure of how much its paths bend (Theorem 3.7).
How straight one reflow gets is measured, not proved. The comparison also needs distillation: a final training run in which the network learns to map each noise straight to its generated sample, , with an LPIPS loss for one step. On CIFAR-10, with a single Euler step (Liu et al., Table 1(a) and App. A):
| One Euler step | FID | FID after distillation |
|---|---|---|
| first flow, no reflow | 378 | 6.18 |
| after one reflow | 12.21 | 4.85 |
| after two reflows | 8.15 | 5.21 |
Lower is better. One reflow alone takes the one-step FID from 378 to 12.21; the strong one-step result, 4.85, is one reflow plus distillation, and distillation without reflow already gives 6.18. Reflow is not free when the ODE is solved accurately: with an adaptive Runge–Kutta solver, about 100 to 130 network evaluations, FID goes from 2.58 to 3.36 after one reflow. The price in training is a second run and 4 million generated pairs per reflow.
Discrete data: diffusion over tokens#
Words and other categories cannot receive Gaussian noise. Discrete diffusion replaces the Gaussian step by a transition matrix between categories, for a one-hot (Austin et al., 2021). The uniform choice replaces a token by a random one with probability . The absorbing choice replaces it by a special [MASK] token with probability , and a masked token stays masked. A token then survives steps with probability , the same product as in the Gaussian case, and the chain ends with every position masked. Austin et al. show that the bound for the absorbing chain reduces to a reweighted masked-language-model loss. The text diffusion note of the NLP course derives that loss in continuous time and generates text by unmasking.
What you should remember#
- DDPM with discretizes ; .
- Fokker–Planck: , from a Taylor step and integration by parts.
- Probability-flow ODE: , the same marginals as the SDE, deterministic and invertible.
- Reverse SDE: ; DDPM’s sampler discretizes it, and on the mixture it corrects a start error that the ODE carries to the end.
- Flow matching regresses onto ; its gradient is that of the intractable marginal loss.
- Curved marginal paths make few steps fail: one Euler step returns the data mean.
Code#
The limit of the DDPM chains, a check of the Fokker–Planck equation, the reverse SDE and the probability-flow ODE with the exact score of a Gaussian mixture, flow matching on the same mixture, the constant gap between the conditional and the marginal loss, and the Gaussian example. NumPy only; it runs in about 30 seconds, and Monte Carlo numbers can differ slightly with the library version.
import numpy as np
beta = lambda t: 0.1 + 19.9 * t # DDPM's linear schedule in continuous time, t in [0, 1]
abar = lambda t: np.exp(-(0.1 * t + 9.95 * t ** 2)) # exp of minus the integral of beta from 0 to t
# 1. DDPM chains with T steps and beta_i = beta(i / T) / T approach the continuous abar
for T in [50, 200, 1000]:
i = np.arange(1, T // 2 + 1)
print(T, round(np.prod(1 - beta(i / T) / T), 5))
print("limit", round(abar(0.5), 5))
# 50 0.05852 / 200 0.07378 / 1000 0.078 / limit 0.07906
# data: the mixture 0.8 N(-4, 1) + 0.2 N(4, 1); under the VP SDE each component keeps variance 1
w, mu = np.array([0.8, 0.2]), np.array([-4.0, 4.0])
def p(x, t): # marginal density p_t(x)
m = np.sqrt(abar(t)) * mu
return (w * np.exp(-(x[:, None] - m) ** 2 / 2)).sum(1) / np.sqrt(2 * np.pi)
def score(x, t): # grad log p_t(x)
m = np.sqrt(abar(t)) * mu
r = w * np.exp(-(x[:, None] - m) ** 2 / 2)
return (r * (m - x[:, None])).sum(1) / r.sum(1)
# 2. Fokker-Planck check at one point: dp/dt = -d(f p)/dx + (1/2) g^2 d2p/dx2, f = -beta x / 2, g^2 = beta
x0, t0, h = np.array([1.0]), 0.3, 1e-4
lhs = (p(x0, t0 + h) - p(x0, t0 - h)) / (2 * h)
fp = lambda x: -beta(t0) * x / 2 * p(x, t0)
rhs = -(fp(x0 + h) - fp(x0 - h)) / (2 * h) + beta(t0) / 2 * (p(x0 + h, t0) - 2 * p(x0, t0) + p(x0 - h, t0)) / h ** 2
print(np.round([lhs[0], rhs[0]], 5)) # [0.31003 0.31003]
# 3. sampling with the exact score: reverse SDE and probability-flow ODE, N Euler steps from t = 1 to 0
rng = np.random.default_rng(0)
def sample(N, sde, x):
dt = 1 / N
for k in range(N, 0, -1):
t = k * dt
if sde: # dx = [f - g^2 s] dt + g dw, run with dt < 0
x = x + (beta(t) * x / 2 + beta(t) * score(x, t)) * dt + np.sqrt(beta(t) * dt) * rng.standard_normal(n)
else: # dx/dt = f - g^2 s / 2
x = x + (beta(t) * x / 2 + beta(t) * score(x, t) / 2) * dt
return x
n = 200_000
for N in [10, 100, 1000]:
for sde in [True, False]:
x = sample(N, sde, rng.standard_normal(n))
print(N, "SDE" if sde else "ODE", round((x < 0).mean(), 3), round(x[x < 0].std(), 3))
# 10 SDE 0.782 1.122 / 10 ODE 0.782 1.071 / 100 SDE 0.799 1.012 / 100 ODE 0.793 1.007
# 1000 SDE 0.799 0.999 / 1000 ODE 0.795 0.994
x1 = np.sqrt(abar(1.0)) * np.where(rng.random(n) < w[1], mu[1], mu[0]) + rng.standard_normal(n) # exact p_1
x = sample(1000, False, x1)
print("ODE from p_1", round((x < 0).mean(), 3)) # ODE from p_1 0.802
# 4. flow matching with the straight path x_t = (1 - t) x0 + t eps; exact marginal velocity u = (x - E[x0 | x_t]) / t
def velocity(x, t):
m, v = (1 - t) * mu, (1 - t) ** 2 + t ** 2 # component k of p_t: N((1 - t) mu_k, v)
r = w * np.exp(-(x[:, None] - m) ** 2 / (2 * v))
r /= r.sum(1, keepdims=True)
x0hat = (r * (mu + (1 - t) / v * (x[:, None] - m))).sum(1)
return (x - x0hat) / t
for N in [1, 2, 10, 100]:
x, dt = rng.standard_normal(100_000), 1 / N
for k in range(N, 0, -1):
x = x - velocity(x, k * dt) * dt # Euler from t = 1 down to t = 0
print(N, round((x < 0).mean(), 3), round(x[x < 0].std(), 3), round(x.mean(), 3))
# 1 1.0 0.0 -2.4 / 2 0.997 0.536 -3.174 / 10 0.834 0.977 -2.601 / 100 0.802 0.999 -2.41
# 5. the conditional and the marginal loss differ by the same constant for any v (here at t = 0.5)
n, t = 4_000_000, 0.5
comp = rng.random(n) < w[1]
xd = np.where(comp, mu[1], mu[0]) + rng.standard_normal(n)
eps = rng.standard_normal(n)
xt = (1 - t) * xd + t * eps
for v in [velocity(xt, t), 0.5 * xt, np.zeros(n)]:
L_cfm = ((v - (eps - xd)) ** 2).mean()
L_fm = ((v - velocity(xt, t)) ** 2).mean()
print(round(L_cfm, 2), round(L_fm, 2), round(L_cfm - L_fm, 2))
# 2.09 0.0 2.09 / 27.13 25.03 2.1 / 18.01 15.91 2.1
# 6. Gaussian data N(2, 0.5^2): the ODE keeps each point's z-score; x(0) = 2.5 ends at
a1 = abar(1.0)
print(f"{a1:.2e}", round(np.sqrt(a1) * 2 + np.sqrt(a1 * 0.25 + 1 - a1) / 0.5 * 0.5, 4)) # 4.32e-05 1.0131
Next#
The network of the continuous view is the same noise predictor or velocity as before, and the ODE turns sampling into a choice of solver. The next note puts these pieces to work at scale: it runs the diffusion in the latent space of an autoencoder, steers it toward a prompt with guidance, and samples it in tens of steps with DDIM, which is Euler’s method for the probability-flow ODE.
References#
- Y. Song, J. Sohl-Dickstein, D. P. Kingma, A. Kumar, S. Ermon, B. Poole. Score-Based Generative Modeling through Stochastic Differential Equations. ICLR, 2021. §3.2 (the reverse-time SDE), §3.4 and App. B (VE and VP SDEs as limits of NCSN and DDPM), §4.2 (predictor–corrector samplers), §4.3 and App. D.1 (the probability-flow ODE).
- B. D. O. Anderson. Reverse-time diffusion equation models. Stochastic Processes and their Applications, 12(3), 313–326, 1982.
- S. Särkkä, A. Solin. Applied Stochastic Differential Equations. Cambridge University Press, 2019. §2.7 (the Picard–Lindelöf theorem, stated without proof), chapter 4 (Itô calculus), Theorem 5.4 (the Fokker–Planck–Kolmogorov equation), §5.5 (means and covariances of SDE solutions).
- Y. Lipman, R. T. Q. Chen, H. Ben-Hamu, M. Nickel, M. Le. Flow Matching for Generative Modeling. ICLR, 2023. Theorems 1–2 (§3), Gaussian conditional paths and their relation to diffusion (§4).
- X. Liu, C. Gong, Q. Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. ICLR, 2023. Numbers from arXiv:2209.03003v1 (2022): Theorems 3.5–3.7 (transport costs, straight couplings, the straightening rate), Table 1(a) (CIFAR-10), App. A (reflow and distillation settings).
- G. Teschl. Ordinary Differential Equations and Dynamical Systems. American Mathematical Society, 2012. Theorem 2.2 (Picard–Lindelöf), Corollary 2.6 (existence on the whole interval under a global Lipschitz bound).
- J. Austin, D. D. Johnson, J. Ho, D. Tarlow, R. van den Berg. Structured Denoising Diffusion Models in Discrete State-Spaces. NeurIPS, 2021. §3 (transition matrices, absorbing state), §4 (the connection to masked language models).
- R. Isachenko. Deep Generative Models, MIPT and YSDA, 2025. Course repository; lecture 10 (the Fokker–Planck equation, the probability-flow ODE, the reverse SDE), lecture 11 (VE and VP SDEs, flow matching), lecture 12 (conditional flow matching, straight paths), lecture 13 (flow matching and diffusion, discrete diffusion).
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. §25.4 (continuous-time models: forward and reverse SDEs and ODEs).