Course contents 29 / 34

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 T=1000T = 1000 steps whose noise variances βt\beta_t grow linearly from 10−410^{-4} to 0.020.02. Halve every βt\beta_t and double TT, 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, β(t)=0.1+19.9 t\beta(t) = 0.1 + 19.9\, t on t∈[0,1]t \in [0, 1], and cut it into TT steps of variance βi=β(i/T)/T\beta_i = \beta(i/T)/T. The signal coefficient αˉ=∏i(1−βi)\bar\alpha = \prod_i (1 - \beta_i) halfway through is:

Steps TTαˉ\bar\alpha at t=0.5t = 0.5
500.0585
2000.0738
10000.0780
limit T→∞T \to \infty0.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 t=0t = 0, the data, to t=1t = 1, almost pure noise, as in the DDPM notes. We write ptp_t for the density of the noised data at time tt, which those notes call q(xt)q(x_t).

From DDPM steps to a stochastic differential equation#

Write Δt=1/T\Delta t = 1/T, so that the step at time tt has variance β(t) Δt\beta(t)\,\Delta t. One DDPM step is

x(t+Δt)=1−β(t)Δt  x(t)+β(t)Δt  ε,x(t + \Delta t) = \sqrt{1 - \beta(t)\Delta t}\; x(t) + \sqrt{\beta(t)\Delta t}\;\varepsilon ,

where ε∼N(0,I)\varepsilon \sim \mathcal N(0, I) is fresh noise. The Taylor expansion 1−u=1−u/2+O(u2)\sqrt{1 - u} = 1 - u/2 + O(u^2) turns it into an increment:

x(t+Δt)−x(t)=−12β(t) x(t) Δt+β(t) Δt ε+O(Δt2).\begin{aligned} x(t + \Delta t) - x(t) ={}& -\tfrac12 \beta(t)\, x(t)\, \Delta t \\ &+ \sqrt{\beta(t)}\, \sqrt{\Delta t}\, \varepsilon + O(\Delta t^2) . \end{aligned}

The drift is proportional to Δt\Delta t, the noise to Δt\sqrt{\Delta t}. The square root is forced. Over a unit of time there are 1/Δt1/\Delta t independent steps, and their variances add; for the total to stay finite and nonzero as Δt→0\Delta t \to 0, each step must have variance proportional to Δt\Delta t, hence a standard deviation proportional to Δt\sqrt{\Delta t}.

A Wiener process (Brownian motion) w(t)w(t) is defined by exactly this: w(0)=0w(0) = 0, continuous paths, and increments w(t+Δt)−w(t)∼N(0,Δt I)w(t + \Delta t) - w(t) \sim \mathcal N(0, \Delta t\, I) independent of the past. So Δt ε\sqrt{\Delta t}\,\varepsilon is one increment dwdw, and the limit of DDPM’s chain is the variance-preserving SDE (Song et al., 2021, §3.4 and App. B):

dx=−12β(t) x dt+β(t) dw.dx = -\tfrac12 \beta(t)\, x\, dt + \sqrt{\beta(t)}\, dw .

The general form is dx=f(x,t) dt+g(t) dwdx = f(x, t)\,dt + g(t)\,dw, with a drift ff and a diffusion coefficient gg. Read it as shorthand for the limit of Euler–Maruyama steps, x←x+f Δt+gΔt εx \leftarrow x + f\,\Delta t + g\sqrt{\Delta t}\,\varepsilon; DDPM’s chain is such a discretization up to O(Δt2)O(\Delta t^2) 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 xi=xi−1+σi2−σi−12 zix_i = x_{i-1} + \sqrt{\sigma_i^2 - \sigma_{i-1}^2}\, z_i of growing noise levels gives, since σi2−σi−12≈(dσ2/dt) Δt\sigma_i^2 - \sigma_{i-1}^2 \approx (d\sigma^2/dt)\,\Delta t, the variance-exploding SDE dx=dσ2/dt  dwdx = \sqrt{d\sigma^2/dt}\; dw.

