Flow Matching Guide and Code

Flow Matching trains a network to name the velocity that carries random noise to real data, by regressing on one straight line at a time. No simulation is needed during training.

Learn how a velocity field turns a cloud of noise into a shape, why a loss on single straight lines trains the right field, and how the same recipe reaches guidance, discrete tokens and curved spaces.

Press Run with one step, then with four, then with thirty-two. Watch the purple noise slide onto the blue moons. Then we build, piece by piece, the field, the path, the loss, the training loop and the extensions.

You need a feel for vectors (an arrow with a length and a direction) and a little Python for the code. We build the rest from zero.

Based on Flow Matching Guide and Code (arXiv 2412.06264, December 2024) by Yaron Lipman, Marton Havasi, Peter Holderrieth, Neta Shaul, Matt Le, Brian Karrer, Ricky T. Q. Chen, David Lopez-Paz, Heli Ben-Hamu and Itai Gat, from FAIR at Meta, MIT CSAIL and the Weizmann Institute. Code: flow_matching. This is an assigned reading of MIT MMAI Lecture 10, Modern Generative AI in the Multimodal AI course (Spring 2026). Every idea is re-taught here in our own words and devices.

Flow noise onto the moons

Toy setting, not a trained network: the 48 blue points are made-up moons, and the velocity is the paper’s exact marginal field for that tiny dataset (Chapter 3 derives it). Each particle takes plain Euler steps (Chapter 1) from a fresh Gaussian draw. The success and miss numbers are measured live on your 200 particles.

Chapter 0

Why Learn a Rule That Moves Noise

See what a generative model must do, why the older recipe was costly to train, and what Flow Matching changes

You hold 48 dots arranged as two curved moons. In your other hand is a bag of random dots drawn from a bell curve, a fuzzy cloud centred on zero. You want a rule that moves each random dot until it lands on the moons. Then you can make as many new moon dots as you like. Pull a random dot from the bag, apply the rule, and out comes a point that looks like data.

That wish is the whole field of generative modeling: learn from examples how to make new ones. Swap the moons for photographs, speech or protein shapes and the wish stays the same. This lesson teaches one paper, Flow Matching Guide and Code, a self-contained reference for one very successful way to find the rule. It comes from FAIR at Meta, with co-authors at MIT CSAIL and the Weizmann Institute.

Two distributions

A distribution says how likely each point is. Think of it as a recipe for scattering dots: most dots land where the recipe is high, few where it is low. The paper uses two. The source distribution p is the bag of noise. It is easy to sample, because a computer can draw bell-curve numbers all day. The target distribution q is the data. We never see its formula. We only hold examples, such as our 48 moon dots.

The goal, in the paper’s words, is a map that sends a sample X0 from p to a sample X1 that behaves as if it came from q. The paper writes samples as capital letters. X0 is a dot from the bag. X1 is a dot that should look like data.

The rule is a velocity

Flow Matching writes the rule as motion. At every moment t between 0 and 1, and at every place x in space, an arrow tells a dot which way to go and how fast. The arrow is a velocity. The full set of arrows, one per place and moment, is a velocity field. A dot starts at t = 0 as noise and rides the arrows until t = 1. Its whole journey is a flow. The hero at the top of this page shows exactly that: 200 dots riding one velocity field onto the moons.

What came before

The idea of a learned velocity is not new. Continuous normalizing flows (Chen et al., 2018; Grathwohl et al., 2018) used it first. They trained the arrows by maximum likelihood: change the arrows until the training examples look as probable as possible under the model. To score one training example, the computer must run the dot’s whole journey, step by step, and then work out how every arrow shaped the result. The paper calls this need for simulation (running the journey during training) a computational burden. It is the cost the field then spent years removing.

Diffusion models removed it by a different route. They destroy data with a random noising process and learn to undo it. Their training needs no simulation, and they became the standard for images. Flow Matching keeps the no-simulation training and drops the random process: its dots follow smooth, deterministic paths. Chapter 5 shows that diffusion is a special case of the same recipe.

The two-step recipe

The paper boils Flow Matching down to two steps, drawn as its Figure 2. First, choose a probability path: a movie of distributions pt that starts as the noise p at t = 0 and ends as the data q at t = 1. Second, train a velocity field whose arrows make dots follow that movie. Training is plain regression: the network guesses an arrow, we compare it with the true arrow, and we shrink the squared difference. Nothing is simulated.

Feel the saving before the explanation. The paper’s own Code 1 trains on 256 moon samples per step for 10,000 steps. Drag the number of solver steps that a simulation-based method would need for each sample.

Count the network calls

Two bars show how many times the network must run to train on one batch of 256 samples. Drag the number of solver steps. The short bar is Flow Matching.

50

Illustrative cost model, not a measurement: it counts one network call per solver step and one call for Flow Matching, and it ignores the extra work of differentiating through the steps, which only widens the gap. The batch of 256 and the 10,000 training steps are from the paper’s Code 1.

With 50 steps, simulation needs 12,800 calls per batch, where Flow Matching needs 256. Over the 10,000 steps of Code 1 that is 128 million calls against 2.56 million. The network is the same. The difference is only what it is asked to do during training.

The road

Each chapter builds one piece of the recipe, then the Field Guide collects the numbers and code.

  1. Flows and velocity fields: what the arrows define, and how a solver rides them.
  2. Probability paths: the movie of distributions, and why single examples suffice.
  3. The conditional trick: the loss on one line equals the loss on the whole field.
  4. Training and sampling: the 20 lines of Code 1, with shapes, and a net you train here.
  5. Schedulers and diffusion: affine paths, four ways to predict, and the link to diffusion.
  6. Straight paths and couplings: optimal transport and fewer solver steps.
  7. Guidance: conditioning on a label and classifier-free guidance.
  8. Beyond the plane: discrete tokens, curved spaces and Generator Matching.
  9. The Field Guide: numbers, checklist, core code, links onward.
What cost does Flow Matching remove compared with training a continuous normalizing flow by maximum likelihood?

Chapter 1

Flows and Velocity Fields

Turn a field of arrows into a journey for every dot, and ride it with a solver whose step count you choose

