09 · Flow matching

NoteDraft — Learning the sampling velocity directly

Part 08 established that a learned velocity can define a continuous normalizing flow. Flow matching gives a regression objective for learning that velocity. We retain \(t=0\) for data and \(t=1\) for the prior; generation runs from 1 to 0. Many flow-matching papers use the opposite convention. With \(\tau=1-t\), the reversed field is \(\widetilde v(x,\tau)=-v(x,1-\tau)\): both the sign and time argument change.

Primary reference: Lipman et al., Flow Matching for Generative Modeling. The straight interpolation below is the zero-terminal-smoothing limit of the Gaussian conditional path, written in our reversed time convention. Independent endpoint interpolation is also studied in rectified flow, stochastic interpolants, and independent conditional flow matching. A positive smoothing variance avoids the point-mass conditional data endpoint; here that endpoint is understood as a limit.

1. The learning objective is still sampling

We want a field \(v_\theta(x,t)\) whose ODE transports \(p_0=p_{\mathrm{data}}\) to a tractable \(p_1\). Once it is learned, draw \(X_1\sim p_1\) and integrate backward.

Score-based diffusion constructs a probability path by a forward SDE, learns its score, and then computes its velocity. Flow matching can instead specify a path through a directly sampleable interpolation and learn the velocity by regression. Neither approach requires solving the sampling ODE for every training example.

We start in one dimension. The same formulas hold for vectors with squared Euclidean loss and vector-valued velocities.

2. Construct training pairs and their conditional velocities

Draw independently

\[X_0\sim p_{\mathrm{data}},\qquad X_1\sim\mathcal N(0,1).\]

For these endpoint draws, define a straight interpolating trajectory

\[\boxed{X_t=(1-t)X_0+tX_1,\qquad \frac{dX_t}{dt}=X_1-X_0.}\]

At time zero the marginal is the data distribution, and at time one it is exactly standard normal. Between them, \(p_t\) is the distribution of the interpolated random variable. It is not the density mixture \((1-t)p_0+tp_1\).

We know the velocity label \(U=X_1-X_0\) because both endpoints are available during training. The predictor receives only \((X_t,t)\), not both endpoints. For \(t>0\), conditioning only on the clean endpoint gives

\[X_t\mid X_0=x_0\sim\mathcal N((1-t)x_0,t^2),\]

with conditional field

\[u_t(x\mid x_0)=\frac{x-x_0}{t}.\]

At a constructed training observation, \(u_t(X_t\mid X_0)=X_1-X_0\). The quotient therefore need not be evaluated in code.

3. Why velocity regression produces the marginal transport

Train with

\[\boxed{\mathcal L_{\mathrm{CFM}}(\theta) =\mathbb E_{t,X_0,X_1} [(v_\theta((1-t)X_0+tX_1,t)-(X_1-X_0))^2],}\]

where \(t\sim\operatorname{Uniform}(0,1)\) and the three draws are independent before constructing \(X_t\). Assume finite second moments for this loss. Squared-error regression gives

\[\boxed{v_*(x,t)=\mathbb E[X_1-X_0\mid X_t=x,t].}\]

This is the conditional flow-matching (CFM) loss. Direct regression onto the unavailable marginal velocity would use \(\mathcal L_{\mathrm{FM}}=\mathbb E_{t,X_t}[(v_\theta(X_t,t)-v_*(X_t,t))^2]\). The two losses differ by a parameter-independent conditional-variance term, so their population gradients and minimizers agree when differentiation is justified.

More explicitly, at a fixed input \(x\) and time \(t\), write \(U=X_1-X_0\) and \(v_*(x,t)=\mathbb E[U\mid X_t=x,t]\). Expanding the square gives

\[\begin{aligned} \mathbb E[(v_\theta(x,t)-U)^2\mid X_t=x,t] &=(v_\theta(x,t)-v_*(x,t))^2\\ &\quad+\operatorname{Var}(U\mid X_t=x,t). \end{aligned}\]

Averaging over the time and interpolation marginals proves the loss relationship. The posterior averaging is supplied by regression on joint endpoint/interpolation samples; no posterior density is evaluated.

The expectation is over endpoint pairs compatible with the fixed noisy/intermediate input. As in Part 03, individual labels differ from their conditional-mean prediction. The loss decomposes into a velocity-estimation error plus a conditional variance independent of the network.

