Skip to content

Section C — Comparison table + code playbook

Initial version: 2026-02-05 · First published: 2026-02-24 · Last content update: 2026-10-29

This section is a compact algorithm ↔ code playbook for three related formulations of dynamics-based generation:

  • Score-based diffusion (SDE): learn a time-dependent score \(s_\theta(x,t)\) and sample with a reverse-time SDE (often with a predictor–corrector scheme), or deterministically via the probability-flow ODE.
  • Discrete diffusion (DDPM): learn a denoiser parameterization (commonly \(\varepsilon_\theta\)) and sample a reverse Markov chain.
  • Flow matching (ODE): learn a velocity field \(v_\theta(x,t)\) by regression and sample by ODE integration.

DDPM and score-SDE models are related diffusion formulations, not disjoint families. Flow matching is a training method for a velocity field; ODE sampling is also available for diffusion models. The comparisons below separate training targets from sampling dynamics.

To avoid duplication, we keep derivations elsewhere:

C0. Notation (shared)

We work in \(\mathbb{R}^D\).

  • Data distribution: \(x_\text{data}\sim q(x)\) (we only have sample access).
  • Simple prior: \(x_\text{prior}\sim p(x)\) (often \(p=\mathcal{N}(0,I)\)).
  • Discrete time (DDPM): \(t\in\{1,\dots,T\}\).
  • Continuous time: \(t\in[0,1]\). Diffusion runs data → noise and is sampled backwards; FM runs noise → data and is sampled forwards. Consequently, \(x_0\) means data in diffusion snippets but prior noise in FM snippets.
  • In diffusion, \(p_t\) denotes the noised-data density; it is not the fixed FM prior \(p\). Uppercase \(X_t\) denotes a random state, while lowercase \(x_t\) denotes a realization or code tensor.
  • DDPM schedules: \(\alpha_t=1-\beta_t\), \(\bar\alpha_t=\prod_{j=1}^t\alpha_j\), with \(\bar\alpha_0=1\). The sampler uses \(\sigma_t\) for reverse-transition standard deviation; it is not the forward marginal noise standard deviation \(\sqrt{1-\bar\alpha_t}\).
  • Model outputs:
  • score: \(s_\theta(x,t)\approx \nabla_x\log p_t(x)\),
  • noise: \(\varepsilon_\theta(x_t,t)\approx\mathbb{E}[\varepsilon\mid X_t=x_t]\) for each fixed \(t\), trained against the sampled noise in the forward noising formula,
  • velocity: \(v_\theta(x,t)\approx\mathbb{E}[\dot\gamma_t(X_0,X_1)\mid X_t=x]\), where \(X_t=\gamma_t(X_0,X_1)\). The sampled path derivative supplies the training label; the population-optimal field is its conditional mean.

C1. Comparison table (what is modeled / learned / sampled)

Aspect Score-based diffusion (SDE) Discrete diffusion (DDPM) Flow matching (ODE)
Dynamics type Itô SDE \(dX_t=f(X_t,t)\,dt+g(t)\,dW_t\) (forward), sample via reverse-time SDE (or PF-ODE) Forward Markov chain \(q(x_t\mid x_{t-1})\) with designed \(\beta_t\), sample via reverse chain Deterministic ODE \(\frac{d}{dt}X_t=v_\theta(X_t,t)\)
What is designed SDE coefficients \((f,g)\) / schedule (e.g., VP/VE) discrete schedule \(\beta_t\) (equiv. \(\alpha_t,\bar\alpha_t\)) an endpoint coupling and interpolation \(\gamma_t\); a solver/grid is chosen separately
What is learned \(s_\theta(x,t)\) (score), or equivalent parameterization typically \(\varepsilon_\theta(x_t,t)\) (noise), sometimes data or diffusion \(v\)-prediction (not automatically the FM velocity) \(v_\theta(x,t)\) (velocity)
Training inputs sample \((x_0,t)\), sample noise \(\varepsilon\), construct \(x_t\sim p_t(\cdot\mid x_0)\) in closed form sample \((x_0,t)\), sample noise \(\varepsilon\), construct \(x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\,\varepsilon\) sample endpoints (noise/data) and time \(t\), construct \(x_t=\gamma_t(x_0,x_1)\)
Supervision target closed-form conditional score \(\nabla_{x_t}\log p(x_t\mid x_0)\) (DSM) regression target \(\varepsilon\) in the forward corruption target velocity \(\dot\gamma_t(x_0,x_1)\)
Sampling randomness stochastic (reverse SDE), or deterministic (PF-ODE) stochastic reverse chain (Gaussian transitions) deterministic conditional on the initial sample (subject to solver and field regularity)
Typical solver Euler–Maruyama + Langevin corrector (PC), or ODE solver for PF-ODE ancestral time stepping Euler / Heun / RK methods (see mathematics-foundation.md)

C2. Training pseudocode comparison (side-by-side)

C2.1 Score-based diffusion (denoising score matching)

Assume a forward SDE is chosen so that the conditional \(p(x_t\mid x_0)\) is tractable (often Gaussian). Use times with positive perturbation variance and a positive weight \(\lambda(t)\). Then the DSM objective regresses the model score to the closed-form conditional score:

\[ \mathbb{E}_{t,x_0,x_t}\Big[\lambda(t)\,\big\|s_\theta(x_t,t)-\nabla_{x_t}\log p(x_t\mid x_0)\big\|^2\Big]. \]

Pseudocode:

repeat:
  sample x0 ~ p_data
  sample t  ~ Uniform(0, 1)
  sample ε  ~ N(0, I)
  construct xt ~ p(xt | x0)   # e.g. VE: x0 + σ(t) ε ; VP: √α̅(t) x0 + √(1-α̅(t)) ε
  set target = ∇_{xt} log p(xt | x0)  # conditional label; not the unknown marginal score
  loss = λ(t) · || sθ(xt,t) - target ||^2
  take optimizer step on loss w.r.t. θ

C2.2 DDPM (noise-prediction loss)

DDPM training commonly regresses \(\varepsilon_\theta\) to the injected noise in the forward corruption:

repeat:
  sample x0 ~ p_data
  sample t  ~ Uniform({1, …, T})
  sample ε  ~ N(0, I)
  set xt = √α̅_t · x0 + √(1-α̅_t) · ε
  loss = || ε - εθ(xt, t) ||^2
  take optimizer step on loss w.r.t. θ

C2.3 Flow matching (velocity regression on a designed path)

Choose a bridge \(\gamma_t(x_0,x_1)\) connecting a prior endpoint and a data endpoint, and regress a velocity field to the path derivative \(\dot\gamma_t\):

\[ \mathbb{E}_{t,(x_0,x_1)}\Big[\|v_\theta(\gamma_t(x_0,x_1),t)-\dot\gamma_t(x_0,x_1)\|^2\Big]. \]

For the linear bridge with independently sampled \(x_0\sim p\), \(x_1\sim q\),

\[ \gamma_t(x_0,x_1)=(1-t)x_0+t x_1,\qquad \dot\gamma_t(x_0,x_1)=x_1-x_0. \]

Pseudocode:

repeat:
  sample x1 ~ p_data
  sample x0 ~ N(0, I)
  sample t ~ Uniform(0, 1)
  xt = (1 - t) · x0 + t · x1
  target = x1 - x0
  loss = || vθ(xt, t) - target ||^2
  take optimizer step on loss w.r.t. θ

Single-time training does not specify a sample trajectory. All three training loops can construct an intermediate state directly, without simulating earlier steps. DDPM uses its closed-form multi-step corruption marginal; a score-based diffusion SDE is still Markov even though DSM samples a single time independently. FM uses a chosen endpoint coupling and interpolation. These training constructions do not imply that generated trajectories follow each sampled training path.

C3. Sampling pseudocode comparison (side-by-side)

C3.1 Score-based diffusion: predictor–corrector reverse-SDE sampler

initialize x ~ terminal prior  # VE: approximately N(0, σ_max² I); VP: approximately N(0, I)
choose 1 = t_0 > … > t_N = t_min > 0
for i = 0, …, N-1:
  t = t_i; t_next = t_{i+1}; Δt = t_next - t < 0
  # Predictor: one reverse-SDE step (Euler–Maruyama)
  sample z ~ N(0, I)
  x ← x + [f(x,t) - g(t)^2 sθ(x,t)] Δt + g(t) √(|Δt|) · z

  # Corrector: K steps at the new time t_next (optional)
  repeat K times:
    sample z ~ N(0, I)
    x ← x + η_step · sθ(x,t_next) + √(2 η_step) · z
return x

The corrector is a finite-step approximation, not an exact projection onto the desired marginal. For deterministic probability-flow sampling, remove the random increment and halve the score coefficient:

# Descending diffusion time, Δt < 0; Euler example
x ← x + [f(x,t) - 0.5 · g(t)^2 · sθ(x,t)] Δt

With exact scores, compatible initialization and suitable regularity, this ODE shares the SDE's marginals, not its trajectories. Removing noise from the reverse SDE without changing the drift is a different algorithm. Guided or approximate fields need not preserve the exact correspondence; see the guidance chapter.

The reverse-time formulas and the probability-flow ODE are summarized in diffusion-models-intro.md (Sections 3.2 and 5.2) and in mathematics-foundation.md (Chapter 2).

C3.2 DDPM: ancestral reverse diffusion

initialize x_T ~ N(0, I)
for t = T, …, 1:
  sample z ~ N(0, I) if t > 1 else 0
  mean = 1/√α_t · (x_t - (1-α_t)/√(1-α̅_t) · εθ(x_t, t))
  x_{t-1} = mean + σ_t · z
return x_0

C3.3 Flow matching: ODE sampling by Heun (improved Euler)

set τ_0 = 0 < τ_1 < … < τ_S = 1
initialize x ~ N(0, I) at t = 0
for s = 0, …, S-1:
  t = τ_s,  t_next = τ_{s+1},  h = t_next - t
  k1 = vθ(x, t)
  x_pred = x + h · k1
  k2 = vθ(x_pred, t_next)
  x = x + (h/2) · (k1 + k2)
return x  # learned model sample; target fit and integration accuracy are not guaranteed

Heun evaluates the field at the next grid point, including the endpoint. The snippet assumes these evaluations are finite. If the chosen exact field is singular at an endpoint, use an appropriate cutoff or endpoint treatment rather than evaluating the singular formula there.

C4. Minimal PyTorch code snippets (training + sampling)

These snippets are intentionally small and meant to make the variable ↔ formula correspondence explicit. For generic ODE/SDE solvers, see mathematics-foundation.md.

C4.1 Score-based diffusion (VE/VP schedules, DSM losses and PC sampler)

import torch


def ve_marginal_std(t, *, sigma_min=0.01, sigma_max=50.0):
    """
    VE schedule: choose a marginal std σ(t) (not the diffusion coefficient g(t)).
    t: shape (B,) in [0,1].
    """
    return sigma_min * (sigma_max / sigma_min) ** t


def vp_beta(t, *, beta_min=0.1, beta_max=20.0):
    """VP noise rate β(t), t in [0,1]."""
    return beta_min + t * (beta_max - beta_min)


def vp_alpha_bar(t, *, beta_min=0.1, beta_max=20.0):
    """
    α̅(t) = exp(-∫_0^t β(s) ds) for linear β(s).
    """
    integral = beta_min * t + 0.5 * (beta_max - beta_min) * t * t
    return torch.exp(-integral)


def dsm_loss_ve(score_model, x0, t, *, sigma_min=0.01, sigma_max=50.0, weight=None):
    """
    VE denoising score matching:
      x_t = x0 + σ(t) ε
      ∇_{x_t} log p(x_t|x0) = -(x_t-x0)/σ(t)^2 = -ε/σ(t)
    """
    eps = torch.randn_like(x0)
    sigma = ve_marginal_std(t, sigma_min=sigma_min, sigma_max=sigma_max)
    while sigma.ndim < x0.ndim:
        sigma = sigma[..., None]
    xt = x0 + sigma * eps
    target = -eps / sigma
    pred = score_model(xt, t)
    loss = (pred - target).pow(2)
    if weight is not None:
        w = weight(t)
        while w.ndim < loss.ndim:
            w = w[..., None]
        loss = w * loss
    return loss.mean()


def dsm_loss_vp(score_model, x0, t, *, beta_min=0.1, beta_max=20.0):
    """Variance-weighted VP DSM; use t > 0 to avoid zero variance."""
    if torch.any(t <= 0) or torch.any(t > 1):
        raise ValueError("VP DSM requires t in (0, 1]")
    a_bar = vp_alpha_bar(t, beta_min=beta_min, beta_max=beta_max)
    while a_bar.ndim < x0.ndim:
        a_bar = a_bar[..., None]
    sigma = torch.sqrt(1.0 - a_bar)
    eps = torch.randn_like(x0)
    xt = torch.sqrt(a_bar) * x0 + sigma * eps
    # sigma^2 * ||score - (-eps/sigma)||^2, without dividing the target.
    return (sigma * score_model(xt, t) + eps).pow(2).mean()


@torch.no_grad()
def langevin_corrector(score_model, x, t, *, snr=0.16, n_steps=1):
    """
    K steps of overdamped Langevin dynamics at fixed t.
    Heuristic step size chosen to keep a target SNR.
    """
    for _ in range(n_steps):
        grad = score_model(x, t)
        noise = torch.randn_like(x)

        grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
        noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
        step_size = (snr * noise_norm / (grad_norm + 1e-12)) ** 2 * 2.0

        x = x + step_size * grad + torch.sqrt(2.0 * step_size) * noise
    return x


@torch.no_grad()
def pc_sampler(
    score_model, shape, *, n_steps=1000, sde="ve", device="cpu",
    corrector_steps=1, snr=0.16, sigma_min=0.01, sigma_max=50.0,
    beta_min=0.1, beta_max=20.0,
):
    """
    Predictor–corrector sampling.
    - VE predictor uses the identity g(t)^2 dt = d(σ(t)^2) for the chosen marginal σ(t).
    - VP predictor uses Euler–Maruyama with f(x,t)=-0.5β(t)x, g(t)=sqrt(β(t)).
    """
    if sde not in {"ve", "vp"}:
        raise ValueError("sde must be 've' or 'vp'")
    if n_steps < 2:
        raise ValueError("n_steps must include at least two time-grid points")
    x = torch.randn(shape, device=device)
    if sde == "ve":
        x = sigma_max * x  # terminal VE prior; match the training schedule
    ts = torch.linspace(1.0, 1e-3, n_steps, device=device)  # reverse-time grid

    for i in range(len(ts) - 1):
        t = ts[i].expand(shape[0])
        t_next = ts[i + 1].expand(shape[0])
        dt = t_next - t  # negative

        z = torch.randn_like(x)

        if sde == "ve":
            sigma = ve_marginal_std(t, sigma_min=sigma_min, sigma_max=sigma_max)
            sigma_next = ve_marginal_std(t_next, sigma_min=sigma_min, sigma_max=sigma_max)
            while sigma.ndim < x.ndim:
                sigma = sigma[..., None]
                sigma_next = sigma_next[..., None]
            d_sigma2 = sigma_next**2 - sigma**2  # negative
            x = x - d_sigma2 * score_model(x, t) + torch.sqrt(torch.clamp(-d_sigma2, min=0.0)) * z

        elif sde == "vp":
            beta = vp_beta(t, beta_min=beta_min, beta_max=beta_max)
            while beta.ndim < x.ndim:
                beta = beta[..., None]
            f = -0.5 * beta * x
            g = torch.sqrt(beta)
            dt_b = dt
            while dt_b.ndim < x.ndim:
                dt_b = dt_b[..., None]
            x = x + (f - (g**2) * score_model(x, t)) * dt_b + g * torch.sqrt(-dt_b) * z

        else:
            raise ValueError("sde must be 've' or 'vp'")

        x = langevin_corrector(score_model, x, t_next, snr=snr, n_steps=corrector_steps)

    return x

Schedule and endpoint conventions. For the default VE schedule, \(\sigma(1)=50\), so its approximate terminal prior has covariance \(2500I\), rather than \(I\). The VE branch scales the initial noise and uses the same schedule parameters in its predictor; VP retains standard Gaussian initialization. These terminal priors are approximations to the finite-time noised data laws. With \(\sigma_{\min}>0\) and a positive stopping time, VE returns a slightly smoothed data law rather than an exact noiseless endpoint. Schedule arguments must match training. This agrees with the prior distinction in the official score-SDE implementation.

The VE example defines a positive minimum smoothing scale: at \(t=0\), its marginal is already data convolved with \(\mathcal N(0,\sigma_{\min}^2I)\). The relation \(g(t)^2=d\sigma(t)^2/dt\) therefore describes evolution from that smoothed initial law. If the SDE instead starts from exactly clean data at zero, its added variance is \(\sigma(t)^2-\sigma_{\min}^2\); the DSM perturbation and target must then be changed consistently. Use a positive training-time cutoff (for example, \(t\geq10^{-3}\)) to avoid numerically vanishing VP variances. The VP and VE losses above are separate choices—do not train with the VE corruption and then select the VP sampler.

Call models in evaluation mode for sampling. These snippets assume floating tensors, matching model/device placement, valid schedule parameters, and batch-shaped times; they illustrate the algorithms rather than provide a production sampler.

C4.2 DDPM (noise-prediction training + ancestral sampler)

import torch


def ddpm_forward_sample(x0, t, alpha_bar):
    """
    x_t = sqrt(alpha_bar[t]) x0 + sqrt(1-alpha_bar[t]) eps
    alpha_bar: shape (T+1,) with alpha_bar[0]=1.
    t: int64 tensor of shape (B,) with values in {1,...,T}.
    """
    eps = torch.randn_like(x0)
    a_bar = alpha_bar[t]
    while a_bar.ndim < x0.ndim:
        a_bar = a_bar[..., None]
    xt = torch.sqrt(a_bar) * x0 + torch.sqrt(1.0 - a_bar) * eps
    return xt, eps


def ddpm_loss_eps(eps_model, x0, t, alpha_bar):
    xt, eps = ddpm_forward_sample(x0, t, alpha_bar)
    pred_eps = eps_model(xt, t)
    return (pred_eps - eps).pow(2).mean()


@torch.no_grad()
def ddpm_sample(eps_model, shape, *, alpha, alpha_bar, sigma):
    """
    Ancestral sampling for a fixed-variance DDPM parameterization.
    Arrays alpha/alpha_bar/sigma are shape (T+1,) with index 0 unused for sampling.
    """
    device = alpha.device
    T = alpha.shape[0] - 1
    x = torch.randn(shape, device=device)

    for t in range(T, 0, -1):
        t_vec = torch.full((shape[0],), t, device=device, dtype=torch.long)
        eps = eps_model(x, t_vec)

        mean = (1.0 / torch.sqrt(alpha[t])) * (x - ((1.0 - alpha[t]) / torch.sqrt(1.0 - alpha_bar[t])) * eps)

        if t > 1:
            x = mean + sigma[t] * torch.randn_like(x)
        else:
            x = mean

    return x

For a fixed posterior-variance choice, set

\[ \widetilde\beta_t =\beta_t\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}, \qquad \sigma_t=\sqrt{\widetilde\beta_t}. \]

A common alternative uses \(\sigma_t^2=\beta_t\) for \(t>1\); the final step above remains deterministic. The variance choice must match the intended model parameterization. The Gaussian reverse transitions are learned approximations, not generally the exact reverse conditionals of an arbitrary data distribution. A finite terminal schedule also makes the standard Gaussian initialization approximate.

C4.3 Flow matching (linear bridge + ODE sampling)

import torch


