Module contents
Lesson 17 of 28Core 120 min

Denoising diffusion probabilistic models: a complete derivation of the objective

Derive a diffusion model as a hierarchical VAE with a fixed noisy encoder: its forward marginal and posterior, diffusion ELBO, parameterizations, simplified noise loss and connection to denoising score matching. Implement a DDPM from scratch.

After this lesson you can

  • Prove the closed Gaussian forward marginal by induction.
  • Derive the mean and variance of q(x_{t-1} | x_t, x_0) by completing squares.
  • Derive the diffusion ELBO into terminal, intermediate Gaussian KL and reconstruction terms.
  • Derive noise-prediction squared error and its relationship to the score.
  • Implement a DDPM from scratch in NumPy (2D) and PyTorch (MNIST), including ancestral sampling.

Before you start

From an image to noise and back

A DDPM converts an example into increasingly noisy variables and learns a reverse chain that builds samples from noise. It is a many-level hierarchical VAE: the key difference is that the forward encoder is fixed in advance while reverse transitions are learned. Repeated denoising is a useful intuition, but every step has a variance and distribution that must be specified.

Use t=1,…,Tt=1,\ldots,T, with x0x_0 as data, βt∈(0,1)\beta_t\in(0,1), αt=1−βt\alpha_t=1-\beta_t and αˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^t\alpha_s, plus αˉ0=1\bar\alpha_0=1. Distinguish αt\alpha_t from its cumulative product: an index difference changes every sampler step.

Variance βt\beta_t belongs to one step; it is not the total variance of xtx_t conditioned on x0x_0. The accumulated variance has a closed form:

q(xt∣x0)=N ⁣(αˉt x0,(1−αˉt)I),xt=αˉt x0+1−αˉt ϵ,ϵ∼N(0,I).q(x_t\mid x_0)=\Normal\!\left(\sqrt{\bar\alpha_t}\,x_0,(1-\bar\alpha_t)I\right), \qquad x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon, \quad \epsilon\sim\Normal(0,I).

For induction, the claim is immediate at t=1t=1. If it holds at t−1t-1, substitute the expression for xt−1x_{t-1} into xt=αtxt−1+βtztx_t=\sqrt{\alpha_t}x_{t-1}+\sqrt{\beta_t}z_t with fresh independent noise. Mean becomes αtαˉt−1x0\sqrt{\alpha_t\bar\alpha_{t-1}}x_0 and variance αt(1−αˉt−1)+βt=1−αˉt\alpha_t(1-\bar\alpha_{t-1})+\beta_t=1-\bar\alpha_t. This permits choosing a time and sampling its marginal directly without simulating every step.

InteractiveScrubbing diffusion time

The same closed-form marginal applies to a CIFAR-10 cat image and the held-out points from the lab’s 2D spiral.

  • Spiral points

At each t the widget computes xₜ = √ᾱₜ x₀ + √(1 − ᾱₜ)ε with the same ε per element. Sharing noise couples the marginals for ease of comparison. A forward Markov trajectory would draw noise at each step. The 32 × 32 image is the first CIFAR-10 test example, a cat, normalized to [−1, 1]. The image and spiral noise use seeds 1710 and 1711. The spiral uses 256 held-out lab points. The widget runs no training.

Image values are clipped for display. The histogram and statistics use all 3,072 unclipped channel values. The histogram shows [−4, 4] and overlays the standard normal as a reference. The linear schedule increases β from 0.0001 to 0.02. The cosine schedule uses s = 0.008, clips β to 0.999, and recomputes ᾱ from those β values. T = 1,000.

Schedule
0
√ᾱₜ
1.00000
√(1 − ᾱₜ)
0.00000
Unclipped channel mean
−0.1499
Unclipped channel standard deviation
0.3658
Compare coefficients, image and cloud. The figure explains the origin of data and noise.

Images are usually scaled to [−1,1][-1,1]. The linear schedule of Ho, Jain and Abbeel uses T=1000T=1000 and βt\beta_t between 10−410^{-4} and 0,020,02; a cosine schedule was proposed later by Nichol and Dhariwal. For the linear schedule, αˉT≈0,006352818\sqrt{\bar\alpha_T}\approx0,006352818: conditional signal is small, although the terminal marginal is not thereby exactly standard normal for every data distribution.

[ ]Cumulative signal of the linear scheduleBrowser
import numpy as np

beta_ho = np.linspace(1e-4, 0.02, 1000, dtype=np.float64)
abar_ho = np.cumprod(1 - beta_ho)
print(f'ᾱ_T = {abar_ho[-1]:.12g}; √ᾱ_T = {np.sqrt(abar_ho[-1]):.11f}')

The posterior when the original datum is known

The forward posterior q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) is accessible during training because x0x_0 is known. For t≥2t\ge2, Bayes gives

q(xt−1∣xt,x0)∝q(xt∣xt−1)q(xt−1∣x0).q(x_{t-1}\mid x_t,x_0)\propto q(x_t\mid x_{t-1})q(x_{t-1}\mid x_0).

Complete the square in u=xt−1u=x_{t-1}. Scalar precision and linear term are

At=αtβt+11−αˉt−1,bt=αtβtxt+αˉt−11−αˉt−1x0.A_t=\frac{\alpha_t}{\beta_t}+\frac{1}{1-\bar\alpha_{t-1}}, \qquad b_t=\frac{\sqrt{\alpha_t}}{\beta_t}x_t+ \frac{\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_{t-1}}x_0.

Thus q=N(At−1bt,At−1I)q=\Normal(A_t^{-1}b_t,A_t^{-1}I). Simplifying:

β~t=1−αˉt−11−αˉtβt,μ~t=αˉt−1βt1−αˉtx0+αt(1−αˉt−1)1−αˉtxt.\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\beta_t,\qquad \tilde\mu_t= \frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}x_0+ \frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}x_t.

Coefficients are positive but need not sum to one. At t=1t=1, xt−1=x0x_{t-1}=x_0 is fixed: the posterior is a point mass and β~1=0\tilde\beta_1=0. The precision expressions above use 1−αˉt−11-\bar\alpha_{t-1} in the denominator and apply to t≥2t\ge2; do not treat the point mass as a nondegenerate Gaussian.

InteractiveGeometry of the forward posterior

The arrows add the contributions c₀x₀ and cₜxₜ. The lower plot zooms in on the uncertainty around the mean.

  • x₀ and its contribution
  • xₜ and its contribution
  • Mean and radii 1σ and 2σ

Given q(xₜ | xₜ₋₁) = N(√αₜ xₜ₋₁, βₜI), the posterior is N(c₀x₀ + cₜxₜ, β̃ₜI), with c₀ = √ᾱₜ₋₁ βₜ/(1 − ᾱₜ), cₜ = √αₜ(1 − ᾱₜ₋₁)/(1 − ᾱₜ) and β̃ₜ = βₜ(1 − ᾱₜ₋₁)/(1 − ᾱₜ). At t = 1 the covariance vanishes. The circles have radii of one and two standard deviations per coordinate. Their enclosed probabilities in 2D differ from the 68% and 95% intervals of a 1D Gaussian. T = 1,000. The cosine schedule uses s = 0.008 and clips β to 0.999 before computing ᾱ.

Schedule
400
Coefficient of x₀
0.00444
Coefficient of xₜ
0.99401
Variance β̃ₜ per coordinate
0.0080322
Conditional mean
(1.186, 1.395)
Move both states and observe the conditioned posterior mean and dispersion.

ELBO of a latent chain

The generator starts from p(xT)=N(0,I)p(x_T)=\Normal(0,I) and uses pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t) for t≥2t\ge2, plus decoder pθ(x0∣x1)p_\theta(x_0\mid x_1). Jensen gives the usual variational bound:

