Flow Matching in Latent Space

A 256 by 256 colour picture is 196,608 numbers. Its latent code is 4,096. Teach the flow to draw the small code, and every one of its 89 steps writes 48 times fewer numbers.

Learn how a straight-line flow from noise to data is trained, why the paper runs it on an autoencoder’s code instead of on pixels, and how it adds class labels, masks and a proof.

Pick pixel space or latent space, pick a size, then press Run 89 steps. Watch how many numbers the network must write. Then we build, piece by piece, the straight path, the loss, the autoencoder, the solver, the guidance and the bound.

You need a feel for what a vector is (a list of numbers) and a little calculus (a derivative is a rate of change). We build the rest from zero.

Reading for MIT MMAI, Lecture 10: Modern Generative AI. Paper: Quan Dao, Hao Phung, Binh Nguyen and Anh Tran (VinAI Research and the National University of Singapore), “Flow Matching in Latent Space”, arXiv 2307.08698, 2023. Every idea is re-taught here in our own words and devices; the numbers come from the paper’s text, tables and appendix.

Count the numbers a flow writes

The latent shape is the paper’s: the Stable Diffusion autoencoder shrinks each side by 8 and keeps 4 channels (Section 5). The 89 steps are the paper’s count for its DiT L/2 model on CelebA-HQ 256 with the adaptive solver (Table 1a). The pixel row is plain arithmetic for the same 89 steps, not a measured run. The block’s small cells are a picture of noise turning into an image, not real data.

Chapter 0

Why Pictures Are Too Big to Flow

See why drawing a picture one number at a time is costly, and what the paper changes

Picture a very patient artist. You hand her a sheet of 256 by 256 dots. Each dot has three dials: red, green and blue. Every dial starts at a random setting, so the sheet looks like television static.

Her job is to turn the dials, a little at a time, until a face appears. After each small turn she must look at every dial again. A 256 by 256 sheet has 196,608 dials. That is the work of one step.

This is how a modern image generator draws. It does not paint in one stroke. It starts from noise (numbers drawn at random, with no pattern) and nudges them toward a picture, step by step. A generative model is a program that learned the pattern of a large pile of example images, so that it can make new images that fit the pattern.

Two ways to nudge: diffusion and flow matching

The older method is diffusion. It learns to remove a little noise at each step. It works very well, but the paper says a sample often needs hundreds to thousands of network calls. Each call is one pass of a neural network, a large function with millions of adjustable weights that was fitted to data.

The newer method is flow matching. It learns a velocity: for any point on the way from noise to picture, which direction to move and how fast. The paper says flow matching is easier to train and faster to sample, because its paths bend less. Chapter 1 builds this from scratch.

There was a catch. Every flow matching model before this paper worked on the pixels themselves. The paper calls them “not yet ready for high-resolution image synthesis”. The artist above must turn 196,608 dials at every step, and a 512 by 512 sheet has four times as many.

The idea: sketch first, paint later

Real painters do not place every dot with equal care at the start. They make a small sketch, fix the layout, and add detail late. The paper does the same. A pretrained autoencoder (a network pair that shrinks an image into a short code and expands the code back into an image) already exists. Stable Diffusion uses one.

The paper runs the flow on that short code, which it calls the latent. The word latent means hidden: the code is not a picture you can look at, but it holds what the picture needs. The flow turns noise into a code. The autoencoder’s decoder then paints the code into an image.

Count the savings. The autoencoder in the paper cuts each side of the image by 8 and keeps 4 channels. A 256 by 256 image with 3 colours becomes a 32 by 32 code with 4 channels. That is 32 × 32 × 4 = 4,096 numbers instead of 196,608. The ratio is 196,608 / 4,096 = 48.

Drag the two dials below. The first is the image side. The second is the downsampling factor h, the number of pixels along one side that the encoder folds into one code cell. The paper uses h = 8.

Shrink the picture into a code

Two bars share one scale. Blue is the picture in pixels. Warm is its latent code with 4 channels. Move the factor h to 1 and the code is no smaller at all.

256
8

Plain arithmetic: pixels = side × side × 3, latent = (side / h) × (side / h) × 4. The paper uses h = 8 and 4 latent channels (Section 5). The factors 1, 2, 4 and 16 are for exploring; they are not trained models. The bars use a log scale, so each gridline is ten times the one before.

The ratio is 3h²/4, because the code has 4 channels where the picture has 3. At h = 8 that gives 3 × 64 / 4 = 48. A flow network that writes 48 times fewer numbers per step is cheaper to train and to run. The paper trains each model for 1.3 to 21.6 days on 1 to 8 GPUs (Tables 8 and 9).

The symptom, the measurement, the fix

The symptom: earlier flow matching, in pixels, was costly and had only been shown without any conditions such as a class label. The measurement: in Table 1a, the pixel-space flow matching model (the paper’s reference FM) needs 128 network calls on CelebA-HQ 256 and scores an FID of 7.34. FID (Fréchet inception distance) compares the statistics of generated images with real ones; lower is better.

The fix: the latent model with a DiT network needs 89 calls and scores 5.26. With a UNet called ADM it needs 85 calls and scores 5.82. Both are better and cheaper on this dataset. The latent flow does not win everywhere. On some datasets a latent diffusion model or a GAN still scores better. Chapter 8 shows where.

Latent space is not free. The decoder can only paint what the code can hold. If the autoencoder blurs a detail, no flow can bring it back. Chapter 7 turns that worry into a formula.

What the paper adds

The paper lists three contributions. First, flow matching in the latent space of a pretrained autoencoder, for high-resolution images. Second, conditions: class labels with a new guidance formula, plus image inpainting and semantic-to-image synthesis. Third, a theorem that bounds the distance between the generated and the true image distribution.

The road

  1. The straight path: a line from noise to data, and the velocity along it.
  2. The loss: how a network learns the velocity, and what it really learns.
  3. The latent space: the autoencoder, the shapes, and the reparameterization trick.
  4. Sampling: Euler, Heun and the adaptive solver, with the cost of each.
  5. Guidance: the classifier-free velocity, derived step by step.
  6. Masks and layouts: inpainting and semantic-to-image by channel stacking.
  7. The bound: what the Wasserstein theorem promises.
  8. The results: every table, and the honest gaps.
  9. The field guide: numbers, checklist, code, and where to go next.

