Skip to content
Generative models and multimodal Frontier 37 min read

Score matching and flow matching

There are two ways to describe how noise becomes data. One learns the score, the gradient of the log-density, and follows it uphill with noise added (a stochastic differential equation). The other learns a velocity field that carries the noise distribution onto the data distribution (an ordinary differential equation). Both are trained by plain regression on targets built from single data points, and for Gaussian noise they are the same model in different coordinates. The idea to walk away with: you never need the density, only a vector field, and you can learn that field from pairs of points.

10,000 ft

Diffusion models were discovered twice: as a variational model with a thousand noisy steps (Ho et al., 2020) and as a score-based model that learns \(\nabla_{\mathbf x}\log p(\mathbf x)\) at many noise levels and samples with Langevin dynamics (Song and Ermon, 2019). Song et al. (2021) unified the two in continuous time with stochastic differential equations, and showed that every diffusion model has a deterministic twin, the probability-flow ODE, which is a continuous normalising flow. Flow matching (Lipman et al., 2022), rectified flow (Liu et al., 2022) and stochastic interpolants (Albergo and Vanden-Eijnden, 2022) then asked the obvious question: if the sampler is an ODE, why not learn its velocity directly, along whatever path from noise to data you like? Choosing straight lines gave a simpler objective, faster samplers and the training recipe behind Stable Diffusion 3, FLUX.1, Meta's Movie Gen, the Voicebox speech model and the π0 robot policy. The same ideas are now the frontier of one-step generation (consistency models, MeanFlow). They connect to optimal transport, to energy-based models, and to the denoising autoencoder.

2,000 ft

Two routes from noise to data, both trained by regression on per-sample targets:

Score route and flow route
Score route and flow route. noise N(0, I), data p_data, a path of distributions p_t from noise to data, score s_θ(x, t) ≈ ∇ log p_t (denoising score matching), velocity v_θ(x, t) (conditional flow matching), reverse SDE stochastic sampler, ODE  dx/dt = v deterministic sampler, regress on −ε/σ, regress on x₁ − x₀, same information for Gaussian pathsScore route and flow route. noise N(0, I), data p_data, a path of distributions p_t from noise to data, score s_θ(x, t) ≈ ∇ log p_t (denoising score matching), velocity v_θ(x, t) (conditional flow matching), reverse SDE stochastic sampler, ODE  dx/dt = v deterministic sampler, regress on −ε/σ, regress on x₁ − x₀, same information for Gaussian paths

  1. The score \(\nabla_{\mathbf x}\log p(\mathbf x)\) needs no normalising constant, so a network can learn it even when the density is intractable.
  2. Denoising score matching: add Gaussian noise to a data point and regress the network onto the direction back to it. The optimum is the score of the noised distribution.
  3. Use many noise levels so the score is accurate everywhere, then sample with annealed Langevin dynamics or the reverse-time SDE.
  4. Flow matching: pick a path between a noise sample \(\mathbf x_0\) and a data sample \(\mathbf x_1\), e.g. \(\mathbf x_t = (1-t)\mathbf x_0 + t\mathbf x_1\), and regress \(v_\theta(\mathbf x_t, t)\) onto \(\mathbf x_1 - \mathbf x_0\).
  5. The regression optimum is the marginal velocity, which moves the whole noise distribution onto the data distribution. Sample by integrating \(d\mathbf x/dt = v_\theta\) from \(t=0\) to \(1\).
  6. Straighter paths need fewer integration steps; reflow, optimal-transport couplings and distillation push towards one step.

Ground level

The score: a density you never have to normalise

Most flexible models of a density are unnormalised: you can write \(p_\theta(\mathbf x) = e^{-E_\theta(\mathbf x)}/Z_\theta\) for any network \(E_\theta\) (an energy-based model), but the normaliser \(Z_\theta = \int e^{-E_\theta(\mathbf x)}d\mathbf x\) is an integral over all images and cannot be computed. Maximum likelihood needs \(\nabla_\theta\log Z_\theta\), which requires samples from the model, which requires the model. This chicken-and-egg problem stalled energy-based models for decades.

Take the gradient with respect to \(\mathbf x\) instead of \(\theta\) and the problem disappears:

\[ \mathbf s(\mathbf x) := \nabla_{\mathbf x}\log p(\mathbf x) = -\nabla_{\mathbf x}E_\theta(\mathbf x) - \underbrace{\nabla_{\mathbf x}\log Z_\theta}_{=\,0}. \]

This vector field is the (Stein) score. It points uphill on the log-density, and it is zero at modes. For a Gaussian \(\mathcal N(\boldsymbol\mu, \sigma^2 I)\) it is \(-(\mathbf x - \boldsymbol\mu)/\sigma^2\): a spring pulling towards the mean, stronger for narrower distributions. For a mixture, it is a responsibility-weighted average of such springs. A network \(\mathbf s_\theta:\mathbb R^D\to\mathbb R^D\) can represent it with no constraint at all.

Sampling from a score: Langevin dynamics. If you know \(\mathbf s\), you can sample from \(p\) without ever evaluating it, by repeating

\[ \mathbf x \leftarrow \mathbf x + \tfrac{\eta}{2}\,\mathbf s(\mathbf x) + \sqrt{\eta}\,\mathbf z,\qquad \mathbf z\sim\mathcal N(\mathbf 0, I). \]

The drift climbs the density; the noise stops everything collapsing onto the mode. As \(\eta\to0\) and the number of steps grows, the iterates are distributed as \(p\). This is gradient ascent with exactly the right amount of noise, and it is how physicists simulate molecules in a heat bath.

Learning a score without knowing the density

We want \(\mathbf s_\theta\approx\nabla\log p_\text{data}\), but we have samples, not \(p_\text{data}\). Minimising the Fisher divergence \(\tfrac12\mathbb E_{p_\text{data}}\lVert\mathbf s_\theta - \nabla\log p_\text{data}\rVert^2\) looks impossible because the target is unknown. Hyvärinen (2005) showed that integration by parts removes it:

\[ \tfrac12\mathbb E_{p}\lVert\mathbf s_\theta - \nabla\log p\rVert^2 = \mathbb E_{p}\Big[\operatorname{tr}\big(\nabla_{\mathbf x}\mathbf s_\theta(\mathbf x)\big) + \tfrac12\lVert\mathbf s_\theta(\mathbf x)\rVert^2\Big] + \text{const}. \]