Drop a leaf into a river. At every spot and every moment the water has a direction and a speed. The leaf does not choose; it simply goes where the water goes. Write down the water’s push at every place and time, and the leaf’s whole path follows.

That is the picture behind Flow Matching. The water is a velocity field, written ut(x): an arrow for each place x at each time t. The leaf is a dot. The path it takes is decided by one rule, and the paper’s Section 3 is about that rule.

The flow ODE

Let ψt(x) be where a dot that started at x has arrived by time t. Its speed at that moment is the field’s arrow at its current place. That sentence, in symbols, is an ordinary differential equation (ODE): a rule that gives a quantity’s rate of change in terms of the quantity itself.

dψt(x)/dt
How fast the dot’s position changes at time t. A vector with the same number of entries as x. The paper calls this equation the flow ODE (its 3.19).
ut
The velocity field. In Flow Matching this is the neural network, written uθt when its weights θ are meant.
ψt(x)
The dot’s current place. The field is read at this place, not at the start. That is what makes the path bend.
ψ0(x) = x
The starting condition: at time 0 the dot sits where it began.

The mapping ψt from starting places to places at time t is the flow. If the field is smooth, a classical theorem (the paper’s Theorem 1) says each dot has exactly one path, and the flow is a diffeomorphism: a smooth, reversible map. Reversible means no two dots ever merge and no dot is lost. You can run any journey backwards. Smooth fields and flows describe each other, so learning the field is the same as learning the flow.

Riding the arrows with a solver

To make a sample we need X1 = ψ1(X0) for a fresh noise dot X0. A computer cannot follow the dot continuously. It takes small steps. The simplest rule is the Euler method: look at the arrow here, move along it for a short time h, repeat.

Xt+h
The dot after one more step.
Xt
The dot now.
h
The step size, h = 1/n for n steps from time 0 to time 1.
ut(Xt)
The arrow at the dot’s current place: one network call.

Euler is the first-order Taylor expansion of the path, so each step hides a small error of order o(h), and after n = 1/h steps the total error shrinks to zero as h does. The paper also shows the midpoint method in its Code 1: peek half a step ahead, read the arrow there, and use that arrow for the whole step. It costs two network calls per step and is more accurate.

A worked example with every number

Take a field where the dot circles the origin once per unit of time: u(x, y) = (−2πy, 2πx). The exact path is a circle. Start at (1, 0) and use n = 8 Euler steps, so h = 0.125 and 2πh = 0.785.

  1. Step 1. The arrow at (1, 0) is (0, 6.283). Move h along it: (1, 0) + 0.125 × (0, 6.283) = (1, 0.785). The dot already sits on a circle of radius 1.27, not 1.
  2. Step 2. The arrow at (1, 0.785) is (−4.935, 6.283). New place: (1 − 0.617, 0.785 + 0.785) = (0.383, 1.571), radius 1.62.
  3. Every step multiplies the radius by the same factor, √(1 + 0.617) = 1.27. After 8 steps: 1.278 = 6.83. The dot should have come home to radius 1.

That is the failure mode. The symptom is a dot that spirals off the circle. The measurement is the radius after one lap. The fix is a smaller step or a better solver. Try it.

Ride a rotating field

The dashed circle is the exact path of one lap. The warm line is the solver’s path from (1, 0). Pick a solver and drag the number of steps. Watch the end point.

8

Toy field with a known exact answer, not a trained model. The solvers are computed live in your browser. The view is cut off at radius 2.2, so a path that leaves the frame is reported in the read-out instead.

With 8 Euler steps the dot ends at radius 6.83. With 64 it still ends at radius 1.36, and it needs about 2,000 steps to get within 1 percent. Midpoint at 8 steps already ends at radius 1.44, and at 64 steps it ends at 1.0007. This is why the paper’s Code 2 and Code 1 both use the midpoint solver.

Two gifts of a flow

A flow has a bonus. Because it is deterministic and reversible, you can compute the exact likelihood of any data point: run the ODE backwards from the data point and add up the field’s divergence (how much the arrows spread out) along the way. The paper’s equation 3.30 states it: d/dt log pt(ψt(x)) = −div(ut)(ψt(x)). Diffusion models generally give only bounds. Chapter 6 shows that straight paths are also cheap to ride.

A dot follows a curved path. You halve the Euler step size h. What happens, and what does it cost?

Chapter 2

Probability Paths From Single Examples

Build a movie of distributions from noise to data by pairing the noise with one example at a time

Picture a time-lapse of a crowd gathering in a square. At the first frame people are spread thinly and evenly. At the last frame they have formed a shape. Every frame in between is a snapshot of where the crowd is dense and where it is thin. A snapshot of that kind is a distribution, and the whole film is a probability path: a distribution pt for each time t from 0 to 1.

The paper asks for two things of the film. It must start as the noise, p0 = p, and end as the data, p1 = q. Those are the boundary conditions. Everything in between is ours to design. Chapter 1 said that a velocity field moves dots. A field generates a path when dots that start in p0 and ride the field are spread like pt at every time t.

The hard way and the easy way

Designing the whole film at once is hard, because q is only a pile of examples. The paper’s key move is to design it one example at a time. Pick a single data point x1. Describe a small film of just that point: noise at the start, a single spike at x1 at the end. This is the conditional probability path pt|1(x | x1), read as the density at x at time t, given that the target is x1.

The paper’s first choice is a bump that shrinks and slides toward x1.

pt|1(x | x1)
How dense the film of one example is at place x and time t. The paper’s equation 2.2.
N
A Gaussian: the bell-curve bump, written N(x | mean, variance).
t·x1
The centre of the bump. It starts at 0 (the noise centre) and slides to x1.
(1 − t)2 I
The spread. It starts at 1, the width of the noise, and shrinks to 0, a spike. I is the identity matrix: the same spread in every direction.

Check the boundaries. At t = 0 the mean is 0 and the spread is 1, so p0|1 is exactly the noise N(0, I), whatever x1 is. At t = 1 the spread is 0 and the mean is x1, so all the mass sits on x1. Both boundary conditions hold, one example at a time.

Mix the small films into the big one

Now pick the target at random from the data and average the small films. This is the marginal probability path, the paper’s equation 4.4.