This paper is a reading for Lecture 10, Modern Generative AI. If flow matching is new, our Flow Matching lesson is a longer companion; this lesson teaches what it needs inline.

The paper’s autoencoder cuts each side by 8 and keeps 4 channels. How many numbers does a 512 by 512 colour image become?

Chapter 1

The Straight Path From Noise to Data

Draw a straight line from a noise point to a data point and read off a velocity

You stand at a train station called Noise. A friend waits at a station called Picture. A straight track joins the two. You ride at one steady speed and arrive exactly one hour later. At any minute you could say where you are, and which way and how fast you are moving.

That is the whole of flow matching, in one image. A flow moves a point from a starting place to an ending place along a path over time. The paper’s flow starts at a noise point and ends at a data point.

Points, paths and time

A vector is a list of numbers, such as the 4,096 numbers of a latent code, or just two numbers for a point on a page. We write the data point as z0 and the noise point as z1. Time t runs from 0 to 1. The paper puts the data at t = 0 and the noise at t = 1, so a sample is made by running time backwards.

The simplest path is a straight line. Halfway through, you are halfway between the two stations. A quarter of the way from the data end, you are three quarters data and one quarter noise. This is a linear interpolation: a weighted mix of the two end points.

zt
Where the point is at time t. Same shape as z0 and z1.
(1 − t)
The weight on the data end. It is 1 at t = 0 and falls to 0 at t = 1.
z0
The data point. In this paper it is a latent code, 32 × 32 × 4 numbers.
t
The weight on the noise end. It is 0 at t = 0 and rises to 1 at t = 1.
z1
The noise point, drawn at random from a standard normal: every number is an independent bell-curve draw.

This is the paper’s path (Section 3, “constant velocity ODE”). Now ask the key question. How fast does zt move as time passes? Take the derivative. The weight on z0 falls at rate 1 and the weight on z1 rises at rate 1, so:

dzt/dt = z1 − z0

The velocity is the same at every time. It is just the arrow from the data point to the noise point. That is why the paper calls it a constant velocity flow.

A worked example, every step

Use a page with two numbers per point. Let z0 = (2, 1) and z1 = (−1, 3). At t = 0.25 the weights are 0.75 and 0.25. The first number is 0.75 × 2 + 0.25 × (−1) = 1.25. The second is 0.75 × 1 + 0.25 × 3 = 1.5. So z0.25 = (1.25, 1.5).

The velocity is z1 − z0 = (−1 − 2, 3 − 1) = (−3, 2). Check it. Move 0.25 further in time: (1.25, 1.5) + 0.25 × (−3, 2) = (0.5, 2). The formula at t = 0.5 gives 0.5 × (2, 1) + 0.5 × (−1, 3) = (0.5, 2). They agree.

An ODE says: here is the speed, everywhere

A network will not know which pair of end points a point belongs to. It will only see the point and the time. So we need a rule that gives a velocity for every place and time. Such a rule, written as a derivative equation, is an ordinary differential equation (ODE):

dxt
A tiny move of the point during a tiny time dt.
v
The velocity field: a function that returns an arrow for any place and time. Section 3 of the paper, Equation 1.
xt
Where the point is now.
t
What time it is.

To make a sample, start at noise (t = 1) and follow the arrows backwards in time to t = 0. If you know v, you can do this on a computer by taking many small steps. Chapter 4 shows how.

Why straight beats bent

Diffusion models use a different path. The paper writes it as xt = αt x0 + (1 − αt2)1/2 x1, the variance preserving path. The two weights always satisfy α2 + (weight)2 = 1, so the point swings along an arc.

An arc has changing direction. A solver that walks in a straight step along a changing direction falls off the track. A straight path has one direction, so a single large step is exact. The paper cites this lower curvature (how fast a path turns) as the reason flow matching samples faster.

Try it. Drag the two end points. Slide the time. Then compare where one big step from the noise end lands on each path.

Take one big step from noise

Blue is data z0, purple is noise z1. Drag either dot. Warm marks the straight path and its velocity arrow; grey marks the curved path. The crosses show where one step from noise lands.

0.50

The straight path is the paper’s. The curved path is an illustration of a variance preserving style path with αt = cos(πt/2); the paper writes the general form in Equation 6. Points are toy 2D numbers, not images.

The cross on the warm path always sits on the data point. The cross on the grey path never does, unless the two end points line up with the origin. This is the geometric reason for the paper’s choice.

A data point is z0 = (2, 1) and a noise point is z1 = (−1, 3). What is the constant velocity z1 − z0 of the straight path?

Chapter 2

Teaching a Network the Average Velocity

Train a network to guess the velocity, and see what it really learns

You drive to a crossroads at noon. Cars arrive from many roads, and each driver is headed for a different city. A signpost stands in the middle. It can show only one arrow. Which arrow should it show?

The signpost cannot know where one particular car is going. It sees only where you stand and what time it is. The best it can do is point along the average direction of all the cars that could be standing there.

A flow matching network is that signpost. It receives a point zt and a time t. It does not know which data point the point came from, nor which noise point. Many different pairs of end points have paths that cross at the same spot, each with its own velocity.

The loss: guess the arrow, square the miss

In training we know the answer for the pair we made. The target arrow is z1 − z0. The network vθ (the θ stands for all its weights) makes a guess. The loss is a score for how wrong the guess is. Here it is the squared error: subtract, square each number, add them up.

L(θ)
The loss, a single number. Training tries to make it small. This is Equation 8 of the paper.
Et, zt
Average over many random times t and many random points zt built from random data and noise pairs.
z1 − z0
The target: the straight-path velocity of the pair we made.
vθ(zt, t)
The network’s guess. It sees only the point and the time. It has the same shape as zt: 4 × 32 × 32.

Take the worked pair from Chapter 1: z0 = (2, 1), z1 = (−1, 3), t = 0.25, so zt = (1.25, 1.5) and the target is (−3, 2). Say the network guesses (−2, 1.5). The miss is (−3 − (−2), 2 − 1.5) = (−1, 0.5). Squares: 1 and 0.25. The loss for this pair is 1.25.

Training lowers the average of this number. Notice what is missing. Training never runs the flow forward. The paper calls this simulation-free: older continuous flow methods had to solve an ODE at every training step, which the paper says made them too costly to scale.

One training step, with shapes

This is the paper’s Algorithm 1, written as data flow. The autoencoder is already trained and frozen. Only the flow network learns.

