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.
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
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.
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.
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.
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.
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: 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.
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.
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.
Chapter 1
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.
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.
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.
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.
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):
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.
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.
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.
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.
Chapter 2
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.
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.
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.
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.
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.
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.
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.
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.
Chapter 3
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 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):
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 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.
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.
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.
Chapter 4
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 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:
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.
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:
| Solver | NFE listed | FID (lower is better) | Time per image |
|---|---|---|---|
| Adaptive (dopri5) | 89 | 5.26 | 1.70 s |
| Euler | 90 | 5.51 | 1.78 s |
| Heun | 50 | 5.26 | 1.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.
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.
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.
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.
Chapter 5
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.
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.
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.
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.
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).
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.
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.
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.
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.
Chapter 6
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.
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 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:
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.
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.
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.
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.
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.
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.)
Chapter 7
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.
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:
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.
Let p0 be the real image distribution and p̂0 the distribution of images the pipeline makes. Theorem 4.1 (Equation 20) says:
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.
Now play with the three budgets. The numbers are made up, so you can see how the parts trade.
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.
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.
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.
Chapter 8
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.
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.
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.
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.
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).
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.
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.
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”.
Chapter 9
Keep the numbers, the checklist, the core code and the way onward
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.
| What | Number | Why it matters |
|---|---|---|
| Latent size, 256 × 256 | 4 × 32 × 32 = 4,096, against 196,608 pixels | 48 times fewer numbers per step |
| Latent size, 512 × 512 | 4 × 64 × 64 = 16,384, against 786,432 | The same 48 times |
| Path and target | zt = (1 − t)z0 + t z1; velocity z1 − z0 | A straight line is solved exactly by one step |
| CelebA-HQ 256, DiT L/2 | FID 5.26, 89 calls, 1.70 s | Beats pixel flow matching (7.34, 128 calls) |
| Solvers (Table 4) | Adaptive 89 / 5.26; Euler 90 / 5.51; Heun 50 / 5.26 | Heun 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 guidance | 0.56, then 0.48, then 0.42 | Fidelity is paid for with variety |
| Inpainting, CelebA-HQ 256 | FID 4.09 (MAT 2.94, LaMa 3.98); 9 input channels | A concatenation trick is competitive |
| Layout to image | FID 26.3 (SDM 18.8, SCGAN 20.8); 8 input channels | Middle of the pack |
| Networks (Tables 6, 7) | DiT L/2 457M, 80.74 GFLOPs; DiT B/2 130M, 23.01; ADM 368M, 28.9 | Cost per call |
| Training time (Tables 8, 9) | ADM CelebA 256: 1.3 days, 2 GPUs; DiT L/2: 5.8 days, 1 GPU | Fits small hardware |
| The bound | W22 ≤ ‖Δ‖2 + Lg2 e1+2L̂ × (flow error) | The autoencoder sets a floor |
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)
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.
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.
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.