log⁡pθ(x0)≥Eq(x1:T∣x0)[log⁡p(xT)+∑t=1Tlog⁡pθ(xt−1∣xt)−∑t=1Tlog⁡q(xt∣xt−1)].\log p_\theta(x_0)\ge \mathbb E_{q(x_{1:T}\mid x_0)} \left[\log p(x_T)+\sum_{t=1}^T\log p_\theta(x_{t-1}\mid x_t) -\sum_{t=1}^T\log q(x_t\mid x_{t-1})\right].

To regroup it, use Bayes’ identity for t≥2t\ge2

q(xt∣xt−1)=q(xt−1∣xt,x0) q(xt∣x0)q(xt−1∣x0).q(x_t\mid x_{t-1})= \frac{q(x_{t-1}\mid x_t,x_0)\,q(x_t\mid x_0)} {q(x_{t-1}\mid x_0)}.

Marginal ratios cancel telescopically. The negative bound, averaged over the forward chain, is

LVLB=LT+∑t=2TLt−1+L0,L_{\mathrm{VLB}}=L_T+\sum_{t=2}^{T}L_{t-1}+L_0, LT=DKL ⁣(q(xT∣x0) ∥ p(xT)),Lt−1=Eq(xt∣x0)DKL ⁣(q(xt−1∣xt,x0) ∥ pθ(xt−1∣xt)),L_T=D_{\mathrm{KL}}\!\left(q(x_T\mid x_0)\,\|\,p(x_T)\right),\qquad L_{t-1}=\mathbb E_{q(x_t\mid x_0)} D_{\mathrm{KL}}\!\left(q(x_{t-1}\mid x_t,x_0)\,\|\,p_\theta(x_{t-1}\mid x_t)\right), L0=Eq(x1∣x0)[−log⁡pθ(x0∣x1)].L_0=\mathbb E_{q(x_1\mid x_0)}[-\log p_\theta(x_0\mid x_1)].

The diffusion ELBO is −LVLB-L_{\mathrm{VLB}} for this x0x_0. LTL_T is KL between Gaussians and does not depend on θ\theta when the forward chain is fixed. Each intermediate term is Gaussian KL if the reverse model is Gaussian too. L0L_0 is reconstruction and needs different treatment: for discrete data it is log mass, not continuous density evaluated at a pixel center.

From reverse mean to noise prediction

Suppose, for t≥2t\ge2, pθ(xt−1∣xt)=N(μθ(xt,t),σt2I)p_\theta(x_{t-1}\mid x_t)=\Normal(\mu_\theta(x_t,t),\sigma_t^2I) with fixed σt2>0\sigma_t^2>0. Gaussian KL gives

Lt−1=Eq[∥μ~t−μθ∥22σt2+D2(β~tσt2−1+log⁡σt2β~t)].L_{t-1}= \mathbb E_q\left[ \frac{\|\tilde\mu_t-\mu_\theta\|^2}{2\sigma_t^2} +\frac D2\left(\frac{\tilde\beta_t}{\sigma_t^2}-1+ \log\frac{\sigma_t^2}{\tilde\beta_t}\right)\right].

The second summand is independent of the learned mean, although not necessarily zero. One can parameterize μθ\mu_\theta directly or predict x^0,θ\hat x_{0,\theta} and substitute into μ~t\tilde\mu_t. With αˉt>0\bar\alpha_t>0, a third option predicts noise:

x^0,θ=xt−1−αˉt ϵθ(xt,t)αˉt,μθ=1αt(xt−βt1−αˉtϵθ(xt,t)).\hat x_{0,\theta}= \frac{x_t-\sqrt{1-\bar\alpha_t}\,\epsilon_\theta(x_t,t)} {\sqrt{\bar\alpha_t}}, \qquad \mu_\theta= \frac{1}{\sqrt{\alpha_t}} \left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\epsilon_\theta(x_t,t)\right).

These are algebraic conversions between outputs for fixed xtx_t and tt, not a claim that all losses or architectures train identically. Substituting xt=αˉtx0+1−αˉtϵx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\epsilon turns the θ\theta-dependent term into

Ex0,ϵ[βt22σt2αt(1−αˉt)∥ϵ−ϵθ(xt,t)∥2].\mathbb E_{x_0,\epsilon} \left[ \frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)} \|\epsilon-\epsilon_\theta(x_t,t)\|^2 \right].

Noise parameterization does not make exact ELBO weights uniform. The simplified loss of Ho and colleagues deliberately chooses an error without that weight:

Lsimple=Et∼Unif{1,…,T}, x0,ϵ[∥ϵ−ϵθ(xt,t)∥2].L_{\mathrm{simple}}= \mathbb E_{t\sim\mathrm{Unif}\{1,\ldots,T\},\,x_0,\epsilon} \left[\|\epsilon-\epsilon_\theta(x_t,t)\|^2\right].

Term t=1t=1 enters this training loss but is not an intermediate KL with β~1=0\tilde\beta_1=0. Changing the distribution of tt without compensation changes loss weighting. Averaging coordinates instead of summing also introduces factor DD: keep it consistent when comparing bits per dimension.

InteractiveHow much each ELBO step weighs

Each pair shows the step’s share of the respective total from t = 2 to t = 100. The vertical scale is in percent.

58.4 %
2255075100
paso t
  • λₜ × error, normalized
  • Uniformly weighted error, normalized

Noise prediction squared error is summed across both coordinates and averaged over 2,048 independent test examples at each step (noise seed 1724). The lab’s MLP was trained on the spiral for 1,800 updates. These values are measured prediction errors. Each distribution is normalized separately, so the bar heights compare shares within each sum.

For ε parameterization and fixed scalar variance, λₜ = βₜ² / [2σₜ²αₜ(1 − ᾱₜ)]. The plot shows the network-dependent terms of the intermediate KL divergences. It excludes constants, L₀ and Lₜₑᵣₘᵢₙₐₗ. At step 1, β̃₁ = 0 and reconstruction accounts for that term. The schedule and measurements come from the 100-step experiment.

Reverse variance σ²ₜ
20
Total 2D test MSE
1.55619
Weight λₜ
0.05975
Weighted share
0.55 %
Uniform share
1.96 %
Compare per-level weights and errors in the stated experiment; simplified loss is not exact ELBO.

Score and Tweedie inside the network

At each tt, the distribution of xtx_t is scaled data plus Gaussian noise with standard deviation 1−αˉt\sqrt{1-\bar\alpha_t}. Its score conditioned on x0x_0 is −ϵ/1−αˉt-\epsilon/\sqrt{1-\bar\alpha_t}. By denoising score matching, the optimal squared-error predictor satisfies

E[ϵ∣xt]=−1−αˉt ∇xtlog⁡qt(xt).\mathbb E[\epsilon\mid x_t] =-\sqrt{1-\bar\alpha_t}\,\nabla_{x_t}\log q_t(x_t).

Thus defining sθ=−ϵθ/1−αˉts_\theta=-\epsilon_\theta/\sqrt{1-\bar\alpha_t} turns noise prediction into a score field; equality with marginal score requires an optimal predictor and usual assumptions. Applying Tweedie to Y=xtY=x_t and X=αˉtx0X=\sqrt{\bar\alpha_t}x_0 recovers the preceding formula for x^0\hat x_0. An approximate prediction need not be a posterior sample.

From noise to a sample

