26.7 Flow Matching and Optimal Transport

The samplers of the previous section call the score once per step, a thousand times for the reverse chain and a few dozen for its deterministic strides. They need so many steps because the paths from noise to data curve, and a solver can follow a curved path only in short pieces. Nobody designed those paths. They came with the noising process. Could we choose the path from noise to data ourselves, and choose one along which a solver can take long steps?

Picture two data points at −2-2 and +2+2 and a cloud of Gaussian noise that must end on them. If every particle moved in a straight line at constant speed toward its own point, one Euler step of length one would carry it there exactly. But a velocity field is one function of position and time. Particles bound for different points pass through the same place, and the field there can point only one way.

Flow matching (Lipman et al., 2023) and rectified flow (Liu et al., 2023) do choose: they prescribe the path and learn only the velocity that moves mass along it. Which paths are cheapest is a much older question, the problem of optimal transport. Gaspard Monge asked it in 1781 about moving a pile of earth into a hole, and under squared distance the cheapest motion turns out to be the one we just wished for, every particle on a straight line at constant speed (McCann, 1997; Benamou and Brenier, 2000).

One regression trains the velocity of any path assembled from simple pieces, because that velocity is an average over particles and least squares learns averages (Section 26.7.1). Straight pieces still give a curved flow. Re-pairing noise with data straightens it (Section 26.7.2), and optimal transport says what the re-pairing aims at (Section 26.7.3). Two parts can wait for a second reading: the conversions between score, noise and velocity that follow the definition of the Gaussian path in Section 26.7.1.3, and the solver comparison of Section 26.7.4.

Figure 26.7.1:

One clock and the papers' clock. This book (top) puts the data at t=0t = 0 and the noise at t=1t = 1, noises the data forward in time, and samples by integrating a score or a velocity from 11 to 00. The flow-matching papers (bottom) put the noise at 00 and the data at 11 and sample forward. The endpoint densities are the same; the substitution t↦1−tt \mapsto 1 - t converts one clock into the other and flips the sign of every velocity.

The data are x0∼p0\mathbf{x}_0 \sim p_0, and ptp_t is a path of densities from p0p_0 to the noise p1=N(0,I)p_1 = \mathcal{N}(\mathbf{0}, \mathbf{I}). A sample from the noise end has two names: ϵ\boldsymbol{\epsilon} when it is Gaussian noise, as in the previous section, and x1\mathbf{x}_1 in statements about pairings, which hold for any two endpoint laws.

26.7.1 Flow Matching#

26.7.1.1 Probability Paths and Velocity Fields#

Diffusion got its path from a noising process and then had to learn the score to run that process backward. Here the path is ours to choose. A probability path is a family of densities (pt)t∈[0,1](p_t)_{t \in [0, 1]} with p0p_0 the data and p1p_1 the noise. A velocity field ut\mathbf{u}_t realizes the path if the pair satisfies the continuity equation of Section 26.5.4, which says that a density moved by a velocity field changes by the net inflow of mass,

∂tpt+∇⋅(pt ut)=0.\partial_t p_t + \nabla \cdot (p_t\, \mathbf{u}_t) = 0 .

Then, for a Lipschitz field, integrating x˙=ut(x)\dot{\mathbf{x}} = \mathbf{u}_t(\mathbf{x}) from a sample of p1p_1 at t=1t = 1 down to t=0t = 0 yields a sample of ptp_t at every time, and of the data at t=0t = 0. Note the direction. The field points the way the noising goes, from data toward noise, and a sampler steps against it. If a network uθ(x,t)\mathbf{u}_{\boldsymbol{\theta}}(\mathbf{x}, t) approximates ut\mathbf{u}_t, generation is an ODE solve from noise. Such a model is a continuous normalizing flow (Section 26.3.3) run backward in time: its flow map from t=1t = 1 to t=0t = 0 is the generator. Flow matching trains it without solving the ODE even once. The natural objective is the flow-matching loss

LFM(θ)=Et∼U[0,1], x∼pt[ ∥uθ(x,t)−ut(x)∥2].(26.7.1)\mathcal{L}_{\mathrm{FM}}(\boldsymbol{\theta}) = \mathbb{E}_{t \sim \mathcal{U}[0,1],\ \mathbf{x} \sim p_t} \left[\, \left\| \mathbf{u}_{\boldsymbol{\theta}}(\mathbf{x}, t) - \mathbf{u}_t(\mathbf{x}) \right\|^2 \right]. \tag{26.7.1}

It is the mean squared error of the network against the true velocity, averaged over time and over the cloud. As it stands it is of no use, because it regresses on a field we cannot evaluate: ut\mathbf{u}_t depends on the whole data distribution.

We therefore build the path out of pieces we can write down. Let a conditioning variable z\mathbf{z}, drawn from a law qq, be a data point, or a pair of a noise point and a data point. For each value of z\mathbf{z}, pick a small moving blob pt(x∣z)p_t(\mathbf{x} \mid \mathbf{z}) that sits on the data point at t=0t = 0 and ends in the noise at t=1t = 1: spread over all of it if z\mathbf{z} is a data point, on its own noise point if z\mathbf{z} is a pair. Each blob comes with a velocity ut(x∣z)\mathbf{u}_t(\mathbf{x} \mid \mathbf{z}) that we know in closed form. The path is the mixture of the blobs, pt(x)=∫pt(x∣z) q(z) dzp_t(\mathbf{x}) = \int p_t(\mathbf{x} \mid \mathbf{z})\, q(\mathbf{z})\, d\mathbf{z}, and we write xt\mathbf{x}_t for a particle of it: draw z\mathbf{z} from qq, then a point of its blob at time tt. Which velocity moves the mixture? Everything in this section rests on the answer.

Proposition (the marginal velocity is a posterior mean). Suppose that for each z\mathbf{z} the density pt(⋅∣z)p_t(\cdot \mid \mathbf{z}) is positive and continuously differentiable in (x,t)(\mathbf{x}, t), that it satisfies the continuity equation ∂tpt(x∣z)=−∇⋅(pt(x∣z) ut(x∣z))\partial_t p_t(\mathbf{x} \mid \mathbf{z}) = -\nabla \cdot \left( p_t(\mathbf{x} \mid \mathbf{z})\, \mathbf{u}_t(\mathbf{x} \mid \mathbf{z}) \right) with a continuously differentiable velocity, and that the integrals below may be differentiated under the integral sign. Define on {pt>0}\{p_t > 0\} the marginal velocity

ut(x)=E[ut(x∣z)∣xt=x]=∫ut(x∣z) pt(x∣z) q(z)pt(x) dz.(26.7.2)\mathbf{u}_t(\mathbf{x}) = \mathbb{E}\left[ \mathbf{u}_t(\mathbf{x} \mid \mathbf{z}) \mid \mathbf{x}_t = \mathbf{x} \right] = \int \mathbf{u}_t(\mathbf{x} \mid \mathbf{z})\, \frac{p_t(\mathbf{x} \mid \mathbf{z})\, q(\mathbf{z})}{p_t(\mathbf{x})}\, d\mathbf{z}. \tag{26.7.2}

Then (pt,ut)(p_t, \mathbf{u}_t) satisfies the continuity equation.

The velocity of the cloud at x\mathbf{x} is the average of the velocities of the blobs that could have put a particle at x\mathbf{x}, each weighted by how likely it is to have done so.

Proof. Differentiate the mixture under the integral sign, substitute the conditional continuity equation, and pull the divergence out of the integral:

∂tpt(x)=∫∂tpt(x∣z) q(z) dz=−∇⋅∫pt(x∣z) ut(x∣z) q(z) dz=−∇⋅(pt(x) ut(x)).\begin{aligned} \partial_t p_t(\mathbf{x}) &= \int \partial_t p_t(\mathbf{x} \mid \mathbf{z})\, q(\mathbf{z})\, d\mathbf{z} \\ &= -\nabla \cdot \int p_t(\mathbf{x} \mid \mathbf{z})\, \mathbf{u}_t(\mathbf{x} \mid \mathbf{z})\, q(\mathbf{z})\, d\mathbf{z} = -\nabla \cdot \left( p_t(\mathbf{x})\, \mathbf{u}_t(\mathbf{x}) \right). \end{aligned}

The last step multiplies and divides by pt(x)p_t(\mathbf{x}) and recognizes (26.7.2). ■\blacksquare

Where only one blob passes, the marginal velocity is that blob's velocity. Where several pass, it is their average, and this averaging is what will bend the flow.

26.7.1.2 The Conditional Flow Matching Theorem#

The target of (26.7.1) is the posterior mean (26.7.2) of a quantity we can compute for every sample. By the regression lemma (Section 26.6.1.2), least squares against a per-sample target fits its conditional mean. We may therefore regress on the per-sample quantity, which is what the conditional flow matching (CFM) loss does:

LCFM(θ)=Et, z∼q, x∼pt(⋅∣z)[ ∥uθ(x,t)−ut(x∣z)∥2].(26.7.3)\mathcal{L}_{\mathrm{CFM}}(\boldsymbol{\theta}) = \mathbb{E}_{t,\ \mathbf{z} \sim q,\ \mathbf{x} \sim p_t(\cdot \mid \mathbf{z})} \left[\, \left\| \mathbf{u}_{\boldsymbol{\theta}}(\mathbf{x}, t) - \mathbf{u}_t(\mathbf{x} \mid \mathbf{z}) \right\|^2 \right]. \tag{26.7.3}

It needs only a sample of (t,z,x)(t, \mathbf{z}, \mathbf{x}) and the closed-form conditional velocity.

Theorem (CFM trains the marginal field). Let ut\mathbf{u}_t be the marginal velocity (26.7.2) and suppose that E∥ut(x∣z)∥2<∞\mathbb{E}\|\mathbf{u}_t(\mathbf{x} \mid \mathbf{z})\|^2 \lt \infty. Then

LCFM(θ)=LFM(θ)+C\mathcal{L}_{\mathrm{CFM}}(\boldsymbol{\theta}) = \mathcal{L}_{\mathrm{FM}}(\boldsymbol{\theta}) + C

with CC independent of θ\boldsymbol{\theta}. In particular the two objectives have the same gradients and the same minimizers (Lipman et al., 2023; Tong et al., 2024).

Proof. Apply the regression lemma with X=(x,t)X = (\mathbf{x}, t), where x∼pt(⋅∣z)\mathbf{x} \sim p_t(\cdot \mid \mathbf{z}), and Y=ut(x∣z)Y = \mathbf{u}_t(\mathbf{x} \mid \mathbf{z}), which is square-integrable by hypothesis. The law of XX is t∼U[0,1]t \sim \mathcal{U}[0,1] and x∼pt\mathbf{x} \sim p_t, and the conditional mean of YY given XX is the marginal velocity, by its definition (26.7.2). The lemma splits LCFM\mathcal{L}_{\mathrm{CFM}} into E∥uθ(X)−ut(x)∥2=LFM\mathbb{E}\| \mathbf{u}_{\boldsymbol{\theta}}(X) - \mathbf{u}_t(\mathbf{x}) \|^2 = \mathcal{L}_{\mathrm{FM}} and C=E∥Y−ut(x)∥2C = \mathbb{E}\| Y - \mathbf{u}_t(\mathbf{x}) \|^2, which does not involve θ\boldsymbol{\theta}. ■\blacksquare

The proof is one line because the lemma does the work, and the theorem needs no hypothesis on the path beyond a square-integrable target. It says only that the regression has the right minimizer. That this minimizer carries p1p_1 to p0p_0, when integrated from t=1t = 1 to t=0t = 0, is what the proposition before it guarantees. The constant CC is the conditional variance of the target. It measures how much the per-sample velocities through a point disagree, so the CFM loss of a perfect field equals CC, not zero. We call CC the floor of the loss. Denoising score matching has the same structure, with the score of the noising kernel as the per-sample quantity and the marginal score as its posterior mean.

No solver appears in this loss, and no trajectory is integrated during training. The model of Section 26.3.1 that was trained through ten Euler steps hit its targets with ten steps and missed them when it was integrated more finely: it had fitted a program of ten steps. What this regression fits is a field, and the number of steps is chosen afterwards.