pt(x)
The film we wanted: the density of the whole crowd at time t.
pt|1(x | x1)
The small film for one example.
q(x1)
How often the data contains x1. For a dataset, the integral becomes a plain average over the examples.

The boundaries survive the averaging. At t = 0 every small film is the same noise, so the average is the noise. At t = 1 every small film is a spike on its own example, so the average is the data. To draw a dot from pt you need no formula: draw X0 from the noise, draw X1 from the data, and take Xt = t X1 + (1 − t) X0, the paper’s equation 2.3. It is a point t of the way along the straight line between them.

Here is the film for a few data points in one dimension. Drag the time.

Play the probability path

Dashed bumps are the small films, one per data point. The warm curve is their average, pt. Blue ticks mark the data. Drag t from 0 to 0.97.

0.50

Illustrative data in one dimension: the points are at −2 and 2 (or −3, −1, 1, 3, or just 2). The curves use the paper’s path N(x | t x1, (1 − t)2) exactly. The vertical scale is refitted at every t, so heights are not comparable between times.

At t = 0.5 with the two points −2 and 2, each bump sits at ±1 with width 0.5. The mixture is 0.40 high over a bump centre and only 0.11 high at the middle. The film is already splitting in two. By t = 0.97 the bumps are 0.03 wide, nearly spikes on the data.

When a path cannot be generated

Not every film is allowed. A flow is deterministic and reversible, so it can never squeeze all dots into one point and then spread them out again. The paper gives an example: a smooth interpolation that sends every pair (x0, x1) to the single point 0 at t = 0.5. No flow can make that film, because a spike at t = 0.5 would stay a spike. The symptom is a path that looks fine on paper but has no velocity field. The measurement is the Continuity Equation, which every generating pair (ut, pt) must satisfy. The fix is to build the small films from invertible maps, as the linear one above is for every t below 1.

The Continuity Equation is conservation of probability. It says that the change of probability inside any region equals minus the probability flowing out through its edge. The paper writes it as dpt/dt + div(pt ut) = 0. The Mass Conservation theorem says that this equation holding is the same as ut generating pt.

In the conditional path N(x | t·x1, (1 − t)2 I), what do the dots look like at t = 0 and at t = 1?

Chapter 3

The Conditional Trick

Derive the arrow for one example, average it into the arrow for the whole dataset, and see why training on one example gives the same gradients

You stand at a crossroads and must tell travellers where to go. Some are headed for town A, some for town B, some for town C. If you knew each traveller’s town, the advice would be easy: point at it. You do not know. All you see is where each person stands and what time it is. The best single advice is a blend of the three pointings, weighted by how likely each town is, given where this person stands.

That blend is the whole content of this chapter. The pointing for a known town is the conditional velocity. The blend is the marginal velocity, the arrow the network must learn. The paper’s surprise is that you can train on the easy pointings and still learn the blend.

The arrow for one example

Fix one data point x1. A dot on the conditional path is Xt|1 = t x1 + (1 − t) X0. Its velocity is the time derivative of that line. We need the velocity as a function of where the dot is, so first solve for the noise: X0 = (x − t x1)/(1 − t) when the dot sits at x.

  1. Differentiate the line. d/dt [t x1 + (1 − t) X0] = x1 − X0.
  2. Replace the noise. x1 − (x − t x1)/(1 − t) = [x1(1 − t) − x + t x1]/(1 − t).
  3. Simplify. The x1 terms collapse to x1, which leaves the paper’s equation 2.6.
ut(x | x1)
The arrow at place x and time t for a dot that is bound for x1.
x1
The example the dot is heading for.
x
Where the dot is now.
1 − t
The time left. The arrow says: cover the remaining gap in the remaining time. It grows as t nears 1.

The blend for the whole dataset

Now let the target be random. At place x and time t, the chance that a dot is bound for x1 comes from Bayes’ rule: p1|t(x1 | x) = pt|1(x | x1) q(x1) / pt(x). In words: examples that make x likely get more weight. The marginal velocity is the weighted average of the pointings, the paper’s equation 4.8.

ut(x)
The marginal velocity: the one arrow per place and time that the network will learn.
ut(x | x1)
The pointing for one example, from the box above.
p1|t(x1 | x)
The weight: how likely this example is, given the dot stands at x at time t.

The paper’s Marginalization Trick (Theorem 3) says that this blended field generates the marginal path of Chapter 2. The proof differentiates the mixture, uses the Continuity Equation for each small film, then multiplies and divides by pt(x). Here is a worked number. The data are −2 and 2, the time is t = 0.5 and the dot stands at x = 0.5.

  1. Pointings. Toward 2: (2 − 0.5)/0.5 = 3. Toward −2: (−2 − 0.5)/0.5 = −5.
  2. Likelihoods. A dot bound for 2 has centre 1 and width 0.5, so exp(−(0.5 − 1)2/0.5) = 0.607. For −2 the centre is −1: exp(−(0.5 + 1)2/0.5) = 0.011.
  3. Weights. 0.607/(0.607 + 0.011) = 0.982 for 2, and 0.018 for −2.
  4. Blend. 0.982 × 3 + 0.018 × (−5) = 2.946 − 0.090 = 2.86.

The dot is pulled almost fully toward 2, because it already stands on that side. Move the query point below and watch the weights flip.

Average the arrows

Blue dots A, B and C are three data points. The dashed arrows are the conditional arrows toward each. The thick warm arrow is their weighted average. Move the teal query point and the time.

0.60
0.30
0.50

Illustrative: three made-up points A (−1.6, 0.9), B (1.5, 1.0) and C (0.2, −1.4). The weights and arrows are the paper’s exact formulas for a finite dataset. Arrows are drawn at 0.3 of their true length so they fit the frame.

Near t = 0 the dot knows little: the three weights are close to equal, and the blend points near the data centre. Near t = 1 one weight wins and the arrow points straight at the nearest example. This is also why the hero lands on the moons.

The loss that never needs the blend

The ideal loss regresses the network onto the blend, the Flow Matching loss LFM = Et, Xt D(ut(Xt), uθt(Xt)), where D is a distance between arrows. We cannot compute it: the blend needs every example. The Conditional Flow Matching loss uses the easy pointing instead.

