Module contents
Lesson 20 of 28Advanced 115 min

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.

InteractiveSampler race

All four methods start from the same batch. Lines follow three particles, and gray points are held-out test data.

t = 100
  • Sampler output
  • 64 test points

The curves connect measurements for 10, 20, 50 and 100 intervals. The readout uses the current selection, which can fall between those points.

This uses the 2D MLP trained in m19-l17 and the same 64 initial Gaussian samples for every method (seed 2010). DDPM adds noise with seed 2011. The 64 test points are separate from training. The distance averages empirical 1D W1 across 32 fixed directions, an approximation distinct from full 2D Wasserstein distance. One seed and a small sample cannot establish a general ranking.

The indices form a rounded uniform grid from 100 to 0, so evaluations use integer model times. Heun takes two function evaluations per interval, except for the final interval to σ = 0. DDIM, DPM-Solver++ 2M, and DDPM with skipped steps take one per interval. DDPM uses the variance β of each jump. The axes adjust to the displayed particles and three trajectories. Trajectories use the weights and noise saved in race-core.json. race_export.py verifies the plotted values for the four budgets.

Method
20
Index t
100
NFE per particle
0 / 20
Final sliced W1
0.30881
Compare trajectories, samples and cost with the model and metric stated in the figure.

DDIM: other chains with the same forward marginals

Use at=αˉta_t=\sqrt{\bar\alpha_t} and bt=1−αˉtb_t=\sqrt{1-\bar\alpha_t}, with at>0a_t>0. For two times 0≤s<t0\le s<t, the conditional kernel of the DDIM family is

qδ(xs∣xt,x0)=N ⁣(asx0+1−αˉs−δt,s2 xt−atx0bt,δt,s2I),q_\delta(x_s\mid x_t,x_0)= \Normal\!\left( a_sx_0+ \sqrt{1-\bar\alpha_s-\delta_{t,s}^2}\, \frac{x_t-a_tx_0}{b_t}, \delta_{t,s}^2 I \right),

if 0≤δt,s2≤1−αˉs0\le\delta_{t,s}^2\le1-\bar\alpha_s and bt>0b_t>0. At s=0s=0 the state is x0x_0 and no variance remains. Conditioned on x0x_0, the forward marginal of xtx_t has standard normal residual. If we generate xsx_s with independent fresh noise, its mean is asx0a_sx_0 and the sum of variances is

(1−αˉs−δt,s2)+δt,s2=1−αˉs.(1-\bar\alpha_s-\delta_{t,s}^2)+\delta_{t,s}^2 =1-\bar\alpha_s.

Therefore q(xs∣x0)=N(asx0,(1−αˉs)I)q(x_s\mid x_0)=\Normal(a_sx_0,(1-\bar\alpha_s)I) for any admissible choice of δt,s\delta_{t,s}. This proof concerns the family constructed with the real x0x_0. 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 x^0=(xt−btϵθ(xt,t))/at\hat x_0=(x_t-b_t\epsilon_\theta(x_t,t))/a_t and replace the residual with ϵθ\epsilon_\theta:

xs=asx^0+1−αˉs−δt,s2 ϵθ(xt,t)+δt,sz,z∼N(0,I).x_s=a_s\hat x_0+ \sqrt{1-\bar\alpha_s-\delta_{t,s}^2}\,\epsilon_\theta(x_t,t) +\delta_{t,s}z,\qquad z\sim\Normal(0,I).

A common choice for 0≤η≤10\le\eta\le1 is

δt,s=η1−αˉs1−αˉt(1−αˉtαˉs).\delta_{t,s}= \eta\sqrt{\frac{1-\bar\alpha_s}{1-\bar\alpha_t} \left(1-\frac{\bar\alpha_t}{\bar\alpha_s}\right)}.

With η=0\eta=0 the update is deterministic for fixed input and network. With η>0\eta>0 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.

InteractiveFrom deterministic to stochastic

Each color shows 32 samples. Lines join the states of three particles, and gray points are from the held-out spiral.

  • η = 0
  • Selected η
  • Held-out test points