The jump from x(0)x(0). Take the expectation of the step given x(0)x(0). The noise has mean zero, so the mean m(t)m(t) obeys m(t+Δt)=(1−12βΔt) m(t)m(t + \Delta t) = (1 - \frac12\beta\Delta t)\, m(t). The variance V(t)V(t) of one coordinate is scaled by the square of the same factor and gains βΔt\beta\Delta t. Dropping terms of order Δt2\Delta t^2 and dividing by Δt\Delta t:

dmdt=−12β(t) m,dVdt=β(t) (1−V).\begin{aligned} \frac{dm}{dt} &= -\tfrac12 \beta(t)\, m , \\ \frac{dV}{dt} &= \beta(t)\,\big(1 - V\big) . \end{aligned}

With m(0)=x(0)m(0) = x(0), V(0)=0V(0) = 0 and αˉ(t)=exp⁡(−∫0tβ(s) ds)\bar\alpha(t) = \exp\big(-\int_0^t \beta(s)\,ds\big), the solutions are m=αˉ(t)  x(0)m = \sqrt{\bar\alpha(t)}\; x(0) and V=1−αˉ(t)V = 1 - \bar\alpha(t), as differentiating with αˉ′=−βαˉ\bar\alpha' = -\beta\bar\alpha confirms. Each step is linear in xx plus independent Gaussian noise, so x(t)x(t) given x(0)x(0) stays Gaussian:

x(t)∣x(0)∼N(αˉ(t) x(0),  (1−αˉ(t)) I).x(t) \mid x(0) \sim \mathcal N\big(\sqrt{\bar\alpha(t)}\, x(0),\; (1 - \bar\alpha(t))\, I\big) .

This is DDPM’s jump to any step. The discrete product converges to the exponential because log⁡(1−βi)=−βi+O(Δt2)\log(1 - \beta_i) = -\beta_i + O(\Delta t^2), and ∑iβ(i/T) Δt\sum_i \beta(i/T)\,\Delta t is a Riemann sum for ∫β\int \beta. For the linear schedule ∫0tβ=0.1 t+9.95 t2\int_0^t \beta = 0.1\,t + 9.95\,t^2, which gives αˉ(0.5)=0.0791\bar\alpha(0.5) = 0.0791, the limit in the table, and αˉ(1)=4.3×10−5\bar\alpha(1) = 4.3 \times 10^{-5}.

How densities move: the Fokker–Planck equation#

A sampler needs the density ptp_t 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 φ\varphi that vanishes far away, together with its derivatives. One step moves xx to x′=x+fΔt+gΔt εx' = x + f\Delta t + g\sqrt{\Delta t}\,\varepsilon. Expand φ(x′)\varphi(x') around xx to second order:

φ(x′)=φ(x)+φ′(x) (fΔt+gΔt ε)+12φ′′(x) g2Δt ε2+o(Δt).\begin{aligned} \varphi(x') ={}& \varphi(x) + \varphi'(x)\,\big(f\Delta t + g\sqrt{\Delta t}\,\varepsilon\big) \\ &+ \tfrac12 \varphi''(x)\, g^2 \Delta t\, \varepsilon^2 + o(\Delta t) . \end{aligned}

The other second-order terms carry Δt3/2\Delta t^{3/2} or Δt2\Delta t^2. Average over ε\varepsilon, which is independent of xx, with E ε=0\mathbb E\,\varepsilon = 0 and E ε2=1\mathbb E\,\varepsilon^2 = 1, then over x∼ptx \sim p_t, and let Δt→0\Delta t \to 0:

ddt∫φ pt dx=∫(φ′f+12g2φ′′) pt dx.\frac{d}{dt} \int \varphi\, p_t\, dx = \int \Big(\varphi' f + \tfrac12 g^2 \varphi''\Big)\, p_t\, dx .

Move the derivatives from φ\varphi to the other factor by integrating by parts, once for the first term and twice for the second; the boundary terms vanish because φ\varphi does. The result is ∫φ [∂tpt+(fpt)′−12g2pt′′] dx=0\int \varphi\, \big[\partial_t p_t + (f p_t)' - \frac12 g^2 p_t''\big]\, dx = 0 for every test function, so the bracket is zero. In dd dimensions the same steps per coordinate give the Fokker–Planck equation:

∂tpt=−∇⋅(f pt)+12g(t)2 Δpt.(2)\partial_t p_t = -\nabla \cdot \big(f\, p_t\big) + \tfrac12 g(t)^2\, \Delta p_t . \tag{2}

Here ∇⋅\nabla \cdot is the divergence and Δ\Delta 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: fptf p_t is a flux, mass times velocity, and its divergence is the net outflow. The second term spreads probability at the rate 12g2\tfrac12 g^2, as heat spreads. The Code section checks equation (2) at one point for the VP SDE: both sides are 0.310030.31003.

Two special cases are used below. With the drift f=12g2∇log⁡pf = \frac12 g^2 \nabla \log p the right side of (2) vanishes, because p∇log⁡p=∇pp\nabla \log p = \nabla p: Langevin dynamics leaves pp unchanged, the balance the MCMC note used. With g=0g = 0 the equation becomes the continuity equation of the ODE dx/dt=fdx/dt = f:

∂tpt=−∇⋅(f pt).\partial_t p_t = -\nabla \cdot \big(f\, p_t\big) .

Along one trajectory of that ODE, the chain rule gives

ddtlog⁡pt(x(t))=∂tpt+f⋅∇ptpt=−∇⋅f.\begin{aligned} \frac{d}{dt} \log p_t(x(t)) &= \frac{\partial_t p_t + f \cdot \nabla p_t}{p_t} \\ &= -\nabla \cdot f . \end{aligned}

The log-density changes at the rate minus the trace of the Jacobian of ff. 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 pt∇log⁡pt=∇ptp_t \nabla \log p_t = \nabla p_t,

12g2 Δpt=∇⋅(12g2 ∇pt)=∇⋅(12g2 pt ∇log⁡pt),\begin{aligned} \tfrac12 g^2\, \Delta p_t &= \nabla \cdot \big(\tfrac12 g^2\, \nabla p_t\big) \\ &= \nabla \cdot \big(\tfrac12 g^2\, p_t\, \nabla \log p_t\big) , \end{aligned}

and the Fokker–Planck equation becomes a continuity equation:

∂tpt=−∇⋅[(f−12g2 ∇log⁡pt) pt].\partial_t p_t = -\nabla \cdot \Big[\big(f - \tfrac12 g^2\, \nabla \log p_t\big)\, p_t\Big] .

It is the equation of the deterministic ODE

  dxdt=f(x,t)−12g(t)2 ∇log⁡pt(x)  (3)\boxed{\;\frac{dx}{dt} = f(x, t) - \tfrac12 g(t)^2\, \nabla \log p_t(x)\;} \tag{3}

called the probability-flow ODE (Song et al., 2021, §4.3 and App. D.1). Start the ODE from the same p0p_0 as the SDE. The velocity v=f−12g2∇log⁡ptv = f - \frac12 g^2 \nabla \log p_t is now a fixed field, built from the SDE’s densities. The density of the ODE’s points and the SDE’s ptp_t both solve the continuity equation of this one field from the same initial condition, so they coincide at every tt if that equation has only one solution. It does when vv is smooth and Lipschitz in xx; 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 v(x,t)v(x, t) be continuous and Lipschitz in xx, uniformly in tt: ∥v(x,t)−v(y,t)∥≤L ∥x−y∥\lVert v(x, t) - v(y, t)\rVert \le L\, \lVert x - y\rVert. Then the ODE dx/dt=vdx/dt = v started at any point has exactly one solution on some interval around the start; if the bound holds on all of Rd\mathbb R^d, the solution exists on the whole of [0,1][0, 1] (Corollary 2.6 there). The intuition: two solutions from one point drift apart at most at the rate LL times their distance, and a distance that starts at zero and grows no faster than LL times itself stays zero.

So every starting point has one trajectory, and running the ODE backwards from any point at time tt gives one starting point: every point at time tt lies on exactly one trajectory. Now take any smooth solution ptp_t of the continuity equation ∂tpt=−∇⋅(v pt)\partial_t p_t = -\nabla \cdot (v\, p_t). The chain rule along a trajectory, as in the previous section, gives a linear equation for one number, which integrates in closed form:

ddt pt(x(t))=∂tpt+v⋅∇pt=−pt(x(t))  ∇⋅v,pt(x(t))=p0(x(0)) e−∫0t∇⋅v ds.\begin{aligned} \frac{d}{dt}\, p_t(x(t)) &= \partial_t p_t + v \cdot \nabla p_t \\ &= -p_t(x(t))\; \nabla \cdot v , \\ p_t(x(t)) &= p_0(x(0))\, e^{-\int_0^t \nabla \cdot v\, ds} . \end{aligned}

The second line expands ∇⋅(v pt)=v⋅∇pt+pt ∇⋅v\nabla \cdot (v\, p_t) = v \cdot \nabla p_t + p_t\, \nabla \cdot v. The last line depends only on p0p_0 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 xx, so vv is Lipschitz; for a learned score the condition is an assumption on the network.

For the VP SDE, f=−12βxf = -\frac12\beta x and g2=βg^2 = \beta; with the score written through DDPM’s noise predictor, ∇log⁡pt≈−εθ/1−αˉ\nabla \log p_t \approx -\varepsilon_\theta / \sqrt{1 - \bar\alpha}:

dxdt=−12β(t) [x+∇log⁡pt(x)]≈−12β(t) [x−εθ(x,t)1−αˉ(t)].\begin{aligned} \frac{dx}{dt} &= -\tfrac12 \beta(t)\, \big[x + \nabla \log p_t(x)\big] \\ &\approx -\tfrac12 \beta(t)\, \Big[x - \frac{\varepsilon_\theta(x, t)}{\sqrt{1 - \bar\alpha(t)}}\Big] . \end{aligned}

Gaussian data. Let the data be N(μ0,v0)\mathcal N(\mu_0, v_0) in one dimension. The noised density is Gaussian with mean mt=αˉ μ0m_t = \sqrt{\bar\alpha}\,\mu_0 and variance Vt=αˉv0+1−αˉV_t = \bar\alpha v_0 + 1 - \bar\alpha, and its score is −(x−mt)/Vt-(x - m_t)/V_t. The claim is that the ODE keeps every point’s zz-score, x(t)=mt+Vt/v0 (x(0)−μ0)x(t) = m_t + \sqrt{V_t / v_0}\,\big(x(0) - \mu_0\big). Differentiate, using mt′=−12βmtm_t' = -\frac12\beta m_t and Vt′=β(1−Vt)V_t' = \beta(1 - V_t), which follow from αˉ′=−βαˉ\bar\alpha' = -\beta\bar\alpha:

dxdt=mt′+Vt′2Vt (x−mt)=−12β mt+12β 1−VtVt (x−mt)=−12β [x−x−mtVt]=−12β [x+∇log⁡pt(x)].\begin{aligned} \frac{dx}{dt} &= m_t' + \frac{V_t'}{2 V_t}\,(x - m_t) \\ &= -\tfrac12 \beta\, m_t + \tfrac12 \beta\, \frac{1 - V_t}{V_t}\,(x - m_t) \\ &= -\tfrac12 \beta\, \Big[x - \frac{x - m_t}{V_t}\Big] \\ &= -\tfrac12 \beta\, \big[x + \nabla \log p_t(x)\big] . \end{aligned}

The third line collects the terms in mtm_t and in x−mtx - m_t. For data N(2,0.52)\mathcal N(2, 0.5^2) the point x(0)=2.5x(0) = 2.5, one standard deviation above the mean, travels to x(1)=1.013x(1) = 1.013, one standard deviation above the noise mean 0.0130.013. Run backwards, the ODE returns it to 2.52.5 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 p1≈N(0,I)p_1 \approx \mathcal N(0, I) and must reach p0p_0. The ODE (3) can simply be integrated from t=1t = 1 down to 00. Is there also a stochastic way back? Build one from the reversed ODE in two moves, with the reversed time τ=1−t\tau = 1 - t, following Isachenko (2025, lecture 10).

  1. In τ\tau the ODE has velocity −(f−12g2∇log⁡pt)-\big(f - \frac12 g^2 \nabla \log p_t\big) and carries ptp_t backwards along the same path of densities.
  2. Add a Langevin pair, the drift 12g2∇log⁡pt\frac12 g^2 \nabla \log p_t and the noise g dwg\,dw. By the first special case of the Fokker–Planck equation, its two terms cancel in (2), so at every moment it leaves the density ptp_t where it is.

The sum is an SDE in τ\tau with drift −f+g2∇log⁡pt-f + g^2 \nabla \log p_t and the same densities. Written in the original time, with dt<0dt < 0, it is the reverse-time SDE:

dx=[f(x,t)−g(t)2 ∇log⁡pt(x)] dt+g(t) dwˉ,(4)dx = \big[f(x, t) - g(t)^2\, \nabla \log p_t(x)\big]\, dt + g(t)\, d\bar w , \tag{4}

where wˉ\bar w 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 tt to t−Δtt - \Delta t, is x+12βx Δt+β ∇log⁡pt Δt+βΔt  zx + \frac12\beta x\,\Delta t + \beta\, \nabla\log p_t\, \Delta t + \sqrt{\beta\Delta t}\; z. DDPM’s step in score form is (x+βt sθ)/1−βt+σtz\big(x + \beta_t\, s_\theta\big)/\sqrt{1 - \beta_t} + \sigma_t z (score matching note). With βt=βΔt\beta_t = \beta\Delta t, σt2=βt\sigma_t^2 = \beta_t and 1/1−βt=1+12βt+O(βt2)1/\sqrt{1 - \beta_t} = 1 + \frac12\beta_t + O(\beta_t^2), the two agree up to O(Δt2)O(\Delta t^2).

The two samplers on a mixture. Take the data of the score matching note, p0=0.8 N(−4,1)+0.2 N(4,1)p_0 = 0.8\,\mathcal N(-4, 1) + 0.2\,\mathcal N(4, 1), where Langevin dynamics at a single noise level put only 0.520.52 of the chains in the left mode. Under the VP SDE each component keeps variance 11 and only its mean shrinks, so the exact score of every ptp_t is available. Start from N(0,1)\mathcal N(0, 1), use NN Euler steps and 200,000 samples:

Steps NNSDE: share leftSDE: sd in left modeODE: share leftODE: sd in left mode
100.7821.1220.7821.071
1000.7991.0120.7931.007
10000.7990.9990.7950.994

Both recover the weights that a single noise level lost; the targets are 0.80.8 and 11.

Where the ODE breaks: it remembers its start. The ODE stalls at 0.7950.795 however many steps it takes. The start is to blame: p1p_1 has component means ±4αˉ(1)=±0.026\pm 4\sqrt{\bar\alpha(1)} = \pm 0.026, not exactly N(0,1)\mathcal N(0, 1). The ODE is a bijection, so it carries that small error all the way to t=0t = 0; started from the exact p1p_1, it gives 0.8020.802. The SDE reaches 0.7990.799 from the same wrong start.

By its construction above, the reverse SDE contains a Langevin pair, which leaves ptp_t 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 ptp_t 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 vθ(x,t)v_\theta(x, t) defines the ODE dx/dt=vθdx/dt = v_\theta. If some velocity utu_t moves the density along the chosen path ptp_t, the natural loss is

LFM(θ)=Et,  x∼pt∥vθ(x,t)−ut(x)∥2,\mathcal L_{\text{FM}}(\theta) = \mathbb E_{t,\; x \sim p_t} \big\lVert v_\theta(x, t) - u_t(x)\big\rVert^2 ,

with tt uniform on [0,1][0, 1]. Neither ptp_t nor utu_t is known in closed form. Lipman et al. (2023) build both from simple pieces.

The straight-line path. Draw an image x0x_0 and a noise ε∼N(0,I)\varepsilon \sim \mathcal N(0, I), and move between them on a straight line:

xt=(1−t) x0+t ε.x_t = (1 - t)\, x_0 + t\, \varepsilon .

Given x0x_0, the point xtx_t is N((1−t) x0,  t2I)\mathcal N\big((1 - t)\, x_0,\; t^2 I\big), a conditional path that starts at the image and ends at noise. Averaged over images, it gives the marginal path ptp_t, which is the data at t=0t = 0 and exactly N(0,I)\mathcal N(0, I) at t=1t = 1. Each point moves with constant velocity; substituting ε=(xt−(1−t) x0)/t\varepsilon = (x_t - (1 - t)\,x_0)/t writes it as a function of the position:

dxtdt=ε−x0=xt−x0t=:ut(xt∣x0).\begin{aligned} \frac{dx_t}{dt} &= \varepsilon - x_0 \\ &= \frac{x_t - x_0}{t} =: u_t(x_t \mid x_0) . \end{aligned}

Lipman et al. run time the other way, from noise at 00 to data at 11, and their straight path (their Eq. 20–23) stops short of the image: it ends at N(x0,σmin⁡2I)\mathcal N(x_0, \sigma_{\min}^2 I) with a small σmin⁡>0\sigma_{\min} > 0, so that the path has a positive density everywhere, which their Theorem 2 below assumes. With σmin⁡=0\sigma_{\min} = 0 and t↦1−tt \mapsto 1 - t 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 xx, ut(x)=E[ε−x0∣xt=x]u_t(x) = \mathbb E[\varepsilon - x_0 \mid x_t = x]. It moves ptp_t (Lipman et al., 2023, Theorem 1). The particles of each conditional path follow the ODE with velocity ut(x∣x0)u_t(x \mid x_0), so its density satisfies the continuity equation. Then:

∂tpt(x)=∫∂tpt(x∣x0) p(x0) dx0=−∫∇⋅(ut(x∣x0) pt(x∣x0)) p(x0) dx0=−∇⋅∫ut(x∣x0) pt(x∣x0) p(x0) dx0=−∇⋅(ut(x) pt(x)).\begin{aligned} \partial_t p_t(x) &= \int \partial_t p_t(x \mid x_0)\, p(x_0)\, dx_0 \\ &= -\int \nabla \cdot \big(u_t(x \mid x_0)\, p_t(x \mid x_0)\big)\, p(x_0)\, dx_0 \\ &= -\nabla \cdot \int u_t(x \mid x_0)\, p_t(x \mid x_0)\, p(x_0)\, dx_0 \\ &= -\nabla \cdot \big(u_t(x)\, p_t(x)\big) . \end{aligned}

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, pt(x∣x0) p(x0)=p(x0∣xt=x) pt(x)p_t(x \mid x_0)\, p(x_0) = p(x_0 \mid x_t = x)\, p_t(x), so the integral is pt(x)p_t(x) times the posterior average of ut(x∣x0)u_t(x \mid x_0), which is ut(x)u_t(x).

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:

LCFM(θ)=Et, x0, ε∥vθ(xt,t)−(ε−x0)∥2.\mathcal L_{\text{CFM}}(\theta) = \mathbb E_{t,\, x_0,\, \varepsilon} \big\lVert v_\theta(x_t, t) - (\varepsilon - x_0)\big\rVert^2 .

Fix tt and expand both squares. The terms E∥vθ∥2\mathbb E\lVert v_\theta\rVert^2 are equal, since xtx_t has the density ptp_t in both. The cross terms are equal by the tower property of conditional expectation:

E[vθ(xt)⊤(ε−x0)]=E[vθ(xt)⊤ E[ε−x0∣xt]]=Ex∼pt[vθ(x)⊤ut(x)].\begin{aligned} \mathbb E\big[v_\theta(x_t)^\top (\varepsilon - x_0)\big] &= \mathbb E\Big[v_\theta(x_t)^\top\, \mathbb E\big[\varepsilon - x_0 \mid x_t\big]\Big] \\ &= \mathbb E_{x \sim p_t}\big[v_\theta(x)^\top u_t(x)\big] . \end{aligned}

The remaining terms, E∥ε−x0∥2\mathbb E\lVert\varepsilon - x_0\rVert^2 and E∥ut∥2\mathbb E\lVert u_t\rVert^2, do not contain θ\theta. So LCFM=LFM+C\mathcal L_{\text{CFM}} = \mathcal L_{\text{FM}} + C, and the two have the same gradient and the same minimizer (Lipman et al., 2023, Theorem 2, which assumes pt>0p_t > 0 everywhere so that utu_t is defined). The constant is the average conditional variance of ε−x0\varepsilon - x_0 given xtx_t, the part of the per-sample target that no function of xtx_t 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 t=0.5t = 0.5, with four million samples, the two losses differ by the same amount for any vv:

vvLCFM\mathcal L_{\text{CFM}}LFM\mathcal L_{\text{FM}}difference
the exact utu_t2.0902.09
0.5 x0.5\, x27.1325.032.10
0018.0115.912.10

Training is one line: draw x0x_0, ε\varepsilon and tt, form xtx_t, and regress vθ(xt,t)v_\theta(x_t, t) onto ε−x0\varepsilon - x_0. Generation draws x(1)∼N(0,I)x(1) \sim \mathcal N(0, I) and integrates dx/dt=vθdx/dt = v_\theta from t=1t = 1 down to 00.

The same network as diffusion. The per-sample target can be written through the image alone, ut(x∣x0)=(x−x0)/tu_t(x \mid x_0) = (x - x_0)/t, so ut(x)=(x−E[x0∣xt=x])/tu_t(x) = \big(x - \mathbb E[x_0 \mid x_t = x]\big)/t. The score of the path is an average too, ∇log⁡pt(x)=E[∇xlog⁡pt(x∣x0)∣xt=x]\nabla \log p_t(x) = \mathbb E\big[\nabla_x \log p_t(x \mid x_0) \mid x_t = x\big], by the identity ∇pt=∫∇pt(x∣x0) p(x0) dx0\nabla p_t = \int \nabla p_t(x \mid x_0)\, p(x_0)\, dx_0 of denoising score matching. With the Gaussian conditional path:

ut(x)=x−E[x0∣x]t,∇log⁡pt(x)=−x−(1−t) E[x0∣x]t2.\begin{aligned} u_t(x) &= \frac{x - \mathbb E[x_0 \mid x]}{t} , \\ \nabla \log p_t(x) &= -\frac{x - (1 - t)\, \mathbb E[x_0 \mid x]}{t^2} . \end{aligned}

Both are affine in the same denoiser E[x0∣xt]\mathbb E[x_0 \mid x_t]. 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 utu_t on the mixture:

Stepsshare leftsd in left modemean
11.0000.000−2.40
20.9970.536−3.17
100.8340.977−2.60
1000.8020.999−2.41

One step from t=1t = 1 gives x−u1(x)=E[x0∣x1]x - u_1(x) = \mathbb E[x_0 \mid x_1]. At t=1t = 1 the point is pure noise, independent of the image, so this is the data mean −2.4-2.4 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 ε\varepsilon to sample x^0\hat x_0, 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 kk reflows, the straightest flow so far is within O(1/k)O(1/k) 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 ε\varepsilon straight to its generated sample, x^0=ε−v(ε,1)\hat x_0 = \varepsilon - v(\varepsilon, 1), 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 stepFIDFID after distillation
first flow, no reflow3786.18
after one reflow12.214.85
after two reflows8.155.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, q(xt∣xt−1)=Cat(Qt xt−1)q(x_t \mid x_{t-1}) = \mathrm{Cat}(Q_t\, x_{t-1}) for a one-hot xx (Austin et al., 2021). The uniform choice replaces a token by a random one with probability βt\beta_t. The absorbing choice replaces it by a special [MASK] token with probability βt\beta_t, and a masked token stays masked. A token then survives tt steps with probability ∏s≤t(1−βs)\prod_{s \le t}(1 - \beta_s), the same product αˉt\bar\alpha_t 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 βi=β(t) Δt\beta_i = \beta(t)\,\Delta t discretizes dx=−12βx dt+β dwdx = -\frac12\beta x\,dt + \sqrt\beta\,dw; αˉ(t)=e−∫0tβ\bar\alpha(t) = e^{-\int_0^t \beta}.
  • Fokker–Planck: ∂tp=−∇⋅(fp)+12g2Δp\partial_t p = -\nabla \cdot (f p) + \frac12 g^2 \Delta p, from a Taylor step and integration by parts.
  • Probability-flow ODE: dx/dt=f−12g2∇log⁡ptdx/dt = f - \frac12 g^2 \nabla \log p_t, the same marginals as the SDE, deterministic and invertible.
  • Reverse SDE: dx=[f−g2∇log⁡pt] dt+g dwˉdx = [f - g^2 \nabla \log p_t]\,dt + g\,d\bar w; DDPM’s sampler discretizes it, and on the mixture it corrects a start error that the ODE carries to the end.
  • Flow matching regresses vθ((1−t)x0+tε,t)v_\theta\big((1 - t)x_0 + t\varepsilon, t\big) onto ε−x0\varepsilon - x_0; 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#