Why does this conditional mean transport the right density? Each endpoint pair supplies a trajectory with known velocity. Averaging its contribution to probability transport at a location gives precisely the field above. Appendix A verifies that the interpolation marginals satisfy

\[\partial_tp_t=-\partial_x(p_tv_*).\]

Under regularity ensuring the corresponding ODE is well posed and the density evolution is unique, its flow follows these marginals. Positive-time regularity does not automatically guarantee a smooth invertible map at a singular data endpoint.

Individual straight paths are not the learned ODE trajectories

Different endpoint pairs can pass through the same position at the same time with different velocities. Their regression average defines a single field. Its trajectories generally differ from the individual training lines. The result concerns shared marginal densities, not recovery of the originally sampled endpoint coupling.

Independent endpoint pairing is convenient, but it is not generally an optimal-transport coupling. Straight conditional paths do not imply globally optimal transport, straight marginal trajectories, or exact one-step sampling. Different couplings with the same endpoint marginals can give different paths and fields.

4. Connection to the posterior mean and score

Let \(m_t(x)=\mathbb E[X_0\mid X_t=x]\). From the interpolation equation,

\[X_1-X_0=\frac{X_t-X_0}{t},\]

so

\[\boxed{v_*(x,t)=\frac{x-m_t(x)}{t},\qquad t>0.}\]

The Gaussian conditional also gives the Tweedie identity

\[s_t(x)=\frac{(1-t)m_t(x)-x}{t^2}.\]

For \(0<t<1\), eliminate \(m_t(x)\) to obtain

\[\boxed{v_*(x,t)=-\frac{x+t\,s_t(x)}{1-t}.}\]

This score-to-velocity formula belongs to this particular interpolation; it is not the VP formula. Here the clean amplitude is \(1-t\) and the noise standard deviation is \(t\), so their squared sum is not generally one. The displayed division by \(1-t\) should not be used at the terminal endpoint. Direct velocity prediction avoids that algebraic singularity; it does not guarantee an easy learning problem at all times.

Recovering the VP probability-flow field

More generally, construct \(X_t=\alpha_tX_0+\sigma_t\varepsilon\) with independent clean data and standard Gaussian noise, and differentiate the sample path using the same pair:

\[U_t=\alpha_t'X_0+\sigma_t'\varepsilon.\]

Conditional regression yields

\[v_*(x,t)=\alpha_t' m_t(x)+\sigma_t'\mathbb E[\varepsilon\mid X_t=x].\]

For a general Gaussian corruption, \(m_t(x)=(x+\sigma_t^2s_t(x))/\alpha_t\) and \(\mathbb E[\varepsilon\mid X_t=x]=-\sigma_ts_t(x)\), by the same differentiation as in Part 03. Substitution gives, on positive-noise times with \(\alpha_t>0\),