LCFM(θ)
The loss we compute. The paper’s equation 4.23.
D
A Bregman divergence, a family of distances that includes the plain squared distance ‖u − v‖2.
ut(Xt | X1)
The target: the pointing for the example this dot came from.
uθt(Xt)
The network’s guess. It sees only Xt and t. It never sees X1.

Theorem 4 says ∇θLFM = ∇θLCFM. The reason is ordinary regression. If you fit noisy labels by least squares, you learn the average label for each input. Here the label for Xt is one example’s pointing, and the average over the examples that could have produced Xt is exactly the blend. Bregman divergences have the needed property: the gradient of D(E[Y], v) equals E[gradient of D(Y, v)]. With the squared distance and the linear path, the target simplifies to X1 − X0 (equation 2.9), a constant per line.

The symptom to expect is a loss that never reaches zero, even for a perfect network. The measurement is the spread of the pointings: the loss floor equals E‖ut(Xt | X1) − ut(Xt)‖2, which is above zero whenever two examples could make the same Xt. The fix is to stop watching for zero. Judge the model by its samples.

The network sees only Xt and t during CFM training, yet each target is one example’s pointing. Why does it still learn the correct marginal velocity?

Chapter 4

Training and Sampling, Step by Step

Follow every tensor through the paper’s twenty-line program, then train a small network in your browser and sample from it

A recipe card has a short list of steps. The whole of Flow Matching fits on one. Take a batch of data. Take a batch of noise. Pick a random time for each pair. Slide each noise dot part of the way to its data dot. Ask the network which way the dot is heading. Compare, and nudge the weights. The paper’s Code 1 does exactly that on two moons, and this chapter reads it line by line.

One training step with shapes

Here is the loop, shortened from Code 1 with the tensor shapes added. B is the batch size (256) and d the data dimension (2 for moons).

pythonclass Flow(nn.Module):                         # the velocity field u_theta(x_t, t)
    def __init__(self, dim=2, h=64):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(dim + 1, h), nn.ELU(),
                                 nn.Linear(h, h), nn.ELU(),
                                 nn.Linear(h, h), nn.ELU(),
                                 nn.Linear(h, dim))
    def forward(self, x_t, t):                 # x_t [B,2], t [B,1]
        return self.net(torch.cat((t, x_t), -1))   # [B,3] in, [B,2] out: one arrow per dot

flow = Flow(); optimizer = torch.optim.Adam(flow.parameters(), 1e-2)
for _ in range(10000):
    x_1  = Tensor(make_moons(256, noise=0.05)[0])   # [256,2] data
    x_0  = torch.randn_like(x_1)                     # [256,2] noise
    t    = torch.rand(len(x_1), 1)                 # [256,1] one time per pair, uniform on [0,1)
    x_t  = (1 - t) * x_0 + t * x_1                   # [256,2] point on the line
    dx_t = x_1 - x_0                                 # [256,2] the target arrow
    optimizer.zero_grad()
    nn.MSELoss()(flow(x_t, t), dx_t).backward()      # squared error between arrows
    optimizer.step()

Why each choice? The time t is an input because the right arrow depends on it: at t = 0 a dot should head for the data centre, at t = 0.9 for its nearest example. Time is sampled uniformly so every moment of the film gets trained. The data and noise are independent: the paper’s coupling (Chapter 6) when no pairing is known. The target is a constant X1 − X0 along each line, so no ODE is run. The network is an ordinary MLP: three hidden layers of 64 units, with ELU activations.

One pair, in numbers, in one dimension. Take X1 = 2, X0 = −0.4 and t = 0.3. The point is Xt = 0.7 × (−0.4) + 0.3 × 2 = 0.32. The target arrow is 2 − (−0.4) = 2.4. If the network says 1.9 at (0.32, 0.3), the loss for this pair is (1.9 − 2.4)2 = 0.25, and its gradient pushes the output up.

Sampling: ride the arrows

To make new data, start from fresh noise and solve the ODE of Chapter 1. Code 1 draws 300 noise dots, takes n_steps = 8 midpoint steps over t from 0 to 1, and plots a frame after each. Its step function reads the arrow at the start, moves half a step, reads the arrow again at the halfway time, and uses that arrow for the whole step. Eight steps cost 16 network calls per dot. Inputs are [300, 2]; outputs are [300, 2]; no batch dimension changes anywhere.

Train one here

The device below runs the same loop in your browser on a smaller problem. The data are two points, −2 and 2, in one dimension. The network is one hidden layer of 24 tanh units with input (x, t). It trains with Adam on batches of 128. After every few steps it samples 400 fresh noise dots with the Euler steps you pick and counts where they land.

Train and sample a tiny flow

Top: the training loss and the best loss any network can reach. Bottom: where 400 noise dots land after your chosen steps, with the two data points marked. Press Train, then change the sampling steps.

A real training loop, small enough to run live: hand-written backpropagation and Adam (learning rate 0.01), seeded so the first run is the same on every visit. It is not the paper’s moons network. The best-possible loss is measured by Monte Carlo from the exact marginal velocity (2 tanh(2tx/(1−t)2) − x)/(1−t) on 20,000 fresh pairs.

Watch the loss. It falls fast, then flattens above the green line, then creeps toward it. It never reaches zero: Chapter 3 explained that the floor is the spread of the pointings. Now look at the histogram. With 1 step the dots collapse into a heap near the middle, because one Euler step can only jump to the average of the two data points. With 4 and 16 steps they split into two clusters on the data. The loss tells you how well the field fits. The samples tell you whether it works.

The symptom is a good-looking loss and bad samples with few steps. The measurement is the fraction of dots within 0.5 of a data point, printed in the read-out. The fix is more steps, a better solver, or straighter paths (Chapter 6).

In the paper’s Code 1, what is the regression target for a pair (x_0, x_1) at time t?

Chapter 5

Schedulers, Four Ways to Predict, and Diffusion

Turn the two knobs that mix noise and data, then see that diffusion models are one setting of the same machine

A sound engineer mixes a track with two faders. One fader sets how much of the clean recording you hear. The other sets how much hiss. At the start, all hiss. At the end, all recording. How the two faders move in between is a design choice, and engineers argue about it.

