Paper notes

Flow Matching: Regress a Fixed Path's Vector Field and Train Continuous Normalizing Flows Without Simulation

Flow Matching (Lipman et al., 2022) turns generative modeling into regression: pick a probability path from noise to data, regress its vector field, and never solve an ODE in training. Gaussian paths include diffusion, and OT paths are another choice. Code compares both on a 2D checkerboard.

Published Updated 19 min read

On this page
  1. Why this paper matters
  2. Method
  3. Experiments and findings
  4. Checking it with code
  5. Limitations and what to keep in mind
  6. What to take from this paper
  7. Further reading
  8. FAQ

Why this paper matters

Diffusion models generate by adding noise step by step and learning to remove it; their paths are confined to a few diffusion processes, which tends to mean very long training and specialized samplers to save steps. Continuous Normalizing Flows (CNFs; Chen et al., 2018) take another view: an ODE ddtϕt(x)=vt(ϕt(x))\frac{d}{dt}\phi_t(x)=v_t(\phi_t(x)) transports a simple distribution such as a standard Gaussian into the data distribution; in principle it can represent any probability path, diffusion paths included. But no scalable way to train them existed: maximum likelihood needs numerical ODE solves during training, and other simulation-free methods either involve intractable integrals or have biased gradients.

Flow Matching (Lipman et al., Meta AI and the Weizmann Institute, October 2022) proposes a simulation-free training framework: fix a probability path from noise to data, then regress the vector field that generates it. The key trick is to replace an intractable objective by a per-sample “conditional” one with the same gradient.

Method

The Flow Matching objective. Let ptp_t be a probability path from p0=N(0,I)p_0=\mathcal N(0,I) to an approximation of the data distribution and utu_t the vector field that generates it. The Flow Matching (FM) objective is

LFM(θ)=Et, pt(x)∥vt(x)−ut(x)∥2L_{FM}(\theta)=\mathbb E_{t,\,p_t(x)}\big\|v_t(x)-u_t(x)\big\|^2

but neither ptp_t nor utu_t is known, so it cannot be used directly.

Conditional Flow Matching (CFM). For each data point x1x_1 define a conditional probability path pt(x∣x1)p_t(x\mid x_1) (the noise distribution at t=0t=0, concentrated near x1x_1 at t=1t=1) and the conditional vector field ut(x∣x1)u_t(x\mid x_1) that generates it. The marginal path pt(x)=∫pt(x∣x1)q(x1)dx1p_t(x)=\int p_t(x\mid x_1)q(x_1)dx_1 is their mixture. The CFM objective is

LCFM(θ)=Et, q(x1), pt(x∣x1)∥vt(x)−ut(x∣x1)∥2L_{CFM}(\theta)=\mathbb E_{t,\,q(x_1),\,p_t(x\mid x_1)}\big\|v_t(x)-u_t(x\mid x_1)\big\|^2

Theorem 2 of the paper says LCFML_{CFM} and LFML_{FM} differ only by a constant independent of θ\theta, so their gradients are identical. It is enough to be able to sample pt(x∣x1)p_t(x\mid x_1) and compute ut(x∣x1)u_t(x\mid x_1) to train without bias; the marginal path and the marginal vector field are never needed.

Gaussian paths. With pt(x∣x1)=N(μt(x1),σt(x1)2I)p_t(x\mid x_1)=\mathcal N\big(\mu_t(x_1),\sigma_t(x_1)^2I\big), the generating vector field is (Theorem 3)

