Skip to content
AILinkDeepTech
Go back
Generative Models Advanced

Flow Matching: Continuous Normalizing Flows, Optimal Transport Paths, and Rectified Flow Dynamics

Abstract

Master Flow Matching: continuity equation foundations, conditional flow matching (CFM) equivalence theorems, optimal transport displacement paths, Reflow trajectory straightening, and production PyTorch ODE solvers.

The Curvature Bottleneck in Classical Diffusion Models

Classical continuous-time diffusion modelsβ€”including Denoising Diffusion Probabilistic Models (DDPM), Score-based Generative Models (SGMs), and Variance Preserving/Variance Exploding Stochastic Differential Equations (VP/VE-SDEs)β€”frame generation as the time-reversal of a forward Ornstein-Uhlenbeck stochastic process:

The reverse probability flow ordinary differential equation (ODE) derived via Fokker-Planck duality takes the form:

While mathematically rigorous, this formulation introduces severe structural and computational bottlenecks:

  1. Curved Integration Trajectories: The score function evolves non-linearly across time. Trajectories between Gaussian noise and complex multi-modal data are highly curved in latent space.
  2. Severe Discretization Truncation Errors: Standard numerical ODE solvers (such as Euler-Maruyama or Runge-Kutta) incur local truncation errors proportional to trajectory curvature: , where . High curvature forces models to execute between and sequential neural evaluations (NFEs) to avoid cumulative sampling drift.
  3. Singularities and Schedule Sensitivity: Handcrafted variance schedules (, cosine schedules, signal-to-noise ratio SNR thresholds) require meticulous tuning and exhibit vanishing or exploding gradients near boundaries and .

Flow Matching (FM) (Lipman et al., 2022; Albergo & Vanden-Eijnden, 2022; Liu et al., 2022) establishes a unified, deterministic framework based on Continuous Normalizing Flows (CNFs). By constructing Optimal Transport (OT) displacement interpolations, Flow Matching straightens generative trajectories into constant-velocity straight lines:

This eliminates trajectory acceleration (), enabling high-fidelity sampling in as few as steps, and serving as the foundational mathematical engine for modern foundational generative models including Stable Diffusion 3, FLUX.1, Lumina-Next, and Meta Voicebox.


Architectural & Theoretical Paradigm Comparison

Generative ParadigmForward ProcessReverse Sampling DynamicTrajectory GeometryTypical NFEs for SOTA FIDLoss Function Objective
DDPM (Ho et al.)Discrete Gaussian Markov ChainDiscrete Reverse Markov TransitionsCurved Stochastic Walk
Score SDE (Song et al.)ItΓ΄ SDE (VP / VE / sub-VP)Reverse-Time SDE / Probability ODEHigh Curvature Curved FlowDenoising Score Matching (DSM)
EDM (Karras et al.)Scaled Gaussian PerturbationEmpirical Probability Flow ODEModerate Curvature Curved FlowReweighted Denoising Loss
Flow Matching (Lipman)Continuous Probability PathDeterministic Vector Field ODEZero-Curvature Straight LineConditional Flow Matching (CFM)
Rectified Flow + ReflowStraight Linear InterpolationDeterministic Reflow Straight LineUntangled Zero-Curvature Line (Distilled)Straight-Line Velocity Regression

Mathematical Foundations of Flow Matching

flowchart TD subgraph Theoretical_Equivalence["Marginal vs Conditional Equivalence"] direction TB MARGINAL["Marginal Target: Vector Field u_t(x)\n(Intractable High-Dimensional Integral)"] EQUIV["Equivalence Theorem (Lipman et al.):\nGrad_theta L_FM(theta) == Grad_theta L_CFM(theta)"] CONDITIONAL["Conditional Target: Vector Field u_t(x | x_0, x_1)\n(Analytic Constant Velocity: x_1 - x_0)"] MARGINAL -.-> EQUIV CONDITIONAL --> EQUIV end subgraph Trajectory_Geometry["Geometric Path Comparison"] direction LR SDE_PATH["Diffusion SDE:\nCurved Random Walks\nDiscretization Error O(dt^2)"] OT_PATH["Optimal Transport Flow:\nConstant Velocity Straight Line\nZero Curvature: d^2x/dt^2 = 0"] REFLOW_PATH["2-Rectified Flow (Reflow):\nUntangled Deterministic Lines\nUltra-Fast 1-4 Step Sampling"] end subgraph Implementation_Graph["Production Execution Graph"] NOISE["Prior Sample: x_1 ~ N(0, I)"] --> INTERPOLATE["Displacement Interpolation:\nx_t = (1 - t) * x_0 + t * x_1"] DATA["Target Sample: x_0 ~ p_data"] --> INTERPOLATE TIME["Timestep: t ~ Uniform(0, 1)"] --> INTERPOLATE INTERPOLATE --> MODEL["Neural Velocity Estimator: v_theta(x_t, t, c)"] VELOCITY_TARGET["Analytical Velocity Target:\nu_t = x_1 - x_0"] --> LOSS["CFM Regression Loss:\n|| v_theta(x_t, t, c) - (x_1 - x_0) ||^2"] MODEL --> LOSS end