This score matching objective needs only samples. Its weakness is the trace of the Jacobian: \(D\) backward passes per example for a \(D\)-dimensional input, hopeless for images. Sliced score matching (Song et al., 2019) estimates the trace with random projections. The cheaper and more influential fix came from a different direction.

Denoising score matching (Vincent, 2011). Corrupt each data point with Gaussian noise, \(\tilde{\mathbf x} = \mathbf x + \sigma\boldsymbol\epsilon\), and regress the network onto the direction back to the clean point:

\[ \mathcal L_\text{DSM}(\theta) = \mathbb E_{\mathbf x\sim p_\text{data},\ \boldsymbol\epsilon\sim\mathcal N(\mathbf 0,I)}\Big\lVert\mathbf s_\theta(\mathbf x + \sigma\boldsymbol\epsilon) + \frac{\boldsymbol\epsilon}{\sigma}\Big\rVert^2 . \]

The per-sample target \(-\boldsymbol\epsilon/\sigma = -(\tilde{\mathbf x}-\mathbf x)/\sigma^2\) is the score of the corruption kernel \(q(\tilde{\mathbf x}\mid\mathbf x)\), which is known. Vincent proved that this objective has the same minimiser as score matching on the noised distribution \(p_\sigma = p_\text{data} * \mathcal N(\mathbf 0, \sigma^2 I)\): the network learns \(\nabla\log p_\sigma\). The reason is general and you will see it again in flow matching: the regression optimum is a conditional mean, and the conditional mean of the per-sample scores is the score of the marginal (derivation in The maths). Notice that \(\mathcal L_\text{DSM}\) is exactly the DDPM noise-prediction loss with \(\mathbf s_\theta = -\epsilon_\theta/\sigma\): the denoiser is a score model.

The picture to keep

Each training pair says "from this noisy point, the clean point was over there". Many clean points are consistent with one noisy point, so the network learns the average direction, weighted by how likely each clean point was. That average direction is the score of the blurred data distribution: arrows pointing back towards where the data is dense.

Why one noise level is not enough

Song and Ermon (2019) identified two failures of a score learned at a single small noise level.

  1. The score is wrong where there is no data. Real data lies near a low-dimensional manifold. Far from it, training samples never appear, so the learned score there is arbitrary, and Langevin chains starting from random noise begin exactly there.
  2. Langevin dynamics cannot get mixture weights right. The score of \(w_1p_1 + w_2p_2\) with well-separated components is, near each component, just that component's score: the weights \(w_1, w_2\) vanish from the gradient. A chain falls into whichever mode is nearest and stays there. Song and Ermon illustrated this with a mixture weighted \(\tfrac15\) and \(\tfrac45\).

