AnyLearn
All lessons
AIadvanced

Flow matching: straightening the path from noise to data

The reframing that took over frontier image generation: learn a velocity field that transports noise to data along direct paths. Conditional flow matching, rectified flow, why straight trajectories mean fewer sampling steps, and how diffusion becomes a special case.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 7

Same destination, straighter road

The last two lessons ended at the same wall twice: a trained diffusion model traces a curved trajectory from noise to data, so taking few, large steps misses the curve, and only distillation tricks got us to one-step generation.

Flow matching attacks the root cause. Instead of defining generation as reversing a corruption process and inheriting whatever trajectories that implies, it asks directly: what is the simplest path from the noise distribution to the data distribution, and can we learn to follow it?

The object it learns is a velocity field vθ(x,t)v_\theta(x, t): at every point in space and "time" t[0,1]t \in [0, 1], an arrow saying which way a sample should move. Generation is then pure physics simulation: drop a Gaussian sample at t=0t=0 and integrate the ODE dxdt=vθ(x,t)\frac{dx}{dt} = v_\theta(x, t) until t=1t=1, where it lands on the data distribution.

If that sounds familiar, it should: lesson 1 showed diffusion sampling is also ODE integration. The difference is that flow matching gets to choose the paths, and it chooses straight lines.

Full lesson text

All 7 steps on one page, for reading, reference, and search.

Show

1. Same destination, straighter road

The last two lessons ended at the same wall twice: a trained diffusion model traces a curved trajectory from noise to data, so taking few, large steps misses the curve, and only distillation tricks got us to one-step generation.

Flow matching attacks the root cause. Instead of defining generation as reversing a corruption process and inheriting whatever trajectories that implies, it asks directly: what is the simplest path from the noise distribution to the data distribution, and can we learn to follow it?

The object it learns is a velocity field vθ(x,t)v_\theta(x, t): at every point in space and "time" t[0,1]t \in [0, 1], an arrow saying which way a sample should move. Generation is then pure physics simulation: drop a Gaussian sample at t=0t=0 and integrate the ODE dxdt=vθ(x,t)\frac{dx}{dt} = v_\theta(x, t) until t=1t=1, where it lands on the data distribution.

If that sounds familiar, it should: lesson 1 showed diffusion sampling is also ODE integration. The difference is that flow matching gets to choose the paths, and it chooses straight lines.

2. The training trick: conditional paths

Learning "the velocity field that transports one distribution to another" sounds intractable, and in general it is: the marginal field depends on the entire dataset at once.