python# one training step; B = batch size (112 for ADM on CelebA 256, 32 for DiT-L/2: Tables 8, 9)
x0 = next(batch)                         # (B, 3, 256, 256)  real images
with torch.no_grad(): z0 = vae.encode(x0)   # (B, 4, 32, 32)    latent codes, encoder frozen
z1 = torch.randn_like(z0)                # (B, 4, 32, 32)    noise
t  = torch.rand(B, 1, 1, 1)              # (B, 1, 1, 1)      one random time per image
zt = (1 - t) * z0 + t * z1               # (B, 4, 32, 32)    a point on the straight path
v  = net(zt, t.flatten())                # (B, 4, 32, 32)    the network's guessed velocity
loss = ((z1 - z0 - v) ** 2).mean()       # one number (the paper writes a sum; code usually averages)
loss.backward(); opt.step()              # Adam or AdamW; lr 5e-5 (ADM), 2e-4 to 1e-4 (DiT)

Each image gets its own random t. A single forward pass gives a single gradient. There is no loop over solver steps in training.

What the signpost really learns

Here is why the average appears. Fix one point z and one time t. Many pairs give a target u = z1 − z0 there. The network can output only one arrow v. The expected squared miss is E‖u − v‖². Its slope in v is −2(E[u] − v). The slope is zero when v = E[u].

So the best arrow is the average target at that point and time. For our straight paths there is a neat form. Since zt = (1 − t)z0 + t z1, we get z1 − z0 = (zt − z0)/t. Average over the data points that could have produced zt, and the best arrow is:

v*(z, t) = (z − m) / t, where m is the average data point that could have led to z at time t

In words: point away from the average source. Our toy below has eight round blobs of data, so m is easy to compute, and v* is exact. It stands in for a trained network.

Open up the signpost

Eight blue blobs are the data. Faint warm arrows are the best velocity everywhere at time t. Click or drag on the plane to place the probe: the thin pink arrows are the straight-line arrows from each blob, thicker for blobs that are more likely, and the bold warm arrow is their average.

0.60

Toy: 8 round Gaussian blobs of spread 0.3 on a ring of radius 1.6, standard normal noise, the paper’s straight path. The arrows are the exact best velocity for this data, from the formula above, not a trained network. The unavoidable miss shown is the part caused by different blobs: the weighted average squared distance between each blob’s arrow and the average arrow.

Slide t toward 1. The probe sits in pure noise, almost every blob is equally likely, and the average arrow just points away from the centre of the ring. Slide toward 0.1. One blob wins, and the arrow aims straight at it.

Symptom, measurement, fix

The symptom: you train a flow network and the loss curve flattens at a value well above zero. It looks like failure. The measurement: look at the unavoidable miss in the device. Even the perfect arrow differs from each blob’s own arrow, so the squared miss cannot reach zero. The floor is the spread of the targets.

The fix is to stop reading the loss as the score. The loss shows that training is moving. The quality of the samples is measured by FID after sampling (Chapter 8). The paper trains for 500 to 1,200 epochs, and judges the model by FID and recall, not by the loss.

At one point and time, three pairs give target arrows (1, 0), (3, 0) and (2, 3). What single arrow minimises the average squared miss?

Chapter 3

Moving the Flow Into the Latent Space

Compress each image with a pretrained autoencoder and run the flow on the code

You want to tell a friend about a painting over the phone. You do not read out every dot of paint. You say “a red barn, a grey sky, three cows on the left”. Your friend rebuilds the picture in their mind. Some fine detail is lost, but the layout and the objects survive.

An autoencoder does the same job with numbers. It is a pair of networks. The encoder E reads an image and writes a short code. The decoder D reads the code and paints an image back. They are trained together until D(E(x)) looks like x.

The paper’s autoencoder: a VAE from Stable Diffusion

The paper does not train its own autoencoder. It reuses the pretrained one from Stable Diffusion, a variational autoencoder (VAE) with a KL penalty. The penalty is an extra training term that keeps the codes close to a standard bell curve, so the code values stay well behaved.

A VAE does not write one code per image. The encoder writes two things: a mean μφ(x) and a spread σφ(x). The code is then drawn around that mean. The paper writes the draw like this (Equation 18):

z
The latent code that goes to the flow. Shape 4 × 32 × 32 for a 256 by 256 image.
μφ(x)
The mean the encoder writes: its best single guess for the code.
η
A fresh random draw, the same shape as z. It is the only random part.
σφ(x)
The spread the encoder writes: how much room the code has to wiggle. The small circle means multiply number by number.
N(0, I)
A standard bell curve on every number, independent of the others.

Why write it this way? A random draw blocks the flow of gradients in training. Moving the randomness into η, which has no weights, leaves μ and σ as plain functions, so gradients can pass through them. This is the reparameterization trick. It matters for training the VAE. The paper needs it for the theory in Chapter 7.

The shapes, end to end

The encoder has a downsampling factor of 8. An RGB image x with height h and width w becomes a code with shape (h/8) × (w/8) × 4. The paper puts it plainly: all experiments run in this latent space.

Take one batch at 256 by 256 with batch size 112, the ADM setting on CelebA-HQ. The images are 112 × 3 × 256 × 256 = 22,020,096 numbers. In 32-bit floats, that is about 88 million bytes. The codes are 112 × 4 × 32 × 32 = 458,752 numbers, about 1.8 million bytes. Every tensor the flow network handles is 48 times smaller.

At sampling time the path reverses. Draw noise z1 with shape 4 × 32 × 32. Run the flow to a code ẑ0, same shape. Pass it through the decoder D. Out comes an image with shape 3 × 256 × 256. The decoder runs once, not at every step.

Both flow networks the paper tests take these small codes as input. DiT L/2 has 457 million weights and costs 80.74 GFLOPs per call (Table 6). ADM costs 28.9 GFLOPs per call on 256 by 256 data (Table 7). A FLOP is one multiplication or addition. A GFLOP is a billion of them.

Now see what the squeeze costs. The device below uses a toy stand-in for an autoencoder. The encoder averages each h by h block of an image into one number. The decoder fills the blocks back in smoothly. A real VAE learns far better codes. But the toy shows the same trade: a smaller code loses more fine detail.

Squeeze, then paint

Left: a 64 × 64 test image with coarse shapes and fine stripes. Middle: the toy code. Right: the rebuilt image. Raise h and watch the fine stripes vanish first.

