# 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.

- URL: https://dmxsf.com/en/wiki/multimodal/diffusion-and-flow-matching/
- [DMXSF](https://dmxsf.com/en/about/)
- Advanced
- Updated: 2026-11-26
- Tags: Diffusion models, Multimodal, Vision models

## 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).

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](https://dmxsf.com/en/wiki/foundations/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 $x_0$ 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: $x_t=\sqrt{1-\beta_t}\,x_{t-1}+\sqrt{\beta_t}\,\epsilon_t$ with $\epsilon_t\sim\mathcal N(0,I)$. Let $\alpha_t=1-\beta_t$ and $\bar\alpha_t=\prod_{s=1}^{t}\alpha_s$. Gaussians are closed under addition, so $t$ steps collapse into a closed form:

*Figure: Generation follows a reverse process: start from random noise, then predict and remove the perturbation associated with each noise level.*

*Figure: Generation follows a reverse process: start from random noise, then predict and remove the perturbation associated with each noise level.*

$$
x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon,\qquad \epsilon\sim\mathcal N(0,I)
$$

This equation shapes training: **there is no need to walk $t$ steps, pick any $t$ and build $x_t$ in one go**. The signal-to-noise ratio $\mathrm{SNR}(t)=\bar\alpha_t/(1-\bar\alpha_t)$ compares signal and noise; at 1 they are equally large. DDPM uses $T=1000$ steps with $\beta_t$ rising linearly from $10^{-4}$ to $0.02$ (Ho et al., 2020).

*Figure: The same 300 points (blue and amber are the two classes) noised with the closed form of the forward process, x_t = √ᾱ_t·x_0 + √(1−ᾱ_t)·ε, with one fixed ε per point across the five panels; β grows linearly from 1e-4 to 0.02, T=1000, and ᾱ_t is the product of (1−β_s) for s=1..t. The axis range is fixed to −3..3 and points outside it are not drawn.*

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 $x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon$ toward their own fixed noise; switch between the linear and the cosine schedule to see how the fall of $\bar\alpha_t$ differs.

### Experiment 1: does the closed form match step-by-step noising

Copy the point $(0.8,-0.3)$ 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 $\sqrt{\bar\alpha_t}\cdot0.8$ and $\sqrt{1-\bar\alpha_t}$. 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.

```python
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
```

```python
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}")
```

```text
    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 $t=1000$ is within the error. At $t=1000$ the signal coefficient $\sqrt{\bar\alpha_T}$ is only 0.0064 and the SNR is $-43.94$ dB: the original point is completely drowned, and $x_T$ 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 $\epsilon_\theta(x_t,t)$ takes three steps: draw a data point $x_0$, a step $t$ and a noise $\epsilon$, build $x_t$ with the closed form, and ask the network to predict $\epsilon$. DDPM's simplified loss is an unweighted mean squared error:

$$
L_{\text{simple}}=\mathbb E_{x_0,\,t,\,\epsilon}\,\big\lVert\epsilon-\epsilon_\theta(x_t,t)\big\rVert^2
$$

**Why does predicting noise generate anything?** The mean-squared-error optimum is the conditional expectation $\mathbb E[\epsilon\mid x_t]$. On the other hand, the score $\nabla\log p_t(x_t)$ of the marginal $p_t$ of $x_t$ (the direction in which density rises fastest) satisfies

$$
\nabla_{x_t}\log p_t(x_t)=\mathbb E\big[\nabla_{x_t}\log p(x_t\mid x_0)\,\big|\,x_t\big]=-\frac{\mathbb E[\epsilon\mid x_t]}{\sqrt{1-\bar\alpha_t}}
$$

so the optimal noise prediction is the score times $-\sqrt{1-\bar\alpha_t}$. 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 $N(0,0.8^2)$, $x_t\sim N(0,\bar\alpha_t\cdot0.8^2+1-\bar\alpha_t)$, the score has a closed form, and the optimal noise prediction is a linear function of $x_t$. The code fits the slope of $\epsilon\approx k\,x_t$ by least squares from samples and compares it with the slope given by $-\sqrt{1-\bar\alpha_t}\cdot$score.

```python
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}")
```

```text
    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 $t$. The two ends also show how hard the task is: at $t=10$ the slope is only 0.0685 (the noise is tiny, $x_t$ is almost the data, and the noise is nearly impossible to guess from $x_t$), and at $t=600$ it is close to 1 ($x_t$ is almost pure noise, $\epsilon\approx x_t$).