Conditional flow matching dissolves the problem with the same move DDPM used (compare lesson 1's per-step denoising): make the target per-example. Pick one noise sample x0N(0,I)x_0 \sim \mathcal{N}(0, I) and one data sample x1x_1. Declare their path to be the straight line:

xt=(1t)x0+tx1x_t = (1 - t)\,x_0 + t\,x_1

Along this line, the velocity is constant and known exactly: dxtdt=x1x0\frac{dx_t}{dt} = x_1 - x_0. So train by regression:

L=Ex0,x1,t[vθ(xt,t)(x1x0)2]\mathcal{L} = \mathbb{E}_{x_0, x_1, t}\left[\, \lVert v_\theta(x_t, t) - (x_1 - x_0) \rVert^2 \,\right]

The theorem that makes this legitimate: regressing on these conditional per-pair velocities yields, in expectation, the correct marginal velocity field for transporting the whole noise distribution to the whole data distribution. Where trajectories from different pairs cross, the network learns their average, which is exactly the marginal flow.

No noise schedules, no αˉt\bar\alpha_t bookkeeping, no variational bound: sample two points, interpolate, regress on their difference.

3. The whole method in fifteen lines

The training loop makes the simplification tangible. Compare line for line with lesson 1's DDPM loop:

import torch

def train_step(model, x1, opt):            # x1: batch of real data
    b = x1.shape[0]
    x0 = torch.randn_like(x1)              # noise endpoint
    t = torch.rand(b, 1, 1, 1)             # continuous t in [0,1]
    x_t = (1 - t) * x0 + t * x1            # straight-line interpolant
    target_v = x1 - x0                     # exact velocity on that line
    pred_v = model(x_t, t.squeeze())
    loss = torch.mean((pred_v - target_v) ** 2)
    opt.zero_grad(); loss.backward(); opt.step()
    return loss.item()

@torch.no_grad()
def sample(model, shape, steps=8):         # Euler integration of the ODE
    x = torch.randn(shape)
    dt = 1.0 / steps
    for i in range(steps):
        t = torch.full((shape[0],), i * dt)
        x = x + model(x, t) * dt
    return x

Differences worth noticing: time is continuous rather than one of 1000 discrete steps; there is no schedule to tune; and the sampler is the most naive ODE solver imaginable, plain Euler, yet 8-16 steps often produce strong samples, because the paths the model was trained on were straight. Everything from lesson 2 still applies unchanged on top: CFG (learn a conditional and unconditional velocity, extrapolate between them), latent spaces, and DiT backbones.

4. Why straight paths are not automatically straight

A subtlety keeps this honest: declaring each training pair's path straight does not make the learned marginal flow straight. When random noise-data pairings cross each other (and with random pairing they cross constantly), the model averages their velocities, and averaged straight lines bend. The learned trajectories are straight-ish, much straighter than diffusion's, but not perfectly straight, which is why few-step sampling is good rather than magically one-step.

Rectified flow adds the fix: an iterative straightening procedure called reflow.

  1. Train a first flow model with random pairings.
  2. Generate samples with it, keeping each output paired with the exact noise that produced it. These pairs, by construction, do not cross the way random pairings do.
  3. Retrain on these coupled pairs. Trajectories straighten substantially; repeat if desired.

Each reflow round trades a little fidelity for a lot of straightness, and after one or two rounds, 1-4 step generation becomes viable without a separate distillation stage. Later refinements (mean-flow-style objectives that regress the time-averaged velocity over an interval rather than the instantaneous one) push one-step quality further still. The intellectual through-line: make the geometry you want at inference time the thing you optimize at training time.

5. Diffusion is a special case

The cleanest way to see how the two frameworks relate: both train a network to point along a prescribed probability path from noise to data; they differ only in which path and which parameterization of the arrow.

Diffusion (DDPM-style)Flow matching (rectified)
Path from noise to dataCurved (variance-preserving mixing)Straight line
Network predictsNoise ϵ\epsilon (equivalently score)Velocity vv
Time1000 discrete steps + scheduleContinuous t[0,1]t \in [0,1], no schedule
Natural samplerStochastic chain or ODE, 20-50+ stepsEuler ODE, 4-16 steps
Few-step routeDistillation (consistency, progressive)Reflow / mean-flow objectives

Choose the Gaussian variance-preserving path in the flow-matching framework and you recover diffusion exactly: the velocity target becomes an affine function of the familiar ϵ\epsilon-target, one linear reparameterization apart. That is why the field talks of one unified family now: train a vector field along a chosen path; pick the path for the properties you want. Straight paths buy cheap sampling; diffusion's curved paths retain some advantages in noise robustness and likelihood evaluation.

The practical scoreboard settled quickly: leading open and commercial image generators (the Stable Diffusion 3 / Flux generation onward) train with flow-matching objectives on DiT backbones, and the pattern spread to video, audio, and molecule generation.

6. Why labs switched: the engineering case

Frameworks win on logistics as much as elegance. The reasons flow matching became the frontier default, in rough order of weight:

  • Fewer moving parts. No noise schedule to design, no discrete-time bookkeeping, no prediction-target debates (ϵ\epsilon vs x0x_0 vs vv); the objective has essentially one form. Fewer hyperparameters means cheaper large-scale experimentation, which matters most exactly at frontier scale.
  • Inference economics. Straighter paths mean fewer function evaluations for the same quality, and inference, not training, dominates the lifetime cost of a deployed image model. A 4-8 step model at production quality changes serving costs qualitatively.
  • Stable continuous-time training. Continuous tt sampling smooths the loss landscape across noise levels; practitioners report fewer schedule-related pathologies at scale.
  • A cleaner theory seam. Optimal-transport language connects flow matching to a large mathematical literature; extensions (paths between any two distributions, not just Gaussian-to-data) fall out naturally, enabling image-to-image, editing, and cross-modal transport in one framework.

A fair caveat closes the account: for a given pretrained model, well-tuned diffusion with a modern solver and distillation remains competitive; head-to-head quality gaps are modest. The switch is best read as the field consolidating on the simpler, more general formulation rather than a rout on sample quality.

7. One framework, and one frontier left

Zoom out and the three lessons so far tell a single story with a strikingly economical core:

  1. Define a path that morphs the data distribution into something trivially samplable (Gaussian noise): curved mixing (diffusion) or straight interpolation (flow matching).
  2. Train a network by regression to point along that path: predict the noise, the score, or the velocity, all linearly interchangeable.
  3. Generate by integrating the learned field from noise to data, with the step count set by path geometry: hundreds for curved paths, a handful for straightened ones, one after reflow or distillation.

Every headline generator for images, video, and audio is an instance of this recipe plus the lesson-2 toolkit (latents, CFG, conditioning).

One domain conspicuously resists the recipe: text. Language is discrete, there is no obvious Gaussian to interpolate toward, and autoregressive transformers already dominate. Yet the prize is tempting: diffusion-style generation refines all positions in parallel, promising order-of-magnitude faster generation than token-by-token decoding, plus natural infilling and revision. How diffusion is being rebuilt for discrete sequences, and how far the resulting language models have come, is the final lesson.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What object does a flow-matching model learn?
    • A discriminator that scores sample realism
    • A velocity field: at each point and time, the direction a sample should move toward the data distribution
    • A discrete Markov chain of denoising steps
    • An energy function over images
  2. In conditional flow matching with straight-line paths, what is the regression target for a pair (noise x₀, data x₁)?
    • The score of the data distribution
    • The noise x₀ itself
    • The schedule coefficient ᾱ_t
    • The constant velocity x₁ − x₀ along their interpolation line
  3. Why aren't the learned marginal trajectories perfectly straight even though every training path is a straight line?
    • Trajectories from different noise-data pairs cross, and the model learns their average, which bends
    • Euler integration introduces curvature
    • The network cannot represent linear functions
    • Continuous time sampling adds noise to the paths
  4. How does reflow (rectified flow) enable 1-4 step generation without a separate distillation stage?
    • It increases the CFG scale during sampling
    • It replaces the ODE with a stochastic sampler
    • It retrains on noise-sample pairs coupled by the model's own generation, which straightens trajectories so big Euler steps stay accurate
    • It adds more sampling steps at high noise levels
  5. What is the relationship between diffusion models and flow matching?
    • They are unrelated frameworks with incompatible objectives
    • Flow matching only works for discrete data
    • Diffusion is strictly more general than flow matching
    • Diffusion corresponds to choosing a curved Gaussian path within the flow-matching framework; the targets differ by a linear reparameterization

Related lessons

AI
advanced

The Memory Wall: Why Training Needs More Than One GPU

Training memory is dominated by things that are not the model. Mixed-precision Adam costs 16 bytes per parameter, so a 70B model needs 1120 GB of state before one activation is stored. This lesson works through where every byte goes, why data parallelism helps throughput but not memory, how accumulation and recomputation trade compute for space, and what each axis of parallelism addresses.

10 steps·~15 min
Robotics
advanced

Modelling Interaction: From Social Forces to Social Pooling

How the field learned to represent people influencing each other: the physics-inspired force model, the Social LSTM pooling layer that replaced hand-designed rules with learned ones, and the attention and graph architectures that followed.

8 steps·~12 min
AI
advanced

What Phase Transitions Mean for Machine Learning

Taking the framework beyond solvable toy models: sharp transitions in real learning, why the loss landscape of a neural network is not the fractured one theory warns about, and what the physics lens genuinely explains.

8 steps·~12 min
AI
advanced

Gradients, Counterfactuals, and Whether to Trust an Explanation

When a model is differentiable you can attribute a prediction with calculus instead of sampling. This lesson covers plain saliency, Integrated Gradients and its axioms, Grad-CAM, then counterfactual explanations, which answer what would have to change rather than what mattered. It closes with the evidence that explanations can fail or be deliberately faked, and a protocol for checking yours.

12 steps·~18 min