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
- Builds on
- 16 concepts →
- Quiz
- 4 questions ↓
Read first
What Generative Models DoThis leads to
—The full path from zero — 16 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- What Generative Models Do
- 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 , 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.
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 from a standard Gaussian and push it through a function to get . If is invertible (every comes from exactly one ), you can compute the probability density of exactly with the change of variables formula:
- is the noise vector that maps to .
- is the standard Gaussian density, which is easy to evaluate.
- The last term corrects for stretching. is the Jacobian matrix of the inverse, and its determinant () measures how much it expands or shrinks volume near . If spreads probability over twice the area, the density must halve.
One-dimensional example. Let , with standard normal. The inverse is , which squeezes lengths by a factor of . At : , where the Gaussian density is , so . The distribution of 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 : a neural network that takes a position and a time and returns the direction and speed of movement. A point moves by following it:
This is an ordinary differential equation (ODE). It says that the rate of change of the position is the velocity. Starting from noise and following the field until gives a sample . 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 , a data point , and a time drawn uniformly between 0 and 1. The straight-line path between them is:
At it is the noise point, at the data point, and in between a weighted mix. Its velocity is the same at every time:
So the flow matching loss is a plain squared error between the network's velocity and that target:
averaged over random choices of , and . 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 , data point , time :
- Point on the line: .
- Target velocity: .
- Check: moving from at that velocity for the remaining time gives , the data point.
The network sees the input and is trained to output . 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 equal time steps of size and repeatedly move a little along the current velocity:
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% |
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 is a curved mix of data and noise, while flow matching uses the straight mix . (Careful: in diffusion notation 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 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 and noise at , 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 more often near the middle (a "logit-normal" distribution) improved results.
- Forgetting the time input. Like a diffusion denoiser, the velocity network must know .
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
- Replace the Euler sampler with the midpoint method: compute
v1 = net(x, t), step half-wayxm = x + v1 * dt / 2, computev2 = net(xm, t + dt/2), thenx = x + v2 * dt. How many steps does it need to reach 90% within 0.1?- Run the sampler backwards (start from real data at , subtract velocity down to ) and check that the result looks like a standard Gaussian (mean near 0, standard deviation near 1).
- 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Flow Matching Guide and Code
A comprehensive tutorial on flow matching by the method's authors, with an accompanying PyTorch library.
Flow Matching for Generative Modeling
A simpler, faster way to train continuous generative models.
Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow
Rectified flow: learn straight noise-to-data paths, then straighten them further by reflowing.
Flow-based Deep Generative Models
Change of variables, RealNVP, Glow and autoregressive flows, explained with consistent notation.
CS236: Deep Generative Models (course notes)
Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.
Density estimation using Real NVP
Affine coupling layers: an invertible network with a cheap Jacobian determinant.
Scaling Rectified Flow Transformers for High-Resolution Image Synthesis
Stable Diffusion 3: rectified flow with a multimodal diffusion Transformer (MM-DiT).
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/flow-matching.md