Weights and the 100 values of ᾱ come from the MLP trained for 1,800 updates on the 2D spiral in the short m19-l17 run. The schedule uses a uniform integer subsequence from 100 to 0. Each network evaluation counts as one NFE per particle. The initial normal batch uses seed 2020. Gaussian increments use seed 2021 and are shared across η values. The widget computes x̂₀ without clipping, and the axes can hide values outside [−4, 4].

With Aₜ = ᾱₜ and s < t, use x̂₀ = (xₜ − √(1 − Aₜ)ε̂)/√Aₜ and additional standard deviation σ = η√[(1 − Aₛ)/(1 − Aₜ) · (1 − Aₜ/Aₛ)]. Then xₛ = √Aₛ x̂₀ + √(1 − Aₛ − σ²)ε̂ + σξ. At η = 0 the update is deterministic. This small network may still fail to preserve visual structure. See Song et al., Equations 12 and 16.

0.50
20
Model step t
100 / 100
NFE per particle
0 / 20
Keep the initialization fixed and change η and the budget; the figure explains the noise and model used.

Deterministic DDIM as rescaled Euler

For η=0\eta=0, define yt=xt/aty_t=x_t/a_t and rt=bt/atr_t=b_t/a_t. Then x^0=yt−rtϵθ(xt,t)\hat x_0=y_t-r_t\epsilon_\theta(x_t,t) and

ys=x^0+rsϵθ(xt,t)=yt+(rs−rt)ϵθ(xt,t).y_s=\hat x_0+r_s\epsilon_\theta(x_t,t) =y_t+(r_s-r_t)\epsilon_\theta(x_t,t).

This is an Euler step in variable rr, 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: btb_t and rt=bt/atr_t=b_t/a_t 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 x^0\hat x_0 and network errors also affect reconstruction.

EDM: separate signal scale, network and sampler

The EDM design space works conveniently with y=x0+σϵy=x_0+\sigma\epsilon and a denoiser Dθ(y,σ)D_\theta(y,\sigma). This σ\sigma corresponds to noise scale in rescaled variables; to port a VP model, use y=xt/aty=x_t/a_t and σ=bt/at\sigma=b_t/a_t, with at>0a_t>0. The VE score and Tweedie give the ODE

dydσ=y−Dθ(y,σ)σ,σ>0.\frac{dy}{d\sigma}=\frac{y-D_\theta(y,\sigma)}{\sigma}, \qquad \sigma>0.

Preconditioning writes Dθ=cskipy+coutFθ(ciny,cnoise)D_\theta=c_{\rm skip}y+c_{\rm out}F_\theta(c_{\rm in}y,c_{\rm noise}). Assume centered data with per-coordinate variance σdata2>0\sigma_{\rm data}^2>0 and independent noise of variance σ2>0\sigma^2>0. Then

cin=1σ2+σdata2,cskip=σdata2σ2+σdata2,cout=σσdataσ2+σdata2.c_{\rm in}=\frac{1}{\sqrt{\sigma^2+\sigma_{\rm data}^2}},\quad c_{\rm skip}=\frac{\sigma_{\rm data}^2}{\sigma^2+\sigma_{\rm data}^2},\quad c_{\rm out}=\frac{\sigma\sigma_{\rm data}}{\sqrt{\sigma^2+\sigma_{\rm data}^2}}.

cinyc_{\rm in}y has unit variance. Choose cskipc_{\rm skip} by minimizing Var⁡(x0−cy)\operatorname{Var}(x_0-cy): the derivative gives c=Cov⁡(x0,y)/Var⁡(y)c=\operatorname{Cov}(x_0,y)/\operatorname{Var}(y). Residual variance is cout2c_{\rm out}^2, so target (x0−cskipy)/cout(x_0-c_{\rm skip}y)/c_{\rm out} has unit variance for σ>0\sigma>0. This normalizes second moments, not proof that the target is Gaussian or all image correlations disappear. Weighting the MSE of DθD_\theta by 1/cout21/c_{\rm out}^2 equals normalized-target MSE, with the stated constants. See Karras and colleagues and their reference implementation.

InteractiveEDM preconditioning

Both axes use base-10 logarithms. The four curves represent different quantities and share the scale to compare their shapes.

Assume independent, centered x and ε with Var(x) = σ_data² and Var(ε) = 1. For y = x + σε, define D(y,σ) = c_skip y + c_out F(c_in y,σ), with c_skip = σ_data²/(σ² + σ_data²), c_out = σσ_data/√(σ² + σ_data²), c_in = 1/√(σ² + σ_data²), and λ = 1/c_out².

The input c_in y has variance 1.00000. The target F* = (x − c_skip y)/c_out has variance 1.00000 under the independence assumption. These are analytic identities. The plot excludes σ = 0 because c_out vanishes there and the weight is singular. See EDMPrecond and EDMLoss.

0.5
0.0
σ
1.0000
c_skip
0.2000
c_out
0.4472
c_in
0.8944
Weight λ
5.000
Target variance
1.00000
Change σ_data and follow the scales under the stated variance assumptions.

Distribute steps and apply Heun

The EDM sampler can place NN positive levels using

σi=(σmax⁡1/ρ+iN−1[σmin⁡1/ρ−σmax⁡1/ρ])ρ,i=0,…,N−1,\sigma_i= \left(\sigma_{\max}^{1/\rho}+ \frac{i}{N-1}\bigl[\sigma_{\min}^{1/\rho}-\sigma_{\max}^{1/\rho}\bigr]\right)^\rho, \quad i=0,\ldots,N-1,

and then append σN=0\sigma_N=0. Choice ρ\rho changes step distribution; there is no optimal value independent of model, endpoints and metric. The official implementation defaults to N=18N=18, σmin⁡=0,002\sigma_{\min}=0,002, σmax⁡=80\sigma_{\max}=80 and ρ=7\rho=7, subject to network limits. On that grid σ5≈12,91008238\sigma_5\approx12,91008238, counting from zero.

[ ]A point on the EDM gridBrowser
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}')
InteractiveWhere to place the steps

The upper row shows EDM spacing in log₁₀ σ. The lower row shows rescaled levels from a linear DDPM schedule.

EDMDDPM
-3-2-1012
log₁₀ σ
  • EDM: σ_min = 0.002, σ_max = 80
  • Linear DDPM, T = 1,000

A short m19-l18 trial measured ρ = 1, 3, 7 and 10 using Heun and EMA: 8 levels, 15 NFE, shared initial noise, and 8 generated and 8 real test images. The model received two updates. The range of σ/α in that run was [0.0100, 0.4736]. Features use clean-fid 0.1.35 InceptionV3W with bicubic preprocessing at 299 pixels. See heun-rho-fid.json for output and hashes, and sampler_lab.py for the code. Eight images give a 2,048-dimensional covariance estimate of rank at most 7 and a strongly biased FID. The values do not support a sampler ranking or comparison with the published experiment.

This chart shows published CIFAR-10 FID against NFE from a separate experiment.

EDM uses σᵢ = [σ_max^(1/ρ) + i(σ_min^(1/ρ) − σ_max^(1/ρ))/(N − 1)]^ρ, with zero-based i and adjustable ρ. The network determines its supported noise range. The final step to σ = 0 lies outside the logarithmic plot. For linear DDPM the display uses σ = √[(1 − ᾱ)/ᾱ] for the rescaled variable x/√ᾱ. The VP deviation is √(1 − ᾱ). The example uses uniformly spaced indices from a linear β schedule of 0.0001 to 0.02.

The FID chart reproduces DDIM Table 1 and Appendix D.2. That experiment uses a pretrained CIFAR-10 network and a quadratic subsequence with one evaluation per step. The authors report results for η = 0 and η = 1. The EDM level parameterization follows the official implementation.

7
Levels or published NFE
EDM σ at index 5
16.02230
Published FID, η = 0
6.84
Published FID, η = 1
18.36
Measured FID for ρ, 15 NFE
573.635
Compare grids and quality measurements with their stated provenance and budget.