The DDPM ancestral sampler starts with xT∼N(0,I)x_T\sim\Normal(0,I) and for t=T,…,1t=T,\ldots,1 evaluates μθ(xt,t)\mu_\theta(x_t,t). At t>1t>1 add σtz\sigma_tz with independent z∼N(0,I)z\sim\Normal(0,I); at the final step add no Gaussian noise. For discrete images the probabilistic model of L0L_0 assigns mass to quantization intervals; returning the mean at t=1t=1 is a generation rule not necessarily equivalent to sampling that discrete decoder.

Choices σt2=βt\sigma_t^2=\beta_t and σt2=β~t\sigma_t^2=\tilde\beta_t yield different chains. β~t\tilde\beta_t belongs to the posterior conditioned on x0x_0, whereas the reverse model observes only xtx_t: choosing it as generator variance is a parameterization decision, not an identity for the marginal posterior. Clipping x^0\hat x_0 to [−1,1][-1,1] changes the mean if reconstructed from it; use it consistently and declare the choice. Calculate αˉt\bar\alpha_t at least in single precision, preferably double when constructing the schedule, not as a float16 cumulative product.

InteractiveThe reverse process step by step

Blue points are chain states. Orange points are the network’s predictions of x₀ at that step. Arrows pair eight states and predictions.

t = 100
  • States xₜ
  • Estimate x̂₀
  • Held-out spiral

The widget replays 64 stored trajectories from the lab’s MLP, trained for 1,800 updates on 4,096 points. The gray reference plots 256 independent test points. Both options share the initial cloud (seed 1730) and per-step noise (1731). At t = 1 both take a deterministic last step. At t = 0 there is no further estimate. Predictions use their original coordinates, and the axes hide points outside [−4, 4]².

The network estimates ε. The reverse mean uses x̂₀ = (xₜ − √(1 − ᾱₜ) ε̂)/√ᾱₜ. The short run illustrates the procedure. Sample appearance alone cannot establish how well it learned the spiral.

Reverse variance
State t
100 / 100
ᾱₜ
0.01630
Variance used in the next step
0.079885
Follow the chain of a trained 2D model and its estimate of x₀; compare the two variances.

Algorithms 1 and 2 of Ho and colleagues follow directly. Training: choose x0x_0, uniform tt and noise, form xtx_t using the closed marginal and optimize MSE of ϵ\epsilon. Sampling: initialize xTx_T, traverse decreasing times, calculate mean with ϵθ\epsilon_\theta and add noise only if t>1t>1. Their CIFAR-10 figures for LsimpleL_{\mathrm{simple}} include FID 3.17 against training data and a test NLL bound of 3.75 bits per dimension; these are published protocol results, not measurements of the next lab. Against test they report FID 5.24.

Lab: two-dimensional DDPM from scratch

Generate a noisy two-dimensional spiral with independent training and test samples. The forward chain has T = 100 steps and linear β from 0.0001 to 0.08 in double precision. Mathematical time runs from 1 to T; index 0 reserves ᾱ₀ = 1. Monte Carlo checks the marginal and exact-posterior residual for a fixed initial observation.

The MLP receives xₜ, sin(πt/T) and cos(πt/T), and predicts noise. Training selects t uniformly from 1 to T and minimizes half total squared error per example. Its backward pass is checked by central differences for every parameter of a small network; prediction error is measured on separate test data with new noise. Sampling starts from standard normal and applies the posterior parameterized by predicted noise. Compare βₜ and β̃ₜ variances; the final step adds no noise and predicted x₀ is not clipped. This short run does not guarantee quality or convergence. Cells share variables and run in order.

[ ]Diffusion marginal and posteriorBrowser
"""Difusión directa y posterior gaussiana, con tiempo matemático 1,...,T."""
import numpy as np

T = 100
beta = np.concatenate(([0.], np.linspace(0.0001, 0.08, T)))
alpha = 1 - beta
abar = np.cumprod(alpha)


def spiral(seed, n):
    rng = np.random.default_rng(seed)
    angle = rng.uniform(1.5 * np.pi, 4.5 * np.pi, n)
    xy = np.column_stack((angle * np.cos(angle), angle * np.sin(angle))) / 7
    return xy + 0.04 * rng.normal(size=xy.shape)


def q_sample(x0, t, noise):
    a = abar[np.asarray(t)]
    return np.sqrt(a)[..., None] * x0 + np.sqrt(1 - a)[..., None] * noise


def posterior(x0, xt, t):
    if not 1 <= t <= T:
        raise ValueError('t debe estar entre 1 y T')
    denominator = 1 - abar[t]
    c0 = np.sqrt(abar[t - 1]) * beta[t] / denominator
    ct = np.sqrt(alpha[t]) * (1 - abar[t - 1]) / denominator
    variance = beta[t] * (1 - abar[t - 1]) / denominator
    return c0 * x0 + ct * xt, variance


# Se generan pares mediante la cadena y se examina el residuo condicional.
rng_check = np.random.default_rng(1701)
test_t = 67
x0_check = np.array([0.7, -0.9])
n_check = 40000
previous = q_sample(np.broadcast_to(x0_check, (n_check, 2)), test_t - 1,
                    rng_check.normal(size=(n_check, 2)))
current = np.sqrt(alpha[test_t]) * previous + np.sqrt(beta[test_t]) * rng_check.normal(size=previous.shape)
post_mean, post_variance = posterior(x0_check, current, test_t)
residual = previous - post_mean
expected_mean = np.sqrt(abar[test_t]) * x0_check
expected_var = 1 - abar[test_t]
mean_error = np.max(np.abs(current.mean(axis=0) - expected_mean))
var_error = np.max(np.abs(current.var(axis=0) - expected_var))
residual_mean = np.max(np.abs(residual.mean(axis=0)))
residual_var_error = np.max(np.abs(residual.var(axis=0) - post_variance))
covariance = np.max(np.abs(np.mean((current - current.mean(axis=0)) * residual, axis=0)))
assert mean_error < .03 and var_error < .03
assert residual_mean < .004 and residual_var_error < .002 and covariance < .004
assert posterior(x0_check, current[0], 1)[1] == 0
print(f'MC n={n_check}, t={test_t}: error media marginal={mean_error:.5f}, varianza={var_error:.5f}.')
print(f'Residuo posterior: media máxima={residual_mean:.5f}, error varianza={residual_var_error:.5f}, covarianza con x_t={covariance:.5f}.')
print(f'β̃₁={posterior(x0_check, current[0], 1)[1]:.1f}; ᾱ_T={abar[-1]:.6f}.')
[ ]MLP and gradientsBrowser
"""MLP de ruido y backward manual para L_simple."""


def initialize(seed, width=32):
    rng = np.random.default_rng(seed)
    return [rng.normal(size=(4, width)) / np.sqrt(4), np.zeros(width),
            rng.normal(size=(width, width)) / np.sqrt(width), np.zeros(width),
            rng.normal(size=(width, 2)) / np.sqrt(width), np.zeros(2)]


def predict(params, x, t):
    t = np.broadcast_to(np.asarray(t), (len(x),))
    phase = np.pi * t / T
    inp = np.column_stack((x, np.sin(phase), np.cos(phase)))
    h1 = np.tanh(inp @ params[0] + params[1])
    h2 = np.tanh(h1 @ params[2] + params[3])
    return h2 @ params[4] + params[5], inp, h1, h2


def loss_grad(params, x0, t, noise):
    xt = q_sample(x0, t, noise)
    pred, inp, h1, h2 = predict(params, xt, t)
    residual = pred - noise
    loss = 0.5 * np.mean(np.sum(residual ** 2, axis=1))
    d2 = residual / len(x0)
    d1 = (d2 @ params[4].T) * (1 - h2 ** 2)
    d0 = (d1 @ params[2].T) * (1 - h1 ** 2)
    grads = [inp.T @ d0, d0.sum(axis=0), h1.T @ d1, d1.sum(axis=0),
             h2.T @ d2, d2.sum(axis=0)]
    return loss, grads