26.7.1.3 Score, Noise, and Velocity#

The marginal-velocity proposition asks for blobs with known velocities, and so far we have named none. The first family is one we already own. The Gaussian paths of the previous section are probability paths of this kind, and on them the velocity is not a new object. Suppose a network has been trained to predict the noise, as diffusion models are. Do we need a second training run to obtain a velocity? We do not. The score, the noise, the clean point and the velocity are affine functions of one posterior mean, and a network that has learned the noise has learned the other three.

Condition on a data point, z=x0\mathbf{z} = \mathbf{x}_0, and take the path

xt=αt x0+σt ϵ,ϵ∼N(0,I),(26.7.4)\mathbf{x}_t = \alpha_t\, \mathbf{x}_0 + \sigma_t\, \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), \tag{26.7.4}

with smooth coefficients (αt,σt)(\alpha_t, \sigma_t), (α0,σ0)=(1,0)(\alpha_0, \sigma_0) = (1, 0) and (α1,σ1)=(0,1)(\alpha_1, \sigma_1) = (0, 1). The blob around αtx0\alpha_t \mathbf{x}_0 has width σt\sigma_t: at t=0t = 0 it is the data point, at t=1t = 1 the noise. This is the noising kernel of the previous section, with the noise end placed at t=1t = 1.

Let us start with the smallest case, Gaussian data x0∼N(0,s02)x_0 \sim \mathcal{N}(0, s_0^2) in one dimension on the cosine path αt=cos⁡πt2\alpha_t = \cos\frac{\pi t}{2}, σt=sin⁡πt2\sigma_t = \sin\frac{\pi t}{2}. The marginal is N(0,st2)\mathcal{N}(0, s_t^2) with st2=αt2s02+σt2s_t^2 = \alpha_t^2 s_0^2 + \sigma_t^2, the score is −x/st2-x/s_t^2, and the velocity is ut(x)=(s˙t/st) xu_t(x) = (\dot{s}_t/s_t)\, x: a Gaussian cloud only stretches or shrinks (Exercise 3). With s0=2s_0 = 2 at t=12t = \tfrac12 we get st2=2.5s_t^2 = 2.5, and a particle at xx has velocity −0.94 x-0.94\, x. The field points inward because noising shrinks this cloud, from width 22 at t=0t = 0 to width 11 at t=1t = 1. A sampler runs against it and stretches the cloud back to width 22. With s0=1s_0 = 1 every ptp_t is the standard Gaussian and the cloud never moves: u≡0u \equiv 0.

Proposition (score–velocity identity). For the Gaussian path (26.7.4), at any tt with αt,σt>0\alpha_t, \sigma_t > 0 and on {pt>0}\{p_t > 0\}, the marginal velocity is an affine function of the marginal score:

ut(x)=α˙tαt x−(σtσ˙t−σt2 α˙tαt)∇log⁡pt(x).(26.7.5)\mathbf{u}_t(\mathbf{x}) = \frac{\dot{\alpha}_t}{\alpha_t}\, \mathbf{x} - \left( \sigma_t \dot{\sigma}_t - \sigma_t^2\, \frac{\dot{\alpha}_t}{\alpha_t} \right) \nabla \log p_t(\mathbf{x}). \tag{26.7.5}

The velocity is a multiple of the position plus a multiple of the score, and the schedule alone fixes both multiples. The data enter only through the score. The bracket in front of the score equals σt2 ddtlog⁡(σt/αt)\sigma_t^2\, \frac{d}{dt} \log(\sigma_t/\alpha_t), which is positive whenever the ratio of noise to signal is growing, as it is on every path we use. The identity can then be solved for the score, and each field determines the other.

Proof. We show that both sides are affine in one posterior mean, x^0=E[x0∣xt=x]\hat{\mathbf{x}}_0 = \mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t = \mathbf{x}]. Differentiating the path gives the conditional velocity x˙t=α˙tx0+σ˙tϵ\dot{\mathbf{x}}_t = \dot{\alpha}_t \mathbf{x}_0 + \dot{\sigma}_t \boldsymbol{\epsilon}, and ϵ=(x−αtx0)/σt\boldsymbol{\epsilon} = (\mathbf{x} - \alpha_t \mathbf{x}_0)/\sigma_t. Taking the posterior mean as in (26.7.2),

ut(x)=σ˙tσt x+(α˙t−αt σ˙tσt)x^0.\mathbf{u}_t(\mathbf{x}) = \frac{\dot{\sigma}_t}{\sigma_t}\, \mathbf{x} + \left( \dot{\alpha}_t - \alpha_t\, \frac{\dot{\sigma}_t}{\sigma_t} \right) \hat{\mathbf{x}}_0.

The marginal score is the posterior mean of the scores of the kernels, which is Tweedie's formula of the previous section. The kernel N(αtx0,σt2I)\mathcal{N}(\alpha_t \mathbf{x}_0, \sigma_t^2 \mathbf{I}) has score (αtx0−x)/σt2(\alpha_t \mathbf{x}_0 - \mathbf{x})/\sigma_t^2, so

∇log⁡pt(x)=E[αtx0−xσt2 | xt=x]=αtx^0−xσt2,x^0=x+σt2 ∇log⁡pt(x)αt.\begin{aligned} \nabla \log p_t(\mathbf{x}) &= \mathbb{E}\left[ \frac{\alpha_t \mathbf{x}_0 - \mathbf{x}}{\sigma_t^2} \,\middle|\, \mathbf{x}_t = \mathbf{x} \right] = \frac{\alpha_t \hat{\mathbf{x}}_0 - \mathbf{x}}{\sigma_t^2}, \\ \hat{\mathbf{x}}_0 &= \frac{\mathbf{x} + \sigma_t^2\, \nabla \log p_t(\mathbf{x})}{\alpha_t}. \end{aligned}

Substituting this x^0\hat{\mathbf{x}}_0 into the velocity and collecting the x\mathbf{x} and ∇log⁡pt\nabla \log p_t terms gives (26.7.5). ■\blacksquare

Two special cases are worth writing out. On a variance-preserving path, αt2+σt2=1\alpha_t^2 + \sigma_t^2 = 1, so σtσ˙t=−αtα˙t\sigma_t \dot{\sigma}_t = -\alpha_t \dot{\alpha}_t and the coefficient of the score collapses to α˙t/αt\dot{\alpha}_t/\alpha_t: ut(x)=α˙tαt(x+∇log⁡pt(x))\mathbf{u}_t(\mathbf{x}) = \frac{\dot{\alpha}_t}{\alpha_t}\big(\mathbf{x} + \nabla \log p_t(\mathbf{x})\big). For the variance-preserving SDE of the previous section, αt=exp⁡(−12∫0tβ(s) ds)\alpha_t = \exp\big(-\tfrac12 \int_0^t \beta(s)\, ds\big), so α˙t/αt=−12β(t)\dot{\alpha}_t/\alpha_t = -\tfrac12 \beta(t) and the velocity is −12β(t)(x+∇log⁡pt(x))-\tfrac12 \beta(t) \big(\mathbf{x} + \nabla \log p_t(\mathbf{x})\big). This is the probability-flow velocity f−12g2∇log⁡pt\mathbf{f} - \tfrac12 g^2 \nabla \log p_t (Section 26.5.4) with f=−12β x\mathbf{f} = -\tfrac12 \beta\, \mathbf{x} and g2=βg^2 = \beta. On this path the flow-matching velocity and the probability-flow ODE are the same field on the same clock. The cosine path of the Gaussian example is variance-preserving too, so we can check the form on it: ∇log⁡pt=−x/st2\nabla \log p_t = -x/s_t^2 gives α˙tαt(1−1/st2) x=αtα˙t(s02−1) x/st2\frac{\dot\alpha_t}{\alpha_t}(1 - 1/s_t^2)\, x = \alpha_t \dot{\alpha}_t (s_0^2 - 1)\, x / s_t^2, the stretching rate s˙t/st\dot{s}_t/s_t found above.

On the straight path αt=1−t\alpha_t = 1 - t, σt=t\sigma_t = t, which the rest of the section uses, the identity reads ut(x)=−(x+t ∇log⁡pt(x))/(1−t)\mathbf{u}_t(\mathbf{x}) = -\big(\mathbf{x} + t\, \nabla \log p_t(\mathbf{x})\big)/(1 - t).

The same posterior mean underlies the targets that networks are trained on in practice (Table 26.7.1).

Table 26.7.1. Network targets on a Gaussian path. Each row gives the quantity a network predicts, the posterior mean it estimates, and its conversion from the score. The name v\mathbf{v}-prediction comes from the literature; on the cosine path its target αtϵ−σtx0\alpha_t\boldsymbol\epsilon - \sigma_t\mathbf{x}_0 is 2/π2/\pi times the velocity target.
Network predictsPosterior meanFrom the score s=∇log⁡pt\mathbf{s} = \nabla \log p_t
score sθ\mathbf{s}_{\boldsymbol{\theta}}∇log⁡pt(x)\nabla \log p_t(\mathbf{x})s\mathbf{s}
noise ϵ^\hat{\boldsymbol{\epsilon}}E[ϵ∣xt=x]\mathbb{E}[\boldsymbol{\epsilon} \mid \mathbf{x}_t = \mathbf{x}]−σt s-\sigma_t\, \mathbf{s}
clean point x^0\hat{\mathbf{x}}_0E[x0∣xt=x]\mathbb{E}[\mathbf{x}_0 \mid \mathbf{x}_t = \mathbf{x}](x+σt2 s)/αt(\mathbf{x} + \sigma_t^2\, \mathbf{s})/\alpha_t
velocity uθ\mathbf{u}_{\boldsymbol{\theta}}E[x˙t∣xt=x]\mathbb{E}[\dot{\mathbf{x}}_t \mid \mathbf{x}_t = \mathbf{x}]the identity (26.7.5)
v\mathbf{v}-prediction v^\hat{\mathbf{v}}E[αtϵ−σtx0∣xt=x]\mathbb{E}[\alpha_t \boldsymbol{\epsilon} - \sigma_t \mathbf{x}_0 \mid \mathbf{x}_t = \mathbf{x}]−σtαt x−σt αt2+σt2αt s-\tfrac{\sigma_t}{\alpha_t}\, \mathbf{x} - \sigma_t\, \tfrac{\alpha_t^2 + \sigma_t^2}{\alpha_t}\, \mathbf{s}

Each row is a tt-dependent affine function of the same posterior mean, so a network trained on any row defines all of them. Which row is easiest to learn is a separate question, about the variance of the training targets at the two ends of the path (Exercise 6). A noise predictor is therefore also a velocity field: the samplers of this section apply to it after the conversion of Table 26.7.1.

26.7.1.4 Example: Two Points in One Dimension#

Before choosing among paths we work one case to the end. For the two-point data set of the opening every object so far has a closed form, and the closed form shows the failure that Section 26.7.2 repairs. The data are x0=±ax_0 = \pm a with probability 12\tfrac12 each, with a=2a = 2: the two modes of the chapter's running mixture with their width removed. The noise is ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1), drawn independently of x0x_0. We take the Gaussian path with αt=1−t\alpha_t = 1 - t and σt=t\sigma_t = t, which joins each data point to its noise point by a straight line at constant speed: xt=(1−t) x0+t ϵx_t = (1 - t)\, x_0 + t\, \epsilon, with velocity x˙t=ϵ−x0\dot{x}_t = \epsilon - x_0.

Take the data point as the conditioning variable, z=x0\mathbf{z} = x_0. Given x0x_0, the position xtx_t is N((1−t) x0,t2)\mathcal{N}((1 - t)\, x_0, t^2), a positive density for t>0t > 0, so the marginal-velocity proposition applies. Eliminating ϵ=(x−(1−t) x0)/t\epsilon = (x - (1 - t)\, x_0)/t expresses the velocity as a function of the current position, ut(x∣x0)=(x−x0)/tu_t(x \mid x_0) = (x - x_0)/t. Run backward in time, the particle heads for its data point at the speed that arrives exactly at t=0t = 0.