Toy: the encoder is a plain block average and the decoder is smooth interpolation, not a trained VAE. The test image is made by a formula, so every visit shows the same picture. The error is the root mean squared difference on a 0 to 255 brightness scale, measured live.

The coarse disc and the soft gradient survive every setting. The thin stripes are gone by h = 4 or h = 8. A trained VAE keeps far more than this toy, but it still cannot keep everything.

Symptom, measurement, fix

The symptom: generated faces look a little soft, and hair or fabric loses texture. The measurement: encode a real image, decode it right away, and compare. No flow is involved. The error you see is the floor for every generated image.

The fix is a better autoencoder, not a better flow. The paper points the same way. Its bound in Chapter 7 contains a term that depends only on the encoder and the decoder, and it points to earlier latent diffusion work that also stresses the choice of a good VAE.

A trained latent flow model scores a high FID, and the team suspects the problem is in the autoencoder. Which quick test isolates the autoencoder?

Chapter 4

Solving the Flow Backwards

Walk from noise to a latent code with an ODE solver, and count the cost

You hike across a foggy hill with a compass and no map. You read the compass, walk ten paces in that direction, and read it again. On a gentle slope you can take long strides. On a winding ridge you must take short ones, or you walk off the edge.

Making an image from a trained flow is the same walk. The network is the compass: for any place and time it gives the velocity. You start at noise, take a step, ask again, and repeat until time reaches 0. Walking an ODE this way is called numerical integration, and the program that does it is a solver.

The simplest walk: Euler

The Euler solver trusts the compass completely for one whole step. Cut time into N equal steps, with tn = n/N. Start from noise at tN = 1 and move backwards. The paper’s Algorithm 2 is this update:

ztn
The point after this step, one notch closer to the data.
ztn+1
The point before this step.
(tn − tn+1)
The step length in time. It is −1/N, a negative number, because time runs backwards.
vθ(…)
One call of the network. Same shape as the point: 4 × 32 × 32.

Each step costs one network call. The count of calls is the number of function evaluations, or NFE. It is the number to watch, because it sets the time to make an image. With DiT L/2 at 80.74 GFLOPs per call (Table 6), 89 calls cost about 89 × 80.74 = 7,186 GFLOPs, or 7.2 trillion operations, for one latent.

Bending with the path: Heun and adaptive steps

Euler trusts the compass at the start of a step. If the path turns inside the step, it misses. The Heun solver fixes that with a second look. It makes the Euler move to a trial point, asks the network again there, and walks with the average of the two arrows. That is two network calls per step, but each step is more accurate.

An adaptive solver goes further. It chooses its own step size as it goes. It makes two estimates of different accuracy, compares them, and shortens the step when they disagree. The paper uses dopri5, the Dormand and Prince method of order 5. The paper found it gave results comparable to Heun, and kept it as the default for all main experiments “for the sake of simplicity”.

Table 4 compares the three on CelebA-HQ 256 with the DiT network:

SolverNFE listedFID (lower is better)Time per image
Adaptive (dopri5)895.261.70 s
Euler905.511.78 s
Heun505.261.83 s

Look at the times. Euler makes 90 calls in 1.78 s, about 0.020 s per call. Heun is listed with 50 and takes 1.83 s. That is close to the time of 90 Euler calls. A Heun step makes two calls, so the listed 50 probably means 50 steps and about 100 calls. The paper does not say how it counts, so this is our reading. It also matches the text: Heun is “slightly slower” because of “an additional one-step forward”. The honest summary is that Heun buys a better FID, 5.26 against 5.51, for about the same time.

Appendix B and Figure 5 repeat the test with many step counts. Heun gets the better FID at every count, and Euler is a little faster per image. Now try the same race in a toy where we can measure the error exactly.

Race the solvers

Purple dots are 64 noise points. Solid dots are where the chosen solver ends. Hollow blue rings are where a 2,000-step Euler run ends. Drag the budget of network calls and compare the two solvers on the curve.

6

Toy: the exact best velocity for 8 round blobs (Chapter 2) in place of a network, so the only error is the solver’s. Error is the mean distance between the solver’s end point and the end point of a 2,000-step Euler run from the same noise, over 64 fixed noise points. Heun with s steps uses 2s − 1 calls: the last step is Euler, because the field has no value at t = 0.

With one call, every sample lands at the same blurry place: the centre of the ring, the average of all the data. With a handful of calls the samples find their blobs. The curve for Heun drops faster, which is what a second-order method promises.

Symptom, measurement, fix

The symptom: samples look like soft averages, or two objects merge. The measurement: lower the step count and watch FID rise, or, as in the toy, plot the end-point error against NFE. The error falls steeply, then flattens. The fix: spend calls where the curve is still steep, or switch to a higher-order or adaptive solver. After the elbow, extra calls buy almost nothing.

A Heun run makes 25 steps, and its last step is a plain Euler step. How many network calls does it make?

Chapter 5

Steering With Class Labels

Add a class label and a guidance dial, and derive why one formula works

You are a tour guide with two maps. One shows the whole city. The other shows only the old harbour district, where your group wants to go. If you follow the harbour map alone, you still pass through some streets that could be anywhere in the city. A smarter guide asks: what does the harbour map say that the city map does not? Then she leans extra hard in that direction.

This is classifier-free guidance. The model runs twice at each step, once knowing the wanted class and once not knowing it. The step follows the difference between the two answers, stretched by a dial.

Adding a label to the network

A condition c is extra information about what to draw. For ImageNet it is a class label such as “macaw”, one of 1,000 classes. The change to the loss is small. The network receives c next to the point and the time (Equation 9):

L(θ) = E ‖ z1 − z0 − vθ(zt, c, t) ‖2

The paper adds one trick, in Algorithm 3. With some probability pu, it replaces the label with an empty token ∅ before the network sees it. One network then learns two jobs: a velocity for each class, and a velocity with no class at all. The paper compares this to dropout, a standard way to hide parts of the input at random during training.

The older route: a separate classifier

Before this paper, the standard way to steer diffusion was classifier guidance. You train a second network that tells which class a noisy image belongs to. Its gradient pushes each step toward the class. The paper points out two costs: an extra network to train, and a classifier that must work on the noisy path points, not just on clean images.

Deriving the classifier-free velocity