# Gradientes de todos los parámetros en una red pequeña, ruido fijo.
grad_rng = np.random.default_rng(1710)
probe_params = initialize(1711, width=5)
probe_data = spiral(1712, 8)
probe_t = grad_rng.integers(1, T + 1, len(probe_data))
probe_noise = grad_rng.normal(size=probe_data.shape)
_, analytic = loss_grad(probe_params, probe_data, probe_t, probe_noise)
grad_error = 0.
for param, gradient in zip(probe_params, analytic):
    for index in np.ndindex(param.shape):
        old = param[index]
        param[index] = old + 1e-5
        plus = loss_grad(probe_params, probe_data, probe_t, probe_noise)[0]
        param[index] = old - 1e-5
        minus = loss_grad(probe_params, probe_data, probe_t, probe_noise)[0]
        param[index] = old
        grad_error = max(grad_error, abs((plus - minus) / 2e-5 - gradient[index]))
assert grad_error < 1e-8
assert np.max(np.abs(predict(probe_params, probe_data, 10)[0] -
                     predict(probe_params, probe_data, 90)[0])) > 1e-6
print(f'Máximo error del backward por diferencias finitas: {grad_error:.2e}.')
[ ]Training and testBrowser
"""Ajuste de ε mediante Adam y evaluación reservada por tiempo."""
train = spiral(1720, 4096)
test = spiral(1721, 2048)
params = initialize(1722)
train_rng = np.random.default_rng(1723)
adam_m = [np.zeros_like(p) for p in params]
adam_v = [np.zeros_like(p) for p in params]
curve = []
N_UPDATES = 1800
BATCH = 128
for step in range(1, N_UPDATES + 1):
    x0 = train[train_rng.integers(len(train), size=BATCH)]
    t = train_rng.integers(1, T + 1, size=BATCH)
    noise = train_rng.normal(size=x0.shape)
    loss, gradients = loss_grad(params, x0, t, noise)
    for j in range(len(params)):
        adam_m[j] = 0.9 * adam_m[j] + 0.1 * gradients[j]
        adam_v[j] = 0.999 * adam_v[j] + 0.001 * gradients[j] ** 2
        first = adam_m[j] / (1 - 0.9 ** step)
        second = adam_v[j] / (1 - 0.999 ** step)
        params[j] -= 0.002 * first / (np.sqrt(second) + 1e-8)
    if step % 100 == 0:
        curve.append([step, float(loss)])
eval_rng = np.random.default_rng(1724)
eval_noise = eval_rng.normal(size=(T, len(test), 2))
error_by_t = []
for t in range(1, T + 1):
    noise = eval_noise[t - 1]
    xt = q_sample(test, t, noise)
    error_by_t.append(float(np.mean(np.sum((predict(params, xt, t)[0] - noise) ** 2, axis=1))))
print(f'Train={len(train)}, test={len(test)}, pasos={N_UPDATES}, lote={BATCH}.')
print(f'Pérdida primer/último lote guardado: {curve[0][1]:.5f}/{curve[-1][1]:.5f}.')
print(f'Error total ε test t=1,50,100: {error_by_t[0]:.5f}, {error_by_t[49]:.5f}, {error_by_t[99]:.5f}.')
[ ]Ancestral samplingBrowser
"""Sampler ancestral, con dos varianzas y estados conservados."""


def generate(params, variance_kind, initial, seed):
    if variance_kind not in ('beta', 'posterior'):
        raise ValueError('Varianza no reconocida')
    rng = np.random.default_rng(seed)
    x = initial.copy()
    states = [x.copy()]
    estimates = []
    for t in range(T, 0, -1):
        predicted_noise = predict(params, x, t)[0]
        x0_pred = (x - np.sqrt(1 - abar[t]) * predicted_noise) / np.sqrt(abar[t])
        mean, post_var = posterior(x0_pred, x, t)
        estimates.append(x0_pred.copy())
        variance = beta[t] if variance_kind == 'beta' else post_var
        if t > 1:
            x = mean + np.sqrt(variance) * rng.normal(size=x.shape)
        else:
            x = mean
        states.append(x.copy())
    return x, np.stack(states), np.stack(estimates)


initial = np.random.default_rng(1730).normal(size=(64, 2))
sample_beta, trajectory_beta, estimate_beta = generate(params, 'beta', initial, 1731)
sample_post, trajectory_post, estimate_post = generate(params, 'posterior', initial, 1731)
assert np.allclose(trajectory_beta[0], initial) and np.allclose(trajectory_post[0], initial)
assert np.isfinite(trajectory_beta).all() and np.isfinite(trajectory_post).all()


def nearest_distance(points, reference):
    delta = points[:, None, :] - reference[None, :, :]
    return float(np.sqrt(np.sum(delta ** 2, axis=2)).min(axis=1).mean())


print(f'Sampler: {T} evaluaciones por partícula; 64 muestras por variante, sin recorte de x₀.')
print(f'Distancia media al vecino de test: β={nearest_distance(sample_beta, test):.5f}; '
      f'β̃={nearest_distance(sample_post, test):.5f}.')
print('La proximidad al vecino no mide diversidad ni garantiza calidad generativa.')

Exercises

ProofComposing Gaussian steps
Prove: Prove the distribution of x_t conditioned on x₀ by induction.
0
Assume independent standard-normal noise z_t and ᾱ₀ = 1.

Step 1 of 3. If the mean at t−1 is √ᾱₜ₋₁ x₀, what is it at t?

ProofCompleting squares
Prove: Derive the mean and variance of q(xₜ₋₁ | xₜ, x₀) for t ≥ 2.
0
Multiply q(xₜ | xₜ₋₁) by q(xₜ₋₁ | x₀) and write u = xₜ₋₁.

Step 1 of 3. What is the scalar precision in u?

ProofSeparating ELBO terms
Prove: Obtain L_T + Σₜ₌₂ᵀ Lₜ₋₁ + L₀ from the chain variational bound.
0
For steps t ≥ 2 replace the forward transition using Bayes’ rule conditioned on x₀.

Step 1 of 3. Which identity introduces posterior q(xₜ₋₁ | xₜ,x₀)?

NumericResidual signal of the linear schedule
For T = 1000 with β linear from 0.0001 to 0.02, calculate √ᾱT. Give at least six decimal places.
QuizNoise prediction and weighting
Why does DDPM L_simple training weight times uniformly when t is chosen uniformly?
CodeThree DDPM operations
Implement q_sample(x0,t,noise,abar), simple_loss(model,x0,t,noise,abar) and p_sample(model,xt,t,noise,beta,abar,variance). Tensors x0, xt and noise have shape [B,D]; t is a mathematical integer in 1..T. beta and abar include index 0, with beta[0]=0 and abar[0]=1. q_sample uses the exact marginal; simple_loss averages squared error between noise and model(xt,t) across batch and coordinates; p_sample uses the noise-parameterized mean without clipping and variance equal to 'beta' or 'posterior'. At t=1 return the mean without noise. Do not modify inputs.
import torch

def q_sample(x0, t, noise, abar):
  pass

def simple_loss(model, x0, t, noise, abar):
  pass

def p_sample(model, xt, t, noise, beta, abar, variance):
  pass
Shift+Enter to run

Local lab: DDPM and variational bound for images