To average this velocity we need the posterior of x0x_0 at a point xx. The posterior odds of +a+a against −a-a at xx are the ratio of the two Gaussian densities. In the exponent the terms x2x^2 and (1−t)2a2(1 - t)^2 a^2 cancel and only the cross term survives, so the odds are exp⁡(2(1−t) ax/t2)\exp\big(2 (1 - t)\, a x / t^2\big) and the posterior mean is E[x0∣xt=x]=atanh⁡((1−t) ax/t2)\mathbb{E}[x_0 \mid x_t = x] = a \tanh\big((1 - t)\, a x / t^2\big). The marginal velocity is therefore

ut(x)=x−atanh⁡ ⁣((1−t) axt2)t.(26.7.6)u_t(x) = \frac{x - a \tanh\!\big(\frac{(1 - t)\, a x}{t^2}\big)}{t}. \tag{26.7.6}

Run backward in time, the cloud at xx heads for the average of the two targets, weighted by how plausible each is from xx, at the speed that arrives on time. At (t,x)=(0.5,0.5)(t, x) = (0.5, 0.5) the velocity is −2.86-2.86; at (0.7,−1)(0.7, -1) it is 0.970.97. Three properties can be read off (26.7.6), and Figure 26.7.2 draws the first two.

  • At t=1t = 1 the field is u1(x)=xu_1(x) = x. The noise sample carries no information about its target, so the posterior mean is the data mean 00. One Euler step from t=1t = 1 to t=0t = 0, x↦x−u1(x)x \mapsto x - u_1(x), sends every sample to 00. This holds for any data under independent pairing: u1(x)=E[ϵ−x0∣ϵ=x]=x−E[x0]\mathbf{u}_1(\mathbf{x}) = \mathbb{E}[\boldsymbol{\epsilon} - \mathbf{x}_0 \mid \boldsymbol{\epsilon} = \mathbf{x}] = \mathbf{x} - \mathbb{E}[\mathbf{x}_0], so one step of the exact field lands on the data mean.
  • The origin first attracts, then repels. As tt falls, a sampler moves against utu_t, so a positive slope at the origin pulls particles toward it and a negative slope pushes them away. The slope is ∂xut(0)=(1−(1−t) a2/t2)/t\partial_x u_t(0) = \big(1 - (1 - t)\, a^2/t^2\big)/t: +0.56+0.56 at t=0.9t = 0.9, zero at t∗=22−2≈0.83t^* = 2\sqrt{2} - 2 \approx 0.83 (the root of (1−t) a2=t2(1 - t)\, a^2 = t^2), −0.31-0.31 at t=0.8t = 0.8 and −14-14 at t=0.5t = 0.5. Particles near 00 drift toward 00 until tt falls to t∗t^* and leave for a mode only later, so the flow chooses a mode late. Far from the origin the tanh⁡\tanh saturates and ut≈(x∓a)/tu_t \approx (x \mp a)/t, the conditional velocity itself.
  • The floor is collected near the noise. The target ϵ−x0\epsilon - x_0 has mean square a2+1=5a^2 + 1 = 5. Of this, C=EtExVar(x0∣xt)/t2≈2.0C = \mathbb{E}_t \mathbb{E}_x \textrm{Var}(x_0 \mid x_t)/t^2 \approx 2.0 is floor, with Var(x0∣xt=x)=a2sech⁡2((1−t) ax/t2)\textrm{Var}(x_0 \mid x_t = x) = a^2 \operatorname{sech}^2\big((1 - t)\, a x/t^2\big), and the remaining 3.03.0 is the mean square of the marginal velocity. Nearly all of CC comes from t>0.5t > 0.5, where the two blobs overlap and a position does not tell which point its particle is bound for. Below t=0.4t = 0.4 it does, and only about a thousandth of the floor is collected there, although the conditional velocity (x−x0)/t(x - x_0)/t grows without bound (Exercise 2).
Figure 26.7.2:

Two data points at ±2\pm 2 and standard Gaussian noise with independent pairing; sampling runs from the noise at t=1t=1 (right) to the data at t=0t=0 (left). (a) Trajectories of the exact marginal flow over the one-standard-deviation bands of the two conditional blobs: until tt falls to t∗=0.83t^*=0.83 every trajectory moves toward 00, and those that start near 00 leave for a mode only below t≈0.6t\approx 0.6. (b) The velocity ut(x)u_t(x) is xx at t=1t=1, its slope at the origin turns negative and steep as tt falls, and it tends to (x∓2)/t(x\mp 2)/t away from the origin.

The cell takes the slope at the origin by a finite difference at the three times of the second property. It then puts the first property to the test, and asks what more steps would do. It integrates the exact field from t=1t = 1 to t=0t = 0 with 11, 22, 44 and 88 equal Euler steps, starting from the whole noise law, and prints how much of the mass lands within 0.10.1 of a data point, together with the mean of ∣x∣|x| at the end. The noise law is a fine grid of starting points weighted by the Gaussian density, so nothing in the output is random.

a = 2.0                                       # data at -a and +a, noise N(0, 1)
def u_two_point(x, t):                        # closed form of the marginal velocity
    return (x - a * np.tanh((1 - t) * a * x / t**2)) / t

ts = np.array([0.9, 0.8, 0.5])
print('slope at the origin at t = 0.9, 0.8, 0.5:',
      ((u_two_point(1e-6, ts) - u_two_point(-1e-6, ts)) / 2e-6).round(2),
      '   t* =', round(2 * np.sqrt(2) - 2, 4))
x1 = np.linspace(-6, 6, 4001)                 # the noise law N(0, 1), as a weighted grid
w = np.exp(-x1**2 / 2) / np.exp(-x1**2 / 2).sum()
for K in (1, 2, 4, 8):                        # K equal Euler steps from t = 1 to t = 0
    x, ts = x1, np.linspace(1, 0, K + 1)
    for t, t_next in zip(ts[:-1], ts[1:]):
        x = x - (t - t_next) * u_two_point(x, t)
    print(f'{K} Euler step(s): mass within 0.1 of +-a {w @ (abs(abs(x) - a) < 0.1):.3f}, '
          f'mean |x| {w @ abs(x):.2f}')
slope at the origin at t = 0.9, 0.8, 0.5: [  0.56  -0.31 -14.  ]    t* = 0.8284
1 Euler step(s): mass within 0.1 of +-a 0.000, mean |x| 0.00
2 Euler step(s): mass within 0.1 of +-a 0.359, mean |x| 1.48
4 Euler step(s): mass within 0.1 of +-a 0.987, mean |x| 1.99
8 Euler step(s): mass within 0.1 of +-a 0.999, mean |x| 2.00

The slopes are those of the formula. After one Euler step no mass at all lies near a data point, and the mean of ∣x∣|x| is 00: every sample sits on the data mean. So the wish of the opening fails at its first test. Every conditional path is straight, yet the marginal flow is curved, and the one long step we hoped to take collapses every sample onto the mean.

More steps repair the damage quickly. Two bring a little over a third of the mass to a data point, four all but about one percent of it, and eight practically all. So few suffice because the last step of any grid lands on the posterior mean atanh⁡(⋅)a \tanh(\cdot), which is ±a\pm a wherever the earlier steps have moved a particle far enough from the origin (Exercise 2). But steps are what we set out to save. How to pair noise with data so that the flow comes out straight, and one step is enough, is the subject of Section 26.7.2.

26.7.2 Rectified Flow#

26.7.2.1 Straight Paths and Their Crossings#

The two-point example used straight conditional paths. In dd dimensions the same construction pairs a data sample x0\mathbf{x}_0 with a noise sample ϵ\boldsymbol{\epsilon}, drawn independently, and joins them by a straight line traversed at constant speed:

xt=(1−t) x0+t ϵ,ut(xt∣z)=x˙t=ϵ−x0,z=(x0,ϵ).(26.7.7)\mathbf{x}_t = (1 - t)\, \mathbf{x}_0 + t\, \boldsymbol{\epsilon}, \qquad \mathbf{u}_t(\mathbf{x}_t \mid \mathbf{z}) = \dot{\mathbf{x}}_t = \boldsymbol{\epsilon} - \mathbf{x}_0, \qquad \mathbf{z} = (\mathbf{x}_0, \boldsymbol{\epsilon}). \tag{26.7.7}

The conditional velocity does not depend on tt, and the CFM loss (26.7.3) becomes the rectified flow objective (Liu et al., 2023; Lipman et al., 2023)

LRF(θ)=Et, x0∼p0, ϵ∼p1[ ∥uθ((1−t)x0+tϵ, t)−(ϵ−x0)∥2].(26.7.8)\begin{aligned} \mathcal{L}_{\mathrm{RF}}(\boldsymbol{\theta}) &= \mathbb{E}_{t,\ \mathbf{x}_0 \sim p_0,\ \boldsymbol{\epsilon} \sim p_1} \\ &\quad \left[\, \left\| \mathbf{u}_{\boldsymbol{\theta}}\big( (1 - t) \mathbf{x}_0 + t \boldsymbol{\epsilon},\ t \big) - (\boldsymbol{\epsilon} - \mathbf{x}_0) \right\|^2 \right]. \end{aligned} \tag{26.7.8}

Training draws data and noise, interpolates between them, and regresses on the difference. That is the whole algorithm. Its name looks ahead: rectified means straightened, and straight is what the flow becomes once the pairing has been repaired. The flow of independent pairs, as we just saw, is not.

One technical point has to be settled. With Gaussian noise we could condition on x0\mathbf{x}_0 alone, as in the two-point example, and the marginal-velocity proposition would apply. Conditioning on the pair is what lets us change the pairing later, but given the pair, a point sliding along a line has no density, so the proposition does not apply as stated. Its conclusion still holds, by the same computation applied to the expectation E φ(xt)\mathbb{E}\,\varphi(\mathbf{x}_t) of a smooth test function φ\varphi (Exercise 7).

Why does the flow bend? Two segments that cross at (x,t)(\mathbf{x}, t) feed the posterior mean (26.7.2) two different directions (Figure 26.7.3). A function has one value at each point, so the field averages them. An ODE whose field is Lipschitz in x\mathbf{x} has exactly one trajectory through each point (Section 26.1.1.3), so two trajectories of the learned flow can never meet. Where the segments cross, the trajectories bend away from each other instead.

Figure 26.7.3:

Three data–noise pairs in one dimension joined by straight segments (dashed), two pairs of which cross (×). Where segments cross, the marginal velocity averages their directions, so the trajectories of its flow (solid), run from the noise at t=1t = 1 to the data at t=0t = 0, bend and never meet. Each trajectory ends on a different data point than its own segment, and the trajectories arrive in the order in which they started.

The goal is a field whose trajectories are straight lines traversed at constant speed. Such a field is constant along each trajectory, so one Euler step of any length is exact. The independent pairing is far from this limit. The loss is minimized by the right field and the pieces are as straight as pieces can be, so the one thing left to change is which noise point is joined to which data point.

26.7.2.2 Example: Two Moons#

The two points had a formula, and the formula said that one step fails. How many steps does a trained network need, on data that have no formula? We take the two moons, two interleaved crescents in the plane, train a small network on them, and count. To count we need a score for samples, and we use the squared energy distance (Székely and Rizzo, 2013) between laws PP and QQ with finite first moments,

E2(P,Q)=2 E∥X−Y∥−E∥X−X′∥−E∥Y−Y′∥,\mathcal{E}^2(P, Q) = 2\, \mathbb{E}\|X - Y\| - \mathbb{E}\|X - X'\| - \mathbb{E}\|Y - Y'\|,

where X,X′∼PX, X' \sim P and Y,Y′∼QY, Y' \sim Q are independent. It compares the mean distance between a point of PP and a point of QQ with the mean distances within each law. Székely and Rizzo call this expression itself the energy distance; we call it squared because its square root is the metric. It is a squared MMD (Section 25.4.1), and it is zero only if P=QP = Q. We estimate it from two samples by the unbiased U-statistic, and every score quoted below is this squared distance.

The cell builds the data, standardized to zero mean and unit variance per coordinate, a held-out sample of 2,0482{,}048 points, and one noise array z_eval that every later comparison reuses. It then scores two references against the held-out sample: a fresh sample of the data, and a point mass at the data mean, which is what one Euler step of the exact field produces.