\[v_*(x,t)=\frac{\alpha_t'}{\alpha_t}x+ \left(\frac{\alpha_t'}{\alpha_t}\sigma_t^2-\sigma_t\sigma_t'\right)s_t(x).\]

For VP, \(\alpha_t'/\alpha_t=-\beta(t)/2\), \(\sigma_t^2=1-\alpha_t^2\), and \(\sigma_t\sigma_t'=\beta(t)\alpha_t^2/2\). Consequently,

\[\boxed{v_*(x,t)=-\frac{\beta(t)}2[x+s_t(x)].}\]

Thus regression on conditional velocities can recover the same probability-flow field as score regression for the same Gaussian marginal path. Reusing one noise draw here defines a differentiable interpolation coupling, not a Brownian SDE trajectory. Finite VP schedules retain the terminal approximation discussed earlier. Also, the derivative label can grow near zero noise; finite-loss and optimization considerations can require a cutoff or weighting.

5. A solved Gaussian example

Take independent \(X_0\sim\mathcal N(\mu,V)\) and \(X_1\sim\mathcal N(0,1)\), with \(V>0\). Straight interpolation gives

\[p_t=\mathcal N(m_t^{\mathrm{path}},V_t),\qquad m_t^{\mathrm{path}}=(1-t)\mu,\quad V_t=(1-t)^2V+t^2.\]

Here \(m_t^{\mathrm{path}}\) is the marginal mean, distinct from the posterior denoiser \(m_t(x)\). The marginal velocity is

\[\boxed{v_*(x,t)=-\mu+ \frac{t-(1-t)V}{V_t}[x-(1-t)\mu].}\]

To verify it, keep a fixed \(Z\sim\mathcal N(0,1)\) and define \(x_t=(1-t)\mu+\sqrt{V_t}Z\). Differentiation produces the displayed field because \(V_t'/2=t-(1-t)V\). Backward transport maps \(x_1=Z\) to \(x_0=\mu+\sqrt VZ\).

Even when \(\mu=0,V=1\), the interpolation variance falls to \(1/2\) at \(t=1/2\) and then rises to one. Equal endpoint distributions do not imply a stationary chosen path. This is another reason to assess the whole path rather than endpoint similarity alone.

Check the score-to-velocity conversion

The score of this Gaussian path is

\[s_t(x)=-\frac{x-(1-t)\mu}{V_t}.\]

For \(0<t<1\), substituting it into the general straight-path formula gives

\[\begin{aligned} -\frac{x+t s_t(x)}{1-t} &=\frac{(t-V_t)x-t(1-t)\mu}{(1-t)V_t}\\ &=\frac{t-(1-t)V}{V_t}x-\frac{t\mu}{V_t}\\ &=-\mu+\frac{t-(1-t)V}{V_t}[x-(1-t)\mu]. \end{aligned}\]

Here \(t-V_t=(1-t)[t-(1-t)V]\). The expression agrees with the field obtained by differentiating the exact trajectory. Unlike the score conversion with its apparent endpoint division, the final Gaussian expression is well defined at both endpoints because \(V>0\).

6. Minimal training and backward sampling

For a scalar network velocity(x, t) and a tensor training_data, the following is the training core. A vector model uses matching vector-shaped noise and averages squared coordinate errors.

# velocity is a time-conditioned neural network; optimizer updates its parameters.
for update in range(updates):
    indices = torch.randint(len(training_data), (batch_size,))
    x0 = training_data[indices]
    x1 = torch.randn_like(x0)
    t = torch.rand(len(x0), device=x0.device)  # One time per example.
    t_broadcast = t.view(-1, *([1] * (x0.ndim - 1)))
    xt = (1 - t_broadcast) * x0 + t_broadcast * x1
    target = x1 - x0
    loss = (velocity(xt, t) - target).square().mean()
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()

Generation uses decreasing time and the same velocity convention:

@torch.no_grad()
def sample_flow(velocity, count=1000, steps=1000):
    was_training = velocity.training
    velocity.eval()
    x = torch.randn(count)
    times = torch.linspace(1.0, 0.0, steps + 1)
    for t, next_t in zip(times[:-1], times[1:]):
        h = t - next_t
        x = x - h * velocity(x, torch.full_like(x, float(t)))
    velocity.train(was_training)
    return x

The scalar network takes position and time tensors of shape (batch,), as does Part 06; a vector network must accept vector positions and one scalar time per example. These are CPU scalar sampling snippets, not a complete trained experiment. Near-endpoint network extrapolation and integration error still require checking; a finite dataset has an atomic empirical endpoint, while the desired population may be continuous. Compare held-out moments, mode mass, CDFs, and exact-field references where available, as in Part 06. A network trained with flow matching is not automatically accurate enough for one Euler step.

Appendix A. Why the averaged velocity follows the marginal path

Let \(\varphi\) be a smooth compactly supported test function. Under integrability allowing differentiation inside the expectation,

\[\begin{aligned} \frac{d}{dt}\mathbb E[\varphi(X_t)] &=\mathbb E[\varphi'(X_t)(X_1-X_0)]\\ &=\mathbb E[\varphi'(X_t)\mathbb E[X_1-X_0\mid X_t,t]]\\ &=\int\varphi'(x)v_*(x,t)p_t(x)\,dx\\ &=-\int\varphi(x)\partial_x[p_t(x)v_*(x,t)]\,dx. \end{aligned}\]

The left side is \(\int\varphi(x)\partial_tp_t(x)\,dx\). The equality before integration by parts is the weak continuity equation. The final derivative can be interpreted distributionally; when \(p_tv_*\) and \(p_t\) have the needed smoothness, it gives the usual differential form. Replace \(\varphi'\) by \(\nabla\varphi\) and the product by an inner product to obtain the vector result. This is the mechanism behind conditional flow matching: known conditional velocities determine a learnable marginal velocity. Lipman et al., conditional flow matching