Train DDPM on 28×28 MNIST and Fashion-MNIST. U-Net predicts ϵ\epsilon from noisy image and sinusoidal time representation. For each image choose tt uniformly between 1 and TT, generate xtx_t from the closed marginal and minimize per-component mean ∥ϵ−ϵθ(xt,t)∥2\|\epsilon-\epsilon_\theta(x_t,t)\|^2. The forward chain uses Ho and colleagues’ linear schedule; αˉt\bar\alpha_t products are calculated in float64 even though the network uses float32. Images are scaled to [−1,1][-1,1] and test data do not participate in training.

To evaluate the variational bound, use analytical LTL_T, one intermediate term with uniform tt from 2 to TT multiplied by T−1T-1, and L0L_0 as discrete Gaussian probability over 256 bins per pixel. Extreme bins extend to infinity. Log-CDF differences use the more stable tail and float64. Fixed reverse variance is σt2=βt\sigma_t^2=\beta_t, including positive variance for the L0L_0 decoder; do not divide by β~1=0\tilde\beta_1=0. Output is bits per dimension, dividing by pixel count and log⁡2\log 2.

Every repetition uses new noise and intermediate times on the same test data. Standard error across repetition means measures Monte Carlo noise for those images, not population uncertainty or model quality. The expectation of negative ELBO upper-bounds negative surprise; one Monte Carlo estimate can fall below it. This is not exact log-likelihood.

Generation uses the ancestral algorithm from standard normal, with σt2=βt\sigma_t^2=\beta_t and no noise at t=1t=1, clipping only for display or evaluation. This visual output is the final-transition mean, as in Ho’s algorithm; it is not an exact sample from the probabilistic discrete decoder used to calculate L0L_0. Report the fraction outside [−1,1][-1,1] before clipping. Standard normal approximation to the terminal marginal depends on TT and schedule, and is especially poor in the T=20T=20 short test.

The harness uses lesson 11’s 64-feature architecture adapted to 28×28 and trained from scratch on the relevant dataset: Fashion-MNIST for Fashion and MNIST for digits. Real and generated images use the same format; the classifier is evaluated on separate test data. Calculate Fréchet distance, unbiased polynomial MMD² with cubic kernel k(u,v)=(u⊤v/d+1)3k(u,v)=(u^\top v/d+1)^3, precision and coverage with k=3k=3 neighbors. An unbiased MMD² estimate can be negative. All use custom features, not Inception: they are not standard FID or KID and are not directly comparable to the 64×64 Fashion harness or other extractors. Low accuracy indicates little classifier evidence; high accuracy does not guarantee a good perceptual metric.

The harness reports 95% percentile bootstrap intervals: 12 replicates in the short test and 100 in full mode, with a fixed seed. They quantify only resampling of evaluated sets with fixed generator and extractor. Duplicates can change neighbor radii and tails; they neither eliminate Fréchet bias nor describe training variability. With 16 samples and only 12 replicates, intervals are very unstable diagnostics, not publishable estimates.

Install torch, torchvision, numpy, scipy and pillow. ORYON_DATASET accepts mnist, fashion or both; ORYON_DATA_ROOT selects data location and ORYON_OUTPUT_DIR results. Full mode uses T=1000T=1000, all training images, 20 epochs, batch 128 and 1024 test images; it also trains the classifier for five epochs. Bound evaluation uses 10 repetitions, and ancestral sampling requires 1000 network evaluations per batch: the full workflow may be costly. A checkpoint stores network, optimizer and schedule, but automatic resumption is not implemented.

For a functional check set ORYON_QUICK=1: use 128 training images, 16 test images, one epoch, T=20T=20, a small network and three Monte Carlo repetitions. In one short run estimated negative ELBO was 7.89 with Monte Carlo standard error 1.15 bits/dim on MNIST and 8.10 with error 1.14 on Fashion. Classifier accuracy was 0% and 25% respectively, and about 40% of generated components fell outside [−1,1][-1,1]. This verifies code, not generation quality, classifier accuracy or a benchmark-comparable result.

Before training, simulate the Gaussian posterior with joint chains, check absence of noise at t=1t=1 and marginal endpoints, verify the decoder’s 256 masses sum to one and remain finite in extreme tails. Also compare sampled-time ELBO with an independent implementation, Fréchet by two formulas and MMD² with an explicit sum. Weights, features, seeds, evaluation and parameters are saved in the output folder.

[ ]Image DDPM and discrete variational boundLocal GPU
"""DDPM en MNIST y Fashion-MNIST, arnés en características y ELBO discreto.

ORYON_DATASET=mnist|fashion|both, ORYON_DATA_ROOT y ORYON_OUTPUT_DIR.
ORYON_QUICK=1 reduce datos, modelo, pasos y evaluación para verificar el código.
Requiere scipy para distancias entre vecinos del arnés de evaluación.
"""
import copy
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 scipy.spatial.distance import cdist
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.utils import save_image

torch.set_num_threads(2)


def schedule(steps, device):
    if steps < 2:
        raise ValueError('Se necesitan al menos dos pasos')
    # Índice cero reservado para x0: se calcula en float64 incluso con redes float32.
    beta = torch.cat((torch.zeros(1, device=device, dtype=torch.float64),
                      torch.linspace(1e-4, .02, steps, device=device, dtype=torch.float64)))
    alpha = 1 - beta
    bar = torch.cumprod(alpha, dim=0)
    previous = torch.cat((torch.ones(1, device=device, dtype=torch.float64), bar[:-1]))
    posterior_variance = torch.zeros_like(beta)
    posterior_variance[1:] = beta[1:] * (1 - previous[1:]) / (1 - bar[1:])
    return {'beta': beta, 'alpha': alpha, 'bar': bar, 'previous': previous,
            'posterior_variance': posterior_variance}


def extract(values, t, x):
    return values[t].to(dtype=x.dtype).reshape(-1, *([1] * (x.ndim - 1)))


def q_sample(x0, t, noise, diffusion):
    if noise.shape != x0.shape or t.shape != (len(x0),):
        raise ValueError('Formas incompatibles en q_sample')
    ab = extract(diffusion['bar'], t, x0)
    return ab.sqrt() * x0 + (1 - ab).sqrt() * noise


def posterior(x0, xt, t, diffusion):
    beta = extract(diffusion['beta'], t, xt)
    alpha = extract(diffusion['alpha'], t, xt)
    ab = extract(diffusion['bar'], t, xt)
    prev = extract(diffusion['previous'], t, xt)
    mean = beta * prev.sqrt() / (1 - ab) * x0 + alpha.sqrt() * (1 - prev) / (1 - ab) * xt
    variance = extract(diffusion['posterior_variance'], t, xt)
    return mean, variance


class Residual(nn.Module):
    def __init__(self, channels, embedding):
        super().__init__()
        self.norm1, self.norm2 = nn.GroupNorm(4, channels), nn.GroupNorm(4, channels)
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
        self.condition = nn.Linear(embedding, channels)

    def forward(self, x, embedding):
        h = self.conv1(F.silu(self.norm1(x))) + self.condition(embedding)[:, :, None, None]
        return x + self.conv2(F.silu(self.norm2(h)))


class TimeUNet(nn.Module):
    def __init__(self, width=32):
        super().__init__()
        if width % 4:
            raise ValueError('El ancho debe ser múltiplo de cuatro')
        emb = 4 * width
        self.embedding = nn.Sequential(nn.Linear(16, emb), nn.SiLU(), nn.Linear(emb, emb))
        self.input = nn.Conv2d(1, width, 3, padding=1)
        self.encoder = Residual(width, emb)
        self.down = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
        self.middle = Residual(2 * width, emb)
        self.up = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
        self.merge = nn.Conv2d(2 * width, width, 3, padding=1)
        self.decoder = Residual(width, emb)
        self.output = nn.Conv2d(width, 1, 3, padding=1)

    def forward(self, x, t):
        frequencies = torch.exp(torch.linspace(0, -math.log(10000), 8, device=x.device, dtype=x.dtype))
        phase = t.to(x.dtype)[:, None] * frequencies[None]
        embedding = self.embedding(torch.cat((phase.sin(), phase.cos()), dim=1))
        skip = self.encoder(self.input(x), embedding)
        h = self.middle(self.down(skip), embedding)
        h = self.merge(torch.cat((self.up(h), skip), dim=1))
        return self.output(self.decoder(h, embedding))