ut(x∣x1)=σt′(x1)σt(x1)(x−μt(x1))+μt′(x1)u_t(x\mid x_1)=\frac{\sigma_t'(x_1)}{\sigma_t(x_1)}\big(x-\mu_t(x_1)\big)+\mu_t'(x_1)
  • Diffusion path (VP). μt=α1−tx1\mu_t=\alpha_{1-t}x_1 and σt=1−α1−t2\sigma_t=\sqrt{1-\alpha_{1-t}^2} with αs=exp⁡(−12∫0sβ(r)dr)\alpha_s=\exp(-\tfrac12\int_0^s\beta(r)dr); the paper takes β\beta rising linearly from 0.1 to 20.
  • Optimal-transport (OT) path. Let the mean and the standard deviation change linearly: μt=t x1\mu_t=t\,x_1 and σt=1−(1−σmin)t\sigma_t=1-(1-\sigma_{min})t. The flow is ψt(x0)=(1−(1−σmin)t) x0+t x1\psi_t(x_0)=(1-(1-\sigma_{min})t)\,x_0+t\,x_1, and the CFM loss becomes
LCFM(θ)=Et, x1, x0∥vt(ψt(x0))−(x1−(1−σmin)x0)∥2L_{CFM}(\theta)=\mathbb E_{t,\,x_1,\,x_0}\big\|v_t(\psi_t(x_0))-\big(x_1-(1-\sigma_{min})x_0\big)\big\|^2

The paper notes that this flow is the optimal-transport displacement map between the two Gaussians, so particles move in straight lines at constant speed, whereas trajectories from diffusion paths can “overshoot” the end point and then backtrack.

Training takes three steps: draw data x1x_1, noise x0x_0 and time tt; compute ψt(x0)\psi_t(x_0) and the target; regress. To sample, an ODE solver integrates x0∼N(0,I)x_0\sim\mathcal N(0,I) from t=0t=0 to t=1t=1.

Experiments and findings

ImageNet and CIFAR-10 (Table 1, excerpt). The same U-Net, the same hyperparameters and number of iterations (baselines were allowed more iterations), unconditional models. NLL is in bits per dimension, and NFE is the average number of function evaluations an adaptive solver (dopri5, tolerance 1e-5) needs, averaged over 50k samples.

MethodC10 NLLC10 FIDC10 NFEIN64 NLLIN64 FID
DDPM3.127.482743.3217.36
Score matching (diffusion path)3.1619.942423.4019.74
ScoreFlow3.0920.784283.3624.95
FM, diffusion path3.108.061833.3316.88
FM, OT path2.996.351423.3114.45

On ImageNet 32×32, FM (OT) has NLL 3.53, FID 5.02 and NFE 122 against 3.54, 6.99 and 262 for DDPM. The paper cautions that its CIFAR-10 FIDs are higher than in earlier papers (DDPM’s own paper reports 3.17) possibly because the architecture was not tuned for CIFAR-10, so the table is for comparison within the same setting and not for comparing absolute values with other papers.

ImageNet 128×128. FM (OT) reaches NLL 2.90 and FID 20.9, which the paper calls state of the art except for IC-GAN, which uses conditioning from a self-supervised ResNet50 (in the table, unconditional BigGAN has 25.3 and PGMGAN 21.7). Training is faster: Dhariwal and Nichol’s diffusion model trained for 4.36 million iterations at batch size 256, while FM used a 25% larger model and only 500k iterations at batch size about 1.5k, which the paper counts as 33% less image throughput.

Sampling efficiency. With fixed-step solvers on the ImageNet 32×32 models, FM (OT) needs roughly 60% of the NFEs of diffusion paths for the same numerical error against a 1000-evaluation solution, and also has a better FID at very low NFE.

Super-resolution (Table 2). From 64×64 to 256×256, FM (OT) has FID 3.4 and IS 200.8, SR3 has 5.2 and 180.1, and the regression baseline has 15.2 and 121.1; in PSNR and SSIM FM (24.7, 0.747) is slightly below SR3 (26.4, 0.762).

Checking it with code

Three things. (1) A numerical check of the theorem. On a 1-D Gaussian x1∼N(3,0.52)x_1\sim\mathcal N(3,0.5^2) the marginal vector field has a closed form, ut(x)=m+ts2−(1−t)t2s2+(1−t)2(x−tm)u_t(x)=m+\frac{ts^2-(1-t)}{t^2s^2+(1-t)^2}(x-tm); train a small network with the CFM loss and see whether it regresses to this marginal field and whether the training loss stops at the analytic irreducible floor. (2) Paths and solvers. On a 2-D checkerboard (4×4, 8 black cells), train an MLP of identical structure (3 layers of 128 units) with the OT path and the VP path (β\beta from 0.1 to 20, tt in [0,1−10−5][0,1-10^{-5}], as in the paper), sample with fixed-step Euler and midpoint solvers at different NFE, measure the distance to real samples by an MMD² with RBF kernels of three bandwidths, and also report the numerical error against a 2000-step Euler solution; 5 seeds per setting, with independent seeds for training data, initialization and sampling noise. (3) Are the trajectories straight? The “trajectory length divided by start-to-end distance” for conditional paths and for the learned marginal flow. This is a teaching-scale version, not the paper’s experiment: the data is 2-D, the model a small MLP and the metric an MMD², not FID.

import statistics as st

import torch
from torch import nn

torch.set_num_threads(1)
BMIN, BMAX, EPS = 0.1, 20.0, 1e-5


def mlp(inp, out, h=128, layers=3):
    mods, d = [], inp
    for _ in range(layers):
        mods += [nn.Linear(d, h), nn.SiLU()]
        d = h
    return nn.Sequential(*mods, nn.Linear(d, out))


def ot_path(t, x0, x1):  # eq. (22)-(23) of the paper, sigma_min = 0
    return (1 - t) * x0 + t * x1, x1 - x0


def vp_path(t, x0, x1):
    # diffusion path (VP): beta rises linearly from 0.1 to 20
    s = 1 - t
    a = torch.exp(-0.5 * (BMIN * s + 0.5 * (BMAX - BMIN) * s ** 2))
    da = 0.5 * (BMIN + s * (BMAX - BMIN)) * a
    sig = (1 - a ** 2).sqrt()
    return a * x1 + sig * x0, da * x1 - a * da / sig * x0


def fit(net, draw, steps, lr, seed):
    g = torch.Generator().manual_seed(seed)
    opt = torch.optim.Adam(net.parameters(), lr=lr)
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda i: max(1e-5, 1 - i / steps))
    for _ in range(steps):
        t, xt, u = draw(512, g)
        loss = ((net(torch.cat([xt, t], 1)) - u) ** 2).sum(1).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
        sched.step()