def flow_matching_loss(v_model, x1, t):
    """
    Linear bridge between x0 ~ N(0,I) and x1 ~ data:
      x_t = (1-t) x0 + t x1
      target = d/dt x_t = x1 - x0
    """
    x0 = torch.randn_like(x1)
    t_for_path = t
    while t_for_path.ndim < x1.ndim:
        t_for_path = t_for_path[..., None]
    xt = (1.0 - t_for_path) * x0 + t_for_path * x1
    target = x1 - x0
    pred = v_model(xt, t)  # convention: model expects t with shape (B,)
    return (pred - target).pow(2).mean()


@torch.no_grad()
def flow_sample(v_model, shape, *, n_steps=50, method="heun", device="cpu"):
    """Sample by integrating dx/dt = v_model(x,t) from t=0 to t=1."""
    if n_steps < 1:
        raise ValueError("n_steps must be positive")
    if method not in {"euler", "heun"}:
        raise ValueError("method must be 'euler' or 'heun'")
    x = torch.randn(shape, device=device)
    ts = torch.linspace(0.0, 1.0, n_steps + 1, device=device)

    for i in range(n_steps):
        t = float(ts[i].item())
        t_next = float(ts[i + 1].item())
        h = t_next - t

        t_vec = torch.full((shape[0],), t, device=device)
        if method == "euler":
            x = x + h * v_model(x, t_vec)

        elif method == "heun":
            k1 = v_model(x, t_vec)
            x_pred = x + h * k1
            t_next_vec = torch.full((shape[0],), t_next, device=device)
            k2 = v_model(x_pred, t_next_vec)
            x = x + 0.5 * h * (k1 + k2)

        else:
            raise ValueError("method must be 'euler' or 'heun'")

    return x

C5. How the simplified loss relates to the ELBO

For fixed reverse variance, the interior Gaussian KL terms of the DDPM negative ELBO reduce to weighted noise-prediction errors, with weight

\[ w_t=\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)}, \qquad t\geq2. \]

The usual unweighted noise MSE drops these time-dependent weights; it is a reweighted surrogate motivated by the ELBO derivation, not generally the same objective. The endpoint reconstruction term and terminal-prior term must also be accounted for when evaluating the full bound. For details, see introduction-beta-CFM-and-ELBO.md and diffusion-models-intro.md, Chapter 4.

C6. Conditioning and guidance in code

For ordinary conditioning, pass the paired condition \(y\) to the model in both training and sampling. The training label remains sampled noise or path velocity. For CFG, train with independent condition dropout, then combine two predictions at the same state and time:

def cfg_prediction(model, x, t, condition, null_condition, scale=1.0):
    unconditional = model(x, t, null_condition)
    conditional = model(x, t, condition)
    return unconditional + scale * (conditional - unconditional)

null_condition must use the model's trained null representation. This wrapper applies to noise, score or velocity outputs when both branches use the same parameterization. Insert its result into the corresponding sampler; it is not automatically a drift. With this convention, scale=1 is ordinary conditional generation, while scale>1 extrapolates. A fixed condition embedding does not imply a fixed effect across time. The full derivation and distributional limitations are in Guidance and classifier-free guidance.

C7. Reading the code as a complete sampler

The training construction supplies labels; the network approximates their conditional expectation; a specified solver turns the learned field or reverse transition into samples. Quality depends on all three choices, including endpoint conventions, initialization and numerical error. Neither conservation of probability nor a small regression loss alone guarantees exact target-distribution matching.

References

  1. Song et al. Score-Based Generative Modeling through Stochastic Differential Equations. ICLR 2021. Reverse SDEs, predictor–corrector sampling and probability-flow ODEs; official SDE definitions.
  2. Ho, Jain and Abbeel. Denoising Diffusion Probabilistic Models. NeurIPS 2020. Noise prediction, reverse transitions and the simplified objective.
  3. Lipman et al. Flow Matching for Generative Modeling. ICLR 2023. Conditional velocity supervision for marginal probability transport.
  4. Ho and Salimans. Classifier-Free Diffusion Guidance. 2022 arXiv version. Conditional/unconditional prediction combination.