def simple_loss(model, x0, t, noise, diffusion):
    return (model(q_sample(x0, t, noise, diffusion), t) - noise).square().mean()


def reverse_mean(model, xt, t, diffusion):
    beta = extract(diffusion['beta'], t, xt)
    alpha = extract(diffusion['alpha'], t, xt)
    abar = extract(diffusion['bar'], t, xt)
    return (xt - beta / (1 - abar).sqrt() * model(xt, t)) / alpha.sqrt()


def p_sample(model, xt, t, noise, diffusion):
    """σt²=βt; el último paso devuelve la media sin añadir ruido."""
    mean = reverse_mean(model, xt, t, diffusion)
    variance = extract(diffusion['beta'], t, xt)
    mask = (t > 1).to(xt.dtype).reshape(-1, *([1] * (xt.ndim - 1)))
    return mean + mask * variance.sqrt() * noise


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


def discrete_decoder_nll(x0, mean, sigma):
    """Negativo del log de masa gaussiana sobre 256 bins, en float64.

    Centros en [-1,1]; el primer y último bin se extienden hasta ±infinito.
    Se calcula en la cola más estable para no restar CDF próximas a uno.
    """
    x, mu, std = x0.double(), mean.double(), sigma.double()
    upper = (x + 1 / 255 - mu) / std
    lower = (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))
    middle = torch.where(lower > 0, right, left)
    logprob = torch.where(x <= -1 + 1e-7, torch.special.log_ndtr(upper), middle)
    logprob = torch.where(x >= 1 - 1e-7, torch.special.log_ndtr(-lower), logprob)
    return -logprob.flatten(1).sum(1)


def estimate_bpd(model, batch, diffusion, repeats, generator):
    """Media MC de L_T + L_0 + (T−1)L_{t−1} por imagen; tiempo uniforme."""
    T = len(diffusion['beta']) - 1
    x0 = batch
    ab_T = diffusion['bar'][T].item()
    prior = .5 * (ab_T * x0.double().square() + (1 - ab_T) - 1 - math.log1p(-ab_T))
    prior = prior.flatten(1).sum(1)
    estimates = []
    with torch.no_grad():
        for _ in range(repeats):
            t = torch.randint(2, T + 1, (len(x0),), device=x0.device, generator=generator)
            noise = torch.randn(x0.shape, device=x0.device, dtype=x0.dtype, generator=generator)
            xt = q_sample(x0, t, noise, diffusion)
            true_mean, true_var = posterior(x0, xt, t, diffusion)
            model_mean = reverse_mean(model, xt, t, diffusion)
            model_var = extract(diffusion['beta'], t, xt)
            kl = .5 * (torch.log(model_var.double() / true_var.double()) +
                       (true_var.double() + (true_mean.double() - model_mean.double()).square()) /
                       model_var.double() - 1)
            kl = kl.flatten(1).sum(1)
            t1 = torch.ones(len(x0), device=x0.device, dtype=torch.long)
            eps1 = torch.randn(x0.shape, device=x0.device, dtype=x0.dtype, generator=generator)
            x1 = q_sample(x0, t1, eps1, diffusion)
            mu1 = reverse_mean(model, x1, t1, diffusion)
            decoder = discrete_decoder_nll(x0, mu1, diffusion['beta'][1].sqrt())
            estimates.append(((prior + (T - 1) * kl + decoder) / (x0[0].numel() * math.log(2))).cpu().numpy())
    return np.stack(estimates)


def feature_array(x):
    x = np.asarray(x, dtype=np.float64)
    if x.ndim != 2 or len(x) < 2 or x.shape[1] == 0 or not np.isfinite(x).all():
        raise ValueError('Se necesitan al menos dos vectores finitos por conjunto')
    return x


def frechet_features(real, generated):
    """Fréchet de m19-l11 en características propias: no es FID Inception."""
    real, generated = feature_array(real), feature_array(generated)
    if real.shape[1] != generated.shape[1]:
        raise ValueError('Las características deben tener la misma dimensión')
    a = np.atleast_2d(np.cov(real, rowvar=False))
    b = np.atleast_2d(np.cov(generated, rowvar=False))
    values, vectors = np.linalg.eigh((a + a.T) / 2)
    values_b = np.linalg.eigvalsh((b + b.T) / 2)
    if values.min() < -1e-9 * max(1., np.abs(values).max()) or values_b.min() < -1e-9 * max(1., np.abs(values_b).max()):
        raise ValueError('La covarianza no es semidefinida positiva')
    root = (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T
    middle = root @ b @ root
    eigenvalues = np.linalg.eigvalsh((middle + middle.T) / 2)
    if eigenvalues.min() < -1e-9 * max(1., np.abs(eigenvalues).max()):
        raise ValueError('El producto de covarianzas no es semidefinido positivo')
    mean_distance = np.square(real.mean(0) - generated.mean(0)).sum()
    result = float(mean_distance + np.trace(a) + np.trace(b) - 2 * np.sqrt(np.maximum(eigenvalues, 0)).sum())
    scale = max(1., mean_distance + abs(np.trace(a)) + abs(np.trace(b)))
    if result < -1e-8 * scale:
        raise ValueError('La distancia es negativa más allá de la tolerancia')
    return max(0., result)


def polynomial_mmd2(real, generated):
    """Estimador insesgado de MMD² polinómica, con el núcleo de KID."""
    real, generated = feature_array(real), feature_array(generated)
    if real.shape[1] != generated.shape[1]:
        raise ValueError('Las características deben tener la misma dimensión')
    dim = real.shape[1]
    a = (real @ real.T / dim + 1) ** 3
    b = (generated @ generated.T / dim + 1) ** 3
    cross = (real @ generated.T / dim + 1) ** 3
    m, n = len(real), len(generated)
    return float((a.sum() - np.trace(a)) / (m * (m - 1)) +
                 (b.sum() - np.trace(b)) / (n * (n - 1)) - 2 * cross.mean())


def precision_recall(real, generated, k=3):
    real, generated = feature_array(real), feature_array(generated)
    if real.shape[1] != generated.shape[1] or k < 1 or k >= min(len(real), len(generated)):
        raise ValueError('Dimensiones o número de vecinos incompatibles')
    def radii(x):
        distance = cdist(x, x, metric='sqeuclidean')
        np.fill_diagonal(distance, np.inf)
        return np.partition(distance, k - 1, axis=1)[:, k - 1]
    r_real, r_generated = radii(real), radii(generated)
    distances = cdist(real, generated, metric='sqeuclidean')
    return (float(np.any(distances <= r_real[:, None], axis=0).mean()),
            float(np.any(distances <= r_generated[None, :], axis=1).mean()))


def evaluate(real, generated, k=3, repeats=100, seed=13):
    real, generated = feature_array(real), feature_array(generated)
    if repeats < 1:
        raise ValueError('repeats debe ser positivo')
    def metrics(x, y):
        precision, recall = precision_recall(x, y, k)
        return np.array([frechet_features(x, y), polynomial_mmd2(x, y), precision, recall])
    observed = metrics(real, generated)
    rng = np.random.default_rng(seed)
    bootstrap = np.stack([metrics(real[rng.integers(len(real), size=len(real))],
                                  generated[rng.integers(len(generated), size=len(generated))])
                          for _ in range(repeats)])
    lower, upper = np.percentile(bootstrap, [2.5, 97.5], axis=0)
    return {name: {'value': float(value), 'bootstrap_95': [float(low), float(high)]}
            for name, value, low, high in zip(('frechet', 'mmd2_poly', 'precision', 'recall'),
                                               observed, lower, upper)}


class FashionFeatures(nn.Module):
    """Arquitectura del arnés Fashion de m19-l11, aplicada aquí a 28×28."""
    def __init__(self):
        super().__init__()
        self.conv = nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                                  nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                                  nn.AdaptiveAvgPool2d((4, 4)), nn.Flatten())
        self.embedding = nn.Sequential(nn.Linear(32 * 4 * 4, 64), nn.ReLU())
        self.classifier = nn.Linear(64, 10)

    def features(self, image):
        return self.embedding(self.conv(image))

    def forward(self, image):
        return self.classifier(self.features(image))