# ---- Part 1: 1-D Gaussian, conditional target vs marginal field ----
M, S = 3.0, 0.5  # x1 ~ N(3, 0.5^2), x0 ~ N(0, 1)


def draw_1d(n, g):
    x1 = M + S * torch.randn(n, 1, generator=g)
    x0 = torch.randn(n, 1, generator=g)
    t = torch.rand(n, 1, generator=g)
    xt, u = ot_path(t, x0, x1)
    return t, xt, u


def u_true(x, t):  # closed form of the marginal field E[x1 - x0 | x_t = x]
    cov = t * S ** 2 - (1 - t)
    var = t ** 2 * S ** 2 + (1 - t) ** 2
    return M + cov / var * (x - t * M)


torch.manual_seed(12)
net1 = mlp(2, 1, h=64, layers=2)
fit(net1, draw_1d, 4000, 3e-3, 11)
t, xt, u = draw_1d(50_000, torch.Generator().manual_seed(13))
with torch.no_grad():
    v = net1(torch.cat([xt, t], 1))
tg = torch.linspace(0.0005, 0.9995, 1000)
floor = ((1 + S ** 2) - (tg * S ** 2 - (1 - tg)) ** 2
         / (tg ** 2 * S ** 2 + (1 - tg) ** 2)).mean()
uv = u_true(xt, t)
rel = ((v - uv) ** 2).mean().sqrt() / uv.pow(2).mean().sqrt()
print(f"1-D check: training loss {((v - u) ** 2).mean():.4f}, "
      f"analytic floor {floor:.4f}, "
      f"relative RMSE of v vs marginal field {rel:.4f}")


# ---- Part 2: OT path vs diffusion path on a 2-D checkerboard ----
def checker(n, g):
    cells = torch.tensor([(i, j) for i in range(4) for j in range(4)
                          if (i + j) % 2 == 0], dtype=torch.float32)
    k = torch.randint(0, len(cells), (n,), generator=g)
    return cells[k] - 2 + torch.rand(n, 2, generator=g)


