Fast samplers: DDIM, EDM and high-order solvers
Derive DDIM and its relation to Euler integration, study EDM preconditioning, noise grids and Heun sampling, and compare exponential solvers and DDIM inversion under a measured evaluation budget.
After this lesson you can
- Derive the DDIM update and prove its admissible kernels preserve the forward marginals.
- Derive EDM preconditioning from unit-variance requirements.
- Implement DDIM, Heun with an EDM schedule and second-order DPM-Solver and measure empirical order.
- Plot FID against NFE for multiple samplers on a model without retraining it.
- Implement DDIM inversion and explain its limitations.
Before you start
Change the path without retraining
A diffusion network can be evaluated at many noise levels, and the sampler decides how to connect them. A thousand transitions can be expensive when each calls a U-Net. Reducing them is a numerical decision: with the same model and seed, two schemes may follow different paths and produce different discretization errors.
Count network function evaluations, or NFE, as well as steps. A second-order corrector may call the network twice per interval; guidance evaluating two network branches also changes cost. NFE does not measure all latency or memory, but starts a fairer comparison.
DDIM: other chains with the same forward marginals
Use and , with . For two times , the conditional kernel of the DDIM family is
if and . At the state is and no variance remains. Conditioned on , the forward marginal of has standard normal residual. If we generate with independent fresh noise, its mean is and the sum of variances is
Therefore for any admissible choice of . This proof concerns the family constructed with the real . Replacing it with an imperfect prediction or taking few large steps does not guarantee the learned generator preserves those marginals exactly. The construction of Song, Meng and Ermon permits a non-Markovian forward chain with the same basic noise-prediction training.
When generating, estimate and replace the residual with :
A common choice for is
With the update is deterministic for fixed input and network. With fresh noise enters; the formula does not say different images always retain the same structure or that a seed fixes the result if the number of random draws changes.
Deterministic DDIM as rescaled Euler
For , define and . Then and
This is an Euler step in variable , with the field evaluated at the start of the interval. In the continuous limit and under the parameterization’s assumptions, this form connects DDIM to the probability-flow ODE. Schedules must map times and scales consistently: and are not the same deviation.
DDIM inversion traverses the grid in reverse using the network to estimate noisy states. Approximate inversion and generative updates evaluate the network at different points: although both are deterministic, they are not exact inverse functions at finite step size. A finer grid may reduce error in favorable conditions, but guidance, clipping and network errors also affect reconstruction.
EDM: separate signal scale, network and sampler
The EDM design space works conveniently with and a denoiser . This corresponds to noise scale in rescaled variables; to port a VP model, use and , with . The VE score and Tweedie give the ODE
Preconditioning writes . Assume centered data with per-coordinate variance and independent noise of variance . Then
has unit variance. Choose by minimizing : the derivative gives . Residual variance is , so target has unit variance for . This normalizes second moments, not proof that the target is Gaussian or all image correlations disappear. Weighting the MSE of by equals normalized-target MSE, with the stated constants. See Karras and colleagues and their reference implementation.
Distribute steps and apply Heun
The EDM sampler can place positive levels using
and then append . Choice changes step distribution; there is no optimal value independent of model, endpoints and metric. The official implementation defaults to , , and , subject to network limits. On that grid , counting from zero.
import numpy as np
N, rho, sigma_min, sigma_max = 18, 7, 0.002, 80.0
grid = (sigma_max**(1/rho) + np.arange(N)/(N-1) *
(sigma_min**(1/rho)-sigma_max**(1/rho)))**rho
print(f'σ₅ = {grid[5]:.10f}; σ₀ = {grid[0]:.1f}; σ₁₇ = {grid[-1]:.3f}')For , an Euler step proposes . Heun evaluates again at and averages both slopes. In the final interval toward zero, the formula divides by : use the Euler proposal without that second evaluation. With intervals and no extra evaluations, the reference scheme costs NFE.
The churn parameter can temporarily increase noise before a step and add Gaussian perturbation. In the reference code, when lies in the enabled interval, and noise with standard deviation is added. Changing churn changes the process and required seeds; it is not merely choosing a different deterministic integrator.
Exponential integrators and guidance
Exponential integrators exploit the diffusion ODE’s known linear part. With and , half the log SNR, the formal solution between a noisy time and a less noisy one can be written
The linear part is integrated exactly and the solver approximates the integral containing the network. DPM-Solver develops approximations of different orders; theoretical order describes error under grid refinement and smoothness assumptions, not a promise of visual quality at every budget.
DPM-Solver++ formulates the method using data prediction and proposes multistep variants including 2M, while studying guided sampling. Strong guidance may make the field harder to integrate. Thresholding alters the solver’s prediction and therefore the effective field; it does not guarantee stability at every scale or amount to a harmless algebraic conversion. For a multistep solver, record startup and history as well as network calls.
Measure quality against cost
The NFE–quality tradeoff requires keeping checkpoint, seeds, reference set and processing fixed. An FID curve must include extractor, sample count, noise range and any clipping or guidance. FID with very few images is biased and may vary greatly: it checks a pipeline, not confidently ranks samplers. Wasserstein distance in a 2D example also does not replace image evaluation or demonstrate coverage alone.
To observe a solver’s numerical order, compare against a strict-tolerance reference in the same field and repeat on refined grids. If error does not decrease as expected, first check noise range, time interpolation and the last step before attributing it to the network. A local order estimate in a smooth field does not automatically predict image-model FID.
Lab: numerical order with an exact denoiser
For a one-dimensional Gaussian mixture, we know the exact posterior mean of clean data given x = x₀ + σε. The flow ODE in VE coordinates is dx/dσ = (x − D(x,σ))/σ. Compare deterministic DDIM, Euler, Heun and noise-prediction DPM-Solver-2 on an EDM grid with ρ = 7 and identical positive endpoints. DDIM and Euler are identical in these coordinates. References are five fixed initial conditions integrated with strict-tolerance RK45; error is trajectory RMS, not a generative quality metric. Orders are estimated by doubling steps; they are not guaranteed at low step counts or for a learned model.
The compared interval ends at σ = 0.08 to avoid dividing by zero. A final Euler step to σ = 0 is then illustrated, equivalent to applying the denoiser once without evaluating the derivative there. Output reports network evaluations, not just steps.
"""Solvers VE para una mezcla cuyo denoiser es analítico."""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.special import logsumexp
MEANS = np.array([-1.5, 1.5])
WEIGHTS = np.array([.6, .4])
DATA_STD = .4
def denoise(x, sigma):
variance = DATA_STD ** 2 + sigma ** 2
diff = x[..., None] - MEANS
logits = np.log(WEIGHTS) - diff ** 2 / (2 * variance)
weights = np.exp(logits - logsumexp(logits, axis=-1, keepdims=True))
posterior = MEANS + DATA_STD ** 2 / variance * diff
return np.sum(weights * posterior, axis=-1)
def derivative(x, sigma):
if sigma <= 0:
raise ValueError('La EDO requiere σ>0')
return (x - denoise(x, sigma)) / sigma
def edm_schedule(n, smin=.08, smax=3., rho=7.):
if n < 1 or not 0 < smin < smax or rho <= 0:
raise ValueError('Malla o extremos inválidos')
return np.linspace(smax ** (1/rho), smin ** (1/rho), n+1) ** rho
def solve_explicit(initial, sigmas, method):
x = initial.copy()
calls = 0
for s, target in zip(sigmas[:-1], sigmas[1:]):
d = derivative(x, s); calls += 1
h = target - s
if method in ('euler', 'ddim'):
# En coordenadas VE, DDIM determinista es Euler en σ.
x = x + h * d
elif method == 'heun':
predicted = x + h * d
d2 = derivative(predicted, target); calls += 1
x = x + .5 * h * (d + d2)
elif method == 'dpm2':
# DPM-Solver-2 de ruido: punto medio en λ=-log σ, α=1.
midpoint = np.sqrt(s * target)
mid_x = x + (midpoint - s) * d
d2 = derivative(mid_x, midpoint); calls += 1
x = x + h * d2
else:
raise ValueError('Método desconocido')
return x, calls
initial = np.array([-2.8, -1.2, 0., 1.1, 2.7])
reference = solve_ivp(lambda s, x: derivative(x, s), (3., .08), initial,
method='RK45', rtol=1e-11, atol=1e-12)
assert reference.success
truth = reference.y[:, -1]
for method in ('ddim', 'euler', 'heun', 'dpm2'):
errors = []
for n in (32, 64, 128):
predicted, nfe = solve_explicit(initial, edm_schedule(n), method)
errors.append(float(np.sqrt(np.mean((predicted-truth) ** 2))))
orders = np.log2(np.array(errors[:-1]) / errors[1:])
print(f'{method}: error RMS 32/64/128={errors[0]:.8f}/{errors[1]:.8f}/{errors[2]:.8f}; '
f'órdenes={orders[0]:.3f}/{orders[1]:.3f}; NFE a 128={nfe}.')
assert np.allclose(solve_explicit(initial, edm_schedule(32), 'ddim')[0],
solve_explicit(initial, edm_schedule(32), 'euler')[0])
# Paso final explícito, sin evaluar la EDO en σ=0.
last, nfe = solve_explicit(initial, edm_schedule(128), 'heun')
clean = last - .08 * derivative(last, .08)
assert np.all(np.isfinite(clean)) and np.allclose(clean, denoise(last, .08))
print(f'RK45 referencia NFE={reference.nfev}, rtol=1e-11, atol=1e-12; último Euler a σ=0 finito.')Exercises
Step 1 of 3. What is the law of (xₜ − aₜx₀)/bₜ given x₀?
Step 1 of 3. Which factor gives unit input variance?
import numpy as np
def edm_sampler(denoiser, x, sigmas, S_churn, rng):
pass
Local lab: compare samplers without retraining
Load the EMA saved in lesson 18 and apply ancestral DDPM with jumps, deterministic DDIM, Heun and DPM-Solver++ 2M midpoint. Weights are not updated. DDPM uses posterior jump variance , a different choice from variance used in lesson 18. Methods share starting points and an index grid of the original schedule; Heun operates in rescaled variables , and uses a second evaluation except at the final step. The independent routine distributes the same eight or more levels in according to EDM’s rule and interpolates between training times. This interpolation asks the network for output at fractional times, so it is not identical to continuous training. No extrapolation is made outside the table.
Output or is supported and the checkpoint’s linear or cosine schedule is reconstructed. If it uses exactly zero terminal SNR, rescaling is singular: start at the last finite level, , from an approximate normal. With any schedule, the initial normal is an approximate prior and the final prediction of is a decoding rule; the network is not evaluated outside its learned range. NFE counts network calls per batch, not seconds or total image count.
The experiment compares each generated sample with the CIFAR-10 test split using InceptionV3W from clean-fid==0.1.35, the same conversions and clean bicubic resizing as lesson 18. The script saves features, images, report.json with hashes, seeds and times, and a fid-vs-nfe.png plot. Finite-sample FID is biased; even the default full mode of 128 images per set is exploratory and not comparable to the 50,000-image standard. Change ORYON_EVAL_COUNT between 2 and 1024 according to memory and budget. DDIM round-trip MSE on test images is also calculated: inversion treats the clean image as the first noisy-level state and its error includes that approximation and discretization. It does not demonstrate exact reversibility.
Install PyTorch, torchvision, NumPy, SciPy, Pillow, Matplotlib and clean-fid==0.1.35. Set ORYON_PREVIOUS_CKPT to your lesson 18 diffusion.pt path and ORYON_INCEPTION_PT to the inception-2015-12-05.pt path used in previous lessons. ORYON_DATA_ROOT and ORYON_OUTPUT_DIR select data and results. If you install diffusers, separately written formulas are checked against its schedulers for one DDIM step without clipping and the first two DPM-Solver++ 2M midpoint steps; otherwise this check is reported as skipped. It uses fixed inputs and does not run the full generation routine.
The ORYON_QUICK=1 test uses a reduced EMA actually trained in the previous lesson, eight images and 4 or 8 levels; ORYON_CIFAR_PARQUET may point to the parquet directory to avoid downloading if you have pyarrow. In a run with the reduced linear checkpoint, DDIM and DPM-Solver++ used 4 and 8 NFE and Heun 7 and 15. DDIM inversion gave MSE 0.004515 and 0.001237 for 4 and 8 levels. With 8 levels, Heun and produced FID 573.8201, 573.8274, 573.6353 and 573.7635 respectively, all at 15 NFE (this is the run saved in heun-rho-fid.json, used by the interactive figure; repeated runs change hundredths, e.g. 573.8246 and 573.8184 for and ). These are results for eight images and two prior training attempts, not a quality comparison or reliable ranking. The check against diffusers==0.42.1 produced maximum errors of 7.75·10⁻⁷ for DDIM and 2.38·10⁻⁷ for the first two DPM-Solver++ 2M steps in the controlled test.
"""Comparación de samplers con la EMA CIFAR de m19-l18; no reentrena."""
import os, math, json, hashlib, io
from pathlib import Path
os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
torch.set_num_threads(2)
def groups(channels):
return math.gcd(32, channels)
class AdaResidual(nn.Module):
def __init__(self, channels, embedding):
super().__init__()
self.norm1 = nn.GroupNorm(groups(channels), channels)
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
self.norm2 = nn.GroupNorm(groups(channels), channels, affine=False)
self.condition = nn.Linear(embedding, 2 * channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
def forward(self, x, embedding):
h = self.conv1(F.silu(self.norm1(x)))
scale, shift = self.condition(embedding).chunk(2, dim=1)
h = self.norm2(h) * (1 + scale[:, :, None, None]) + shift[:, :, None, None]
return x + self.conv2(F.silu(h))
class SpatialAttention(nn.Module):
"""Atención de producto escalar solo en mapas de 16×16 y 8×8."""
def __init__(self, channels, head_dim=32):
super().__init__()
self.heads = max(1, channels // min(head_dim, channels))
if channels % self.heads:
raise ValueError('Los canales deben dividirse entre las cabezas')
self.norm = nn.GroupNorm(groups(channels), channels)
self.qkv = nn.Conv2d(channels, 3 * channels, 1)
self.output = nn.Conv2d(channels, channels, 1)
def forward(self, x):
batch, channels, height, width = x.shape
q, k, v = self.qkv(self.norm(x)).chunk(3, dim=1)
def arrange(z):
return z.reshape(batch, self.heads, channels // self.heads, height * width).transpose(2, 3)
h = F.scaled_dot_product_attention(arrange(q), arrange(k), arrange(v))
h = h.transpose(2, 3).reshape(batch, channels, height, width)
return x + self.output(h)
class DiffusionUNet(nn.Module):
"""CIFAR 32×32, niveles 32/16/8; ancho 128 en el modo completo."""
def __init__(self, width=128):
super().__init__()
if width < 8 or width % 8:
raise ValueError('El ancho debe ser un múltiplo de ocho')
embedding = 4 * width
self.width = width
self.time = nn.Sequential(nn.Linear(width, embedding), nn.SiLU(), nn.Linear(embedding, embedding))
self.input = nn.Conv2d(3, width, 3, padding=1)
self.enc32a = AdaResidual(width, embedding)
self.enc32b = AdaResidual(width, embedding)
self.down16 = nn.Conv2d(width, 2 * width, 3, stride=2, padding=1)
self.enc16a = AdaResidual(2 * width, embedding)
self.enc16b = AdaResidual(2 * width, embedding)
self.attn16_down = SpatialAttention(2 * width)
self.down8 = nn.Conv2d(2 * width, 3 * width, 3, stride=2, padding=1)
self.mid8a = AdaResidual(3 * width, embedding)
self.attn8 = SpatialAttention(3 * width)
self.mid8b = AdaResidual(3 * width, embedding)
self.up16 = nn.ConvTranspose2d(3 * width, 2 * width, 4, stride=2, padding=1)
self.merge16 = nn.Conv2d(4 * width, 2 * width, 1)
self.dec16a = AdaResidual(2 * width, embedding)
self.dec16b = AdaResidual(2 * width, embedding)
self.attn16_up = SpatialAttention(2 * width)
self.up32 = nn.ConvTranspose2d(2 * width, width, 4, stride=2, padding=1)
self.merge32 = nn.Conv2d(2 * width, width, 1)
self.dec32a = AdaResidual(width, embedding)
self.dec32b = AdaResidual(width, embedding)
self.out_norm = nn.GroupNorm(groups(width), width)
self.output = nn.Conv2d(width, 3, 3, padding=1)
def forward(self, x, t, T):
half = self.width // 2
freq = torch.exp(torch.linspace(0, -math.log(10000), half, device=x.device, dtype=x.dtype))
phase = (t.to(x.dtype) * (1000. / T))[:, None] * freq[None]
emb = self.time(torch.cat((phase.sin(), phase.cos()), dim=1))
h = self.input(x)
s32 = self.enc32b(self.enc32a(h, emb), emb)
h = self.down16(s32)
s16 = self.attn16_down(self.enc16b(self.enc16a(h, emb), emb))
h = self.mid8a(self.down8(s16), emb)
h = self.mid8b(self.attn8(h), emb)
h = self.merge16(torch.cat((self.up16(h), s16), dim=1))
h = self.attn16_up(self.dec16b(self.dec16a(h, emb), emb))
h = self.merge32(torch.cat((self.up32(h), s32), dim=1))
h = self.dec32b(self.dec32a(h, emb), emb)
return self.output(F.silu(self.out_norm(h)))
def make_schedule(kind, T, device, zero_terminal=False):
if T < 2 or kind not in ('linear', 'cosine'):
raise ValueError('Calendario o número de pasos inválidos')
if kind == 'linear':
beta = torch.linspace(1e-4, .02, T, dtype=torch.float64, device=device)
else:
t = torch.arange(T + 1, dtype=torch.float64, device=device) / T
f = torch.cos((t + .008) / 1.008 * math.pi / 2).square()
beta = (1 - f[1:] / f[:-1]).clamp(max=.999)
bar = torch.cumprod(1 - beta, dim=0)
if zero_terminal:
a = bar.sqrt()
# Preserva el primer nivel ruidoso, no el índice t=0 que se añade después.
a = (a - a[-1]) * a[0] / (a[0] - a[-1])
bar = a.square()
previous = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar[:-1]))
beta = 1 - bar / previous
beta = torch.cat((torch.zeros(1, dtype=beta.dtype, device=device), beta))
bar = torch.cat((torch.ones(1, dtype=bar.dtype, device=device), bar))
previous = torch.cat((bar[:1], bar[:-1]))
return {'T': T, 'kind': kind, 'beta': beta, 'bar': bar, 'previous': previous,
'zero_terminal': zero_terminal}
def grid(T, n):
if n < 2 or n > T:
raise ValueError('Los pasos deben estar entre 2 y T')
ids = np.rint(np.linspace(T, 1, n)).astype(int)
if len(set(ids)) != n:
raise ValueError('La malla contiene tiempos repetidos')
return ids.tolist()
def estimate(model, x, t, abar, T, parameterization):
a, s = math.sqrt(abar), math.sqrt(1 - abar)
raw = model(x, torch.full((len(x),), float(t), device=x.device), T)
if parameterization == 'epsilon':
if a == 0:
raise ValueError('Salida epsilon no admite α terminal cero')
eps, x0 = raw, (x - s * raw) / a
elif parameterization == 'v':
x0, eps = a * x - s * raw, s * x + a * raw
else:
raise ValueError('Salida desconocida')
return x0, eps
def get_bar(bars, t):
# Interpolación de log ᾱ entre índices ruidosos válidos; nunca extrapola.
if not 1 <= t <= len(bars)-1:
raise ValueError('Tiempo fuera de la tabla de entrenamiento')
low = int(math.floor(t)); high = min(low + 1, len(bars)-1)
if abs(t-low) < 1e-12:
if bars[low] <= 0: raise ValueError('α es cero en ese tiempo')
return bars[low]
if bars[low] <= 0 or bars[high] <= 0:
raise ValueError('La malla continua no admite α terminal cero')
return math.exp((high-t)*math.log(bars[low]) + (t-low)*math.log(bars[high])) if high != low else bars[low]
def time_for_ratio(bars, ratio):
finite = bars[1:][bars[1:] > 0]
ratios = np.sqrt((1-finite)/finite)
if ratio < ratios[0]-1e-10 or ratio > ratios[-1]+1e-10:
raise ValueError('σ/α fuera de la tabla')
# Interpolación consistente con log ᾱ, no con σ/α.
target_bar = 1/(1+ratio**2)
return float(np.interp(math.log(target_bar), np.log(finite[::-1]), np.arange(len(finite), 0, -1)))
@torch.no_grad()
def generate(model, bars, parameterization, ids, method, initial, generator):
T = len(bars)-1
x = initial.clone()
nfe = 0
previous_x0, previous_lambda = None, None
for j, t in enumerate(ids):
nxt = ids[j+1] if j+1 < len(ids) else 0
a_t, s_t = math.sqrt(bars[t]), math.sqrt(1-bars[t])
a_n, s_n = math.sqrt(bars[nxt]), math.sqrt(1-bars[nxt])
x0, eps = estimate(model, x, t, bars[t], T, parameterization)
nfe += 1
if nxt == 0:
x = x0
elif method == 'ddim':
x = a_n*x0 + s_n*eps
elif method == 'ddpm':
# Posterior q(x_s|x_t,x0) de una transición saltada.
ratio = bars[t]/bars[nxt]
variance = (1-bars[nxt])/(1-bars[t])*(1-ratio)
mean = a_n*(1-ratio)/(1-bars[t])*x0 + math.sqrt(ratio)*(1-bars[nxt])/(1-bars[t])*x
x = mean + math.sqrt(max(0., variance))*torch.randn(x.shape, device=x.device, generator=generator)
elif method == 'heun':
# VE reescalada y=x/α, r=σ/α, dy/dr=εθ.
r_t, r_n = s_t/a_t, s_n/a_n
y = x/a_t
proposal = y + (r_n-r_t)*eps
_, eps_next = estimate(model, a_n*proposal, nxt, bars[nxt], T, parameterization)
nfe += 1
x = a_n*(y + .5*(r_n-r_t)*(eps+eps_next))
elif method == 'dpmpp2m':
# DPM-Solver++ multistep segundo orden, midpoint, λ=log(α/σ).
lam_t, lam_n = math.log(a_t/s_t), math.log(a_n/s_n)
h = lam_n-lam_t
corrected = x0
if previous_x0 is not None:
r = (lam_t-previous_lambda)/h
corrected = x0 + .5*(x0-previous_x0)/r
x = (s_n/s_t)*x - a_n*math.expm1(-h)*corrected
previous_x0, previous_lambda = x0, lam_t
else:
raise ValueError('Sampler desconocido')
if not torch.isfinite(x).all():
raise FloatingPointError('Muestra no finita')
return x, nfe
@torch.no_grad()
def heun_rho(model, bars, parameterization, start, count, rho, initial):
# Calendario EDM en r=σ/α dentro del rango de la tabla del checkpoint.
rmax = math.sqrt((1-bars[start])/bars[start])
rmin = math.sqrt((1-bars[1])/bars[1])
ratios = np.linspace(rmax**(1/rho), rmin**(1/rho), count)**rho
times = [time_for_ratio(bars, float(r)) for r in ratios]
x = initial.clone(); nfe = 0; T = len(bars)-1
for i, (r, t) in enumerate(zip(ratios, times)):
b = get_bar(bars, t); a = math.sqrt(b)
x0, eps = estimate(model, x, t, b, T, parameterization); nfe += 1
if i == count-1:
x = x0
else:
rn, tn = float(ratios[i+1]), times[i+1]
bn = get_bar(bars, tn); an = math.sqrt(bn)
y = x/a; proposal = y+(rn-r)*eps
_, eps_next = estimate(model, an*proposal, tn, bn, T, parameterization); nfe += 1
x = an*(y+.5*(rn-r)*(eps+eps_next))
if not torch.isfinite(x).all(): raise FloatingPointError('Heun produjo valores no finitos')
return x, nfe, times, ratios.tolist()
@torch.no_grad()
def ddim_inversion(model, bars, parameterization, ids, clean):
# Se interpreta la imagen limpia como primer estado t=1 aproximado.
x = clean.clone(); T = len(bars)-1; ascending = list(reversed(ids))
for t, nxt in zip(ascending[:-1], ascending[1:]):
x0, eps = estimate(model, x, t, bars[t], T, parameterization)
x = math.sqrt(bars[nxt])*x0 + math.sqrt(1-bars[nxt])*eps
encoded = x.clone()
back, nfe = generate(model, bars, parameterization, ids, 'ddim', x,
torch.Generator(device=x.device).manual_seed(2019))
return back, encoded, len(ascending)-1, nfe
def low_rank_fid(real, fake):
real, fake = np.asarray(real, np.float64), np.asarray(fake, np.float64)
x, y = real-real.mean(0), fake-fake.mean(0)
cross = np.linalg.svd(x @ y.T, compute_uv=False).sum()/math.sqrt((len(x)-1)*(len(y)-1))
value = np.square(real.mean(0)-fake.mean(0)).sum()+(x*x).sum()/(len(x)-1)+(y*y).sum()/(len(y)-1)-2*cross
if value < -1e-7: raise ValueError('FID negativo fuera de tolerancia')
return max(float(value), 0.)
def features(images, inception, device):
resize = build_resizer('clean'); chunks = []
with torch.inference_mode():
for start in range(0, len(images), 4):
pixels = (images[start:start+4].clamp(0, 1)*255).round().to(torch.uint8)
arrays = pixels.permute(0,2,3,1).cpu().numpy()
resized = np.stack([resize(array).transpose(2,0,1) for array in arrays])
chunks.append(inception(torch.from_numpy(resized).to(device)).cpu().numpy())
return np.concatenate(chunks)
def test_images(root, count, parquet):
if parquet:
import pyarrow.parquet as pq
paths = sorted(Path(parquet).glob('test-*.parquet'))
if not paths: raise ValueError('No existe parquet de test')
rows = []
for path in paths:
for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['img']):
rows.extend(row['img']['bytes'] for row in batch.to_pylist())
if len(rows) >= count: break
if len(rows) >= count: break
if len(rows) < count: raise ValueError('Faltan ejemplos de test')
images = []
for row in rows[:count]:
with Image.open(io.BytesIO(row)) as image:
images.append(transforms.ToTensor()(image.convert('RGB')))
return torch.stack(images), [str(path) for path in paths]
data = datasets.CIFAR10(root, train=False, download=True, transform=transforms.ToTensor())
return torch.stack([data[i][0] for i in range(count)]), ['torchvision CIFAR10 test, primeras filas']
def verify(device):
for kind in ('linear', 'cosine'):
for param in ('epsilon', 'v'):
bars = make_schedule(kind, 20, device)['bar'].cpu().numpy()
zero_bars = make_schedule(kind, 20, device, True)['bar'].cpu().numpy()
assert get_bar(zero_bars, 19.) == zero_bars[19]
limit = math.sqrt((1-zero_bars[19])/zero_bars[19])
assert abs(time_for_ratio(zero_bars, limit)-19.) < 1e-8
assert len(grid(20, 8)) == 8
for t in (1., 3.5, 19., 20.):
b = get_bar(bars, t)
assert abs(time_for_ratio(bars, math.sqrt((1-b)/b))-t) < 1e-8
class Oracle(nn.Module):
def forward(self, x, t, T):
b = torch.as_tensor([get_bar(bars, float(v)) for v in t], device=x.device, dtype=x.dtype)
a, s = b.sqrt()[:,None,None,None], (1-b).sqrt()[:,None,None,None]
# Prior normal estándar estacionario: E[x0|xt]=a*xt.
return s*x if param == 'epsilon' else torch.zeros_like(x)
model = Oracle().to(device)
initial = torch.randn((2,3,4,4), device=device)
for method in ('ddpm','ddim','heun','dpmpp2m'):
result, nfe = generate(model, bars, param, grid(20, 8), method, initial,
torch.Generator(device=device).manual_seed(2000))
assert torch.isfinite(result).all() and nfe == (15 if method == 'heun' else 8)
print('Controles: ε/v, calendarios, adaptación σ/α y NFE correctos.', flush=True)
def diffusers_check():
try:
from diffusers import DDIMScheduler, DPMSolverMultistepScheduler
except ImportError:
print('Contraste diffusers omitido: instala diffusers para activarlo.', flush=True)
return {'available': False}
schedule = make_schedule('linear', 20, 'cpu')
scheduler = DDIMScheduler(num_train_timesteps=20, trained_betas=schedule['beta'][1:].numpy(),
clip_sample=False, set_alpha_to_one=True, timestep_spacing='leading')
scheduler.set_timesteps(4)
t = int(scheduler.timesteps[0]); nxt = t-5
gen = torch.Generator().manual_seed(2017)
x = torch.randn((2, 3, 4, 4), generator=gen); eps = torch.randn(x.shape, generator=gen)
official = scheduler.step(eps, t, x, eta=0).prev_sample
b, bn = float(schedule['bar'][t+1]), float(schedule['bar'][nxt+1])
expected = math.sqrt(bn)*(x-math.sqrt(1-b)*eps)/math.sqrt(b)+math.sqrt(1-bn)*eps
error = float((official-expected).abs().max())
assert error < 1e-5
dpm = DPMSolverMultistepScheduler(num_train_timesteps=20, trained_betas=schedule['beta'][1:].numpy(),
algorithm_type='dpmsolver++', solver_order=2, solver_type='midpoint',
prediction_type='sample', thresholding=False)
dpm.set_timesteps(4)
z = torch.randn((2,3,4,4), generator=gen)
m0 = torch.randn(z.shape, generator=gen); m1 = torch.randn(z.shape, generator=gen)
original = z.clone()
step0 = dpm.step(m0, dpm.timesteps[0], z).prev_sample
step1 = dpm.step(m1, dpm.timesteps[1], step0).prev_sample
def coeff(r):
r = float(r); a = 1/math.sqrt(1+r*r); return a, a*r
a0,s0 = coeff(dpm.sigmas[0]); a1,s1 = coeff(dpm.sigmas[1]); a2,s2 = coeff(dpm.sigmas[2])
l0,l1,l2 = math.log(a0/s0), math.log(a1/s1), math.log(a2/s2)
h0,h1 = l1-l0,l2-l1
manual0 = (s1/s0)*original-a1*math.expm1(-h0)*m0
manual1 = (s2/s1)*manual0-a2*math.expm1(-h1)*(m1+.5*(m1-m0)*h1/h0)
error_dpm = max(float((step0-manual0).abs().max()), float((step1-manual1).abs().max()))
assert error_dpm < 1e-5
print(f'Contraste diffusers: DDIM error máximo {error:.2g}; DPM++ 2M {error_dpm:.2g}.', flush=True)
return {'available': True, 'ddim_eta0_max_error': error, 'dpmpp2m_max_error': error_dpm,
'scope': 'DDIM un paso; DPM++ primer y segundo paso midpoint sin clipping'}
def sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1024*1024), b''): h.update(block)
return h.hexdigest()
def main():
quick = os.environ.get('ORYON_QUICK') == '1'
checkpoint_path = os.environ.get('ORYON_PREVIOUS_CKPT')
inception_file = os.environ.get('ORYON_INCEPTION_PT')
if not checkpoint_path or not inception_file:
raise ValueError('Define ORYON_PREVIOUS_CKPT y ORYON_INCEPTION_PT')
inception_path = Path(inception_file)
if inception_path.name != 'inception-2015-12-05.pt' or not inception_path.is_file():
raise ValueError('ORYON_INCEPTION_PT debe nombrar inception-2015-12-05.pt existente')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'dispositivo {device}, quick {quick}', flush=True)
verify(device)
scheduler_check = diffusers_check()
checkpoint = torch.load(checkpoint_path, map_location='cpu', weights_only=True)
for key in ('ema','width','T','schedule','parameterization'):
if key not in checkpoint: raise ValueError(f'Falta {key} en checkpoint m19-l18')
T, kind, param = checkpoint['T'], checkpoint['schedule'], checkpoint['parameterization']
zero = checkpoint.get('zero_terminal', False)
schedule = make_schedule(kind, T, 'cpu', zero)
bars = schedule['bar'].numpy()
model = DiffusionUNet(checkpoint['width']).to(device).eval().requires_grad_(False)
model.load_state_dict(checkpoint['ema'])
del checkpoint
# Para SNR cero, el reescalado sigma/alpha es singular: se comienza en T−1.
start = T-1 if bars[-1] == 0 else T
if start < 2: raise ValueError('El calendario no contiene suficientes tiempos finitos')
if zero: print('SNR terminal cero: se empieza en T-1 con prior normal aproximado.', flush=True)
counts = [4, 8] if quick else [10, 20, 50]
counts = sorted(set(min(n, start) for n in counts))
n = 8 if quick else int(os.environ.get('ORYON_EVAL_COUNT', '128'))
if n < 2 or n > 1024: raise ValueError('ORYON_EVAL_COUNT debe estar entre 2 y 1024')
parquet = os.environ.get('ORYON_CIFAR_PARQUET')
if parquet and not quick: raise ValueError('Parquet solo se admite en quick')
real, source = test_images(os.environ.get('ORYON_DATA_ROOT', './data'), n, parquet)
inception = InceptionV3W(str(inception_path.parent), download=False, resize_inside=False).to(device).eval()
ref_features = features(real, inception, device)
output = Path(os.environ.get('ORYON_OUTPUT_DIR', './sampler-comparison')); output.mkdir(parents=True, exist_ok=True)
rows = []; all_features = {'reference': ref_features}
for count in counts:
ids = grid(start, count)
for method in ('ddpm','ddim','heun','dpmpp2m'):
result = []
# Misma semilla inicial para los cuatro métodos con igual lote y presupuesto.
gen = torch.Generator(device=device).manual_seed(2018)
total_nfe = None
for offset in range(0, n, 4):
size = min(4, n-offset)
initial = torch.randn((size,3,32,32), device=device, generator=gen)
noise_gen = torch.Generator(device=device).manual_seed(2100+offset)
images, nfe = generate(model, bars, param, ids, method, initial, noise_gen)
if total_nfe is not None: assert total_nfe == nfe
total_nfe = nfe
result.append(images.cpu())
result = torch.cat(result)
outside = float(((result < -1) | (result > 1)).float().mean())
fake_features = features((result+1)/2, inception, device)
fid = low_rank_fid(ref_features, fake_features)
key = f'{method}_{count}'
all_features[key] = fake_features
save_image(((result[:16]+1)/2).clamp(0,1), output/f'{key}.png', nrow=4)
row = {'method':method, 'steps':count, 'nfe_per_batch':total_nfe,
'fid':fid, 'outside_fraction':outside, 'timesteps':ids}
rows.append(row)
print(f'{key}: NFE={total_nfe}, FID={fid:.4f}, fuera={outside:.4f}', flush=True)
inversion = []
for count in counts:
originals = real[:min(4,n)].to(device)*2-1
reconstructed, _, nf_enc, nf_dec = ddim_inversion(model, bars, param, grid(start,count), originals)
mse = float((reconstructed-originals).square().mean())
inversion.append({'steps':count, 'encoding_nfe':nf_enc, 'decoding_nfe':nf_dec, 'mse':mse})
print(f'Inversión DDIM {count}: MSE={mse:.6f}, NFE ida/vuelta={nf_enc}/{nf_dec}', flush=True)
rho_rows = []
rho_steps = counts[-1]
for rho in (1,3,7,10):
chunks = []; gen = torch.Generator(device=device).manual_seed(2018)
for offset in range(0, n, 4):
initial = torch.randn((min(4,n-offset),3,32,32), device=device, generator=gen)
sample, rho_nfe, rho_times, ratios = heun_rho(model, bars, param, start, rho_steps, rho, initial)
chunks.append(sample.cpu())
samples = torch.cat(chunks)
fake = features((samples+1)/2, inception, device)
all_features[f'heun_rho_{rho}'] = fake
fid = low_rank_fid(ref_features, fake)
outside = float(((samples < -1)|(samples > 1)).float().mean())
rho_rows.append({'rho':rho, 'steps':rho_steps, 'nfe':rho_nfe, 'fid':fid,
'outside_fraction':outside, 'timesteps':rho_times, 'ratios':ratios})
print(f'Heun ρ={rho}: NFE={rho_nfe}, FID={fid:.4f}, fuera={outside:.4f}', flush=True)
np.savez_compressed(output/'features.npz', **all_features)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for method in ('ddpm', 'ddim', 'heun', 'dpmpp2m'):
series = [row for row in rows if row['method'] == method]
ax.plot([row['nfe_per_batch'] for row in series], [row['fid'] for row in series], 'o-', label=method)
ax.set(xlabel='Evaluaciones de la red por lote', ylabel='FID Inception estimado',
title=f'CIFAR-10: {n} imágenes por conjunto')
ax.legend(); fig.tight_layout(); fig.savefig(output/'fid-vs-nfe.png', dpi=150); plt.close(fig)
report = {'checkpoint_sha256':sha256(checkpoint_path), 'inception_sha256':sha256(inception_path),
'checkpoint':checkpoint_path, 'kind':kind, 'parameterization':param, 'T':T,
'zero_terminal':zero, 'start_t':start, 'quick':quick, 'reference':source,
'sample_seed':2018, 'noise_seed_base':2100, 'n_real':n, 'n_generated':n,
'FID_protocol':'InceptionV3W clean-fid 0.1.35, RGB uint8, PIL float bicúbico a 299',
'fid':rows, 'heun_rho':rho_rows, 'inversion':inversion, 'diffusers_check':scheduler_check,
'caveat':'FID con pocas muestras es sesgado. Normal terminal aproximada; sin extrapolación.'}
(output/'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('FID de muestra finita sesgado; este ensayo no demuestra calidad ni superioridad.', flush=True)
del model, inception
if device.type == 'cuda': torch.cuda.empty_cache()
if __name__ == '__main__':
main()
npm run lab and open the connection link.DDIM changes the trajectory without changing basic training; EDM separates preconditioning, grid and solver; exponential integrators exploit the ODE’s linear part. Comparison requires compatible conventions and cost measured in network evaluations.