Module contents
Lesson 19 of 28Advanced 120 min

Continuous-time diffusion: SDEs, the reverse process and the probability flow ODE

Connect DDPM and NCSN to continuous-time stochastic differential equations; derive the probability-flow ODE, study reverse-time sampling and likelihood weighting, and compute flow likelihood with Hutchinson's estimator.

After this lesson you can

  • Write the VP-SDE and VE-SDE and relate them to the continuous limits of DDPM and NCSN noise levels.
  • State the reverse-time SDE and explain why it only needs the score.
  • Derive the probability-flow ODE from the Fokker-Planck equation.
  • Implement reverse Euler-Maruyama, predictor-corrector and an ODE solver and check their marginals.
  • Calculate diffusion flow likelihood using the ODE and Hutchinson's estimator.

Before you start

One problem, different paths

Imagine a data cloud gradually turning into noise. You can follow particles along stochastic trajectories or move them with a deterministic field transporting the same family of densities. Individual curves differ; under suitable assumptions, distributions at each time match. This distinction connects the DDPM chain, NCSN noise levels and continuous flows.

We work in 0≤t≤T0\le t\le T with the diffusion stochastic differential equation

dXt=f(Xt,t) dt+g(t) dWt.dX_t=f(X_t,t)\,dt+g(t)\,dW_t.

WtW_t is Brownian motion and g(t)g(t) is scalar and state-independent. We assume regularity, existence of solutions, and positive differentiable densities wherever we use the score. If the diffusion matrix depends on xx, time reversal and probability flow require additional terms: the simplified formulas below do not carry over unchanged.

In an Itô SDE, a forward Euler-Maruyama step of length h>0h>0 approximates

Xt+h=Xt+f(Xt,t)h+g(t)h Z,Z∼N(0,I).X_{t+h}=X_t+f(X_t,t)h+g(t)\sqrt h\,Z,\qquad Z\sim\Normal(0,I).

Noise scales with h\sqrt h, not hh. Finite discretization introduces error; reducing the step does not replace checking convergence and stability.

VP, VE and sub-VP

Let B(t)=∫0tβ(s) dsB(t)=\int_0^t\beta(s)\,ds with β(t)>0\beta(t)>0. The VP-SDE is

dXt=−12β(t)Xt dt+β(t) dWt,Xt∣X0=x0∼N ⁣(e−B(t)/2x0,[1−e−B(t)]I).dX_t=-\frac12\beta(t)X_t\,dt+\sqrt{\beta(t)}\,dW_t, \quad X_t\mid X_0=x_0\sim \Normal\!\left(e^{-B(t)/2}x_0,\left[1-e^{-B(t)}\right]I\right).

The mean follows from solving the linear part; conditional variance satisfies v′=−βv+βv'=-\beta v+\beta, v(0)=0v(0)=0. It is called VP because identity initial covariance remains identity; this does not mean every initial distribution preserves all moments. For Δt=T/N\Delta t=T/N and βi≈β(ti)Δt\beta_i\approx\beta(t_i)\Delta t, expanding 1−βi=1−β(ti)Δt/2+O(Δt2)\sqrt{1-\beta_i}=1-\beta(t_i)\Delta t/2+O(\Delta t^2) shows the drift and variance of a DDPM increment. Under standard scheme convergence conditions, the chain converges to this VP-SDE as the grid is refined.

The VE-SDE uses dXt=g(t)dWtdX_t=g(t)dW_t with g(t)2=dσ(t)2/dtg(t)^2=d\sigma(t)^2/dt. If it starts exactly at X0=x0X_0=x_0, then

Xt∣x0∼N ⁣(x0, [σ(t)2−σ(0)2]I).X_t\mid x_0\sim\Normal\!\left(x_0,\,[\sigma(t)^2-\sigma(0)^2]I\right).

Under the convention starting from data already perturbed with variance σ(0)2\sigma(0)^2, total variance relative to x0x_0 is σ(t)2\sigma(t)^2. This perturbation family connects to Gaussian levels of NCSN; its generative annealed Langevin procedure is not simply forward Euler-Maruyama on this VE-SDE.

To see the limit, couple noise levels via a forward chain starting from X0=x0+σ(0)Z0X_0=x_0+\sigma(0)Z_0 and adding independent Gaussian increments:

Xt+h=Xt+σ(t+h)2−σ(t)2 Zt.X_{t+h}=X_t+\sqrt{\sigma(t+h)^2-\sigma(t)^2}\,Z_t.

If σ2\sigma^2 is increasing and differentiable, increment variance is g(t)2h+o(h)g(t)^2h+o(h) and its mean is zero. Under the usual scheme conditions, refining the grid gives the VE-SDE above. The conditional distribution relative to x0x_0 has variance σ(t)2\sigma(t)^2 thanks to initial noise. This construction couples NCSN marginals in a particular way; training separately with noisy examples does not by itself determine that coupling across times.

[ ]Derivative of the VE scaleBrowser
import numpy as np

sigma_min, sigma_max, t = 0.01, 50.0, 0.5
sigma_squared = sigma_min**2 * (sigma_max/sigma_min)**(2*t)
g_squared = 2*sigma_squared*np.log(sigma_max/sigma_min)
print(f'σ²(0,5) = {sigma_squared:.6f}; g²(0,5) = {g_squared:.10f}')

The sub-VP of Song and colleagues retains VP drift and uses

g(t)2=β(t)(1−e−2B(t)),Xt∣x0∼N ⁣(e−B(t)/2x0, [1−e−B(t)]2I).g(t)^2=\beta(t)\left(1-e^{-2B(t)}\right),\qquad X_t\mid x_0\sim\Normal\!\left(e^{-B(t)/2}x_0,\,[1-e^{-B(t)}]^2 I\right).

The square is the coordinate-wise variance; standard deviation is 1−e−B(t)1-e^{-B(t)}. For finite times, the chosen terminal prior may only approximate the actual marginal pTp_T: state whether initialization uses the example’s exact marginal or an approximate normal.

InteractiveVP, VE and sub-VP

These curves describe q(xₜ | x₀) conditional on the fixed data point.

VP and sub-VP use β(t) = 0.1 + 4.9t, a(t) = exp[−(0.1t + 2.45t²)/2], and conditional variances 1 − a² and (1 − a²)², respectively. VE keeps a = 1 and uses σ(t) = 0.1·100ᵗ. Starting from clean data adds variance σ(t)² − 0.1². If the starting state already includes N(0, 0.1²) noise, the variance relative to clean data is σ(t)². See Song et al., Appendix B.

The marginal prior also depends on the starting distribution. If the clean data were N(0, 1), the terminal variance for this process would be 1.0000. With arbitrary data, the terminal marginal can be non-Gaussian. It approximates the standard prior under suitable conditions and with enough time.

Process
50
2.0
Conditional mean
1.4361
Conditional variance
0.48444
Terminal mean given x₀
0.5589
Terminal conditional variance
0.9219
Compare conditional mean, spread and terminal distribution under the stated starting convention.

Reverse time without blindly flipping signs

The time-reversal result of Anderson, under its regularity assumptions, expresses reverse drift through the score st(x)=∇xlog⁡pt(x)s_t(x)=\nabla_x\log p_t(x). To avoid ambiguity, define increasing τ=T−t\tau=T-t and Yτ=XT−τY_\tau=X_{T-\tau}. Then

dYτ=[−f(Yτ,T−τ)+g(T−τ)2sT−τ(Yτ)]dτ+g(T−τ) dWˉτ.dY_\tau= \left[-f(Y_\tau,T-\tau)+g(T-\tau)^2s_{T-\tau}(Y_\tau)\right]d\tau +g(T-\tau)\,d\bar W_\tau.

The SDE uses only ff, gg and the marginal score, not normalized density. A local intuition applies Bayes to a short step: the chance of coming from a point depends both on the forward transition and on how much mass lay near that point. Expanding that mass contributes the score term. This guides the sign, but is not a complete proof of the theorem. If written in the original decreasing variable tt, differential dtdt is negative and the usual drift form appears as f−g2stf-g^2s_t.

The exact reverse SDE requires the true score and corresponding prior pTp_T. A network sθs_\theta and terminal normal approximate those objects; errors in rarely visited regions can affect trajectories even when mean training loss is small.

From Fokker-Planck to an ODE

For isotropic diffusion depending only on time, the Fokker-Planck equation is

∂tpt=−∇⋅(fpt)+12g(t)2Δpt.\partial_t p_t=-\nabla\cdot(f p_t)+\frac12 g(t)^2\Delta p_t.

Since ∇pt=pt∇log⁡pt\nabla p_t=p_t\nabla\log p_t, the diffusion term can be incorporated into a divergence:

∂tpt=−∇⋅[pt(f−12g2∇log⁡pt)].\partial_t p_t=-\nabla\cdot \left[p_t\left(f-\frac12g^2\nabla\log p_t\right)\right].

This is the continuity equation of the probability-flow ODE

dXtdt=v(Xt,t)=f(Xt,t)−12g(t)2st(Xt).\frac{dX_t}{dt}=v(X_t,t)=f(X_t,t)-\frac12g(t)^2s_t(X_t).

With the exact score, the same initial distribution and unique solutions to both evolution equations, SDE and ODE share ptp_t. The ODE does not reproduce the same random trajectory or coupling between times. To generate, integrate from TT to a small time; reversing a loop without changing the time increment’s sign is insufficient.

Notes by Holderrieth and Erives develop this connection between transport and diffusion from a unified perspective.

InteractiveDensity under the VP-SDE

The curve shows the analytic marginal. Arrows show the probability-flow ODE field in the selected direction.

t = 0.00
  • Analytic pₜ
  • Flow direction

The x marginal comes from a 2D mixture with weights 0.65 and 0.35, means −2 and 2, and initial standard deviation 0.35. VP uses β(t) = 0.1 + 4.9t and a(t) = exp[−(0.1t + 2.45t²)/2]. Each component has mean a(t)μ and variance a(t)²·0.35² + 1 − a(t)². The arrows use velocity v = −β(t)[x + ∂ₓ log pₜ(x)]/2 with compressed lengths to show direction. Reversing the evolution flips the arrows. The plot draws the field and density directly.

The Fokker–Planck equation can be written as ∂ₜp = −∂ₓ(pv). Under the continuous-process assumptions, the two evolutions give the same marginals even when individual paths differ. See Song et al..

Direction
Time t
0.00
Mean scale a(t)
1.0000
Variance per component
0.1225
Follow the known marginals and the field transporting them; reverse the direction of travel.

For increasing τ\tau, a family interpolating between deterministic flow and reverse SDE can be constructed:

dYτ=[−f+1+η22g2s]dτ+ηg dWτ,η≥0.dY_\tau=\left[-f+\frac{1+\eta^2}{2}g^2s\right]d\tau+\eta g\,dW_\tau, \qquad \eta\ge0.

Functions are evaluated at (Yτ,T−τ)(Y_\tau,T-\tau). At η=0\eta=0 this yields the reverse ODE and at η=1\eta=1 the reverse SDE. With the exact score, correct terminal prior and well-defined solutions, this family’s Fokker-Planck equation gives the same marginals. With discretization, finite samples or an approximate score, empirical curves can differ.

InteractiveDifferent trajectories, same marginals

The three lines track individual particles. Both paths start from the same set of points.

  • ODE
  • Selected process

The exact 2D Gaussian mixture has weights 0.65 and 0.35, means (−2, −1) and (2, 1), and standard deviation 0.35. VP uses β(t) = 0.1 + 4.9t. The 64 starting points come from the exact terminal mixture marginal p₁ with seed 1910. The Gaussian increments share seed 1911 across η values.

Using reverse time s = 1 − t, the update is x′ = x + [βx/2 + (1 + η²)β score/2]Δs + η√(βΔs)ξ. At η = 0 this is Euler for the ODE, and at η = 1 it is Euler–Maruyama for the reverse SDE. With the exact score and correct terminal distribution, the continuous family has the same marginals. With 200 steps and 64 draws, histogram fluctuations and discretization introduce differences. The lines show every 5 steps and the histogram omits points outside the plotted interval.

1.0
Original time t
1.000
Samples with x₁ < 0
34 / 64
Integration step
1 / 200
Compare deterministic and stochastic particles; empirical figures are subject to discretization and sampling.

Learn the score and sample

If forward kernel q0t(xt∣x0)q_{0t}(x_t\mid x_0) is known, a time-conditioned network can be trained with continuous denoising score matching:

Et,x0,xt[λ(t)∥sθ(xt,t)−∇xtlog⁡q0t(xt∣x0)∥2].\mathbb E_{t,x_0,x_t}\left[ \lambda(t)\left\|s_\theta(x_t,t)- \nabla_{x_t}\log q_{0t}(x_t\mid x_0)\right\|^2\right].

The distribution chosen for tt and weight λ(t)\lambda(t) are part of the objective. Likelihood weighting uses λ(t)=g(t)2\lambda(t)=g(t)^2 in the framework analyzed by Song, Durkan, Murray and Ermon, with the constants and conditions of their bound. It does not automatically turn a finite network or Monte Carlo estimate into exact maximum likelihood.

A reverse Euler-Maruyama predictor advances in τ\tau using the SDE increment. A predictor-corrector interleaves correction steps, such as Langevin on the current-level score, to try improving the sample before advancing. Correction adds evaluations and does not guarantee equilibrium in finitely many steps. For the ODE you can use RK45 or another solver with tolerances and record network function evaluations, or NFE: comparing only nominal step counts may hide different amounts of work.

Density through the flow

If field vθ=f−12g2sθv_\theta=f-\frac12g^2s_\theta defines a differentiable invertible flow in [ε,T][\varepsilon,T], the instantaneous change-of-variables formula gives

ddtlog⁡pt(Xt)=−∇⋅vθ(Xt,t),log⁡pε(xε)=log⁡pT(xT)+∫εT∇⋅vθ(Xt,t) dt.\frac{d}{dt}\log p_t(X_t)=-\nabla\cdot v_\theta(X_t,t),\qquad \log p_\varepsilon(x_\varepsilon)= \log p_T(x_T)+\int_\varepsilon^T\nabla\cdot v_\theta(X_t,t)\,dt.

Flow likelihood is exact as an identity for that continuous model if divergence and integration are evaluated exactly. In practice RK45 has tolerances and a Hutchinson estimator uses Z⊤JvZZ^\top J_vZ, with E[ZZ⊤]=I\mathbb E[ZZ^\top]=I, to estimate the trace. Keeping one probe fixed during an integration lets the solver see a reproducible field; repeating probes and tolerances helps measure numerical variation. One probe and finite tolerance do not give an exact figure.

Stopping at ε>0\varepsilon>0 avoids evaluating a potentially singular score on discrete data or data concentrated on a manifold. This computes flow density at that time, not automatically a discrete probability. For quantized images, state dequantization and its scale: for example, converting density on [0,1]D[0,1]^D to a discrete estimate with 256 bins per coordinate yields an 8-bit-per-dimension correction; on [−1,1]D[-1,1]^D each bin has width 2/2562/256 and the correction is 7. One dequantization noise realization does not automatically give the exact discrete likelihood.

Song and colleagues report 2.83 bits/dim on CIFAR-10 for ScoreFlow with likelihood weighting, importance sampling and variational dequantization under their protocol. This figure is not attributed to this lesson’s reduced lab and is not equivalent without adjustments to another checkpoint’s discrete ELBO.

Encode and return

Integrating the ODE forward assigns a code to each input; solving it backward can reconstruct it. For a well-defined field and solution, deterministic encoding is unique, but a numerical solver introduces round-trip error. Uniqueness of the map does not prove a learned score is exact or identify a distribution without further assumptions. Interpolating codes also depends on the prior, interpolation and field; it does not guarantee every intermediate image is plausible.

InteractiveEncode with the ODE

Two real images are encoded and decoded with the exact score of an empirical mixture.

The explicit data prior is an equal-weight mixture of isotropic Gaussians with standard deviation 0.35, centered at the first 32 MNIST training examples normalized to [−1, 1]. The endpoints are examples 1 and 3, with labels 0 and 1. The exact score comes from smoothing that small mixture with the VP SDE.

RK45 encodes the endpoints from t = 0 to 1 using relative tolerance 10⁻⁶ and absolute tolerance 10⁻⁷. The same solver decodes each of the 11 precomputed latent points from 1 to 0. Directions are interpolated on the sphere and radii linearly. The terminal law is the exact transformed mixture. Numerical round-trip errors have measured maxima of 4.68e-7 and 1.74e-7 for the two images. Values are clipped for display. Source script: export_mnist_ode.py.

Order
0.5
Fraction u
0.5
Decoder evaluations
110
Maximum round-trip error at the first endpoint
4.68e-7
Examine codes, interpolations and reconstruction error for the model stated in the figure.

Lab: SDE and ODE with known score

The initial distribution is a 2D Gaussian mixture with weights 0.65 and 0.35, means (−2, −1) and (2, 1), and standard deviation 0.35 per coordinate. Its x marginal supplies the 1D case. The VP-SDE uses β(t) = 0.1 + 4.9t on [0,1]; mixture means, variances, score and Jacobian evolve analytically. We check score and Jacobian with finite differences.

Reverse chains start from the mixture’s exact terminal marginal, not an approximate standard normal. We compare reverse Euler-Maruyama, predictor-corrector and the flow ODE integrated using RK45 at t = 1, 0.5 and 0, measuring coordinate-wise KS and moment errors. The initial distribution is smooth, so t = 0 is regular here; singular data might require different endpoint treatment. Sampling and discretization errors do not prove marginals match exactly.

For likelihood, integrate the ODE forward together with its divergence, add that integral to the exact terminal log density and compare with the known log density at t = 0. The trace is evaluated analytically and with one or 64 Rademacher probes fixed throughout each trajectory integration: redrawing at every evaluation would change the adaptive problem. These differences include probe randomness; in the tolerance limit, the calculation is exact only with exact divergence and this example’s exact score. Cells share variables and run in order.

[ ]Mixture and exact scoreBrowser
"""VP-SDE y mezcla gaussiana con densidad, score y Jacobiano exactos."""
import numpy as np
from scipy.special import logsumexp, ndtr
from scipy.integrate import solve_ivp
from scipy.stats import kstest

WEIGHTS = np.array([.65, .35])
CENTERS = np.array([[-2., -1.], [2., 1.]])
STD0 = .35


def beta(t):
    return .1 + 4.9 * t


def parameters(t, dimension):
    if not 0 <= t <= 1 or dimension not in (1, 2):
        raise ValueError('Tiempo o dimensión inválidos')
    a = np.exp(-.5 * (.1 * t + 2.45 * t * t))
    return a * CENTERS[:, :dimension], a * a * STD0 ** 2 + 1 - a * a


def mix_fields(x, t):
    x = np.asarray(x, dtype=float)
    means, variance = parameters(t, x.shape[1])
    delta = means[None, :, :] - x[:, None, :]
    logits = np.log(WEIGHTS)[None, :] - np.sum(delta ** 2, axis=2) / (2 * variance)
    logp = logsumexp(logits, axis=1) - x.shape[1] * .5 * np.log(2 * np.pi * variance)
    responsibilities = np.exp(logits - logsumexp(logits, axis=1, keepdims=True))
    mean_delta = np.sum(responsibilities[:, :, None] * delta, axis=1)
    score = mean_delta / variance
    centered = delta - mean_delta[:, None, :]
    covariance = np.einsum('nk,nki,nkj->nij', responsibilities, centered, centered)
    jac = -np.eye(x.shape[1])[None, :, :] / variance + covariance / variance ** 2
    return logp, score, jac


def sample_marginal(t, n, dimension, seed):
    rng = np.random.default_rng(seed)
    means, variance = parameters(t, dimension)
    labels = rng.choice(len(WEIGHTS), size=n, p=WEIGHTS)
    return means[labels] + np.sqrt(variance) * rng.normal(size=(n, dimension))


def cdf_coordinate(values, t, coordinate=0):
    means, variance = parameters(t, 2)
    return np.sum(WEIGHTS * ndtr((np.asarray(values)[..., None] - means[:, coordinate]) / np.sqrt(variance)), axis=-1)


probe = np.array([[.3, -.7], [-.8, .2]])
step = 1e-5
_, analytic, jac = mix_fields(probe, .4)
for axis in range(2):
    move = np.zeros_like(probe); move[:, axis] = step
    lp, sp, _ = mix_fields(probe + move, .4)
    lm, sm, _ = mix_fields(probe - move, .4)
    assert np.allclose((lp - lm) / (2 * step), analytic[:, axis], atol=1e-8)
    assert np.allclose((sp - sm) / (2 * step), jac[:, :, axis], atol=1e-8)
print('Score y Jacobiano exactos verificados por diferencias centrales en dos puntos.')
print(f'Mezcla 2D: pesos {WEIGHTS.tolist()}, medias {CENTERS.tolist()}, σ₀={STD0}; β(t)=0.1+4.9t.')
[ ]Three samplers and marginalsBrowser
"""EDE inversa, predictor-corrector y EDO en marginales conocidas."""


def drift(x, t, eta):
    score = mix_fields(x, t)[1]
    return -.5 * beta(t) * (x + (1 + eta ** 2) * score)


def reverse_euler(initial, n_steps, eta, seed, correct=False):
    if n_steps < 2 or n_steps % 2 or not 0 <= eta <= 1:
        raise ValueError('Usa un número par de pasos y 0≤η≤1')
    rng = np.random.default_rng(seed)
    x = initial.copy()
    checkpoints = [x.copy()]
    dt = 1 / n_steps
    for i in range(n_steps):
        time = 1 - i * dt
        x += -dt * drift(x, time, eta) + eta * np.sqrt(beta(time) * dt) * rng.normal(size=x.shape)
        if correct:
            next_time = max(0., time - dt)
            # Un corrector de Langevin con paso fijo, reversible para el score exacto
            # solo en el límite de paso pequeño; la discretización introduce sesgo.
            h = .002
            x += h * mix_fields(x, next_time)[1] + np.sqrt(2 * h) * rng.normal(size=x.shape)
        if i + 1 in (n_steps // 2, n_steps):
            checkpoints.append(x.copy())
    return np.stack(checkpoints)


def probability_flow(initial):
    shape = initial.shape
    def velocity(t, flat):
        return drift(flat.reshape(shape), t, 0).reshape(-1)
    solution = solve_ivp(velocity, (1., 0.), initial.ravel(), t_eval=[1., .5, 0.],
                         rtol=1e-5, atol=1e-6, method='RK45')
    if not solution.success:
        raise RuntimeError(solution.message)
    return solution.y.T.reshape(3, *shape), solution.nfev


def diagnostics(states, dimension):
    values = []
    for time, points in zip((1., .5, 0.), states):
        means, variance = parameters(time, dimension)
        expected_mean = WEIGHTS @ means
        centered = means - expected_mean
        expected_cov = variance * np.eye(dimension) + (centered.T * WEIGHTS) @ centered
        mean_error = np.max(np.abs(points.mean(0) - expected_mean))
        covariance_error = np.max(np.abs(np.cov(points, rowvar=False) - expected_cov))
        ks = max(float(kstest(points[:, j], lambda z: cdf_coordinate(z, time, j)).statistic)
                 for j in range(dimension))
        values.append((float(time), float(ks), float(mean_error), float(covariance_error)))
    return values


observations = {}
for dimension in (1, 2):
    # Se parte de la marginal terminal exacta, no de una normal estándar aproximada.
    start = sample_marginal(1., 512, dimension, 1910 + dimension)
    sde = reverse_euler(start, 300, 1., 1920 + dimension)
    pc = reverse_euler(start, 300, 1., 1930 + dimension, correct=True)
    ode, nfe = probability_flow(start)
    observations[dimension] = {'sde': sde, 'pc': pc, 'ode': ode, 'nfe': nfe}
    for name, states in (('EDE', sde), ('predictor-corrector', pc), ('EDO RK45', ode)):
        checks = diagnostics(states, dimension)
        print(f'{dimension}D {name}: KS máx por coordenada en t=1,.5,0 '
              f'{[round(row[1], 4) for row in checks]}; error máximo de media '
              f'{max(row[2] for row in checks):.4f}; covarianza {max(row[3] for row in checks):.4f}.')
    print(f'{dimension}D RK45 NFE={nfe}; EDE 300 pasos, PC 300 predictores + 300 correctores.')
print('KS es marginal por coordenada; tamaños finitos y discretización no prueban igualdad de distribuciones.')
[ ]Likelihood and HutchinsonBrowser
"""Cambio de variable instantáneo con traza exacta y Hutchinson fijo."""
points = sample_marginal(0., 8, 2, 1940)
rng_trace = np.random.default_rng(1941)
probes = 2 * rng_trace.integers(0, 2, size=(64, len(points), 2)) - 1
n = len(points)


def augmented(t, state):
    x = state[:2*n].reshape(n, 2)
    _, score, jac = mix_fields(x, t)
    vector = -.5 * beta(t) * (x + score)
    trace = np.trace(jac, axis1=1, axis2=2)
    one = np.einsum('ni,nij,nj->n', probes[0], jac, probes[0])
    many = np.einsum('pni,nij,pnj->n', probes, jac, probes) / len(probes)
    # ∫ div f dt se suma a log p_1 para recuperar log p_0.
    return np.concatenate((vector.ravel(), -.5 * beta(t) * (2 + trace),
                           -.5 * beta(t) * (2 + one), -.5 * beta(t) * (2 + many)))


initial_augmented = np.concatenate((points.ravel(), np.zeros(3*n)))
solution = solve_ivp(augmented, (0., 1.), initial_augmented, method='RK45', rtol=1e-7, atol=1e-8)
if not solution.success:
    raise RuntimeError(solution.message)
result = solution.y[:, -1]
terminal = result[:2*n].reshape(n, 2)
terminal_logp = mix_fields(terminal, 1.)[0]
true_logp = mix_fields(points, 0.)[0]
exact_logp = terminal_logp + result[2*n:3*n]
single_logp = terminal_logp + result[3*n:4*n]
multiple_logp = terminal_logp + result[4*n:5*n]
exact_error = np.max(np.abs(exact_logp - true_logp))
single_error = np.mean(np.abs(single_logp - true_logp))
multiple_error = np.mean(np.abs(multiple_logp - true_logp))
assert exact_error < 1e-5
print(f'Log p con divergencia exacta: error absoluto máximo={exact_error:.2e}; RK45 NFE={solution.nfev}.')
print(f'Hutchinson con sondas Rademacher fijas: error absoluto medio 1 sonda={single_error:.6f}, 64 sondas={multiple_error:.6f}.')
print('Los errores de Hutchinson son de esta semilla y estos puntos; más sondas no garantizan mejorar cada realización.')

Exercises

ProofFrom diffusion to transport
Prove: Derive the flow ODE velocity from Fokker-Planck.
0
Assume pₜ is positive and differentiable, g is scalar and independent of x, and regularity and boundary conditions justify the operations.

Step 1 of 3. How is diffusion written as a divergence?

ProofThe limit of a DDPM chain
Prove: Identify the continuous limit of a chain with βᵢ = β(tᵢ)Δt.
0
Assume regular, positive, bounded β, independent Gaussian increments and Δt = T/N.

Step 1 of 3. What is the first-order expansion of √(1−β(t)Δt)?

NumericDiffusion of a VE schedule
For σ(t)=0.01·(50/0.01)^t, what is g(t)² = dσ²/dt at t=0.5? Use the natural logarithm and give three decimal places.
QuizChoose the procedure
You want to integrate a flow density, reconstruct an input using a deterministic map and explore whether correction steps improve quality. What assignment is reasonable?
CodeReverse a VP in two ways
Implement reverse_sde_sample(score, x_terminal, beta, steps, rng) and probability_flow_sample(score, x_terminal, beta). Assume T=1, positive constant β and a vector of 1D samples; score(x,t) returns the marginal score at forward time t. For the SDE integrate increasing τ with Euler-Maruyama in steps equal steps. For the ODE integrate with scipy.integrate.solve_ivp in forward time from 1 to 0, using rtol=1e-6 and atol=1e-7. Do not modify x_terminal. The seed is controlled by rng.
import numpy as np
from scipy.integrate import solve_ivp

def reverse_sde_sample(score, x_terminal, beta, steps, rng):
  pass

def probability_flow_sample(score, x_terminal, beta):
  pass
Shift+Enter to run

Local lab: a VP-SDE on CIFAR-10

Train the previous lesson’s U-Net with continuous time: the full 18,477,315-parameter architecture, AdaGN residual blocks, attention and skip connections. With ORYON_PREVIOUS_CKPT you can initialize from EMA in a diffusion.pt checkpoint produced by that lesson; code respects whether its output is noise or velocity, but does not assume the previous noise schedule matches this one. Without the variable, start from scratch. For a full run install PyTorch with torchvision, NumPy, SciPy and Pillow. First use downloads CIFAR-10 via torchvision to ORYON_DATA_ROOT; ORYON_OUTPUT_DIR chooses where to save weights, images and report. The checkpoint stores weights, EMA, optimizer and AMP state for inspection; this lab does not resume training automatically.

The objective samples tt uniformly in [ε,1][\varepsilon,1] and weights score error by g(t)2=β(t)g(t)^2=\beta(t), with β(t)=0,1+19,9t\beta(t)=0,1+19,9t and ε=0,001\varepsilon=0,001. EMA advances only after an effective AMP step. Defaults propose 50,000 attempts, microbatches of 8 and accumulation of 4; change ORYON_UPDATES to suit your budget. Test is separate from train. Compare predictor-corrector and probability ODE images and field evaluations, but do not mistake this demonstration for a quality benchmark. Both start from a standard normal chosen as terminal prior, which only approximates the forward marginal; saved images are clipped to the display range and the report gives the fraction outside it before clipping.

To estimate density, uniformly dequantize each integer value kk as y=2(k+u)/256−1y=2(k+u)/256-1, u∼U[0,1)u\sim U[0,1), and integrate the state augmented with ODE velocity divergence from ε\varepsilon to 1. One Rademacher probe remains fixed throughout each trajectory and integration is repeated with different probes and tolerances, reporting NFE and standard error across probes. The correction is +7 bits per dimension for this range, since bin width is 2/2562/256; for data scaled to [0,1][0,1] it would be +8. The result is a Monte Carlo estimate of the dequantization bound, also affected by solver and Hutchinson approximation: a single realization does not guarantee a pointwise bound and error across few probes does not measure every error. Probability mass outside the cube is not assigned to the 256 levels.

The code also estimates −ELBO-\mathrm{ELBO} of a DDPM built by discretizing the same VP and using the same EMA weights, integer images and normal prior. It shows one sampled time term multiplied by its number of terms, terminal KL and L0L_0 with Gaussian bin probabilities including edge tails; sampling is repeated and its Monte Carlo standard error reported. The DDPM decoder uses centers 2k/255−12k/255-1 and infinite tail boundaries, whereas the ODE uses uniform dequantization of width 2/2562/256. They are different models and encodings: their numbers are neither an identity nor a controlled flow-versus-DDPM quality comparison. Nor are they directly comparable to a benchmark with a different split or preprocessing.

With ORYON_QUICK=1 use 64 train images, one test image, width 8, two attempts and a milder VP (βmax⁡=2\beta_{\max}=2, ε=0,05\varepsilon=0,05). To use local parquet only for this test, install pyarrow and set ORYON_CIFAR_PARQUET to the directory containing train-00000-of-00001.parquet and test-00000-of-00001.parquet. Without parquet torchvision is used. Selection, seeds, tolerances and results go in report.json; ORYON_EVAL_COUNT sets the test-image count in full mode. In a short run without checkpoint, predictor-corrector used 24 score evaluations and the generation ODE 20; mean estimates from two probes for one image were about 9.1 bpd at both tolerances 0.04 and 0.02. The DDPM −ELBO-\mathrm{ELBO} estimate was 8.36 bpd, with Monte Carlo standard error 0.11. Two steps and one image check the pipeline, not learning or the precision of these figures. Checks include a normal with known log density, stationary score for PC and ODE signs, trace, bin sum and checkpoint reload.

[ ]Continuous score, predictor-corrector and ODE density on CIFAR-10Local GPU
"""VP-SDE continua en CIFAR-10, muestreo y densidad por EDO.

Usa ORYON_QUICK=1 para una verificación corta. ORYON_PREVIOUS_CKPT puede
apuntar al checkpoint linear-epsilon de m19-l18. Se necesita scipy y torch.
"""
import copy
import io
import json
import math
import os
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from scipy.integrate import solve_ivp
from torch import nn
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image
torch.set_num_threads(2)

def groups(channels):
    return math.gcd(32, channels)


class AdaResidual(nn.Module):
    def __init__(self, channels, embedding):
        super().__init__()
        self.norm1 = nn.GroupNorm(groups(channels), channels)
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
        self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
        self.condition = nn.Linear(embedding, 2 * channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)

    def forward(self, x, embedding):
        h = self.conv1(F.silu(self.norm1(x)))
        scale, shift = self.condition(embedding).chunk(2, dim=1)
        h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
        return x + self.conv2(F.silu(h))


class SpatialAttention(nn.Module):
    """Atención de producto escalar solo en mapas de 16×16 y 8×8."""
    def __init__(self, channels, head_dim=32):
        super().__init__()
        self.heads = max(1, channels // min(head_dim, channels))
        if channels % self.heads:
            raise ValueError('Los canales deben dividirse entre las cabezas')
        self.norm = nn.GroupNorm(groups(channels), channels)
        self.qkv = nn.Conv2d(channels, 3 * channels, 1)
        self.output = nn.Conv2d(channels, channels, 1)

    def forward(self, x):
        batch, channels, height, width = x.shape
        q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
        def arrange(z):
            return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
        h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
        h = h.transpose(2, 3).reshape(batch, channels, height, width)
        return x + self.output(h)


class DiffusionUNet(nn.Module):
    """CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
    def __init__(self, width=128):
        super().__init__()
        if width < 8 or width % 8:
            raise ValueError('El ancho debe ser un múltiplo de ocho')
        embedding = 4 * width
        self.width = width
        self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
        self.input = nn.Conv2d(3, width, 3, padding=1)
        self.enc32a = AdaResidual(width, embedding)
        self.enc32b = AdaResidual(width, embedding)
        self.down16 = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
        self.enc16a = AdaResidual(2 * width, embedding)
        self.enc16b = AdaResidual(2 * width, embedding)
        self.attn16_down = SpatialAttention(2 * width)
        self.down8 = nn.Conv2d(2 * width, 3 * width, 3, stride=2, padding=1)
        self.mid8a = AdaResidual(3 * width, embedding)
        self.attn8 = SpatialAttention(3 * width)
        self.mid8b = AdaResidual(3 * width, embedding)
        self.up16 = nn.ConvTranspose2d(3 * width, 2 * width, 4, stride=2, padding=1)
        self.merge16 = nn.Conv2d(4 * width, 2 * width, 1)
        self.dec16a = AdaResidual(2 * width, embedding)
        self.dec16b = AdaResidual(2 * width, embedding)
        self.attn16_up = SpatialAttention(2 * width)
        self.up32 = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
        self.merge32 = nn.Conv2d(2 * width, width, 1)
        self.dec32a = AdaResidual(width, embedding)
        self.dec32b = AdaResidual(width, embedding)
        self.out_norm = nn.GroupNorm(groups(width), width)
        self.output = nn.Conv2d(width, 3, 3, padding=1)

    def forward(self, x, t, T):
        half = self.width // 2
        freq = torch.exp(torch.linspace(0, -math.log(10000), half, device=x.device, dtype=x.dtype))
        phase = (t.to(x.dtype) * (1000. / T))[:, None] * freq[None]
        emb = self.time(torch.cat((phase.sin(), phase.cos()), dim=1))
        h = self.input(x)
        s32 = self.enc32b(self.enc32a(h, emb), emb)
        h = self.down16(s32)
        s16 = self.attn16_down(self.enc16b(self.enc16a(h, emb), emb))
        h = self.mid8a(self.down8(s16), emb)
        h = self.mid8b(self.attn8(h), emb)
        h = self.merge16(torch.cat((self.up16(h), s16), dim=1))
        h = self.attn16_up(self.dec16b(self.dec16a(h, emb), emb))
        h = self.merge32(torch.cat((self.up32(h), s32), dim=1))
        h = self.dec32b(self.dec32a(h, emb), emb)
        return self.output(F.silu(self.out_norm(h)))


def beta_at(t, beta_min, beta_max):
    return beta_min + t * (beta_max - beta_min)


def integrated_beta(t, beta_min, beta_max):
    return beta_min * t + .5 * (beta_max - beta_min) * t * t


def vp_coefficients(t, beta_min, beta_max):
    integral = integrated_beta(t, beta_min, beta_max)
    signal = torch.exp(-.5 * integral)
    noise = torch.sqrt(-torch.expm1(-integral))
    return signal, noise


def noise_prediction(model, xt, t, beta_min, beta_max, parameterization):
    """La red de m19-l18 toma el tiempo normalizado por T y predice ε o v."""
    raw = model(xt, t * 1000, 1000)
    if parameterization == 'epsilon':
        return raw
    if parameterization == 'v':
        signal, std = vp_coefficients(t, beta_min, beta_max)
        return std[:, None, None, None] * xt + signal[:, None, None, None] * raw
    raise ValueError('El checkpoint debe predecir epsilon o v')


def score(model, xt, t, beta_min, beta_max, parameterization):
    _, std = vp_coefficients(t, beta_min, beta_max)
    return -noise_prediction(model, xt, t, beta_min, beta_max, parameterization) / std[:, None, None, None]


def likelihood_loss(model, clean, t, noise, beta_min, beta_max, parameterization):
    signal, std = vp_coefficients(t, beta_min, beta_max)
    xt = signal[:, None, None, None] * clean + std[:, None, None, None] * noise
    prediction = noise_prediction(model, xt, t, beta_min, beta_max, parameterization)
    weight = beta_at(t, beta_min, beta_max) / std.square()
    return (weight[:, None, None, None] * (prediction.float() - noise).square()).mean()


@torch.no_grad()
def update_ema(ema, model, step, max_decay=.9999):
    decay = min(max_decay, (1 + step) / (10 + step))
    for avg, current in zip(ema.parameters(), model.parameters(), strict=True):
        avg.mul_(decay).add_(current, alpha=1-decay)
    for avg, current in zip(ema.buffers(), model.buffers(), strict=True):
        avg.copy_(current)


def optimizer_step(scaler, optimizer, model, ema, completed):
    old_scale = scaler.get_scale()
    scaler.step(optimizer)
    scaler.update()
    if scaler.get_scale() < old_scale:
        return completed, True
    completed += 1
    update_ema(ema, model, completed)
    return completed, False


def dequantize(images, generator, device):
    pixels = (images.to(device).float() * 255).round()
    uniform = torch.rand(pixels.shape, device=device, generator=generator)
    return 2 * ((pixels + uniform) / 256) - 1


class ParquetCifar(Dataset):
    def __init__(self, folder, split, count):
        import pyarrow.parquet as pq
        self.images, self.files_used = [], []
        for path in sorted(Path(folder).glob(f'{split}-*.parquet')):
            self.files_used.append(str(path))
            for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['img']):
                self.images.extend(row['img']['bytes'] for row in batch.to_pylist())
                if len(self.images) >= count:
                    break
            if len(self.images) >= count:
                break
        if len(self.images) < count:
            raise ValueError('Faltan imágenes CIFAR en parquet')
        self.images = self.images[:count]

    def __len__(self):
        return len(self.images)

    def __getitem__(self, i):
        with Image.open(io.BytesIO(self.images[i])) as image:
            return transforms.ToTensor()(image.convert('RGB')), 0


def get_data(root, quick, parquet, n_eval):
    if quick and parquet:
        train, test = ParquetCifar(parquet, 'train', 64), ParquetCifar(parquet, 'test', n_eval)
        return train, test, {'source': 'parquet', 'train': 'primeras 64 filas',
                             'test': f'primeras {n_eval} filas', 'train_files': train.files_used,
                             'test_files': test.files_used, 'selection_seed': None}
    train = datasets.CIFAR10(root, train=True, download=True, transform=transforms.ToTensor())
    test = datasets.CIFAR10(root, train=False, download=True, transform=transforms.ToTensor())
    if quick:
        indices = torch.randperm(len(train), generator=torch.Generator().manual_seed(1910)).tolist()
        train = Subset(train, indices[:64])
    return train, Subset(test, range(n_eval)), {'source': 'torchvision CIFAR10',
            'train': '64 de una permutación' if quick else 'todos los ejemplos',
            'test': f'primeras {n_eval} filas', 'selection_seed': 1910 if quick else None}


def probability_velocity(model, xt, t, beta_min, beta_max, parameterization):
    batch_t = torch.full((len(xt),), t, device=xt.device, dtype=xt.dtype)
    return -.5 * beta_at(t, beta_min, beta_max) * (
        xt + score(model, xt, batch_t, beta_min, beta_max, parameterization))


def pc_sample(model, count, eps, steps, beta_min, beta_max, parameterization, device, seed):
    """Predictor de Euler-Maruyama inverso más corrector Langevin acotado."""
    gen = torch.Generator(device=device).manual_seed(seed)
    x = torch.randn((count, 3, 32, 32), device=device, generator=gen)
    times = np.linspace(1., eps, steps + 1)
    nfe = 0
    with torch.no_grad():
        for i in range(steps):
            current, following = float(times[i]), float(times[i+1])
            dt = current - following
            bt = beta_at(current, beta_min, beta_max)
            t = torch.full((count,), current, device=device)
            s = score(model, x, t, beta_min, beta_max, parameterization)
            nfe += 1
            z = torch.randn(x.shape, device=device, generator=gen)
            x = x + dt * (.5 * bt * x + bt * s) + math.sqrt(bt * dt) * z
            next_t = torch.full((count,), following, device=device)
            s = score(model, x, next_t, beta_min, beta_max, parameterization)
            nfe += 1
            # Paso fijo declarado; no se garantiza mezcla o mejora de calidad.
            h = .0001
            z = torch.randn(x.shape, device=device, generator=gen)
            x = x + h * s + math.sqrt(2 * h) * z
            if not torch.isfinite(x).all():
                raise FloatingPointError('El predictor-corrector dejó de ser finito')
    return x.detach().cpu(), nfe


def ode_sample(model, count, eps, beta_min, beta_max, parameterization, device, seed, rtol, atol):
    gen = torch.Generator(device=device).manual_seed(seed)
    initial = torch.randn((count, 3, 32, 32), device=device, generator=gen)
    shape = tuple(initial.shape)
    def rhs(t, flat):
        with torch.no_grad():
            x = torch.as_tensor(flat, dtype=torch.float32, device=device).reshape(shape)
            velocity = probability_velocity(model, x, t, beta_min, beta_max, parameterization)
            return velocity.detach().cpu().numpy().astype(np.float64).ravel()
    result = solve_ivp(rhs, (1., eps), initial.cpu().numpy().astype(np.float64).ravel(),
                       method='RK45', rtol=rtol, atol=atol)
    if not result.success or not np.isfinite(result.y[:, -1]).all():
        raise RuntimeError(f'Falló la EDO de generación: {result.message}')
    return torch.from_numpy(result.y[:, -1].reshape(shape)).float(), result.nfev


def ode_logdensity(model, initial, probe, eps, beta_min, beta_max, parameterization, device, rtol, atol):
    """Flujo directo de ε a 1; sonda de Hutchinson fija durante toda la trayectoria."""
    shape = tuple(initial.shape)
    if shape[0] != 1 or probe.shape != shape:
        raise ValueError('Se necesita una imagen y una sonda del mismo tamaño')
    direction = probe.to(device=device, dtype=torch.float32)
    def rhs(t, augmented):
        with torch.enable_grad():
            x = torch.as_tensor(augmented[:-1], dtype=torch.float32, device=device).reshape(shape)
            x = x.detach().requires_grad_(True)
            velocity = probability_velocity(model, x, t, beta_min, beta_max, parameterization)
            jtv = torch.autograd.grad((velocity * direction).sum(), x)[0]
            trace = (jtv * direction).sum().item()
            return np.concatenate((velocity.detach().cpu().numpy().astype(np.float64).ravel(), [trace]))
    y0 = np.concatenate((initial.detach().cpu().numpy().astype(np.float64).ravel(), [0.]))
    result = solve_ivp(rhs, (eps, 1.), y0, method='RK45', rtol=rtol, atol=atol)
    if not result.success or not np.isfinite(result.y[:, -1]).all():
        raise RuntimeError(f'Falló la EDO aumentada: {result.message}')
    final, divergence_integral = result.y[:-1, -1], result.y[-1, -1]
    prior_logp = -.5 * (np.square(final).sum() + len(final) * math.log(2 * math.pi))
    # d log p/dt = -div(v): log p_eps = log p_1 + integral div(v) dt.
    return float(prior_logp + divergence_integral), result.nfev


def logdiffexp(larger, smaller):
    return larger + torch.log(-torch.expm1(smaller - larger))


def discrete_decoder_nll(x0, mean, sigma):
    """Masa de 256 bins en [-1,1], con bins extremos semiinfinitos."""
    x, mu, std = x0.double(), mean.double(), sigma.double()
    upper, lower = (x + 1/255 - mu)/std, (x - 1/255 - mu)/std
    left = logdiffexp(torch.special.log_ndtr(upper), torch.special.log_ndtr(lower))
    right = logdiffexp(torch.special.log_ndtr(-lower), torch.special.log_ndtr(-upper))
    logp = torch.where(lower > 0, right, left)
    logp = torch.where(x <= -1 + 1e-7, torch.special.log_ndtr(upper), logp)
    logp = torch.where(x >= 1 - 1e-7, torch.special.log_ndtr(-lower), logp)
    return -logp.flatten(1).sum(1)


def discrete_elbo_bpd(model, pixels, n_steps, beta_min, beta_max, parameterization, device, seed, repeats):
    """ELBO de otra distribución: discretización VP y mismo predictor ε/v."""
    tgrid = torch.arange(n_steps + 1, device=device, dtype=torch.float64) / n_steps
    bar = torch.exp(-integrated_beta(tgrid, beta_min, beta_max))
    beta = torch.cat((torch.zeros_like(bar[:1]), 1 - bar[1:] / bar[:-1]))
    x0 = pixels.to(device).float() * 2 - 1
    gen = torch.Generator(device=device).manual_seed(seed)
    prior = .5 * (bar[-1].item() * x0.double().square() - bar[-1].item() -
                  math.log1p(-bar[-1].item()))
    prior = prior.flatten(1).sum(1)
    samples = []
    with torch.no_grad():
        for _ in range(repeats):
            idx = torch.randint(2, n_steps+1, (len(x0),), device=device, generator=gen)
            noise = torch.randn(x0.shape, device=device, generator=gen)
            b, prev = bar[idx].float(), bar[idx-1].float()
            a = b.sqrt()[:, None, None, None]
            sigma = (1-b).sqrt()[:, None, None, None]
            xt = a*x0 + sigma*noise
            predicted_noise = noise_prediction(model, xt, idx.float()/n_steps, beta_min, beta_max, parameterization)
            predicted_x0 = (xt-sigma*predicted_noise)/a
            bt = beta[idx].float()[:, None, None, None]
            before = prev[:, None, None, None]
            denom = (1-b)[:, None, None, None]
            c0 = bt * before.sqrt() / denom
            ct = (1-bt).sqrt() * (1-before) / denom
            true_mean, model_mean = c0*x0 + ct*xt, c0*predicted_x0 + ct*xt
            qvar = bt*(1-before)/denom
            kl = .5*(torch.log(bt.double()/qvar.double()) +
                     (qvar.double()+(true_mean.double()-model_mean.double()).square())/bt.double()-1)
            kl = kl.flatten(1).sum(1)
            one = torch.full((len(x0),), 1/n_steps, device=device)
            eps1 = torch.randn(x0.shape, device=device, generator=gen)
            a1 = math.sqrt(bar[1].item())
            sigma1 = math.sqrt(1-bar[1].item())
            x1 = a1*x0 + sigma1*eps1
            mean1 = (x1 - sigma1*noise_prediction(model, x1, one, beta_min, beta_max, parameterization))/a1
            decoder = discrete_decoder_nll(x0, mean1, beta[1].sqrt())
            samples.append(((prior + (n_steps-1)*kl + decoder) / (x0[0].numel()*math.log(2))).cpu().numpy())
    return np.stack(samples)


def verify(device):
    """Controles ligeros, también independientes de la red CIFAR."""
    # Normal con varianza y media no estacionarias: log densidad conocida.
    beta = 1.3
    initial_mean = np.array([1., -.5])
    initial_variance = .4
    start = np.array([.2, -.7])
    def rhs(t, state):
        decay = np.exp(-beta*t)
        mean = np.sqrt(decay)*initial_mean
        variance = decay*initial_variance + 1-decay
        s = -(state[:2]-mean)/variance
        velocity = -.5*beta*(state[:2]+s)
        divergence = -beta*(1-1/variance)
        return np.r_[velocity, divergence]
    result = solve_ivp(rhs, (0., 1.), np.r_[start, 0.], rtol=1e-9, atol=1e-9)
    m1 = np.exp(-beta/2)*initial_mean
    v1 = np.exp(-beta)*initial_variance + 1-np.exp(-beta)
    logp1 = -.5*(2*np.log(2*np.pi*v1)+np.square(result.y[:2, -1]-m1).sum()/v1)
    logp0 = -.5*(2*np.log(2*np.pi*initial_variance)+np.square(start-initial_mean).sum()/initial_variance)
    assert result.success and abs(logp1+result.y[2, -1]-logp0) < 1e-7
    # Media de las dos sondas Rademacher distintas produce la traza exacta de una matriz 2D.
    matrix = torch.tensor([[2., 3.], [-1., 4.]], device=device)
    xx = torch.tensor([[.2, -.3]], device=device, requires_grad=True)
    traces = []
    for direction in (torch.tensor([[1., 1.]], device=device), torch.tensor([[1., -1.]], device=device)):
        velocity = xx @ matrix.T
        jtv = torch.autograd.grad((velocity*direction).sum(), xx)[0]
        traces.append((jtv*direction).sum())
    assert torch.allclose(torch.stack(traces).mean(), torch.trace(matrix))
    # Para p_t=N(0,I) el score es −x y la velocidad ODE es exactamente cero.
    class Stationary(nn.Module):
        def forward(self, x, t, T):
            _, std = vp_coefficients(t / 1000, .1, 2.)
            return std[:, None, None, None] * x
    oracle = Stationary().to(device)
    ode, _ = ode_sample(oracle, 2, .05, .1, 2., 'epsilon', device, 1904, 1e-3, 1e-3)
    start_rng = torch.Generator(device=device).manual_seed(1904)
    initial = torch.randn((2, 3, 32, 32), device=device, generator=start_rng).cpu()
    assert torch.allclose(ode, initial, atol=1e-6, rtol=0)
    pc, pc_nfe = pc_sample(oracle, 32, .05, 20, .1, 2., 'epsilon', device, 1905)
    assert pc_nfe == 40
    assert abs(pc.mean().item()) < .03 and abs(pc.var().item()-1) < .08
    # Masa de los 256 bins incluso en colas extremas.
    bins = torch.linspace(-1, 1, 256, device=device, dtype=torch.float64).reshape(256, 1)
    nll = discrete_decoder_nll(bins, torch.full_like(bins, .93), torch.tensor(.2, device=device))
    assert abs(torch.exp(-nll).sum().item()-1) < 1e-12
    assert torch.isfinite(discrete_decoder_nll(bins, torch.full_like(bins, 3.), torch.tensor(.02, device=device))).all()
    with torch.device('meta'):
        full = DiffusionUNet(128)
    assert sum(p.numel() for p in full.parameters()) == 18_477_315
    print(f'Controles: logdensidad normal error {abs(logp1+result.y[2,-1]-logp0):.2g}, '
          'marginal estacionaria PC/ODE, traza, bins y 18.477.315 parámetros.', flush=True)


def main():
    quick = os.environ.get('ORYON_QUICK') == '1'
    root = os.environ.get('ORYON_DATA_ROOT', './data')
    output = Path(os.environ.get('ORYON_OUTPUT_DIR', './score-sde-results'))
    output.mkdir(parents=True, exist_ok=True)
    parquet = os.environ.get('ORYON_CIFAR_PARQUET')
    if parquet and not quick:
        raise ValueError('ORYON_CIFAR_PARQUET solo se utiliza en quick')
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f'dispositivo {device}; quick {quick}', flush=True)
    verify(device)
    n_eval = 1 if quick else int(os.environ.get('ORYON_EVAL_COUNT', '2'))
    if not 1 <= n_eval <= 100:
        raise ValueError('ORYON_EVAL_COUNT debe estar entre 1 y 100')
    train, test, data_meta = get_data(root, quick, parquet, n_eval)
    beta_min, beta_max, eps = (.1, 2., .05) if quick else (.1, 20., .001)
    updates, width, microbatch, accumulation = (2, 8, 4, 1) if quick else (
        int(os.environ.get('ORYON_UPDATES', '50000')), 128, 8, 4)
    if updates < 1:
        raise ValueError('ORYON_UPDATES debe ser positivo')
    previous = os.environ.get('ORYON_PREVIOUS_CKPT')
    parameterization = 'epsilon'
    restored = None
    if previous:
        restored = torch.load(previous, map_location='cpu', weights_only=True)
        if not all(key in restored for key in ('width', 'model', 'ema', 'parameterization')):
            raise ValueError('El checkpoint no corresponde al laboratorio m19-l18')
        width = restored['width']
        parameterization = restored['parameterization']
        if parameterization not in ('epsilon', 'v'):
            raise ValueError('El checkpoint debe predecir epsilon o v')
    torch.manual_seed(1912)
    model = DiffusionUNet(width).to(device)
    if restored is not None:
        model.load_state_dict(restored['ema'])
        print(f'Inicialización desde EMA del checkpoint {previous}, ancho {width}, salida {parameterization}.', flush=True)
        del restored
    ema = copy.deepcopy(model).eval().requires_grad_(False)
    optimizer = torch.optim.AdamW(model.parameters(), lr=.0002)
    scaler = torch.amp.GradScaler('cuda', enabled=device.type == 'cuda')
    loader = DataLoader(train, batch_size=microbatch, shuffle=True, drop_last=True, num_workers=0,
                        generator=torch.Generator().manual_seed(1913))
    batches = iter(loader)
    generator = torch.Generator(device=device).manual_seed(1914)
    completed, skipped, history = 0, 0, []
    for attempt in range(1, updates+1):
        optimizer.zero_grad(set_to_none=True)
        average = 0.
        for _ in range(accumulation):
            try:
                images, _ = next(batches)
            except StopIteration:
                batches = iter(loader)
                images, _ = next(batches)
            clean = dequantize(images, generator, device)
            t = eps + (1-eps)*torch.rand((len(clean),), device=device, generator=generator)
            noise = torch.randn(clean.shape, device=device, generator=generator)
            with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type == 'cuda'):
                loss = likelihood_loss(model, clean, t, noise, beta_min, beta_max, parameterization)
            if not torch.isfinite(loss):
                raise FloatingPointError('La pérdida dejó de ser finita')
            scaler.scale(loss/accumulation).backward()
            average += loss.item()/accumulation
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
        completed, was_skipped = optimizer_step(scaler, optimizer, model, ema, completed)
        skipped += int(was_skipped)
        if attempt == 1 or attempt == updates or attempt % 500 == 0:
            history.append({'attempt': attempt, 'effective_updates': completed, 'loss': average, 'skipped': skipped})
            print(f'VP-SDE intento {attempt}: pérdida {average:.6f}, pasos AMP saltados {skipped}', flush=True)
    checkpoint = {'model': model.state_dict(), 'ema': ema.state_dict(), 'optimizer': optimizer.state_dict(),
                  'scaler': scaler.state_dict(), 'width': width, 'parameterization': parameterization,
                  'beta_min': beta_min, 'beta_max': beta_max, 'eps': eps, 'attempts': updates,
                  'effective_updates': completed, 'skipped_amp': skipped, 'previous': previous}
    torch.save(checkpoint, output / 'score-sde.pt')
    reload = torch.load(output / 'score-sde.pt', map_location=device, weights_only=True)
    assert all(torch.equal(reload['ema'][key], value) for key, value in ema.state_dict().items())
    del model, optimizer, scaler, checkpoint, reload, batches, clean, noise, loss
    ema.eval().requires_grad_(False)
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    n_sample, n_steps = (2, 12) if quick else (16, 500)
    tolerance_pairs = [(0.04, 0.04), (0.02, 0.02)] if quick else [(1e-3, 1e-3), (3e-4, 3e-4)]
    pc, pc_nfe = pc_sample(ema, n_sample, eps, n_steps, beta_min, beta_max, parameterization, device, 1915)
    ode, sample_nfe = ode_sample(ema, n_sample, eps, beta_min, beta_max, parameterization,
                                 device, 1915, *tolerance_pairs[0])
    for name, images in (('pc', pc), ('ode', ode)):
        outside = float(((images < -1) | (images > 1)).float().mean())
        print(f'{name}: {n_sample} muestras, fracción fuera de [−1,1]={outside:.4f}', flush=True)
        save_image(((images+1)/2).clamp(0, 1), output / f'{name}.png', nrow=4)
    print(f'Predictor-corrector: NFE={pc_nfe} ({n_steps} predictores y {n_steps} correctores)', flush=True)
    print(f'ODE de generación: NFE={sample_nfe}, rtol=atol={tolerance_pairs[0][0]}', flush=True)
    pixels = torch.stack([test[i][0] for i in range(n_eval)])
    fixed_gen = torch.Generator(device=device).manual_seed(1916)
    dequantized = dequantize(pixels, fixed_gen, device)
    probes = 2 if quick else 3
    probe_rng = torch.Generator(device=device).manual_seed(1917)
    results = []
    for image_index in range(n_eval):
        initial = dequantized[image_index:image_index+1]
        for probe_index in range(probes):
            direction = (2*torch.randint(0, 2, initial.shape, device=device, generator=probe_rng)-1).float()
            for rtol, atol in tolerance_pairs:
                logp, nfe = ode_logdensity(ema, initial, direction, eps, beta_min, beta_max,
                                           parameterization, device, rtol, atol)
                # Cuantización uniforme de 256 valores en [-1,1]: -log2(width) = +7.
                bpd = -logp / (initial[0].numel()*math.log(2)) + 7
                results.append({'image': image_index, 'probe': probe_index, 'rtol': rtol,
                                'atol': atol, 'nfe': nfe, 'bpd': bpd})
                print(f'ODE imagen {image_index}, sonda {probe_index}, rtol={rtol}: '
                      f'bpd estimado={bpd:.6f}, NFE={nfe}', flush=True)
    summaries = []
    for image_index in range(n_eval):
        for rtol, atol in tolerance_pairs:
            values = np.array([row['bpd'] for row in results if row['image'] == image_index and row['rtol'] == rtol])
            mean = float(values.mean())
            se = float(values.std(ddof=1) / math.sqrt(len(values)))
            summaries.append({'image': image_index, 'rtol': rtol, 'bpd_mean': mean, 'probe_standard_error': se})
            print(f'ODE imagen {image_index}, rtol={rtol}: media={mean:.6f}, '
                  f'EE entre {probes} sondas={se:.6f}', flush=True)
    ddpm = discrete_elbo_bpd(ema, pixels, 20 if quick else 1000, beta_min, beta_max,
                             parameterization, device, 1918, 2 if quick else 8)
    ddpm_means = ddpm.mean(axis=1)
    print(f'DDPM discretizado, misma red, −ELBO estimado={ddpm_means.mean():.6f} bpd; '
          f'EE MC={ddpm_means.std(ddof=1)/math.sqrt(len(ddpm_means)):.6f}', flush=True)
    report = {'quick': quick, 'data_selection': data_meta, 'parameterization': parameterization,
              'source_checkpoint': previous, 'width': width, 'beta_min': beta_min, 'beta_max': beta_max,
              'eps': eps, 'attempts': updates, 'effective_updates': completed, 'skipped_amp': skipped,
              'history': history, 'n_test': n_eval, 'samples_each': n_sample, 'pc_steps': n_steps,
              'pc_corrector_step': .0001, 'pc_nfe': pc_nfe, 'sample_nfe': sample_nfe, 'ode_density_results': results,
              'ode_probe_summaries': summaries,
              'hutchinson_seed': 1917, 'dequantization_seed': 1916, 'ddpm_seed': 1918,
              'ddpm_bpd_mc_means': ddpm_means.tolist(), 'data_scaling': 'uniforme dequantizado en [-1,1], +7 bpd',
              'prior': 'normal estándar elegida; aproximación a la marginal terminal',
              'notice': 'ODE y DDPM son distribuciones diferentes pese a compartir pesos; no comparar con benchmarks sin protocolo.'}
    (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    print('La identidad continua es exacta para el flujo definido; solver, sonda y dequantización son aproximaciones.', flush=True)
    print('ODE en ε y ELBO DDPM usan la misma red, pero definen modelos distintos y no son intercambiables.', flush=True)
    del ema, train, test, loader
    if device.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()


This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
Key idea

With an exact score and suitable conditions, reverse SDE and ODE transport the same marginals along different paths. A learned network, approximate prior and numerical integration turn that ideal equality and flow likelihood into objects that must be checked.