def two_moons(n, rng, noise=0.07):
    t = rng.uniform(0.0, np.pi, n)
    m = rng.integers(0, 2, n)                      # which moon
    X = np.stack([np.cos(t) * (1 - 2 * m) + m,
                  np.sin(t) * (1 - 2 * m) + 0.5 * m], axis=1)
    return X + noise * rng.standard_normal((n, 2))

rng = np.random.default_rng()
raw = two_moons(8192, rng)
mu, sd = raw.mean(0), raw.std(0)
moons = (raw - mu) / sd                            # standardized training data
held_out = (two_moons(2048, rng) - mu) / sd
z_eval = rng.standard_normal((2048, 2))            # noise for every comparison

def energy_distance(a, b):                         # squared energy distance, U-statistic
    d = lambda u, v: np.linalg.norm(u[:, None, :] - v[None, :, :], axis=-1)
    n, m = len(a), len(b)
    return (2 * d(a, b).mean() - d(a, a).sum() / (n * (n - 1))
            - d(b, b).sum() / (m * (m - 1)))

print(f'fresh data sample vs held-out: {energy_distance(moons[:2048], held_out):+.4f}')
print(f'point mass at the data mean vs held-out: '
      f'{energy_distance(np.zeros((2048, 2)), held_out):.3f}')
fresh data sample vs held-out: -0.0000
point mass at the data mean vs held-out: 0.904

Two samples of the same law score within a few thousandths of zero, which is the resolution of the metric at this sample size. The point mass scores about 0.90.9.

The model is a small tanh network that takes (x,t)(\mathbf{x}, t) and returns a velocity; field evaluates it. The function train_rf takes a sampler of pairs, so that we can change the pairing later. It returns the network together with its loss averaged over the last 500500 batches, because single batches scatter, and over the two coordinates, so the printed value is LRF/2\mathcal{L}_{\mathrm{RF}}/2.

def make_net():                         # 3 -> 256 -> 256 -> 2, Glorot weights, zero biases
    net = nn.Sequential(nn.Linear(3, 256), nn.Tanh(), nn.Linear(256, 256), nn.Tanh(),
                        nn.Linear(256, 2))
    for layer in net[::2]:
        nn.init.xavier_uniform_(layer.weight)
        nn.init.zeros_(layer.bias)
    return net

def field(net, x, t):                   # the time enters centered, as 2t - 1
    return net(torch.cat([x, 2 * t - 1], 1))

def train_rf(sample_pairs, steps=10000, batch=2048, tail=500):
    """Regress v(x_t, t) on eps - x0 (papers: -(x1 - x0) at time 1 - t).
    Return the net and the mean tail loss."""
    net = make_net()
    opt = torch.optim.Adam(net.parameters(), lr=3e-3)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps)   # 3e-3 -> 0
    tail_sum = torch.zeros(())
    for step in range(steps):
        x0, eps = sample_pairs(batch)              # data, noise
        t = torch.rand(batch, 1)
        xt = (1 - t) * x0 + t * eps                # a point on each segment
        loss = ((field(net, xt, t) - (eps - x0))**2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
        sched.step()
        if step >= steps - tail:
            tail_sum += loss.detach()              # stays on the device
    return net, (tail_sum / tail).item()

The first run pairs noise and data independently. By the CFM theorem its loss cannot reach zero, and where it stops measures how much the segments cross. The floor CC is the conditional variance of ϵ−x0\boldsymbol{\epsilon} - \mathbf{x}_0 given xt\mathbf{x}_t, averaged over tt. Can we know it before we train? For a finite data set we can, without any network. Given xt\mathbf{x}_t, the posterior of x0\mathbf{x}_0 puts on each training point x0′\mathbf{x}_0' a weight proportional to exp⁡(−∥xt−(1−t) x0′∥2/2t2)\exp\big(-\|\mathbf{x}_t - (1 - t)\, \mathbf{x}_0'\|^2 / 2t^2\big). The target is ϵ−x0=(xt−x0)/t\boldsymbol{\epsilon} - \mathbf{x}_0 = (\mathbf{x}_t - \mathbf{x}_0)/t, so its conditional variance is the posterior variance of x0\mathbf{x}_0 divided by t2t^2. The function pairing_floor averages this quantity over 4,0004{,}000 draws of (t,x0,ϵ)(t, \mathbf{x}_0, \boldsymbol{\epsilon}) and halves it, because train_rf reports its loss per coordinate.

def pairing_floor(data, rng, m=4000, chunk=500):
    """Floor C of independent pairing, per coordinate: E Var(eps - x0 | x_t) / 2."""
    t = rng.uniform(0, 1, (m, 1))
    xt = (1 - t) * data[rng.integers(0, len(data), m)] + t * rng.standard_normal((m, 2))
    var = []
    for i in range(0, m, chunk):              # posterior of x0 over all training points
        ti, xi = t[i:i + chunk], xt[i:i + chunk]
        d2 = ((xi**2).sum(1, keepdims=True) - 2 * (1 - ti) * xi @ data.T
              + (1 - ti)**2 * (data**2).sum(1))           # |x_t - (1 - t) x0'|^2
        logw = -d2 / (2 * ti**2)
        r = np.exp(logw - logw.max(1, keepdims=True))
        r /= r.sum(1, keepdims=True)
        v = r @ (data**2).sum(1) - ((r @ data)**2).sum(1)  # Var(x0 | x_t), summed
        var.append(v / ti[:, 0]**2)           # eps - x0 = (x_t - x0) / t
    return np.concatenate(var).mean() / 2

print(f'floor of the independent pairing, per coordinate: {pairing_floor(moons, rng):.2f}')
floor of the independent pairing, per coordinate: 1.39

The floor is about 1.371.37 per coordinate, and the estimate moves in the second decimal from one draw to the next. A perfect network would stop there. Ours has two hidden layers of 256256 units and 10,00010{,}000 steps of 2,0482{,}048 pairs each to get close.

data = torch.tensor(moons, dtype=torch.float32)
def independent_pairs(n):                       # random data rows, fresh noise
    return data[torch.randint(0, len(data), (n,))], torch.randn(n, 2)

net, plateau = train_rf(independent_pairs)
print(f'CFM loss, mean of the last 500 batches: {plateau:.2f}')
CFM loss, mean of the last 500 batches: 1.40

The loss settles at about 1.41.4 per coordinate, within a few hundredths of the floor. A loss of 1.41.4 therefore does not mean a poor fit. Almost all of it is the disagreement of crossing segments, which no network can remove. By the CFM theorem only the excess over the floor is error of the field.

Those few hundredths are not as small as they look, though. The target has mean square 22 per coordinate, one each from the noise and the standardized data, and 1.371.37 of it is floor. The field itself therefore has a mean square of only about 0.60.6, and its error is a few percent of that. We shall meet this error again in the samples.

Sampling integrates x˙=uθ(x,t)\dot{\mathbf{x}} = \mathbf{u}_{\boldsymbol{\theta}}(\mathbf{x}, t) from t=1t = 1 down to 00 with Euler's method (Section 26.2): KK steps of length 1/K1/K, each of which subtracts uθ(x,t)/K\mathbf{u}_{\boldsymbol{\theta}}(\mathbf{x}, t)/K at t=1,1−1/K,…,1/Kt = 1, 1 - 1/K, \ldots, 1/K. The function euler_path returns the whole trajectory, of shape (steps + 1, n, 2); its last row is the sample.

@torch.inference_mode()
def euler_path(net, z, steps):
    q = torch.tensor(z, dtype=torch.float32)
    path = [q]
    for k in range(steps):                     # t = 1, 1 - 1/steps, ..., 1/steps
        t = torch.full((len(z), 1), 1 - k / steps)
        q = q - field(net, q, t) / steps
        path.append(q)
    return torch.stack(path).numpy()

One step of the exact field would give the point mass that scored 0.90.9. For the trained field, the cell integrates the noise array z_eval with K=1,2,4,…,64K = 1, 2, 4, \ldots, 64 steps and plots the squared energy distance to the held-out data on log–log axes. The estimate is unbiased, so at the resolution of the metric it can turn negative; the plot clips it at 10−310^{-3}.

steps_list = [1, 2, 4, 8, 16, 32, 64]
eds = [energy_distance(euler_path(net, z_eval, K)[-1], held_out) for K in steps_list]
print('  '.join(f'{K}: {e:.3f}' for K, e in zip(steps_list, eds)))
d2l.plot(steps_list, np.maximum(eds, 1e-3), 'Euler steps',
         'squared energy distance', xscale='log', yscale='log')
1: 0.736  2: 0.170  4: 0.031  8: 0.004  16: -0.000  32: -0.001  64: -0.001

One step scores 0.70.7 to 0.750.75, the same order as the point mass at the mean (0.90.9): the network has learned, imperfectly, the collapse that the exact field performs at t=1t = 1. Two steps score 0.160.16 to 0.190.19, four 0.030.03 to 0.040.04, eight about 0.010.01 or less, and from sixteen steps on the score stays within a few thousandths of zero. The decline is Euler's discretization error. What remains is the error of the trained field, and it is as small as the metric can resolve with 2,0482{,}048 points. More steps help, as they should for a field fitted without a solver; the field trained through ten Euler steps in Section 26.3.1 got worse when its steps were refined.

A score is one number, and it is worth looking at what it summarizes. The next cell draws the samples of 11, 22, 88 and 3232 steps, and beside them the held-out data.

panels = [(f'{K} Euler step(s)', euler_path(net, z_eval, K)[-1]) for K in (1, 2, 8, 32)]
fig, axes = d2l.plt.subplots(1, 5, figsize=(12, 2.6), sharex=True, sharey=True)
for ax, (title, s) in zip(axes, panels + [('held-out data', held_out)]):
    d2l.plot(s[:, 0], s[:, 1], title, fmts=('.',),
             xlim=(-2.5, 2.5), ylim=(-2.5, 2.5), axes=ax)

One step gives a blob around the mean and two a slanted band. Eight steps spread the cloud into two crescents, with many points still strewn between them. Thirty-two steps clear most of these and draw two separate moons, like the data in the last panel. Set them beside the data, though, and they are a little thicker, with a few points left in the gaps. More steps do not remove them, so these flaws belong to the field and not to the solver: they are what the few hundredths between the loss and its floor look like.

The score hardly registers these flaws. It compares mean distances between points, so it reports where the mass lies long before it reports how sharp the edges are, and a score at the resolution of the metric does not certify samples as sharp as the data. What more steps do remove is the solver's error, and by the score that takes sixteen to thirty-two network calls per sample. This is the cost of the curvature that the independent pairing builds into the flow.

26.7.2.3 Reflow#

The independent pairing is what bends the flow, and the trained model supplies a better one. Run its ODE from fresh noise and pair each noise point ϵ\boldsymbol{\epsilon} with the endpoint x^0(ϵ)\hat{\mathbf{x}}_0(\boldsymbol{\epsilon}) at which it arrives. Trajectories of one flow never cross, so these pairs cross far less than independent ones. Retraining the same architecture on the new pairs is called reflow (Liu et al., 2023).

Does re-pairing do any harm? It could spoil the endpoint laws, or pair points that lie farther apart than before. It does neither. How far a pairing moves its points is measured by its transport cost E c(x1−x0)\mathbb{E}\, c(\mathbf{x}_1 - \mathbf{x}_0), the mean over the pairs of a convex function cc of the displacement, such as its squared length. In the statement capitals denote random paths: Xt\mathbf{X}_t is the straight segment of a pair, and Zt\mathbf{Z}_t the trajectory of the flow that starts from the same noise point.