The paper starts from the link between a flow and a diffusion process. Any flow can be written as v = f − (g²/2) ∇ log pt. Here f and g are the drift and noise strength of the matching diffusion, and ∇ log pt is the score: the direction in which a point becomes more likely. Follow the derivation in four short steps.

  1. Check the link on our path. For zt = (1 − t)z0 + t z1, the point is a bell curve around (1 − t)z0 with spread t. Its score is −(zt − (1 − t)z0)/t². The paper gives f = −zt/(1 − t) and g²/2 = t/(1 − t). Insert them: the velocity becomes (zt − z0)/t, which equals z1 − z0. The formula and our straight path agree.
  2. Add the class. Bayes’ rule says the score of the class-conditioned density is the score plus ∇ log p(c | zt): how much a small move raises the chance of class c. So the guided velocity is v − γ (t/(1 − t)) ∇ log p(c | zt). The dial γ scales it (Equation 14).
  3. Swap the classifier for two velocities. By Bayes again, ∇ log p(c | zt) = ∇ log p(zt | c) − ∇ log p(zt). Multiply both sides by g²/2 and use step 1’s link: (g²/2)(∇ log p(zt | c) − ∇ log p(zt)) = v∅ − vc, where vc is the velocity with the class and v∅ the one without. The drift f cancels.
  4. Substitute. The guided velocity is v∅ − γ(v∅ − vc), which rearranges to the line below (Equation 17). The paper marks this step “≈”, since both velocities come from one trained network.
ṽ
The velocity the solver actually follows. Same shape as the code: 4 × 32 × 32.
v∅
The network’s answer with the label blanked: the city map.
γ
The guidance dial. γ = 0 ignores the label. γ = 1 is the plain conditional model. Above 1 over-shoots toward the class.
vc
The network’s answer with the label: the harbour map.
v∅
The same blank-label answer, subtracted to leave only what the label adds.

Sampling (Algorithm 4) is Euler with this velocity. At each step it calls the network twice, with c and with ∅, blends the two answers and steps. In practice both calls go in one batch. The guided model costs about twice the calls of the plain one.

One check on the sign. Sampling moves backwards in time, so the step is z − (1/N)ṽ. A bigger γ gives a bigger pull along vc − v∅, which points toward what the class adds. The paper’s results use γ between 1.25 and 1.5 for scores, and 1.5 to 4.0 for pictures (Appendix D.2).

Feel the dial

The toy below has two classes. Class A is three blobs on the left. Class B is three blobs on the right. One shared blob in the middle belongs to both classes. Both velocities are exact for this data, so what you see is the formula itself.

Turn the guidance dial

Ask for class A. Each dot is one sample. Green dots land on a class A blob, grey dots on the shared blob, red dots on class B or off the data. Drag γ and watch the bar under the plane.

1.00

Toy: 200 samples, 60 Euler steps, round blobs of spread 0.3. vc is the exact best velocity for the class A data (three blobs plus the shared one), v∅ for all data, so they are exact stand-ins for a trained network. “On a blob” means within 0.9 of its centre. This illustrates the formula; it is not the paper’s ImageNet model.

At γ = 0 the label is ignored and many samples land on class B. At γ = 1 no sample lands on class B, but about a third land on the shared blob, which could be either class. A dial of 3 pushes nearly all samples onto the three blobs that are clearly class A. At 8 the push is too strong and some samples are flung off the data.

Symptom, measurement, fix

The symptom: a class-conditional model gives vague images, half way between classes. The measurement: on ImageNet, DiT B/2 scores an FID of 20.38 with γ = 1. The fix: guidance. At γ = 1.25 the FID is 8.77, and at 1.5 it is 4.46 (Table 3a). The price shows in recall, a measure of how much of the real variety the model covers: it falls from 0.56 to 0.48 and then to 0.42. Guidance trades variety for fidelity.

At one step the network answers vc = (4, 2) with the label and v∅ = (2, 2) without it. With γ = 1.5, what velocity does the solver follow?

Chapter 6

Masks and Layouts by Stacking

Feed an inpainting mask or a semantic layout in as extra channels

A restorer receives a torn photograph. If she gets only the damaged print, she does not know which edges are torn and which are part of the picture. So the client also hands over a second sheet: a black and white map that marks the hole. With the photo and the map side by side, she knows where to paint and what to match.

The paper treats image conditions the same way. It does not invent a new network part. It lays the extra sheets on top of the latent, like layers in a sandwich, and lets the first layer of the network read them all.

Channels: the layers of a tensor

A channel is one grid of numbers, one number for every position. A colour photo has 3 channels: red, green and blue. The latent code has 4. A tensor is a stack of such grids, such as 4 × 32 × 32. To concatenate tensors is to stack them along the channel axis, so a 4-channel and a 1-channel grid make a 5-channel one. The grids must share height and width.

That last rule explains the paper’s resizing steps. Every condition must first be shrunk to 32 × 32, the size of the latent, so it can join the stack.

Inpainting: fill the hole

Inpainting means filling a missing region of an image with fitting content. The input is a masked image xm (the picture with the hole blanked out) and a mask m (white where pixels are missing). The recipe, from Section 5.2, has four moves:

  1. Encode the masked picture. The frozen encoder turns xm into zm, shape 4 × 32 × 32.
  2. Shrink the mask. Resize m to the latent size. The paper calls the result ⁿm, shape 1 × 32 × 32.
  3. Stack. The network input is concat[zt, zm, ⁿm], which has 4 + 4 + 1 = 9 channels.
  4. Predict as usual. The output is still a velocity with 4 channels. The loss is the same squared error as before.

During sampling only zt changes. The other five channels stay fixed at every step, and the network sees them again each time. They tell it which latent cells to fill and what surrounds them. The paper calls this “a very simple concatenation trick”. It trains and tests on CelebA-HQ 256 with the protocol of the MAT paper: 24,183 images to train and 2,993 to evaluate.

Semantic to image: paint by layout

In semantic-to-image synthesis you give a layout: a map that says which region is hair, skin, eyes, background, and so on. The network must paint a photo that fits it. The layout m has C classes. It is stored as a one-hot grid: C channels, and at each position exactly one channel is 1 and the others are 0.

A C-channel stack is too wide to join the 4-channel latent directly. The paper adds a small learned network ωφ that squeezes the layout from C channels down to 4. The output mc has the same shape as zt. The flow network then reads concat[zt, mc], which has 8 channels. The squeezing network ωφ is trained together with the flow network (Section 5.2).

