7. Phase Space Evolution, Liouville's Theorem & Continuous Flow Matching
From Hamiltonian Incompressibility and the Continuity Equation to Continuous Normalizing Flows, Flow Matching, and Optimal Transport
"The phase space is a strange and beautiful world where every point represents an entire universe in a specific microscopic state, and time evolution is nothing other than an incompressible fluid flow."
— Ludwig Boltzmann & J. Willard Gibbs
In the previous chapters, we analyzed static equilibrium ensembles, free energy landscapes, and the stochastic dynamics of Brownian particles via the Langevin equation and the Fluctuation-Dissipation theorem. In this chapter, we take a foundational step: we investigate the exact deterministic laws governing how probability distributions evolve through continuous dynamical systems.
We begin in the classical realm of 19th-century statistical mechanics with Hamiltonian mechanics, the phase space probability density ρ(q,p,t), and Liouville's Theorem, which establishes the profound incompressibility of Hamiltonian phase space flows. We then bridge this classical physics to 21st-century deep learning. By relaxing the Hamiltonian constraint to general vector fields on Euclidean and Riemannian manifolds, we arrive at the General Probability Continuity Equation, the engine behind Continuous Normalizing Flows (CNFs), and Flow Matching (Lipman et al., 2023).
Finally, we establish the exact mathematical dictionary linking Stochastic Differential Equations (SDEs), Fokker-Planck Equations, Deterministic Probability Flow ODEs, and Optimal Transport Flow Matching.
Consider a classical physical system with d degrees of freedom. In Newtonian mechanics, the state is specified by positions q∈Rd and velocities q˙∈Rd. In Hamiltonian mechanics, the state is elevated to a point in a 2d-dimensional phase spaceΓ≅R2d, parameterized by canonical generalized coordinates q=(q1,…,qd)⊤ and their conjugate momenta p=(p1,…,pd)⊤.
The state vector is denoted by:
z=(qp)∈Γ≅R2d
The total energy of the system is governed by the scalar Hamiltonian functionH(q,p,t):R2d×R→R. For standard mechanical systems with kinetic energy T(p) and potential energy V(q):
H(q,p)=i=1∑d2mipi2+V(q1,…,qd)
The time evolution of the microstate z(t) is governed by Hamilton's Canonical Equations of Motion:
q˙ip˙i=∂pi∂H=−∂qi∂Hfor i∈{1,…,d}
We can express these equations compactly using the canonical symplectic matrixJ∈R2d×2d:
z˙=J∇zH(z)
where:
J=(0−IdId0),J⊤=−J=J−1,J2=−I2d
Energy Conservation in Autonomous Systems
If the Hamiltonian does not explicitly depend on time (∂t∂H=0), the total energy is strictly conserved along any trajectory:
In statistical mechanics, we almost never know the exact microscopic state z(0) of a system containing N∼1023 particles. Instead, following Josiah Willard Gibbs, we define a statistical ensemble: a collection of an infinite number of virtual, non-interacting copies of the system, each evolving according to Hamilton's equations under identical macroscopic constraints.
We define the phase space probability densityρ(q,p,t)=ρ(z,t) such that the probability dP of finding the system in an infinitesimal phase volume element d2dz=dqdp=∏i=1ddqidpi at time t is:
dP=ρ(q,p,t)dq1…dqddp1…dpd=ρ(z,t)d2dz
The density is non-negative and normalized over the entire phase space Γ:
Substituting Hamilton's equations q˙i=∂pi∂H and p˙i=−∂qi∂H:
∂t∂ρ+i=1∑d(∂qi∂ρ∂pi∂H−∂pi∂ρ∂qi∂H)=0
We introduce the Poisson Bracket{⋅,⋅} between two phase space observables A(q,p) and B(q,p):
{A,B}≡i=1∑d(∂qi∂A∂pi∂B−∂pi∂A∂qi∂B)
This yields the celebrated Classical Liouville Equation:
∂t∂ρ=−{ρ,H}
Alternatively, defining the Liouvillian OperatorL^≡−{⋅,H}:
∂t∂ρ=L^ρ⟹ρ(t)=eL^tρ(0)
[!NOTE]
Physical Interpretation of Liouville's Theorem
Lagrangian Viewpoint (Co-moving observer): As an observer rides along a trajectory z(t) in phase space, the local probability density surrounding them never changes: dtdρ(z(t),t)=0.
Eulerian Viewpoint (Stationary observer): At a fixed coordinate z∈Γ, the local density changes at a rate exactly balanced by the advective probability flux: ∂t∂ρ=−∇zρ⋅v(z)=−{ρ,H}.
Equilibrium Ensembles: A distribution is stationary (∂t∂ρ=0) if and only if {ρ,H}=0. This is automatically satisfied whenever ρ(q,p)=f(H(q,p)) depends on coordinates only through the conserved energy H, yielding the Microcanonical Ensembleρ∝δ(H−E) and Canonical Ensembleρ∝e−βH.
In modern machine learning, statistics, and non-conservative physics, dynamics are not restricted to Hamiltonian vector fields. The vector field ut(x)∈Rd can have non-zero divergence (∇⋅ut=0), representing stretching, compression, and arbitrary smooth deformations of space.
In generative modeling, our objective is to transform an easily sampleable base noise distribution p0(x0)=N(x0;0,Id) into a complex, multi-modal target data distribution q(x1)≈pdata(x1).
Let ψt:Rd→Rd be the continuous flow map generated by an Ordinary Differential Equation (ODE) parameterized by a neural network vθ(x,t):
dtdx(t)=vθ(x(t),t),x(0)=x0∼p0(x0)
The state at time t is given by integrating the vector field:
x(t)=ψt(x0)=x0+∫0tvθ(x(s),s)ds
The pushforward distribution pt=[ψt]♯p0 satisfies the discrete change-of-variables formula:
pt(x(t))=p0(x0)det(∂x0∂ψt(x0))−1
Taking the logarithm:
logpt(x(t))=logp0(x0)−logdet(∂x0∂ψt(x0))
Using our Lagrangian continuity result dtdlogpt(x(t))=−∇⋅vθ(x(t),t), we integrate directly from t=0 to t=1:
The exact divergence ∇⋅vθ(x,t)=Tr(∂x∂vθ) requires computing all d diagonal elements of the Jacobian matrix ∂x∂vθ∈Rd×d. For high-dimensional data (e.g., images with d=3×512×512≈7.8×105), computing the full Jacobian requires d backward passes of automatic differentiation, which is computationally prohibitive (O(d) backward passes).
To solve this, Continuous Normalizing Flows (Chen et al., 2018; Grathwohl et al., 2019 - FFJORD) utilize Hutchinson's Stochastic Trace Estimator.
Let ϵ∈Rd be a random noise vector drawn from a zero-mean distribution with covariance identity Cov(ϵ)=E[ϵϵ⊤]=Id (such as standard Gaussian N(0,Id) or Rademacher distribution ϵi∈{−1,+1} with equal probability).
Despite the mathematical elegance of CNFs, training them via Maximum Likelihood requires numerically integrating the ODE x(t) and its divergence across the entire time interval t∈[0,1] for every gradient step. This makes CNF training notoriously slow, unstable, and prone to error accumulation.
Flow Matching (Lipman et al., ICLR 2023; Albergo & Vanden-Eijnden, 2023; Liu et al., 2023) revolutionizes continuous generative modeling by providing a simulation-free objective. It enables training continuous normalizing flows with simple regression losses—completely bypassing numerical ODE integration during training.
Lipman et al. (2023) solved this impasse by introducing Conditional Flow Matching (CFM).
Instead of working with the intractable marginal path pt(x), we condition on individual data points x1∼q(x1) (or pairs (x0,x1)). We define simple, tractable conditional probability pathspt(x∣x1) and corresponding conditional vector fieldsut(x∣x1) that satisfy the conditional continuity equation:
∂t∂pt(x∣x1)+∇⋅(pt(x∣x1)ut(x∣x1))=0
The marginal quantities are related to the conditional quantities by marginalization:
This objective is completely tractable and simulation-free: we sample x1∼q(x1), sample t∼U[0,1], sample x∼pt(x∣x1), evaluate the closed-form conditional vector field ut(x∣x1), and compute a standard MSE loss!
We now present the complete, rigorous mathematical proof that optimizing the tractable LCFM(θ) is mathematically identical to optimizing the intractable LFM(θ).
Theorem (Conditional Flow Matching Equivalence — Lipman et al., 2023)
Assuming pt(x)>0 for all x∈Rd and t∈[0,1], the gradients of the marginal Flow Matching loss and the Conditional Flow Matching loss with respect to the network parameters θ are identical:
∇θLFM(θ)=∇θLCFM(θ)
Consequently, LCFM(θ) and LFM(θ) share the exact same global and local parameter minima.
Now examine the cross-term ∫Rdpt(x)⟨vθ(x,t),ut(x)⟩dx. Substitute the definition of the marginal vector field ut(x)=∫ut(x∣x1)pt(x)pt(x∣x1)q(x1)dx1:
In practice, this is computed over mini-batches using the Hungarian algorithm or Earth Mover's Distance solver.
[!TIP]
Why Straight Paths Matter
When the trajectories x(t) are straight lines (ut(x)=const), the velocity field does not change direction along the flow. This allows numerical ODE solvers (e.g., Euler or Heun) to take massive step sizes, generating high-fidelity images in as few as 1 to 4 evaluation steps, compared to 50–1000 steps required by traditional curved diffusion models!
Consider a general forward Stochastic Differential Equation (SDE) in Rd:
dxt=f(xt,t)dt+g(t)dwt
where f(x,t)∈Rd is the drift coefficient, g(t)∈R is the scalar diffusion coefficient, and wt is standard d-dimensional Brownian motion (dwt∼N(0,dtId)).
The time evolution of the marginal probability density pt(x) is governed by the Fokker-Planck Equation (Forward Kolmogorov Equation):
∂t∂pt(x)=−∇⋅(f(x,t)pt(x))+21g(t)2∇2pt(x)
where ∇2pt(x)=∑i=1d∂xi2∂2pt=∇⋅(∇pt(x)) is the spatial Laplacian.
The following table summarizes the exact mathematical and conceptual correspondences between Classical Hamiltonian Statistical Mechanics, Stochastic Non-Equilibrium Thermodynamics, and Modern Continuous Generative Modeling.
Below is a complete, minimal, and fully runnable implementation of Optimal Transport Conditional Flow Matching (OT-CFM) in PyTorch, including Hutchinson trace estimation for log-likelihood evaluation.
import torchimport torch.nn as nnimport torch.optim as optimclass TimeMLP(nn.Module): """Time-dependent Vector Field v_theta(x, t)""" def __init__(self, dim=2, hidden_dim=128): super().__init__() self.net = nn.Sequential( nn.Linear(dim + 1, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, dim) ) def forward(self, x, t): # x: [B, dim], t: [B, 1] t_input = t if t.dim() == 2 else t.unsqueeze(-1) tx = torch.cat([x, t_input], dim=-1) return self.net(tx)class ConditionalFlowMatcher: """Optimal Transport / Linear Conditional Flow Matcher""" def __init__(self, sigma_min=1e-4): self.sigma_min = sigma_min def compute_loss(self, model, x_1): """ x_1: Target data batch [B, dim] """ B, dim = x_1.shape x_0 = torch.randn_like(x_1) # Base distribution p_0 ~ N(0, I) t = torch.rand(B, 1, device=x_1.device) # t ~ Uniform[0, 1] # Affine interpolation path: psi_t(x_0, x_1) = (1 - (1 - sigma_min)*t) * x_0 + t * x_1 # Target vector field: u_t(x|x_0, x_1) = x_1 - (1 - sigma_min) * x_0 psi_t = (1.0 - (1.0 - self.sigma_min) * t) * x_0 + t * x_1 u_t = x_1 - (1.0 - self.sigma_min) * x_0 # Neural network prediction v_pred = model(psi_t, t) # CFM Regression Loss loss = torch.mean((v_pred - u_t) ** 2) return loss @torch.no_grad() def sample_ode(self, model, num_samples, dim, steps=50, device='cpu'): """Euler ODE Integrator: dx = v_theta(x, t) dt from t=0 to 1""" x = torch.randn(num_samples, dim, device=device) dt = 1.0 / steps for step in range(steps): t_val = step * dt t_tensor = torch.full((num_samples, 1), t_val, device=device) v = model(x, t_tensor) x = x + v * dt # Euler step return xdef hutchinson_divergence(model, x, t, num_probes=1): """ Computes unbiased estimate of div(v_theta) = Tr(dv/dx) using Hutchinson's estimator """ x.requires_grad_(True) v = model(x, t) div = torch.zeros(x.shape[0], device=x.device) for _ in range(num_probes): # Rademacher noise eps in {-1, +1} eps = torch.randint(0, 2, x.shape, device=x.device).float() * 2.0 - 1.0 # Vector-Jacobian Product (VJP) vjp = torch.autograd.grad(v, x, grad_outputs=eps, create_graph=True)[0] div += torch.sum(vjp * eps, dim=-1) return div / num_probes
Let ω=mk. Differentiating q˙: q¨=mp˙=−mkq=−ω2q. The general solutions are:
q(t)p(t)=q0cos(ωt)+mωp0sin(ωt)=p0cos(ωt)−mωq0sin(ωt)
The Jacobian matrix is:
M(t)=(∂q0∂q(t)∂q0∂p(t)∂p0∂q(t)∂p0∂p(t))=(cos(ωt)−mωsin(ωt)mω1sin(ωt)cos(ωt))
Computing the determinant:
det(M(t))=(cos(ωt))(cos(ωt))−(mω1sin(ωt))(−mωsin(ωt))=cos2(ωt)+sin2(ωt)≡1
This proves exact volume preservation det(M(t))=1. ■
Differentiating ψt(x0,x1) with respect to t:
dtdψt(x0,x1)=μ˙t(x1)+σ˙tx0
Inverting the flow map for x0: x0=σtx−μt(x1). Substituting this into the velocity expression gives:
ut(x∣x1)=μ˙t(x1)+σtσ˙t(x−μt(x1))
Let pt(x∣x1)=(2πσt2)−d/2exp(−2σt2∥x−μt(x1)∥22).
Compute the time derivative of logpt:
∂t∂logpt=−σtdσ˙t+σt3σ˙t∥x−μt∥2+σt21(x−μt)⊤μ˙t
Compute the spatial gradient:
∇logpt=−σt2x−μt
Compute the divergence of ut:
∇⋅ut=i=1∑d∂xi∂(μ˙t,i+σtσ˙t(xi−μt,i))=dσtσ˙t
Now evaluate the left side of the continuity equation in logarithmic form:
∂t∂logpt+ut⋅∇logpt+∇⋅ut=[−dσtσ˙t+σt3σ˙t∥x−μt∥2+σt2μ˙t⋅(x−μt)]+(μ˙t+σtσ˙t(x−μt))⋅(−σt2x−μt)+dσtσ˙t=−dσtσ˙t+σt3σ˙t∥x−μt∥2+σt2μ˙t⋅(x−μt)−σt2μ˙t⋅(x−μt)−σt3σ˙t∥x−μt∥2+dσtσ˙t=0
Multiplying by pt(x∣x1) yields ∂t∂pt+∇⋅(ptut)=0. ■