Proposition (reflow keeps the marginals and lowers the transport cost). Let the pair (X0,X1)(\mathbf{X}_0, \mathbf{X}_1) of a data point and a noise point have finite second moments, let Xt=(1−t)X0+tX1\mathbf{X}_t = (1 - t) \mathbf{X}_0 + t \mathbf{X}_1, let ut\mathbf{u}_t be the marginal velocity of this straight path, and let Zt\mathbf{Z}_t solve Z˙t=ut(Zt)\dot{\mathbf{Z}}_t = \mathbf{u}_t(\mathbf{Z}_t) backward in time from the noise end, Z1=X1\mathbf{Z}_1 = \mathbf{X}_1. Assume that Xt\mathbf{X}_t has a positive density for every t>0t > 0 and that ut\mathbf{u}_t is continuously differentiable and Lipschitz in x\mathbf{x} with a constant independent of tt, so that this flow exists. Then (i) Zt\mathbf{Z}_t has the law of Xt\mathbf{X}_t for every tt, in particular Z0∼p0\mathbf{Z}_0 \sim p_0; (ii) for every convex function cc,

E c(Z1−Z0)  ≤  E c(X1−X0).(26.7.9)\mathbb{E}\, c(\mathbf{Z}_1 - \mathbf{Z}_0) \;\le\; \mathbb{E}\, c(\mathbf{X}_1 - \mathbf{X}_0). \tag{26.7.9}

Proof. (i) The law of Xt\mathbf{X}_t satisfies the continuity equation with ut\mathbf{u}_t, by the marginal-velocity proposition with z=(X0,X1)\mathbf{z} = (\mathbf{X}_0, \mathbf{X}_1) in the weak form that covers point masses (Exercise 7). The law of Zt\mathbf{Z}_t satisfies it too, because Zt\mathbf{Z}_t moves with the field ut\mathbf{u}_t. Both equal p1p_1 at t=1t = 1, and two solutions of the continuity equation with such a field that agree at one time agree at every time. This uniqueness is the one step we do not prove in full: Section 26.5.4.3 gave the argument for smooth positive densities, where along each trajectory both log-densities change at the rate −∇⋅ut-\nabla \cdot \mathbf{u}_t, and we use it here without redoing it in the weak form. (ii) Write the displacement as a time integral and apply Jensen's inequality twice:

E c(Z1−Z0)=E c(∫01ut(Zt) dt)≤∫01E c(ut(Zt)) dt=∫01E c(E[X1−X0∣Xt]) dt≤E c(X1−X0).\begin{aligned} \mathbb{E}\, c(\mathbf{Z}_1 - \mathbf{Z}_0) &= \mathbb{E}\, c\Big(\int_0^1 \mathbf{u}_t(\mathbf{Z}_t)\, dt\Big) \le \int_0^1 \mathbb{E}\, c\big(\mathbf{u}_t(\mathbf{Z}_t)\big)\, dt \\ &= \int_0^1 \mathbb{E}\, c\big(\mathbb{E}[\mathbf{X}_1 - \mathbf{X}_0 \mid \mathbf{X}_t]\big)\, dt \le \mathbb{E}\, c(\mathbf{X}_1 - \mathbf{X}_0). \end{aligned}

The first inequality is Jensen's inequality for the time average. The equality uses (i) to replace Zt\mathbf{Z}_t by Xt\mathbf{X}_t and then the definition of the marginal velocity. The last inequality is the conditional Jensen inequality. ■\blacksquare

With c=∥⋅∥2c = \|\cdot\|^2 the last step loses exactly the conditional variance, so the cost falls at least by the floor of the old pairing: E∥Z1−Z0∥2≤E∥X1−X0∥2−C\mathbb{E}\|\mathbf{Z}_1 - \mathbf{Z}_0\|^2 \le \mathbb{E}\|\mathbf{X}_1 - \mathbf{X}_0\|^2 - C. The floor CC, a nuisance in training, is the saving that one round of reflow guarantees. Where no segments cross, the floor is zero and re-pairing has nothing to gain.

The hypotheses are stronger than our examples allow. For the two points, and for any finite training set paired independently with Gaussian noise, the marginal field is Lipschitz on [δ,1][\delta, 1] for each δ>0\delta > 0 but not up to t=0t = 0: the slope −14-14 of the two-point field at t=0.5t = 0.5 grows without bound as t→0t \to 0. The proof then covers the flow down to time δ\delta only: it gives (i) for t≥δt \ge \delta, and (ii) in the form E c((Z1−Zδ)/(1−δ))≤E c(X1−X0)\mathbb{E}\, c\big((\mathbf{Z}_1 - \mathbf{Z}_\delta)/(1 - \delta)\big) \le \mathbb{E}\, c(\mathbf{X}_1 - \mathbf{X}_0). The limit δ→0\delta \to 0 we do not prove, and in this sense the examples that follow go beyond the proposition.

For the two points the conclusion can be verified directly. A flow in one dimension preserves order, so one round pairs each noise point ϵ\epsilon with asign⁡(ϵ)a \operatorname{sign}(\epsilon) (Exercise 4). This pairing costs a2−2a2/π+1=1.81a^2 - 2a\sqrt{2/\pi} + 1 = 1.81 against a2+1=5a^2 + 1 = 5 for the independent one, and its segments never cross, so the second round has C=0C = 0 and its field is integrated exactly by one Euler step.

For the two moons, the cell draws 8,1928{,}192 fresh noise points, integrates the trained model for 3232 steps to obtain their endpoints, and trains a new network with train_rf on these fixed pairs.

eps_pairs = rng.standard_normal((8192, 2))            # noise endpoints, kept
x0_pairs = euler_path(net, eps_pairs, 32)[-1]         # the model's own endpoints
X0, Eps = (torch.tensor(p, dtype=torch.float32) for p in (x0_pairs, eps_pairs))
def model_pairs(n):                                   # the same pairs, never re-paired
    i = torch.randint(0, len(X0), (n,))
    return X0[i], Eps[i]

net2, plateau2 = train_rf(model_pairs)
print(f'reflow loss, mean of the last 500 batches: {plateau2:.4f}')
reflow loss, mean of the last 500 batches: 0.0007

The reflow loss settles below a thousandth, where the first loss stopped at 1.41.4, so the new segments almost never cross. A field without crossings is nearly constant along its trajectories, and then a few Euler steps should do. The next cell samples from both models with 11, 22 and 3232 steps from the same noise array.

It also prints the mean squared length of the old and the new pairs, the cost that the proposition bounds. The old pairs cost 44: noise and standardized data each have unit variance in each of two coordinates, and for independent draws the variances add. The floor of the independent pairing, summed over the two coordinates, is twice the value printed above, about 2.752.75. For the exact marginal flow the proposition therefore promises new pairs that cost at most about 1.251.25.

for K in (1, 2, 32):
    e1 = energy_distance(euler_path(net, z_eval, K)[-1], held_out)
    e2 = energy_distance(euler_path(net2, z_eval, K)[-1], held_out)
    print(f'{K:2d} Euler step(s): squared energy distance  original {e1:.3f}'
          f'  reflowed {e2:.3f}')
x0_indep = moons[rng.integers(0, len(moons), len(eps_pairs))]
print(f'mean squared pair length: independent {np.mean(np.sum((eps_pairs - x0_indep)**2, 1)):.2f}'
      f', reflowed {np.mean(np.sum((eps_pairs - x0_pairs)**2, 1)):.2f}')
 1 Euler step(s): squared energy distance  original 0.736  reflowed -0.001
 2 Euler step(s): squared energy distance  original 0.170  reflowed -0.001
32 Euler step(s): squared energy distance  original -0.001  reflowed -0.001
mean squared pair length: independent 4.04, reflowed 0.29

One Euler step of the reflowed model scores the same as thirty-two steps of the original: a thousandth or two at most, the resolution of the metric, where the original's single step scored about 0.70.7. It could not have done better. The reflowed network was trained to reproduce the original's 3232-step endpoints, so it inherits the first model's error along with its samples.

The mean squared length of the pairs drops from 44 to about 0.30.3, far below the 1.251.25 that the bound guarantees. The slack is in the first step of the proof: Jensen's inequality for the time average is far from tight on the curved trajectories of the first flow.

Straightness can be measured as well, by the mean distance of each 3232-step trajectory from the chord joining its two ends.

def chord_gap(P):                                     # P: (steps + 1, n, 2) trajectory
    chord = P[0] + (P[-1] - P[0]) * np.linspace(0, 1, len(P))[:, None, None]
    return np.linalg.norm(P - chord, axis=-1).mean()

print(f'mean distance from the chord: original {chord_gap(euler_path(net, z_eval, 32)):.3f}'
      f', reflowed {chord_gap(euler_path(net2, z_eval, 32)):.3f}')
mean distance from the chord: original 0.249, reflowed 0.005

The original trajectories wander about a quarter of a unit from their chords. They set out toward the mean, where a single Euler step left them, and turn out to the moons only later. The reflowed ones stay within half a hundredth of theirs, about fifty times closer, which is why one step suffices. Reflow straightens a flow, but it does not make it optimal. In more than one dimension a flow can be straight and crossing-free and still move mass farther than it must.

26.7.3 Optimal Transport and Straightness#

26.7.3.1 Couplings and the Wasserstein Distance#

Reflow lowered the transport cost. How low can it go, and is the flow of the cheapest pairing straight? We restate the vocabulary of Section 25.4.2. A coupling π\pi of p0p_0 and p1p_1 is a joint law of pairs with these marginals, a plan that says how much mass travels from each source point to each target point. The 2-Wasserstein distance is the cost of the cheapest plan under squared distance,

W22(p0,p1)=min⁡π∈Π(p0,p1) E(x0,x1)∼π[ ∥x1−x0∥2],(26.7.10)W_2^2(p_0, p_1) = \min_{\pi \in \Pi(p_0, p_1)}\ \mathbb{E}_{(\mathbf{x}_0, \mathbf{x}_1) \sim \pi} \left[\, \| \mathbf{x}_1 - \mathbf{x}_0 \|^2 \right], \tag{26.7.10}

where Π(p0,p1)\Pi(p_0, p_1) is the set of couplings. So W22W_2^2 is the least mean squared displacement that turns one law into the other.

What does the cheapest plan look like? When one of the two laws has a density and both have finite second moments, it is unique and it does not split mass: it is a map from the law with the density. For us that law is the noise p1p_1, and the map from noise to data is the gradient of a convex function, the Brenier map. This is Brenier's theorem (Brenier, 1991), which we cite without proof. The data need no density: the two points have none, and neither has a finite training set such as our 8,1928{,}192 moons. On a line the theorem is easy to picture. The derivative of a convex function of one variable never decreases, so the optimal map keeps the points in order.

The smallest case is a Gaussian in one dimension, with data N(m,s2)\mathcal{N}(m, s^2), s>0s > 0, and noise N(0,1)\mathcal{N}(0, 1). The sorted pairing sends each quantile to the same quantile, x0=m+sϵx_0 = m + s\epsilon, and costs E(m+sϵ−ϵ)2=m2+(s−1)2\mathbb{E}(m + s\epsilon - \epsilon)^2 = m^2 + (s - 1)^2. The independent pairing costs E(ϵ−x0)2=m2+1+s2\mathbb{E}(\epsilon - x_0)^2 = m^2 + 1 + s^2. In one dimension the sorted pairing is optimal for every convex cost: if two pairs cross, swapping their targets does not increase the cost (Exercise 2d of Section 25.4). Hence

W22(N(0,1),N(m,s2))=m2+(s−1)2.(26.7.11)W_2^2\big(\mathcal{N}(0, 1), \mathcal{N}(m, s^2)\big) = m^2 + (s - 1)^2 . \tag{26.7.11}

The distance separates the cost of shifting the mean from the cost of stretching the width. Between N(0,4)\mathcal{N}(0, 4) and N(0,1)\mathcal{N}(0, 1) it is 11, against 55 for independent pairs (panels (a) and (b) of Figure 26.7.4): the independent pairing spends four fifths of its cost moving mass past other mass.

This explains where the trajectories of Figure 26.7.3 end. In one dimension the trajectories of a flow cannot cross, so a flow preserves order, and the order-preserving pairing is the optimal one. On a line, one round of reflow therefore reaches optimal transport (Exercise 4).

In two dimensions, freedom from crossings is not enough. Rotate a standard Gaussian cloud about the origin by a quarter turn in unit time, with the field that assigns to the point (ξ1,ξ2)(\xi_1, \xi_2) the velocity π2 (−ξ2,ξ1)\tfrac{\pi}{2}\, (-\xi_2, \xi_1). No two trajectories cross, and the cloud ends where it started, so W22(p0,p1)=0W_2^2(p_0, p_1) = 0. Yet every particle moves, at speed π2∥x∥\tfrac{\pi}{2}\|\mathbf{x}\|. It is a carousel: everyone travels, and the crowd as a whole goes nowhere (panel (c) of Figure 26.7.4).