Worked example. Data \(0.2\,\mathcal N(-4, 0.5^2) + 0.8\,\mathcal N(4, 0.5^2)\), with the exact score (so all failures are the sampler's). Start 20,000 chains spread uniformly on \([-8, 8]\):

Sampler Left-mode fraction (true 0.200) Std of right mode (true 0.500)
Langevin at the data score, 5,000 steps 0.494 n/a
Annealed Langevin, 10 noise levels × 100 steps 0.243 0.511
Annealed Langevin, 30 noise levels × 100 steps 0.212 0.502

Plain Langevin returns the starting split (about half the chains began on each side), not the data's weights. The fix, annealing, learns the score of \(p_\sigma\) for a sequence of noise levels from large (where the blurred modes overlap, so chains can move between them and the weights are visible in the score) to small (where the score is sharp). Sampling runs Langevin at each level in turn. With too few levels, chains get stranded when the modes separate between consecutive levels, which is why the 10-level run still over-weights the small mode. Song and Ermon's noise-conditional score network (NCSN) learned all levels with one network \(\mathbf s_\theta(\mathbf x,\sigma)\) and reached an Inception Score of 8.87 on CIFAR-10; NCSNv2 (Song and Ermon, 2020) gave principled rules for the largest noise level and the spacing. Diffusion models are this idea with a particular, carefully weighted, noise schedule.

Continuous time: one SDE, its reverse, and an ODE twin

Let the number of noise levels go to infinity. Noising becomes a stochastic differential equation (SDE),

\[ d\mathbf x = \mathbf f(\mathbf x, t)\,dt + g(t)\,d\mathbf w , \]

a drift \(\mathbf f\) plus Brownian noise of scale \(g(t)\), run from \(t=0\) (data) to \(t=1\) (noise) in the convention of Song et al. (2021). DDPM is the variance-preserving SDE \(d\mathbf x = -\tfrac12\beta(t)\mathbf x\,dt + \sqrt{\beta(t)}\,d\mathbf w\); NCSN is the variance-exploding SDE \(d\mathbf x = \sqrt{d[\sigma^2(t)]/dt}\;d\mathbf w\).

A result of Anderson (1982) says the reverse process is also an SDE, and it needs only the score:

\[ d\mathbf x = \big[\mathbf f(\mathbf x, t) - g(t)^2\,\nabla_{\mathbf x}\log p_t(\mathbf x)\big]dt + g(t)\,d\bar{\mathbf w}, \]

run backwards in time with its own Brownian motion \(\bar{\mathbf w}\). Learn \(\mathbf s_\theta(\mathbf x, t)\approx\nabla\log p_t\) by denoising score matching at every \(t\), plug it in, integrate from noise to data: that is a diffusion model's sampler. DDPM's ancestral sampler is one discretisation of it.

The second result is the important one for what follows. There is a deterministic process with the same marginals \(p_t\) at every time, the probability-flow ODE:

\[ \frac{d\mathbf x}{dt} = \mathbf f(\mathbf x, t) - \tfrac12 g(t)^2\,\nabla_{\mathbf x}\log p_t(\mathbf x). \]

You can check it with the continuity equation (derived in The maths): the Fokker–Planck equation of the SDE and the continuity equation of the ODE are the same PDE. The ODE is what DDIM discretises. Because it is deterministic and invertible, it maps each noise vector to one data point and back, it allows exact likelihoods through the change-of-variables formula, and it can be integrated with off-the-shelf adaptive solvers. With these tools Song et al. reached FID 2.20 and 2.99 bits per dimension on CIFAR-10 and generated 1024×1024 images from a score model for the first time.

Flows: moving a distribution with a vector field

A normalising flow pushes a simple distribution through an invertible map \(\mathbf x = T(\mathbf z)\) and tracks the density with the change-of-variables formula, \(\log p_X(\mathbf x) = \log p_Z(\mathbf z) - \log\lvert\det\partial T/\partial\mathbf z\rvert\). Discrete flows (RealNVP, Glow) must use layers with cheap Jacobian determinants, which limits them.

A continuous normalising flow (Chen et al., 2018, Neural ODEs) defines \(T\) as the time-1 map of an ODE \(d\mathbf x/dt = \mathbf v_\theta(\mathbf x, t)\) with any network \(\mathbf v_\theta\). The density along a trajectory obeys the instantaneous change of variables

\[ \frac{d}{dt}\log p_t\big(\mathbf x(t)\big) = -\nabla\cdot\mathbf v_\theta\big(\mathbf x(t), t\big), \]

so the log-determinant becomes an integral of a divergence (FFJORD estimates it with Hutchinson's trace trick). CNFs are wonderfully flexible but were trained by maximum likelihood, which means integrating the ODE inside every training step: slow, and hard to scale. The probability-flow ODE showed that a diffusion model is a CNF, trained without ever simulating it. Flow matching generalises that trick to any path.

Flow matching: regress the velocity

Pick a probability path \(p_t\), \(t\in[0,1]\), with \(p_0 = \mathcal N(\mathbf 0, I)\) and \(p_1 = p_\text{data}\). Some velocity field \(\mathbf u_t\) generates it (moves \(p_0\) to \(p_t\) by the ODE). If we knew \(\mathbf u_t\) we could regress onto it: \(\mathcal L_\text{FM} = \mathbb E_{t,\ \mathbf x\sim p_t}\lVert\mathbf v_\theta(\mathbf x, t) - \mathbf u_t(\mathbf x)\rVert^2\). We do not; \(\mathbf u_t\) depends on the whole data distribution.

The trick (Lipman et al., 2022) is to build \(p_t\) out of per-sample paths. For a noise sample \(\mathbf x_0\) and a data sample \(\mathbf x_1\), take the straight line

\[ \mathbf x_t = (1-t)\,\mathbf x_0 + t\,\mathbf x_1,\qquad \frac{d\mathbf x_t}{dt} = \mathbf x_1 - \mathbf x_0 . \]

Averaging these lines over random pairs defines \(p_t\). The conditional flow matching loss regresses onto the per-pair velocity, which is known:

\[ \mathcal L_\text{CFM}(\theta) = \mathbb E_{t\sim U[0,1],\ \mathbf x_0\sim\mathcal N(\mathbf 0, I),\ \mathbf x_1\sim p_\text{data}}\Big\lVert\mathbf v_\theta\big((1-t)\mathbf x_0 + t\mathbf x_1,\ t\big) - (\mathbf x_1 - \mathbf x_0)\Big\rVert^2 . \]

Lipman et al.'s theorem: \(\nabla_\theta\mathcal L_\text{CFM} = \nabla_\theta\mathcal L_\text{FM}\). The two losses differ by a constant, so minimising the tractable one trains the network to the marginal velocity

\[ \mathbf u_t(\mathbf x) = \mathbb E\big[\mathbf x_1 - \mathbf x_0 \,\big|\, \mathbf x_t = \mathbf x\big], \]

the average direction of all the lines passing through \(\mathbf x\) at time \(t\). Integrating \(d\mathbf x/dt = \mathbf v_\theta\) from a fresh noise sample at \(t=0\) lands on a sample from the data distribution at \(t=1\). This is the whole algorithm. It has no SDE, no noise schedule to tune beyond the choice of path, and the training loop is four lines.

One flow matching training step
One flow matching training step. x₀ ~ N(0, I), x₁ from data, t ~ U[0, 1] (or logit-normal), x_t = (1−t) x₀ + t x₁, v_θ(x_t, t), ‖v_θ − (x₁ − x₀)‖², target x₁ − x₀One flow matching training step. x₀ ~ N(0, I), x₁ from data, t ~ U[0, 1] (or logit-normal), x_t = (1−t) x₀ + t x₁, v_θ(x_t, t), ‖v_θ − (x₁ − x₀)‖², target x₁ − x₀
training pairs: straight lines, they crosslearned flow: curved, never cross
Left: fourteen random (noise, data) pairs for the eight-Gaussian ring and the straight lines flow matching trains on. They cross, so at a crossing the regression target is ambiguous and the network learns the average. Right: the same fourteen noise points carried by the resulting marginal velocity field (exact, 16 Euler steps). An ODE's trajectories cannot cross, so each noise point is routed to a nearby mode along a curved path. Computed with the code in Build it.

The picture explains the main limitation. Straight conditional paths do not make straight marginal paths: because random pairs cross, the averaged velocity bends trajectories, and bent trajectories need more integration steps. In the Build it experiment with the exact marginal velocity, the median trajectory is 13% longer than the straight line between its endpoints, and a single Euler step sends every sample to the data mean (the origin), because at \(t = 0\) the average direction from any point is towards \(\mathbb E[\mathbf x_1]\). Four steps put 88.5% of samples on a mode, eight steps 95.9%, 128 steps 98.9% (the theoretical value for this mixture is 98.9%).

Diffusion is flow matching with a Gaussian path

The linear path is not special. Any interpolation \(\mathbf x_t = a_t\mathbf x_1 + b_t\mathbf x_0\) with \(a_0 = 0, a_1 = 1, b_0 = 1, b_1 = 0\) works, with target \(\dot a_t\mathbf x_1 + \dot b_t\mathbf x_0\). Choosing \(a_t, b_t\) from a diffusion schedule (\(a_t = \sqrt{\bar\alpha}\), \(b_t = \sqrt{1-\bar\alpha}\) with time reversed) gives a diffusion model trained with a velocity loss. And because the path is Gaussian given \(\mathbf x_1\), the velocity and the score determine each other. For the linear path,

\[ \mathbf u_t(\mathbf x) = \frac{\mathbf x + (1-t)\,\nabla_{\mathbf x}\log p_t(\mathbf x)}{t}, \]

which the code checks numerically to \(2\times10^{-15}\). So "score model", "noise predictor", "\(\mathbf x_0\) predictor", "\(\mathbf v\) predictor" and "flow" are linear reparameterisations of the same learned object. What differs between methods is the path (which determines how curved the trajectories are), the weighting over \(t\) (which noise levels the network practises most) and the sampler. Stable Diffusion 3 (Esser et al., 2024) ran a large study of these choices and adopted rectified flow (the linear path) with \(t\) drawn from a logit-normal distribution, which concentrates training on intermediate times where the velocity is hardest to predict.

Straightening the paths

If trajectories were straight, one Euler step would be exact. Three ways to get closer:

  • Reflow (Liu et al., 2022). Train a flow; then pair each noise sample with the point its own ODE reaches, and retrain on straight lines between these pairs. The new coupling is deterministic, so lines no longer cross, and Liu et al. prove that rectification never increases convex transport costs. In Build it, one reflow takes one-step sampling from 0.1% of samples on a mode to 56%, at some cost in multi-step quality because the second fit is imperfect.
  • Optimal-transport couplings (Tong et al., 2023; Pooladian et al., 2023, Multisample Flow Matching). Within each mini-batch, pair noise and data by solving a small assignment problem so that pairs are close. The resulting conditional paths cross less, the marginal paths are straighter, and training variance falls.
  • Distillation to few steps. Train a student to jump along the teacher's ODE: consistency models (map any point on a trajectory to its endpoint), shortcut models (condition on the step size), and MeanFlow (Geng et al., 2025), which learns the average velocity over an interval, \(\mathbf u(\mathbf x_t, r, t) = \frac{1}{t-r}\int_r^t\mathbf v(\mathbf x_\tau,\tau)d\tau\), using an identity that relates it to the instantaneous velocity. MeanFlow reached FID 3.43 on ImageNet 256×256 with a single network evaluation, trained from scratch.

Where these models are used

Flow matching became the default training objective for large generative models within two years of publication: Stable Diffusion 3 (rectified flow transformer), FLUX.1 ("a 12 billion parameter rectified flow transformer", per its model card), Meta's Movie Gen (a 30B-parameter video model trained with flow matching), the Voicebox speech generator (speech and audio) and Physical Intelligence's π0 robot policy, which uses a flow-matching action head on top of a vision-language model (embodied AI). Score-based SDE samplers remain important for inverse problems (inpainting, super-resolution, medical image reconstruction), where you add the gradient of a measurement likelihood to the learned score, and theory has caught up: Chen et al. (2022) proved that, given an accurate score, diffusion sampling converges to the data distribution in polynomially many steps without strong assumptions on the data.

History

Who found it

Aapo Hyvärinen introduced score matching in 2005 to fit unnormalised models. Pascal Vincent showed in 2011 that training a denoising autoencoder is score matching on noise-blurred data. Brian Anderson derived reverse-time diffusion equations in 1982, in control theory, decades before anyone generated an image. Yang Song and Stefano Ermon turned the pieces into a generative model in 2019 (NCSN, multiple noise levels, annealed Langevin), then, with Sohl-Dickstein, Kingma, Kumar and Poole, into the SDE framework (late 2020; an ICLR 2021 outstanding paper). Continuous normalising flows came from Ricky Chen, Yulia Rubanova, Jesse Bettencourt and David Duvenaud's Neural ODEs (NeurIPS 2018 best paper). In autumn 2022 three groups independently proposed simulation-free training of flows: Yaron Lipman and colleagues at Meta (flow matching), Xingchao Liu, Chengyue Gong and Qiang Liu (rectified flow) and Michael Albergo and Eric Vanden-Eijnden (stochastic interpolants). By 2024 SD3 and FLUX had made rectified flow the industrial standard, and in December 2024 Lipman et al. published a guide and library for flow matching.

First principles

Strip away the notation and three ideas carry everything on this page.

1. Gradients of log-densities do not see normalisers. The score is local information about where probability increases, and it is all a sampler needs. That is why both Langevin dynamics and the reverse SDE need \(\nabla\log p_t\) and never \(p_t\).

2. Regression onto a noisy target learns the conditional mean. If a network minimises \(\mathbb E\lVert f(\mathbf y) - \mathbf z\rVert^2\), its optimum is \(f^*(\mathbf y) = \mathbb E[\mathbf z\mid\mathbf y]\), and the expected loss splits into \(\mathbb E\lVert f - f^*\rVert^2\) plus a constant that does not depend on \(f\). Denoising score matching and conditional flow matching are both this fact. The per-sample targets (the direction back to one clean point; the velocity along one straight line) are noisy and individually meaningless, but their conditional averages are the marginal score and the marginal velocity, exactly the fields that transport whole distributions. You learn a property of the population from per-sample supervision, the same reason linear regression recovers \(\mathbb E[y\mid x]\) from noisy labels.

3. Mass is conserved. A distribution moved by a velocity field obeys the continuity equation \(\partial_t p_t + \nabla\cdot(p_t\mathbf u_t) = 0\). A diffusion adds a term \(\tfrac12 g^2\Delta p_t\) (Fokker–Planck). Since \(\Delta p = \nabla\cdot(p\nabla\log p)\), any diffusion can be rewritten as a pure transport with velocity \(\mathbf f - \tfrac12 g^2\nabla\log p_t\): that is the probability-flow ODE, and it is why stochastic and deterministic samplers share marginals. Conversely, any ODE can be given noise without changing its marginals if you correct the drift with the score.

What breaks if you change things? Learn the score at one noise level and Langevin gets mixture weights wrong (the worked example). Use an ODE path whose endpoint at \(t=0\) is not a distribution you can sample, and you cannot start. Use crossing conditional paths and you get curved trajectories; use a perfectly straight coupling (optimal transport) and one step suffices, but computing that coupling over a whole dataset is as hard as the original problem, which is why reflow and mini-batch OT approximate it.

The maths

Notation. \(\mathbf x\in\mathbb R^D\). Networks map \((B, D)\) inputs and \((B,)\) times to \((B, D)\) outputs. \(\nabla\) is the gradient in \(\mathbf x\); \(\nabla\cdot\) is divergence; \(\Delta\) is the Laplacian.

Derivation: Hyvärinen's score matching identity (1-D)

Expand the Fisher divergence: \(\tfrac12\mathbb E_p[(s_\theta - (\log p)')^2] = \mathbb E_p[\tfrac12 s_\theta^2] - \mathbb E_p[s_\theta(\log p)'] + \text{const}\). The cross term is \(\int p\,s_\theta\,p'/p\,dx = \int s_\theta\,p'\,dx = [s_\theta p] - \int s_\theta'\,p\,dx\). If \(s_\theta p\to0\) at \(\pm\infty\), the boundary term vanishes, leaving \(-\mathbb E_p[s_\theta']\). Hence the objective \(\mathbb E_p[s_\theta' + \tfrac12 s_\theta^2]\), which needs only samples. In \(D\) dimensions, integrate by parts in each coordinate; \(s_\theta'\) becomes \(\operatorname{tr}\nabla\mathbf s_\theta\).

Derivation: denoising score matching learns the score of the noised density

Let \(p_\sigma(\tilde{\mathbf x}) = \int q(\tilde{\mathbf x}\mid\mathbf x)p(\mathbf x)d\mathbf x\) with \(q = \mathcal N(\mathbf x, \sigma^2 I)\). Then

\[ \nabla\log p_\sigma(\tilde{\mathbf x}) = \frac{\int\nabla_{\tilde{\mathbf x}}q(\tilde{\mathbf x}\mid\mathbf x)\,p(\mathbf x)\,d\mathbf x}{p_\sigma(\tilde{\mathbf x})} = \int\nabla_{\tilde{\mathbf x}}\log q(\tilde{\mathbf x}\mid\mathbf x)\;p(\mathbf x\mid\tilde{\mathbf x})\,d\mathbf x = \mathbb E\Big[-\frac{\tilde{\mathbf x}-\mathbf x}{\sigma^2}\,\Big|\,\tilde{\mathbf x}\Big]. \]

The marginal score is the posterior mean of the conditional scores. The DSM loss regresses \(\mathbf s_\theta(\tilde{\mathbf x})\) onto \(-(\tilde{\mathbf x}-\mathbf x)/\sigma^2\), so its minimiser is that posterior mean, \(\nabla\log p_\sigma\). Rearranging gives Tweedie's formula, \(\mathbb E[\mathbf x\mid\tilde{\mathbf x}] = \tilde{\mathbf x} + \sigma^2\nabla\log p_\sigma(\tilde{\mathbf x})\): the optimal denoiser is one score step.

Derivation: the probability-flow ODE has the SDE's marginals

The SDE \(d\mathbf x = \mathbf f\,dt + g\,d\mathbf w\) has density evolving by Fokker–Planck: \(\partial_t p_t = -\nabla\cdot(\mathbf f p_t) + \tfrac12 g^2\Delta p_t\). Write \(\Delta p_t = \nabla\cdot\nabla p_t = \nabla\cdot(p_t\nabla\log p_t)\), so

\[ \partial_t p_t = -\nabla\cdot\Big(p_t\big[\mathbf f - \tfrac12 g^2\nabla\log p_t\big]\Big). \]

This is the continuity equation of the ODE \(d\mathbf x/dt = \mathbf f - \tfrac12 g^2\nabla\log p_t\). Same initial density, same PDE, same marginals at every \(t\). The reverse-time SDE comes from the same manipulation with \(g^2\) instead of \(\tfrac12 g^2\) and a backward Brownian motion.

Derivation: conditional flow matching has the same gradient as flow matching

Let \(p_t(\mathbf x) = \int p_t(\mathbf x\mid\mathbf z)\,q(\mathbf z)\,d\mathbf z\) where \(\mathbf z = (\mathbf x_0,\mathbf x_1)\), and let \(\mathbf u_t(\mathbf x\mid\mathbf z)\) generate \(p_t(\cdot\mid\mathbf z)\). Define the marginal velocity \(\mathbf u_t(\mathbf x) = \int\mathbf u_t(\mathbf x\mid\mathbf z)\,\frac{p_t(\mathbf x\mid\mathbf z)q(\mathbf z)}{p_t(\mathbf x)}d\mathbf z = \mathbb E[\mathbf u_t(\mathbf x\mid\mathbf z)\mid\mathbf x_t = \mathbf x]\). It generates \(p_t\): summing the conditional continuity equations \(\partial_t p_t(\mathbf x\mid\mathbf z) = -\nabla\cdot(p_t(\mathbf x\mid\mathbf z)\mathbf u_t(\mathbf x\mid\mathbf z))\) over \(q(\mathbf z)\) gives \(\partial_t p_t = -\nabla\cdot(p_t\mathbf u_t)\). Now expand both losses:

\[ \lVert\mathbf v_\theta - \mathbf u\rVert^2 = \lVert\mathbf v_\theta\rVert^2 - 2\langle\mathbf v_\theta,\mathbf u\rangle + \lVert\mathbf u\rVert^2 . \]

The \(\lVert\mathbf v_\theta\rVert^2\) terms agree because both are expectations over the same \(p_t\). The cross terms agree because \(\mathbb E_{\mathbf x\sim p_t}\langle\mathbf v_\theta(\mathbf x),\mathbf u_t(\mathbf x)\rangle = \mathbb E_{\mathbf z,\ \mathbf x\sim p_t(\cdot\mid\mathbf z)}\langle\mathbf v_\theta(\mathbf x),\mathbf u_t(\mathbf x\mid\mathbf z)\rangle\) by the definition of \(\mathbf u_t\) as a conditional mean. The last terms do not involve \(\theta\). So \(\mathcal L_\text{FM} = \mathcal L_\text{CFM} + \text{const}\). For the linear path, \(\mathbf u_t(\mathbf x\mid\mathbf z) = \mathbf x_1 - \mathbf x_0\).

Derivation: velocity from the score for the linear Gaussian path

With \(\mathbf x_t = t\mathbf x_1 + (1-t)\mathbf x_0\) and \(\mathbf x_0\sim\mathcal N(\mathbf 0, I)\), the conditional of \(\mathbf x_t\) given \(\mathbf x_1\) is \(\mathcal N(t\mathbf x_1, (1-t)^2I)\), so Tweedie gives \(\mathbb E[\mathbf x_0\mid\mathbf x_t] = -(1-t)\nabla\log p_t(\mathbf x_t)\). From \(\mathbf x_t = t\,\mathbb E[\mathbf x_1\mid\mathbf x_t] + (1-t)\,\mathbb E[\mathbf x_0\mid\mathbf x_t]\), \(\mathbb E[\mathbf x_1\mid\mathbf x_t] = (\mathbf x_t + (1-t)^2\nabla\log p_t)/t\). Then

\[ \mathbf u_t = \mathbb E[\mathbf x_1\mid\mathbf x_t] - \mathbb E[\mathbf x_0\mid\mathbf x_t] = \frac{\mathbf x_t + (1-t)^2\nabla\log p_t + t(1-t)\nabla\log p_t}{t} = \frac{\mathbf x_t + (1-t)\nabla\log p_t(\mathbf x_t)}{t}. \]

Langevin dynamics, precisely. The SDE \(d\mathbf x = \tfrac12\nabla\log p(\mathbf x)\,dt + d\mathbf w\) has \(p\) as its stationary distribution (check with Fokker–Planck: the drift flux \(\tfrac12 p\nabla\log p\) cancels the diffusion flux \(\tfrac12\nabla p\)). The update in Ground level is its Euler–Maruyama discretisation with step \(\eta\); the discretisation bias vanishes as \(\eta\to0\) (or is removed by a Metropolis correction).

Likelihood of a flow. For any of these ODE models, \(\log p_1(\mathbf x(1)) = \log p_0(\mathbf x(0)) - \int_0^1\nabla\cdot\mathbf v_\theta(\mathbf x(t), t)\,dt\), with the divergence estimated by Hutchinson's estimator \(\mathbb E_{\boldsymbol\epsilon}[\boldsymbol\epsilon^\top(\partial\mathbf v/\partial\mathbf x)\boldsymbol\epsilon]\) (one vector–Jacobian product per sample). This is how flow-matching and diffusion models report bits per dimension.

Build it

1. Langevin dynamics, with and without annealing (NumPy). The exact score of a two-component mixture, sampled by plain and annealed Langevin:

import numpy as np
rng = np.random.default_rng(0)

# Data: 0.2 N(-4, 0.5^2) + 0.8 N(4, 0.5^2). Smoothing it with N(0, sigma^2) noise gives a
# mixture with variances 0.25 + sigma^2, whose score we can write down exactly.
w, mu, s2 = np.array([0.2, 0.8]), np.array([-4.0, 4.0]), 0.25

def score(x, sigma):
    v = s2 + sigma**2
    logp = np.log(w) - 0.5 * np.log(v) - 0.5 * (x[:, None] - mu) ** 2 / v
    r = np.exp(logp - logp.max(1, keepdims=True)); r /= r.sum(1, keepdims=True)
    return (r * (mu - x[:, None]) / v).sum(1)            # d/dx log p_sigma(x)

def langevin(x, sigma, n_steps, eps):
    for _ in range(n_steps):
        x = x + 0.5 * eps * score(x, sigma) + np.sqrt(eps) * rng.standard_normal(x.shape)
    return x

def left_fraction(x): return np.mean(x < 0)

x_init = rng.uniform(-8, 8, 20_000)                      # start spread out, no knowledge of the data
plain = langevin(x_init.copy(), sigma=0.0, n_steps=5_000, eps=0.01)
print(f"plain Langevin, 5000 steps     : left-mode fraction {left_fraction(plain):.3f}  (true 0.200)")

for levels in [10, 30]:                                 # NCSN-style annealing, large to small
    x = x_init.copy()
    for sig in np.geomspace(10, 0.01, levels):
        x = langevin(x, sig, n_steps=100, eps=0.1 * (sig**2 + s2))   # step ~ variance at level
    print(f"annealed Langevin, {levels:2d} levels   : left-mode fraction {left_fraction(x):.3f}"
          f"   std of right mode {np.std(x[x > 0]):.3f} (true 0.500)")
plain Langevin, 5000 steps     : left-mode fraction 0.494  (true 0.200)
annealed Langevin, 10 levels   : left-mode fraction 0.243   std of right mode 0.511 (true 0.500)
annealed Langevin, 30 levels   : left-mode fraction 0.212   std of right mode 0.502 (true 0.500)

2. The marginal velocity field, and how many steps it needs (NumPy). For a Gaussian-mixture data distribution the flow-matching optimum \(\mathbf u_t(\mathbf x) = \mathbb E[\mathbf x_1 - \mathbf x_0\mid\mathbf x_t]\) has a closed form. Integrate it with Euler steps and measure the curvature of the paths; then check the velocity–score identity:

import numpy as np
rng = np.random.default_rng(0)

# Data x1: 8 Gaussians (std 0.2) on a circle of radius 3. Noise x0 ~ N(0, I).
# Linear (rectified-flow / OT) path: x_t = t*x1 + (1-t)*x0, target velocity x1 - x0.
ang = 2 * np.pi * np.arange(8) / 8
mu, s = 3 * np.stack([np.cos(ang), np.sin(ang)], 1), 0.2

def velocity(x, t):
    """Exact marginal velocity u_t(x) = E[x1 - x0 | x_t = x] for this mixture."""
    v = t**2 * s**2 + (1 - t) ** 2                       # x_t | k ~ N(t mu_k, v I)
    d = x[:, None, :] - t * mu                            # (N, 8, 2)
    logr = -0.5 * (d**2).sum(-1) / v
    r = np.exp(logr - logr.max(1, keepdims=True)); r /= r.sum(1, keepdims=True)
    e_x1 = mu + t * s**2 / v * d                          # E[x1 | x_t, k]
    e_x0 = (1 - t) / v * d                                # E[x0 | x_t, k]
    return (r[..., None] * (e_x1 - e_x0)).sum(1)

def sample(n_steps, vel=velocity, n=8_000):
    x = rng.standard_normal((n, 2)); length = np.zeros(n); start = x.copy()
    for i in range(n_steps):                              # Euler from t=0 (noise) to t=1 (data)
        t = i / n_steps
        dx = vel(x, t) / n_steps
        x, length = x + dx, length + np.linalg.norm(dx, axis=1)
    return x, length / np.maximum(np.linalg.norm(x - start, axis=1), 1e-9)

def report(x):
    dist = np.linalg.norm(x[:, None, :] - mu, axis=-1)
    near, k = dist.min(1) < 0.6, dist.argmin(1)           # within 3 std of a mode centre
    counts = np.bincount(k[near], minlength=8) / max(near.sum(), 1)
    return f"on a mode {near.mean():.3f}   mode shares {counts.min():.3f}-{counts.max():.3f}"

for n_steps in [1, 2, 4, 8, 32, 128]:
    x, ratio = sample(n_steps)
    print(f"{n_steps:3d} Euler steps: {report(x)}   path length / displacement {np.median(ratio):.3f}")

# Diffusion and flow matching learn the same thing: velocity = (x + (1-t) * score) / t
def score(x, t):                                          # exact d/dx log p_t(x)
    v = t**2 * s**2 + (1 - t) ** 2
    d = x[:, None, :] - t * mu
    logr = -0.5 * (d**2).sum(-1) / v
    r = np.exp(logr - logr.max(1, keepdims=True)); r /= r.sum(1, keepdims=True)
    return -(r[..., None] * d).sum(1) / v
x, t = 2 * rng.standard_normal((5, 2)), 0.6
print("max |velocity - (x + (1-t) score)/t| =", np.abs(velocity(x, t) - (x + (1 - t) * score(x, t)) / t).max())
  1 Euler steps: on a mode 0.000   mode shares 0.000-0.000   path length / displacement 1.000
  2 Euler steps: on a mode 0.232   mode shares 0.116-0.135   path length / displacement 1.919
  4 Euler steps: on a mode 0.885   mode shares 0.119-0.133   path length / displacement 1.366
  8 Euler steps: on a mode 0.959   mode shares 0.120-0.129   path length / displacement 1.229
 32 Euler steps: on a mode 0.985   mode shares 0.119-0.136   path length / displacement 1.149
128 Euler steps: on a mode 0.989   mode shares 0.123-0.127   path length / displacement 1.134
max |velocity - (x + (1-t) score)/t| = 2.4424906541753444e-15

3. Flow matching as regression, then reflow (NumPy). No gradient descent at all: the velocity is linear in 2,000 random Fourier features of \((\mathbf x, t)\), so minimising \(\mathcal L_\text{CFM}\) is ridge regression with a closed-form solution. Then one round of reflow. It takes about a minute:

import numpy as np
rng = np.random.default_rng(0)

# Flow matching is regression. Fit v(x, t) ~ x1 - x0 on random Fourier features of (x, t)
# by ridge regression (closed form, no gradient descent), then integrate the ODE.
ang = 2 * np.pi * np.arange(8) / 8
mu, s = 3 * np.stack([np.cos(ang), np.sin(ang)], 1), 0.2        # same 8-Gaussian ring
data = lambda n: mu[rng.integers(0, 8, n)] + s * rng.standard_normal((n, 2))

F = 2000                                                          # number of random features
Wf = rng.standard_normal((3, F)) * np.array([[1.5], [1.5], [6.0]])
bf = rng.uniform(0, 2 * np.pi, F)
phi = lambda x, t: np.cos(np.column_stack([x, np.broadcast_to(t, len(x))]) @ Wf + bf)

def fit(pairs, n_batches, B=5000, lam=1e-3):
    """Minimise E||v(x_t, t) - (x1 - x0)||^2 over linear readouts: the CFM loss."""
    A, c = np.zeros((F, F)), np.zeros((F, 2))
    for _ in range(n_batches):
        x0, x1 = pairs(B); t = rng.uniform(0, 1, B)
        P = phi(t[:, None] * x1 + (1 - t[:, None]) * x0, t)      # features of x_t
        A += P.T @ P; c += P.T @ (x1 - x0)
    coef = np.linalg.solve(A + lam * n_batches * B / F * np.eye(F), c)
    return lambda x, t: phi(x, t) @ coef

def ode(vel, x, n_steps):                                         # Euler, t: 0 (noise) -> 1 (data)
    for i in range(n_steps): x = x + vel(x, i / n_steps) / n_steps
    return x

def report(x):
    dist = np.linalg.norm(x[:, None, :] - mu, axis=-1)
    near, k = dist.min(1) < 0.6, dist.argmin(1)
    shares = np.bincount(k[near], minlength=8) / max(near.sum(), 1)
    return f"on a mode {near.mean():.3f}   mode shares {shares.min():.3f}-{shares.max():.3f}"

# 1-rectified flow: independent coupling of noise and data
v1 = fit(lambda B: (rng.standard_normal((B, 2)), data(B)), n_batches=40)
for n in [1, 4, 32, 128]:
    print(f"flow matching, {n:3d} steps: " + report(ode(v1, rng.standard_normal((8000, 2)), n)))

# Reflow: pair each noise with the point its own ODE reaches, refit on those straight lines
def coupled(B):
    x0 = rng.standard_normal((B, 2))
    return x0, ode(v1, x0, 32)
v2 = fit(coupled, n_batches=10)
for n in [1, 2, 4]:
    print(f"after reflow,  {n:3d} steps: " + report(ode(v2, rng.standard_normal((8000, 2)), n)))
flow matching,   1 steps: on a mode 0.001   mode shares 0.000-0.600
flow matching,   4 steps: on a mode 0.718   mode shares 0.111-0.144
flow matching,  32 steps: on a mode 0.886   mode shares 0.120-0.133
flow matching, 128 steps: on a mode 0.899   mode shares 0.122-0.130
after reflow,    1 steps: on a mode 0.563   mode shares 0.115-0.137
after reflow,    2 steps: on a mode 0.671   mode shares 0.115-0.131
after reflow,    4 steps: on a mode 0.711   mode shares 0.118-0.134

The learned field is good but not perfect (89.9% on a mode at 128 steps against 98.9% for the exact field): 2,000 random features cannot represent the sharp velocity near \(t = 1\). Reflow trades a little of that accuracy for straightness: one step goes from 0.1% to 56.3%.

4. Flow matching for images (PyTorch; standard code, not run here). The whole training loop, with SD3's logit-normal time sampling:

import torch

def flow_matching_loss(model, x1):                     # x1: (B, C, H, W) data
    x0 = torch.randn_like(x1)                          # noise
    t = torch.sigmoid(torch.randn(x1.size(0)))         # logit-normal t in (0, 1)
    tb = t.view(-1, 1, 1, 1)
    xt = (1 - tb) * x0 + tb * x1                       # straight-line interpolation
    return ((model(xt, t) - (x1 - x0)) ** 2).mean()    # regress onto the velocity

@torch.no_grad()
def sample(model, shape, steps=50):
    x = torch.randn(shape)
    for i in range(steps):                             # Euler from t = 0 to t = 1
        t = torch.full((shape[0],), i / steps)
        x = x + model(x, t) / steps
    return x

Things to try

  • In snippet 1, move the modes to \(\pm 2\), then to \(\pm 1\). At \(\pm 2\) plain Langevin still returns about 0.47; at \(\pm 1\) the modes overlap, chains cross freely and it recovers about 0.21. Annealing matters exactly when modes are separated by low-density gaps.
  • In snippet 2, replace Euler with the midpoint method (evaluate the velocity at a half step). Compare 4 midpoint steps (8 evaluations) with 8 Euler steps.
  • In snippet 2, compute the trajectories' straightness for a variance-preserving diffusion path (\(a_t = \sin(\pi t/2)\), \(b_t = \cos(\pi t/2)\)) instead of the linear one.
  • In snippet 3, pair noise and data within each batch by solving an assignment problem (sort by angle is a cheap 2-D proxy) and refit. Does one-step sampling improve without reflow?
  • In snippet 3, train the score instead (target \(-\mathbf x_0/(1-t)\)) and sample with the identity \(\mathbf u = (\mathbf x + (1-t)\mathbf s)/t\). Where does it become unstable, and why?

In practice

  • Default recipe (2026): rectified-flow (linear) path, velocity prediction, \(t\) from a logit-normal or a resolution-shifted distribution, a transformer backbone, Euler or Heun with 20–50 steps, classifier-free guidance applied to the velocity (latent diffusion and guidance).
  • Conversions are free: a trained ε-, \(\mathbf x_0\)-, \(\mathbf v\)- or score model can be sampled with an ODE or SDE solver of your choice. Libraries such as diffusers and Meta's flow_matching implement the conversions.
  • Endpoints are fragile: near \(t = 1\) (data) the velocity is sharp and near \(t = 0\) it is close to the data mean. Clip or shift the time distribution, and never trust one-step Euler without distillation.
  • For inverse problems (inpainting, deblurring, reconstruction), keep the SDE view: add \(\nabla_{\mathbf x}\log p(\mathbf y\mid\mathbf x)\) to the learned score, or use the posterior-sampling variants built on it.

Common misconceptions

\"Rectified flow produces straight trajectories.\"

It trains on straight conditional paths. The learned marginal trajectories are curved wherever conditional paths cross (the figure above). Only reflow or optimal-transport couplings make them nearly straight.

\"Flow matching and diffusion are rival methods.\"

With Gaussian noise they learn interchangeable quantities. The differences are the path, the time weighting and the sampler, all of which can be mixed and matched.

\"The score is the gradient of the data density.\"

It is the gradient of the log-density, and the score a diffusion model learns is that of the noised density \(p_t\), which exists and is smooth even though the data distribution itself may have no density at all (it lives on a manifold).

Check yourself

Why does the score not depend on the normalising constant, and why does that matter?

\(\nabla_{\mathbf x}\log(\tilde p(\mathbf x)/Z) = \nabla_{\mathbf x}\log\tilde p(\mathbf x)\) because \(Z\) does not depend on \(\mathbf x\). A network can therefore model the score of an unnormalised density, and samplers such as Langevin dynamics only need the score.

In denoising score matching with noise σ, what is the regression target, and what does the optimal network compute?

Target \(-(\tilde{\mathbf x}-\mathbf x)/\sigma^2 = -\boldsymbol\epsilon/\sigma\). The optimum is its conditional mean given \(\tilde{\mathbf x}\), which equals \(\nabla\log p_\sigma(\tilde{\mathbf x})\), the score of the data convolved with \(\mathcal N(\mathbf 0,\sigma^2I)\).

Why does plain Langevin dynamics with the exact score return 0.494 instead of 0.2 for the left-mode fraction?

Between well-separated modes the density is negligible, so chains almost never cross, and the score near each mode does not depend on the mixture weights. Each chain stays in the basin it started in; with uniform initialisation on \([-8,8]\), about half start on each side.

Write the probability-flow ODE for the variance-preserving SDE.

\(\mathbf f = -\tfrac12\beta(t)\mathbf x\), \(g = \sqrt{\beta(t)}\), so \(d\mathbf x/dt = -\tfrac12\beta(t)\big[\mathbf x + \nabla\log p_t(\mathbf x)\big]\).

In flow matching, the per-sample targets x₁ − x₀ are different for every pair that passes through the same point. What does the network learn there?

Their conditional mean, the marginal velocity \(\mathbb E[\mathbf x_1-\mathbf x_0\mid\mathbf x_t=\mathbf x]\). The CFM loss has the same gradient as regressing onto that marginal velocity directly; the disagreement between pairs only adds a constant to the loss.

Why does one Euler step of the exact marginal velocity send every sample to the data mean?

At \(t=0\), \(\mathbf x_t = \mathbf x_0\) is independent of \(\mathbf x_1\), so \(\mathbf u_0(\mathbf x) = \mathbb E[\mathbf x_1] - \mathbf x\). One step of size 1 gives \(\mathbf x + \mathbb E[\mathbf x_1] - \mathbf x = \mathbb E[\mathbf x_1]\). The first step only knows the average destination; the structure appears as \(t\) grows.

Hard: why does reflow make paths straighter, and why can it hurt multi-step quality?

After the first flow, each noise point is paired with a deterministic endpoint, and the ODE's trajectories do not cross, so the straight lines between these pairs cross far less. The regression target becomes nearly unambiguous and the learned field nearly constant along each line. But the new training data are the first model's samples, with its errors, and the second fit adds its own error, so quality can degrade.

Hard: show that the Langevin SDE dx = ½∇log p dt + dw has p as a stationary distribution.

Fokker–Planck: \(\partial_t q = -\nabla\cdot(q\,\tfrac12\nabla\log p) + \tfrac12\Delta q\). At \(q = p\): \(-\tfrac12\nabla\cdot(p\nabla\log p) + \tfrac12\Delta p = -\tfrac12\nabla\cdot\nabla p + \tfrac12\Delta p = 0\).

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads