◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

Normalizing Flows and Flow Matching

Flows generate data by smoothly moving random noise points until they land on the data. Normalizing flows do it with invertible layers and exact probabilities. Flow matching, a simpler cousin of diffusion, trains a network to predict the velocity along straight lines from noise to data. It powers several leading image, video and speech models.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

What Generative Models Do

This leads to

—
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. What Generative Models Do
  17. Normalizing Flows and Flow Matching

Read them roughly in this order. See it on the concept map →

Why it matters

Every generative model has to turn simple randomness into complicated data. Flows make this literal. Picture each random number as a particle and the network as a current that carries particles smoothly from a blob of noise onto the shape of the data.

There are two generations of the idea:

  • Normalizing flows (2014–2019) build the noise-to-data map from invertible layers, so they can compute the exact probability of any example. That property is still valued in physics and science applications. As image generators, they were overtaken.
  • Flow matching and rectified flow (2022) keep the "particles moving through a current" picture but train it in a radically simpler way: draw a straight line from a noise point to a data point and teach a network the velocity along it. The result is a close, cleaner cousin of diffusion. It needs fewer sampling steps and has become the training method of choice for several leading models as of late 2026. Examples include Stable Diffusion 3, the FLUX image models, Meta's Movie Gen video model and several speech generators.

If you have read the Diffusion Models chapter, this one will feel like a simplification, and it is.

The intuition

Imagine a crowd scattered at random across a square, and a set of marked spots arranged in the shape of two crescent moons. You want to give everyone in the crowd a rule of the form "wherever you are standing at time tt, walk in this direction at this speed". After one minute of following the rule, the crowd should be standing on the moons.

That rule is a velocity field: an arrow at every place and every moment. Generation means "start at a random spot and follow the arrows". The question is how to learn the arrows.

Flow matching learns them with a trick. During training, pick one random person and one random marked spot, and draw a straight line between them. If that person walked the line at constant speed, their velocity would simply be (spot − start). Ask a network: "for someone at this point on the line, at this time, what velocity should they have?" Repeat for millions of random pairs.

Of course, many lines pass through any given point, heading in different directions. The network can't match all of them, so it learns their average. That average turns out to be exactly the field we want. Follow it from any noise point and you arrive somewhere on the data. Because the averaged arrows are well defined at every point, the resulting paths never cross. They bend smoothly around each other.

Training: random straight lines pair each noise point with a random data point Learned flow: follow the velocity field 100 Euler steps from noise with the trained network lines cross: at a crossing, the target velocity is ambiguous paths never cross; they bend to reach the moons noise x₀data x₁generated sample
Fig. 1 Left: during training, random noise points (grey) are paired with random data points (blue) and joined by straight lines. The lines cross everywhere. Right: the network trained in the code below learns the average velocity at each point. Following it from fresh noise (grey) gives smooth, non-crossing paths that end on the two moons (green).

Key idea Flow matching trains a network to predict a velocity that carries noise to data. Training uses straight lines between random noise and data points, with target velocity data − noise. Generation starts from noise and follows the learned velocity in a few small steps.

How it works

Normalizing flows: exact probabilities with invertible maps

Start with the older idea. Take a random vector z\mathbf{z} from a standard Gaussian and push it through a function ff to get x=f(z)\mathbf{x} = f(\mathbf{z}). If ff is invertible (every x\mathbf{x} comes from exactly one z\mathbf{z}), you can compute the probability density of x\mathbf{x} exactly with the change of variables formula:

log⁡pX(x)=log⁡pZ ⁣(f−1(x))+log⁡∣det⁡∂f−1∂x∣\log p_X(\mathbf{x}) = \log p_Z\!\big(f^{-1}(\mathbf{x})\big) + \log \left| \det \frac{\partial f^{-1}}{\partial \mathbf{x}} \right|
  • f−1(x)f^{-1}(\mathbf{x}) is the noise vector that maps to x\mathbf{x}.
  • pZp_Z is the standard Gaussian density, which is easy to evaluate.
  • The last term corrects for stretching. ∂f−1∂x\frac{\partial f^{-1}}{\partial \mathbf{x}} is the Jacobian matrix of the inverse, and its determinant (det⁡\det) measures how much it expands or shrinks volume near x\mathbf{x}. If ff spreads probability over twice the area, the density must halve.

One-dimensional example. Let x=f(z)=2z+1x = f(z) = 2z + 1, with zz standard normal. The inverse is z=(x−1)/2z = (x - 1)/2, which squeezes lengths by a factor of 12\tfrac{1}{2}. At x=1x = 1: z=0z = 0, where the Gaussian density is 0.3990.399, so pX(1)=0.399×12=0.199p_X(1) = 0.399 \times \tfrac{1}{2} = 0.199. The distribution of xx is a Gaussian with mean 1 and standard deviation 2, as expected.

A normalizing flow stacks many invertible layers, so the total log-determinant is the sum of each layer's. The name comes from running the flow backwards: it "normalizes" complicated data into a normal (Gaussian) distribution. Training is plain maximum likelihood with the formula above. The engineering challenge is to design layers that are expressive and invertible, with a determinant that is cheap to compute. The key invention was the coupling layer (NICE 2014, RealNVP 2016). It splits the input into two halves, leaves one half unchanged, and uses it to scale and shift the other half. That is trivially invertible, and its Jacobian is triangular, so the determinant is just the product of the scale factors. Glow (2018) added invertible 1×1 convolutions and generated sharp 256×256 faces.

The catch: every layer must keep the full dimensionality (no bottleneck) and stay invertible. This makes flows large and less expressive per parameter than diffusion models, and their image quality fell behind.

Continuous flows: an ordinary differential equation

Now make the layers infinitely thin. Instead of a stack of maps, describe a velocity field vθ(x,t)\mathbf{v}_\theta(\mathbf{x}, t): a neural network that takes a position x\mathbf{x} and a time t∈[0,1]t \in [0, 1] and returns the direction and speed of movement. A point moves by following it:

dxdt=vθ(x,t)\frac{d\mathbf{x}}{dt} = \mathbf{v}_\theta(\mathbf{x}, t)

This is an ordinary differential equation (ODE). It says that the rate of change of the position is the velocity. Starting from noise x(0)\mathbf{x}(0) and following the field until t=1t = 1 gives a sample x(1)\mathbf{x}(1). The map is automatically invertible (run time backwards), with no architectural restrictions. These "continuous normalizing flows" (Neural ODEs, 2018) were elegant, but training them by maximum likelihood meant solving the ODE inside every training step, which was slow.

Flow matching: train the velocity directly

Flow matching (Lipman and colleagues, 2022) removes the expensive part. You never solve the ODE during training. Instead, you choose a simple path from noise to data and regress the network onto its velocity.

Pick a noise point x0∼N(0,I)\mathbf{x}_0 \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), a data point x1\mathbf{x}_1, and a time tt drawn uniformly between 0 and 1. The straight-line path between them is:

xt=(1−t) x0+t x1\mathbf{x}_t = (1 - t)\,\mathbf{x}_0 + t\,\mathbf{x}_1

At t=0t = 0 it is the noise point, at t=1t = 1 the data point, and in between a weighted mix. Its velocity is the same at every time:

dxtdt=x1−x0\frac{d\mathbf{x}_t}{dt} = \mathbf{x}_1 - \mathbf{x}_0

So the flow matching loss is a plain squared error between the network's velocity and that target:

L(θ)=∥vθ(xt,t)−(x1−x0)∥2L(\theta) = \big\lVert \mathbf{v}_\theta(\mathbf{x}_t, t) - (\mathbf{x}_1 - \mathbf{x}_0) \big\rVert^2

averaged over random choices of x0\mathbf{x}_0, x1\mathbf{x}_1 and tt. The key theorem of the paper is that minimising this per-pair loss gives the same gradients as matching the true averaged velocity field. Its flow carries the noise distribution exactly onto the data distribution. You get a continuous flow at the cost of a regression.

Worked example. Noise point x0=(0.5,−1.0)\mathbf{x}_0 = (0.5, -1.0), data point x1=(1.2,0.3)\mathbf{x}_1 = (1.2, 0.3), time t=0.25t = 0.25:

  • Point on the line: xt=0.75×(0.5,−1.0)+0.25×(1.2,0.3)=(0.675,−0.675)\mathbf{x}_t = 0.75 \times (0.5, -1.0) + 0.25 \times (1.2, 0.3) = (0.675, -0.675).
  • Target velocity: x1−x0=(0.7,1.3)\mathbf{x}_1 - \mathbf{x}_0 = (0.7, 1.3).
  • Check: moving from xt\mathbf{x}_t at that velocity for the remaining time 0.750.75 gives (0.675+0.525,  −0.675+0.975)=(1.2,0.3)(0.675 + 0.525,\; -0.675 + 0.975) = (1.2, 0.3), the data point.

The network sees the input (0.675,−0.675,t=0.25)(0.675, -0.675, t{=}0.25) and is trained to output (0.7,1.3)(0.7, 1.3). Other pairs whose lines pass near that point at that time pull its answer towards their own velocities. The result is the average.

Sampling with Euler steps

To generate, solve the ODE numerically. The simplest solver is the Euler method: take NN equal time steps of size Δt=1/N\Delta t = 1/N and repeatedly move a little along the current velocity:

x←x+Δt  vθ(x,t),t←t+Δt\mathbf{x} \leftarrow \mathbf{x} + \Delta t \; \mathbf{v}_\theta(\mathbf{x}, t), \qquad t \leftarrow t + \Delta t

Our 2-D model, trained on the two moons, gives:

Euler steps Median distance to nearest real point Within 0.1 of data
1 0.356 0%
2 0.200 26%
10 0.006 90%
100 0.006 94%
1 step0% within 0.1 of data 2 steps26% within 0.1 10 steps90% within 0.1 The same trained network, sampled with 1, 2 and 10 Euler steps.One step lands every point on the average of the data; with 100 steps, 94% land within 0.1.
Fig. 2 The same flow matching network sampled with 1, 2 and 10 Euler steps. With one step, every point lands near the middle, because at t = 0 the average velocity from any noise point points towards the average of the data. Ten steps already trace the moons.

Compare the DDPM in the previous chapter, which used 1,000 steps for 95%. The learned paths are nearly straight, so a few large steps follow them well. Better ODE solvers (Heun, midpoint, adaptive) reduce the count further.

Rectified flow: straightening the paths

Paths from the averaged field are not perfectly straight. Where lines crossed in training, the average bends. Rectified flow (Liu, Gong and Liu, 2022), developed at the same time as flow matching with essentially the same training loss, adds a further trick called reflow. Generate many (noise, sample) pairs with the trained model, then train a new model on those pairs. Their straight lines no longer cross, so the new flow is straighter and can be sampled in very few steps, even one. Stable Diffusion 3's paper is titled Scaling Rectified Flow Transformers.

How flow matching relates to diffusion

Diffusion also moves points from noise to data, just along a different path. Its noisy example αˉt x0+1−αˉt ϵ\sqrt{\bar\alpha_t}\,\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon is a curved mix of data and noise, while flow matching uses the straight mix (1−t) x0+t x1(1-t)\,\mathbf{x}_0 + t\,\mathbf{x}_1. (Careful: in diffusion notation x0\mathbf{x}_0 is the data. Here it is the noise. Notation differs between papers.) With Gaussian noise, predicting the noise, the clean data or the velocity are interchangeable. Diffusion with a deterministic sampler is itself a flow, and flow matching with Gaussian noise is a form of diffusion. In practice flow matching offers:

  • a simpler derivation and code, with no β\beta schedule to choose,
  • straighter paths, so fewer sampling steps,
  • and in large-scale comparisons (for example the SD3 paper) equal or better quality.

Modern systems mix the vocabularies freely: "a rectified-flow Transformer trained with flow matching, sampled with an Euler scheduler in diffusers."

In code

Flow matching on the two moons, in PyTorch. Compare it with the DDPM code in Diffusion Models: there is no noise schedule, and the training target is simply x1 - x0. It runs in about 15 seconds on a CPU.

import torch, torch.nn as nn
from sklearn.datasets import make_moons

torch.manual_seed(0)
X = torch.tensor(make_moons(10_000, noise=0.03, random_state=0)[0], dtype=torch.float32)
X = (X - X.mean(0)) / X.std(0)

# Velocity network: sees (point, time) and outputs a 2-D velocity
net = nn.Sequential(nn.Linear(3, 128), nn.SiLU(), nn.Linear(128, 128), nn.SiLU(),
                    nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, 2))
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(5001):
    x1 = X[torch.randint(0, len(X), (512,))]      # data
    x0 = torch.randn_like(x1)                     # noise
    t = torch.rand(512, 1)                        # random time in [0, 1]
    xt = (1 - t) * x0 + t * x1                    # point on the straight line
    target = x1 - x0                              # its (constant) velocity
    loss = ((net(torch.cat([xt, t], 1)) - target) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 2500 == 0:
        print(f"step {step}  loss {loss.item():.3f}")

def sample(n_steps, n=2000):                      # Euler integration from t=0 to t=1
    x = torch.randn(n, 2)
    with torch.no_grad():
        for i in range(n_steps):
            t = torch.full((n, 1), i / n_steps)
            x = x + net(torch.cat([x, t], 1)) / n_steps
    return x

for n_steps in [1, 2, 10, 100]:
    d = torch.cdist(sample(n_steps), X).min(1).values
    print(f"{n_steps:3d} steps: median distance to data {d.median():.3f}  within 0.1: {(d < 0.1).float().mean():.0%}")

# step 0  loss 1.906
# step 2500  loss 1.371
# step 5000  loss 1.417
#   1 steps: median distance to data 0.356  within 0.1: 0%
#   2 steps: median distance to data 0.200  within 0.1: 26%
#  10 steps: median distance to data 0.006  within 0.1: 90%
# 100 steps: median distance to data 0.006  within 0.1: 94%

Notice the loss: it stalls around 1.4 and never approaches zero, yet the samples are excellent. The per-pair targets are inherently ambiguous: many different lines pass through the same point. The best the network can do is predict their average, and the leftover spread is unavoidable error. As with diffusion, look at samples, not just the loss.

Common pitfalls

  • Time-direction conventions. Some papers and libraries (rectified flow, SD3, diffusers' flow-matching schedulers) put data at t=0t = 0 and noise at t=1t = 1, the opposite of this chapter. The velocity's sign flips with it. Mixing conventions gives samples that run away from the data.
  • Expecting the loss to reach zero. It won't (see above). Compare runs by sample quality.
  • Too few steps with a curved field. One Euler step collapses samples to the mean, as the picture shows. Use enough steps, a better solver, or a distilled or reflowed model for few-step generation.
  • Uniform time sampling at scale. For images, the middle times are the hardest and most informative. SD3 found that sampling tt more often near the middle (a "logit-normal" distribution) improved results.
  • Forgetting the time input. Like a diffusion denoiser, the velocity network must know tt.

Watch out Normalizing flows give exact likelihoods, but flow-matching models do not by default. Their likelihood can be computed by solving an extra ODE, but it is expensive and rarely done. Don't assume every "flow" model can score data cheaply.

Where it leads

  • Diffusion Transformers: the Transformer backbones that most flow-matching image and video models use.
  • Latent Diffusion and Stable Diffusion: flow matching usually runs in a VAE's latent space, exactly like latent diffusion.
  • Video Generation: Movie Gen and other recent video models are trained with flow matching.
  • Music and Voice Generation: Meta's Voicebox and several later speech generators use flow matching to produce speech features.
  • Few-step generation: reflow, consistency models and adversarial distillation all aim at one- to four-step samplers.

A bit of history

Laurent Dinh, with David Krueger and Yoshua Bengio, introduced NICE in 2014. With Sohl-Dickstein and Bengio he followed it with RealNVP in 2016. Rezende and Mohamed coined "normalizing flows" for variational inference in 2015. Glow (Kingma and Dhariwal, 2018) produced the most impressive flow-generated faces. In 2018 Chen, Rubanova, Bettencourt and Duvenaud's Neural Ordinary Differential Equations won a best-paper award at NeurIPS and introduced continuous flows. FFJORD made them more practical.

In 2022 three groups independently found the regression shortcut: Lipman and colleagues at Meta (Flow Matching for Generative Modeling), Liu, Gong and Liu (Rectified Flow), and Albergo and Vanden-Eijnden (stochastic interpolants). Within two years the approach had moved into production. Stable Diffusion 3 (2024) used rectified flow, Black Forest Labs' FLUX.1 models (2024) followed, and Meta's Movie Gen (2024) trained a 30-billion-parameter video model with flow matching.

Try it

  1. Replace the Euler sampler with the midpoint method: compute v1 = net(x, t), step half-way xm = x + v1 * dt / 2, compute v2 = net(xm, t + dt/2), then x = x + v2 * dt. How many steps does it need to reach 90% within 0.1?
  2. Run the sampler backwards (start from real data at t=1t=1, subtract velocity down to t=0t=0) and check that the result looks like a standard Gaussian (mean near 0, standard deviation near 1).
  3. Harder: implement one round of reflow. Generate 10,000 (noise, sample) pairs with 100 steps, train a fresh network on straight lines between those pairs, and compare 1-step and 2-step quality before and after.

Hint for 2: because the flow is invertible, data → noise is just the same ODE with time reversed.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Noise point x₀ = (0.5, −1.0), data point x₁ = (1.2, 0.3), time t = 0.25. What target velocity is the network trained to output?

  2. You sample a trained flow-matching model with just one Euler step and every point lands near the middle of the data. Why?

  3. Your flow-matching training loss stalls around 1.4, yet samples look excellent. What explains this?

  4. What main advantage do normalizing flows have that flow-matching models don't offer cheaply?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Flow Matching Guide and Code

Lipman et al. (Meta) · 2024 · Advanced · Free

A comprehensive tutorial on flow matching by the method's authors, with an accompanying PyTorch library.

Article

Flow-based Deep Generative Models

Lilian Weng · 2018 · Advanced · Free

Change of variables, RealNVP, Glow and autoregressive flows, explained with consistent notation.

Course

CS236: Deep Generative Models (course notes)

Stefano Ermon & Aditya Grover (Stanford) · Intermediate · Free

Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.

Paper

Density estimation using Real NVP

Dinh, Sohl-Dickstein & Bengio · 2016 · Advanced · Free

Affine coupling layers: an invertible network with a cheap Jacobian determinant.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/flow-matching.md