Straightening the arcs does not cure this. Pair each x0\mathbf{x}_0 with its quarter turn Rx0\mathbf{R}\mathbf{x}_0 and join the two by a segment. The segments ((1−t)I+tR)x0\big((1 - t)\mathbf{I} + t\mathbf{R}\big)\mathbf{x}_0 never cross, because that matrix is invertible for every tt, and each is traversed at constant speed. So C=0C = 0 and reflow leaves the pairing unchanged, yet it costs E∥Rx0−x0∥2=4\mathbb{E}\|\mathbf{R}\mathbf{x}_0 - \mathbf{x}_0\|^2 = 4 against W22=0W_2^2 = 0. On a line, crossings are the only way to waste motion. In the plane a pairing can be straight, crossing-free and still wrong. Brenier's theorem says what this one lacks. An optimal map is the gradient of a convex function, and a quarter turn is not the gradient of anything: the derivative of a gradient is a symmetric matrix, and R\mathbf{R} is not symmetric.

Figure 26.7.4:

Three ways to move a Gaussian. (a) Independent pairing of data N(0,4)\mathcal{N}(0,4) at t=0t=0 with noise N(0,1)\mathcal{N}(0,1) at t=1t=1, drawn for ten equally spaced quantile levels (0.05,0.15,…,0.950.05, 0.15, \ldots, 0.95): segments cross, and the mean squared displacement is 55. (b) The sorted pairing x0=2ϵx_0=2\epsilon never crosses and costs 11, the squared Wasserstein distance. (c) A standard Gaussian cloud in the plane, turned by a quarter. The arcs of the rotation (dashed) have kinetic energy π2/2\pi^2/2. The chords that pair each point with its quarter turn (arrows) are straight, never cross and cost 44. The cloud ends where it started, so W22=0W_2^2=0: in two dimensions a straight, crossing-free pairing need not be optimal.

A pairing records only where each particle ends. How should the motion in between be charged? Consider one particle that travels from x1\mathbf{x}_1 to x0\mathbf{x}_0 in unit time along some path xt\mathbf{x}_t. By Jensen's inequality for the time average,

∫01∥x˙t∥2 dt  ≥  ∥∫01x˙t dt∥2=∥x1−x0∥2,\int_0^1 \|\dot{\mathbf{x}}_t\|^2\, dt \;\ge\; \Big\| \int_0^1 \dot{\mathbf{x}}_t\, dt \Big\|^2 = \|\mathbf{x}_1 - \mathbf{x}_0\|^2,

with equality only if the velocity is constant. The integral of the squared speed is smallest on the straight line at constant speed, and it charges for every detour and every change of pace. Its mean over the particles is the kinetic energy of a flow, ∫01E∥ut(xt)∥2 dt\int_0^1 \mathbb{E}\|\mathbf{u}_t(\mathbf{x}_t)\|^2\, dt. The carousel has kinetic energy (π/2)2 E∥x∥2=π2/2≈4.9(\pi/2)^2\, \mathbb{E}\|\mathbf{x}\|^2 = \pi^2/2 \approx 4.9, all of it wasted.

Kinetic energy also ranks flows with the same endpoints. Take three flows between data N(0,4)\mathcal{N}(0, 4) and noise N(0,1)\mathcal{N}(0, 1): the straight flow of the sorted pairing, the marginal flow of straight segments under the independent pairing, and the cosine path of Section 26.7.1.3. Which is cheapest, and does a flow assembled from straight segments beat one that is not? All three have Gaussian marginals N(0,st2)\mathcal{N}(0, s_t^2), so their velocity is (s˙t/st) x(\dot{s}_t/s_t)\, x and the kinetic energy is ∫01s˙t2 dt\int_0^1 \dot{s}_t^2\, dt (Exercise 3). The cell first checks the two pairing costs, 55 and 11, by sorting samples.

n = 200_000
x0, eps = 2 * rng.standard_normal(n), rng.standard_normal(n)
print(f'data N(0,4), noise N(0,1): independent pairing {np.mean((eps - x0)**2):.2f}, '
      f'sorted pairing {np.mean((np.sort(eps) - np.sort(x0))**2):.3f}')

def kinetic_energy(s, t):                    # marginals N(0, s_t^2): u_t(x) = (s'/s) x
    return np.sum(np.diff(s)**2 / np.diff(t))  # the integral of (ds/dt)^2

t = np.linspace(0, 1, 100_001)
for name, s in [('sorted, straight', 2 - t),
                ('independent, straight', np.sqrt(4 * (1 - t)**2 + t**2)),
                ('cosine path', np.sqrt(1 + 3 * np.cos(np.pi * t / 2)**2))]:
    print(f'{name:22s} kinetic energy {kinetic_energy(s, t):.3f}')
data N(0,4), noise N(0,1): independent pairing 4.99, sorted pairing 0.985
sorted, straight       kinetic energy 1.000
independent, straight  kinetic energy 1.858
cosine path            kinetic energy 1.234

The sorted straight flow is cheapest, and its kinetic energy is W22=1W_2^2 = 1. The surprise is the order of the other two. The straight segments of the independent pairing produce a marginal flow that costs 1.861.86, more than the cosine path's 1.231.23. Its variance st2=4(1−t)2+t2s_t^2 = 4(1 - t)^2 + t^2 first shrinks, as tt falls from 11 to 0.80.8, and then grows, so its particles move inward and back out. Straight conditional segments under the wrong pairing do not make a straight flow.

26.7.3.2 The Benamou–Brenier Theorem#

The cheapest of the three flows cost exactly W22W_2^2, the cost of the cheapest pairing. This is no accident of Gaussians. The cheapest flow between two laws always costs what the cheapest pairing costs, and it is the flow that carries each pair of that pairing along its segment at constant speed. This is the deepest fact of the section. It connects the static problem (26.7.10), which pairs endpoints, to the objects that flow matching trains, which are flows.

Theorem (Benamou–Brenier). Let p0p_0 and p1p_1 have finite second moments, and let one of them, here the noise p1p_1, have a density. Call a pair (pt,ut)(p_t, \mathbf{u}_t) admissible if ut\mathbf{u}_t is continuously differentiable and Lipschitz in x\mathbf{x} with a constant independent of tt, and the pair satisfies the continuity equation with the endpoints p0p_0 and p1p_1. (i) Every admissible pair has kinetic energy at least W22(p0,p1)W_2^2(p_0, p_1). (ii) Join the pairs of an optimal coupling by straight segments. If the marginal velocity of this path is admissible, its kinetic energy is W22(p0,p1)W_2^2(p_0, p_1), so that, with the minimum over admissible pairs, (Benamou and Brenier, 2000)

W22(p0,p1)=min⁡(pt,ut) ∫01∫∥ut(x)∥2 pt(x) dx dt.(26.7.12)W_2^2(p_0, p_1) = \min_{(p_t, \mathbf{u}_t)}\ \int_0^1 \int \| \mathbf{u}_t(\mathbf{x}) \|^2\, p_t(\mathbf{x})\, d\mathbf{x}\, dt . \tag{26.7.12}

The condition in (ii) is met, for example, when the Brenier map is a smooth diffeomorphism whose derivative and inverse derivative are bounded. Without it the equality still holds, with the minimum taken over weak solutions of the continuity equation with square-integrable velocity. We do not prove this general form, and our examples need it: the optimal field for the two points has slope 1/t1/t and is not admissible.

Proof. We bound the least kinetic energy by W22W_2^2 from below and from above. Step II is the lower bound (i), and step III gives (ii).

I. Every flow defines a coupling. Let Zt\mathbf{Z}_t solve Z˙t=ut(Zt)\dot{\mathbf{Z}}_t = \mathbf{u}_t(\mathbf{Z}_t) backward in time from Z1∼p1\mathbf{Z}_1 \sim p_1. By the uniqueness fact used in the reflow proposition, Zt∼pt\mathbf{Z}_t \sim p_t for every tt, so (Z0,Z1)(\mathbf{Z}_0, \mathbf{Z}_1) is a coupling of p0p_0 and p1p_1.

II. Lower bound. The cost of this coupling is at least W22W_2^2, and Jensen's inequality for the time average bounds it by the kinetic energy:

W22(p0,p1)≤E∥Z1−Z0∥2=E∥∫01ut(Zt) dt∥2≤∫01E∥ut(Zt)∥2dt=∫01 ⁣ ⁣∫∥ut∥2 pt dx dt.\begin{aligned} W_2^2(p_0, p_1) &\le \mathbb{E} \left\| \mathbf{Z}_1 - \mathbf{Z}_0 \right\|^2 = \mathbb{E} \left\| \int_0^1 \mathbf{u}_t(\mathbf{Z}_t)\, dt \right\|^2 \\ &\le \int_0^1 \mathbb{E} \left\| \mathbf{u}_t(\mathbf{Z}_t) \right\|^2 dt = \int_0^1\!\! \int \|\mathbf{u}_t\|^2\, p_t\, d\mathbf{x}\, dt . \end{aligned}

III. Upper bound. Take an optimal coupling π⋆\pi^\star and its straight interpolation Xt=(1−t)X0+tX1\mathbf{X}_t = (1 - t)\mathbf{X}_0 + t\mathbf{X}_1, with marginal velocity ut(x)=E[X1−X0∣Xt=x]\mathbf{u}_t(\mathbf{x}) = \mathbb{E}[\mathbf{X}_1 - \mathbf{X}_0 \mid \mathbf{X}_t = \mathbf{x}]. By the marginal-velocity proposition in its weak form this pair satisfies the continuity equation with the right endpoints, and by the conditional Jensen inequality its kinetic energy is

∫01E∥E[X1−X0∣Xt]∥2 dt≤E∥X1−X0∥2=W22(p0,p1).\int_0^1 \mathbb{E}\big\|\mathbb{E}[\mathbf{X}_1 - \mathbf{X}_0 \mid \mathbf{X}_t]\big\|^2\, dt \le \mathbb{E}\|\mathbf{X}_1 - \mathbf{X}_0\|^2 = W_2^2(p_0, p_1).

The two bounds meet. ■\blacksquare

What does the theorem say about the model? Train rectified flow on an optimal pairing and the wish of the opening is granted: the floor is zero, the exact field is constant along each trajectory, and one Euler step of length one integrates it without error. Both properties are cases of equality in the proof, whose two inequalities we met in the reflow proposition. When the flow of an optimal coupling is admissible it attains the lower bound, so the inequality in III is an equality for it and the conditional variance is zero: the segments of an optimal coupling do not cross. Jensen's inequality in II is tight only if each particle moves at constant velocity, so every minimizer moves its particles along straight lines at constant speed. The converse fails, as the quarter turn showed. A flow can be straight, free of crossings and exact in one step without being cheapest; it attains W22W_2^2 only if its pairing is optimal as well (Exercise 7).

An optimal coupling is the target, then, and practice has two approximations to it. Reflow re-pairs by the model. A minibatch optimal-transport pairing (Tong et al., 2024; Pooladian et al., 2023) needs no trained model: before each training step it re-pairs the noise and data points of the batch by the assignment of least total squared distance. Exercise 5 trains the two moons with this pairing and measures what it does to the loss plateau, to the one-step score and to the length of the pairs. Neither method finds the optimal coupling of the two laws. A batch plan depends on the batch. Reflow stops at any pairing without crossings, optimal or not, as the quarter turn showed, and it inherits the errors of the first model besides.

26.7.4 Sampling with a Learned Field#

Straightening the flow is one way to save network calls. The other is to use the calls better: a solver of higher order, or steps placed where the path moves. This is open to a learned score as well as to a learned velocity, because the probability-flow ODE of Section 26.6.3 turns a score into a velocity field, and on a variance-preserving path into the very field that flow matching would learn. A sample costs one field evaluation per solver stage, and the question is how to use a budget of them. We run one experiment, on a field with no learning error, so that every error in it is the solver's.