For d(y,σ)=(y−Dθ(y,σ))/σd(y,\sigma)=(y-D_\theta(y,\sigma))/\sigma, an Euler step proposes y′=y+(σnext−σ)d(y,σ)y'=y+(\sigma_{\rm next}-\sigma)d(y,\sigma). Heun evaluates again at (y′,σnext)(y',\sigma_{\rm next}) and averages both slopes. In the final interval toward zero, the dd formula divides by σnext=0\sigma_{\rm next}=0: use the Euler proposal without that second evaluation. With NN intervals and no extra evaluations, the reference scheme costs 2N−12N-1 NFE.

The churn parameter can temporarily increase noise before a step and add Gaussian perturbation. In the reference code, γ=min⁡(Schurn/N,2−1)\gamma=\min(S_{\rm churn}/N,\sqrt2-1) when σ\sigma lies in the enabled interval, σ^=(1+γ)σ\hat\sigma=(1+\gamma)\sigma and noise with standard deviation σ^2−σ2 Snoise\sqrt{\hat\sigma^2-\sigma^2}\,S_{\rm noise} 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 at,bt>0a_t,b_t>0 and λ=log⁡(at/bt)\lambda=\log(a_t/b_t), half the log SNR, the formal solution between a noisy time ss and a less noisy one tt can be written

xt=atasxs−at∫λsλte−λϵθ(xλ,λ) dλ.x_t=\frac{a_t}{a_s}x_s -a_t\int_{\lambda_s}^{\lambda_t}e^{-\lambda} \epsilon_\theta(x_\lambda,\lambda)\,d\lambda.

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 x^0\hat x_0 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 and order on a mixtureBrowser
"""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

ProofA family of kernels
Prove: Prove that the DDIM kernel preserves the forward marginal conditioned on x₀.
0
Fix 0 < s < t, δ² between 0 and 1−ᾱₛ, and use independent fresh noise.

Step 1 of 3. What is the law of (xₜ − aₜx₀)/bₜ given x₀?

ProofNormalize input and target
Prove: Derive EDM preconditioning coefficients from second moments.
0
Let y = x₀ + σε, with centered x₀ of variance σ_data² > 0, independent standard normal ε and σ > 0.

Step 1 of 3. Which factor gives unit input variance?

NumericAn EDM schedule point
With N=18 positive levels, σ_max=80, σ_min=0.002, ρ=7 and indices starting at zero, calculate σ₅. Give four decimal places.
QuizHeun’s final interval
Why does the reference EDM sampler apply Euler to the final interval up to σ=0?
CodeHeun with churn and counter
Implement edm_sampler(denoiser,x,sigmas,S_churn,rng). sigmas is a strictly decreasing vector of at least two nonnegative values; all but the last are positive, and the last can be zero or positive. In each of N intervals use γ=min(S_churn/N, √2−1), σ_hat=(1+γ)σ and x_hat=x+√(σ_hat²−σ²)ξ; if γ=0 do not consume noise. Calculate d=(x_hat−denoiser(x_hat,σ_hat))/σ_hat, make the Euler proposal, and if σ_next>0 correct with Heun. Return (sample,NFE), without modifying x. Use rng.normal(size=x.shape); S_noise=1 and churn active in every interval.
import numpy as np

def edm_sampler(denoiser, x, sigmas, S_churn, rng):
  pass
Shift+Enter to run

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 β~\tilde\beta, a different choice from variance β\beta used in lesson 18. Methods share starting points and an index grid of the original schedule; Heun operates in rescaled variables y=x/αy=x/\alpha, r=σ/αr=\sigma/\alpha and uses a second evaluation except at the final step. The independent ρ\rho routine distributes the same eight or more levels in rr according to EDM’s rule and interpolates log⁡αˉ\log\bar\alpha 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 ϵ\epsilon or vv is supported and the checkpoint’s linear or cosine schedule is reconstructed. If it uses exactly zero terminal SNR, rescaling σ/α\sigma/\alpha is singular: start at the last finite level, T−1T-1, from an approximate normal. With any schedule, the initial normal is an approximate prior and the final prediction of x0x_0 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 ϵ\epsilon 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 ρ=1,3,7,10\rho=1,3,7,10 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 ρ=1\rho=1 and 33). 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.

[ ]DDIM, Heun and DPM-Solver++ with a CIFAR-10 EMALocal GPU
"""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()



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

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.