Flow Matching
Flow matching trains a neural network to move samples of Gaussian noise to samples of a data distribution along a learned velocity field. Time runs from (pure noise) to (clean data). A noise sample has the same shape as a data sample , for example for an MNIST digit. Training builds a noisy input by linear interpolation:
Smaller means more noise. For a fixed pair , the point moves on a straight line at constant velocity. This velocity is the conditional flow, conditioned on the single data point :
The network is trained with the conditional flow matching loss
A conditional model also receives a condition , such as a class label or a text prompt.The velocity we want is the marginal flow , which carries the whole noise distribution onto . It averages the conditional flows over all data points, weighted by how likely each one is to have produced :
Here is the distribution of given , and . The sum becomes an integral when is continuous. The flow matching loss cannot be computed, because is unknown. The theorem guarantees that training on per-sample targets learns anyway.Sampling draws and integrates the deterministic ODE from to . The usual solver is Euler’s method with step size :
A single evaluation also gives the one-step estimate of the clean image, . It is blurry for small and sharp near . The network is usually a 6.4. U-Net. Steering samples toward a condition is the subject of 10.3.2. Classifier-Free Guidance.
Time Runs the Other Way in DDPM Notation
DDPM-style diffusion writes for the clean image and for pure noise, and its network predicts the noise . Flow matching writes for noise and for the clean image, and its network predicts a velocity. Under the interpolation above the three common predictions convert into each other at fixed : , , and . The last formula divides by and breaks down at .
Names for the Velocity Network
The lecture’s loss slides write the network as , and its sampling slides and Project 3 Part A write . Project 3 Part B and the discussion worksheets write . All of these denote the same trained network. This note keeps for the exact target fields and for the network.
Intuition
Turning noise into a realistic image in one step is hard. The reverse direction is easy, since adding enough noise destroys any image. Locally the two directions are almost reversible. A slightly noisy image can be cleaned up well. Flow matching uses this asymmetry. It defines a path from noise to data and trains a network to take small steps along it. A single big step does not work. Project 3 trains a 6.4. U-Net with an L2 loss to map pure noise straight to MNIST digits, and the outputs look like one blurry average of all digits. The input carries no information about which digit to produce, so the L2-optimal output is the mean of the training set.
During training, the data point behind each noisy input is known, so the target is exact. During sampling it is unknown, and many data points could have produced the same . The network therefore sees one input with several targets. Under the L2 loss it learns their average, weighted by the posterior probability of each data point given , as computed by Bayes’ rule. The average is called marginal because the data point is averaged out, as in a marginal distribution. A flow is the motion of points under a velocity field, and matching means regressing the network’s velocity onto a target velocity. The figure shows the 1D case with two data points at . The two conditional paths through have slopes and . The marginal velocity is their average with weights and . The gray curves are the marginal paths that the sampler follows.
\usepackage{tikz}
\usepackage{amsmath}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=8cm,y=1.8cm,>=latex]
\draw[->] (0,-2.3) -- (1.1,-2.3) node[right] {$t$};
\draw[->] (0,-2.3) -- (0,2.45) node[above] {$x$};
\draw (1,-2.3) -- (1,2.3);
\node[below] at (0,-2.3) {$t = 0$ (noise)};
\node[below] at (1,-2.3) {$t = 1$ (clean)};
\draw[cold,thick,domain=-2.2:2.2,samples=60,variable=\y] plot ({-0.14*exp(-\y*\y/2)},\y);
\node[cold,left] at (-0.03,1.9) {$x_0 \sim \mathcal{N}(0,1)$};
\foreach \s in {1,-1} {
\draw[mid,thin] plot[smooth] coordinates {(0.00,\s*0.150) (0.10,\s*0.136) (0.20,\s*0.124) (0.30,\s*0.115) (0.40,\s*0.112) (0.50,\s*0.123) (0.55,\s*0.141) (0.60,\s*0.177) (0.65,\s*0.246) (0.70,\s*0.347) (0.75,\s*0.455) (0.80,\s*0.564) (0.85,\s*0.673) (0.90,\s*0.782) (0.96,\s*0.913) (1.00,\s*1.000)};
\draw[mid,thin] plot[smooth] coordinates {(0.00,\s*0.550) (0.10,\s*0.498) (0.20,\s*0.454) (0.30,\s*0.422) (0.40,\s*0.410) (0.50,\s*0.435) (0.60,\s*0.519) (0.70,\s*0.638) (0.80,\s*0.758) (0.90,\s*0.879) (1.00,\s*1.000)};
\draw[mid,thin] plot[smooth] coordinates {(0.00,\s*1.100) (0.10,\s*0.996) (0.20,\s*0.908) (0.30,\s*0.841) (0.40,\s*0.806) (0.50,\s*0.811) (0.60,\s*0.844) (0.70,\s*0.883) (0.80,\s*0.922) (0.90,\s*0.961) (1.00,\s*1.000)};
\draw[mid,thin] plot[smooth] coordinates {(0.00,\s*1.800) (0.10,\s*1.630) (0.20,\s*1.484) (0.30,\s*1.369) (0.40,\s*1.288) (0.50,\s*1.232) (0.60,\s*1.185) (0.70,\s*1.139) (0.80,\s*1.092) (0.90,\s*1.046) (1.00,\s*1.000)};
}
\draw[cold,dashed] (0,0) -- (1,1);
\draw[cold,dashed] (0,2) -- (1,-1);
\draw[->,cold,very thick] (0.5,0.5) -- (0.75,0.75);
\draw[->,cold,very thick] (0.5,0.5) -- (0.62,0.14);
\draw[->,hot,very thick] (0.5,0.5) -- (0.75,0.6308);
\filldraw (0.5,0.5) circle (1.5pt);
\node[left,fill=white,inner sep=1pt] at (0.48,0.45) {$(t, x) = (0.5, 0.5)$};
\node[cold,above,fill=white,inner sep=1pt] at (0.62,0.80) {$u_t(x \mid {+1}) = 1$, weight $0.88$};
\node[cold,below,fill=white,inner sep=1pt] at (0.64,0.10) {$u_t(x \mid {-1}) = -3$, weight $0.12$};
\node[hot,right,fill=white,inner sep=1pt] at (0.76,0.56) {$u_t(x) = 0.52$};
\filldraw[hot] (1,1) circle (2pt) node[right,black] {$x_1 = +1$};
\filldraw[hot] (1,-1) circle (2pt) node[right,black] {$x_1 = -1$};
\node[mid,right] at (1,0) {marginal paths};
\end{tikzpicture}
\end{document}Properties
(Training and Sampling Loops) Training draws a random time at every step, while sampling visits all times in order.
The training loop never runs the sampler. Each step draws an image, a time and a noise tensor, and regresses on one velocity. In PyTorch the loop reads:
x = next(dataset) # clean image x_1
t = torch.rand(1) # t ~ U[0, 1]
noise = torch.randn_like(x) # x_0 ~ N(0, I)
x_t = (1 - t) * noise + t * x # noisy input
flow_pred = model(x_t, t) # v_theta(x_t, t)
flow_gt = x - noise # target x_1 - x_0
loss = F.mse_loss(flow_pred, flow_gt)
loss.backward()
optimizer.step()Sampling starts from pure noise and takes steps Euler steps of size dt = 1/steps:
x_t = torch.randn_like(x) # x_0 ~ N(0, I)
steps = 100
dt = 1.0 / steps
for i in range(steps):
t = i * dt
velocity = model(x_t, t) # v_theta(x_t, t)
x_t = x_t + dt * velocityEach Euler step costs one network evaluation. Project 3 Part A uses , so generation from pure noise takes evaluations, and denoising an image from takes . Noise is drawn fresh for every batch, so the network never sees the same noisy input twice.
(One-Step Estimate Is a Posterior Mean) With the exact marginal flow, the one-step estimate equals , the average of all plausible clean images.
Solving the interpolation for the noise gives . Taking the conditional expectation of given yields , so . At small the likelihood is close to for every . The posterior then stays close to , and the estimate is close to the mean of the whole dataset. This explains why early one-step predictions look like Galton’s composite portraits (Galton, 1878), which average many faces into one blurry face. As grows, the Gaussians narrow (standard deviation ) and their centers separate. The posterior concentrates on a subpopulation, and the estimate becomes the mean of that subpopulation. Near it concentrates on one image and the estimate turns sharp. Colorization with an L2 loss shows the same averaging, as described in 8.3. Image Colorization.
(Straight Conditional, Curved Marginal Paths) Every training pair moves on a straight line, yet sampling trajectories curve.
The marginal velocity depends on through the posterior weights, and these weights change along the path. A trajectory first heads toward the dataset mean, while all data points are still plausible. It then turns toward one region of the data once the posterior commits. This curvature is why a single Euler step from noise gives the blurry mean and why the step size matters. The ODE trajectories never cross, since the velocity at a point is unique. In 1D they therefore keep their order, so the lowest noise values end at the lowest data values.
(Training Averages Targets by Frequency) At each the network converges to the average of the training targets, weighted by how often each target occurs.
Consider data at and with probability each. At and , both data points need the same noise , so the targets and appear equally often, and . At and , the targets and are equally likely, and . At and , reaching needs , more than nine standard deviations. Target dominates, and . The frequencies follow as well as the Gaussian. Duplicating in the dataset makes the sampler produce twice as often as .
(Exact Minimizer Memorizes) The loss can be minimized perfectly without a network, and the result can only reproduce training images.
For a finite training set, the marginal flow formula can be evaluated directly by summing over all training images. This non-parametric velocity minimizes the loss exactly. Near its posterior collapses onto the nearest training image, so every sample is a copy of a training image. Minimizing the objective alone therefore guarantees neither interpolation between images nor new combinations of content. A neural network cannot represent this sum exactly. Its smoothing is what produces new images, and why this works is still an open research question.
(Train/Test Mismatch) The network is trained on exact interpolations of real images but tested on its own trajectories.
Training inputs are with a real and fresh Gaussian noise. Sampling inputs are Euler iterates , which carry the network’s earlier errors and the discretization error. These inputs can drift away from the distribution the network was trained on. In machine learning one normally trains on the same distribution one tests on. Flow and diffusion models break this rule and still work reasonably well. Smaller steps reduce the discretization part of the error at the cost of more network evaluations.
(One Family of Schedules) DDPM, DDIM, VP and VE ODEs, flow matching and rectified flow differ mainly in how mixes noise and data.
A general path writes with schedule functions and . Linear interpolation (, ) gives flow matching and rectified flow. A variance-preserving (VP) schedule keeps , as in DDPM. A variance-exploding (VE) schedule keeps the image unscaled and adds noise of growing size, . The choices differ in time steps and image scaling, and some train or sample better than others. DDIM and EDM are further choices of time steps and samplers within the same family. The training target can be the clean image (), the noise (, as in diffusion) or the velocity ( with ). At fixed the three targets are affine functions of each other.
(Deterministic Versus Stochastic Sampling) A flow sampler maps each noise sample to one fixed image, while a DDPM sampler re-injects noise along the way.
Flow sampling integrates an ODE, so the same always gives the same image, and the trajectory is smooth. A DDPM sampler takes one step that reduces the noise and then adds a little fresh noise back. Its trajectories therefore wiggle, and the same starting noise can end at different images. Both procedures carry the noise distribution to the data distribution. Project 3 Part A builds its editing applications on the deterministic Euler sampler, as described in 8.6. Flow-Based Image Editing.
Derivation
We want to show that and differ by a constant that does not depend on . Fix and write , and . Expanding both squared errors with the inner product gives
The first terms are identical. For the cross terms, condition on . The network output depends only on , so by the tower property of expectation and the definition of ,
The last terms and do not involve . Hence with independent of , and . The same expansion shows that the best function of is . This is the general fact that L2 regression learns a conditional mean. It matches the marginal flow formula in the callout.
Examples
(Easy) Plugging a Noise Predictor into a Flow Sampler
A classmate has a pretrained network that predicts the noise in , as diffusion models do. Assume it was trained on the same interpolation . They want to reuse the Euler sampler from Project 3, which expects a velocity. At one pixel, at , and the network predicts .
Convert the prediction to a velocity, take one Euler step with , and find the one-step estimate. What goes wrong near ? The velocity is , so . Substituting into the interpolation gives . Therefore . The Euler step gives . The one-step estimate is . Solving the interpolation for the clean value gives the same number, .
The conversion divides by . An error in becomes an error in the velocity, so at an error of grows to . At we have exactly. A perfect noise predictor returns , and the formula gives . The noise prediction at carries no information about the data, while the true velocity does. The converted sampler must therefore start at a small .
(Medium) Marginal Velocity for a Two-Point Dataset
A 1D dataset holds two values, and , each with probability . Think of one pixel that is either white or black after normalization. Noise is .
Compute the posterior weights, the marginal velocity and the one-step estimate at , and . Given , the noisy value is . The ratio of the two Gaussian likelihoods is The posterior weight of is therefore , and . The conditional velocities are and . The marginal velocity is their weighted sum, and the one-step estimate simplifies to .
conditional velocities and and and At the noise does not depend on the data. The weights equal the prior, the velocity points at the dataset mean , and the one-step estimate is that mean. This is the 1D version of a blurry average image. At the value is times as likely under , so the estimate moves to . At , producing from needs , while producing it from needs . The likelihood ratio is , and the estimate is almost exactly . In closed form, .
(Hard) Four Euler Steps on the Two-Point Dataset
Use the same dataset and the exact marginal velocity from the previous example. A sampler starts at and takes four Euler steps of size .
Compute the four steps, compare them with the exact ODE trajectory, and explain the shape of the path.
Euler exact The path first moves toward the dataset mean and then turns toward . Early on both data points are plausible, and their pulls nearly cancel. Later the posterior commits to . At Euler lags well behind the exact path ( against ). Each step reuses the velocity from the start of the step over a long interval. The last step still ends near . Its size makes it a one-step estimate, and with the exact velocity this estimate is the posterior mean . With steps, Euler ends at . Every start ends at and every start ends at , which sends half of the noise to each data point, as requires. A trained network replaces the exact velocity, so its own errors add to the Euler error.
See Also
- 10.3.1. Diffusion Models, the noise-predicting relative written in DDPM notation.
- 10.3.2. Classifier-Free Guidance, which combines conditional and unconditional velocities.
- 8.6. Flow-Based Image Editing, for the Project 3 applications built on a pretrained flow model.
- 6.4. U-Net, the usual architecture for .
- 10.1. Generative Adversarial Networks, a one-step generator trained with a learned loss instead of regression.