Lesson 5.5 — Flow Matching
Previous lesson · 5.4 Score-based Generative Models · Course overview · Next lesson · 5.6 Conditional Generation & Guidance
Probability Transport
Lesson 5.4 constructs a velocity from a diffusion score. Flow matching learns the velocity directly. Here time zero denotes noise and time one denotes data. This is the reverse of the forward diffusion convention and independent of any physical execution clock.
A flow map carries an initial point to its position at time . Applying it to the whole initial distribution gives the pushforward. For a set , its probability at time is the initial probability of the set of points that flow into . Training aims to match distributions, so there is no need to assign each base draw to a specific training observation.
Where the velocity is sufficiently regular and solutions exist throughout the interval in both directions, the ODE defines an invertible flow. A smooth invertible flow with nonsingular Jacobian cannot turn a full-dimensional Gaussian exactly into a distribution supported on a lower-dimensional manifold. The target mixture here is full dimensional.
Vector Fields and ODE Integration
The velocity is the instantaneous derivative at the current time and position. It can turn as the point evolves. Local Lipschitz continuity in the position, together with the usual time regularity, ensures local uniqueness. Sampling also requires the solution to exist over the interval.
Euler advances along the current velocity. With sufficient smoothness it has first-order global integration error. The example below rotates and contracts around the origin. The exact trajectory gives a reference for measuring error at the same time.
Vector Field & ODE Simulator
In the transport experiment, the particles start from one Gaussian and follow the analytical marginal velocity toward the mixture. Each step evaluates the field at the current locations.
Probability Transport Explorer
Conservation of Probability Mass
For a fixed region, the mass changes by the negative of the outward probability flux through the boundary. The divergence theorem converts that flux into a local conservation law.
Expand the divergence and take the derivative along a trajectory to obtain the instantaneous log-density change.
This is the continuous counterpart of the log-determinant correction in an invertible flow. A positive divergence expands local volumes and decreases density. For in two dimensions, lengths scale by , areas by , and densities by . The lab visualizes this exact transformation.
Continuity Equation Visualizer
Conditional Probability Paths
Pair a Gaussian source point with a data point and interpolate between them. The joint law of these pairs is the coupling. Independent pairing leaves the endpoint distributions unchanged and gives one particular intermediate path. Other couplings can change that path.
Condition on a fixed endpoint . As time increases, the Gaussian center moves toward and its standard deviation shrinks. At the conditional distribution is a point mass; the marginal over random data endpoints can remain continuous. For the linear path the conditional field is for . Compute the sampled derivative from the two endpoints during training to avoid this division.
The general Gaussian path uses , starting with and and ending with and .
Conditional Probability Path
Conditional Flow Matching Objective
Sample a data point, a Gaussian point, and a uniform time. Form the interpolated point and train the network to predict the pair's displacement. This provides a target using one draw and does not require integration during training. In this objective, conditioning refers to the path endpoint. Lesson 5.6 also introduces a separate task condition.
Source points, data points, interpolants, and targets have shape . Time has shape and broadcasts over feature coordinates. The implementation averages squared error over coordinates and examples. Several sampled displacements can be consistent with the same interpolated point and time, giving the regression target a nonzero conditional variance.
Inspect the velocity label of an individual training pair
Velocity Target Inspector
Conditional Expectation and the Marginal Velocity

