8.6Diffusion Transformers & flow matching
Swap the U-Net for a Transformer over latent patches, and swap curved noise-to-data paths for straight ones. Together they power SD3, FLUX and most new image and video models.
Two things worth changing
By 2022, latent diffusion worked. But two parts of the recipe looked like historical accidents rather than necessities.
The first was the backbone. The U-Net, a convolutional design from 2015 medical imaging, was carrying the whole denoising job. Meanwhile, language models had shown that the TransformerTransformerThe neural network architecture behind modern LLMs: stacked blocks of self-attention and feed-forward layers with residual connections. keeps improving predictably as you add parameters and compute (see scaling laws). Would image generation scale the same way if it used the same architecture?
The second was the path. The DDPM forward process mixes data and noise along a curve: . When you integrate a curved path with big steps, you cut corners and miss. That’s a big reason samplers needed dozens of steps. Is there a path from noise to data that is easier to follow?
Picture getting from the airport (noise) to your hotel (an image) through a city whose roads wind and curve. If you’re only allowed to check your map a few times and drive straight between checks, you’ll overshoot every bend and end up in the wrong neighborhood. Diffusion’s curved paths are those winding roads; each map check is one network evaluation.
Rectified flow builds a highway: the route from each starting point to its destination is a straight line, and the network tells you the constant direction and speed to drive. Check the map once at the start and you can almost drive the whole way blind. And the Transformer is the better navigator: it looks at the whole map (all patches) at once, and gets reliably better as you train a bigger one.
Diffusion Transformers (DiT)
Peebles and Xie’s Scalable Diffusion Models with Transformers (2022) asked the first question directly. Their DiTDiffusion Transformer (DiT)A diffusion denoiser built from Transformer blocks over latent patches instead of a U-Net. treats the noisy latent exactly the way a Vision TransformerVision Transformer (ViT)A Transformer that treats an image as a sequence of patch tokens. treats an image:
- Patchify. Cut the latent (for a 256×256 image, a 32×32×4 latent from the Stable Diffusion VAE) into patches and linearly embed each patch as a token. With that’s tokens; with just 16 tokens.
- Transformer blocks. Standard self-attention and MLP blocks over all tokens.
- Unpatchify. A final linear layer turns each token back into a patch of predicted noise (and variance).
The interesting design question was how to inject the conditioning, the timestep and the class label (DiT was trained class-conditionally on ImageNet, not on text). The paper tried feeding them as extra tokens, using cross-attention, and modulating layer norms; the winner was adaLN-ZeroadaLN-ZeroDiT's conditioning: the timestep and class embedding predict per-block scale, shift and gate values for layer norm, with gates initialized to zero.. The timestep and class embeddings are summed and passed through a small MLP that outputs, for every block, a scale and shift for the layer norms and a gate that multiplies each residual branch. The gates are initialized to zero, so each block starts as the identity function and training gently “turns on” its contribution, a trick that stabilizes deep networks.
The headline result was about scaling. Across model sizes (S, B, L, XL) and patch sizes, sample quality, measured by FID, improved smoothly as the forward-pass compute in GFLOPs increased, whether that compute came from more layers or from smaller patches (more tokens). The largest, DiT-XL/2 (patch size 2), reached an FID of 2.27 on class-conditional ImageNet 256×256, beating the prior diffusion models of the time. Transformer scaling, it turned out, transfers to pixels.
MMDiT: letting text and image talk both ways
U-Net models read text through one-way cross-attention: image queries, text keys and values. Stable Diffusion 3 (Esser et al., 2024, Scaling Rectified Flow Transformers for High-Resolution Image Synthesis) introduced the MMDiTMMDiTMultimodal Diffusion Transformer (SD3): text and image tokens keep separate weights but attend to each other in one joint attention.. Text tokens (from two CLIP encoders and T5-XXL) and image patch tokens each keep their own weights for the projections and MLPs, because the two modalities are so different, but in every block their sequences are concatenated for one joint attention. Image tokens attend to text and text tokens attend to image, so the text representation is refined by what’s being drawn. In the paper’s controlled comparisons, MMDiT beat both a cross-attention DiT and a plain concatenation variant, and quality kept improving with scale up to their largest model, about 8B parameters.
Flow matching and rectified flow
Now the second question. Lipman et al.’s flow matching (2022) and Liu, Gong and Liu’s rectified flow (2022) start from a generalization of the diffusion setup. Pick any path that interpolates between a data point and a noise sample . The simplest possible choice is a straight line:
At you have data, at pure noise. Along this line, the velocity is constant: . So train a network to predict it:
That’s the whole training loop: same shape as DDPM’s, with a different target. To sample, start from noise at and integrate the ODE backward to with any ODE solver; the plainest is Euler, .
There’s a subtlety. Each training pair follows a straight line, but the network can’t know which data point a given noisy came from, because many pairs’ lines cross the same spot. It learns the average velocity of all lines through that point. The resulting flowFlow matching / rectified flowTraining a model to predict a velocity field that carries noise to data along (ideally straight) paths. Used in SD3 and FLUX. transports noise to data correctly, but its trajectories are not perfectly straight. Where the data has a single mode they come close; where lines heading to different modes cross, the averaged velocity bends.
Reflow fixes that. Generate many (noise, image) pairs by running the trained flow, then train a new flow on those pairs. Because the pairs are now matched by the flow itself, their straight lines no longer cross much, and the new model’s paths are nearly straight. Liu et al. showed that reflowed models can sample well with very few steps, even one, especially after distillation.
Hollow circles: starting noise. Dashed grey: the true ODE paths. Orange: what an Euler solver with this many steps actually does. The velocities are computed exactly for this toy, so every error you see is a discretization error, not a learning error.
Everything here is exact: for this small Gaussian-mixture dataset, the optimal velocity fields can be computed in closed form, so the only error is from taking big steps. “DDPM-style” means the probability-flow ODE of DDPM’s linear noise schedule, integrated with plain Euler steps in . Things to try:
- One blob, 2 steps. Rectified flow’s paths are nearly straight lines at nearly constant speed (straightness gap close to 0), so two Euler steps land close to the reference. The DDPM-style paths do almost nothing for the first half of the time and then rush, so the same two steps miss badly.
- Two clusters, rectified flow, 1 step. Every sample lands on the data’s average, between the clusters. At pure noise, the network can’t yet tell which cluster a sample will go to, so its velocity points at the mean: the “blurry average” again. Paths bend later, once they commit to a cluster.
- Two clusters, 2 to 4 steps. Rectified flow’s endpoint error is now about half of the DDPM-style error. Not perfect, but a much better use of a small step budget.
- Reflow, 1 step. Perfectly straight paths, so a single Euler step lands exactly where 240 steps would. This option is idealized: it uses the straight segment from each noise sample to its rectified-flow endpoint, which is what reflow aims for; a real reflowed network only approximates it.
SD3 and FLUX
SD3 combines both ideas: an MMDiT backbone trained with the rectified-flow objective. One finding of the paper is that which timesteps you train on matters: sampling from a logit-normal distribution, which concentrates training on the hard, middle noise levels, beat uniform sampling. SD3 also moved to a 16-channel VAE latent, up from Stable Diffusion’s 4, to preserve more fine detail.
FLUX.1, released in August 2024 by Black Forest Labs (founded by several of the original latent diffusion authors), is described on its model cards as a 12-billion-parameter rectified flow transformer. The public reference code shows MMDiT-style double-stream blocks followed by single-stream blocks; beyond that, no full technical paper was published for FLUX.1, so treat finer architectural claims you read online with care. Its fastest variant, FLUX.1 [schnell], is distilled to generate in 1–4 steps. Many of the open video models you’ll meet in the next lesson use the same recipe: a Transformer backbone, often trained with a flow-matching objective.
MATH CORNER · optionalVelocity, noise and data predictions, with one Euler step by hand
Rectified flow uses , target . Given a velocity prediction you can recover both endpoints:
So velocity, noise and data prediction are interchangeable parameterizations, just like - and -prediction in DDPM. In general, for any path , the ideal velocity field is
which is exactly what the demo computes. For rectified flow, , . For the cosine VP path, , .
Worked example (one training pair, 1D). Data , noise . Integrate from to with one Euler step, using each path’s true velocity for this pair.
| path | (start) | velocity at | one step: | error |
|---|---|---|---|---|
| straight: | −1 | 0 | ||
| cosine: | −1 | 0.142 |
On a straight line, Euler is exact with any step size. On the curve, the velocity at the start points along the tangent, so one step overshoots. With many training pairs mixed together, rectified flow’s marginal paths also bend a little, which is what reflow removes.
In code
The rectified-flow training step and an Euler sampler. Compare with the DDPM version in the diffusion lesson: only the interpolation and the target changed.
import torch
def rf_train_step(model, x0, opt):
t = torch.rand(x0.shape[0]) # SD3 uses a logit-normal t instead
eps = torch.randn_like(x0)
tt = t.view(-1, 1, 1, 1)
xt = (1 - tt) * x0 + tt * eps # straight line from data to noise
loss = (model(xt, t) - (eps - x0)).pow(2).mean() # predict the velocity
opt.zero_grad(); loss.backward(); opt.step()
@torch.no_grad()
def rf_sample(model, shape, steps=20):
x = torch.randn(shape) # t = 1: pure noise
ts = torch.linspace(1, 0, steps + 1)
for t, t_next in zip(ts[:-1], ts[1:]):
v = model(x, t.repeat(shape[0]))
x = x + (t_next - t) * v # Euler step toward t = 0
return x
- “Flow matching is a completely different kind of model from diffusion.” It’s a close cousin. With Gaussian noise, the straight-line path is one choice of noise schedule, and velocity prediction is one parameterization; the probability-flow ODE of diffusion is also a flow. The practical differences are the simpler path and target.
- “Rectified flow paths are perfectly straight.” Each training pair’s path is straight, but the learned marginal flow averages crossing lines, so its trajectories bend. Reflow (or distillation) is needed to make them nearly straight.
- “DiT is just a ViT.” The backbone is ViT-like, but DiT’s conditioning through adaLN-Zero (timestep and class modulating every block, zero-initialized gates) is a key ingredient; the paper found it clearly better than simply adding conditioning tokens.
- “Transformers made image generation cheaper.” They made it scale more predictably. Attention cost grows with the square of the token count, which is why small patch sizes and high resolutions are expensive.
Check your understanding
Q1.In DiT, what happens when you halve the patch size p (e.g. from 4 to 2) for the same latent?
Q2.What does adaLN-Zero do?
Q3.For rectified flow with x_t = (1−t)x₀ + tε, what is the network trained to predict?
Q4.Why do straighter trajectories allow fewer sampling steps?
Q5.What is distinctive about MMDiT (SD3) compared with U-Net cross-attention?
Further reading
- paperScalable Diffusion Models with Transformers (Peebles & Xie, 2022) — DiT: patchified latents, adaLN-Zero, GFLOPs scaling.
- paperFlow Matching for Generative Modeling (Lipman et al., 2022) — The flow-matching objective and its links to diffusion.
- paperFlow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow (Liu, Gong, Liu, 2022) — Straight-line interpolation and reflow.
- paperScaling Rectified Flow Transformers for High-Resolution Image Synthesis (Esser et al., 2024) — The SD3 paper: MMDiT and logit-normal timestep sampling.
- docsFLUX.1 [dev] model card (Black Forest Labs) — Official description of the 12B rectified flow transformer.
- codeblack-forest-labs/flux reference code — Minimal inference code for the FLUX.1 models.