Heun's method is second order but evaluates the field twice per step. Is it worth two evaluations? We take the probability-flow ODE with the exact score of the running mixture, components at ±2\pm 2 with variance 0.250.25, under the variance-preserving schedule with β(t)\beta(t) rising linearly from 0.10.1 to 2020. The cell integrates from t=1t = 1 to t=0t = 0 with Euler and with Heun's method (Section 26.2), and compares the endpoints of 8,0008{,}000 starting points with a Heun solution of 800800 steps. Both methods get the same budgets of 1010 to 8080 field evaluations (the row NFE of the printed table, for "number of function evaluations"), spent on two grids of times: equal steps in tt, and the squared grid tk=(1−k/K)2t_k = (1 - k/K)^2 for k=0,…,Kk = 0, \ldots, K, whose steps shrink toward the data end t=0t = 0. Heun's error falls like the square of the step and Euler's like the step, so with enough evaluations Heun must win. Are ten enough?

bmin, bmax = 0.1, 20.0
beta_fn = lambda t: bmin + t * (bmax - bmin)            # VP noise schedule
abar_fn = lambda t: np.exp(-(bmin * t + 0.5 * (bmax - bmin) * t**2))
def score_vp(q, t, means=(-2.0, 2.0), var=0.25):        # exact mixture score
    a = abar_fn(t)
    v = a * var + (1 - a)
    w = np.stack([np.exp(-(q - np.sqrt(a) * m)**2 / (2 * v)) for m in means])
    return (w * np.stack([(np.sqrt(a) * m - q) / v
                          for m in means])).sum(0) / w.sum(0)
def pf_ode(q, t):                                       # probability-flow ODE
    return -0.5 * beta_fn(t) * (q + score_vp(q, t))
def solve(q, ts, heun=False):                           # steps along grid ts
    for t1, t2 in zip(ts[:-1], ts[1:]):
        h, d1 = t2 - t1, pf_ode(q, t1)
        q = q + 0.5 * h * (d1 + pf_ode(q + h * d1, t2)) if heun else q + h * d1
    return q
grids = {'uniform': lambda K: np.linspace(1, 0, K + 1),     # equal steps in t
         'squared': lambda K: np.linspace(1, 0, K + 1)**2}  # dense near t = 0
