Flow matching, rectified flow and optimal transport
Before this lesson: score matching and the "conditional target" idea (lesson 13); flow matching for images, if you want the ML side first (generative models 10); matrix square roots (linear algebra 07); Lagrange multipliers (optimization 08); conditional expectation (probability 04). Time: about 120 minutes, plus the notebook.
Why this matters #
- Fast generative ensembles. A generative weather model samples many possible future states. The cost of one sample is (solver steps) × (one network call). Straighter paths mean fewer steps. ArchesWeatherGen (Couairon et al., 2024) is a weather ensemble model trained with flow matching. Stable Diffusion 3 (Esser et al., 2024) trains rectified-flow transformers for images.
- Comparing distributions. The Wasserstein distance compares two distributions by how far mass must move. It compares a generated ensemble with observations, and its Gaussian version (the Bures formula) is the formula behind FID, the standard score for image generators.
- Seismic imaging. A Wasserstein misfit between observed and simulated seismograms is less prone to cycle skipping than the least-squares misfit in full-waveform inversion (see lesson 04).
- Data assimilation. The ensemble transform particle filter (Reich, 2013) turns a weighted ensemble into an equally weighted one with an optimal transport plan (lesson 06).
1. Predict first #
2. The picture #
One pair: a straight line #
Fix a noise point and a data point . The straight line has the constant velocity . One Euler step of size 1 from lands exactly on .
Many pairs: the lines cross, the flow bends #
Now draw many pairs. Their lines cross. An ODE cannot have crossing paths: through each point passes exactly one solution. So the best single velocity at is the average direction of all lines that pass through at time :
Averaging over crossing lines bends the paths. In the figure, grey lines are the pairs and orange curves are the paths of the flow with this average velocity, which is what a perfect model learns.
Switch the coupling between "independent" and "minibatch OT", and move the time slider. Grey: one straight line per pair, from a noise point to a data point (aqua). Orange: with the independent coupling, the paths of the exact marginal velocity , started at the same noise points. They first move toward the centre and then turn, because early on the model cannot know which data point a path will reach. With minibatch OT the pairs are re-matched to minimise : the transport cost drops, and no pair can be made cheaper by swapping partners. For an exact OT coupling the straight lines are the paths of the flow (Theorem 6).
The 1D example, in full #
Take noise and data . At the line through goes to or to with equal chance. So : every path starts toward the mean , and only later turns to or . Section 4(d) derives the whole field: .
Move the slider for the number of Euler steps ; then switch the coupling. The background is the velocity over time (horizontal) and position (vertical): violet where , yellow where . Dark lines: exact paths from 13 noise values. Orange: Euler with steps from the same values. With the independent coupling, one step sends every sample to , the mean of the data; the mean distance to the nearest data point is 2.0 for , about 0.5 for and about 0.01 for . With the monotone (OT) coupling, negative noise goes to and positive noise to : the paths are straight and one step is exact.
A better pairing gives straight paths #
Send negative noise to and positive noise to . Now no lines cross. The average over the lines through a point is the one line itself, and the paths are straight. This sorted pairing is the optimal transport coupling. There are two ways to straighten the paths:
- choose a better coupling before training (exact OT, or minibatch OT);
- train once, then re-pair each noise point with the end point of the model's own path, and train again (reflow).
In the 1D example (noise , data , independent coupling), what is the velocity of the perfect model at time ?
At the position says nothing about (independent coupling), so . The model cannot know the target yet. "Toward the nearest data point" is the velocity of the OT coupling, not of the independent one. The two directions do not cancel, because is part of both.
3. Definitions and main results #
Flows and the continuity equation #
A velocity field defines a flow: the solution of . If , the density of solves the continuity equation
In words: the density at a point changes only because mass flows in or out; no mass is created. We say " generates ". (Lesson 12 derived the Fokker–Planck equation; with zero diffusion it is this equation.)
Flow matching needs a path of densities from noise to data and a field that generates it. The flow matching (FM) loss is
We do not know , so we cannot compute this loss. The way out uses pairs.
A coupling of and is a joint distribution of whose marginals are and . The independent coupling is : draw and separately. Given a coupling, set , let be the law of , and define the marginal velocity
Theorem 1 (the marginalization trick) #
The marginal velocity generates . When is regular enough (for example, Lipschitz in ), the ODE started from has the marginals and ends at the data distribution .
Why it is true, in one line. Each pair moves mass along its own line. At a point , the total flow of mass is the sum over the lines through ; dividing by the density gives the average velocity there.
Proof of Theorem 1 (weak form)
Take any smooth test function with compact support.
- Along each line, . Take the expectation: .
- Condition on (the tower property ): this equals .
- The left side is . Integrate the right side by parts: for every . This is the weak form of .
Theorem 2 (conditional flow matching) #
Define the conditional flow matching (CFM) loss
Then , where does not depend on . So the two losses have the same gradients and the same minimizer .
- Expand: .
- The term is the same in both losses, because .
- Cross term, by the tower property: .
- What remains does not contain : .
This is the argument of denoising score matching in lesson 13: a conditional target whose conditional mean is the marginal target. The floor is the variance of the direction given the position. It is zero exactly when no two lines meet at the same time.
You train CFM with the independent coupling and a perfect network. What value does the CFM loss reach?
The best predictor of a random target is its conditional mean , and the loss left over is the conditional variance. It is positive because lines cross. A CFM loss that does not go to zero is normal; it is not a sign of a bad model.
Link to diffusion. With source and the independent coupling, (check yourself 6). A velocity model and a score model carry the same information.
Theorem 3 (rectified flow lowers convex transport costs) #
Let be the marginal velocity of a coupling , and let solve with . Assume this ODE has a unique solution (Liu, Gong and Liu, 2022, call the coupling rectifiable). Then is again a coupling of and (Theorem 1), called the rectified flow, and for every convex cost :
Proof of Theorem 3
- , so by Jensen's inequality over : .
- and have the same law (Theorem 1), so .
- , so by conditional Jensen: .
- Take expectations and integrate over : .
The new coupling is deterministic: is a function of .
Straightness. Liu et al. define . means straight paths at constant speed, so one Euler step is exact. For the two Jensen steps become equalities plus variance terms, and
Reflow. Train a new flow on the pairs , then repeat. The transport cost falls in each round by and cannot fall below . Summing over rounds gives for the -th rectified flows . The price: each round must simulate the current flow to make new pairs, and each round fits a model to model output, so errors add up. In practice one or two reflows are used, often followed by distillation into a one-step model (generative models 12).
Optimal transport: Monge and Kantorovich #
Let and be probability distributions and a cost of moving a unit of mass from to .
- Monge problem: find a map with (if then ) that minimizes . A map may not exist: cannot be split into .
- Kantorovich problem: minimize over all couplings . Mass may now be split. This is a linear program, and under mild conditions (for example, a continuous cost bounded below) a minimizer exists. For discrete weights , and a cost matrix : minimize over transport plans with and .
- Birkhoff–von Neumann: with and weights , some optimal is a permutation matrix
divided by . Then Monge and Kantorovich agree, and the Hungarian algorithm
(
scipy.optimize.linear_sum_assignment) solves the problem in . - Wasserstein distance: . It is a metric on distributions with finite -th moments.
- Brenier's theorem: for the cost , with a density, and finite second moments, the optimal map exists, is unique (-almost everywhere), and is the gradient of a convex function, . Conversely, a map with convex that pushes to is optimal.
1D OT is sorting. On a line, for every convex cost , the monotone coupling is optimal: the -th smallest source point goes to the -th smallest target point. In terms of the quantile functions and , . The reason: if two pairs cross, but , then swapping partners does not raise the cost, and for a strictly convex cost it lowers it.
Drag the points. Blue: source points; aqua: target points; each has weight . Orange: the sorted matching. Magenta dashed: the pairing in index order . The readout checks all pairings by brute force: the best one always has the sorted cost, and the orange lines never cross.
Theorem 4 (Gaussian , the Bures formula) #
For and ,
The first term moves the centre; the second term (the Bures term) reshapes the covariance. The optimal map is affine: with the symmetric positive definite matrix
Proof sketch of Theorem 4 (for ; the singular case follows by continuity)
- For any coupling, with . So OT means: make as large as possible.
- Try with symmetric positive semidefinite. Then , so we need . The matrix above solves it: substitute and use .
- Then , and by the cyclic property of the trace, .
- The map is for the convex , so it is optimal by Brenier's theorem. Put into step 1.
Special cases. In 1D, with standard deviations . For commuting covariances, the Bures term is . For non-Gaussian distributions with the same means and covariances, the formula is a lower bound on (Gelbrich's bound).
Drag the centres and the small axis handles, and move . Blue: the source ; aqua: the target , as 1-standard-deviation ellipses. Grey segments: the straight paths of the OT map for 12 points of the source ellipse. Yellow: the distribution at time (the law of ), which is again Gaussian. Try "shift only": the Bures term is . Try "rotation": the means agree, but the shape term is not zero.
What is between and in 1D (the second numbers are variances)?
In 1D, with standard deviations: . Using variances gives or , which is wrong. is , not .
Entropic OT and the Sinkhorn algorithm #
Exact OT between points costs about . A popular alternative adds an entropy term. With and , entropic OT is
The problem is strictly convex, so the solution is unique. The entropy term rewards spread-out plans, so sets how blurred the plan is.
Form of the solution. Use multipliers for the row constraints and for the column constraints (optimization 08). Setting the derivative of the Lagrangian with respect to to zero gives . Absorb the constant into :
Equivalently with the Gibbs kernel , , .
Sinkhorn alternates two scalings. Each one makes one marginal exact: , then (elementwise division). In the log domain, with :
Each iteration costs and is all matrix–vector work, so it runs well on a GPU. The number of iterations grows as shrinks. Why the log domain: in float64, so kernel entries with above about 745 underflow. When a whole row of is zero, divides by zero. The LSE with its maximum subtracted never underflows.
Move ; then press Reset and Step a few times. Rows are five source points with weights , columns five target points with weights , cost . Darker orange cells carry more mass; blue outlines mark the exact OT plan. After a row step the row sums (right) equal ; after a column step the column sums (top) equal . Small : a sharp plan close to the exact one, but thousands of iterations (about 11 500 for ). Large : a blurred plan close to the independent plan .
Theorem 5: the bias of entropic OT, and the dual problem
Theorem 5. , where OT is the exact optimal cost and .
- is a coupling and OT is the minimum over couplings, so the gap is .
- beats an exact OT plan on the entropic objective: . So the gap is .
- For every coupling, : a joint entropy is at least each marginal entropy and at most their sum.
- So the gap is .
As , tends to an exact OT plan (the one of largest entropy if there are several); as , it tends to .
The dual. Entropic OT has the unconstrained concave dual problem (up to a constant). Setting the gradient in to zero gives exactly the -update above, and the same for . So Sinkhorn is block coordinate ascent on the dual: each half-step maximizes over one block exactly. See Peyré and Cuturi, Computational Optimal Transport, ch. 4.
Theorem 6 (optimal transport paths do not cross) #
Let be optimal for the cost . If two pairs and in the support of are at the same point at some time , then they are the same pair.
- Optimality means that swapping partners cannot lower the cost (c-cyclical monotonicity): .
- Expand both sides. The squared norms cancel, and what is left is with and .
- Meeting at time means , so .
- Then forces , and so .
Consequences. Under the OT coupling, the position determines its pair, so : the floor is , the flow moves along the straight lines, , and one Euler step is exact. An optimal coupling is a fixed point of reflow. Its kinetic energy equals , the smallest possible value: by the Benamou–Brenier formula, is the minimum of over all pairs that solve the continuity equation from to .
Minibatch OT (Tong et al., 2023; Pooladian et al., 2023). In each training batch, draw noise points and data points and re-pair them by exact OT (an assignment problem). This coupling lies between the independent one and the OT one: its transport cost is lower than the independent coupling's, and it approaches the OT coupling as . Limits: an assignment costs about , and in high dimension a batch is a very coarse sample of the two distributions (empirical OT converges slowly, at a rate like ), so the paths become only partly straight.
In Theorem 6, which property of the optimal plan does the proof use?
Step 1 is c-cyclical monotonicity for two pairs; after expanding it becomes . The proof does not need a map (the plan may split mass) or a density. The cost is not a metric (it fails the triangle inequality), and the proof does not need one.
Answers to section 1. (1) All samples land at , the data mean, since : a complete collapse, at distance 2 from every data point. (2) No, by Theorem 6. Their lines may still cross in space at different times, but two particles never occupy the same place at the same time.
4. Worked example #
(a) 1D OT by sorting. Take and , weights , cost .
- Sort both: , .
- Pair in order: , , .
- Cost: .
- The pairing in the given order, , , , costs .
(b) The Bures formula. , ; , .
- Mean term: .
- Since : .
- has eigenvalues (eigenvector ) and (eigenvector ). So has eigenvalues and , and .
- Bures term: .
- . The OT map is , with (the "worked example" preset of the Bures figure).
(c) Sinkhorn on a 2×2 problem. , .
- Exact OT keeps each mass in place: cost 0.
- By symmetry , so and .
- The row sum must be : . So , and the cost is .
- For : , , cost , below the bound of Theorem 5. For : cost .
(d) The collapse, in numbers. Noise , data , independent coupling.
- Given , .
- Bayes' rule with equal prior weights: the posterior odds of against are . So .
- Since , the marginal velocity is .
- One Euler step: for every .
- The exact flow from first moves toward (down to about at ), then turns and reaches . Since 1D flows keep the order of points, the rectified coupling is : the OT coupling.
- Transport costs. Independent: . OT: . The difference is of the first rectification.
In example (d), what is the transport cost of the OT coupling ?
Expand: with . The cross term is negative because each point moves toward its own side. Straight paths do not mean zero cost: mass still has to move.
5. In code #
NumPy and SciPy check examples (a)–(c). The Hungarian algorithm in linear_sum_assignment solves the
assignment problem exactly; logsumexp gives a stable LSE.
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.linalg import sqrtm
from scipy.special import logsumexp
# (a) 1D OT: sorting agrees with the exact assignment problem.
x, y = np.array([0.0, 1.0, 3.0]), np.array([5.0, 2.0, 4.0])
C = (x[:, None] - y[None, :]) ** 2 # cost matrix |x_i - y_j|^2
rows, cols = linear_sum_assignment(C) # Hungarian algorithm: exact OT for equal weights
print(C[rows, cols].mean(), cols) # 5.6667 [1 2 0]: pairs 0->2, 1->4, 3->5
print(np.mean((np.sort(x) - np.sort(y)) ** 2)) # 5.6667: sort both and pair in order
print(np.mean((x - y) ** 2)) # 9.0: the pairing in the given order
# (b) Gaussian W2 by the Bures formula.
def bures_w2sq(m1, S1, m2, S2):
R = sqrtm(S1)
return np.sum((m1 - m2) ** 2) + np.trace(S1 + S2 - 2 * sqrtm(R @ S2 @ R)).real
m1, S1 = np.zeros(2), np.eye(2)
m2, S2 = np.array([1.0, 0.0]), np.array([[2.0, 1.0], [1.0, 2.0]])
print(bures_w2sq(m1, S1, m2, S2), 5 - 2 * np.sqrt(3)) # 1.5359 1.5359
# (c) Log-domain Sinkhorn on the 2 x 2 problem; closed form P12 = 1 / (2 (e^{1/eps} + 1)).
def sinkhorn_log(a, b, C, eps, iters=2000):
f, g = np.zeros(len(a)), np.zeros(len(b))
for _ in range(iters):
f = eps * np.log(a) - eps * logsumexp((g[None, :] - C) / eps, axis=1)
g = eps * np.log(b) - eps * logsumexp((f[:, None] - C) / eps, axis=0)
return np.exp((f[:, None] + g[None, :] - C) / eps)
a = b = np.array([0.5, 0.5])
C = np.array([[0.0, 1.0], [1.0, 0.0]])
for eps in (1.0, 0.1):
P = sinkhorn_log(a, b, C, eps)
print(eps, P[0, 1], 1 / (2 * (np.exp(1 / eps) + 1)), (C * P).sum())
# 1.0 0.13447 0.13447 0.26894 (exact OT cost is 0; the gap is below eps*log 2 = 0.693)
# 0.1 2.2699e-05 2.2699e-05 4.5398e-05
And example (d): the closed-form marginal velocity, one Euler step against an accurate ODE solve, Euler with a few steps, and the two transport costs by Monte Carlo:
from scipy.integrate import solve_ivp
def u(t, x): # exact marginal velocity of example (d)
return (2 * np.tanh(2 * t * x / (1 - t) ** 2) - x) / (1 - t)
for x0 in (0.5, -0.1, 1.5):
one_step = x0 + u(0.0, x0) # one Euler step from t = 0 to t = 1
sol = solve_ivp(u, (0.0, 1 - 1e-6), [x0], method="Radau", rtol=1e-9, atol=1e-12)
print(x0, one_step, round(sol.y[0, -1], 4))
# 0.5 0.0 2.0 / -0.1 0.0 -2.0 / 1.5 0.0 2.0: one step gives 0; the exact flow ends at ±2
z = np.random.default_rng(0).standard_normal(200_000)
for N in (1, 2, 4, 8): # Euler with N steps from many noise samples
xs = z.copy()
for k in range(N):
xs = xs + u(k / N, xs) / N
print(N, np.mean(np.minimum(np.abs(xs - 2), np.abs(xs + 2))))
# mean distance to the nearest data point: 2.0, 0.51, 0.011, 1.2e-05
x1 = np.random.default_rng(1).choice([-2.0, 2.0], size=z.size)
print(np.mean((x1 - z) ** 2), np.mean((2 * np.sign(z) - z) ** 2), 5 - 4 * np.sqrt(2 / np.pi))
# about 5.0, about 1.807, 1.8085 (= W2^2)
6. Where it shows up #
- Generative models. Stable Diffusion 3 trains rectified-flow transformers (Esser et al., 2024). Meta's Movie Gen is trained with flow matching (2024).
- Weather ensembles. ArchesWeatherGen (Couairon et al., 2024) uses flow matching to sample weather states around a deterministic forecast. Ensemble models pay per network call and per member, so the number of solver steps matters (lesson 16 compares model families).
- Seismology. Wasserstein misfits for full-waveform inversion (Engquist and Froese, 2014; Métivier et al., 2016) compare seismograms as distributions of mass along time; they are more convex with respect to time shifts than the least-squares misfit, which reduces cycle skipping (lesson 04).
- Evaluation. FID is the Bures between Gaussian fits of two sets of image features. The same formula compares an ensemble's mean and covariance with observations; by Gelbrich's bound it never overstates the true .
- Data assimilation. The ensemble transform particle filter (Reich, 2013) turns a weighted ensemble into an equally weighted one with an OT plan.
7. Common mistakes #
- Thinking the model learns . It learns the conditional mean . When paths cross, the best CFM loss is , and the learned paths are curved even though every conditional path is straight.
- Mixing time conventions. Flow matching uses noise, data; score-based diffusion often uses the opposite. Converting flips the sign of the velocity.
- versus . The optimal cost for the squared distance is , and so is the Bures formula. Take the square root before you call it a distance.
sqrtmon singular or nearly singular covariances. It can return NaN or complex values. Useeighand clip tiny negative eigenvalues to 0.- Sinkhorn with for small . It underflows; use the log domain. And remember that is above the exact OT cost (Theorem 5).
- Minibatch OT done once, or reflow done many times. The pairing must be recomputed in every batch. Each reflow round fits a model to model output, so errors pile up.
8. Check yourself #
- Compute between and in 1D (the second numbers are variances).
Answer
, so . - For the independent coupling, why does the CFM loss of the best possible model stay above zero, and
what is its value?
Answer
Lines meet, so the direction is random given the position . The best model predicts its conditional mean ; the loss left over is , the conditional variance. - Costs up to 10 and . What goes wrong in the scaling form of Sinkhorn, and what fixes it?
Answer
is as small as , which is in float64; can be and divides by zero. The log-domain updates with a stable LSE (subtract the maximum) fix it. - Where does the proof of Theorem 3 use convexity, and why are there two uses?
Answer
Step 1: Jensen over time, because is the time average of . Step 3: conditional Jensen, because is the conditional mean of given . - Source , target in 1D. Give the OT map, the velocity field of the
straight OT flow, and say whether one Euler step is exact.
Answer
. On the path, , so and . One step: , so it is exact. - With source and linear paths, express the marginal velocity through the score of .
Answer
, and Tweedie's formula ([lesson 13](/ml-for-science/13-score-matching-diffusion/)) for the Gaussian part gives . Then .
Write the continuity equation for a density moved by a velocity field .
.
What is the conditional flow matching (CFM) loss for linear paths?
with .
State the marginalization trick.
The average conditional velocity generates the marginal path , so regressing on conditional targets learns the marginal field.
Why are the learned paths curved for an independent coupling?
Lines of different pairs pass through the same point at the same time; the model learns their average direction, and averaging bends the paths.
What does reflow do, and why does it help?
It re-pairs each noise point with the end point of the current flow and trains again; convex transport costs do not increase and the paths become straighter, so fewer solver steps are needed.
What is the difference between the Monge and the Kantorovich problem?
Monge looks for a map (mass cannot be split); Kantorovich looks for a coupling (a plan that may split mass), which is a linear program.
How do you solve OT between two equal-size samples on a line?
Sort both and pair them in order; this is optimal for every convex cost of .
State the Bures formula for between two Gaussians.
.
Write the log-domain Sinkhorn update for .
; it makes the row sums of equal to .
What does control in entropic OT?
The blur of the plan: small gives a plan close to exact OT but slow Sinkhorn convergence; large gives a plan close to .
9. Interview angle #
- "Flow matching or diffusion: what is the difference?" With Gaussian paths they learn the same object up to a linear change (velocity ↔ score). They differ in the path, the loss weighting and the sampler. Flow matching regresses a velocity and needs no simulation during training.
- "Why can rectified flow sample in few steps?" Its paths are straighter (Theorem 3, reflow); for one Euler step is exact. In practice reflow is followed by distillation.
- "What is between two Gaussians? What is FID?" The Bures formula; FID is that formula applied to Gaussian fits of Inception features of real and generated images.
- "Monge versus Kantorovich?" A map versus a coupling. A map may not exist; the coupling problem is a linear program that has a solution under mild conditions.
- "How do you compute OT between points?" Not with the exact linear program (about cubic cost). Use Sinkhorn on a GPU (with its bias), minibatch OT, or sliced OT (1D sorting along random directions).
10. Practice #
The notebook for this lesson runs in Colab or in the browser. It has five exercises, each with a check cell and a folded solution:
- 1D OT by sorting, checked against the exact assignment (
linear_sum_assignment) and brute force. - The Bures formula and the OT map between two Gaussians, checked by sampling.
- Log-domain Sinkhorn on a small problem; its cost approaches the exact OT cost as , within the bound of Theorem 5.
- The exact marginal velocity for a 1D mixture, and Euler sampling with few and many steps.
- Minibatch OT pairing: the transport cost and the swap test for batch sizes from 4 to 256.
11. Watch and read #
- Lipman et al., Flow Matching Guide and Code (2024): §3.5 (the continuity equation), §4.4–4.5 (the marginalization trick; FM and CFM have the same gradient), §4.7 (optimal transport and the linear conditional flow), §4.9.2 (multisample couplings).
- Lipman et al., Flow Matching for Generative Modeling (ICLR 2023): the original paper.
- Liu, Gong and Liu, Flow Straight and Fast (ICLR 2023): rectified flow, Theorems 3.3–3.7 (marginals, convex costs, straightness, reflow).
- Tong et al., Improving and generalizing flow-based generative models with minibatch optimal transport (2023) and Pooladian et al., Multisample Flow Matching (2023): minibatch OT couplings.
- Peyré, Optimal Transport for Machine Learners (2025): §2.6 (1D OT by sorting), §2.3–2.4 (Monge and Brenier), §2.7 (the Bures formula), §3 (Kantorovich), §8 (entropic OT and Sinkhorn), §16 (flow matching).
- Peyré and Cuturi, Computational Optimal Transport (2019): ch. 2 (Kantorovich), ch. 4 (entropic regularization and Sinkhorn).
- Cuturi, Sinkhorn Distances (NeurIPS 2013): entropic OT for machine learning.
- Couairon et al., ArchesWeather & ArchesWeatherGen (2024): flow matching for weather ensembles.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.