def make_draw(path):
    def draw(n, g):
        x1 = checker(n, g)
        x0 = torch.randn(n, 2, generator=g)
        t = torch.rand(n, 1, generator=g) * (1 - EPS)
        xt, u = path(t, x0, x1)
        return t, xt, u
    return draw


@torch.no_grad()
def solve(net, x0, nfe, method):
    n = nfe if method == "euler" else nfe // 2
    h, x = 1.0 / n, x0.clone()

    def f(x, t):
        return net(torch.cat([x, torch.full((len(x), 1), t)], 1))

    for i in range(n):
        t = i * h
        if method == "euler":
            x = x + h * f(x, t)
        else:
            x = x + h * f(x + 0.5 * h * f(x, t), t + 0.5 * h)
    return x


@torch.no_grad()
def euler_traj(net, x0, n=256):  # the whole trajectory, shape (n+1, samples, 2)
    xs = [x0]
    for i in range(n):
        t = torch.full((len(x0), 1), i / n)
        xs.append(xs[-1] + net(torch.cat([xs[-1], t], 1)) / n)
    return torch.stack(xs)


def mmd2(a, b):  # RBF kernels with three bandwidths
    def k(u, v):
        d = torch.cdist(u, v) ** 2
        return sum(torch.exp(-d / (2 * s * s)) for s in (0.1, 0.3, 1.0))
    return (k(a, a).mean() + k(b, b).mean() - 2 * k(a, b).mean()).item()


def length_ratio(xs):  # trajectory length / straight-line distance
    d = (xs[1:] - xs[:-1]).norm(dim=-1).sum(0)
    return (d / (xs[-1] - xs[0]).norm(dim=-1)).mean().item()


NFES, SEEDS = (4, 8, 10, 20, 40), range(5)
PATHS = {"ot": ot_path, "vp": vp_path}
res, floors, marg = {}, [], {"ot": [], "vp": []}
for seed in SEEDS:
    g = torch.Generator().manual_seed(4000 + seed)
    real, real2 = checker(2000, g), checker(2000, g)
    floors.append(mmd2(real, real2) * 1e3)
    g = torch.Generator().manual_seed(3000 + seed)
    x0 = torch.randn(2000, 2, generator=g)
    for kind, path in PATHS.items():
        torch.manual_seed(2000 + seed)
        net = mlp(3, 2)
        fit(net, make_draw(path), 6000, 2e-3, 1000 + seed)
        ref = solve(net, x0, 2000, "euler")
        for nfe in NFES:
            for m in ("euler", "mid"):
                x = solve(net, x0, nfe, m)
                err = ((x - ref) ** 2).sum(1).mean().item()
                res.setdefault((nfe, m, kind), []).append(
                    (mmd2(x, real) * 1e3, err))
        marg[kind].append(length_ratio(euler_traj(net, x0)))

print(f"\nMMD^2 x1e3 between two real samples (floor): "
      f"{st.mean(floors):.2f}")
print("\nMMD^2 x1e3 (mean±std, 5 seeds) and error vs the 2000-step solution")
print(" NFE solver       OT MMD       VP MMD   OT err   VP err")
for nfe in NFES:
    for m in ("euler", "mid"):
        row = []
        for kind in ("ot", "vp"):
            v = res[(nfe, m, kind)]
            a = [p[0] for p in v]
            row.append((f"{st.mean(a):5.1f}±{st.stdev(a):4.1f}",
                          st.mean(p[1] for p in v)))
        print(f"{nfe:4d} {m:6s}  {row[0][0]:>11s}  {row[1][0]:>11s}"
              f"  {row[0][1]:7.4f}  {row[1][1]:7.4f}")

x1 = checker(2000, torch.Generator().manual_seed(5))
x0 = torch.randn(2000, 2, generator=torch.Generator().manual_seed(6))
cond = {}
for kind, path in PATHS.items():
    ts = torch.linspace(0, 1 - EPS, 257)
    cond[kind] = length_ratio(torch.stack(
        [path(t.expand(2000, 1), x0, x1)[0] for t in ts]))