z = rng.standard_normal(8000)
ref = solve(z, grids['uniform'](800), heun=True)        # fine reference
nfes = [10, 20, 40, 80]                                 # Heun: n // 2 steps
errs = {f'{m}, {g}': [np.abs(solve(z, grid(n // k), k == 2) - ref).mean()
                      for n in nfes]
        for g, grid in grids.items() for m, k in (('Euler', 1), ('Heun', 2))}
print(f'{"NFE":16s}' + ''.join(f'{n:8d}' for n in nfes))
for name, e in errs.items():
    print(f'{name:16s}' + ''.join(f'{v:8.4f}' for v in e))
d2l.plot(nfes, list(errs.values()), 'field evaluations', 'mean endpoint error',
         legend=list(errs), xscale='log', yscale='log')
NFE                   10      20      40      80
Euler, uniform    0.0439  0.0204  0.0099  0.0049
Heun, uniform     0.0814  0.0285  0.0086  0.0024
Euler, squared    0.1084  0.0533  0.0264  0.0131
Heun, squared     0.0340  0.0148  0.0047  0.0013

On the uniform grid the orders show in the rates. Each doubling of the budget divides Euler's error by about two and Heun's by a factor that grows from about three toward four. At equal cost, though, Heun loses at 1010 evaluations (about 0.080.08 against Euler's 0.040.04) and at 2020 (nearly 0.030.03 against 0.020.02), and leads only from 4040. On the squared grid Heun wins at every budget, and at 1010 evaluations its error, about 0.030.03, is below Euler's on either grid. Euler moves the other way: the squared grid more than doubles its error. On this field, at small budgets, the grid decides which solver wins.

How can a first-order method beat a second-order one? The endpoint error is a sum of signed step errors, and signed errors can cancel. The next cell measures how much. It takes the error of the kk-th coarse step, started from a point of the exact path, and multiplies it by the sensitivity of the endpoint to a displacement at that time, read off a neighboring trajectory of the exact flow. The product ckc_k is the step's contribution to the endpoint error, to first order. The cell prints two tables: the share ∣∑kck∣/∑k∣ck∣|\sum_k c_k| / \sum_k |c_k| that survives the summation, and the total ∑k∣ck∣\sum_k |c_k| before any cancellation, averaged over the starting points. Its last line says how much of each path's length lies between t=1t = 1 and t=0.5t = 0.5.

def exact_path(q, ts):                  # fine Heun path, and the gain dx(0)/dx(t)
    qs = [np.stack([q, q + 1e-6])]      # the path and a close neighbor
    for t1, t2 in zip(ts[:-1], ts[1:]):
        qs.append(solve(qs[-1], [t1, t2], heun=True))
    qs = np.array(qs)
    return qs[:, 0], (qs[-1, 1] - qs[-1, 0]) / (qs[:, 1] - qs[:, 0])

def step_errors(ts, qs, gain, steps, heun):   # c_k, shape (steps, starting points)
    j = np.arange(0, len(ts), (len(ts) - 1) // steps)    # coarse nodes
    return np.array([gain[b] * (solve(qs[a], ts[[a, b]], heun) - qs[b])
                     for a, b in zip(j[:-1], j[1:])])   # step error, carried to 0

paths = {g: exact_path(z, grid(400)) for g, grid in grids.items()}   # 400 fine steps
cs = {f'{m}, {g}': [step_errors(grids[g](400), qs, gain, n // k, k == 2) for n in nfes]
      for g, (qs, gain) in paths.items() for m, k in (('Euler', 1), ('Heun', 2))}
stats = {'surviving share': (lambda c: np.abs(c.sum(0)).mean() / np.abs(c).sum(0).mean(), '.2f'),
         'total of |c_k|': (lambda c: np.abs(c).sum(0).mean(), '.4f')}   # sum_k |c_k|
for title, (stat, fmt) in stats.items():
    print(f'{title:16s}' + ''.join(f'{n:8d}' for n in nfes))
    for name, c in cs.items():
        print(f'{name:16s}' + ''.join(f'{stat(c_n):8{fmt}}' for c_n in c))
d = np.abs(np.diff(paths['uniform'][0], axis=0))    # |fine step| along each path
share = (d[:200].sum(0) / d.sum(0)).mean()           # first 200 steps: t from 1 to 0.5
print(f'share of the path length covered by t = 0.5: {share:.2f}')
surviving share       10      20      40      80
Euler, uniform      0.11    0.11    0.12    0.12
Heun, uniform       0.59    0.66    0.71    0.73
Euler, squared      0.31    0.32    0.34    0.35
Heun, squared       0.25    0.36    0.41    0.42
total of |c_k|        10      20      40      80
Euler, uniform    0.2867  0.1502  0.0769  0.0389
Heun, uniform     0.1317  0.0414  0.0119  0.0032
Euler, squared    0.2472  0.1327  0.0691  0.0353
Heun, squared     0.1258  0.0397  0.0113  0.0030
share of the path length covered by t = 0.5: 0.09

By t=0.5t = 0.5 the paths have covered less than a tenth of their length, because for most of that time the noised law is close to N(0,1)\mathcal{N}(0, 1), whose score cancels the drift. Equal steps in tt use half the budget on that tenth, which is the reason for trying a crowded grid at all.

The shares explain Euler's lead. On equal steps only about an eighth of Euler's step errors survives in the endpoint, at every budget, against more than half of Heun's. Before cancellation Euler's step errors are the larger ones: its totals in the second table are more than twice Heun's at every budget. Had as large a share of them survived, Euler would have lost everywhere. Its lead is cancellation, a property of this field on this grid and not of the method. The squared grid takes it away: about a third of Euler's step errors survives there, and a quarter to two fifths of Heun's.

Surprisingly, this is nearly all that the squared grid changes. The totals hardly notice the grid. For Heun at 1010 evaluations the total is 0.130.13 on equal steps and 0.1250.125 on the squared grid, and the two stay within a few percent of each other at every budget. Euler's total is even smaller on the squared grid, by about a seventh at 1010 evaluations and a tenth at 8080, and yet its endpoint error more than doubles. So crowding the steps made the step errors only a little smaller in total. What it changed is how much of them cancels, to Heun's gain and Euler's loss. The squared grid is cruder than it looks: its step at time tt is about 2t2\sqrt{t} times the equal step, shorter below t=1/4t = 1/4 and longer above.

Samplers for image models crowd their steps toward the data as well, and they tune how much by measurement (Karras et al., 2022), as Section 17.5 describes. Our tables show why they have to measure: a comparison of solvers on one grid is a statement about that grid.

Two questions stay open. Nobody knows how to find the optimal pairing cheaply in high dimension; reflow and batch re-pairing only approach it. And the question the chapter began with, how few steps a model can take, is still answered by trial for each new field: the number of steps and their placement are tuned, not derived. Chapter 17 takes up both questions for images.

26.7.5 Summary#

The path from noise to data can be chosen. The velocity that realizes it is the posterior mean of the velocities of per-sample paths, so conditional flow matching trains it by least squares, with a loss floor CC that measures how much those paths disagree. Every model of this section and the previous one is trained this way: it fits a conditional mean of a per-sample quantity that is known in closed form, and it samples with a solver. On a Gaussian path the score, the noise and the velocity are affine in one posterior mean, so one network can be read as any of them. Straight conditional paths give a curved flow wherever segments cross; reflow re-pairs noise with the flow's own endpoints, does not increase the transport cost, and on the two moons lets one Euler step match thirty-two. The cost cannot fall below the squared Wasserstein distance, the least kinetic energy of any flow between the endpoints, which straight constant-speed motion attains only under an optimal pairing. How many steps a field needs also depends on where they are placed, because the grid decides how much of the step errors cancels. On the exact field of the running mixture, Heun's method loses to Euler below about 4040 evaluations on a uniform grid and wins at every budget on a grid crowded toward the data.

26.7.6 Exercises#

  1. Stochastic interpolants. ● Albergo et al. (2023) write the paths of this section and of the previous one as xt=atx0+btx1+ctw\mathbf{x}_t = a_t \mathbf{x}_0 + b_t \mathbf{x}_1 + c_t \mathbf{w}, where (x0,x1)(\mathbf{x}_0, \mathbf{x}_1) is drawn from a coupling of p0p_0 and p1p_1, w∼N(0,I)\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) is independent of both, and the smooth schedules satisfy a0=b1=1a_0 = b_1 = 1 and a1=b0=c0=c1=0a_1 = b_0 = c_0 = c_1 = 0. With a Gaussian p1p_1 the diffusion and rectified-flow paths are the one-sided case c≡0c \equiv 0; the latent term ctwc_t \mathbf{w} serves two-sided paths between arbitrary p0p_0 and p1p_1.

    1. Take z=(x0,x1,w)\mathbf{z} = (\mathbf{x}_0, \mathbf{x}_1, \mathbf{w}) in the marginal velocity (26.7.2). Show that it is E[a˙tx0+b˙tx1+c˙tw∣xt=x]\mathbb{E}[\dot{a}_t \mathbf{x}_0 + \dot{b}_t \mathbf{x}_1 + \dot{c}_t \mathbf{w} \mid \mathbf{x}_t = \mathbf{x}], and write the corresponding CFM loss (26.7.3).
    2. Give schedules that recover rectified flow (26.7.7) and the cosine path, whose data and noise coefficients are cos⁡πt2\cos \tfrac{\pi t}{2} and sin⁡πt2\sin \tfrac{\pi t}{2}, both with independent endpoints and p1=N(0,I)p_1 = \mathcal{N}(\mathbf{0}, \mathbf{I}).
    3. For p1=N(0,I)p_1 = \mathcal{N}(\mathbf{0}, \mathbf{I}), independent endpoints, and ct>0c_t > 0, show that the interpolant has the same marginal velocity as the interpolant with c≡0c \equiv 0 and bt2+ct2\sqrt{b_t^2 + c_t^2} in place of btb_t.
    4. For ct>0c_t > 0, show that ∇log⁡pt(x)=−E[w∣xt=x]/ct\nabla \log p_t(\mathbf{x}) = -\mathbb{E}[\mathbf{w} \mid \mathbf{x}_t = \mathbf{x}] / c_t. What does interior noise provide when p1p_1 is an arbitrary distribution rather than a Gaussian?
  2. Late decisions. Take the two-point example with data ±a\pm a.

    1. Give the point +a+a the weight ww and the point −a-a the weight 1−w1 - w. Repeat the derivation of (26.7.6) and show that the posterior mean becomes atanh⁡((1−t) ax/t2+12log⁡w1−w)a \tanh\big((1 - t)\, a x/t^2 + \tfrac12 \log\tfrac{w}{1 - w}\big). Where does one Euler step from t=1t = 1 to t=0t = 0 land now?
    2. For equal weights, show that ∂xut(0)=(1−(1−t) a2/t2)/t\partial_x u_t(0) = \big(1 - (1 - t)\, a^2/t^2\big)/t and that, as tt falls, the origin turns from attracting to repelling at t∗=12(a4+4a2−a2)t^* = \tfrac12\big(\sqrt{a^4 + 4a^2} - a^2\big), which is 22−2≈0.832\sqrt{2} - 2 \approx 0.83 for a=2a = 2. How does t∗t^* behave as a→∞a \to \infty and as a→0a \to 0? Interpret both limits.
    3. Show that away from the origin the slope ∂xut\partial_x u_t tends to 1/t1/t, and that an Euler step from t=ht = h down to t=0t = 0 lands exactly on ±a\pm a from any point where the tanh⁡\tanh is saturated. Which part of the flow, then, limits a fixed-step solver, and at which times?
    4. The floor is C=EtExVar(x0∣xt)/t2C = \mathbb{E}_t \mathbb{E}_x \textrm{Var}(x_0 \mid x_t)/t^2 with Var(x0∣xt=x)=a2sech⁡2((1−t) ax/t2)\textrm{Var}(x_0 \mid x_t = x) = a^2 \operatorname{sech}^2\big((1 - t)\, a x/t^2\big). Show that C≤a2+1C \le a^2 + 1. Then explain why the times near t=0t = 0 contribute almost nothing to CC although the conditional velocity (x−x0)/t(x - x_0)/t is unbounded there. Use the fact that the density of xtx_t near 00 is of order e−(1−t)2a2/2t2/te^{-(1 - t)^2 a^2/2t^2}/t.
  3. Kinetic energy of Gaussian paths.

    1. Show that if pt=N(0,st2)p_t = \mathcal{N}(0, s_t^2) in one dimension, the velocity ut(x)=(s˙t/st) xu_t(x) = (\dot{s}_t/s_t)\, x satisfies the continuity equation, and that its kinetic energy is ∫01s˙t2 dt\int_0^1 \dot{s}_t^2\, dt. Why does a Gaussian cloud need no other velocity?
    2. For data N(0,4)\mathcal{N}(0, 4) and noise N(0,1)\mathcal{N}(0, 1), write down sts_t for the three flows of the cell: the straight flow of the sorted pairing, the marginal flow of straight segments under the independent pairing, and the cosine path. Show that the first two kinetic energies are exactly 11 and 5−π5 - \pi.
    3. Repeat the independent pairing for data N(0,1)\mathcal{N}(0, 1). Show that its marginal flow has kinetic energy 2−π/2≈0.432 - \pi/2 \approx 0.43 although W22=0W_2^2 = 0. Which pairing costs nothing, and what is its flow?
  4. [code] One reflow round on two points. Take data ±a\pm a, noise N(0,1)\mathcal{N}(0, 1), the independent pairing, and the marginal flow (26.7.6) of the two-point example.

    1. Using the order-preservation proposition of Section 26.3.1.2 and symmetry, show that the flow map from t=1t = 1 to t=0t = 0 is ϵ↦asign⁡(ϵ)\epsilon \mapsto a \operatorname{sign}(\epsilon), so one reflow round produces the sorted pairing.
    2. Show that its cost is a2−2a2/π+1a^2 - 2a\sqrt{2/\pi} + 1, about 1.811.81 for a=2a = 2, against a2+1=5a^2 + 1 = 5 for the independent pairing, and explain why this cost is W22W_2^2.
    3. Show that the reflowed segments (1−t) asign⁡(ϵ)+t ϵ(1 - t)\, a \operatorname{sign}(\epsilon) + t\, \epsilon never cross, so that the floor of the second round is C=0C = 0, and write down its field. Is one Euler step of it exact?
    4. Integrate the closed-form field with RK4 from 20,00020{,}000 Gaussian draws at t=1t = 1 down to t=10−3t = 10^{-3} (the slope of the field grows like 1/t1/t, so stop short of 00), and check the endpoints and the cost.
    5. The floor of the independent pairing is C≈2.03C \approx 2.03 for a=2a = 2. Compute it by quadrature from the formula in part (d) of Exercise 2, and find the time above which 99%99\% of it is collected. Check the bound E∥Z1−Z0∥2≤E∥X1−X0∥2−C\mathbb{E}\|\mathbf{Z}_1 - \mathbf{Z}_0\|^2 \le \mathbb{E}\|\mathbf{X}_1 - \mathbf{X}_0\|^2 - C of the reflow proposition. How much slack does it leave here?
  5. [code] Minibatch optimal-transport pairing. Replace independent_pairs by a sampler that draws its batch in blocks of 256256 noise points and 256256 data points and re-pairs each block by the assignment of least total squared distance (scipy.optimize.linear_sum_assignment on the 256×256256 \times 256 cost matrix), and train with train_rf.

    1. Report the loss plateau, the squared energy distance at 11, 22, 88 and 3232 steps, and the mean squared pair length before and after re-pairing. Compare with the independent pairing and with reflow.
    2. Show that a re-paired noise point is still a standard Gaussian draw and a re-paired data point is still a draw from the data, so the marginal field still carries p1p_1 to p0p_0.
    3. Explain why the batch pairing is not an optimal coupling of the two distributions, and what happens as the block size grows. Which of the two re-pairing methods needs a trained model, and which inherits its errors?
  6. Conditioning of prediction targets. Take the Gaussian path (26.7.4) with one-dimensional data x0∼N(0,1)x_0 \sim \mathcal{N}(0, 1) and the cosine path.

    1. Compute, as functions of tt, the variances of the sampled training targets in Table 26.7.1: the conditional score −ϵ/σt-\epsilon/\sigma_t, the noise ϵ\epsilon, the clean point x0x_0, the velocity α˙tx0+σ˙tϵ\dot{\alpha}_t x_0 + \dot{\sigma}_t \epsilon, and the v\mathbf{v}-target αtϵ−σtx0\alpha_t \epsilon - \sigma_t x_0. Which blow up, and at which end of the path?
    2. A network trained on the noise outputs ϵ^\hat{\epsilon} with error δ\delta. Show that the implied clean point (x−σtϵ^)/αt(x - \sigma_t \hat{\epsilon})/\alpha_t carries the error σtδ/αt\sigma_t \delta/\alpha_t, and that the noise implied by a clean-point prediction with error δ\delta carries αtδ/σt\alpha_t \delta/\sigma_t. At which end of the path is each amplified?
    3. Show that on the cosine path the velocity target equals π/2\pi/2 times the v\mathbf{v}-target, so that v\mathbf{v}-prediction is velocity prediction, and that the velocity implied by a noise prediction carries the error πδ/(2αt)\pi\delta/(2\alpha_t). Which parameterizations keep the error bounded at both ends?
    4. The conversions of Table 26.7.1 hold for any data. Check (26.7.5) numerically on the mixture 12N(−2,0.25)+12N(2,0.25)\tfrac12 \mathcal{N}(-2, 0.25) + \tfrac12 \mathcal{N}(2, 0.25) on the cosine path at t=0.4t = 0.4. On a grid of points xx, compute the marginal velocity once as the posterior mean of α˙tx0+σ˙tϵ\dot{\alpha}_t x_0 + \dot{\sigma}_t \epsilon, weighting each component by its posterior probability, and once from the score of the noised mixture. The two should agree to rounding error. Which numbers in the computation change when the mixture weights become 0.80.8 and 0.20.2, and which do not?
  7. Reflow preserves marginals and can stall.

    1. Prove part (i) of the reflow proposition in detail for the straight path, whose conditional laws are point masses. For a smooth test function φ\varphi with compact support, show that ddtE φ(Xt)=E[∇φ(Xt)⋅ut(Xt)]\frac{d}{dt}\mathbb{E}\,\varphi(\mathbf{X}_t) = \mathbb{E}\big[\nabla\varphi(\mathbf{X}_t) \cdot \mathbf{u}_t(\mathbf{X}_t)\big], which is the continuity equation in weak form. Where is the tower property used, and where the Lipschitz hypothesis?
    2. Let πk\pi_k be the pairing after kk rounds. Show that Eπk∥x1−x0∥2\mathbb{E}_{\pi_k}\|\mathbf{x}_1 - \mathbf{x}_0\|^2 is non-increasing and bounded below by W22W_2^2, hence convergent.
    3. Show that if a round changes nothing, πk+1=πk\pi_{k+1} = \pi_k, then C=0C = 0 for πk\pi_k. Identify the fixed point in one dimension.
    4. In two dimensions pair each x0∼N(0,I)\mathbf{x}_0 \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) with Rx0\mathbf{R}\mathbf{x}_0, where R\mathbf{R} is the quarter-turn rotation. Show that the segments ((1−t)I+tR)x0\big((1 - t)\mathbf{I} + t\mathbf{R}\big)\mathbf{x}_0 never cross (the matrix is invertible for every tt, because its eigenvalues are (1−t)±i t(1 - t) \pm \mathrm{i}\, t), so that C=0C = 0 and reflow changes nothing, while the cost is E∥Rx0−x0∥2=4\mathbb{E}\|\mathbf{R}\mathbf{x}_0 - \mathbf{x}_0\|^2 = 4 against W22=0W_2^2 = 0. For which matrices A\mathbf{A} is the linear map x↦Ax\mathbf{x} \mapsto \mathbf{A}\mathbf{x} the gradient of a convex function, and hence an optimal pairing of N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) with its image?
  8. [code] A stochastic sampler for a flow-matching model. ●

    1. On the straight path αt=1−t\alpha_t = 1 - t, σt=t\sigma_t = t, invert (26.7.5) to get ∇log⁡pt(x)=−(x+(1−t) ut(x))/t\nabla \log p_t(\mathbf{x}) = -\big(\mathbf{x} + (1 - t)\, \mathbf{u}_t(\mathbf{x})\big)/t.
    2. Show that for every g≥0g \ge 0 the SDE dX=[ut(X)−12g2∇log⁡pt(X)]dt+g dWˉd\mathbf{X} = \big[\mathbf{u}_t(\mathbf{X}) - \tfrac12 g^2 \nabla \log p_t(\mathbf{X})\big] dt + g\, d\bar{\mathbf{W}}, integrated from t=1t = 1 down to t=0t = 0 with a Brownian motion Wˉ\bar{\mathbf{W}} that runs backward in time, has the marginals ptp_t. Substitute τ=1−t\tau = 1 - t, write the Fokker–Planck equation in τ\tau, and use ∇⋅(p∇log⁡p)=Δp\nabla \cdot (p \nabla \log p) = \Delta p. Why does the score term enter with a minus sign here? A trained velocity field therefore defines a family of stochastic samplers.
    3. Implement the sampler with Euler–Maruyama for the trained two-moons field, with g∈{0,12,1}g \in \{0, \tfrac12, 1\} and K∈{8,32,128}K \in \{8, 32, 128\} steps. Evaluate the score at t=1,1−1/K,…,1/Kt = 1, 1 - 1/K, \ldots, 1/K only, because it is singular at t=0t = 0, and report the squared energy distance of each run. Which gg needs the fewest steps for a given quality, and does noise help at K=8K = 8?
    4. Repeat for the reflowed field. Explain, from the straightness of its trajectories, why no one-step stochastic sample can match its one-step deterministic sample.

Discussions