Flow matching and rectified flow
Before this lesson: lesson 04 (continuous flows and the continuity equation), lesson 08 (conversions between targets, Tweedie's formula) and lesson 09 (the probability-flow ODE, Euler sampling, DDIM = Euler, NFE). Optimal transport appears only in the last part; the ML for science track treats it in depth. Time: about 100 minutes, plus the notebook.
Why this matters #
Continuous normalizing flows (lesson 04) are trained by maximum likelihood, which needs an ODE solve and a trace estimate for every training example: slow and noisy. Flow matching (Lipman et al. 2023; Liu et al. 2023; Albergo and Vanden-Eijnden 2023, as "stochastic interpolants") removes the ODE from training. The loss is a mean squared error, as simple as the diffusion loss of lesson 07.
Rectified-flow transformers generate images in Stable Diffusion 3 (Esser et al. 2024) and Flux; Meta's Movie Gen is trained with flow matching. In science, flow matching emulates weather fields, molecules and seismic waveforms, and Riemannian flow matching works on spheres and other manifolds. Because sampling cost is (steps) × (network cost), the straightness of the paths decides the cost of every sample. Reflow, minibatch optimal transport and distillation (lesson 12) all aim at straighter paths.
1. Predict first #
2. The picture #
One pair: a straight line #
Fix one data point and one noise point . The straight line
starts at the data () and ends at the noise (). Its velocity is constant: . If you knew the pair, one Euler step of size 1 from would land exactly on . This line is called the conditional path (it is conditioned on the pair), and is the conditional velocity.
Many pairs: the lines cross #
Now draw many pairs: data points from , noise points from , independently. Their lines cross. At one place and one time, different lines move in different directions. But a network sees only the place and the time ; it does not know which pair a point came from. So it cannot follow every line.
Move the time slider in the conditional paths view. Each yellow point moves on a straight magenta line from its noise point (green) to its data point (blue); the violet arrows show its velocity in the sampling direction (toward ). Near the center, close points move in very different directions. Now switch to marginal flow: one smooth velocity field moves every point, the paths bend, and the orange end points land on the modes. Compare the transport costs: about 5.6 for the random pairs, about 1.05 for the start and end points of the marginal flow. Then try minibatch OT for the pairs. The velocity of the marginal flow is computed exactly from the known mixture, not learned.
The best guess is an average #
What is the best single velocity at the point and time ? Under the squared error, the best prediction is the conditional mean (lesson 08): the average of the velocities of all lines that pass through at time , each weighted by how likely its pair is to be there. This average is the marginal velocity
The next figure makes this concrete in one dimension. With the two data points , exactly two lines pass through each point : one that ends at and one that ends at .
Drag the yellow point in the plane. The two dashed lines are the conditional paths through it; the darker one has the larger posterior weight. The grey arrows are their velocities, the violet arrow is the weighted average, the marginal velocity. Between the modes (try between the modes) the two lines have equal weight and their velocities cancel. Near a mode at little noise, one line has all the weight and the marginal velocity equals its velocity. The magenta curves are paths of the marginal ODE: they never cross, and they bend where the weights change.
A training pair is , , and the time is . What are the network input and the CFM regression target?
, and the target is the conditional velocity . The first option has the sign of the reversed time convention (). The conditional mean is what the network learns, not what you feed it; you cannot compute it from a batch.
3. Definitions and main results #
Flows, paths and the continuity equation #
A velocity field defines a flow: . If has density and you solve the ODE, the density of solves the continuity equation
(lesson 04). We say that generates the path . A probability path is a family of densities from the data () to the noise ().
Fix the linear path: draw and independently and set . Its density is the marginal path. If we knew a velocity that generates it, we could train a network with the flow matching (FM) loss
But we do not know . The next two theorems find it and remove it from the loss.
Theorem 1 (the marginalization trick) #
The marginal velocity generates the marginal path .
Intuition. The density at changes because points flow in and out. Every pair moves with its own velocity, but for the flux of mass through only the average velocity of the mass at matters.
Proof (weak form; is any smooth test function with compact support).
- Each pair moves on its line, so by the chain rule . Take expectations: .
- Condition on (the tower property): is fixed given , so the right side is
- In integrals: (integration by parts; vanishes far away).
- This holds for every , so : the continuity equation.
When is regular enough (for example, Lipschitz in ), the ODE started from therefore has the marginals and ends at .
Theorem 2 (conditional flow matching, CFM) #
Define the conditional flow matching loss
Then , where is the marginal velocity and does not depend on . So the two losses have the same gradient and the same minimizer .
Proof. Fix and write .
- Expand: .
- The first term is the same in both losses, because in both.
- The cross term, by the tower property:
This is the cross term of . 4. So , which does not contain . Written as one term:
This is the same argument as denoising score matching (lesson 06): a conditional target whose conditional mean is the marginal target. The floor is the variance of the direction given the position. It is zero only when no two lines cross. So the CFM loss never reaches zero for a model with crossing lines, even a perfect one; do not read its value as an error.
Your flow-matching network has reached the minimum of the CFM loss, but the loss value is about 1.0, not 0. What does this tell you?
By Theorem 2, . A perfect network makes but cannot remove , because different pairs pass through the same with different targets. To judge a model, compare samples, or compare the loss with a model of known quality.
Sampling #
Training gives . To sample, draw at and integrate backward to . With Euler on a grid :
Each step costs one NFE, as in lesson 09. Heun and other solvers work the same way.
Choose the number of Euler steps. With 1 step every sample (orange) lands exactly at the center, the mean of the data. With 2 steps the samples form a ring of radius about 1.4, inside the data. With 4 steps about 83% are on a mode, and with 8 steps about 97%. The magenta lines are Euler paths. The velocity is exact (computed from the known mixture), so every error you see comes from the step size.
Why one step lands on the mean. At the point says nothing about , so , and (from the formula below). One step of size 1 gives : the same point for every noise. The first velocity is an average direction toward the data mean, and the paths turn only later. This is the price of crossing lines.
Flow matching and diffusion #
Take a general Gaussian path (lessons 08–09); the linear path has and . Write (the denoiser) and .
Proposition 3 (the velocity is a denoiser). The marginal velocity of the path is
Proof.
- The conditional velocity is . Its conditional mean given is , because the expectation is linear.
- Linear path: , , so .
- Tweedie's formula (lesson 08) for is . Put it into step 2: .
So a velocity network, a denoiser and a score network carry the same information: they are linear maps of each other at every . In lesson 08's language, the velocity is one more prediction target, with and .
The PF-ODE is a flow-matching ODE. For the VP path, the probability-flow ODE of lesson 09 has the drift with and . With this drift is , the marginal velocity of Proposition 3. So diffusion's PF-ODE is the flow-matching ODE of its own Gaussian path. Diffusion and flow matching differ in the path (), in the loss weight over noise levels (lesson 08) and in the sampler grid, not in the kind of object they learn.
Proposition 4 (an Euler step of flow matching is a DDIM step). For the linear path, one Euler step from to with the exact velocity gives the same point as the DDIM step with the same denoiser output.
Proof. Euler: . DDIM (lesson 09) with , :
This is Theorem 3 of lesson 09 again: on the linear path, and are already straight-line coordinates. Flow matching with Euler steps and DDIM are one sampler on different time grids.
A model from a paper with the convention " noise, data" outputs at . What is the velocity in this track's convention, and at which ?
, and since the velocity changes sign: . Forgetting either the time map or the sign makes the sampler run the wrong way or at the wrong noise level.
Straight conditional paths, curved marginal paths #
Every conditional path is a straight line. The marginal paths are not, because the average direction at a point changes with time: early (near ) all lines through a point point toward the data mean on average; late (near ) only the lines from one nearby data point carry weight. The marginal paths also cannot cross: an ODE with a Lipschitz velocity has exactly one solution through each point , so two paths that meet at one time were the same path all along. Crossing lines are replaced by paths that bend away from each other.
Curvature costs steps. Euler is exact on a straight path with constant speed (lesson 09: a step is exact when the slope does not change along it), and it errs where the path turns. So we want a coupling of noise and data whose lines do not cross. Two ways to get one: rectified flow and optimal transport.
Rectified flow and reflow #
Let be any coupling of the data and the noise (at first, the independent one), let be its marginal velocity, and let solve backward from . Liu, Gong and Liu (2023) call the rectified coupling. By Theorem 1, has the data distribution, so is again a coupling of the same two distributions, now a deterministic one: is a function of .
Theorem 5 (rectified flow does not increase convex transport costs). If the ODE has unique solutions, then for every convex function ,
Proof (two uses of Jensen's inequality)
- , an average over time. Jensen in : .
- and have the same law (Theorem 1), so .
- , so conditional Jensen gives .
- Take expectations in step 3, integrate over , and chain with steps 1–2: .
For both inequalities become identities with explicit gaps (the variance decompositions of a time average and of a conditional mean):
where is the CFM floor of Theorem 2 and , the straightness, measures how much the flow's velocity changes along its paths ( means straight paths at constant speed, so one Euler step is exact).
Reflow. Train a new flow-matching model on the rectified pairs instead of independent pairs. Its lines come from a deterministic, non-crossing map, so they cross much less: is small and the new paths are straighter. Repeating gives the -rectified flow. By the identity in the proof, the squared transport cost falls by in each round and can never fall below 0; Liu et al. derive from this that .
Compare the two flows and move the number of Euler steps. Before reflow, the exact magenta paths from the noise points (green) first head toward 0 and turn late; the orange Euler polylines with 1 step all end at 0 (error 1.0), with 2 steps at (error 0.44). Switch to after one reflow: the paths are straight lines, and Euler is exact with any number of steps. In 1D a flow keeps the order of points, so the rectified pairing sends negative noise to and positive noise to : it is the optimal transport pairing, with cost instead of .
What reflow costs. Each round must simulate the current flow to produce many pairs (pairs × steps × network cost), and it fits a model to model outputs, so errors accumulate. In practice one or two rounds are used, often followed by distillation into a one-step model (lesson 12). On CIFAR-10, Liu et al. report FID 378 for one Euler step of the 1-rectified flow, and 4.85 for the 2-rectified flow plus distillation. InstaFlow (Liu et al. 2024) applies reflow and distillation to Stable Diffusion for one-step text-to-image generation.
What does one round of reflow change?
Reflow keeps the data and the noise distributions and the regression loss. It only replaces the independent pairs by the deterministic pairs of the trained flow. These pairs have no higher transport cost for any convex cost (Theorem 5), their lines cross much less, and fewer Euler steps are needed.
Minibatch optimal transport and further directions
Optimal transport pairs do not cross. Among all couplings of and , the one with the smallest is the optimal transport (OT) coupling; its cost is . If two of its pairs met at a time , swapping their partners would lower the cost, which is impossible. (Write , ; optimality gives , and meeting means , which forces .) So under the OT coupling the lines do not cross, , the marginal velocity is the line velocity, and one Euler step is exact. By the Benamou–Brenier theorem this flow also has the smallest kinetic energy of all flows between the two distributions.
Minibatch OT (Tong et al. 2024; Pooladian et al. 2023). In each training batch, draw data and noise
points and re-pair them by an exact assignment (scipy.optimize.linear_sum_assignment). The coupling lies
between independent and OT. For the 8 Gaussians the mean squared distance of the pairs is about 6.0 for
independent pairs, 1.7 for , 1.2 for and 1.0 for . Limits: an exact assignment costs about
, and in high dimensions a batch is a coarse sample of the distributions, so the straightening is only
partial. Conditional generation and large image models often see little gain.
Beyond Euclidean data. Riemannian flow matching replaces straight lines by geodesics on a manifold (the sphere for global weather, rotation groups for molecules); discrete flow matching works on tokens. The ML for science track covers optimal transport, Sinkhorn and flow matching on the sphere.
Answers to section 1. (1) All samples land at , the data mean: one Euler step gives for every noise point. (2) No. The marginal ODE has exactly one path through each point ; crossing training lines are replaced by curved paths that bend away from each other. (3) No. It outputs the conditional mean , the average over all pairs that could have produced . The loss that remains at the optimum is the floor of Theorem 2.
4. Worked example #
Data with probability each, noise , linear path.
(a) The marginal velocity at , .
- Given , .
- Posterior weights by Bayes' rule (equal priors): (in general ). So and .
- Conditional velocities: the line to has , so ; the line to has , so . (Check: .)
- Marginal velocity: .
- Check with the denoiser: ✓, and ✓.
The velocity is negative: moving toward (sampling), grows toward the more likely data point .
(b) Euler with one and two steps. At , , so .
- One step: for every .
- Two steps: first . At , and . Then .
- For : , an error of against the exact end point . The mean error over is .
(c) Reflow in 1D. The exact flow keeps the order of points, so it sends to and to : .
- Independent pairs: (the cross term vanishes by independence).
- Rectified pairs: , using .
- The drop equals of the first rectification. After reflow the lines from to never cross, so the new velocity is , constant along each line, and one Euler step is exact.
(d) Converting a velocity. A model in the reversed convention outputs at for some . In this track's time and . The implied clean sample at is , and the implied noise is . Check: ✓.
5. In code #
NumPy checks the worked example, Theorem 2, the Euler formulas, Proposition 4 and the minibatch OT costs. The notebook has these cells, a small trained model and the exercises.
import numpy as np
from scipy.optimize import linear_sum_assignment
# Two-point data x0 in {-1, +1}, noise eps ~ N(0, 1), path x_t = (1 - t) x0 + t eps
def v_marg(x, t): # exact marginal velocity (x - D) / t
return (x - np.tanh(x * (1 - t) / t**2)) / t
# (a) the worked example at t = 0.5, x = 0.3
t, x = 0.5, 0.3
w_plus = 1 / (1 + np.exp(-2 * x * (1 - t) / t**2))
u_plus, u_minus = (x - 1) / t, (x + 1) / t
print(round(w_plus, 4), round(w_plus * u_plus + (1 - w_plus) * u_minus, 4), round(v_marg(x, t), 4))
# 0.7685 -0.4741 -0.4741
# (b) CFM = FM + constant: shift the exact v by 0.1; the CFM loss rises by exactly 0.1^2 = 0.01
rng = np.random.default_rng(0)
n = 2_000_000
x0 = rng.choice([-1.0, 1.0], n)
eps = rng.standard_normal(n)
tt = rng.uniform(0.05, 1.0, n) # avoid t near 0, where v is steep
xt = (1 - tt) * x0 + tt * eps
target = eps - x0
cfm = lambda v: np.mean((v - target) ** 2)
print(round(cfm(v_marg(xt, tt)), 4), round(cfm(v_marg(xt, tt) + 0.1) - cfm(v_marg(xt, tt)), 4))
# 1.0707 0.01 (the first number is the floor V > 0; the second is the FM loss of the shifted model)
# (c) Euler from t = 1: one step gives the data mean, two steps give tanh(eps)
e = np.array([-1.5, 0.2, 1.0])
x1 = e - 1.0 * v_marg(e, 1.0)
xh = e - 0.5 * v_marg(e, 1.0)
x2 = xh - 0.5 * v_marg(xh, 0.5)
print(x1, np.round(x2, 4), np.round(np.tanh(e), 4)) # [0. 0. 0.] [-0.9051 0.1974 0.7616] (twice)
# (d) an Euler step of flow matching is a DDIM step (a_t = 1 - t, sigma_t = t)
D, x, t, t2 = 0.4, 1.3, 0.7, 0.45 # any denoiser output, state and two times
euler = x + (t2 - t) * (x - D) / t
eps_hat = (x - (1 - t) * D) / t
ddim = (1 - t2) * D + t2 * eps_hat
print(round(euler, 6), round(ddim, 6)) # 0.978571 0.978571
# (e) minibatch OT: pair B data points with B noise points by an exact assignment
K, s = 8, 0.15
MU = np.array([[2 * np.cos(2 * np.pi * k / K), 2 * np.sin(2 * np.pi * k / K)] for k in range(K)])
for B in (1, 16, 64, 256):
costs = []
for _ in range(4096 // B):
xb = MU[rng.integers(0, K, B)] + s * rng.standard_normal((B, 2))
eb = rng.standard_normal((B, 2))
C = ((xb[:, None] - eb[None]) ** 2).sum(-1)
r, c = linear_sum_assignment(C)
costs.append(C[r, c].mean())
print(B, round(np.mean(costs), 2))
# 1 6.03 / 16 1.68 / 64 1.1 / 256 0.97 (independent pairs: E|eps|^2 + E|x0|^2 = 2 + 4.045)
The CFM loss of the exact velocity is about 1.07 here: the model is perfect, but the loss is far from 0. Shifting the velocity by 0.1 raises the loss by exactly , the FM loss of the shifted model, as Theorem 2 says.
6. Where it shows up #
- Image and video models. Stable Diffusion 3 trains a rectified-flow transformer with the linear path and samples from a logit-normal distribution, shifted toward high noise for large images (Esser et al. 2024). Flux uses the same objective. Meta's Movie Gen is trained with flow matching.
- Few-step generation. Reflow, InstaFlow and other straightening methods prepare a flow for distillation into one or a few steps (lesson 12).
- Guidance and latent models. Classifier-free guidance (lesson 11) works on velocities as on scores, since they are linear maps of each other; most large flow models run in the latent space of an autoencoder (lesson 13).
- Science. Flow matching emulates weather and climate fields, generates molecules and protein structures (often with Riemannian flow matching on rotations and spheres), and samples seismic waveforms. When an emulator must produce many ensemble members, the straightness of its paths sets the compute budget.
- Likelihoods. A trained flow is a continuous normalizing flow, so its exact log-likelihood can be computed with the instantaneous change of variables of lesson 04, at the cost of an accurate ODE solve.
7. Common mistakes #
- Thinking the model learns . It learns the conditional mean. When lines cross, the best CFM loss is , and the marginal paths are curved although every training path is straight.
- Mixing time conventions. Papers use "data at 0" or "data at 1". Converting maps and flips the sign of the velocity. A sampler that runs the wrong way produces noise, not data.
- Reading the CFM loss as an error. Its floor depends on the data and the coupling. Compare samples, not loss values, across couplings or datasets.
- One large Euler step on an independent-coupling model. It lands on the data mean (blur). Use several steps, a better solver, or straighten the flow first.
- Sampling only near the ends, or uniformly without thought. The distribution of in training is a loss weight over noise levels (lesson 08). Stable Diffusion 3 found logit-normal sampling better than uniform.
- Minibatch OT done once, or reflow done many times. The OT pairing must be recomputed in every batch; each reflow round fits a model to model output, so errors accumulate.
- Dividing by at . The formula is singular at ; a network that predicts directly has no problem, but code that converts from a denoiser must stop at a small or take the last step to .
8. Check yourself #
- Write the CFM loss for the linear path, and say which quantity a perfect network outputs.
Answer
with . A perfect network outputs the marginal velocity . - Show that the CFM gradient equals the FM gradient. Which step of the proof uses the tower property?
Answer
Expand both squares. The terms agree because . The cross term equals by the tower property, which is the FM cross term. The remaining terms do not depend on . - Data in 1D, noise , independent coupling, linear path. Compute the marginal velocity.
Answer
has variance . Gaussian conditioning: . So . At : ; at : (the variance is smallest there); at : . - Why can paths of the marginal ODE not cross, although the training lines do?
Answer
With a Lipschitz velocity the ODE has exactly one solution through each point . If two paths met at one time, they would be the same solution at all times. The training lines are not solutions of one ODE; each follows its own pair's velocity. - In the proof that reflow lowers convex costs, where is convexity used, and why twice?
Answer
Once in time: is the time average of , so Jensen gives . Once in conditional expectation: is the conditional mean of , so . The equality of the laws of and links the two steps. - Show that for the linear path and .
Answer
From and : , and . The same identities hold for the conditional means, so they hold for the predictions.
Give the linear conditional path of flow matching and its velocity (this track's convention).
with data and noise; the velocity is .
What is the marginal velocity, and what does it generate?
; it generates the marginal path (it solves the continuity equation with it).
Write the CFM loss.
.
Why does the CFM loss have the same gradient as the FM loss?
Their cross terms agree by the tower property, because the conditional mean of given is the marginal velocity; the rest does not depend on .
What is the minimum value of the CFM loss?
, the variance of the target given the position; it is 0 only when lines do not cross.
Express the linear-path velocity through the denoiser .
.
Where does one Euler step of size 1 from land, and why?
On the data mean for every noise point, because and .
What is reflow?
Generate pairs with the trained flow and retrain flow matching on these pairs; convex transport costs do not increase and the paths become straighter.
Convert a velocity from the convention "noise at , data at " to this track's convention.
and .
9. Interview angle #
- "Flow matching or diffusion: what is the difference?" — With Gaussian paths they learn the same object up to a linear map (velocity, denoiser, score). They differ in the path (), the loss weight over noise levels and the sampler grid. Flow matching regresses a velocity on straight lines and is simulation-free.
- "Why is the CFM loss valid if the network never sees the marginal velocity?" — The conditional target's mean given is the marginal velocity; by the tower property the two losses differ by a constant.
- "Why can't you sample a flow-matching model in one step?" — Lines of independent pairs cross; the learned velocity is an average; the first step heads toward the data mean. Straighten (reflow, OT couplings) or distill.
- "What does rectified flow guarantee?" — The rectified coupling has no higher cost for every convex cost, and repeated reflow makes the paths straight in the limit. It is not in general the optimal transport map in , but in 1D it is.
- "You load a flow model from another code base and get noise. First thing to check?" — The time convention and the sign of the velocity, then the noise scale of the prior.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
- Estimate the marginal velocity of the two-point data by Monte Carlo (binning ) and compare it with .
- Write the CFM batch (inputs and targets) and the loss; check Theorem 2 numerically. A demonstration then fits a small velocity model on two moons by least squares and samples it with Euler.
- Write a flow-matching Euler sampler for the 8 Gaussians with the exact velocity; measure the sample error against the number of steps.
- 1D reflow: compute the ODE map numerically for a two-Gaussian mixture and check that it equals the quantile (optimal transport) map; after reflow one step is exact.
- Minibatch OT with
linear_sum_assignment: measure how the pairing cost and the CFM floor fall with the batch size.
11. Watch and read #
- Lipman, Havasi, Holderrieth, Shaul, Le, Karrer, Chen, Lopez-Paz, Ben-Hamu, Gat, Flow Matching Guide and Code (2024): section 3.5 (the continuity equation), section 4.4 (the marginalization trick), section 4.5 (FM and CFM gradients agree), section 4.7 (the linear path and optimal transport).
- Lipman, Chen, Ben-Hamu, Nickel, Le, Flow Matching for Generative Modeling (ICLR 2023).
- Liu, Gong, Liu, Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow (ICLR 2023): Theorems 3.3 and 3.5 (marginals and convex costs), straightness and reflow.
- Albergo and Vanden-Eijnden, Building Normalizing Flows with Stochastic Interpolants (ICLR 2023).
- Tong, Fatras, Malkin, Huguet, Zhang, Rector-Brooks, Wolf, Bengio, Improving and Generalizing Flow-Based Generative Models with Minibatch Optimal Transport (TMLR 2024).
- Esser et al., Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Stable Diffusion 3, 2024): section 3 (the linear path and its weighting), the logit-normal time distribution.
- Liu, Zhang, Ma, Peng, Liu, InstaFlow: One Step is Enough for High-Quality Diffusion-Based Text-to-Image Generation (ICLR 2024).
- Holderrieth and Erives, An Introduction to Flow Matching and Diffusion Models (MIT 6.S184 lecture notes, 2025).
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.