def checks(device):
    d = schedule(20, device)
    assert d['bar'][0].item() == 1 and d['posterior_variance'][1].item() == 0
    assert torch.all(d['beta'][1:] > 0) and torch.all(d['beta'][1:] < 1)
    assert torch.all(d['bar'][1:] < d['bar'][:-1])
    gen = torch.Generator(device=device).manual_seed(1701)
    x0 = torch.tensor([[.7]], device=device).expand(20000, 1)
    t = torch.full((len(x0),), 10, dtype=torch.long, device=device)
    z1 = torch.randn(x0.shape, device=device, generator=gen)
    z2 = torch.randn(x0.shape, device=device, generator=gen)
    xp = q_sample(x0, t - 1, z1, d)
    xt = extract(d['alpha'], t, xp).sqrt() * xp + extract(d['beta'], t, xp).sqrt() * z2
    mu, var = posterior(x0, xt, t, d)
    residual = ((xp - mu) / var.sqrt()).flatten()
    correlation = torch.mean((residual - residual.mean()) * (xt.flatten() - xt.mean())) / xt.std()
    assert abs(residual.mean().item()) < .04 and abs(residual.var(unbiased=True).item() - 1) < .05
    assert abs(correlation.item()) < .04
    one = torch.ones(2, dtype=torch.long, device=device)
    zero = torch.zeros((2, 1, 4, 4), device=device)
    class Zero(nn.Module):
        def forward(self, x, t):
            return torch.zeros_like(x)
    mu = reverse_mean(Zero(), zero, one, d)
    assert torch.equal(p_sample(Zero(), zero, one, torch.ones_like(zero), d), mu)
    assert torch.equal(p_sample(Zero(), zero, one, -torch.ones_like(zero), d), mu)
    # Las 256 masas de un decodificador gaussiano suman 1, incluso en los bordes.
    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()
    # Contraste independiente de L_T + (T−1) KL + L_0, usando el mismo azar.
    small = schedule(5, device)
    x_test = torch.zeros((3, 1, 1, 1), device=device, dtype=torch.float64)
    first = torch.Generator(device=device).manual_seed(1703)
    second = torch.Generator(device=device).manual_seed(1703)
    actual_bpd = estimate_bpd(Zero(), x_test, small, 1, first)[0]
    tt = torch.randint(2, 6, (3,), device=device, generator=second)
    e = torch.randn(x_test.shape, device=device, dtype=x_test.dtype, generator=second)
    bar = extract(small['bar'], tt, x_test)
    prev = extract(small['previous'], tt, x_test)
    beta = extract(small['beta'], tt, x_test)
    alpha = 1 - beta
    xtest = bar.sqrt() * x_test + (1 - bar).sqrt() * e
    qmean = beta * prev.sqrt() / (1 - bar) * x_test + alpha.sqrt() * (1 - prev) / (1 - bar) * xtest
    qvar = beta * (1 - prev) / (1 - bar)
    pmean = xtest / alpha.sqrt()
    kl = .5 * (torch.log(beta / qvar) + (qvar + (qmean - pmean).square()) / beta - 1)
    noise1 = torch.randn(x_test.shape, device=device, dtype=x_test.dtype, generator=second)
    x1 = math.sqrt(1e-4) * noise1
    mean1 = x1 / math.sqrt(1 - 1e-4)
    normal = torch.distributions.Normal(torch.tensor(0., device=device, dtype=torch.float64),
                                        torch.tensor(1., device=device, dtype=torch.float64))
    lower = (-1 / 255 - mean1.double()) / .01
    upper = (1 / 255 - mean1.double()) / .01
    decoder = -(normal.cdf(upper) - normal.cdf(lower)).log().flatten()
    last = small['bar'][-1].item()
    prior = .5 * ((1-last) - 1 - math.log1p(-last))
    expected_bpd = (prior + 4 * kl.flatten().double() + decoder) / math.log(2)
    assert np.allclose(actual_bpd, expected_bpd.cpu().numpy(), rtol=1e-5, atol=1e-5), (actual_bpd, expected_bpd)
    tvec = torch.tensor([0, 1], device=device, dtype=torch.long)
    z = torch.randn((2, 1, 4, 4), device=device, generator=gen)
    assert torch.equal(q_sample(z, tvec, torch.zeros_like(z), d)[0], z[0])
    # Contraste de Fréchet contra identidad de rango bajo en dimensión pequeña.
    random = np.random.default_rng(1702)
    a, b = random.normal(size=(12, 4)), random.normal(size=(11, 4))
    x, y = a - a.mean(0), b - b.mean(0)
    cross = np.linalg.svd(x @ y.T, compute_uv=False).sum() / math.sqrt((len(a)-1)*(len(b)-1))
    exact = ((a.mean(0)-b.mean(0))**2).sum() + (x*x).sum()/(len(a)-1) + (y*y).sum()/(len(b)-1) - 2*cross
    assert abs(exact - frechet_features(a, b)) < 1e-10
    def kernel(x, y):
        return (x @ y / len(x) + 1) ** 3
    explicit_mmd = (sum(kernel(x, y) for i, x in enumerate(a) for j, y in enumerate(a) if i != j) /
                    (len(a)*(len(a)-1)) +
                    sum(kernel(x, y) for i, x in enumerate(b) for j, y in enumerate(b) if i != j) /
                    (len(b)*(len(b)-1)) -
                    2 * sum(kernel(x, y) for x in a for y in b) / (len(a)*len(b)))
    assert abs(explicit_mmd - polynomial_mmd2(a, b)) < 1e-10
    assert precision_recall(a, a, k=3) == (1., 1.)
    assert all(np.isfinite(value['bootstrap_95']).all() for value in evaluate(a, b, repeats=5, seed=1704).values())
    print(f'Controles: posterior simulada media={residual.mean():.4f}, varianza={residual.var():.4f}, '
          'decoder discreto, t=0/1, Fréchet, MMD² y vecinos correctos.', flush=True)