print("\nPath length / straight-line distance (mean, 256-step Euler)")
print(f"conditional path: OT {cond['ot']:.3f}, VP {cond['vp']:.3f}")
print(f"marginal flow   : OT {st.mean(marg['ot']):.3f}, "
      f"VP {st.mean(marg['vp']):.3f}")

Output (CPU, one thread, about 1.5 minutes; individual numbers may differ slightly in another environment):

1-D check: training loss 0.7857, analytic floor 0.7854, relative RMSE of v vs marginal field 0.0209

MMD^2 x1e3 between two real samples (floor): 2.92

MMD^2 x1e3 (mean±std, 5 seeds) and error vs the 2000-step solution
 NFE solver       OT MMD       VP MMD   OT err   VP err
   4 euler     55.1± 3.3    16.7± 1.3   0.1665   0.0547
   4 mid        9.1± 0.8    17.3± 1.7   0.0146   0.0506
   8 euler     16.3± 1.4     6.6± 0.5   0.0425   0.0099
   8 mid        5.6± 0.6    16.3± 1.4   0.0006   0.0153
  10 euler     12.1± 1.1     5.8± 0.4   0.0273   0.0063
  10 mid        5.6± 0.6     8.3± 0.3   0.0002   0.0038
  20 euler      6.9± 0.6     5.1± 0.5   0.0068   0.0016
  20 mid        5.5± 0.6     5.2± 0.6   0.0000   0.0001
  40 euler      5.8± 0.5     5.0± 0.6   0.0017   0.0004
  40 mid        5.5± 0.6     5.1± 0.6   0.0000   0.0000

Path length / straight-line distance (mean, 256-step Euler)
conditional path: OT 1.000, VP 1.270
marginal flow   : OT 2.756, VP 1.302

How to read these numbers:

  1. Regressing the conditional target learns the marginal vector field. The training loss is 0.7857 against an analytic floor of 0.7854: it cannot reach zero because the same xtx_t corresponds to many (x0,x1)(x_0,x_1) pairs, so the target itself is noisy. The network’s relative RMSE against the analytic marginal field is only 0.0209, so Theorem 2 holds in this example.
  2. The solver flips the conclusion. With the midpoint method (as in the paper’s Figures 4 and 7), OT has MMD² of 9.1, 5.6 and 5.6 at NFE 4, 8 and 10 against 17.3, 16.3 and 8.3 for the diffusion path, so OT clearly needs fewer steps, and its numerical error is much smaller (0.0006 against 0.0153 at NFE=8, 0.0002 against 0.0038 at NFE=10); from NFE=20 both sit on a plateau around 5 (OT 5.5, VP 5.2, a difference under one standard deviation), which is the model’s own error, not the solver’s. With first-order Euler the conclusion reverses: at NFE=8 OT has 16.3 and VP 6.6, so VP is better. I did not test this on an image model, so all I can say is that the paper’s claim that OT sampling is more efficient was reproduced in this toy, but it depends on a second-order solver.
  3. “Straight” is a property of the conditional path, not of the marginal flow. For conditional paths, OT has a length ratio of exactly 1.000 and VP 1.270; but in the learned marginal flow, OT trajectories are 2.756 times longer than the straight-line distance and VP only 1.302. Part of the reason shows in the marginal field at t=0t=0: with independent pairing u0(x)=E[x1]−xu_0(x)=\mathbb E[x_1]-x, so every point first contracts toward the data mean (the center of the board) and then spreads out to the black cells, an inward-then-outward trajectory; the diffusion path barely moves early on and only runs to the data in the last stretch, so it is closer to a straight line. Straightening the marginal flow itself needs something else, for example the reflow of Rectified Flow (Liu et al., 2022, cited by the paper), which this experiment does not touch.
  4. With too few steps OT’s Euler solution collapses toward the mean. By the formula, a single Euler step gives x0+u0(x0)=E[x1]x_0+u_0(x_0)=\mathbb E[x_1], which puts every sample at the data mean (the script does not run NFE=1; this is a derivation); already at NFE=4 the OT Euler solution has an MMD² as high as 55.1.
  5. Limits. Only 2000 points per sample and 5 seeds; the MMD² floor (between two real samples) is about 2.92 and the models’ own plateau is around 5, so this small network did not fit down to the floor; a 2-D checkerboard is very different from ImageNet, so the ranking of paths cannot be extrapolated directly.