Step through both stacks below. Pick a task, and shrink or grow the hole or the class count, to see how the input tensor changes.

Build the input sandwich

Pick a task. Slabs on the left are stacked into one input; the network box turns them into a 4-channel velocity. Move the slider to change the hole or the number of layout classes.

50%

Channel counts and the 32 × 32 latent size are the paper’s (Section 5.2, 256 by 256 images). The hole is a centred square, an illustration; the paper follows the mask protocol of MAT. The paper does not state C for its CelebA-HQ layouts in the text we use, so the slider is an exploration, starting at an illustrative 19. The slab patterns are pictures of noise, image and mask, not real data.

Notice how little changes. The network’s output stays 4 channels at 32 × 32. Only its first layer is wider, because it reads 9 or 8 channels where it read 4.

What the tables say

For inpainting, Table 3c lists FID, P-IDS and U-IDS. The last two are higher-is-better scores of how often a trained classifier cannot tell the result from a real image. The paper’s model scores FID 4.09, P-IDS 13.25 and U-IDS 21.59. MAT, built for this task, gets 2.94, 20.88 and 32.01. LaMa gets 3.98, 8.82 and 22.57. So the paper beats ICT (5.24), MADF (10.43), DeepFill v2 (5.69) and EdgeConnect (5.24) on FID. It trails MAT on all three scores and LaMa slightly on FID and U-IDS.

For layouts, Table 3b gives an FID of 26.3. That beats Pix2PixHD (38.5), SPADE (29.2), DAGAN (29.1) and CLADE (30.6). It trails SCGAN (20.8) and SDM (18.8). The paper names the special techniques they use: saliency guidance for SCGAN, and a special normalisation plus classifier-free guidance for SDM.

Symptom, measurement, fix

The symptom: the filled area ignores the surroundings, so colours or edges jump at the border. The measurement: check that the mask channel is really reaching the network and has the right size. A mask left at full image size cannot be stacked and will crash, and a mask resized with a smooth filter blurs the border cells. The fix: resize the mask to 32 × 32 with a nearest-cell rule so each latent cell is clearly inside or outside the hole. (The paper only says the mask is “resized”; the nearest-cell choice is ours.)

For inpainting the network receives zt (4 channels), the encoded masked image zm (4 channels) and the resized mask (1 channel). How many input channels does the first layer read, and how many channels does the output velocity have?

Chapter 7

What the Bound Promises

Read the Wasserstein bound and see why the autoencoder sets a floor

You photocopy a family photo and give the copy to a friend. She then redraws it by hand from a trace of its outline. The final drawing differs from the original for two reasons. The photocopy already lost some detail. And her hand slipped while tracing, more on a wobbly line than on a smooth one.

You can add the two errors. The copy’s loss is a fixed floor. The tracing error can shrink with practice, but a wobbly line makes any slip bigger. The paper’s theorem says the same about its pipeline.

A distance between two piles

The theorem needs a way to say how far the generated images are from the real ones, as whole collections. The paper uses the 2-Wasserstein distance. Picture two piles of sand with different shapes. The distance is the cheapest cost to reshape one pile into the other, where moving a grain costs the square of the distance it travels. The paper’s Equation 21 writes it for squared distance:

W22(α, β)
The squared distance between pile α and pile β. It is 0 only if they are the same pile.
π
A moving plan: a rule that says which grain of α goes to which place in β. The minimum picks the cheapest plan.
‖x − y‖2
The squared distance one grain travels.

This is the same kind of distance that FID measures, between two bell curves fitted to image features. The paper says the quantity it bounds “coincides with” FID.

The theorem in plain words

Let p0 be the real image distribution and p̂0 the distribution of images the pipeline makes. Theorem 4.1 (Equation 20) says:

W22(p0, p̂0)
How far the generated images are from real ones, as piles.
‖Δ‖2
The reconstruction floor. Δ is the gap between a real image and its autoencoder rebuild. It depends only on the encoder and the decoder. The paper assumes it is bounded.
Lg
The decoder’s Lipschitz constant: a speed limit. If two codes are d apart, their decoded images are at most Lg × d apart. A decoder with a small Lg does not magnify code errors.
e1+2L̂
An amplifier set by L̂, the Lipschitz constant of the learned velocity in z: how fast it can change from place to place. A smoother field has smaller L̂ and a smaller amplifier.
∫∫ |v − v̂|2 dqt dt
The flow matching error: the squared gap between the true latent velocity v and the learned v̂, averaged over time and over where codes lie. This is what training lowers.

Read it as two budgets. The first is a floor that no flow can remove. The second grows with the flow error, and it is multiplied by two constants that describe how well-behaved the decoder and the velocity field are.

Why it holds, in three moves

  1. Split. A decoded real code differs from the real image by Δ. Write the distance between piles as the Δ term plus the distance between decoded real codes and decoded generated codes (Equations 24 to 26).
  2. Pass through the decoder. If the decoder obeys the speed limit Lg, a distance between decoded piles is at most Lg2 times the distance between the code piles (the step just before Equation 27).
  3. Bound the code piles. A result from the stochastic interpolants paper (Proposition A.2 here) says the distance between true and learned flows is at most e1+2L̂ times the integrated velocity error (Equation 23). Put the three together and you have Equation 20.

Now play with the three budgets. The numbers are made up, so you can see how the parts trade.

Move the bound

Three bars on a log scale: the floor, the flow term and the total bound. Change the autoencoder (floor and decoder speed limit) or the flow (smoothness and error), and watch which bar moves.

0.04
1.5
0.5
0.02

Illustrative values only. The paper proves the bound but does not measure these constants for its models. Slider values are the quantities of Equation 20: floor = ‖Δ‖², flow term = Lg² e1+2L̂ × (flow error). Floors from 0 to 0.20, Lg from 0.5 to 3.0, L̂ from 0 to 2.0, flow error from 0 to 0.10.

Push the flow error to zero. The flow bar vanishes and the total sits on the floor. Only a better autoencoder lowers the floor. Now raise L̂ and watch the flow term grow with an exponential: a bumpy velocity field makes the same error far more costly.

What the bound does not say

The bound is an upper limit, and it can be loose. The amplifier e1+2L̂ is already about 20 at L̂ = 1. The paper does not estimate L̂, Lg or Δ for its trained models. It needs assumptions: the learned velocity must be smooth and Lipschitz, the decoder must be Lipschitz and deterministic, and the reconstruction gap must be bounded.