The linear path of Chapters 2 to 4 is one such mix: the signal fader goes up as t, the hiss fader goes down as 1 − t. The paper generalizes it as affine conditional flows, its Section 4.8.

ψt(x | x1)
Where a noise dot x ends up at time t when its target is x1. The paper’s equation 4.50.
αt
The signal fader. It rises from α0 = 0 to α1 = 1.
x1
The data example.
σt
The noise fader. It falls from σ0 = 1 to σ1 = 0.

The pair (αt, σt) is the scheduler. It must be smooth, with α strictly rising and σ strictly falling. Code 5 of the paper lists four: conditional optimal transport (α = t, σ = 1 − t, our linear path), a polynomial (α = tn, σ = 1 − tn), a linear variance-preserving one (α = t, σ = √(1 − t2)) and a cosine one (α = sin(πt/2), σ = cos(πt/2)). Differentiating the mix gives the target arrow, and the marginal field is its average:

ut(x)
The marginal arrow (the paper’s equation 4.52).
α̇t
The rate at which the signal fader rises, the derivative of αt.
σ̇t
The rate at which the noise fader falls. It is negative.

Four ways to say the same thing

A network that guesses the arrow is one choice. The average above contains X1 and X0, so the network could instead guess either of them. Write x1|t(x) = E[X1 | Xt = x], the x1-prediction (a denoiser: the best guess at the clean data), and x0|t(x), the x0-prediction (the guess at the noise, called ε-prediction in diffusion). Since x = α x1 + σ x0, each guess can be swapped for the other and for the arrow.

  1. From the mix. x0 = (x − α x1)/σ.
  2. Put it in the arrow. α̇ x1 + σ̇ (x − α x1)/σ = (σ̇/σ) x + (α̇ − σ̇ α/σ) x1. This is the paper’s equation 4.56.
  3. The noise route is the mirror: u = (α̇/α) x + (σ̇ − α̇ σ/α) x0|t(x). Equation 4.57.
  4. The score. For Gaussian paths the gradient of the log density is ∇ log pt(x) = −x0|t(x)/σt. Equation 4.77.

The paper’s Table 1 lists all the conversions among velocity, x1, x0 and score. They differ only by two numbers that depend on t, so you may train in the form that suits you and sample in another. Code 6 trains an x1-prediction with the loss ‖model(xt, t) − x1‖2 and converts to a velocity when it samples.

A number check at t = 0.6 with the linear scheduler, X1 = 2 and X0 = −0.4. The mixed point is x = 0.6 × 2 + 0.4 × (−0.4) = 1.04. The direct arrow is α̇ x1 + σ̇ x0 = 2 + (−1)(−0.4) = 2.4. Through x1: (−1/0.4)(1.04) + (1 + 0.6/0.4)(2) = −2.6 + 5.0 = 2.4. Through x0: (1/0.6)(1.04) + (−1 − 0.4/0.6)(−0.4) = 1.733 + 0.667 = 2.4. Three routes, one answer. Try other schedulers below.

Turn the two faders

Blue is the signal fader α, purple the noise fader σ. The dot marks time t. The read-out computes the arrow for X1 = 2 and X0 = −0.4 by three routes.

0.60

The four schedulers are the ones in the paper’s Code 5. The pair X1 = 2, X0 = −0.4 is made up for the check. The identity itself is exact, and it holds for any pair.

The conversion has a catch, and the symptom shows near the ends of time. The factor σ̇/σ grows without limit as σ goes to zero. In theory the terms cancel. In practice the network is never exact, so its error is multiplied. The measurement is that factor: for the linear scheduler it is 2 at t = 0.5 and 20 at t = 0.95. The paper’s fix is to replace the conversion by its known limit at the ends, which for a Gaussian source is u0(x) = σ̇0 x and u1(x) = α̇1 x.

Diffusion is a special case

A Gaussian source with the independent coupling gives conditional paths N(x | αt x1, σt2 I). The paper then states that standard diffusion models are exactly this family: its Variance Preserving and Variance Exploding paths are choices of (α, σ). Three differences are only conventions. Time runs backwards in diffusion (noise at r = ∞, data at r = 0), where Flow Matching uses noise at t = 0 and data at t = 1. Diffusion samples with a random SDE that has the same marginals as the flow. And diffusion names its network after the score, the noise (ε) or “v”, where v-prediction is the velocity for a particular path. Everything in Table 1 converts between them.

Two practical consequences follow. The marginal velocity of a Gaussian path is a gradient, so it is the kinetically optimal field for that path. And a trained field can be moved to a different scheduler without retraining, by rescaling time and space with the signal-to-noise ratio ρt = αt/σt (the paper’s Section 4.8.2).

A network is trained to predict the clean data x1 (the denoiser). How do you sample from it as a flow?

Chapter 6

Straight Paths and Couplings

See why straight journeys need fewer solver steps, and how pairing noise with data cleverly makes the lines cross less

Two lanes of traffic cross at a junction. Each driver wants to go straight to a destination, but the lanes interleave: a car heading left meets a car heading right, and the junction must make each wait or swerve. If the same cars were assigned to destinations so that no lane crossed another, every journey could be a straight run with no swerving.

That is the question of this chapter. In Chapter 1 the solver paid for curvature: a straight path is exact for one Euler step, and a curved path needs many. So how straight can the journeys be, and what controls it?

The straight line is the cheapest conditional path

The paper first asks which conditional flow costs the least motion. It measures cost by kinetic energy: the sum, over time and place, of squared speed weighted by how much probability sits there, written ∫∫ ‖ut(x)‖2 pt(x) dx dt. Minimizing it while moving p to q is the dynamic Optimal Transport problem. Its solution is the OT displacement interpolant: each dot moves in a straight line at constant speed to a partner determined by an optimal map φ.

The marginal field is hard to optimize directly, so the paper bounds it. By Jensen’s inequality the kinetic energy of the blended field is at most the average kinetic energy of the pointings, taken per pair (x0, x1). Each pair can then be minimized on its own: choose the path γt from x0 to x1 that minimizes ∫‖γ̇t‖2 dt. The Euler-Lagrange equation says the path has zero acceleration, so it is the straight line γt = t x1 + (1 − t) x0. That is exactly the linear path we have used. When the target is a single point, Theorem 5 says it is the exact OT solution.