Figure 1: Mathematical topology and execution flow of Conditional Flow Matching (CFM) operating on Optimal Transport paths.


1. Continuous Normalizing Flows & The Continuity Equation

Let denote the state space. A Continuous Normalizing Flow (CNF) defines a time-dependent diffeomorphism governed by an Ordinary Differential Equation:

where is a time-dependent vector field. The push-forward probability density satisfies the fundamental Continuity Equation (Conservation of Probability):

where denotes the divergence operator.

Given a target velocity field that successfully transports an initial distribution (or standard Gaussian prior ) across time, we parameterize a neural network to minimize the Marginal Flow Matching objective:

The Intractability Bottleneck:

The true marginal velocity field is an intractable expectation over data distribution :

Evaluating directly requires computing the partition function , rendering naive intractable for internet-scale data.


2. The Conditional Flow Matching (CFM) Equivalence Theorem

To bypass marginal density integration, Lipman et al. introduced Conditional Flow Matching (CFM). Instead of targeting the global marginal field, we supervise the model using conditioned probability paths generated by conditioned vector fields .

The Conditional Flow Matching objective is:

Rigorous Theorem: Gradient Equivalence of FM and CFM

Assuming for all and , the parameter gradients of the marginal objective and the conditional objective are strictly identical:

Analytical Proof:

Expanding the gradient of the marginal loss:

Substituting the marginal velocity definition :

Engineering Significance: To optimize a global generative vector field over arbitrary distributions, we do not need to know the true marginal probability density . Regressing per-sample conditional trajectories guarantees stochastic gradient convergence to the exact marginal velocity field.


3. Optimal Transport (OT) Displacement Interpolation

Under the 2-Wasserstein metric , the path connecting a base distribution and target distribution that minimizes kinetic action (kinetic energy expenditure ) is McCann’s Displacement Interpolation:

where (clean data) and (prior noise), or reversed depending on convention.

Differentiating directly with respect to time parameter :

Fundamental Geometric Properties:

  1. Zero Curvature: . The trajectory is an exact line segment in Euclidean space.
  2. Constant Velocity Magnitude: The instantaneous velocity vector does not accelerate or decelerate across the entire interval .
  3. Loss Simplification: The training regression target collapses to a trivial linear subtraction:


4. Trajectory Crossing and the Reflow Algorithm

While individual conditional paths are linear, sampling independent pairs produces trajectory crossings in high-dimensional space: two different paths intersect at intermediate time ( with different endpoints).

When paths cross, the marginal vector field must average contradicting velocity vectors:

This induces curvature in the integrated marginal flow and causes blurred outputs when stepping with large discretization intervals ().

[Independent Coupling (1-RF)]           [Straightened Monge Coupling (2-RF / Reflow)]
   x_1 (Noise)                              x_1 (Noise)
    o       o       o                        o       o       o
     \     / \     /                          \       \       \
      \   /   \   /      Trajectory            \       \       \    Completely Uncrossed
       \ /     \ /       Crossings              \       \       \   Straight Trajectories
        X       X                                \       \       \
       / \     / \                                \       \       \
      o   o   o   o                                o       o       o
    x_0 (Data Distribution)                  x_0 (Data Distribution)

The Reflow algorithm (Liu et al., 2022) straightens these trajectories via iterative self-distillation:

The 2-Rectified Flow Protocol:

  1. Train Base 1-Rectified Flow: Train using random independent pairs .
  2. Generate Deterministic Couplings: For a batch of noise vectors , solve the reverse ODE numerically using a high-precision solver (e.g., RK45 with 100 steps) to arrive at synthetic endpoints .
  3. Train 2-Rectified Flow on Couplings: Train a new network on the deterministic pairs :

Because is uniquely mapped from , the paths never intersect. The resulting vector field exhibits virtually zero curvature, allowing high-quality one-step and two-step generation (1-NFE / 2-NFE generation).


Production PyTorch Implementation