What it does give is a clear reading. The paper concludes that quality in latent flow depends on the encoder and decoder through constants, and that this reflects the speed-versus-quality trade that earlier latent diffusion work also found.

A team trains its flow until the flow matching error is nearly zero, but its generated faces still miss fine detail. According to the bound, what limits them?

Chapter 8

Reading the Tables

Read every main table, and see what the paper wins and what it does not

You open a sports page and see a table of scores. Before you can say who won, you need to know three things. Is a high number good or bad? Did every team play under the same rules? And which numbers did the reporter measure herself?

A results table in a paper is the same. This chapter first teaches the columns. Then it walks every main table and figure, says what each one shows, and says where the paper does not win.

The columns

FID (Fréchet inception distance) compares generated and real images. Both sets go through a fixed image-recognition network. FID measures how far apart the two clouds of features are. Lower is better.

Recall asks a different question: how much of the variety in the real images do the generated ones cover? Higher is better. A model that draws only a few good faces gets a low recall. NFE is the number of network calls per sample (Chapter 4). Time is seconds per image. Values marked with a star were measured by the authors on their own machine, so the other rows come from other papers and other hardware.

Unconditional images (Tables 1 and 2)

Table 1a opens with CelebA-HQ at 256 by 256. The latent flow with DiT L/2 scores an FID of 5.26 with 89 calls in 1.70 s. With ADM it scores 5.82 with 85 calls. The earlier pixel-space flow matching, which the authors ran themselves, scores 7.34 with 128 calls. So the latent move helps on both quality and cost. The latent diffusion model LDM scores 5.11 with 50 calls, a little better in FID and cheaper in calls.

At 512 by 512 the ADM version scores 6.35 with 94 calls, against 6.40 for WaveDiff and 8.43 for DDGAN. Those two use just 2 calls each. On FFHQ (Table 1b) the DiT version scores 4.55 and LDM scores 4.98. The GANs ProjectedGAN and StyleGAN use a single call and score 3.08 and 4.16.

Table 2 covers two LSUN scenes. On Church, DiT gets 5.54 and ADM gets 7.7, against 10.54 for pixel-space flow matching. LDM gets 4.02, and several GANs do better still. On Bedroom, DiT gets 4.92 and LDM gets 2.95. The paper words its claim carefully: “comparable results”, not best results. In every unconditional comparison the DiT backbone beats the ADM backbone.

Look at the scoreboard yourself. Pick a dataset and see where the paper’s rows land.

Read the scoreboard

Pick a dataset. Bars are the FID values printed in the paper’s tables, shortest is best. Warm bars are this paper’s rows. Grey bars are other methods as the paper lists them.

Every value is copied from Tables 1, 2, 3a and 5 of the paper (FID, lower is better). Rows with a star in the paper were measured on the authors’ machine; the others come from the cited papers, so the settings differ. NFE appears only where the paper lists it. ImageNet rows use the class-conditional setting; “cfg” is the guidance dial γ of Chapter 5, and the figure after “M” is the model’s size in millions of weights.

Conditional tasks (Table 3 and Table 5)

ImageNet is where guidance shows its force (Chapter 5). DiT B/2 goes from FID 20.38 to 8.77 at γ = 1.25 and to 4.46 at γ = 1.5, with 130 million weights. The paper says its small network beats the larger LDM-8-G, which scores 7.76 with 506 million. That holds at γ = 1.5; at 1.25 the score of 8.77 is still behind. But Table 5 also lists LDM-4-G at 3.60 and DiT-XL/2-G at 3.22. The paper says it could not train DiT L/2 or XL/2 on ImageNet for lack of resources, so the best DiT scores are out of reach for this comparison.

Chapter 6 gave the inpainting and layout rows. In short, the paper is competitive on inpainting (FID 4.09 against MAT’s 2.94) and middling on layout (26.3 against SDM’s 18.8).

Ablations and figures

The only true ablation in the main text is the solver study (Table 4 and Figure 5, Chapter 4). Guidance is ablated by sweeping γ (Table 3a). The text we read has no study of the autoencoder, the factor h, or the probability pu of blanking the label. That gap matters, because Chapter 7 says the autoencoder sets a floor.

Figure 1 is the pipeline: encode, flow, decode. Figures 2 and 3 show samples from each dataset, plus CelebA-HQ at 512. Figure 4 shows the layout and inpainting results against the ground truth. Figure 5 plots FID and time against step count for Euler and Heun. Figures 6 to 10 in the appendix are non-curated, meaning not hand-picked. Figures 11 to 20 show ImageNet classes at guidance scales of 4.0, 2.0 and 1.5. Pictures only show what a model can do. They do not show how often it fails.

Training cost and limits

The paper trains on small hardware. ADM on CelebA-HQ 256 took 1.3 days on 2 GPUs (batch 112, 600 epochs). ADM on FFHQ took 4.4 days on 1 GPU. DiT L/2 on CelebA took 5.8 days on 1 GPU (Tables 8 and 9).

The paper names two limits itself: a risk of spreading false images, and the greenhouse gases of training. We add four more from the tables. It stops at 512 pixels. It never scales DiT beyond B/2 on ImageNet. It has no text prompts. And each image takes 1.7 to 5.4 s and dozens of network calls, where a GAN takes one.

Symptom, measurement, fix

The symptom: you read “best FID” in an abstract and expect a table full of wins. The measurement: sort the rows, as the device does, and note the NFE and the source of each row. The fix: state the claim you can support. Here that is “better than pixel-space flow matching, and in the range of latent diffusion and GANs”, not “state of the art”.

On ImageNet, DiT B/2 with guidance 1.5 scores an FID of 4.46 and a recall of 0.42, against 20.38 and 0.56 with guidance 1. What does this pair of results show?

Chapter 9

The Field Guide

Keep the numbers, the checklist, the core code and the way onward

The one-paragraph summary

Flow matching teaches a network the velocity of a straight path from a noise point z1 to a data point z0, by squared error against z1 − z0, with no ODE solved during training. The paper runs this on the latent code of a frozen Stable Diffusion autoencoder, shape 4 × 32 × 32 for a 256 by 256 image, which is 48 times fewer numbers than the pixels. Sampling starts at noise and walks the ODE backwards with an Euler, Heun or adaptive solver, then decodes once. It adds a label with classifier-free velocity guidance, ṽ = v∅ + γ(vc − v∅), derived from the link between a flow and a score. Masks and layouts join as stacked channels. A theorem bounds the Wasserstein-2 distance by an autoencoder floor plus an amplified flow error. Results beat pixel-space flow matching and sit in the range of latent diffusion and GANs.