Why the blended paths still bend

Each conditional path is straight. The paths that dots actually follow under the marginal field need not be. Two lines from different pairs may cross. At the crossing point a dot sits on both lines, but a flow is deterministic and can give it only one arrow. The field averages the two pointings, and the true trajectories bend away from both lines. More crossings mean more bending, and more bending means more solver steps.

The paper notes one guarantee: the blended kinetic energy is never larger than E‖X1 − X0‖2, the average squared length of the pairs used in training (equation 4.49). So shorter training pairs mean a cheaper field. And the pairs are ours to choose. The choice of how to pair noise dots with data dots is the coupling π0,1. The simplest is the independent coupling: pair at random. If a pairing is known, as in image in-painting where the masked image is X0 and the full image is X1, use it directly. The paper cites results beating guided diffusion on in-painting, super-resolution and de-blurring.

Multisample couplings

When no pairing is known, Pooladian et al. (2023) propose a cheap improvement, described in the paper’s Section 4.9.2.

  1. Draw k noise dots and k data dots, independently.
  2. Find the best pairing among them: the one-to-one matching with the smallest total cost, such as the sum of squared lengths.
  3. Train on those pairs. Pick one pair at random from the matching.

For k = 1 this is the independent coupling. For larger k the average length of the pairs falls, and for quadratic cost it approaches the Optimal Transport cost as k grows. A worked case with k = 2: noise at −1 and 1, data at 3 and −3. Pairing −1 with 3 and 1 with −3 gives squared lengths 16 + 16 = 32, and the two lines cross in the middle. Pairing −1 with −3 and 1 with 3 gives 4 + 4 = 8, and no line crosses. The matching step picked the second.

Pair noise with data

Purple dots are noise, blue dots are data. Lines are the training pairs. Pick how to pair them and how many dots k to match at once. Press Draw new dots for a fresh batch.

6

Toy dots: noise from a Gaussian and data sampled from a made-up two-moon shape, both centred on the origin. The matching is an exact search over all k! pairings. The averages are over 300 fresh draws, computed live. Crossings are counted exactly for the current draw.

With k = 1 both modes are the same, by definition. Raise k and watch the lines untangle. On this toy, optimal pairing at k = 6 cuts the average squared pair length from 4.37 to 1.95, and the average number of crossing pairs from about 3.4 to 0.2. The training pairs get shorter and straighter, so the learned field needs fewer solver steps.

The symptom of crossing pairs is a model that works at 32 steps but breaks at 2. The measurement is the average squared pair length, E‖X1 − X0‖2, and the count of crossing lines. The fix is a better coupling, at the price of one small matching problem per minibatch.

In the paper’s multisample coupling with k noise dots and k data dots, what does the matching step do?

Chapter 7

Guidance and Conditional Generation

Tell the flow what to make with a label, then turn up the label’s pull and measure what it costs in variety

Ask an artist for “a drawing” and you get anything. Ask for “a drawing of a cat” and you get a cat, but maybe a vague one. Ask the artist to try extra hard at the cat part and the cat becomes unmistakable, and also the same cat every time. This chapter is that dial. The paper’s Section 4.10 covers it in two parts: how to condition a flow on a label, and how to turn the label up.

Conditioning on a label

Suppose each training example comes with a label y, such as a class name or a caption: pairs (x1, y). The goal is to sample from q(x1 | y), the data given the label. The recipe barely changes. Build the path from the small films of examples that carry label y, pt|Y(x | y) = ∫ pt|1(x | x1) q(x1 | y) dx1. Then train one network with y as an extra input, uθt(x | y), on the same Conditional Flow Matching loss (equation 4.86). The conditional path does not depend on y, so the loss is unchanged. Only the input grows by the label’s encoding.

The paper adds two caveats from the diffusion literature. Guidance works best when many examples share a label, as with class names. It is harder when the guide is complex and rarely repeats, as with image captions.

Turning the label up

For Gaussian paths, velocities and scores convert into each other (Chapter 5, Table 1), so guidance tricks from diffusion carry over. Start from Bayes’ rule applied to the guided path. Taking the gradient of the logarithm gives the paper’s equation 4.89.

∇ log pt|Y(x | y)
The score of the label-conditioned path: which way the density rises when we know the label.
∇ log pY|t(y | x)
The score of a classifier: which way makes the label more likely at place x and time t.
∇ log pt(x)
The score of the unconditional path: which way the density rises with no label.

Read it as a sum of two pushes: the push toward data in general, plus the push toward places where a classifier recognizes the label. Classifier guidance (Song et al., 2021; Dhariwal and Nichol, 2021) trains a separate time-dependent classifier and adds its gradient, scaled by a number w, to an unconditional velocity (equation 4.91). The scale is usually above 1.

Classifier-free guidance (Ho and Salimans, 2021) needs no classifier. Rearrange the equation: the classifier’s score is the difference between the conditional and unconditional scores. Substitute into the velocity and the guided arrow becomes a blend of two arrows from the same network.

ũθt(x | y)
The arrow used for sampling. The paper’s equation 4.93.
w
The guidance scale, a number you pick when you sample. w = 0 is the unconditional model, w = 1 the plain conditional model, w > 1 pushes past it.
uθt(x | ∅)
The arrow with the label hidden. ∅ is a placeholder for “no label”.
uθt(x | y)
The arrow with the label shown.

One network learns both arrows, because during training the label is replaced by ∅ with probability puncond (equation 4.94), a coin flip per example. The paper says CFG is, at the time of writing, the most popular approach to training a conditional model, used in large-scale image and video work. It also admits that the exact distribution CFG samples from is unknown.

A number to hold on to. At some place and time, say the unconditional arrow is 2.0 and the conditional arrow is 3.0. With w = 1 the result is 3.0. With w = 2 it is (1 − 2)(2.0) + 2(3.0) = 4.0. With w = 4 it is (−3)(2.0) + 4(3.0) = 6.0. The guided arrow extrapolates beyond the conditional one, along the line from the unconditional arrow through it.