Below is a complete, modular PyTorch implementation encompassing Optimal Transport Conditional Flow Matching (OT-CFM), the Reflow Dataset Generator, and high-order ODE Numerical Solvers (Euler, Heun/Midpoint, RK4).

Step 1: Flow Matching Core Loss Engine & Velocity Backbone

from __future__ import annotations

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


class TimestepEmbedder(nn.Module):
    """Sinusoidal positional embeddings for continuous time t in [0, 1]."""

    def __init__(self, hidden_dim: int, frequency_embedding_size: int = 256) -> None:
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(frequency_embedding_size, hidden_dim),
            nn.SiLU(),
            nn.Linear(hidden_dim, hidden_dim),
        )
        self.frequency_embedding_size = frequency_embedding_size

    @staticmethod
    def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10000.0) -> torch.Tensor:
        half = dim // 2
        freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
        args = t.float().unsqueeze(1) * freqs.unsqueeze(0)
        embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
        if dim % 2 == 1:
            embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
        return embedding

    def forward(self, t: torch.Tensor) -> torch.Tensor:
        t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
        return self.mlp(t_freq)


class VelocityMLP(nn.Module):
    """A continuous velocity field network v_theta(x, t, c) for continuous latent vectors."""

    def __init__(self, data_dim: int, hidden_dim: int = 512, cond_dim: int = 512) -> None:
        super().__init__()
        self.time_embed = TimestepEmbedder(hidden_dim)
        self.cond_proj = nn.Linear(cond_dim, hidden_dim) if cond_dim > 0 else None

        self.net = nn.Sequential(
            nn.Linear(data_dim + hidden_dim, hidden_dim),
            nn.LayerNorm(hidden_dim),
            nn.SiLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.LayerNorm(hidden_dim),
            nn.SiLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.LayerNorm(hidden_dim),
            nn.SiLU(),
            nn.Linear(hidden_dim, data_dim),
        )

    def forward(
        self,
        x: torch.Tensor,
        t: torch.Tensor,
        cond: torch.Tensor | None = None,
    ) -> torch.Tensor:
        # t is shape [B], continuous in [0, 1]
        t_emb = self.time_embed(t)
        if self.cond_proj is not None and cond is not None:
            t_emb = t_emb + self.cond_proj(cond)

        h = torch.cat([x, t_emb], dim=-1)
        return self.net(h)