### One quantity, several parameterizations

The network can predict other things. For $x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon$, given $x_t$ and $t$ the quantities below differ from one another by algebra only:

| Network output | Training target | Recover the clean sample $\hat x_0$ | Note |
| --- | --- | --- | --- |
| Noise $\hat\epsilon$ | $\epsilon$ | $\hat x_0=(x_t-\sqrt{1-\bar\alpha_t}\,\hat\epsilon)/\sqrt{\bar\alpha_t}$ | DDPM's default |
| Clean sample $\hat x_0$ | $x_0$ | Output directly | Differs from noise prediction only by a weight that depends on $t$ |
| Score $\hat s$ | $-\epsilon/\sqrt{1-\bar\alpha_t}$ | $\hat x_0=(x_t+(1-\bar\alpha_t)\,\hat s)/\sqrt{\bar\alpha_t}$ | The score-model literature's form |
| Velocity $\hat v$ | $\sqrt{\bar\alpha_t}\,\epsilon-\sqrt{1-\bar\alpha_t}\,x_0$ | $\hat x_0=\sqrt{\bar\alpha_t}\,x_t-\sqrt{1-\bar\alpha_t}\,\hat v$ | 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 $x_0-\hat x_0=\frac{\sqrt{1-\bar\alpha_t}}{\sqrt{\bar\alpha_t}}(\hat\epsilon-\epsilon)$ we get

$$
\lVert\epsilon-\hat\epsilon\rVert^2=\mathrm{SNR}(t)\,\lVert x_0-\hat x_0\rVert^2
$$

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 $\sin(\pi 2^k s),\cos(\pi 2^k s)$ of the time $s\in[0,1]$ ($k=0,\dots,5$), and an optional class embedding. Training is Adam with a cosine learning-rate decay, 8000 steps, batch size 512, learning rate $2\times10^{-3}$. The network has only 135,938 parameters, and the whole page's code runs end to end in about three minutes on this machine.

```python
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())}")
```

```text
parameters: 135938
```

```python
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 $\epsilon_\theta$ to generate? Two samplers are common.

**DDPM ancestral sampling** starts from $x_T\sim\mathcal N(0,I)$; every step denoises with the network's noise estimate and then adds a little fresh random noise (variance $\beta_t$; Ho et al. report similar results with the posterior variance):

$$
x_{t-1}=\frac{1}{\sqrt{\alpha_t}}\Big(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\hat\epsilon\Big)+\sqrt{\beta_t}\,z,\qquad z\sim\mathcal N(0,I)
$$

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 $\eta=0$) and may skip many steps at once (Song et al., 2020). It first recovers an estimate $\hat x_0$ of the clean sample from the current noise estimate, then re-noises it with the same $\hat\epsilon$ to a smaller noise level $t'$:

$$
\begin{aligned}
\hat x_0&=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\hat\epsilon}{\sqrt{\bar\alpha_t}}\\
x_{t'}&=\sqrt{\bar\alpha_{t'}}\,\hat x_0+\sqrt{1-\bar\alpha_{t'}}\,\hat\epsilon
\end{aligned}
$$

With no random term, the same noise always gives the same sample, and $t'$ can be much smaller than $t$, 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**.

```python
@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 $z$, data $x_1$) and join them with a straight line:

$$
x_s=(1-s)\,z+s\,x_1,\qquad \frac{dx_s}{ds}=x_1-z,\qquad s\in[0,1]
$$

$s=0$ is noise and $s=1$ is data, the opposite direction to diffusion's "larger $t$ is noisier". The velocity along this line is the constant $x_1-z$, and the network $v_\theta(x,s)$ regresses it:

$$
L_{\text{FM}}=\mathbb E_{z,\,x_1,\,s}\,\big\lVert v_\theta(x_s,s)-(x_1-z)\big\rVert^2
$$

To generate, start from noise at $s=0$ and solve the ODE $dx/ds=v_\theta(x,s)$ up to $s=1$. The simplest solver, Euler, cuts the interval into $N$ pieces: $x\leftarrow x+v_\theta(x,s)/N$.

