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 , with as data, , and , plus . Distinguish from its cumulative product: an index difference changes every sampler step.
Variance belongs to one step; it is not the total variance of conditioned on . The accumulated variance has a closed form:
For induction, the claim is immediate at . If it holds at , substitute the expression for into with fresh independent noise. Mean becomes and variance . This permits choosing a time and sampling its marginal directly without simulating every step.
Images are usually scaled to . The linear schedule of Ho, Jain and Abbeel uses and between and ; a cosine schedule was proposed later by Nichol and Dhariwal. For the linear schedule, : conditional signal is small, although the terminal marginal is not thereby exactly standard normal for every data distribution.
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 is accessible during training because is known. For , Bayes gives
Complete the square in . Scalar precision and linear term are
Thus . Simplifying:
Coefficients are positive but need not sum to one. At , is fixed: the posterior is a point mass and . The precision expressions above use in the denominator and apply to ; do not treat the point mass as a nondegenerate Gaussian.
ELBO of a latent chain
The generator starts from and uses for , plus decoder . Jensen gives the usual variational bound:
To regroup it, use Bayes’ identity for
Marginal ratios cancel telescopically. The negative bound, averaged over the forward chain, is
The diffusion ELBO is for this . is KL between Gaussians and does not depend on when the forward chain is fixed. Each intermediate term is Gaussian KL if the reverse model is Gaussian too. 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 , with fixed . Gaussian KL gives
The second summand is independent of the learned mean, although not necessarily zero. One can parameterize directly or predict and substitute into . With , a third option predicts noise:
These are algebraic conversions between outputs for fixed and , not a claim that all losses or architectures train identically. Substituting turns the -dependent term into
Noise parameterization does not make exact ELBO weights uniform. The simplified loss of Ho and colleagues deliberately chooses an error without that weight:
Term enters this training loss but is not an intermediate KL with . Changing the distribution of without compensation changes loss weighting. Averaging coordinates instead of summing also introduces factor : keep it consistent when comparing bits per dimension.
Score and Tweedie inside the network
At each , the distribution of is scaled data plus Gaussian noise with standard deviation . Its score conditioned on is . By denoising score matching, the optimal squared-error predictor satisfies
Thus defining turns noise prediction into a score field; equality with marginal score requires an optimal predictor and usual assumptions. Applying Tweedie to and recovers the preceding formula for . An approximate prediction need not be a posterior sample.
From noise to a sample
The DDPM ancestral sampler starts with and for evaluates . At add with independent ; at the final step add no Gaussian noise. For discrete images the probabilistic model of assigns mass to quantization intervals; returning the mean at is a generation rule not necessarily equivalent to sampling that discrete decoder.
Choices and yield different chains. belongs to the posterior conditioned on , whereas the reverse model observes only : choosing it as generator variance is a parameterization decision, not an identity for the marginal posterior. Clipping to changes the mean if reconstructed from it; use it consistently and declare the choice. Calculate at least in single precision, preferably double when constructing the schedule, not as a float16 cumulative product.
Algorithms 1 and 2 of Ho and colleagues follow directly. Training: choose , uniform and noise, form using the closed marginal and optimize MSE of . Sampling: initialize , traverse decreasing times, calculate mean with and add noise only if . Their CIFAR-10 figures for 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.
"""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 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}.')"""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}.')"""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
Step 1 of 3. If the mean at t−1 is √ᾱₜ₋₁ x₀, what is it at t?
Step 1 of 3. What is the scalar precision in u?
Step 1 of 3. Which identity introduces posterior q(xₜ₋₁ | xₜ,x₀)?
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
Local lab: DDPM and variational bound for images
Train DDPM on 28×28 MNIST and Fashion-MNIST. U-Net predicts from noisy image and sinusoidal time representation. For each image choose uniformly between 1 and , generate from the closed marginal and minimize per-component mean . The forward chain uses Ho and colleagues’ linear schedule; products are calculated in float64 even though the network uses float32. Images are scaled to and test data do not participate in training.
To evaluate the variational bound, use analytical , one intermediate term with uniform from 2 to multiplied by , and 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 , including positive variance for the decoder; do not divide by . Output is bits per dimension, dividing by pixel count and .
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 and no noise at , 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 . Report the fraction outside before clipping. Standard normal approximation to the terminal marginal depends on and schedule, and is especially poor in the 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 , precision and coverage with 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 , 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, , 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 . 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 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.
"""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()
npm run lab and open the connection link.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.