class OptimalTransportCFM(nn.Module):
    """Optimal Transport Conditional Flow Matching (OT-CFM) Training Objective."""

    def __init__(self, sigma_min: float = 1e-4) -> None:
        super().__init__()
        self.sigma_min = sigma_min

    def compute_loss(
        self,
        model: nn.Module,
        x_0: torch.Tensor,
        x_1: torch.Tensor | None = None,
        cond: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """
        Computes OT-CFM loss:
        - x_0: Clean data batch [B, D]
        - x_1: Gaussian prior noise [B, D] (sampled if None)
        """
        batch_size, *_, device = *x_0.shape, x_0.device
        if x_1 is None:
            x_1 = torch.randn_like(x_0)

        # 1. Sample continuous timestep uniformly: t ~ U(0, 1)
        t = torch.rand(batch_size, device=device)

        # 2. Compute McCann OT displacement interpolation: x_t = (1 - t) * x_0 + t * x_1
        # To prevent degenerate boundary variance, we incorporate sigma_min
        t_exp = t.view(batch_size, *([1] * (x_0.ndim - 1)))
        x_t = (1.0 - (1.0 - self.sigma_min) * t_exp) * x_0 + t_exp * x_1

        # 3. Exact constant conditional velocity target: u_t = x_1 - (1 - sigma_min) * x_0
        u_t = x_1 - (1.0 - self.sigma_min) * x_0

        # 4. Neural velocity prediction
        v_pred = model(x_t, t, cond)

        # 5. Mean Squared Error regression
        return F.mse_loss(v_pred, u_t)

Step 2: High-Precision Numerical ODE Solvers for Inference

from __future__ import annotations

import torch
import torch.nn as nn


@torch.no_grad()
def solve_ode_euler(
    model: nn.Module,
    x_init: torch.Tensor,
    steps: int = 20,
    cond: torch.Tensor | None = None,
    guidance_scale: float = 1.0,
    null_cond: torch.Tensor | None = None,
    t_start: float = 1.0,
    t_end: float = 0.0,
) -> torch.Tensor:
    """
    First-order Euler numerical integrator for Flow Matching ODE:
    dx/dt = v_theta(x, t)
    """
    x = x_init.clone()
    batch_size = x.shape[0]
    timesteps = torch.linspace(t_start, t_end, steps + 1, device=x.device)

    for i in range(steps):
        t_curr = timesteps[i].repeat(batch_size)
        dt = timesteps[i + 1] - timesteps[i]  # Negative when integrating from 1 to 0

        # Forward velocity evaluation
        v = model(x, t_curr, cond)

        # Classifier-Free Guidance extrapolation
        if guidance_scale > 1.0 and null_cond is not None:
            v_uncond = model(x, t_curr, null_cond)
            v = v_uncond + guidance_scale * (v - v_uncond)

        # Euler step
        x = x + dt * v

    return x


@torch.no_grad()
def solve_ode_midpoint(
    model: nn.Module,
    x_init: torch.Tensor,
    steps: int = 10,
    cond: torch.Tensor | None = None,
    t_start: float = 1.0,
    t_end: float = 0.0,
) -> torch.Tensor:
    """
    Second-order Runge-Kutta (Midpoint / Heun) numerical ODE integrator.
    Halves truncation error to O(dt^3) per step.
    """
    x = x_init.clone()
    batch_size = x.shape[0]
    timesteps = torch.linspace(t_start, t_end, steps + 1, device=x.device)

    for i in range(steps):
        t_curr = timesteps[i].repeat(batch_size)
        dt = timesteps[i + 1] - timesteps[i]
        t_mid = t_curr + 0.5 * dt

        # Stage 1: Half-step predictor
        v_curr = model(x, t_curr, cond)
        x_mid = x + 0.5 * dt * v_curr

        # Stage 2: Midpoint corrector
        v_mid = model(x_mid, t_mid, cond)
        x = x + dt * v_mid

    return x


@torch.no_grad()
def solve_ode_rk4(
    model: nn.Module,
    x_init: torch.Tensor,
    steps: int = 10,
    cond: torch.Tensor | None = None,
    t_start: float = 1.0,
    t_end: float = 0.0,
) -> torch.Tensor:
    """
    Classical Fourth-Order Runge-Kutta (RK4) ODE solver.
    Delivers near-analytic precision on complex multi-modal trajectories.
    """
    x = x_init.clone()
    batch_size = x.shape[0]
    timesteps = torch.linspace(t_start, t_end, steps + 1, device=x.device)

    for i in range(steps):
        t_n = timesteps[i].repeat(batch_size)
        dt = timesteps[i + 1] - timesteps[i]

        k1 = model(x, t_n, cond)
        k2 = model(x + 0.5 * dt * k1, t_n + 0.5 * dt, cond)
        k3 = model(x + 0.5 * dt * k2, t_n + 0.5 * dt, cond)
        k4 = model(x + dt * k3, t_n + dt, cond)

        x = x + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)

    return x

Step 3: Complete Reflow Training & Dataset Untangling

from __future__ import annotations

import torch
import torch.nn as nn
from flow_matching_core import OptimalTransportCFM, VelocityMLP
from ode_solvers import solve_ode_rk4


def train_1_rectified_flow(
    model: VelocityMLP,
    data_loader: torch.utils.data.DataLoader,
    epochs: int = 10,
    lr: float = 1e-4,
    device: str = "cuda",
) -> None:
    """Trains base 1-Rectified Flow model on independent couplings (x_0, x_1)."""
    model.to(device)
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-5)
    cfm = OptimalTransportCFM()

    model.train()
    for epoch in range(epochs):
        total_loss = 0.0
        for batch in data_loader:
            x_0 = batch[0].to(device)
            optimizer.zero_grad(set_to_none=True)

            loss = cfm.compute_loss(model, x_0)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            optimizer.step()

            total_loss += loss.item()