Turn up the label

The data have four modes: −3, −1, 1 and 3. The label “right” means the two modes at 1 and 3. Drag the guidance scale w and see where 600 samples land.

1.00

Toy setting, not a trained network: the two arrows are the exact marginal velocities for the four data points (unconditional) and for the two labelled points (conditional), and 600 seeded noise dots take 40 Euler steps. A real model learns both arrows from data with a label dropout.

At w = 0 the samples spread over all four modes and only about 47 percent land near the labelled modes. At w = 1 all of them do, split almost evenly between 1 and 3 (47 percent sit at 3). At w = 3 about 98 percent sit at the single mode 3. At w = 4 the spread is zero. The label is obeyed perfectly and the variety is gone.

That is the trade-off. The symptom is samples that look right but all alike. The measurement is the share of samples on each allowed mode, or their spread. The fix is a moderate w, found by looking at both quality and variety.

In classifier-free guidance with scale w = 3, how is the sampling arrow built from the network’s two outputs?

Chapter 8

Beyond the Plane: Tokens, Curved Spaces and Generator Matching

Keep the same two-step recipe and change the space: words that appear out of blanks, points on a sphere, and any process at all

Think of a crossword that starts empty. Letters do not slide into place. They simply appear, one square at a time, until the grid is full. A velocity that moves dots smoothly cannot describe that. Yet the recipe of this paper, choose a path and then train the thing that makes it, still applies. The second half of the guide shows how, and this chapter walks through it.

The paper’s Figure 1 lists four time-continuous processes that carry a source sample X0 to a target sample X1: a flow in continuous space, a diffusion in continuous space, a jump process in continuous space, and a Continuous Time Markov Chain (CTMC), a jump process on a finite set of states. For every one, the recipe is unchanged: choose a path pt from source to target, then train a generator, the object that plays the part of velocity.

Discrete Flow Matching: words from blanks

Text is made of tokens from a finite vocabulary, so there is no smooth motion between two words. A CTMC replaces the arrow with a rate: the chance per unit time of jumping from the current token to another. Write a sequence as d tokens. The paper’s Section 7 builds the path token by token, a mixture path.

pit|0,1
The chance of each token value at position i and time t, given the source tokens x0 and the target tokens x1. The paper’s equation 7.22.
κt
A scheduler from 0 to 1. At time t, each position independently shows the target token with probability κt and the source token otherwise.

With a source of all-mask tokens m (“blanks”), this is the crossword: at t = 0 every square is blank, at t = 1 every square holds the target word, and between them squares fill in at random. The conditional jump rate for a blank square is κ̇t/(1 − κt). The network is a discrete x1-prediction: for every position it outputs a probability over the clean token, pθ,i1|t(x1 | x). The loss is cross-entropy, justified by the same Bregman argument (Proposition 1) as before.

The paper’s standalone Code 11 does this for the moons. It rounds each moon point onto a grid of 128 values per coordinate, so each sample is a sequence of d = 2 tokens with vocabulary V = 128. The source is a uniform random token for each coordinate. The training step is three lines. Pick t, keep each coordinate of the data with probability t and otherwise keep the noise token, then take cross-entropy against the data token. The network returns logits of shape [B, d, V].

To sample, take Euler steps of size h. At each step, for each position: draw a clean token from the network’s posterior, then jump to it with probability h κ̇t/(1 − κt). A tiny worked case with κt = t: the jump probability is h/(1 − t). With 4 steps (h = 0.25) the four probabilities are 0.25, 0.33, 0.5 and 1.0, and an expected 8 × 0.75 × 0.67 × 0.5 = 2 blanks remain after step 3. The last step always fills the rest. In general the chance that a blank survives to time t is exactly 1 − t.

Fill the blanks

Eight tokens start as blanks. Drag the time to reveal them along the mixture path, or press a sampler to watch it fill the blanks in n Euler steps.

0.40

Toy sequence of made-up tokens, with the scheduler κt = t. The sampler assumes a perfect posterior (it always reveals the true word), so it shows only the schedule of jumps; a real model must predict the words. The reveal probabilities are the exact Euler jump probabilities h/(1 − t).

Run the 2-step sampler. At t = 0 each blank is revealed with probability 0.5. At t = 0.5 the jump probability is 0.5/0.5 = 1, so every remaining blank fills. More steps spread the work out, so each step decides fewer tokens, and the model sees more context before it commits.

Curved spaces

Some data live on a curved surface: weather on the sphere of the Earth, the angles of a protein backbone. A Riemannian manifold is such a space: it looks flat up close but bends overall. Its tangent space at a point is the flat plane that just touches it there, and arrows live in that plane. The paper’s Section 5 shows the same pieces carry over. The loss compares network and target velocities with a Bregman divergence in each tangent plane. The Marginalization Trick holds (its Theorem 10). Training is again simulation-free. The paper credits Riemannian Flow Matching (Chen and Lipman, 2024) with becoming state of the art for applications in chemistry, such as protein folding.

Any process: Generator Matching

Sections 8 and 9 generalize everything to Continuous Time Markov Processes. A generator is the object that says how a process changes; for a flow it is the velocity, for a CTMC it is a rate matrix. The paper’s Theorem 18 says that for finite sets and for Rd the generators have a complete, known form: a rate matrix in the discrete case, and a sum of drift, diffusion and jump parts in Rd. Because the generator enters the path equation linearly, models for the same path can be mixed by weights that sum to 1, and models for different modalities, such as text and images, combine by factorizing their paths. The paper says this lets one build multimodal models in a principled way.

In Discrete Flow Matching with a mask source and scheduler κt = t, why does the last Euler step always fill every remaining blank?

Chapter 9

The Field Guide

Collect the numbers, terms, checklist and core code, and find the next lessons to read

Here is the whole paper in one paragraph. A generative model needs a rule that moves noise onto data. Flow Matching writes the rule as a velocity field, which defines a flow through an ODE. To train the field, pick a probability path built from single examples, such as the straight line Xt = t X1 + (1 − t) X0. Regress the network onto the easy conditional arrow X1 − X0. The gradients equal those of the unreachable full loss, so the network learns the blended arrow. Sampling is an ODE solve. The same recipe covers other schedulers and diffusion, guidance, discrete tokens, curved spaces and general Markov processes.