The numbers that matter

WhatNumberWhy it matters
Latent size, 256 × 2564 × 32 × 32 = 4,096, against 196,608 pixels48 times fewer numbers per step
Latent size, 512 × 5124 × 64 × 64 = 16,384, against 786,432The same 48 times
Path and targetzt = (1 − t)z0 + t z1; velocity z1 − z0A straight line is solved exactly by one step
CelebA-HQ 256, DiT L/2FID 5.26, 89 calls, 1.70 sBeats pixel flow matching (7.34, 128 calls)
Solvers (Table 4)Adaptive 89 / 5.26; Euler 90 / 5.51; Heun 50 / 5.26Heun matches adaptive at about the same time
ImageNet, DiT B/2 (130M)FID 20.38, then 8.77 (γ = 1.25), then 4.46 (γ = 1.5)Guidance is the biggest single gain
Recall with guidance0.56, then 0.48, then 0.42Fidelity is paid for with variety
Inpainting, CelebA-HQ 256FID 4.09 (MAT 2.94, LaMa 3.98); 9 input channelsA concatenation trick is competitive
Layout to imageFID 26.3 (SDM 18.8, SCGAN 20.8); 8 input channelsMiddle of the pack
Networks (Tables 6, 7)DiT L/2 457M, 80.74 GFLOPs; DiT B/2 130M, 23.01; ADM 368M, 28.9Cost per call
Training time (Tables 8, 9)ADM CelebA 256: 1.3 days, 2 GPUs; DiT L/2: 5.8 days, 1 GPUFits small hardware
The boundW22 ≤ ‖Δ‖2 + Lg2 e1+2L̂ × (flow error)The autoencoder sets a floor

A checklist to rebuild it

  1. Load a pretrained KL autoencoder and freeze it. Check that a 256 by 256 image gives a 4 × 32 × 32 code.
  2. Pick a velocity network: ADM (a UNet) or DiT. Give it the point, the time and, for labels, a class input with a blank token.
  3. Train with Algorithm 1: random time, noise, straight-path point, squared error to z1 − z0. For labels, blank the label with probability pu.
  4. Judge by samples and FID after sampling, not by the loss, which cannot reach zero.
  5. Sample from t = 1 to 0 with an ODE solver. Count calls, and remember guidance doubles them per step.
  6. Sweep γ (the paper reports 1.25 and 1.5), and track FID and recall together.
  7. Decode once with the frozen decoder.
  8. For masks or layouts, resize to the latent grid and stack as channels; widen the first layer.
  9. Measure the autoencoder alone, with no flow, to know the floor.

The core, as code

This is a sketch of Algorithms 1, 3 and 4 in PyTorch style. vae, net and opt stand for your own pieces; the null label is a reserved class index.

pythondef train_step(x0, label, p_u):                 # x0: (B, 3, 256, 256), label: (B,)
    with torch.no_grad(): z0 = vae.encode(x0)      # (B, 4, 32, 32), frozen
    z1 = torch.randn_like(z0)                       # noise
    t = torch.rand(z0.size(0), 1, 1, 1)             # t ~ U[0, 1]
    zt = (1 - t) * z0 + t * z1                      # point on the straight path
    drop = torch.rand_like(t.flatten()) < p_u       # blank the label with probability p_u
    label = torch.where(drop, NULL, label)
    loss = ((z1 - z0 - net(zt, t.flatten(), label)) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()

@torch.no_grad()
def sample(label, gamma, N=50):                 # Euler; the paper's default is the adaptive dopri5
    z = torch.randn(label.size(0), 4, 32, 32)       # z at t = 1
    for n in range(N, 0, -1):
        t = torch.full((z.size(0),), n / N)
        vc = net(z, t, label)                        # with the class
        vu = net(z, t, torch.full_like(label, NULL)) # with the blank token
        v = vu + gamma * (vc - vu)                   # Equation 17
        z = z - v / N                                # one step back in time
    return vae.decode(z)                             # (B, 3, 256, 256), decoded once

# inpainting: the network input is nine channels, the output stays four
inp = torch.cat([zt, vae.encode(x_masked), mask_32x32], dim=1)   # (B, 9, 32, 32)

Where this sits

The paper joins three earlier lines. Flow matching and rectified flow supply the straight path (Lipman et al.; Liu et al.). Stochastic interpolants supply the proposition behind the bound (Albergo and Vanden-Eijnden). Latent diffusion and Stable Diffusion supply the autoencoder, and DiT supplies one of the two networks. Classifier-free guidance comes from Ho and Salimans. The new parts are the join, the velocity form of guidance, and the bound.

Keep going

Read this paper next to Lecture 10, Modern Generative AI. For the basics, try Flow Matching, Score Matching and Guidance and Architectures and Latent Space. For the autoencoder side, see VAE and VQ-VAE. For the network, see DiT. For a large system built on flow matching in a latent space, see the Movie Gen reading.

The takeaway. Do the hard work where the picture is small. A straight-line flow is easy to train, a frozen autoencoder shrinks each image by 48 times, and a blank label turns one network into a guide. What remains is a floor set by the autoencoder, and the honest result: better than pixel flow matching, in the range of latent diffusion.
You must re-implement the paper and have time for only one extra experiment that tells you the most about the final quality limit. Which one?

Credit: “Flow Matching in Latent Space” by Quan Dao, Hao Phung, Binh Nguyen and Anh Tran, VinAI Research and the National University of Singapore, arXiv 2307.08698 (2023). The authors’ code is at github.com/VinAIResearch/LFM. This lesson is our own re-telling for the MIT MMAI course follow-along; every figure of merit comes from the paper’s tables and appendix, and the toy devices are labelled illustrative.

Now press Present or Teach and explain the pipeline from memory: why the flow runs on a 4,096-number code, what the network learns at a point, how a label turns into a guided velocity, and what the bound says the autoencoder costs. Then go back to the counter at the top, switch between pixel and latent space at 512, and say how many times fewer numbers each of the 89 steps writes.

Flow Matching in Latent Space (MIT MMAI reading)
Read the paper · Authors’ code · The course site · Lecture 10 · Back to Gleams