@torch.no_grad()
def construct_reflow_dataset(
    model_1rf: VelocityMLP,
    num_samples: int,
    data_dim: int,
    steps: int = 50,
    device: str = "cuda",
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Executes ODE integration from x_1 ~ N(0, I) down to t=0 to construct
    deterministic uncrossed pairs (x_0_hat, x_1).
    """
    model_1rf.eval()
    model_1rf.to(device)

    # 1. Sample pure noise prior x_1
    x_1_all = torch.randn(num_samples, data_dim, device=device)

    # 2. Integrate ODE down to t=0 using high-order RK4
    x_0_hat_all = solve_ode_rk4(
        model_1rf,
        x_init=x_1_all,
        steps=steps,
        t_start=1.0,
        t_end=0.0,
    )

    return x_0_hat_all.cpu(), x_1_all.cpu()


def train_2_rectified_flow(
    model_2rf: VelocityMLP,
    x_0_hat: torch.Tensor,
    x_1: torch.Tensor,
    batch_size: int = 256,
    epochs: int = 10,
    lr: float = 1e-4,
    device: str = "cuda",
) -> None:
    """
    Trains 2-Rectified Flow (Reflow) on straightened deterministic couplings.
    Eliminates path crossings, enabling 1-step to 4-step generation.
    """
    model_2rf.to(device)
    optimizer = torch.optim.AdamW(model_2rf.parameters(), lr=lr)
    num_samples = x_0_hat.shape[0]

    model_2rf.train()
    for epoch in range(epochs):
        perm = torch.randperm(num_samples)
        for i in range(0, num_samples, batch_size):
            idx = perm[i : i + batch_size]
            b_x0 = x_0_hat[idx].to(device)
            b_x1 = x_1[idx].to(device)

            b_size = b_x0.shape[0]
            t = torch.rand(b_size, 1, device=device)

            # Straight displacement path
            x_t = (1.0 - t) * b_x0 + t * b_x1
            target_v = b_x1 - b_x0

            optimizer.zero_grad(set_to_none=True)
            v_pred = model_2rf(x_t, t.squeeze(-1))
            loss = F.mse_loss(v_pred, target_v)

            loss.backward()
            optimizer.step()

Empirical Benchmark Evaluation

Quantitative performance benchmarking comparing traditional diffusion sampling versus Flow Matching and Reflow on ImageNet and :

Generative ModelSampling MethodODE Steps (NFE)ImageNet FID ()Generation Speed (sec / image)Path Curvature ()
ADM (Dhariwal & Nichol)DDIM Solver (High)
LDM / SD 1.5PNDM Solver (Moderate)
EDM (Karras et al.)Heun 2nd-order (Low)
1-Rectified Flow (Base)Euler Integrator (Near-Linear)
1-Rectified Flow (Base)Midpoint / Heun (Near-Linear)
2-Rectified Flow (Reflow)Euler Integrator (Straight)
InstaFlow (Reflow + Distill)Exact Single-Step (Ideal Line)

Troubleshooting Common Flow Matching Faults

1. Velocity Explosion Near Boundary Limits ( or )

  • Symptom: Model predictions output NaN or gradient norms spike past when approaches or .
  • Root Cause: Division by or catastrophic cancellation in numerical standard deviation parameterizations.
  • Remedy: Always clamp timesteps strictly within with , or adopt the constant variance form with .

2. Output Blurring and Semantic Collapse at Small Steps ()

  • Symptom: Sampling with 4 or 8 Euler steps produces low-contrast, averaged images resembling overlapping scenes.
  • Root Cause: High trajectory crossing density in 1-Rectified Flow due to unaligned random couplings .
  • Remedy: Implement the 2-Rectified Flow (Reflow) protocol to straighten trajectories, or incorporate Min-Cost Maximum Matching (Wasserstein OT mini-batch sorting) during 1-RF training.

3. Classifier-Free Guidance (CFG) Over-Saturation

  • Symptom: Generated images exhibit unnatural contrast, edge sharpening halos, or color burning when guidance scale .
  • Root Cause: In velocity space, extrapolating amplifies vector norms beyond the physical velocity domain of the data distribution.
  • Remedy: Apply Velocity Norm Rescaling:

References

  1. Lipman, Y., Chen, R. T. Q., Ben-Hamu, H., Nicklas, M., & Le, M. (2022). Flow Matching for Generative Modeling. International Conference on Learning Representations (ICLR 2023).
  2. Liu, X., Gong, C., & Liu, Q. (2022). Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. International Conference on Learning Representations (ICLR 2023).
  3. Albergo, M. S., & Vanden-Eijnden, E. (2022). Building Normalizing Flows with Stochastic Interpolants. International Conference on Learning Representations (ICLR 2023).
  4. Esser, P., et al. (2024). Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Stable Diffusion 3). arXiv:2403.03206.
  5. Black Forest Labs (2024). FLUX.1 Technical Architecture and Rectified Flow Optimization.
  6. Song, Y., Sohl-Dickstein, J., Kingma, D. P., Kumar, A., Ermon, S., & Poole, B. (2020). Score-Based Generative Modeling through Stochastic Differential Equations. ICLR 2021.


Cite this Explanation

@article{ailinkdeeptech2026flowmatching,
  title={Flow Matching: Continuous Normalizing Flows, Optimal Transport Paths, and Rectified Flow Dynamics},
  author={AILinkDeepTech},
  journal={AILinkDeepTech Algorithm Explanations},
  year={2026},
  url={https://ailinkdeeptech.com/research/flow_matching/}
}

Related Explanations