The numbers to remember

ItemValueWhere in the paper
Conditional pathN(x | t x1, (1 − t)2 I)Section 2, eq. 2.2
Training targetX1 − X0 at Xt = (1 − t) X0 + t X1eq. 2.9
Conditional velocity(x1 − x) / (1 − t)eq. 2.6
Marginal velocityE[ut(Xt | X1) | Xt = x]eq. 4.8, 4.10
Code 1 setupbatch 256, 10,000 steps, Adam 0.01, MLP of 64 units (3 hidden layers, ELU)Code 1
Code 1 sampler300 dots, 8 midpoint steps (2 network calls each)Code 1
Euler / midpoint cost1 call per step / 2 calls per stepSection 3.4.2, Code 2
Affine mixXt = αt X1 + σt X0; four schedulers in Code 5Section 4.8
Score from noise guess∇ log pt(x) = −x0|t(x) / σteq. 4.77
Classifier-free guidance(1 − w) u(x | ∅) + w u(x | y)eq. 4.93
Discrete mixture pathtoken = x1 with probability κt, else x0; jump rate κ̇t/(1 − κt)eq. 7.22
Code 11 setupvocabulary 128, 2 tokens per sample, cross-entropy loss, logits [B, 2, 128]Code 11

What the paper’s figures show

This is a guide, not a benchmark paper, so it has no accuracy tables. Its figures teach. Figure 1 shows four processes from source to target: a flow, a diffusion, a jump process and a CTMC. Figure 2 is the blueprint: data, path design, training by regression, sampling by ODE. Figure 3 shows the conditional path and arrow for one example next to the blended path and arrow for the whole dataset. Figure 9 maps how velocity, flow, path, boundary conditions and loss depend on each other. Table 1 converts between velocity, x1-prediction, x0-prediction and score.

Terms

TermPlain meaning
Velocity fieldAn arrow for every place and time; the network’s output.
FlowEach dot’s journey when it rides the arrows.
Probability pathA distribution for each time, from noise to data.
Conditional pathThe path for one data example.
Marginalization TrickThe blend of conditional arrows generates the blended path.
CFM lossSquared error against one example’s arrow; same gradients as the full loss.
SchedulerThe pair (αt, σt) of signal and noise faders.
CouplingHow noise dots are paired with data dots.
GeneratorThe velocity’s counterpart for any Markov process.

The checklist

  1. Choose the source (Gaussian noise, a mask, or a paired input) and the data.
  2. Choose the path: start with the linear one, then try another scheduler.
  3. Choose the coupling: independent first, minibatch matching if few steps matter.
  4. Choose the prediction: velocity, x1, noise or score; convert with Table 1.
  5. Train by regression on a single example’s arrow. Watch samples, not only the loss.
  6. Sample with an ODE solver. Compare 1, 4 and 16 steps and Euler against midpoint.
  7. Add a label with dropout to ∅; set w small and check variety.
  8. Change the space only if you must: tokens, manifolds, or several modalities.

The core as code

The paper’s Code 4 uses its flow_matching library. The whole training loop and the sampler:

pythonfrom flow_matching.path import AffineProbPath
from flow_matching.path.scheduler import CondOTScheduler
from flow_matching.solver import ODESolver

path = AffineProbPath(scheduler=CondOTScheduler())         # alpha_t = t, sigma_t = 1 - t
for x_0, x_1 in dataloader:                                  # each [B, *data_dim]
    t = torch.rand(batch_size)                              # [B]
    sample = path.sample(t=t, x_0=x_0, x_1=x_1)             # x_t and dx_t, both [B, *data_dim]
    loss = torch.pow(velocity_model(sample.x_t, t) - sample.dx_t, 2).mean()
    optimizer.zero_grad(); loss.backward(); optimizer.step()

solver = ODESolver(velocity_model=velocity_model)
x_0 = torch.randn(batch_size, *data_dim)                    # fresh noise
x_1 = solver.sample(x_init=x_0, method='midpoint', step_size=1.0 / 100)

When something goes wrong

Find the chapter that fixes it

Pick what you see. The read-out names the cause, the number to measure and the fix, with the numbers from this lesson’s devices.

The numbers are from this lesson’s own toy devices (Chapters 4, 5, 6 and 7), which are illustrative, not results from the paper.

Where it sits, and where to go next

This paper is the assigned reading for Lecture 10, Modern Generative AI of MIT MMAI. Earlier in the series, Lecture 9 covers multimodal generation. For the same topic from other angles, see our lessons Flow Matching (MIT 6.S184), Flow Matching (the architecture Gleam) and Diffusion. Read the paper itself for the proofs we skipped: arXiv 2412.06264, with code at github.com/facebookresearch/flow_matching.

Limits worth stating: the guide is a reference, so it offers no benchmark comparison between schedulers or couplings; CFG’s exact sampling distribution is unknown; guidance is harder for rare, complex labels; and the hero’s exact field would memorize a dataset, because it reproduces the examples. A real network generalizes only because it is smooth and finite.

Credit: Flow Matching Guide and Code is by Yaron Lipman, Marton Havasi, Peter Holderrieth, Neta Shaul, Matt Le, Brian Karrer, Ricky T. Q. Chen, David Lopez-Paz, Heli Ben-Hamu and Itai Gat (FAIR at Meta, MIT CSAIL, Weizmann Institute). The words, devices and toy numbers here are ours.

The takeaway. Flow Matching works because a hard target, the velocity of the whole data cloud, is the average of easy targets, the straight line to each single example. Squared-error regression turns that average into training. Everything else in the paper, from schedulers and couplings to guidance, tokens and curved spaces, chooses a different path or a different space and keeps that one idea.

Now press Present or Teach and explain it from memory: why the conditional arrow is X1 − X0, why the blended arrow still gets learned, and why crossing lines cost solver steps. Then go back to the moons at the top, run 1 step and then 32, and explain the difference.

Flow Matching Guide and Code
Read the paper · Lecture 10, Modern Generative AI · ← Back to microLearning