During training one position $x_s$ is crossed by many different (noise, data) pairs, so the network learns the **conditional mean** of their velocities, $v^*(x,s)=\mathbb E[x_1-z\mid x_s=x]$, and this marginal velocity field carries the noise distribution onto the data distribution (Lipman et al., 2022; details in the [flow matching paper note](https://dmxsf.com/en/blog/flow-matching-for-generative-modeling/)). Because it is a conditional mean, the trajectories are no longer straight: the lines are averaged where they cross.

```python
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", $x=\alpha(s)\,x_{\text{data}}+\sigma(s)\,\epsilon$. 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 | $\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon$, larger $t$ is noisier | $(1-s)\,z+s\,x_1$, larger $s$ is closer to data |
| Network predicts | Noise $\epsilon$ | Velocity $x_1-z$ |
| Sampler | Stochastic ancestral sampling; deterministic DDIM | Deterministic ODE, Euler |
| Time input of the network | $t/T$ | $s$ |

**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.

```python
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}")
```

```text
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 $z$ along the ODE to endpoints $x_1'$, treats ($z$, $x_1'$) 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 $\epsilon$ 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 $10^{-3}$). All three use the same noise and sample 10,000 points with 1 to 128 network evaluations (NFE).

```python
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))
```

```text
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
```

*Figure: Samples from the seed-0 models trained in the steps block above: all three models use the same noise, and the first 250 points are drawn. The reflow model is fine-tuned from the flow-matching model on its own ODE endpoint pairs. The in-view share in the one-step DDIM panel is counted over all 10,000 samples. This is one concrete draw; the numbers are in the next figure and the tables above.*

*Figure: Data from the steps output above: each point is the mean of 3 training seeds and the vertical bars are ±1 standard deviation; the grey band is the noise floor of sw (a fresh real set against the reference, mean ± standard deviation). The three curves are different path-plus-sampler combinations, not a controlled comparison of diffusion and flow matching; the task is 2-D toy data.*

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 $\hat x_0=(z-\sqrt{1-\bar\alpha_T}\,\hat\epsilon)/\sqrt{\bar\alpha_T}$, so the error of the noise estimate is amplified by $1/\sqrt{\bar\alpha_T}=157.4$, and when the single step lands on $\bar\alpha_0=1$ the output is exactly this amplified $\hat x_0$. 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 $s=0$, $x_s=z$ carries no information about $x_1$, the optimal velocity is $v^*(z,0)=\mathbb E[x_1]-z$, and one Euler step lands on $z+v^*=\mathbb E[x_1]$: the same point for every $z$, the data mean. The `extras` block 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.

```python
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})")
```

```text
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 $(0.006,0.000)$ and its standard deviation $(0.036,0.057)$, against a data standard deviation of $(0.870,0.492)$: 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 $c$ (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 $p_{\text{uncond}}$, so one network learns both the conditional prediction $v_c$ and the unconditional prediction $v_u$; at sampling time the two are extrapolated:

$$
\tilde v=(1+w)\,v_c-w\,v_u=v_u+(1+w)\,(v_c-v_u)
$$

$w=0$ means no guidance; $w>0$ pushes the prediction away from the unconditional direction and amplifies "the change the condition brings". (The paper uses $(1+w)\epsilon_c-w\epsilon_u$; many code bases write $s\,v_c-(s-1)\,v_u$ with $s=1+w$, so check the convention first.) For scores, $\nabla\log p(x\mid c)=\nabla\log p(x)+\nabla\log p(c\mid x)$, so the extrapolation scales the gradient of "how much $x$ looks like $c$" by $(1+w)$; 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 $w\in\{0,0.5,1,2,4,8\}$;
- 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) and `sw` (sliced Wasserstein distance to real samples of the same class); the three columns on the right are the gap between the two training seeds.

```python
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}")
```

```text
                                         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
