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 and 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.
One clock and the papers' clock. This book (top) puts the data at and the noise at , noises the data forward in time, and samples by integrating a score or a velocity from to . The flow-matching papers (bottom) put the noise at and the data at and sample forward. The endpoint densities are the same; the substitution converts one clock into the other and flips the sign of every velocity.
The data are , and is a path of densities from to the noise . A sample from the noise end has two names: when it is Gaussian noise, as in the previous section, and 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 with the data and the noise. A velocity field 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,
Then, for a Lipschitz field, integrating from a sample of at down to yields a sample of at every time, and of the data at . Note the direction. The field points the way the noising goes, from data toward noise, and a sampler steps against it. If a network approximates , 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 to is the generator. Flow matching trains it without solving the ODE even once. The natural objective is the flow-matching loss
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: depends on the whole data distribution.
We therefore build the path out of pieces we can write down. Let a conditioning variable , drawn from a law , be a data point, or a pair of a noise point and a data point. For each value of , pick a small moving blob that sits on the data point at and ends in the noise at : spread over all of it if is a data point, on its own noise point if is a pair. Each blob comes with a velocity that we know in closed form. The path is the mixture of the blobs, , and we write for a particle of it: draw from , then a point of its blob at time . 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 the density is positive and continuously differentiable in , that it satisfies the continuity equation with a continuously differentiable velocity, and that the integrals below may be differentiated under the integral sign. Define on the marginal velocity
Then satisfies the continuity equation.
The velocity of the cloud at is the average of the velocities of the blobs that could have put a particle at , 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:
The last step multiplies and divides by and recognizes (26.7.2).
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:
It needs only a sample of and the closed-form conditional velocity.
Theorem (CFM trains the marginal field). Let be the marginal velocity (26.7.2) and suppose that . Then
with independent of . 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 , where , and , which is square-integrable by hypothesis. The law of is and , and the conditional mean of given is the marginal velocity, by its definition (26.7.2). The lemma splits into and , which does not involve .
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 to , when integrated from to , is what the proposition before it guarantees. The constant 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 , not zero. We call 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, , and take the path
with smooth coefficients , and . The blob around has width : at it is the data point, at the noise. This is the noising kernel of the previous section, with the noise end placed at .
Let us start with the smallest case, Gaussian data in one dimension on the cosine path , . The marginal is with , the score is , and the velocity is : a Gaussian cloud only stretches or shrinks (Exercise 3). With at we get , and a particle at has velocity . The field points inward because noising shrinks this cloud, from width at to width at . A sampler runs against it and stretches the cloud back to width . With every is the standard Gaussian and the cloud never moves: .
Proposition (score–velocity identity). For the Gaussian path (26.7.4), at any with and on , the marginal velocity is an affine function of the marginal score:
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 , 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, . Differentiating the path gives the conditional velocity , and . Taking the posterior mean as in (26.7.2),
The marginal score is the posterior mean of the scores of the kernels, which is Tweedie's formula of the previous section. The kernel has score , so
Substituting this into the velocity and collecting the and terms gives (26.7.5).
Two special cases are worth writing out. On a variance-preserving path, , so and the coefficient of the score collapses to : . For the variance-preserving SDE of the previous section, , so and the velocity is . This is the probability-flow velocity (Section 26.5.4) with and . 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: gives , the stretching rate found above.
On the straight path , , which the rest of the section uses, the identity reads .
The same posterior mean underlies the targets that networks are trained on in practice (Table 26.7.1).
| Network predicts | Posterior mean | From the score |
|---|---|---|
| score | ||
| noise | ||
| clean point | ||
| velocity | the identity (26.7.5) | |
| -prediction |
Each row is a -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 with probability each, with : the two modes of the chapter's running mixture with their width removed. The noise is , drawn independently of . We take the Gaussian path with and , which joins each data point to its noise point by a straight line at constant speed: , with velocity .
Take the data point as the conditioning variable, . Given , the position is , a positive density for , so the marginal-velocity proposition applies. Eliminating expresses the velocity as a function of the current position, . Run backward in time, the particle heads for its data point at the speed that arrives exactly at .
To average this velocity we need the posterior of at a point . The posterior odds of against at are the ratio of the two Gaussian densities. In the exponent the terms and cancel and only the cross term survives, so the odds are and the posterior mean is . The marginal velocity is therefore
Run backward in time, the cloud at heads for the average of the two targets, weighted by how plausible each is from , at the speed that arrives on time. At the velocity is ; at it is . Three properties can be read off (26.7.6), and Figure 26.7.2 draws the first two.
- At the field is . The noise sample carries no information about its target, so the posterior mean is the data mean . One Euler step from to , , sends every sample to . This holds for any data under independent pairing: , so one step of the exact field lands on the data mean.
- The origin first attracts, then repels. As falls, a sampler moves against , so a positive slope at the origin pulls particles toward it and a negative slope pushes them away. The slope is : at , zero at (the root of ), at and at . Particles near drift toward until falls to and leave for a mode only later, so the flow chooses a mode late. Far from the origin the saturates and , the conditional velocity itself.
- The floor is collected near the noise. The target has mean square . Of this, is floor, with , and the remaining is the mean square of the marginal velocity. Nearly all of comes from , where the two blobs overlap and a position does not tell which point its particle is bound for. Below it does, and only about a thousandth of the floor is collected there, although the conditional velocity grows without bound (Exercise 2).
Two data points at and standard Gaussian noise with independent pairing; sampling runs from the noise at (right) to the data at (left). (a) Trajectories of the exact marginal flow over the one-standard-deviation bands of the two conditional blobs: until falls to every trajectory moves toward , and those that start near leave for a mode only below . (b) The velocity is at , its slope at the origin turns negative and steep as falls, and it tends to 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 to with , , and equal Euler steps, starting from the whole noise law, and prints how much of the mass lands within of a data point, together with the mean of 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 is : 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 , which is 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 dimensions the same construction pairs a data sample with a noise sample , drawn independently, and joins them by a straight line traversed at constant speed:
The conditional velocity does not depend on , and the CFM loss (26.7.3) becomes the rectified flow objective (Liu et al., 2023; Lipman et al., 2023)
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 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 of a smooth test function (Exercise 7).
Why does the flow bend? Two segments that cross at 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 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.
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 to the data at , 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 and with finite first moments,
where and are independent. It compares the mean distance between a point of and a point of 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 . 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 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 .
The model is a small tanh network that takes 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 batches, because single
batches scatter, and over the two coordinates, so the printed value is
.
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 is the conditional variance of
given , averaged over
. Can we know it before we train? For a finite data set we can, without
any network. Given , the posterior of puts on
each training point a weight proportional to
. The
target is ,
so its conditional variance is the posterior variance of
divided by . The function pairing_floor averages this quantity over
draws of 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 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 units and steps of 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 per coordinate, within a few hundredths of the floor. A loss of 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 per coordinate, one each from the noise and the standardized data, and of it is floor. The field itself therefore has a mean square of only about , and its error is a few percent of that. We shall meet this error again in the samples.
Sampling integrates
from down to with Euler's method
(Section 26.2): steps of length , each of
which subtracts at
. 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 . For
the trained field, the cell integrates the noise array z_eval with
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
.
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 to , the same order as the point mass at the mean (): the network has learned, imperfectly, the collapse that the exact field performs at . Two steps score to , four to , eight about 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 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 , , and 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 with the endpoint 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 , the mean over the pairs of a convex function of the displacement, such as its squared length. In the statement capitals denote random paths: is the straight segment of a pair, and 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 of a data point and a noise point have finite second moments, let , let be the marginal velocity of this straight path, and let solve backward in time from the noise end, . Assume that has a positive density for every and that is continuously differentiable and Lipschitz in with a constant independent of , so that this flow exists. Then (i) has the law of for every , in particular ; (ii) for every convex function ,
Proof. (i) The law of satisfies the continuity equation with , by the marginal-velocity proposition with in the weak form that covers point masses (Exercise 7). The law of satisfies it too, because moves with the field . Both equal at , 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 , 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:
The first inequality is Jensen's inequality for the time average. The equality uses (i) to replace by and then the definition of the marginal velocity. The last inequality is the conditional Jensen inequality.
With the last step loses exactly the conditional variance, so the cost falls at least by the floor of the old pairing: . The floor , 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 for each but not up to : the slope of the two-point field at grows without bound as . The proof then covers the flow down to time only: it gives (i) for , and (ii) in the form . The limit 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 with (Exercise 4). This pairing costs against for the independent one, and its segments never cross, so the second round has and its field is integrated exactly by one Euler step.
For the two moons, the cell draws fresh noise points, integrates
the trained model for 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 , 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 , and 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 : 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 . For the exact marginal flow the proposition therefore promises new pairs that cost at most about .
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 . It could not have done better. The reflowed network was trained to reproduce the original's -step endpoints, so it inherits the first model's error along with its samples.
The mean squared length of the pairs drops from to about , far below the 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 -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 of and 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,
where is the set of couplings. So 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 , 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 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 , , and noise . The sorted pairing sends each quantile to the same quantile, , and costs . The independent pairing costs . 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
The distance separates the cost of shifting the mean from the cost of stretching the width. Between and it is , against 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 the velocity . No two trajectories cross, and the cloud ends where it started, so . Yet every particle moves, at speed . 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 with its quarter turn and join the two by a segment. The segments never cross, because that matrix is invertible for every , and each is traversed at constant speed. So and reflow leaves the pairing unchanged, yet it costs against . 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 is not symmetric.
Three ways to move a Gaussian. (a) Independent pairing of data at with noise at , drawn for ten equally spaced quantile levels (): segments cross, and the mean squared displacement is . (b) The sorted pairing never crosses and costs , 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 . The chords that pair each point with its quarter turn (arrows) are straight, never cross and cost . The cloud ends where it started, so : 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 to in unit time along some path . By Jensen's inequality for the time average,
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, . The carousel has kinetic energy , all of it wasted.
Kinetic energy also ranks flows with the same endpoints. Take three flows between data and noise : 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 , so their velocity is and the kinetic energy is (Exercise 3). The cell first checks the two pairing costs, and , 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 . The surprise is the order of the other two. The straight segments of the independent pairing produce a marginal flow that costs , more than the cosine path's . Its variance first shrinks, as falls from to , 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 , 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 and have finite second moments, and let one of them, here the noise , have a density. Call a pair admissible if is continuously differentiable and Lipschitz in with a constant independent of , and the pair satisfies the continuity equation with the endpoints and . (i) Every admissible pair has kinetic energy at least . (ii) Join the pairs of an optimal coupling by straight segments. If the marginal velocity of this path is admissible, its kinetic energy is , so that, with the minimum over admissible pairs, (Benamou and Brenier, 2000)
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 and is not admissible.
Proof. We bound the least kinetic energy by from below and from above. Step II is the lower bound (i), and step III gives (ii).
I. Every flow defines a coupling. Let solve backward in time from . By the uniqueness fact used in the reflow proposition, for every , so is a coupling of and .
II. Lower bound. The cost of this coupling is at least , and Jensen's inequality for the time average bounds it by the kinetic energy:
III. Upper bound. Take an optimal coupling and its straight interpolation , with marginal velocity . 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
The two bounds meet.
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 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 with variance , under the variance-preserving schedule with rising linearly from to . The cell integrates from to with Euler and with Heun's method (Section 26.2), and compares the endpoints of starting points with a Heun solution of steps. Both methods get the same budgets of to field evaluations (the row NFE of the printed table, for "number of function evaluations"), spent on two grids of times: equal steps in , and the squared grid for , whose steps shrink toward the data end . 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 evaluations (about against Euler's ) and at (nearly against ), and leads only from . On the squared grid Heun wins at every budget, and at evaluations its error, about , 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 -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 is the step's contribution to the endpoint error, to first order. The cell prints two tables: the share that survives the summation, and the total before any cancellation, averaged over the starting points. Its last line says how much of each path's length lies between and .
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 the paths have covered less than a tenth of their length, because for most of that time the noised law is close to , whose score cancels the drift. Equal steps in 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 evaluations the total is on equal steps and 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 evaluations and a tenth at , 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 is about times the equal step, shorter below 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 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 evaluations on a uniform grid and wins at every budget on a grid crowded toward the data.
26.7.6 Exercises#
-
Stochastic interpolants. ● Albergo et al. (2023) write the paths of this section and of the previous one as , where is drawn from a coupling of and , is independent of both, and the smooth schedules satisfy and . With a Gaussian the diffusion and rectified-flow paths are the one-sided case ; the latent term serves two-sided paths between arbitrary and .
- Take in the marginal velocity (26.7.2). Show that it is , and write the corresponding CFM loss (26.7.3).
- Give schedules that recover rectified flow (26.7.7) and the cosine path, whose data and noise coefficients are and , both with independent endpoints and .
- For , independent endpoints, and , show that the interpolant has the same marginal velocity as the interpolant with and in place of .
- For , show that . What does interior noise provide when is an arbitrary distribution rather than a Gaussian?
-
Late decisions. Take the two-point example with data .
- Give the point the weight and the point the weight . Repeat the derivation of (26.7.6) and show that the posterior mean becomes . Where does one Euler step from to land now?
- For equal weights, show that and that, as falls, the origin turns from attracting to repelling at , which is for . How does behave as and as ? Interpret both limits.
- Show that away from the origin the slope tends to , and that an Euler step from down to lands exactly on from any point where the is saturated. Which part of the flow, then, limits a fixed-step solver, and at which times?
- The floor is with . Show that . Then explain why the times near contribute almost nothing to although the conditional velocity is unbounded there. Use the fact that the density of near is of order .
-
Kinetic energy of Gaussian paths.
- Show that if in one dimension, the velocity satisfies the continuity equation, and that its kinetic energy is . Why does a Gaussian cloud need no other velocity?
- For data and noise , write down 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 and .
- Repeat the independent pairing for data . Show that its marginal flow has kinetic energy although . Which pairing costs nothing, and what is its flow?
-
[code] One reflow round on two points. Take data , noise , the independent pairing, and the marginal flow (26.7.6) of the two-point example.
- Using the order-preservation proposition of Section 26.3.1.2 and symmetry, show that the flow map from to is , so one reflow round produces the sorted pairing.
- Show that its cost is , about for , against for the independent pairing, and explain why this cost is .
- Show that the reflowed segments never cross, so that the floor of the second round is , and write down its field. Is one Euler step of it exact?
- Integrate the closed-form field with RK4 from Gaussian draws at down to (the slope of the field grows like , so stop short of ), and check the endpoints and the cost.
- The floor of the independent pairing is for . Compute it by quadrature from the formula in part (d) of Exercise 2, and find the time above which of it is collected. Check the bound of the reflow proposition. How much slack does it leave here?
-
[code] Minibatch optimal-transport pairing. Replace
independent_pairsby a sampler that draws its batch in blocks of noise points and data points and re-pairs each block by the assignment of least total squared distance (scipy.optimize.linear_sum_assignmenton the cost matrix), and train withtrain_rf.- Report the loss plateau, the squared energy distance at , , and steps, and the mean squared pair length before and after re-pairing. Compare with the independent pairing and with reflow.
- 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 to .
- 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?
-
Conditioning of prediction targets. Take the Gaussian path (26.7.4) with one-dimensional data and the cosine path.
- Compute, as functions of , the variances of the sampled training targets in Table 26.7.1: the conditional score , the noise , the clean point , the velocity , and the -target . Which blow up, and at which end of the path?
- A network trained on the noise outputs with error . Show that the implied clean point carries the error , and that the noise implied by a clean-point prediction with error carries . At which end of the path is each amplified?
- Show that on the cosine path the velocity target equals times the -target, so that -prediction is velocity prediction, and that the velocity implied by a noise prediction carries the error . Which parameterizations keep the error bounded at both ends?
- The conversions of Table 26.7.1 hold for any data. Check (26.7.5) numerically on the mixture on the cosine path at . On a grid of points , compute the marginal velocity once as the posterior mean of , 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 and , and which do not?
-
Reflow preserves marginals and can stall.
- Prove part (i) of the reflow proposition in detail for the straight path, whose conditional laws are point masses. For a smooth test function with compact support, show that , which is the continuity equation in weak form. Where is the tower property used, and where the Lipschitz hypothesis?
- Let be the pairing after rounds. Show that is non-increasing and bounded below by , hence convergent.
- Show that if a round changes nothing, , then for . Identify the fixed point in one dimension.
- In two dimensions pair each with , where is the quarter-turn rotation. Show that the segments never cross (the matrix is invertible for every , because its eigenvalues are ), so that and reflow changes nothing, while the cost is against . For which matrices is the linear map the gradient of a convex function, and hence an optimal pairing of with its image?
-
[code] A stochastic sampler for a flow-matching model. ●
- On the straight path , , invert (26.7.5) to get .
- Show that for every the SDE , integrated from down to with a Brownian motion that runs backward in time, has the marginals . Substitute , write the Fokker–Planck equation in , and use . Why does the score term enter with a minus sign here? A trained velocity field therefore defines a family of stochastic samplers.
- Implement the sampler with Euler–Maruyama for the trained two-moons field, with and steps. Evaluate the score at only, because it is singular at , and report the squared energy distance of each run. Which needs the fewest steps for a given quality, and does noise help at ?
- 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.