def run_one(kind, root, output_root, quick, device):
    cls = datasets.MNIST if kind == 'mnist' else datasets.FashionMNIST
    transform = transforms.ToTensor()
    original_train = cls(root, train=True, download=True, transform=transform)
    original_test = cls(root, train=False, download=True, transform=transform)
    order = torch.randperm(len(original_train), generator=torch.Generator().manual_seed(1710)).tolist()
    train = Subset(original_train, order[:128] if quick else order)
    count, batch_size, epochs, width, T = (16, 8, 1, 8, 20) if quick else (1024, 128, 20, 32, 1000)
    test = Subset(original_test, range(count))
    train_loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0,
                              generator=torch.Generator().manual_seed(1711))
    diffusion = schedule(T, device)
    torch.manual_seed(1712)
    model = TimeUNet(width).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=.0002)
    generator = torch.Generator(device=device).manual_seed(1713)
    output = Path(output_root) / kind
    output.mkdir(parents=True, exist_ok=True)
    history = []
    for epoch in range(1, epochs + 1):
        model.train()
        total, n = 0., 0
        for images, _ in train_loader:
            x0 = images.to(device) * 2 - 1
            t = torch.randint(1, T + 1, (len(x0),), device=device, generator=generator)
            noise = torch.randn(x0.shape, device=device, generator=generator)
            loss = simple_loss(model, x0, t, noise, diffusion)
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 10, error_if_nonfinite=True)
            optimizer.step()
            total += loss.item() * len(x0)
            n += len(x0)
        history.append(total / n)
        print(f'{kind} época {epoch}: Lsimple media por componente {total/n:.6f}', flush=True)
    checkpoint = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'width': width,
                  'T': T, 'epochs': epochs, 'dataset': kind, 'quick': quick,
                  'betas': diffusion['beta'].cpu(), 'train_seed': 1712}
    torch.save(checkpoint, output / 'ddpm.pt')
    restored = torch.load(output / 'ddpm.pt', map_location=device, weights_only=True)
    inference = TimeUNet(width).to(device).eval()
    inference.load_state_dict(restored['model'])
    assert all(torch.equal(model.state_dict()[k], inference.state_dict()[k]) for k in model.state_dict())
    del model, optimizer, checkpoint, restored, loss, x0, noise
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    # MC independiente por repetición sobre las mismas imágenes test: error de MC, no de población.
    evaluation_gen = torch.Generator(device=device).manual_seed(1714)
    eval_loader = DataLoader(test, batch_size=8 if quick else 64, shuffle=False, num_workers=0)
    repeats = 3 if quick else 10
    per_repeat = [[] for _ in range(repeats)]
    for images, _ in eval_loader:
        values = estimate_bpd(inference, images.to(device) * 2 - 1, diffusion, repeats, evaluation_gen)
        for i in range(repeats):
            per_repeat[i].extend(values[i].tolist())
    repeat_means = np.asarray([np.mean(values) for values in per_repeat])
    bpd = float(repeat_means.mean())
    se_mc = float(repeat_means.std(ddof=1) / math.sqrt(repeats))
    print(f'{kind}: −ELBO estimado {bpd:.5f} bits/dim; error estándar MC {se_mc:.5f} '
          f'({repeats} repeticiones, {count} test).', flush=True)
    # Algoritmo de Ho para imágenes: media sin ruido en t=1; no se recorta dentro de la cadena.
    sample_gen = torch.Generator(device=device).manual_seed(1715)
    generated = []
    with torch.no_grad():
        for start in range(0, count, 8 if quick else 64):
            size = min(8 if quick else 64, count - start)
            x = torch.randn((size, 1, 28, 28), device=device, generator=sample_gen)
            for step in range(T, 0, -1):
                t = torch.full((size,), step, device=device, dtype=torch.long)
                noise = (torch.randn(x.shape, device=device, generator=sample_gen)
                         if step > 1 else torch.zeros_like(x))
                x = p_sample(inference, x, t, noise, diffusion)
                if not torch.isfinite(x).all():
                    raise FloatingPointError('La cadena ancestral dejó de ser finita')
            generated.append(x.cpu())
    generated = torch.cat(generated)
    outside = float(((generated < -1) | (generated > 1)).float().mean())
    fake = ((generated + 1) / 2).clamp(0, 1)
    save_image(fake[:16], output / 'samples.png', nrow=4)
    del inference, generated
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    # Arnés de m19-l11: misma arquitectura, adaptada a 28×28 y entrenada en el conjunto elegido.
    torch.manual_seed(1716)
    classifier = FashionFeatures().to(device)
    classifier_opt = torch.optim.Adam(classifier.parameters(), lr=.001)
    classifier_epochs = 1 if quick else 5
    for _ in range(classifier_epochs):
        classifier.train()
        for images, labels in train_loader:
            images, labels = images.to(device), labels.to(device)
            classifier_opt.zero_grad(set_to_none=True)
            F.cross_entropy(classifier(images), labels).backward()
            classifier_opt.step()
    classifier.eval()
    real_features, fake_features = [], []
    correct, position = 0, 0
    with torch.no_grad():
        for images, labels in eval_loader:
            n = len(images)
            features = classifier.features(images.to(device))
            correct += (classifier.classifier(features).argmax(1).cpu() == labels).sum().item()
            real_features.append(features.cpu().numpy())
            fake_features.append(classifier.features(fake[position:position+n].to(device)).cpu().numpy())
            position += n
    real_features, fake_features = np.concatenate(real_features), np.concatenate(fake_features)
    metric_repeats = 12 if quick else 100
    metrics = evaluate(real_features, fake_features, k=3, repeats=metric_repeats, seed=1717)
    accuracy = correct / count
    np.savez_compressed(output / 'features.npz', real=real_features, generated=fake_features)
    torch.save({'model': classifier.state_dict(), 'kind': kind, 'epochs': classifier_epochs,
                'resolution': 28}, output / 'feature-classifier.pt')
    report = {'dataset': kind, 'quick': quick, 'T': T, 'train_count': len(train), 'test_count': count,
              'epochs': epochs, 'training_losses': history, 'negative_elbo_bpd_mc_mean': bpd,
              'monte_carlo_standard_error': se_mc, 'mc_repeats': repeats,
              'metrics_custom_features': metrics, 'metric_bootstrap_repeats': metric_repeats,
              'metric_bootstrap_seed': 1717, 'neighbors_k': 3, 'classifier_test_accuracy': accuracy,
              'classifier_epochs': classifier_epochs, 'out_of_range_before_display_clip': outside,
              'variance': 'beta_t', 'decoder': 'gaussiana discretizada; bins extremos semiinfinitos',
              'display_sampler': 'media sin ruido en t=1', 'feature_extractor': 'm19-l11 FashionFeatures adaptado a 28×28; no Inception',
              'training_seed': 1712, 'elbo_seed': 1714, 'sampling_seed': 1715}
    (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    for name, value in metrics.items():
        print(f"{kind} {name}: {value['value']:.6f}; bootstrap 95 % {value['bootstrap_95']}", flush=True)
    print(f'{kind}: clasificador test {accuracy:.3f}; fuera de [−1,1] {outside:.3f}. '
          'Son características propias, no FID ni KID Inception.', flush=True)
    print('El promedio MC estima una cota superior del NLL, no garantiza una cota en cada realización.', flush=True)
    del classifier, classifier_opt, train, test, train_loader, fake
    if device.type == 'cuda':
        torch.cuda.empty_cache()


def main():
    quick = os.environ.get('ORYON_QUICK') == '1'
    selection = os.environ.get('ORYON_DATASET', 'both').lower()
    if selection not in ('mnist', 'fashion', 'both'):
        raise ValueError('ORYON_DATASET debe ser mnist, fashion o both')
    root = os.environ.get('ORYON_DATA_ROOT', './data')
    output = os.environ.get('ORYON_OUTPUT_DIR', './ddpm-results')
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f'dispositivo {device}; quick {quick}', flush=True)
    checks(device)
    for kind in ('mnist', 'fashion') if selection == 'both' else (selection,):
        run_one(kind, root, output, quick, device)


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

The fixed forward chain provides a closed Gaussian marginal and posterior. ELBO compares that posterior with the reverse model; uniform noise loss reweights terms for training, and the sampler applies reverse steps using declared conventions and indices.