```

*Figure: Samples from the seed-0 model trained in the cfg block above, class 0, with the same noise in every panel. The table averages two classes and two training seeds; only one of them is drawn here. The grey lines are the noise-free centre lines of class 0 (upper half circle) and class 1 (lower half circle); the stronger the guidance, the more the samples are pushed to where they look most like class 0, the end farthest from class 1, and beyond the range of the data itself.*

How to read it:

- **`w=0` reproduces 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 $w=0.5$ and 1.000 at $w=1$. dist is lowest at $w=0.5$ and $w=1$ (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 $w$, from 0.542 to 0.333; sw rises monotonically from 0.018 to 0.569, already more than ten times the noise floor at $w=1$. Guidance is not free, it changes the distribution.
- **Overdo it and the samples leave the data region**: dist is back to 0.155 at $w=2$, equal to no guidance, and 0.227 and 0.345 at $w=4$ and $w=8$, clearly above the real data's 0.162 (more than twice as large at $w=8$); in the figure the samples at $w=4$ slide to the left end of the half circle, away from class 1, and at $w=8$ they pass that end and extend up and to the left, out of the data region.
- **Results are less stable at large $w$**: the gap between the two seeds is at most 0.007 in dist for $w\le1$ but 0.034 at $w=4$, and the std gap grows from 0.000 at $w=0$ to 0.029 at $w=4$. A plausible reason is that extrapolation amplifies small differences in $v_c-v_u$; this page did not test it separately. So do not treat the exact numbers at large $w$ as conclusions; the trends agree in both seeds.
- **This is a toy**: the classes are two half circles with no "semantics", and the best $w$ depends on the model and the task, so do not carry $w=1$ 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 $p\times p$ patches, embeds them linearly into a token sequence, adds position encodings as in a [ViT](https://dmxsf.com/en/blog/vit-an-image-is-worth-16x16-words/), and runs a Transformer (see the [Transformer block](https://dmxsf.com/en/wiki/architecture/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](https://dmxsf.com/en/blog/clip-learning-transferable-visual-models/) and [T5](https://dmxsf.com/en/blog/t5-exploring-the-limits-of-transfer-learning/)). 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](https://dmxsf.com/en/blog/diffusion-policy-visuomotor-policy-learning-via-action-diffusion/)). π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](https://dmxsf.com/en/blog/pi0-a-vision-language-action-flow-model-for-general-robot-control/)); the action head of GR00T N1 is a diffusion Transformer trained with flow matching that produces 16 steps at a time ([paper note](https://dmxsf.com/en/blog/gr00t-n1-an-open-foundation-model-for-generalist-humanoid-robots/)). 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 $t$, drawn uniformly from $[0,1]$; 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 $1/\sqrt{\bar\alpha_T}$ | 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 $v_c-v_u$ and changes the distribution | Scan $w$ on a validation set, looking at fidelity and diversity together, and rerun large-$w$ 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 $\bar\alpha_t<0.01$) | Use a cosine schedule or importance-sample $t$ (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 $t$ is noisier, in flow matching $s=0$ 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 $w$.
- 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 $x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon$ do for training?**

- [ ] It lets the network output the clean sample $x_0$ directly
- [x] Any $t$ can be picked and $x_t$ built in one go, with no need to walk $t$ steps
- [ ] It guarantees that sampling takes one step
- [ ] It turns DDIM into a stochastic sampler

> The closed form gives every training sample $x_t$ at any noise level with one forward pass, so the cost of training does not depend on $T$. 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
- [x] At $s=0$ the input $z$ carries no information about $x_1$, the optimal velocity is $\mathbb E[x_1]-z$, and one full step lands exactly on the data mean
- [ ] Euler is always inaccurate on straight trajectories

> One Euler step gives $z+v^*(z,0)=\mathbb E[x_1]$, the same point for every $z$. In the experiment the mean of the output is $(0.006,0.000)$ and its standard deviation only $(0.036,0.057)$, while the data standard deviation is $(0.870,0.492)$.

**3. Which statements about this page's CFG experiment are correct? (multiple choice)**

- [x] From $w=0$ to $w=8$ the diversity `std` falls monotonically, from 0.542 to 0.333
- [ ] The larger $w$ is, the closer the samples are to the data manifold
- [x] At $w=1$ `acc` reaches 1.000, but `sw` is 0.217, far above 0.018 without guidance
- [ ] CFG does not add network calls at sampling time

> At $w=8$ `dist` is 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
- [x] DDIM ($\eta=0$) 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
- [x] 65,536
- [ ] 262,144
- [ ] 3,145,728

> $(1024/8)^2\times4=65{,}536$, 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

1. Prove that $\lVert\epsilon-\hat\epsilon\rVert^2=\mathrm{SNR}(t)\,\lVert x_0-\hat x_0\rVert^2$.
2. With this page's linear schedule, at which step does $\bar\alpha_t$ first drop below 0.5? What share of the steps has $\bar\alpha_t<0.01$, and what share $\bar\alpha_t<0.001$? Does this match Nichol and Dhariwal's remark that "the last quarter is almost pure noise"?
3. 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?
4. 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?
5. In CFG training, what happens at sampling time if the label is never replaced by the null class?

<details>
<summary>Reference answers</summary>

**1.** $\hat x_0=(x_t-\sqrt{1-\bar\alpha_t}\,\hat\epsilon)/\sqrt{\bar\alpha_t}$ and $x_0=(x_t-\sqrt{1-\bar\alpha_t}\,\epsilon)/\sqrt{\bar\alpha_t}$; subtracting gives $x_0-\hat x_0=\frac{\sqrt{1-\bar\alpha_t}}{\sqrt{\bar\alpha_t}}(\hat\epsilon-\epsilon)$. Taking squared norms, $\lVert x_0-\hat x_0\rVert^2=\frac{1-\bar\alpha_t}{\bar\alpha_t}\lVert\epsilon-\hat\epsilon\rVert^2=\lVert\epsilon-\hat\epsilon\rVert^2/\mathrm{SNR}(t)$, and rearranging finishes the proof.

**2.** SNR below 1 is equivalent to $\bar\alpha_t<0.5$.

```python
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}")
```

```text
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 $\bar\alpha_t<0.01$ (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.**

```python
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")
```

```text
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 $v_u$ is arbitrary, the extrapolation direction in $(1+w)v_c-wv_u$ is meaningless, and for $w>0$ 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".

</details>

## Further reading

- Ho, Jain, Abbeel. [Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239) (DDPM, 2020); the [paper note](https://dmxsf.com/en/blog/ddpm-denoising-diffusion-probabilistic-models/) on this site.
- Song, Meng, Ermon. [Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502) (DDIM, 2020).
- Song et al. [Score-Based Generative Modeling through Stochastic Differential Equations](https://arxiv.org/abs/2011.13456) (2020): the continuous-time view and the probability flow ODE.
- Nichol, Dhariwal. [Improved Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2102.09672) (2021): the cosine schedule and learned variances.
- Karras et al. [Elucidating the Design Space of Diffusion-Based Generative Models](https://arxiv.org/abs/2206.00364) (EDM, 2022): pulls the design choices of diffusion models apart so they can be compared.
- Lipman et al. [Flow Matching for Generative Modeling](https://arxiv.org/abs/2210.02747) (2022); the [paper note](https://dmxsf.com/en/blog/flow-matching-for-generative-modeling/) on this site.
- Liu, Gong, Liu. [Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow](https://arxiv.org/abs/2209.03003) (2022): reflow.
- Salimans, Ho. [Progressive Distillation for Fast Sampling of Diffusion Models](https://arxiv.org/abs/2202.00512) (2022): v-prediction and progressive distillation.
- Song et al. [Consistency Models](https://arxiv.org/abs/2303.01469) (2023): one-step generation.
- Ho, Salimans. [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598) (2022).
- Rombach et al. [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) (2021).
- Peebles, Xie. [Scalable Diffusion Models with Transformers](https://arxiv.org/abs/2212.09748) (DiT, 2022).
- Esser et al. [Scaling Rectified Flow Transformers for High-Resolution Image Synthesis](https://arxiv.org/abs/2403.03206) (Stable Diffusion 3, 2024).
- Nie et al. [Large Language Diffusion Models](https://arxiv.org/abs/2502.09992) (LLaDA, 2025).
- On this site: [Diffusion Policy](https://dmxsf.com/en/blog/diffusion-policy-visuomotor-policy-learning-via-action-diffusion/), [π0](https://dmxsf.com/en/blog/pi0-a-vision-language-action-flow-model-for-general-robot-control/) and [GR00T N1](https://dmxsf.com/en/blog/gr00t-n1-an-open-foundation-model-for-generalist-humanoid-robots/) apply the method to robot actions.

## Companion code

[Diffusion and flow matching: verify a Gaussian path](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/diffusion-and-flow-matching): Measure the forward diffusion variance and integrate a simple analytic flow, checking how Euler error changes with step count.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run multimodal/diffusion-and-flow-matching`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/diffusion-and-flow-matching/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/diffusion-and-flow-matching/README.en.md)
- [`diffusion_flow.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/multimodal/diffusion_flow.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#diffusion-and-flow-matching)

## 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.
