Flow matching: conditional targets and marginal motion
流匹配
Fit an affine velocity field and separate regression, time interpolation and solver errors.
flow-matchingLearn the motion without simulating the journey during training
Suppose you can draw noise and real data, but cannot evaluate the data density. Join a noise point to a data point by a path whose position and velocity you can calculate. A model can learn those velocities from randomly selected times. At generation time, an ODE solver follows the learned field from new noise.
The subtlety is that many training paths can pass through the same location. The model sees the current location and time, not the destination of the particular pair that produced it. Its optimal prediction averages the possible velocities. Flow Matching, introduced by Lipman and colleagues in October 2022, formalizes how that conditional regression can learn a marginal probability flow. We use the February 2023 revision. Read normalizing flows and score SDEs first.
A density path needs a compatible velocity field
Let noise have density p0 and let the target data distribution be q. A continuous normalizing flow follows a time-dependent vector field vθ:
The second equation says that a target field ut transports the target density path pt. If that field were available, one could regress it directly:
Usually it is not available. The paper instead constructs tractable conditional paths pt(x|x1), indexed by data samples x1. Their mixture is the marginal path. The correct marginal velocity is a posterior-weighted average, not an unconditional average of all destination vectors:
Under the stated regularity and positivity conditions, this field generates the mixture path. Conditional flow matching (CFM) uses accessible conditional velocities:
The constant C does not depend on θ. It is the conditional target’s irreducible variance. Equality of gradients in expectation does not mean equal scalar losses or identical finite minibatch gradients. Theorem 2 establishes this distinction; our example checks it independently.
Choose a path with a direct training target
For a Gaussian conditional path, choose mean μt and standard deviation σt>0. Its affine sampling map and corresponding velocity are:
A useful choice is μt=tx1 and σt=1−(1−σmin)t. It produces straight conditional paths:
Training samples t, x0 and x1, constructs xt, and compares vθ(xt,t) with the right-hand velocity. No ODE rollout is needed to obtain this target. Sampling still needs an ODE solver unless an additional construction permits one-step generation.
With positive σmin the endpoint distribution is the data convolved with a small Gaussian, not exactly q. The paper calls these conditional Gaussian paths optimal-transport paths. That does not establish that the resulting marginal coupling between arbitrary noise and data distributions is the globally optimal transport map. Conditional straightness also does not force the learned marginal trajectories to be straight.
The maintained affine-path library makes the general derivative explicit. Its CondOT scheduler uses αt=t and σt=1−t, the zero-floor case. This later implementation is a useful comparison, not the original 2022 code version; our positive-floor example follows the paper’s nondegenerate construction.
A marginal velocity with an independent answer
Let X0∼N(0,1), X1∼N(μ,v1) independently, and write a(t)=1−(1−σmin)t. Gaussian conditioning gives:
Its exact marginal flow from starting noise z is:
Differentiating that expression recovers ut. This supplies a reference independent of the trained regression and numerical solver.
Separate regression, interpolation and integration errors
Save as flow_matching.py with Python 3.12 and NumPy 1.26.4. The example uses μ=1.4, v1=.49, σmin=.1 and seventeen equally spaced times. Each time has two affine coefficients, giving 34 learned parameters. A 5×5 product Gaussian quadrature evaluates the population quadratic objective. There is no finite empirical image dataset.
The model learns all coefficients by explicit gradient descent. Between the seventeen trained times it linearly interpolates coefficients; this is an additional approximation. RK4 then integrates that interpolated field. A separate run integrates the analytic field, so reducing solver step size cannot hide a representation error behind a better numerical method.
For J times and Q quadrature nodes per Gaussian, each gradient update costs O(JQ²) time and stored training arrays use O(JQ²). Integrating N scalar points for S RK4 steps costs O(SN), with four field evaluations per step and O(N+J) working memory. These costs belong to the affine example, not a neural image model.
"""Original conditional-flow regression with a nonzero terminal noise floor."""
import json
import numpy as np
MU,VAR,SIGMA_MIN=1.4,.49,.1
TIMES=np.linspace(0,1,17)
def path(time):
t=np.asarray(time,float)
if not np.all(np.isfinite(t)) or np.any((t<0)|(t>1)):raise ValueError('Time in[0,1] required.')
a=1-(1-SIGMA_MIN)*t;return MU*t,a*a+VAR*t*t
def oracle(time):
mean,var=path(time);a=1-(1-SIGMA_MIN)*np.asarray(time)
slope=(VAR*np.asarray(time)-(1-SIGMA_MIN)*a)/var
return np.stack([slope,MU-slope*mean],axis=-1)
def training_data():
z,w=np.polynomial.hermite.hermgauss(5);z=np.sqrt(2)*z;w=w/np.sqrt(np.pi)
x0=np.broadcast_to(z[:,None],(5,5)).ravel();x1=np.broadcast_to(MU+np.sqrt(VAR)*z[None,:],(5,5)).ravel()
weights=(w[:,None]*w[None,:]).ravel();t=TIMES[:,None];a=1-(1-SIGMA_MIN)*t
return a*x0+t*x1,x1-(1-SIGMA_MIN)*x0,weights
def objective(theta,data,target=None):
theta=np.asarray(theta,float);x,u,w=data
if theta.shape!=(17,2) or not np.all(np.isfinite(theta)):raise ValueError('Finite17 by2 coefficients required.')
y=u if target is None else target;error=theta[:,0,None]*x+theta[:,1,None]-y
loss=np.mean((error*error)@w)
gradient=2/17*np.column_stack([(error*x)@w,error@w])
return float(loss),gradient
def train():
data=training_data();theta=np.zeros((17,2));history=[objective(theta,data)[0]]
for step in range(4000):
theta-=objective(theta,data)[1]
if (step+1)%800==0:history.append(objective(theta,data)[0])
return theta,history
def velocity(x,time,theta=None):
if theta is None:c=oracle(time)
else:c=np.array([np.interp(time,TIMES,theta[:,j]) for j in range(2)])
return c[0]*x+c[1]
def solve(x,steps,theta=None):
if type(steps) is not int or not 1<=steps<=2048:raise ValueError('Steps1..2048 required.')
x=np.asarray(x,float).copy();h=1/steps
for i in range(steps):
t=i*h;k1=velocity(x,t,theta);k2=velocity(x+h*k1/2,t+h/2,theta);k3=velocity(x+h*k2/2,t+h/2,theta);k4=velocity(x+h*k3,t+h,theta)
x+=h*(k1+2*k2+2*k3+k4)/6
return x
def demo():
theta,history=train();x,u,w=training_data();c=oracle(TIMES);target=c[:,0,None]*x+c[:,1,None]
offsets=[]
for p in [np.zeros_like(theta),theta]:offsets.append(objective(p,(x,u,w))[0]-objective(p,(x,u,w),target)[0])
probes=np.array([-2.,0.,2.]);exact=MU+np.sqrt(VAR+SIGMA_MIN**2)*probes
return dict(training_mse=history,coefficient_error=float(np.max(abs(theta-oracle(TIMES)))),cfm_minus_fm=offsets,terminal_variance=VAR+SIGMA_MIN**2,data_variance=VAR,oracle_errors={str(n):float(np.max(abs(solve(probes,n)-exact))) for n in [4,16,64]},fitted_errors={str(n):float(np.max(abs(solve(probes,n,theta)-exact))) for n in [16,64,256]})
if __name__=='__main__':print(json.dumps(demo(),indent=2))
Four thousand updates at rate 1 reduce CFM MSE from 3.26 to .9838767154. The largest coefficient error against the analytic optimum is about 3.55×10⁻¹⁵. The positive final loss is the conditional regression variance. At two different parameter tables, CFM minus marginal FM loss remains .9838767154, and the gradients agree.
The true endpoint variance is .5, not the clean data variance .49: the extra .01 is σmin². For probes −2, 0 and 2, the analytic-field RK4 maximum endpoint error falls from 3.34×10⁻⁵ at 4 steps to 4.09×10⁻¹⁰ at 64. The fitted/interpolated field stays near .00246145 error even at 256 steps. Its time interpolation, not incomplete optimization, limits this experiment.
Simulation-free training is not error-free generation
A good regression objective does not certify an accurate ODE solution, endpoint distribution or density estimate. Finite model capacity, time weighting, endpoint noise, interpolation, discretization and terminal sampling each have separate effects. To compute likelihoods, a continuous-flow implementation must additionally track divergence and numerical integration error.
The marginal field is not unique in general; density-preserving rotational components can change trajectories. The chosen conditional path and coupling therefore affect the learning problem even when endpoints agree. Related approaches include rectified flow, which emphasizes recoupling and repeated straightening. The two topics share a regression construction but answer different questions.
Which error survives more solver steps?
- Target. With σmin=.1, x0=.3 and x1=−.8, what is the conditional velocity? Answer: −.8−.9·.3=−1.07. It is constant along that conditional straight path.
- Hand calculation. Clean variance is .49. What is the endpoint variance with σmin=.1? Answer: .49+.1²=.5. Calling it exactly the clean data distribution would omit endpoint smoothing.
- Loss. Why can the optimal CFM loss stay positive when the learned marginal velocity is exact? Answer: Multiple conditional velocities can occur at the same state and time. Their conditional mean is learnable, while their residual variance contributes the θ-independent constant.
- Diagnosis. RK4 refinement barely changes an error of .00246. What should be checked next? Answer: The field representation—in this example interpolation between trained times—and its difference from an independent analytic field, rather than indefinitely increasing solver steps.
Check the conditional-to-marginal step
Read Sections 3–4, Theorems 1–3 and Equations 20–23. Compare the later affine path and scheduler implementations, keeping their zero-floor convention distinct. Selected theorem statements and constructions were read in official v2 HTML; complete appendix proofs, neural training and image benchmarks were not reproduced. The reference library’s noncommercial code was not copied or executed.
Make a prediction, then check
Does simulation-free training remove the ODE solver at sampling time?
Learning objectives
- Derive the conditional-to-marginal velocity.
- Compare FM and CFM gradients.
- Explain terminal noise floors.
- Locate an interpolation error floor.
Prerequisites & connections
Explore related knowledge →References
- Flow Matching for Generative Modeling (v2 HTML)
Yaron Lipman; Ricky T. Q. Chen; Heli Ben-Hamu; Maximilian Nickel; Matt Le · 2023 - fm-affine method reference at 11568d3
facebookresearch/flow_matching contributors · 2026 - fm-scheduler method reference at 11568d3
facebookresearch/flow_matching contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Flow Matching v2 selected sections3-4/theorems1-3 and fixed later-maintained affine path/scheduler code. Eight paired equations and four explained exercises;34-parameter Gaussian population regression, all gradients, conditional-variance loss gap, independent least squares, RK4 and interpolation-error floor. Positive residual endpoint noise and zero-floor library path distinguished; no image or general optimal-transport reproduction.
- Single AI author checked Flow Matching v2 selected sections3-4/theorems1-3 and fixed later-maintained affine path/scheduler code. Eight paired equations and four explained exercises;34-parameter Gaussian population regression, all gradients, conditional-variance loss gap, independent least squares, RK4 and interpolation-error floor. Positive residual endpoint noise and zero-floor library path distinguished; no image or general optimal-transport reproduction.
- Four computed SVG variants per topic. Eleven numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Mobile-title and cost-axis corrections preserved. Full article acceptance recorded separately.
Source locations checked:
- Flow Matching for Generative Modeling (v2 HTML) · Read Sections3-4 selected constructions/theorems1-3, equations20-23 and conditional OT qualification. First2022-10-06; v2 dated2023-02-08. HTML after bounded PDF failure; no complete appendix or image benchmark audit.
- fm-affine method reference at 11568d3 · Read 57-93: affine path and analytical derivative, later maintained library rather than original2022 implementation. CC BY-NC4.0 title/opening only. Fixed public commit; reference only, no copied/executed code.
- fm-scheduler method reference at 11568d3 · Read 104-118: CondOT alpha=t,sigma=1-t and derivative signs; zero floor differs from paper positive sigma_min. CC BY-NC4.0 title/opening only. Fixed public commit; reference only, no copied/executed code.
Related topics