Limitations and what to keep in mind

  • The marginal flow is not necessarily straight. Straight conditional paths do not guarantee a straight learned flow; with independent pairing of (x0,x1)(x_0,x_1) the marginal trajectories of multimodal data bend, which motivates later work on better couplings and straightening.
  • The best path depends on the data and the solver. The paper’s OT advantage was observed on ImageNet with the midpoint scheme and dopri5; my toy shows the conclusion reverses with Euler.
  • FIDs in Table 1 should not be compared across papers. The paper itself says its CIFAR-10 FIDs are high and the architecture was not tuned for that data set, and the baselines were allowed more iterations.
  • Sampling still needs an ODE solve. Training is simulation-free, but sampling needs dozens to hundreds of network evaluations; the paper’s NFE figures (122 to 428) are adaptive-solver averages at tolerance 1e-5.
  • Likelihood evaluation cost. The reported NLLs come from numerical integration of the ODE, described in the paper’s appendix; I did not reproduce them.

What to take from this paper

  1. Turn generative modeling into regression. Fix a path, regress its vector field, and never solve an ODE during training.
  2. Conditioning makes the intractable objective tractable. The per-sample pt(x∣x1)p_t(x\mid x_1) and ut(x∣x1)u_t(x\mid x_1) give the same gradient, and the noise in the conditional target is why the loss floor is not zero.
  3. Diffusion is one Gaussian path among many. Switching to the OT path simplifies the target to x1−(1−σmin)x0x_1-(1-\sigma_{min})x_0.
  4. Which path is better depends on the solver and the data. A straight conditional path does not make the marginal flow straight, so sampling efficiency has to be measured with a concrete solver.
  5. The same recipe was later used for video, robot actions and large text-to-image models. That is outside this post’s experiments; see the respective papers.

Further reading

FAQ

What exactly does Flow Matching regress during training?
It learns a time-dependent vector field v_t(x); to generate, start from Gaussian noise and integrate the ODE dx/dt = v_t(x) up to t=1. In training you draw a data point x1, noise x0 and a time t, feed x_t = (1−t)x0 + t·x1 to the network, and regress the target x1 − x0 (the paper's OT path with σ_min=0). No ODE is solved anywhere in training.
How is Flow Matching related to diffusion models?
The paper's family of Gaussian probability paths contains diffusion paths as a special case and allows others, such as optimal-transport (OT) paths; sampling uses a deterministic ODE solver instead of a stochastic SDE. The paper says training diffusion paths with Flow Matching is more robust than score matching: on CIFAR-10 the FID is 8.06 against 19.94, but not everywhere, since on ImageNet 32×32 score matching has the lower FID (5.68 against 6.37).
Why is the OT path said to need fewer sampling steps, and what does that depend on?
The paper points out that the OT conditional path is a straight line at constant speed, so the conditional vector field has a fixed direction and is easier to regress; on ImageNet 32×32 it needs roughly 60% of the function evaluations of diffusion paths for the same numerical error. The straightness belongs to the conditional path only: on a 2D checkerboard I measured marginal trajectories 2.76 times longer than the straight-line distance, and with the second-order midpoint solver OT needs fewer steps, while with first-order Euler the diffusion path is better.
Why does the Flow Matching training loss not go to zero, and is that a problem?
Given x_t, the conditional target x1 − x0 is still random, because the same x_t can come from different (x0, x1) pairs, so the loss has an irreducible floor and the network converges to the conditional expectation, which is the marginal vector field (Theorem 2 of the paper says the conditional and original objectives have the same gradient). On a 1-D Gaussian I measured a training loss of 0.7857 against an analytic floor of 0.7854, and a relative error of 0.0209 between the network and the analytic marginal field.