In this example both the source and target are standard normal. That deliberate choice lets us isolate the effect of pairing. On the left, each training line joins an independently chosen pair. The two colored lines pass through the same midpoint at the same time with opposite velocities. A sampler arriving there cannot consult either line’s destination.
On the right, start at the same displayed source points and follow the population mean velocity. The cloud narrows toward the middle and expands again. Each particle follows a single curve, and the final cloud has the target distribution even though individual points do not have to arrive at the endpoints assigned on the left. The left panel illustrates selected pairs. The right-hand field averages over the full distribution of pairs.
Derive the curved trajectories from the straight interpolant
For independent standard normals, is Gaussian with variance . Its covariance with the training velocity is . Gaussian conditional expectation gives
Differentiating the trajectory recovers the velocity. At the midpoint the conditional mean velocity is zero everywhere, although individual training pairs still carry nonzero velocities. At the end , so the original spread returns.
Let and . When expanding the squared error, the cross-term vanishes after conditioning on the point and time.
The extra term is independent of the model parameters. The velocity transports the marginal because integrating the conditional continuity equations gives a marginal flux of , under the regularity conditions that allow the exchanges of differentiation and integration.
For a known component with center , the interpolated point and displacement are jointly Gaussian. The interpolation variance is and the cross-covariance of the displacement and point is .
The analytical field averages component velocities using their posterior responsibilities at the selected space-time point. It is finite at each endpoint for this full-dimensional mixture. The heat map rescales density within each frame and the displayed arrows compress magnitude. Sampled training lines can intersect with distinct directions. A deterministic velocity gives one direction at each point and time, and its integral curves can be curved.
Follow the mean velocity for the four-component target
Marginal Velocity & Conditional Expectation
| Target mode | Weight | Mean velocity |
|---|---|---|
| 1 | 25% | (-2.3, -2) |
| 2 | 25% | (-2.3, 1.2) |
| 3 | 25% | (0.9, -2) |
| 4 | 25% | (0.9, 1.2) |
Euler, Heun, and Runge–Kutta Sampling
Rectified Flow uses straight interpolation targets and can repeat the training with pairs generated by the learned flow. This reflow procedure is meant to straighten trajectories. A single training run with linear conditional paths can still produce curved marginal trajectories.
For RK4, begin with and evaluate at successive provisional points.
For sufficiently smooth fields, the methods have global orders one, two, and four, using one, two, and four field evaluations per step. The lab fixes the step count and compares the endpoint RMSE against a 160-step RK4 reference. The training experiment instead fixes the number of model evaluations. A more accurate solver reduces integration error for a given field, while errors in the field itself remain.
Euler / Heun / RK4 Sampling
Engineering Experiment · Flow Matching on a Gaussian Mixture
Reuse the four-mode target with centers and standard deviation 0.30. Train and validate on 256 points each. Each training batch uses 32 independently paired source and data points and uniform times. Fixed validation pairs and times keep the measurement comparable across updates.
The 5–24–24–2 tanh MLP has 794 parameters and takes the two point coordinates, time, , and . The default uses seed 3, learning rate 0.005, and 1000 Adam updates. The regression metric is mean squared velocity error per coordinate. DDPM measures mean squared noise error, so the loss scales answer different questions.
Live Flow Matching Training
Results on the default split
Validation velocity MSE goes from 3.582045 to 2.120689. Start all samplers at the same 256 Gaussian points and match the number of evaluations. Evaluate 24 fixed projections for sliced Wasserstein-2, use radius 0.75 for membership, and require at least 13 points for coverage. Include every generated point in the metrics.
| Sampler | NFE | Learned SW₂ | Oracle SW₂ | Coverage | Within radius | Mode counts |
|---|---|---|---|---|---|---|
| Euler 40 | 40 | 0.417966 | 0.340887 | 4/4 | 79.30% | [66, 42, 48, 47] |
| Heun 20 | 40 | 0.426970 | 0.342340 | 4/4 | 79.30% | [65, 42, 49, 47] |
| RK4 10 | 40 | 0.427531 | 0.343016 | 4/4 | 79.30% | [65, 42, 49, 47] |
Euler yields the smallest learned sliced Wasserstein-2 in this run, and all three learned samplers put about 79.3% of generated points within the mode radius. The analytical field puts roughly 93% within the radius. Differences in these metrics reflect a combination of field estimation, numerical integration, and finite-sample effects. The preceding DDPM and score-model runs use different probability paths and prediction targets despite the shared mixture.
Reproducible PyTorch implementation
The script implements training, the analytical velocity, Euler, Heun, RK4, and the distribution metrics in CPU float64. Keep the initial draws fixed when comparing endpoint errors across solvers.
import math, torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
def rng(seed):
def r():
nonlocal seed
seed=(1664525*seed+1013904223)&0xffffffff
return seed/4294967296
return r
def normal(r):return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def noise(r,n):return torch.tensor([[normal(r),normal(r)] for _ in range(n)])
CENTERS=torch.tensor([[-1.6,-1.6],[-1.6,1.6],[1.6,-1.6],[1.6,1.6]])
def data(seed,n=256):
r=rng(seed);return torch.tensor([[float(c)+.30*normal(r) for c in CENTERS[int(4*r())]] for _ in range(n)])
def var(t):return (1-t)**2+.09*t*t
def feats(x,t):return torch.cat([x,t[:,None],(1-t)[:,None],var(t).sqrt()[:,None]],-1)
class Net(nn.Module):
def __init__(self,r):
super().__init__();self.layers=nn.ModuleList()
for ni,no in [(5,24),(24,24),(24,2)]:
l=nn.Linear(ni,no);l.weight.data.copy_(torch.tensor([.8*(r()-.5) for _ in range(ni*no)]).reshape(no,ni));l.bias.data.zero_();self.layers.append(l)
def forward(self,x,t):
h=feats(x,t);return self.layers[2](self.layers[1](self.layers[0](h).tanh()).tanh())
def flat(self):return torch.cat([p.flatten() for p in self.parameters()]).tolist()
def batch(r,X,n=32):
idx=[int(r()*len(X)) for _ in range(n)];t=torch.tensor([r() for _ in range(n)]);z=noise(r,n);y=X[idx];return (1-t[:,None])*z+t[:,None]*y,t,y-z
def velocity(x,t):
v=var(t);d=x[:,None,:]-t*CENTERS;w=torch.softmax(-d.square().sum(-1)/(2*v),dim=1)
return (w[:,:,None]*(CENTERS+(.09*t-(1-t))/v*d)).sum(1)
def metrics(x,y):
a=torch.arange(24)*math.pi/24;d=torch.stack([a.cos(),a.sin()],1);sw=(torch.sort(x@d.T,dim=0).values-torch.sort(y@d.T,dim=0).values).square().mean().sqrt().item();dist=torch.cdist(x,CENTERS);v,i=dist.min(1);counts=torch.bincount(i[v<=.75],minlength=4);return dict(swd=sw,counts=counts.tolist(),valid=(v<=.75).double().mean().item(),coverage=int((counts>=13).sum()))
@torch.no_grad()
def sample(m,z,steps=40,method='euler'):
x=z.clone();h=1/steps
def f(x,t):
tt=torch.tensor(t);return velocity(x,tt) if m is None else m(x,tt.expand(len(x)))
for i in range(steps):
t=i*h;k1=f(x,t)
if method=='euler':x=x+h*k1
elif method=='heun':x=x+h/2*(k1+f(x+h*k1,t+h))
else:
k2=f(x+h*k1/2,t+h/2);k3=f(x+h*k2/2,t+h/2);k4=f(x+h*k3,t+h);x=x+h/6*(k1+2*k2+2*k3+k4)
return x
def run(seed=3,steps=1000,lr=.005):
tr,va=data(seed),data(seed+1000);z=noise(rng(seed+2000),256);val=batch(rng(seed+5000),va,256);m=Net(rng(seed+3000));opt=torch.optim.Adam(m.parameters(),lr=lr);r=rng(seed+4000);hist=[]
for i in range(steps+1):
if i%100==0 or i==steps:
with torch.no_grad():
x,t,e=val;loss=(m(x,t)-e).square().mean().item();hist.append(dict(i=i,loss=loss,p=m.flat()))
if i==steps:break
x,t,e=batch(r,tr);opt.zero_grad();loss=(m(x,t)-e).square().mean();loss.backward();opt.step()
for name,n,method in [('euler',40,'euler'),('heun',20,'heun'),('rk4',10,'rk4')]:
hist[-1][name]=metrics(sample(m,z,n,method),va);hist[-1]['oracle_'+name]=metrics(sample(None,z,n,method),va)
return hist
if __name__=='__main__':
import json
h=run();print(json.dumps([{k:v for k,v in a.items() if k!='p'} for a in (h[0],h[-1])],indent=2))
References and Action Generation
- Lipman et al. develop flow matching and conditional velocity regression. Flow Matching for Generative Modeling
- Liu, Gong, and Liu describe rectified flow and reflow. Flow Straight and Fast
- Chen et al. describe neural ordinary differential equations. Neural Ordinary Differential Equations
- The course develops probability paths and ODE sampling. MIT 6.S184
- The robotics example uses a conditional flow to generate action chunks. π₀
For a robot action chunk with batch, horizon, and action dimensions, the velocity field acts in the space of whole chunks. The virtual time used to generate a chunk is independent of its execution index. Other implementations can use the opposite time direction, which reverses the corresponding velocity convention.
Previous lesson · 5.4 Score-based Generative Models · Course overview · Next lesson · 5.6 Conditional Generation & Guidance