Diffusion Models and Flow Matching: Generating Images, Actions and Text from Noise
Diffusion models turn data into Gaussian noise with a known process and train a network to undo it step by step; flow matching regresses a velocity field instead, so sampling is an ODE solve. This page builds DDPM, DDIM, flow matching and reflow on 2-D data and measures steps against quality.
After this page you will be able to
- Write the closed form of the forward noising process and the DDPM noise-prediction loss, and explain why noise, score and velocity are one quantity in different clothes.
- Tell DDPM's stochastic sampler, DDIM's deterministic sampler and flow matching's ODE sampler apart, and implement them in a few dozen lines of PyTorch.
- Explain why one-step generation fails (flow matching collapses to the data mean, DDIM amplifies the error of the noise estimate) and how reflow, distillation and consistency models cut the step count.
- Write the classifier-free guidance (CFG) formula and measure the trade-off between fidelity, diversity and drift from the data distribution as the guidance scale grows.
- Describe the data flow of latent diffusion, DiT and MM-DiT: how an image becomes tokens, how text conditioning enters, and how many tokens that makes.
- Judge where diffusion or flow matching fits better than autoregression: images, robot actions and text (LLaDA).
On this page
- Why another family of generative models
- The forward process: turning data into noise
- Experiment 1: does the closed form match step-by-step noising
- Training: predict the noise, and the noise hides the score
- Experiment 2: checking against data with a known score
- One quantity, several parameterizations
- The network and the training code
- Sampling: walking from noise back to data
- Flow matching: from denoising to walking in straight lines
- Steps versus sample quality
- How to measure whether the samples are good
- Reflow: straightening the trajectories
- Experiment 3: step curves for DDIM, flow matching and reflow
- Conditioning and classifier-free guidance
- Latent diffusion and DiT: turn the image into tokens, then denoise
- Beyond images: actions and text
- Practical notes and common pitfalls
- Summary and exercises
- Quick self-check
- Exercises
- Further reading
- FAQ
Diffusion models and flow matching turn generative modeling into a regression problem: define a known path from data to Gaussian noise, then train a network to predict what the path “took away” at each point; to generate, start from noise and follow the network’s direction back to data. Images (Stable Diffusion, DiT), robot actions (Diffusion Policy, π0) and text (LLaDA) all use this recipe. This page builds DDPM, DDIM, flow matching and reflow from scratch in a few dozen lines of PyTorch on a 2-D two-moons dataset and measures three things on a CPU: how sampling steps buy sample quality, why one-step generation fails, and how classifier-free guidance (CFG) trades fidelity against diversity.
Why another family of generative models
An autoregressive LLM factorizes the joint distribution into a product of conditionals and samples one token from a discrete vocabulary at a time (see next-token prediction). Continuous, high-dimensional data with strongly coupled positions, such as pixels, latents or robot joint angles, does not factor naturally into conditionals with a fixed order. Diffusion and flow matching take a different route: do not factor at all, learn a continuous transformation that carries a simple distribution (Gaussian noise) onto the data distribution. At sampling time all positions of the sample sharpen at once, and the amount of compute is dialed with the number of steps.
| Autoregressive (LLM) | Diffusion / flow matching | |
|---|---|---|
| Unit of generation | One token, in order | All positions of the sample at once |
| Network calls per sample | Proportional to length (with a KV cache each call only handles the new token) | Equal to the step count, a few to thousands; each call costs more as the sample grows |
| Training objective | Cross-entropy (next token) | Mean squared error (regress noise or velocity) on continuous data |
| Source of randomness | Sampling from the vocabulary at every step | The initial noise (stochastic samplers add fresh noise each step) |
| Typical data | Text, code | Images, video, audio, robot actions |
| Exceptions | Images can be tokenized and generated autoregressively | LLaDA applies diffusion to text (see below) |
The next three sections cover the known forward path, the denoising direction learned by regression, and the samplers that follow that direction back; then come flow matching, two experiments and conditional generation.
The forward process: turning data into noise
Let be a data point (a 2-D point on this page). Each forward step shrinks the signal a little and adds a little Gaussian noise: with . Let and . Gaussians are closed under addition, so steps collapse into a closed form:


This equation shapes training: there is no need to walk steps, pick any and build in one go. The signal-to-noise ratio compares signal and noise; at 1 they are equally large. DDPM uses steps with rising linearly from to (Ho et al., 2020).
The data are two half circles (class 0 on top, class 1 below), each with Gaussian noise of 0.05. The setup block below defines the schedule and the dataset that every later experiment shares.
The widget below turns the closed form into something you can drag: scrub t (or play) and the same 600 points travel by toward their own fixed noise; switch between the linear and the cosine schedule to see how the fall of differs.
Experiment 1: does the closed form match step-by-step noising
Copy the point 100,000 times, really noise it 1000 steps one at a time, and compare the mean and standard deviation of the first coordinate with the closed-form predictions and . Environment: Apple M2 Max (64 GB), Python 3.14.3, NumPy 2.4.2, PyTorch 2.10.0 (CPU, 4 threads). Seeds are fixed, so rerunning on the same machine gives bit-identical numbers; on other setups a few numbers may differ slightly.
import copy
import math
from functools import partial
import torch
import torch.nn as nn
torch.set_num_threads(4)
T = 1000 # DDPM: 1000 noise steps
beta = torch.cat([torch.zeros(1), torch.linspace(1e-4, 0.02, T)])
abar = torch.cumprod(1 - beta, 0) # abar[t] = alpha-bar_t, t = 0..T
def moons(n, g, noise=0.05):
"""Two half circles centred at 0: class 0 on top, class 1 below."""
a = torch.rand(n, generator=g) * math.pi
c = (torch.rand(n, generator=g) < 0.5).long()
x = torch.where(c == 0, torch.cos(a), 1 - torch.cos(a)) - 0.5
y = torch.where(c == 0, torch.sin(a), 0.5 - torch.sin(a)) - 0.25
p = torch.stack([x, y], 1)
return p + noise * torch.randn(n, 2, generator=g), c
g = torch.Generator().manual_seed(0)
x = torch.tensor([0.8, -0.3]).repeat(100000, 1) # 100k copies of one point
print(f"{'t':>5} {'abar':>9} {'SNR dB':>8} {'mean th':>8} {'mean me':>8}"
f" {'std th':>8} {'std me':>8}")
for t in range(1, T + 1): # noise it step by step
x = (1 - beta[t]).sqrt() * x
x = x + beta[t].sqrt() * torch.randn(x.shape, generator=g)
if t in (1, 10, 100, 300, 1000):
ab = abar[t]
snr = 10 * math.log10(ab / (1 - ab))
print(f"{t:5d} {ab:9.2e} {snr:8.2f} {ab.sqrt() * 0.8:8.4f}"
f" {x[:, 0].mean():8.4f} {(1 - ab).sqrt():8.4f}"
f" {x[:, 0].std():8.4f}")
r = abar[T].sqrt()
print(f"sqrt(abar_T) = {r:.4f}; 1 / sqrt(abar_T) = {1 / r:.1f}")
t abar SNR dB mean th mean me std th std me
1 1.00e+00 40.00 0.8000 0.7999 0.0100 0.0100
10 9.98e-01 27.22 0.7992 0.7992 0.0435 0.0436
100 8.97e-01 9.40 0.7577 0.7568 0.3209 0.3220
300 3.96e-01 -1.83 0.5037 0.5059 0.7769 0.7756
1000 4.04e-05 -43.94 0.0051 0.0074 1.0000 1.0000
sqrt(abar_T) = 0.0064; 1 / sqrt(abar_T) = 157.4
Means and standard deviations agree to three decimals; with 100,000 samples the mean has a sampling error of about 0.003, so the gap of 0.0074 against 0.0051 at is within the error. At the signal coefficient is only 0.0064 and the SNR is dB: the original point is completely drowned, and can be treated as a standard Gaussian. The reciprocal 157.4 on the last line comes back in the one-step sampling discussion.
The linear schedule has a known weakness: the SNR drops to very low values early. Nichol and Dhariwal (2021) observed that the last quarter of the linear schedule is almost pure noise and switched to a cosine schedule; Exercise 2 measures this with this page’s schedule.
Training: predict the noise, and the noise hides the score
Training a denoising network takes three steps: draw a data point , a step and a noise , build with the closed form, and ask the network to predict . DDPM’s simplified loss is an unweighted mean squared error:
Why does predicting noise generate anything? The mean-squared-error optimum is the conditional expectation . On the other hand, the score of the marginal of (the direction in which density rises fastest) satisfies
so the optimal noise prediction is the score times . The relation comes from denoising score matching (Vincent, 2011); Song and Ermon (2019) used it to train score networks, and Ho et al. (2020) connected it to the variational bound of diffusion models. What the network learns is “from this noisy sample, which way does density increase”, and sampling follows that direction back.
Experiment 2: checking against data with a known score
For one-dimensional Gaussian data , , the score has a closed form, and the optimal noise prediction is a linear function of . The code fits the slope of by least squares from samples and compares it with the slope given by score.
s = 0.8 # data: N(0, s^2) in one dimension
x0 = s * torch.randn(400000, generator=g)
e = torch.randn(400000, generator=g)
print(f"{'t':>5} {'fitted slope':>13} {'-sigma*score':>13}")
for t in (10, 100, 300, 600):
ab = abar[t]
xt = ab.sqrt() * x0 + (1 - ab).sqrt() * e
slope = (xt * e).sum() / (xt * xt).sum() # least squares: e ~ k * xt
theory = (1 - ab).sqrt() / (ab * s**2 + 1 - ab) # -sigma_t * score
print(f"{t:5d} {slope:13.4f} {theory:13.4f}")
t fitted slope -sigma*score
10 0.0685 0.0679
100 0.4746 0.4740
300 0.9064 0.9062
600 0.9962 0.9963
The slopes agree to within 0.001 at all four values of . The two ends also show how hard the task is: at the slope is only 0.0685 (the noise is tiny, is almost the data, and the noise is nearly impossible to guess from ), and at it is close to 1 ( is almost pure noise, ).
One quantity, several parameterizations
The network can predict other things. For , given and the quantities below differ from one another by algebra only:
| Network output | Training target | Recover the clean sample | Note |
|---|---|---|---|
| Noise | DDPM’s default | ||
| Clean sample | Output directly | Differs from noise prediction only by a weight that depends on | |
| Score | The score-model literature’s form | ||
| Velocity | v-prediction of Salimans and Ho (2022), more stable with few sampling steps |
A different parameterization does not change what the model can represent; it changes how the loss is weighted across noise levels. From we get
so predicting noise is the same as predicting the clean sample and multiplying the error by the SNR. The “velocity” here is the v-prediction notation and is not the velocity of flow matching below (time is parameterized differently).
The network and the training code
Every later method shares one network: an MLP with 3 hidden layers of width 256 whose input is the 2-D point, the Fourier features of the time (), and an optional class embedding. Training is Adam with a cosine learning-rate decay, 8000 steps, batch size 512, learning rate . The network has only 135,938 parameters, and the whole page’s code runs end to end in about three minutes on this machine.
class Net(nn.Module):
"""MLP (x, time[, class]) -> R^2, the same for every method below."""
def __init__(self, width=256, classes=0):
super().__init__()
self.freqs = math.pi * 2.0 ** torch.arange(6) # pi, 2pi, ..., 32pi
self.emb = nn.Embedding(classes + 1, 16) if classes else None
layers = [nn.Linear(14 + (16 if classes else 0), width), nn.SiLU()]
for _ in range(2):
layers += [nn.Linear(width, width), nn.SiLU()]
self.f = nn.Sequential(*layers, nn.Linear(width, 2))
def forward(self, x, s, c=None): # s in [0, 1]
a = s[:, None] * self.freqs
h = [x, torch.sin(a), torch.cos(a)]
if self.emb is not None:
h.append(self.emb(c))
return self.f(torch.cat(h, 1))
print(f"parameters: {sum(p.numel() for p in Net().parameters())}")
parameters: 135938
def fit(net, loss_fn, steps, lr, seed):
g = torch.Generator().manual_seed(seed)
opt = torch.optim.Adam(net.parameters(), lr=lr)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps)
for _ in range(steps):
loss = loss_fn(net, g)
opt.zero_grad()
loss.backward()
opt.step()
sched.step()
return net
def ddpm_loss(net, g, bs=512): # predict the noise
x0, _ = moons(bs, g)
e = torch.randn(bs, 2, generator=g)
t = torch.randint(1, T + 1, (bs,), generator=g)
ab = abar[t][:, None]
xt = ab.sqrt() * x0 + (1 - ab).sqrt() * e
return ((net(xt, t / T) - e) ** 2).mean()
In ddpm_loss the network receives the time t / T, so 1 is pure noise and values near 0 are clean data.
Sampling: walking from noise back to data
How do we use the trained to generate? Two samplers are common.
DDPM ancestral sampling starts from ; every step denoises with the network’s noise estimate and then adds a little fresh random noise (variance ; Ho et al. report similar results with the posterior variance):
It has to walk step by step: the 1000 training steps are the 1000 sampling steps.
DDIM reuses the same trained network, drops the random term (the paper’s ) and may skip many steps at once (Song et al., 2020). It first recovers an estimate of the clean sample from the current noise estimate, then re-noises it with the same to a smaller noise level :
With no random term, the same noise always gives the same sample, and can be much smaller than , so far fewer than 1000 steps will do. The DDIM paper points out that this update resembles the Euler integration of an ODE; Song et al. (2020) wrote diffusion as a stochastic differential equation and derived a “probability flow ODE” with the same marginals, which is the common starting point of DDIM, flow matching and every ODE sampler below: integrate a velocity field deterministically, with randomness only in the initial noise.
@torch.no_grad()
def ancestral(net, z, g): # DDPM: 1000 stochastic steps
x = z
for t in range(T, 0, -1):
e = net(x, torch.full((len(x),), t / T))
x = (x - beta[t] / (1 - abar[t]).sqrt() * e) / (1 - beta[t]).sqrt()
if t > 1:
x = x + beta[t].sqrt() * torch.randn(x.shape, generator=g)
return x
@torch.no_grad()
def ddim(net, z, steps): # deterministic, fewer steps
x = z
ts = torch.linspace(T, 0, steps + 1).round().long()
for t, u in zip(ts[:-1], ts[1:]): # jump from step t to step u
e = net(x, torch.full((len(x),), t.item() / T))
x0 = (x - (1 - abar[t]).sqrt() * e) / abar[t].sqrt()
x = abar[u].sqrt() * x0 + (1 - abar[u]).sqrt() * e
return x
Flow matching: from denoising to walking in straight lines
Flow matching (Lipman et al., 2022) and rectified flow (Liu et al., 2022) write the same thing more directly. Take a pair (noise , data ) and join them with a straight line:
is noise and is data, the opposite direction to diffusion’s “larger is noisier”. The velocity along this line is the constant , and the network regresses it:
To generate, start from noise at and solve the ODE up to . The simplest solver, Euler, cuts the interval into pieces: .
During training one position is crossed by many different (noise, data) pairs, so the network learns the conditional mean of their velocities, , and this marginal velocity field carries the noise distribution onto the data distribution (Lipman et al., 2022; details in the flow matching paper note). Because it is a conditional mean, the trajectories are no longer straight: the lines are averaged where they cross.
def fm_loss(net, g, pairs=None, bs=512): # predict the velocity x1 - z
if pairs is None: # fresh data and fresh noise
x1, _ = moons(bs, g)
z = torch.randn(bs, 2, generator=g)
else: # reflow: given (noise, data) pairs
i = torch.randint(0, len(pairs[0]), (bs,), generator=g)
z, x1 = pairs[0][i], pairs[1][i]
s = torch.rand(bs, generator=g)
xs = (1 - s[:, None]) * z + s[:, None] * x1 # straight line
return ((net(xs, s) - (x1 - z)) ** 2).mean()
@torch.no_grad()
def euler(net, z, steps): # flow matching: integrate dx/ds = v
x = z
for i in range(steps):
x = x + net(x, torch.full((len(x),), i / steps)) / steps
return x
Relation to diffusion. Both belong to the family of “Gaussian paths”, . DDPM’s path is curved and variance-preserving, flow matching uses linear interpolation; predicting noise, score or velocity differ by a conversion. What really differs is four choices: the path, the prediction target, the sampler and the loss weighting. The table compares the two recipes on this page:
| DDPM with DDIM (this page) | Flow matching with Euler (this page) | |
|---|---|---|
| Path | , larger is noisier | , larger is closer to data |
| Network predicts | Noise | Velocity |
| Sampler | Stochastic ancestral sampling; deterministic DDIM | Deterministic ODE, Euler |
| Time input of the network |
Before reading the results, note that this is not a controlled experiment. The two recipes differ in path, prediction target and sampler at the same time, so the question answered is “how do these two common recipes behave with the same small network and training budget”, not “is flow matching intrinsically better than diffusion”. For a large-scale comparison see the study Esser et al. (2024) ran while training Stable Diffusion 3: on text-to-image they compared rectified flow with established diffusion formulations, and with an improved timestep sampler rectified flow came out ahead.
Steps versus sample quality
How to measure whether the samples are good
Two-dimensional data can be inspected visually, and two numbers quantify it:
- Sliced Wasserstein distance
sw: project two point sets onto 128 random directions, compute the one-dimensional Wasserstein-1 distance in each (sort and compare point by point), and average; smaller means closer to the real distribution. It has sampling noise: drawing 10,000 fresh real points against the reference set also gives a nonzero number, the “noise floor”. Differences below the noise floor mean nothing. - On-manifold share
on: the share of samples within 0.15 of a noise-free half circle. The data noise is 0.05, so 0.15 is about 3 standard deviations, and the real data scores 0.997.
def arc_dist(p, c):
"""Distance from points p to the noise-free half circle of class c."""
sg = (1.0 - 2.0 * c)[:, None] # class 0: +1, class 1: -1
q = sg * p + torch.tensor([0.5, 0.25]) # rotate: the arc is y >= 0
ends = torch.minimum((q - torch.tensor([1.0, 0.0])).norm(dim=1),
(q + torch.tensor([1.0, 0.0])).norm(dim=1))
return torch.where(q[:, 1] >= 0, (q.norm(dim=1) - 1).abs(), ends)
def on_manifold(p, r=0.15): # share of points within r of an arc
c = torch.zeros(len(p), dtype=torch.long)
d = torch.minimum(arc_dist(p, c), arc_dist(p, 1 - c))
return (d < r).float().mean().item()
def sw(a, b, dirs): # sliced Wasserstein-1 distance
pa = (a @ dirs).sort(0).values
pb = (b @ dirs).sort(0).values
return (pa - pb).abs().mean().item()
g = torch.Generator().manual_seed(7)
dirs = torch.randn(2, 128, generator=g)
dirs = dirs / dirs.norm(dim=0) # 128 random directions
ref, _ = moons(10000, g) # reference: real samples
floor = torch.tensor([sw(moons(10000, g)[0], ref, dirs) for _ in range(20)])
print(f"real data, on-manifold share: {on_manifold(ref):.3f}")
print(f"noise floor of sw (fresh real set vs reference, 20 draws): "
f"{floor.mean():.4f} +- {floor.std():.4f}")
real data, on-manifold share: 0.997
noise floor of sw (fresh real set vs reference, 20 draws): 0.0113 +- 0.0033
The noise floor is 0.0113, with a standard deviation of 0.0033 over 20 draws.
Reflow: straightening the trajectories
Flow matching does badly in one step because the trajectories of the marginal velocity field are curved and need small steps to follow. Reflow (Liu et al., 2022) takes a trained flow-matching model, integrates a batch of noise vectors along the ODE to endpoints , treats (, ) as new pairs and fine-tunes the model on them with the same straight-line loss. The paper proves that the new pairs form a deterministic coupling whose transport cost does not increase, and that repeating the procedure gives flows with increasingly straight paths that tolerate very coarse discretization. If the trajectory is a straight line, one Euler step is exact.
Experiment 3: step curves for DDIM, flow matching and reflow
For each of 3 training seeds, train three models: the DDPM network (sampled with DDIM), the flow-matching network, and a network obtained by reflow from the flow-matching one (50,000 (noise, ODE endpoint) pairs, fine-tuned for 4000 steps at learning rate ). All three use the same noise and sample 10,000 points with 1 to 128 network evaluations (NFE).
NFE = [1, 2, 4, 8, 16, 32, 64, 128]
res = {"DDIM": [], "FM": [], "reflow": []} # res[name][seed][nfe]
for seed in range(3):
torch.manual_seed(seed)
dd = fit(Net(), ddpm_loss, 8000, 2e-3, 1000 + seed)
torch.manual_seed(seed)
fm = fit(Net(), fm_loss, 8000, 2e-3, 1000 + seed)
gz = torch.Generator().manual_seed(2000 + seed)
Z = torch.randn(50000, 2, generator=gz) # reflow: noise ...
X = euler(fm, Z, 128) # ... and where the ODE ends
rf = fit(copy.deepcopy(fm), partial(fm_loss, pairs=(Z, X)),
4000, 1e-3, 3000 + seed)
z = torch.randn(10000, 2, generator=gz) # same noise for every model
for name, net, run in (("DDIM", dd, ddim), ("FM", fm, euler),
("reflow", rf, euler)):
outs = [run(net, z, k) for k in NFE]
res[name].append([(sw(x, ref, dirs), on_manifold(x)) for x in outs])
if seed == 0:
dd0, fm0, rf0, z0 = dd, fm, rf, z
R = {k: torch.tensor(v) for k, v in res.items()} # (seed, nfe, metric)
print("sw, mean +- std over 3 training seeds (lower is better)")
print(f"{'NFE':>4} {'DDIM':>15} {'FM':>15} {'reflow':>15}")
for i, k in enumerate(NFE):
cells = [f"{R[m][:, i, 0].mean():.4f}+-{R[m][:, i, 0].std():.4f}"
for m in R]
print(f"{k:4d} " + " ".join(f"{c:>15}" for c in cells))
print()
print("share of samples within 0.15 of the data manifold (mean +- std)")
print(f"{'NFE':>4} {'DDIM':>11} {'FM':>11} {'reflow':>11}")
for i, k in enumerate(NFE):
cells = [f"{R[m][:, i, 1].mean():.3f}+-{R[m][:, i, 1].std():.3f}"
for m in R]
print(f"{k:4d} " + " ".join(f"{c:>11}" for c in cells))
sw, mean +- std over 3 training seeds (lower is better)
NFE DDIM FM reflow
1 3.0745+-0.3857 0.5619+-0.0019 0.0200+-0.0032
2 0.3936+-0.0277 0.2966+-0.0025 0.0165+-0.0048
4 0.2300+-0.0186 0.1459+-0.0032 0.0159+-0.0052
8 0.1201+-0.0084 0.0630+-0.0032 0.0157+-0.0054
16 0.0543+-0.0054 0.0322+-0.0034 0.0156+-0.0055
32 0.0303+-0.0039 0.0199+-0.0047 0.0156+-0.0056
64 0.0225+-0.0045 0.0161+-0.0055 0.0155+-0.0057
128 0.0195+-0.0049 0.0150+-0.0059 0.0155+-0.0057
share of samples within 0.15 of the data manifold (mean +- std)
NFE DDIM FM reflow
1 0.024+-0.004 0.003+-0.001 0.921+-0.004
2 0.373+-0.105 0.317+-0.014 0.935+-0.004
4 0.248+-0.051 0.621+-0.010 0.943+-0.003
8 0.512+-0.029 0.883+-0.008 0.947+-0.001
16 0.848+-0.008 0.943+-0.005 0.950+-0.001
32 0.911+-0.006 0.958+-0.003 0.952+-0.001
64 0.930+-0.007 0.963+-0.001 0.953+-0.001
128 0.937+-0.006 0.966+-0.002 0.953+-0.001
How to read the two tables and two figures:
- One step: three outcomes. One-step DDIM has sw 3.0745 and the samples are almost all out of frame. The reason is that from pure noise , so the error of the noise estimate is amplified by , and when the single step lands on the output is exactly this amplified . One-step flow matching has sw 0.5619 and an on-manifold share of 0.003, a single blob; one-step reflow has sw 0.0200 and an on-manifold share of 0.921.
- Why one-step flow matching collapses to the mean. At , carries no information about , the optimal velocity is , and one Euler step lands on : the same point for every , the data mean. The
extrasblock below measures it. - 8 to 16 steps: flow matching is clearly better than DDIM. At 8 steps sw is 0.0630 against 0.1201 and the on-manifold share 0.883 against 0.512; at 16 steps 0.0322 against 0.0543 and 0.943 against 0.848. The gaps are several times the seed-to-seed standard deviation.
- 64 to 128 steps: sw differences vanish in the noise. At 128 steps DDIM has 0.0195 (standard deviation 0.0049), flow matching 0.0150 (0.0059), reflow 0.0155 (0.0057), and the noise floor is 0.0113 (0.0033). These gaps are smaller than or close to the seed spread, so we do not interpret them. The on-manifold share still separates the methods: 0.966 for flow matching, 0.937 for DDIM.
- The reflow curve is flat. sw goes from 0.0200 at 1 step to 0.0155 at 128 steps, a difference within the seed spread; the on-manifold share creeps from 0.921 to 0.953: once straightened, the number of steps hardly matters. At 128 steps its 0.953 is a little below flow matching’s 0.966. One plausible explanation is that reflow learns the previous model’s samples, so the previous model’s errors are carried over; this page did not test it separately.
- For DDIM the on-manifold share drops from 2 to 4 steps (0.373 against 0.248), and at 2 steps the standard deviation is 0.105. Results in this range are unstable and we do not interpret them; sw falls monotonically here.
x = ancestral(dd0, z0, torch.Generator().manual_seed(4000))
print(f"DDPM ancestral, 1000 steps (seed 0): "
f"sw {sw(x, ref, dirs):.4f}, on-manifold {on_manifold(x):.3f}")
x = euler(fm0, z0, 1) # one Euler step
m, sd, dm, ds = x.mean(0), x.std(0), ref.mean(0), ref.std(0)
print(f"FM, 1 Euler step: mean ({m[0]:.3f}, {m[1]:.3f}), "
f"std ({sd[0]:.3f}, {sd[1]:.3f})")
print(f"data: mean ({dm[0]:.3f}, {dm[1]:.3f}), "
f"std ({ds[0]:.3f}, {ds[1]:.3f})")
DDPM ancestral, 1000 steps (seed 0): sw 0.0140, on-manifold 0.959
FM, 1 Euler step: mean (0.006, 0.000), std (0.036, 0.057)
data: mean (-0.011, 0.006), std (0.870, 0.492)
Stochastic 1000-step ancestral sampling (one model only, seed 0) gives sw 0.0140 and an on-manifold share of 0.959, higher than DDIM at 128 steps (0.937), at the price of 1000 network calls. The mean of the one-step flow-matching output is and its standard deviation , against a data standard deviation of : the samples really do pile up around the mean.
The widget below draws “the straightness averaged away at the crossings”, with an exact one-dimensional solution: the data is two modes at ±mu, the noise a Gaussian of the same variance. On the left, with independent pairing, the paths bend and one Euler step lands every sample on the mean, 0. On the right, with reflow pairing, the paths are the straight lines themselves and one Euler step is already exact. Drag mu for the curvature and the step count for the falling error. The page’s experiment 3 on the two-moons data closes the widget.
Conditioning and classifier-free guidance
Generation often has to follow a condition (a class, a text prompt). The earliest way to make samples “match the condition better” was classifier guidance: train a separate classifier on noisy samples and use its gradient to correct the score (Dhariwal and Nichol, 2021). Classifier-free guidance (CFG; Ho and Salimans, 2022) removes the classifier: during training the condition is replaced by a “null condition” with probability , so one network learns both the conditional prediction and the unconditional prediction ; at sampling time the two are extrapolated:
means no guidance; pushes the prediction away from the unconditional direction and amplifies “the change the condition brings”. (The paper uses ; many code bases write with , so check the convention first.) For scores, , so the extrapolation scales the gradient of “how much looks like ” by ; the paper compares it to low-temperature sampling or truncation, trading diversity for fidelity. The experiment is the same idea in two dimensions:
- the data noise is 0.2, so the two half circles overlap and the condition matters;
- during training 10% of the samples have their label replaced by the null class 2 (the paper tried 0.1, 0.2 and 0.5);
- sampling uses 64 Euler steps and guidance scales ;
- 2 training seeds, four measures:
acc(the share of samples closer to the half circle of their own class than to the other one),dist(the mean distance to the own-class half circle),std(the mean of the two coordinate standard deviations, a diversity measure) andsw(sliced Wasserstein distance to real samples of the same class); the three columns on the right are the gap between the two training seeds.
def cond_loss(net, g, bs=512): # flow matching with a class label
x1, c = moons(bs, g, 0.2) # noisier moons: classes overlap
c = torch.where(torch.rand(bs, generator=g) < 0.1, 2, c) # 10%: no label
z = torch.randn(bs, 2, generator=g)
s = torch.rand(bs, generator=g)
xs = (1 - s[:, None]) * z + s[:, None] * x1
return ((net(xs, s, c) - (x1 - z)) ** 2).mean()
@torch.no_grad()
def guided(net, z, c, w, steps=64): # v = (1 + w) v_cond - w v_uncond
x, null = z, torch.full_like(c, 2)
for i in range(steps):
s = torch.full((len(x),), i / steps)
v = (1 + w) * net(x, s, c) - w * net(x, s, null)
x = x + v / steps
return x
nets = []
for seed in range(2):
torch.manual_seed(seed)
nets.append(fit(Net(classes=2), cond_loss, 8000, 2e-3, 5000 + seed))
xr, cr = moons(40000, g, 0.2)
real = [xr[cr == k][:5000] for k in (0, 1)]
other = [xr[cr == k][5000:10000] for k in (0, 1)]
def evaluate(net, w, seed): # mean over the two classes
out = []
for k in (0, 1):
c = torch.full((5000,), k)
gz = torch.Generator().manual_seed(6000 + 10 * seed + k)
x = guided(net, torch.randn(5000, 2, generator=gz), c, w)
own = arc_dist(x, c)
acc = (own < arc_dist(x, 1 - c)).float().mean()
out.append([acc, own.mean(), x.std(0).mean(), sw(x, real[k], dirs)])
return torch.tensor(out).mean(0)
print(" " * 41 + "gap between the two seeds")
print(f"{'w':>5} {'acc':>7} {'dist':>7} {'std':>7} {'sw':>7}"
f" {'dist':>7} {'std':>7} {'sw':>7}")
acc, dist, std = [], [], []
for k in (0, 1):
c = torch.full((5000,), k)
acc.append((arc_dist(real[k], c) < arc_dist(real[k], 1 - c)).float().mean())
dist.append(arc_dist(real[k], c).mean())
std.append(real[k].std(0).mean())
floor2 = torch.tensor([sw(other[k], real[k], dirs) for k in (0, 1)]).mean()
print(f"{'real':>5} {torch.stack(acc).mean():7.3f} "
f"{torch.stack(dist).mean():7.3f} {torch.stack(std).mean():7.3f} "
f"{floor2:7.3f}")
for w in (0, 0.5, 1, 2, 4, 8):
a, b = [evaluate(n, w, i) for i, n in enumerate(nets)]
m, d = (a + b) / 2, (a - b).abs()
print(f"{w:5.1f} {m[0]:7.3f} {m[1]:7.3f} {m[2]:7.3f} {m[3]:7.3f}"
f" {d[1]:7.3f} {d[2]:7.3f} {d[3]:7.3f}")
gap between the two seeds
w acc dist std sw dist std sw
real 0.965 0.162 0.553 0.014
0.0 0.961 0.157 0.542 0.018 0.002 0.000 0.001
0.5 0.993 0.130 0.504 0.129 0.004 0.001 0.005
1.0 1.000 0.128 0.476 0.217 0.007 0.002 0.003
2.0 1.000 0.155 0.434 0.335 0.015 0.011 0.001
4.0 1.000 0.227 0.379 0.457 0.034 0.029 0.003
8.0 1.000 0.345 0.333 0.569 0.023 0.027 0.011
How to read it:
w=0reproduces the data: acc 0.961 (real data 0.965), dist 0.157 (0.162), std 0.542 (0.553), sw 0.018, close to the noise floor of 0.014.- Guidance raises fidelity: acc is 0.993 at and 1.000 at . dist is lowest at and (0.130 and 0.128, a difference below the seed gap of 0.007, so they cannot be told apart), and below the real data’s 0.162: the samples hug the half circle more tightly than real data does.
- The price is diversity and drift from the distribution: std falls monotonically with , from 0.542 to 0.333; sw rises monotonically from 0.018 to 0.569, already more than ten times the noise floor at . Guidance is not free, it changes the distribution.
- Overdo it and the samples leave the data region: dist is back to 0.155 at , equal to no guidance, and 0.227 and 0.345 at and , clearly above the real data’s 0.162 (more than twice as large at ); in the figure the samples at slide to the left end of the half circle, away from class 1, and at they pass that end and extend up and to the left, out of the data region.
- Results are less stable at large : the gap between the two seeds is at most 0.007 in dist for but 0.034 at , and the std gap grows from 0.000 at to 0.029 at . A plausible reason is that extrapolation amplifies small differences in ; this page did not test it separately. So do not treat the exact numbers at large as conclusions; the trends agree in both seeds.
- This is a toy: the classes are two half circles with no “semantics”, and the best depends on the model and the task, so do not carry elsewhere. CFG needs one more unconditional evaluation per step, doubling the sampling cost.
Latent diffusion and DiT: turn the image into tokens, then denoise
Diffusion on pixels is expensive: one 1024x1024 RGB image has 3,145,728 values and each denoising step passes all of them through the network. Latent diffusion (Rombach et al., 2021) first trains an autoencoder that compresses images into a smaller latent, diffuses and samples only in latent space, and decodes to an image at the end; conditions such as text enter the denoiser through cross-attention. Exercise 3 computes the latent sizes in code: the autoencoder of Stable Diffusion 1.x shrinks each spatial side by 8 and keeps 4 channels, so a 1024x1024 image becomes 65,536 numbers, 48 times fewer; SD3 raises the channels to 16 (Esser et al., 2024 compared 4, 8 and 16 channels and chose 16 for better reconstruction), 262,144 numbers, 12 times fewer. The price is that image quality is capped by what the autoencoder can reconstruct.
The denoiser also moved from a U-Net to a Transformer. DiT (Diffusion Transformer, Peebles and Xie, 2022) cuts the latent into patches, embeds them linearly into a token sequence, adds position encodings as in a ViT, and runs a Transformer (see the Transformer block); time and class conditions enter through adaptive layer norm (adaLN-Zero). A 256x256 image becomes a 32x32x4 latent through the autoencoder; the paper finds that more Gflops (a deeper or wider network, or more tokens) consistently give lower FID, and DiT-XL/2 reaches an FID of 2.27 on class-conditional ImageNet 256x256 (with classifier-free guidance at scale 1.5, which the paper applies to the first three latent channels only). SD3’s MM-DiT gives text tokens and image tokens separate weights and joins the two kinds of token inside attention so information flows both ways (Esser et al., 2024); the text comes from two CLIP encoders and a T5 encoder (see the notes on CLIP and T5). SD3 treats each 2x2 latent patch as one token, so a 1024x1024 image is 4096 image tokens, a sequence length comparable to an LLM with a 4K context; the quadratic cost of attention is of the same order, and exact-attention optimizations such as FlashAttention apply as well.
Beyond images: actions and text
- Robot actions. Actions are continuous, neighbouring values within a chunk are strongly correlated, and one observation often admits several valid behaviours, which regression would average. Diffusion Policy (Chi et al., 2023) writes the policy as a conditional denoising diffusion model over the observation and generates a short sequence of future actions at once (paper note). π0 adds an action expert that generates action chunks by flow matching next to a pretrained vision-language model, producing 50 steps at a time with 10 Euler integration steps at inference (paper note); the action head of GR00T N1 is a diffusion Transformer trained with flow matching that produces 16 steps at a time (paper note). Every integration step is a network call that counts toward control latency, so “steps for quality” is a real budget question here, and the experiments above are its miniature.
- Text. Text is discrete and cannot simply be given Gaussian noise. LLaDA (Nie et al., 2025) uses masked diffusion: the forward process independently replaces each token with a mask with probability , drawn uniformly from ; a Transformer without a causal mask is trained to predict the masked tokens; generation starts from all masks, predicts every masked position at once at each step, and re-masks the positions with the lowest confidence. This is close to BERT’s masked language modeling, except that the masking ratio varies randomly and the model can generate. The paper reports that the 8B LLaDA is competitive with LLaMA3 8B in in-context learning and says it mitigates the “reversal curse”: it beats GPT-4o on a reversal poem completion task. The price is that bidirectional attention keeps the standard causal KV cache from being reused directly, because the representations of earlier positions change as later positions are unmasked, so the inference system needs another approach.
Practical notes and common pitfalls
| Symptom | Common cause | What to do |
|---|---|---|
| Samples are a blur, or all near the mean, at 1 to 4 steps | A single step predicts only the conditional mean (one flow-matching step equals the data mean); DDIM’s single step amplifies the error of the noise estimate by | Use reflow, progressive distillation or consistency models; do not demand one-step generation from an undistilled model |
| Doubling the steps barely moves the metric | You are on the plateau of model error or metric noise | Measure the noise floor and the seed standard deviation first, and stop at the plateau |
| Samples too uniform, or outside the data region, at a large guidance scale | Extrapolation amplifies the difference and changes the distribution | Scan on a validation set, looking at fidelity and diversity together, and rerun large- results with other seeds |
| The first long stretch of sampling barely changes the result | The linear schedule drops the SNR very low too early (about a third of this page’s 1000 steps have ) | Use a cosine schedule or importance-sample (SD3 favours perceptually relevant noise levels) |
| Image quality is capped | Diffusion can only produce what the autoencoder can represent | Use an autoencoder with better reconstruction (more channels) and evaluate its reconstruction on its own first |
| Code reuse comes out backwards | In diffusion a larger is noisier, in flow matching is noise; v-prediction and the flow-matching velocity are different quantities | Write down the path and the time convention before swapping parameterizations or samplers |
Summary and exercises
- Diffusion and flow matching are both “a known path plus regression”: the forward path is fixed and needs no learning, the network only regresses noise, score or velocity along it with a plain mean squared error, and generation follows the learned direction from noise back to data.
- Parameterizations differ by algebra and loss weights; DDPM’s ancestral sampler is stochastic, while DDIM and flow matching’s Euler solver are deterministic ODE samplers.
- Steps are compute that buys quality, but one-step generation needs special treatment: unmodified flow matching collapses to the data mean in one step, DDIM amplifies the error of the noise estimate; reflow, distillation and consistency models straighten or compress the trajectories.
- CFG buys fidelity with an extra network call, at the price of diversity and drift from the distribution, and there is no universal best .
- Images use latent space plus DiT to cut cost; actions use flow matching for high-rate continuous outputs; text needs discrete masked diffusion.
Quick self-check
1. What does the closed form do for training?
- It lets the network output the clean sample directly
- Any can be picked and built in one go, with no need to walk steps
- It guarantees that sampling takes one step
- It turns DDIM into a stochastic sampler
The closed form gives every training sample at any noise level with one forward pass, so the cost of training does not depend on . What to predict and how many steps to sample are separate choices.
2. In this page’s experiment, why do the samples of one Euler step of flow matching without reflow pile up in a blob?
- The network is too small
- The learning rate is too large
- At the input carries no information about , the optimal velocity is , and one full step lands exactly on the data mean
- Euler is always inaccurate on straight trajectories
One Euler step gives , the same point for every . In the experiment the mean of the output is and its standard deviation only , while the data standard deviation is .
3. Which statements about this page’s CFG experiment are correct? (multiple choice)
- From to the diversity
stdfalls monotonically, from 0.542 to 0.333 - The larger is, the closer the samples are to the data manifold
- At
accreaches 1.000, butswis 0.217, far above 0.018 without guidance - CFG does not add network calls at sampling time
At
distis 0.345, more than twice the unguided 0.157, so the samples leave the data region; CFG needs a conditional and an unconditional prediction at every step.
4. How does DDIM differ from DDPM ancestral sampling?
- DDIM needs to retrain the network with another loss
- DDIM must use exactly the 1000 training steps
- DDIM is another name for flow matching
- DDIM () drops the random term, is deterministic, can skip steps, and reuses the same trained network
The DDIM paper keeps the training objective and changes only the sampling: the same noise always gives the same sample, and the number of steps can be far below the training steps.
5. With 8x spatial downsampling and 4 channels, how many values does a 1024x1024x3 image have in Stable Diffusion 1.x’s latent space?
- 4,096
- 65,536
- 262,144
- 3,145,728
, 48 times fewer than the 3,145,728 pixel values. 262,144 is SD3’s 16 channels, and 4096 is the token count after SD3 cuts the latent into 2x2 patches.
Exercises
- Prove that .
- With this page’s linear schedule, at which step does first drop below 0.5? What share of the steps has , and what share ? Does this match Nichol and Dhariwal’s remark that “the last quarter is almost pure noise”?
- For a 1024x1024 image, how many latent values do the autoencoders of SD1.x (8x downsampling, 4 channels) and SD3 (8x downsampling, 16 channels) produce? SD3 treats each 2x2 latent patch as one token; how many image tokens is that?
- Why is the on-manifold share of the reflow model at 128 steps (0.953) lower than that of the original flow-matching model (0.966)? How would you test your explanation?
- In CFG training, what happens at sampling time if the label is never replaced by the null class?
Reference answers
1. and ; subtracting gives . Taking squared norms, , and rearranging finishes the proof.
2. SNR below 1 is equivalent to .
ab = abar[1:]
t_half = int((ab > 0.5).sum()) + 1
print(f"abar_t first drops below 0.5 (SNR < 1) at t = {t_half}")
for thr in (0.01, 0.001):
print(f"share of steps t with abar_t < {thr}: "
f"{(ab < thr).float().mean():.3f}")
abar_t first drops below 0.5 (SNR < 1) at t = 260
share of steps t with abar_t < 0.01: 0.327
share of steps t with abar_t < 0.001: 0.175
From step 260 on the SNR is below 1; about a third of the steps have (signal coefficient below 0.1) and about a sixth have it below 0.001. This agrees with Nichol and Dhariwal’s observation: the tail of the linear schedule is almost pure noise, and the network’s work there contributes little to sample quality (they also found that a model trained with the linear schedule does not get much worse in FID when up to 20% of the reverse process is skipped at its start, the noisiest stretch).
3.
H = W = 1024
for name, d in (("Stable Diffusion 1.x, 4 channels", 4),
("Stable Diffusion 3, 16 channels", 16)):
lat = (H // 8) * (W // 8) * d
print(f"{name}: {3 * H * W} pixel values -> {lat} latent values "
f"({3 * H * W / lat:.0f}x fewer), {(H // 16) * (W // 16)} tokens "
f"at patch size 2")
Stable Diffusion 1.x, 4 channels: 3145728 pixel values -> 65536 latent values (48x fewer), 4096 tokens at patch size 2
Stable Diffusion 3, 16 channels: 3145728 pixel values -> 262144 latent values (12x fewer), 4096 tokens at patch size 2
SD1.x gives 65,536 values (48 times fewer), SD3 gives 262,144 (12 times fewer), and SD3 has 4096 image tokens.
4. One explanation: reflow’s training data are the previous model’s own samples, which carry the previous model’s errors, so when many steps are allowed the second model approximates “the previous model’s output distribution” rather than the real data. Ways to test it: (a) reflow from a better previous model (more steps, more training) and see whether the plateau moves up; (b) compare the samples of the reflow model and the previous model at 128 steps directly and see whether the first copies the biases of the second; (c) add seeds and confirm that the gap between 0.953 and 0.966 (seed standard deviations of about 0.001 to 0.002) is stable.
5. The network never sees the null class, so the embedding of class 2 stays at its random initialization, the output of the unconditional branch is arbitrary, the extrapolation direction in is meaningless, and for the samples are pushed to unpredictable places. Dropping the condition at random during training is exactly what teaches one network “the denoising direction when there is no condition”.
Further reading
- Ho, Jain, Abbeel. Denoising Diffusion Probabilistic Models (DDPM, 2020); the paper note on this site.
- Song, Meng, Ermon. Denoising Diffusion Implicit Models (DDIM, 2020).
- Song et al. Score-Based Generative Modeling through Stochastic Differential Equations (2020): the continuous-time view and the probability flow ODE.
- Nichol, Dhariwal. Improved Denoising Diffusion Probabilistic Models (2021): the cosine schedule and learned variances.
- Karras et al. Elucidating the Design Space of Diffusion-Based Generative Models (EDM, 2022): pulls the design choices of diffusion models apart so they can be compared.
- Lipman et al. Flow Matching for Generative Modeling (2022); the paper note on this site.
- Liu, Gong, Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow (2022): reflow.
- Salimans, Ho. Progressive Distillation for Fast Sampling of Diffusion Models (2022): v-prediction and progressive distillation.
- Song et al. Consistency Models (2023): one-step generation.
- Ho, Salimans. Classifier-Free Diffusion Guidance (2022).
- Rombach et al. High-Resolution Image Synthesis with Latent Diffusion Models (2021).
- Peebles, Xie. Scalable Diffusion Models with Transformers (DiT, 2022).
- Esser et al. Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Stable Diffusion 3, 2024).
- Nie et al. Large Language Diffusion Models (LLaDA, 2025).
- On this site: Diffusion Policy, π0 and GR00T N1 apply the method to robot actions.
FAQ
- What is the difference between diffusion models and flow matching?
- Both define a path from noise to data, train a network to regress some quantity along that path, and generate by following the network's direction back to the data. They differ in four choices: the path (DDPM uses a curved, variance-preserving path, flow matching usually a straight line between noise and data), what the network predicts (noise or velocity), the sampler (stochastic ancestral sampling or a deterministic ODE) and the loss weighting; for Gaussian paths, switching parameterization is just algebra. In this page's experiment, with the same small network and training budget, flow matching with Euler steps puts 0.883 of its samples on the data manifold at 8 steps, DDIM only 0.512. That compares two recipes, not paths, so it does not prove that the path itself is better.
- Why do diffusion models need many sampling steps, and how can the number be reduced?
- Each step only estimates the denoising direction at the current noise level, and the trajectory from pure noise to a clean sample is curved, so it takes many small steps to follow. There are three ways to cut the count: a better solver (DDIM, higher-order ODE solvers), straightening the trajectories (reflow), and distilling a many-step model into a few-step one (progressive distillation, consistency models). In this page's experiment, one Euler step of flow matching without reflow puts every sample near the data mean (sw 0.562), while the same model after reflow reaches sw 0.020 in one step, close to the noise floor of 0.011.
- What is classifier-free guidance (CFG), and how do I choose the guidance scale?
- CFG (Ho and Salimans, 2022) randomly drops the condition during training so that one network learns both the conditional and the unconditional prediction, then extrapolates at sampling time to (1+w) times the conditional prediction minus w times the unconditional one. A larger w follows the condition more closely and gives less varied samples that drift further from the data distribution, and every step needs one extra unconditional evaluation. There is no universal best value, so scan it on a validation set and look at fidelity and diversity together. In this page's 2-D experiment, raising w from 0 to 1 lifts class accuracy from 0.961 to 1.000, lowers diversity (standard deviation) from 0.542 to 0.476 and raises the distance sw to the real distribution from 0.018 to 0.217.
- Why do image diffusion models work in a latent space?
- Pixel space is large: one 1024x1024 RGB image has 3,145,728 values and every denoising step passes all of them through the network. Latent diffusion (Rombach et al., 2021) first compresses images with a pretrained autoencoder, diffuses only in the latent space and decodes at the end. With 8x spatial downsampling, the 4-channel latent of Stable Diffusion 1.x has 65,536 values, 48 times fewer; SD3 uses 16 channels, 262,144 values, 12 times fewer. The price is that image quality is capped by what the autoencoder can reconstruct.
- Can diffusion models generate text, and how do they compare with autoregressive LLMs?
- Yes, with a discrete variant. LLaDA (Nie et al., 2025) randomly replaces tokens with a mask in the forward process, trains a bidirectional Transformer to predict the masked tokens, and generates by starting from all masks and unmasking over several steps, re-masking low-confidence positions each time. The paper reports that the 8B LLaDA is competitive with LLaMA3 8B in in-context learning and beats GPT-4o on a reversal poem completion task. But bidirectional attention means the standard causal KV cache cannot be reused directly, because the representations of earlier positions change as later positions are unmasked.