Module contents
Stage 4 of 9Advanced 100 min

Fast samplers: DDIM, Heun and higher-order solvers

Compare DDIM, Euler, Heun and a second-order exponential solver by numerical error, network evaluations and FID, then invert and interpolate with DDIM.

After this lesson you can

  • Derive DDIM and verify its relationship to DDPM and Euler.
  • Implement Euler and Heun with a configurable noise schedule.
  • Derive and compare a second-order exponential solver.
  • Compare FID versus network evaluations and use DDIM for inversion and interpolation.

Before you start

One thousand evaluations per image

The model from the previous lesson generates samples with ancestral sampling: one thousand reverse steps, each calling the U-Net. Generating the 10,000 images for FID-10k costs ten million image evaluations of the network. Changing the network is not the expensive part; using it so many times is. This lesson keeps the trained noise predictor and changes only the rule that uses it, reducing generation from a thousand evaluations to a few dozen.

The idea already appeared in the generative models module: sampling follows a probability-flow ODE, and generation integrates it from pure noise to data. Fast sampling is therefore an initial-value problem solved with a few large steps. Everything we know about Euler and Runge-Kutta applies: order, truncation error, and grid choice. One distinction from textbook numerical analysis is that cost is measured in network evaluations rather than steps.

Before the formulas, inspect the problem in the plane. The interactive uses the four-Gaussian mixture from the toy diffusion example, whose exact field is known, so numerical error can be separated from learning error. Every trajectory starts at (0.5,−0.4)(0.5,-0.4) at t=1t=1 and ends at t=0.002t=0.002. The dashed reference is the same ODE integrated by Heun with 1024 intervals.

InteractiveA reverse trajectory with few steps
x₁x₂
  • Trajectory of the selected method
  • Reference: Heun with 1024 intervals
  • Reference endpoint
  • Initial state at t = 1
Method
Score
Grid
12
100
Total NFE12
Displayed step12 of 12
Final error0.2512
Visible width1.84 units
Same initial state, field, and time interval. Only the integration rule and grid change. Error is endpoint distance, not a measure of sample quality.

With Euler and 12 intervals, the endpoint is 0.250.25 units from the reference; Heun with the same 12 intervals ends 0.0360.036 away but uses 24 evaluations. Select DDIM: the path is identical to Euler, and the next section proves why. Switch the grid to “Time”: the final jump moves from noise level 0.990.99 to 0.1270.127 in one step and the error grows. With the “Learned” score (the small network from p07-l01), the reference changes too because it solves a different ODE. The displayed distance still measures integration error only.

DDIM: another process with the same marginals

DDPM is trained on the marginal loss q(xt∣x0)=N(at x0,(1−at)I)q(x_t\mid x_0)=\mathcal N(\sqrt{a_t}\,x_0,(1-a_t)I), where at=αˉta_t=\bar\alpha_t. It uses the complete Markov chain only for sampling. Song, Meng and Ermon observed that any family of processes with those same marginals can use the same predictor, and constructed one that can skip times.

The square root is real: since as≤1a_s\leq1, we have 1−at/as≤1−at1-a_t/a_s\leq1-a_t, hence σt,s2≤η2(1−as)≤1−as\sigma_{t,s}^2\leq\eta^2(1-a_s)\leq1-a_s. The step has a simple interpretation. The process of Song and colleagues defines qσ(xs∣xt,x0)q_\sigma(x_s\mid x_t,x_0) as the Gaussian with mean asx0+1−as−σ2 (xt−atx0)/1−at\sqrt{a_s}x_0+\sqrt{1-a_s-\sigma^2}\,(x_t-\sqrt{a_t}x_0)/\sqrt{1-a_t} and covariance σ2I\sigma^2I. The sampler substitutes x0x_0 for x^0\hat x_0, making (xt−atx^0)/1−at(x_t-\sqrt{a_t}\hat x_0)/\sqrt{1-a_t} exactly εθ(xt,t)\varepsilon_\theta(x_t,t). Thus the step points to the position of x^0\hat x_0 at noise level ss and reuses the noise direction seen by the network.

The exercise asks for the key property: the process preserves the training marginals for any η\eta.

ProofPreserving the marginal
Prove: Let τ₁ < τ₂ < … < τ_S be a time grid with decreasing a. Consider the DDIM reverse process conditioned on the true x₀: x_{τ_S} ~ N(√a_{τ_S} x₀, (1−a_{τ_S})I). For consecutive s < t, let x_s = √a_s x₀ + √(1−a_s−σ²) (x_t − √a_t x₀)/√(1−a_t) + σz, where z is independent standard normal and σ² lies between 0 and 1−a_s. Prove that x_t follows N(√a_t x₀, (1−a_t)I) at every grid time.
0
Write ε = (x_t − √a_t x₀)/√(1−a_t) and assume as an induction hypothesis that x_t | x₀ ~ N(√a_t x₀, (1−a_t)I).

Step 1 of 4. Under the induction hypothesis, what is the law of ε given x₀?

What does each endpoint of η\eta recover? With η=1\eta=1, σt,s2\sigma_{t,s}^2 is the variance of the posterior q(xs∣xt,x0)q(x_s\mid x_t,x_0) of the original forward Markov process between ss and tt, whose transition is N(at/as xs,(1−at/as)I)\mathcal N(\sqrt{a_t/a_s}\,x_s,(1-a_t/a_s)I). If ss and tt are consecutive, 1−at/as=βt1-a_t/a_s=\beta_t and the step matches DDPM ancestral sampling with posterior variance. With skips, it is the ancestral step of a DDPM whose schedule is the subgrid. With η=0\eta=0, no noise is added: the step is deterministic, and all randomness is in xTx_T. This is deterministic DDIM sampling, which we will reinterpret as an ODE integrator. The cell checks the consecutive-step identity with two independently written formulas.

[ ]DDIM with η = 1 versus the DDPM posteriorBrowser
import numpy as np

def ddim_step(x, eps, at, previous, eta, z):
    if not (0 < at < previous <= 1 and 0 <= eta <= 1):
        raise ValueError("Orden de tiempos o eta no válido")
    variance=eta**2*(1-previous)/(1-at)*(1-at/previous)
    x0=(x-np.sqrt(1-at)*eps)/np.sqrt(at)
    return np.sqrt(previous)*x0+np.sqrt(max(0,1-previous-variance))*eps+np.sqrt(variance)*z

x=np.array([.4,-.7]); eps=np.array([.2,.8]); z=np.array([-.1,.3])
previous=.7
alpha_step=.98
at=previous*alpha_step
beta_step=1-alpha_step
posterior_variance=beta_step*(1-previous)/(1-at)
ancestral=(x-beta_step/np.sqrt(1-at)*eps)/np.sqrt(alpha_step)+np.sqrt(posterior_variance)*z
err=np.max(np.abs(ddim_step(x,eps,at,previous,1,z)-ancestral))
assert err < 1e-12
print("Error máximo DDIM eta=1 frente a posterior consecutiva:",err)

The ODE in noise coordinates

For the continuous VP process, dx=−12β(t)x dt+β(t) dW\mathrm{d}x=-\tfrac12\beta(t)x\,\mathrm{d}t+\sqrt{\beta(t)}\,\mathrm{d}W with a(t)=exp⁡(−∫0tβ)a(t)=\exp(-\int_0^t\beta), the probability-flow ODE of Song and colleagues is

dxdt=−12β(t)[x+∇xlog⁡pt(x)].\frac{\mathrm{d}x}{\mathrm{d}t}=-\tfrac12\beta(t)\bigl[x+\nabla_x\log p_t(x)\bigr].

Its solutions transport p1p_1 into ptp_t for every tt. They share marginals with the reverse SDE, while their trajectories differ. Integration uses decreasing tt, so increments are negative. Its form depends on the parameterization. A change of variables makes it almost trivial. Let y=x/ay=x/\sqrt a and define the noise-to-signal ratio s=(1−a)/as=\sqrt{(1-a)/a}, which falls from smax⁡s_{\max} to 00 as noise is removed. Using the Tweedie score, ∇log⁡pt(x)=−εˉ(x,t)/1−a\nabla\log p_t(x)=-\bar\varepsilon(x,t)/\sqrt{1-a}, where εˉ(x,t)=E[ε∣xt=x]\bar\varepsilon(x,t)=\mathbb E[\varepsilon\mid x_t=x] is learned by the noise predictor.

dadt=−βa  ⇒  ddt1a=β2a\frac{\mathrm{d}a}{\mathrm{d}t}=-\beta a\;\Rightarrow\;\frac{\mathrm{d}}{\mathrm{d}t}\frac{1}{\sqrt a}=\frac{\beta}{2\sqrt a}
Derivative of a(t) = exp(−∫β).
1/4

In coordinates (y,s)(y,s) the ODE has no linear part: its slope is only the predicted noise. Integrating the probability-flow ODE advances yy from s0=smax⁡s_0=s_{\max} to sn=smin⁡s_n=s_{\min} along a grid s0>s1>⋯>sns_0>s_1>\dots>s_n with steps hk=sk+1−sk<0h_k=s_{k+1}-s_k<0, evaluating the network at x=a(s) yx=\sqrt{a(s)}\,y. Euler uses yk+1=yk+hk εθ(xk,tk)y_{k+1}=y_k+h_k\,\varepsilon_\theta(x_k,t_k). This reveals why DDIM matched Euler in the interactive.

Proof

Divide the DDIM step with σ=0\sigma=0 by as\sqrt{a_s} and use x^0=yt−st εθ\hat x_0=y_t-s_t\,\varepsilon_\theta:

ys=xsas=x^0+1−asas εθ=yt−stεθ+ssεθ=yt+(ss−st) εθ(xt,t).y_s=\frac{x_s}{\sqrt{a_s}}=\hat x_0+\sqrt{\frac{1-a_s}{a_s}}\,\varepsilon_\theta=y_t-s_t\varepsilon_\theta+s_s\varepsilon_\theta=y_t+(s_s-s_t)\,\varepsilon_\theta(x_t,t).

This is the Euler step with h=ss−sth=s_s-s_t.

∎

The result is exact rather than asymptotic: both rules are the same function of xtx_t, so their trajectories coincide point by point. Euler has global error O(hmax⁡)O(h_{\max}) if the slope is Lipschitz in yy and sufficiently smooth in ss. Heun’s method (explicit trapezoid) predicts with Euler, evaluates the network again at the endpoint, and averages:

y~=yk+hk εθ(xk,tk),yk+1=yk+hk2[εθ(xk,tk)+εθ(ak+1 y~,tk+1)].\tilde y=y_k+h_k\,\varepsilon_\theta(x_k,t_k),\qquad y_{k+1}=y_k+\tfrac{h_k}{2}\bigl[\varepsilon_\theta(x_k,t_k)+\varepsilon_\theta(\sqrt{a_{k+1}}\,\tilde y,t_{k+1})\bigr].

Its local error is O(h3)O(h^3) and global error is O(hmax⁡2)O(h_{\max}^2) if the slope is C2C^2 in (y,s)(y,s) and Lipschitz in yy (as seen in Runge-Kutta). It costs two evaluations per interval. In the parameterization of Karras and colleagues, the slope is (x−D(x,σ))/σ(x-D(x,\sigma))/\sigma with a denoiser DD. It is singular at σ=0\sigma=0, so a grid ending at zero noise uses Euler for the last interval. Here the grids end at smin⁡>0s_{\min}>0 and Heun uses two evaluations in every interval.

[ ]The exact field and integratorsBrowser
import numpy as np
centers=np.array([[2.,0.],[-2.,0.],[0.,2.],[0.,-2.]])
tmin=.002
def a(t): return np.exp(-8*t)
def sigma(t): return np.sqrt((1-a(t))/a(t))
def time(s): return np.log1p(s*s)/8
def score(x,t):
    v=1-a(t)+.09*a(t)
    d=x[...,None,:]-np.sqrt(a(t))*centers
    logits=-(d*d).sum(axis=-1)/(2*v)
    w=np.exp(logits-logits.max(axis=-1,keepdims=True))
    w/=w.sum(axis=-1,keepdims=True)
    return -(w[...,None]*d).sum(axis=-2)/v
def epsilon(x,t): return -np.sqrt(1-a(t))*score(x,t)
def karras(n):
    return np.linspace(sigma(1)**(1/7),sigma(tmin)**(1/7),n+1)**7
def uniform_time(n):
    return sigma(np.linspace(1,tmin,n+1))
def integrate(method,n,x,grid="karras"):
    levels=karras(n) if grid=="karras" else uniform_time(n)
    x=np.array(x,dtype=float)
    path=[x.copy()]
    for s,q in zip(levels[:-1],levels[1:]):
        t,u=time(s),time(q)
        at,au=np.sqrt(a(t)),np.sqrt(a(u))
        e=epsilon(x,t)
        if method=="ddim":
            x=ddim_step(x,e,a(t),a(u),0,np.zeros_like(x))
        elif method=="dpm":
            h=np.log(s/q); m=np.sqrt(s*q); tm=time(m)
            mid=np.sqrt(a(tm))/at*x-np.sqrt(1-a(tm))*np.expm1(h/2)*e
            em=epsilon(mid,tm)
            x=au/at*x-np.sqrt(1-a(u))*np.expm1(h)*em
        else:
            y=x/at
            predicted=y+(q-s)*e
            if method=="heun":
                e2=epsilon(au*predicted,u)
                y=y+(q-s)*(e+e2)/2
            elif method=="euler":
                y=predicted
            else: raise ValueError("Método desconocido")
            x=au*y
        path.append(x.copy())
    return np.array(path)
initial=np.array([.5,-.4])
reference=integrate("heun",1024,initial)[-1]
for method in ("euler","heun","ddim","dpm"):
    end=integrate(method,12,initial)[-1]
    nfe=12*(2 if method in ("heun","dpm") else 1)
    print(method,"NFE",nfe,"extremo",np.round(end,6),
          "distancia a Heun refinado",np.linalg.norm(end-reference))

Euler and DDIM give the same endpoint up to rounding, as predicted by the theorem. The mixture is from p07-l01: four centers on the axes, component variance 0.09, a(t)=e−8ta(t)=e^{-8t}, so β=8\beta=8 is constant, smax⁡=e8−1≈54.6s_{\max}=\sqrt{e^8-1}\approx54.6 and smin⁡=e0.016−1≈0.127s_{\min}=\sqrt{e^{0.016}-1}\approx0.127. Error is measured against a numerical reference for the same equation, not against a data point. A single trajectory can improve with fewer steps through accidental error cancellation, so the next section averages over many initial states.

Where to place the steps

With a fixed interval budget, the question is where to place them. Uniform spacing in tt appears neutral but is not: the field εθ\varepsilon_\theta changes slowly at high noise, where everything is nearly Gaussian, and quickly at low noise, where details appear and the mixture separates into components. Karras and colleagues propose levels uniform in s1/ρs^{1/\rho}:

si=(smax⁡1/ρ+in(smin⁡1/ρ−smax⁡1/ρ))ρ,i=0,…,n,s_i=\Bigl(s_{\max}^{1/\rho}+\tfrac{i}{n}\bigl(s_{\min}^{1/\rho}-s_{\max}^{1/\rho}\bigr)\Bigr)^{\rho},\qquad i=0,\dots,n,

with ρ=7\rho=7 in their paper. For ρ→∞\rho\to\infty the grid approaches a geometric grid (uniform in log⁡s\log s); with ρ=1\rho=1 it is uniform in ss. In the 12-interval example, the last Karras jump goes from s=0.272s=0.272 to 0.1270.127 (ratio 2.1), while the grid uniform in tt jumps from 0.9880.988 to 0.1270.127 (ratio 7.8), precisely where the field bends most.

Numeric
With s_max = 54.589, s_min = 0.12700, ρ = 7 and n = 12 intervals, what is the penultimate Karras grid level s₁₁? Give three significant figures.

The next interactive compares error with cost. For 32 fixed initial states xT∼N(0,I)x_T\sim\mathcal N(0,I), integrate each method with several interval counts and plot mean endpoint error against NFE on log-log axes. A straight line with slope −p-p means error ∝NFE−p\propto\mathrm{NFE}^{-p}: the empirically measured method order, as in empirical order verification.

InteractiveError versus network evaluations
  • Euler = DDIM (1 NFE per interval)
  • Heun (2 NFE per interval)
  • DPM-Solver-2 (2 NFE per interval)
Grid
Score
24
Best at this budgetDPM-2, 24 NFE
Mean error of the best method0.0268
Slope Euler/DDIM−1.02
Slope Heun−2.05
Slope DPM-2−2.02
Mean error over 32 initial states relative to Heun with 1024 intervals on the same grid. Slopes are fit to the four highest-NFE points. The vertical line marks the chosen budget.

On the Karras grid, Euler’s slope is close to −1-1 and those of Heun and DPM-Solver-2 are close to −2-2: theoretical order appears once steps are small. Set the budget to 8 NFE, however, and Heun with 4 intervals loses to Euler with 8. A high-order method recovers the cost of its second evaluation once its step size enters the asymptotic regime. Switch to a grid uniform in tt: at the same NFE errors are several times larger and slopes stabilize much later. The cell reproduces the table with another seed.

[ ]Mean error and empirical orderBrowser
starts=np.random.default_rng(0).standard_normal((32,2))
counts=(4,8,16,32,64,128)
for grid in ("karras","time"):
    ref=integrate("heun",1024,starts,grid)[-1]
    for method in ("euler","heun","dpm"):
        cost=2 if method!="euler" else 1
        errors=np.array([np.linalg.norm(integrate(method,n,starts,grid)[-1]-ref,axis=1).mean() for n in counts])
        nfe=cost*np.array(counts)
        order=-np.polyfit(np.log(nfe[-3:]),np.log(errors[-3:]),1)[0]
        print(f"{grid:6s} {method:5s}","NFE",[int(v) for v in nfe],"error",[f"{e:.2g}" for e in errors],f"orden {order:.2f}")

Second-order exponential solvers

In variable xx, the VP ODE has a linear part −12βx-\tfrac12\beta x with an exact solution given by a scale factor. Direct Euler integration in xx discretizes this part and introduces error where the solution is already known. Exponential solvers, including DPM-Solver by Lu and colleagues, integrate that part exactly by variation of constants and approximate only the predictor integral. Use α=a\alpha=\sqrt a, σVP=1−a\sigma_{\rm VP}=\sqrt{1-a}, and the half-log SNR λ=log⁡(α/σVP)=−log⁡s\lambda=\log(\alpha/\sigma_{\rm VP})=-\log s. The exact solution between tt and u<tu<t is

xu=αuαtxt−αu∫λtλue−λ εˉ(xλ,λ) dλ.x_u=\frac{\alpha_u}{\alpha_t}x_t-\alpha_u\int_{\lambda_t}^{\lambda_u}e^{-\lambda}\,\bar\varepsilon(x_\lambda,\lambda)\,\mathrm{d}\lambda.

No additional derivation is needed: this is the ODE in (y,s)(y,s) written in terms of s=e−λs=e^{-\lambda}, because ds=−e−λdλ\mathrm{d}s=-e^{-\lambda}\mathrm{d}\lambda and yu=yt+∫stsuεˉ dsy_u=y_t+\int_{s_t}^{s_u}\bar\varepsilon\,\mathrm{d}s. Multiply by αu\alpha_u. Freezing εˉ\bar\varepsilon at its initial value makes the integral αue−λu(eh−1)ε=σuexpm1⁡(h) ε\alpha_u e^{-\lambda_u}(e^{h}-1)\varepsilon=\sigma_u\operatorname{expm1}(h)\,\varepsilon with h=λu−λt>0h=\lambda_u-\lambda_t>0. This is DPM-Solver-1 and, by the preceding theorem, it is again DDIM: Euler in (y,s)(y,s), deterministic DDIM, and the first-order exponential solver are the same method.

The second-order solver evaluates the predictor at the midpoint in λ\lambda, λm=λt+h/2\lambda_m=\lambda_t+h/2, that is, at the geometric mean sm=stsus_m=\sqrt{s_ts_u}:

xm=αmαtxt−σmexpm1⁡(h/2) εθ(xt,t),xu=αuαtxt−σuexpm1⁡(h) εθ(xm,m).x_m=\frac{\alpha_m}{\alpha_t}x_t-\sigma_m\operatorname{expm1}(h/2)\,\varepsilon_\theta(x_t,t), \qquad x_u=\frac{\alpha_u}{\alpha_t}x_t-\sigma_u\operatorname{expm1}(h)\,\varepsilon_\theta(x_m,m).

Here σm\sigma_m is the VP deviation at λm\lambda_m, not the ratio ss. Dividing by α\alpha reveals the structure: ym=yt+(sm−st)εθ(xt,t)y_m=y_t+(s_m-s_t)\varepsilon_\theta(x_t,t) is Euler to the midpoint, and yu=yt+(su−st) εθ(xm,m)y_u=y_t+(s_u-s_t)\,\varepsilon_\theta(x_m,m) is the midpoint method with a geometric node.

Proof

In (y,s)(y,s) the step is yk+1=yk+h f(yk+chfk, sk+ch)y_{k+1}=y_k+h\,f(y_k+chf_k,\,s_k+ch) with ch=sm−skch=s_m-s_k. By Taylor expansion, the exact solution satisfies y(sk+h)=yk+hf+h22(fs+fyf)+O(h3)y(s_k+h)=y_k+hf+\tfrac{h^2}{2}(f_s+f_yf)+O(h^3) and the step gives yk+hf+ch2(fs+fyf)+O(h3)y_k+hf+ch^2(f_s+f_yf)+O(h^3). With r=sk+1/sk=1+h/skr=s_{k+1}/s_k=1+h/s_k, c=(r−1)/(r−1)=1/(r+1)=12−h8sk+O(h2)c=(\sqrt r-1)/(r-1)=1/(\sqrt r+1)=\tfrac12-\tfrac{h}{8s_k}+O(h^2), hence (c−12)h2=O(h3/smin⁡)(c-\tfrac12)h^2=O(h^3/s_{\min}) and local error O(h3)O(h^3). Lipschitz continuity propagates local errors with a bounded factor, giving global error O(hmax⁡2)O(h_{\max}^2), as for any consistent second-order one-step method.

∎

Lu and colleagues prove the analogous result for DPM-Solver-kk in λ\lambda under similar regularity assumptions. The constant grows when smin⁡→0s_{\min}\to0, and λ\lambda diverges at zero noise, so these methods stop at positive noise. An image network trained only at integer indices requires a choice of schedule interpolation and network time. Rounding indices makes the field discontinuous and breaks the C2C^2 assumption.

Counting work and measuring quality

The NFE–quality trade-off is the curve relating the number of predictor evaluations per sample (NFE, number of function evaluations) to a quality metric under a fixed protocol. NFE counts calls per sample: one vectorized call on a batch of 32 images makes 32 image evaluations but only one NFE for each. Heun and DPM-Solver-2 cost two per interval; Euler and DDIM cost one. Wall-clock time also depends on batch size, precision, and device. Equal NFE need not mean equal time, though it is a useful proxy when the network dominates cost.

Numeric
A grid has 18 times including both endpoints. Heun uses two evaluations per interval except the last, which uses Euler only. How many network evaluations are made?

The Karras convention counts differently: 18 positive levels followed by zero give 18 intervals and 2⋅17+1=352\cdot17+1=35 NFE, the well-known 35 evaluations in their paper. This does not contradict the exercise, whose 18 times include both endpoints. The grid is named differently, so always state the convention.

Quiz
A report compares Euler with 25 intervals and Heun with 25 intervals on the same network, observes a lower FID for Heun, and concludes that Heun is better at the same budget. What is wrong?

What curve should we expect with images? Published numbers are guidance, not a target, because the model, sample count, and protocol differ. In Table 1 of Song, Meng and Ermon, on CIFAR-10 with the same model trained using the DDPM objective and a quadratic subgrid, DDIM with η=0\eta=0 achieves FID 13.36, 6.84, 4.67 and 4.16 at 10, 20, 50 and 100 steps, while η=1\eta=1 achieves 41.07, 18.36, 8.01 and 5.78. At 1000 steps the order reverses: η=0\eta=0 reaches 4.04 and ancestral sampling with larger variance (σ^\hat\sigma) reaches 3.17. The DPM-Solver abstract reports FID 4.70 at 10 evaluations and 2.87 at 20 on CIFAR-10 with a continuous-time model. Karras and colleagues reach unconditional FID 1.97 with 35 evaluations using Heun, their grid, and models retrained under their parameterization. With the p07-l03 U-Net and FID-10k (biased upward compared with 50,000 samples), absolute values differ. The expected pattern is deterministic DDIM well ahead of ancestral sampling at few evaluations, Heun and DPM-Solver-2 ahead of DDIM at a few dozen NFE, and their advantage shrinking or reversing below about 10 NFE.

Inversion and interpolation

With η=0\eta=0, sampling deterministically maps noise to an image. It can be approximately reversed to encode an image as noise by integrating the same ODE with increasing ss. The forward and reverse passes evaluate the network at different states, so the discrete maps are not exact inverses at finite step counts, even though the continuous ODE is reversible. Quantization, pixel clipping, and network error add discrepancies. The p07-l03 U-Net was trained at indices 1 through 1000; evaluating index 0 extrapolates, so inversion starts at index 1. The DDIM paper studies reconstruction and interpolation in Section 5.

Linear interpolation between two independent noises z1,z2∼N(0,Id)z_1,z_2\sim\mathcal N(0,I_d) fails in a specific way. The midpoint (z1+z2)/2(z_1+z_2)/2 follows N(0,12Id)\mathcal N(0,\tfrac12I_d), and a high-dimensional Gaussian norm concentrates: ∥z∥≈d\lVert z\rVert\approx\sqrt d with fluctuations of order one. For CIFAR-10, d=3072d=3072: endpoint norms are near 55.455.4 and the midpoint near 39.239.2, a region where the network has almost never seen xTx_T. Spherical interpolation follows the arc between directions. For unit vectors u,vu,v at angle 0<θ<π0<\theta<\pi,

slerp⁡(u,v,r)=sin⁡((1−r)θ)sin⁡θ u+sin⁡(rθ)sin⁡θ v,\operatorname{slerp}(u,v,r)=\frac{\sin((1-r)\theta)}{\sin\theta}\,u+\frac{\sin(r\theta)}{\sin\theta}\,v,

which has unit norm for every rr. The implementation interpolates endpoint norms separately and rejects antipodal endpoints, for which there are infinitely many arcs. For nearly parallel endpoints it normalizes the linearly interpolated directions to avoid division by a small sine. This does not guarantee that intermediate points follow an exact normal distribution, only that their norms remain in the typical region. The appearance of an interpolation does not measure fidelity or coverage.

[ ]Inversion and interpolation in 2DBrowser
def invert_toy(x,n):
    levels=karras(n)[::-1]
    x=np.array(x,dtype=float,copy=True)
    for s,q in zip(levels[:-1],levels[1:]):
        t,u=time(s),time(q)
        e=epsilon(x,t)
        x0=(x-np.sqrt(1-a(t))*e)/np.sqrt(a(t))
        x=np.sqrt(a(u))*x0+np.sqrt(1-a(u))*e
    return x
def slerp(x,y,r):
    x=np.asarray(x,dtype=float); y=np.asarray(y,dtype=float)
    if not 0<=r<=1: raise ValueError("r fuera de [0,1]")
    nx,ny=np.linalg.norm(x),np.linalg.norm(y)
    if nx==0 or ny==0: raise ValueError("Dirección de norma cero")
    u,v=x/nx,y/ny
    cosine=float(np.clip(np.dot(u,v),-1,1))
    if cosine < -1+1e-8: raise ValueError("Arco antipodal ambiguo")
    if cosine > 1-1e-8:
        direction=(1-r)*u+r*v
        direction/=np.linalg.norm(direction)
    else:
        theta=np.arccos(cosine)
        direction=(np.sin((1-r)*theta)*u+np.sin(r*theta)*v)/np.sin(theta)
    return ((1-r)*nx+r*ny)*direction

original=np.array([1.5,.2])
for n in (12,24,96):
    encoded=invert_toy(original,n)
    reconstructed=integrate("ddim",n,encoded)[-1]
    print("ida y vuelta 2D, intervalos",n,"error",np.linalg.norm(reconstructed-original))
middle=slerp([1.,0.],[0.,1.],.5)
assert np.allclose(middle,[2**-.5,2**-.5])
print("Slerp de dos extremos de norma 1, punto medio:",middle,"norma",np.linalg.norm(middle))
try:
    slerp([1.,0.],[-1.,0.],.5)
except ValueError:
    print("Antipodales: arco ambiguo, rechazado")
z=np.random.default_rng(1).standard_normal((2,3072))
print("Normas de dos ruidos de CIFAR:",np.round(np.linalg.norm(z,axis=1),1),
      "punto medio lineal:",round(float(np.linalg.norm(z.mean(0))),1),
      "slerp:",round(float(np.linalg.norm(slerp(z[0],z[1],.5))),1))

Even with the exact score, the round trip has appreciable error with 12 intervals and improves as the grid is refined. The discrete map evaluates the field at the start of each interval and is not undone by traversing the grid in reverse.

Quiz
Why can reconstruction fail when inverting and returning with deterministic DDIM and few steps?

Lab: the sampler library

Now repeat the experiment with tensors and the U-Net. The lab has four parts: the sampler library, the p07-l03 definitions needed to load your checkpoint, a short check that generates image grids with each method, and the FID-10k sweep that plots the curve. The cells run locally (PyTorch with CUDA), and each Oryon Learn page opens its own kernel, so this lesson includes everything it uses.

The library receives a callable predict(x,t) that predicts noise and the cumulative schedule αˉ\bar\alpha indexed from 0 to TT. It linearly interpolates log⁡αˉ\log\bar\alpha between integer indices and passes real-valued times to the network. The U-Net accepts them through its sinusoidal embedding although it was trained with integers, so interpolation is an experimental choice. Methods stop at index 1, still slightly noisy, without an extra evaluation. The final estimate of x^0\hat x_0 is added outside using the same rule for all. The final check uses a zero predictor on CPU to check shapes, NFE, and the DDIM–Euler identity.

[ ]PyTorch samplers for a predictorLocal GPU
import math
import numpy as np
import torch

def coefficients(t, abar):
    t=float(t)
    if not 1 <= t <= len(abar)-1:
        raise ValueError("El índice continuo debe estar entre 1 y T")
    lo=int(math.floor(t))
    hi=min(lo+1,len(abar)-1)
    loga=(1-(t-lo))*math.log(float(abar[lo]))+(t-lo)*math.log(float(abar[hi]))
    alpha=math.exp(loga/2)
    vp=math.sqrt(-math.expm1(loga))
    return alpha,vp

def time_from_ratio(s, abar):
    logs=-np.log(np.asarray(abar,dtype=np.float64))
    target=math.log1p(s*s)
    if target < logs[1]-1e-12 or target > logs[-1]+1e-12:
        raise ValueError("Ruido fuera del calendario entrenado")
    target=float(np.clip(target,logs[1],logs[-1]))
    right=int(np.searchsorted(logs,target))
    if right<=1: return 1.
    if right>=len(logs): return float(len(abar)-1)
    left=right-1
    return left+(target-logs[left])/(logs[right]-logs[left])

def image_grid_times(abar, intervals, grid):
    if intervals<1: raise ValueError("Se requiere al menos un intervalo")
    if grid=="time": return np.linspace(len(abar)-1,1,intervals+1)
    if grid!="karras": raise ValueError("Malla desconocida")
    a0,v0=coefficients(len(abar)-1,abar)
    a1,v1=coefficients(1,abar)
    sigmas=np.linspace((v0/a0)**(1/7),(v1/a1)**(1/7),intervals+1)**7
    sigmas[0]=v0/a0
    sigmas[-1]=v1/a1
    return np.array([time_from_ratio(float(s),abar) for s in sigmas])

@torch.inference_mode()
def sample_images(predict, x_initial, abar, method, intervals, grid="karras",
                  eta=0., generator=None):
    if method not in ("ddim","euler","heun","dpm"):
        raise ValueError("Método desconocido")
    if not 0 <= eta <= 1 or (method!="ddim" and eta!=0):
        raise ValueError("Eta solo se usa con DDIM")
    if eta and generator is None:
        raise ValueError("DDIM estocástico requiere generador explícito")
    times=image_grid_times(abar,intervals,grid)
    x=x_initial.clone().float()
    nfe=0
    def call(x,t):
        nonlocal nfe
        nfe+=1
        return predict(x,torch.full((len(x),),t,device=x.device,dtype=torch.float32)).float()
    for t,u in zip(times[:-1],times[1:]):
        al,sv=coefficients(t,abar)
        au,su=coefficients(u,abar)
        s,q=sv/al,su/au
        e=call(x,t)
        if method=="ddim":
            variance=eta**2*(su*su)/(sv*sv)*(1-(al*al)/(au*au))
            x0=(x-sv*e)/al
            x=au*x0+math.sqrt(max(0,su*su-variance))*e
            if eta:
                z=torch.randn(x.shape,device=x.device,dtype=x.dtype,generator=generator)
                x=x+math.sqrt(variance)*z
        elif method=="dpm":
            h=math.log(s/q)
            mid=time_from_ratio(math.sqrt(s*q),abar)
            am,sm=coefficients(mid,abar)
            xm=(am/al)*x-sm*math.expm1(h/2)*e
            em=call(xm,mid)
            x=(au/al)*x-su*math.expm1(h)*em
        else:
            y=x/al
            predicted=y+(q-s)*e
            if method=="heun":
                e2=call(au*predicted,u)
                y=y+(q-s)*(e+e2)/2
            else:
                y=predicted
            x=au*y
    return x,nfe

beta=torch.linspace(1e-4,.02,1000,dtype=torch.float64)
abar=torch.cat((torch.ones(1,dtype=torch.float64),torch.cumprod(1-beta,0)))
initial=torch.ones(2,3,4,4)
zero=lambda x,t: torch.zeros_like(x)
out={}
for method in ("ddim","euler","heun","dpm"):
    result,nfe=sample_images(zero,initial,abar,method,4)
    assert result.shape==initial.shape and torch.isfinite(result).all()
    assert nfe==(8 if method in ("heun","dpm") else 4)
    out[method]=result
assert torch.allclose(out["ddim"],out["euler"],atol=1e-4)
print("Control CPU con predictor cero: formas finitas; NFE 4, 4, 8 y 8.")
print("DDIM determinista y Euler coinciden:",torch.allclose(out["ddim"],out["euler"],atol=1e-4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Inversion applies the deterministic formula at increasing times from index 1. Passing a clean image as that state introduces another approximation. The function makes it explicit so the caller can decide how to produce the initial state and measure reconstruction against the same input. To interpolate images, slerp_tensor flattens the coordinates, preserves endpoint norms, and rejects antipodal endpoints.

[ ]Tensor inversion and interpolationLocal GPU
@torch.inference_mode()
def invert_image(predict,x_start,abar,intervals,grid="karras"):
    times=image_grid_times(abar,intervals,grid)[::-1]
    x=x_start.clone().float()
    for t,u in zip(times[:-1],times[1:]):
        al,sv=coefficients(t,abar)
        au,su=coefficients(u,abar)
        e=predict(x,torch.full((len(x),),t,device=x.device,dtype=torch.float32)).float()
        x0=(x-sv*e)/al
        x=au*x0+su*e
    return x,len(times)-1

def slerp_tensor(x,y,r):
    if x.shape!=y.shape or not 0<=r<=1: raise ValueError("Forma o proporción inválida")
    x=x.float(); y=y.float()
    nx=torch.linalg.vector_norm(x); ny=torch.linalg.vector_norm(y)
    if nx.item()==0 or ny.item()==0: raise ValueError("Dirección de norma cero")
    u,v=x/nx,y/ny
    c=torch.clamp(torch.sum(u*v),-1,1)
    if c.item() < -1+1e-8: raise ValueError("Arco antipodal ambiguo")
    if c.item() > 1-1e-8:
        direction=(1-r)*u+r*v
        direction=direction/torch.linalg.vector_norm(direction)
    else:
        angle=torch.acos(c)
        direction=(torch.sin((1-r)*angle)*u+torch.sin(r*angle)*v)/torch.sin(angle)
    return ((1-r)*nx+r*ny)*direction

toy=torch.tensor([[[[1.,0.],[0.,1.]]]])
encoded,n1=invert_image(zero,toy,abar,4)
decoded,n2=sample_images(zero,encoded,abar,"ddim",4)
assert torch.allclose(toy,decoded,atol=1e-5)
mid=slerp_tensor(torch.tensor([1.,0.]),torch.tensor([0.,1.]),.5)
assert torch.allclose(torch.linalg.vector_norm(mid),torch.tensor(1.))
print("Control con predictor cero: inversión y vuelta, NFE",n1,n2,
      "error máximo",float((decoded-toy).abs().max()))
print("Slerp tensor, norma del punto medio",float(torch.linalg.vector_norm(mid)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With a zero predictor the round trip is exact because the field does not depend on state. With the U-Net it will not be exact, and measuring error at 10, 50, and 200 intervals is a useful experiment for your images.

The pieces from p07-l03

Loading your checkpoint requires the architecture, schedule, ancestral step, and FID evaluation from p07-l03. The next cell copies them unchanged. If you changed the U-Net in that lesson, repeat the change here: load_state_dict(..., strict=True) fails clearly when the definitions disagree.

[ ]Definitions reused from p07-l03Local GPU
import io, json, pathlib, hashlib, base64
import torch.nn.functional as F
from torch import nn
from PIL import Image

def time_embedding(t,dim):
    half=dim//2
    scales=torch.exp(-math.log(10000)*torch.arange(half,device=t.device,dtype=torch.float32)/(half-1))
    phase=t.float()[:,None]*scales[None,:]
    return torch.cat((phase.sin(),phase.cos()),dim=1)

class Residual(nn.Module):
    def __init__(self,cin,cout,tdim):
        super().__init__()
        self.n1=nn.GroupNorm(32,cin)
        self.c1=nn.Conv2d(cin,cout,3,padding=1)
        self.time=nn.Linear(tdim,cout)
        self.n2=nn.GroupNorm(32,cout)
        self.c2=nn.Conv2d(cout,cout,3,padding=1)
        self.skip=nn.Identity() if cin==cout else nn.Conv2d(cin,cout,1)
    def forward(self,x,t):
        h=self.c1(F.silu(self.n1(x)))
        h=h+self.time(F.silu(t))[:,:,None,None]
        return self.skip(x)+self.c2(F.silu(self.n2(h)))

class Attention(nn.Module):
    def __init__(self,channels,heads=4):
        super().__init__()
        assert channels%heads==0
        self.heads=heads
        self.norm=nn.GroupNorm(32,channels)
        self.qkv=nn.Conv2d(channels,3*channels,1)
        self.out=nn.Conv2d(channels,channels,1)
    def forward(self,x):
        b,c,h,w=x.shape
        q,k,v=self.qkv(self.norm(x)).reshape(b,3,self.heads,c//self.heads,h*w).unbind(1)
        q,k,v=(z.transpose(-1,-2) for z in (q,k,v))
        h1=F.scaled_dot_product_attention(q,k,v).transpose(-1,-2).reshape(b,c,h,w)
        return x+self.out(h1)

class DiffusionUNet(nn.Module):
    def __init__(self,width=224):
        super().__init__()
        a,b,c=width,2*width,3*width
        self.width=width
        self.temb=nn.Sequential(nn.Linear(width,4*width),nn.SiLU(),nn.Linear(4*width,4*width))
        self.stem=nn.Conv2d(3,a,3,padding=1)
        self.down0=Residual(a,a,4*width)
        self.reduce0=nn.Conv2d(a,a,3,stride=2,padding=1)
        self.down1=Residual(a,b,4*width)
        self.attn_down=Attention(b)
        self.reduce1=nn.Conv2d(b,b,3,stride=2,padding=1)
        self.down2=Residual(b,c,4*width)
        self.mid=Residual(c,c,4*width)
        self.up1=Residual(c+b,b,4*width)
        self.attn_up=Attention(b)
        self.up0=Residual(b+a,a,4*width)
        self.final=nn.Sequential(nn.GroupNorm(32,a),nn.SiLU(),nn.Conv2d(a,3,3,padding=1))
    def forward(self,x,t):
        if x.ndim!=4 or x.shape[1:]!=(3,32,32) or t.shape!=(x.shape[0],):
            raise ValueError("Se esperan imágenes (B,3,32,32) y tiempos (B,)")
        t=self.temb(time_embedding(t,self.width))
        h0=self.down0(self.stem(x),t)
        h1=self.attn_down(self.down1(self.reduce0(h0),t))
        h2=self.mid(self.down2(self.reduce1(h1),t),t)
        up=F.interpolate(h2,scale_factor=2,mode="nearest")
        up=self.attn_up(self.up1(torch.cat((up,h1),dim=1),t))
        up=F.interpolate(up,scale_factor=2,mode="nearest")
        return self.final(self.up0(torch.cat((up,h0),dim=1),t))

def make_schedule(kind,steps=1000,device="cpu"):
    if kind=="linear":
        beta=torch.linspace(1e-4,.02,steps,dtype=torch.float64,device=device)
    elif kind=="cosine":
        t=torch.linspace(0,1,steps+1,dtype=torch.float64,device=device)
        desired=torch.cos(((t+.008)/(1+.008))*math.pi/2).square()
        desired=desired/desired[0]
        beta=(1-desired[1:]/desired[:-1]).clamp(max=.999)
    else:
        raise ValueError("Calendario desconocido")
    if not bool(((beta>0)&(beta<1)).all()):
        raise ValueError("Beta fuera de (0,1)")
    a=1-beta
    abar=torch.cat((torch.ones(1,device=device,dtype=torch.float64),torch.cumprod(a,dim=0)))
    return beta.float(),a.float(),abar.float()

def ancestral_step(x,t,eps,beta,alpha,abar,variance,generator):
    if not 1<=t<=len(beta) or variance not in ("posterior","beta"):
        raise ValueError("Paso o varianza inválidos")
    b=beta[t-1]
    mean=(x-b*eps/torch.sqrt(1-abar[t]))/torch.sqrt(alpha[t-1])
    if t==1:
        return mean
    var=b*(1-abar[t-1])/(1-abar[t]) if variance=="posterior" else b
    z=torch.randn(x.shape,device=x.device,dtype=x.dtype,generator=generator)
    return mean+torch.sqrt(var)*z

def file_sha(path):
    with open(path,"rb") as f:
        return hashlib.file_digest(f,"sha256").hexdigest()

def load_fid_reference(path,device):
    from cleanfid.inception_torchscript import InceptionV3W
    from cleanfid.resize import build_resizer
    path=pathlib.Path(path)
    record=json.loads((path/"fid_results.json").read_text(encoding="utf-8"))
    if record["protocol"]!="cifar10-train-bootstrap-clean-fid-0.1.35":
        raise ValueError("Protocolo de referencia incompatible")
    if file_sha(path/"inception-2015-12-05.pt")!=record["extractor_sha256"]:
        raise ValueError("Huella del extractor distinta")
    if file_sha(path/"train_features.npy")!=record["train_sha256"]:
        raise ValueError("Huella de características train distinta")
    stats=np.load(path/"cifar10_reference.npz")
    if str(stats["train_sha256"])!=record["train_sha256"]:
        raise ValueError("La referencia no corresponde a las características")
    features=np.load(path/"train_features.npy",mmap_mode="r")
    if features.shape!=(50000,2048):
        raise ValueError("Forma de referencia inesperada")
    mean=torch.zeros(2048,device=device,dtype=torch.float64)
    for start in range(0,len(features),4096):
        chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)
        mean+=chunk.sum(0)
    mean/=len(features)
    cov=torch.zeros((2048,2048),device=device,dtype=torch.float64)
    for start in range(0,len(features),4096):
        chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)-mean
        cov+=chunk.T@chunk
    cov/=len(features)-1
    if not np.allclose(mean.cpu().numpy(),stats["mean_train"],rtol=1e-7,atol=1e-7):
        raise ValueError("Media de referencia no coincide")
    if not np.allclose(cov.cpu().numpy(),stats["cov_train"],rtol=1e-7,atol=1e-7):
        raise ValueError("Covarianza de referencia no coincide")
    del chunk,features
    extractor=InceptionV3W(str(path),download=False).eval().to(device)
    return mean,cov,extractor,build_resizer("clean"),record

def feature_fid(samples,mean,cov):
    z=torch.as_tensor(samples,device=mean.device,dtype=torch.float64)
    m=z.mean(0); centered=z-m
    c=centered.T@centered/(len(z)-1)
    def eig(x):
        values,vectors=torch.linalg.eigh((x+x.T)/2)
        scale=max(1.,float(values.abs().max()))
        if float(values.min()) < -1e-8*scale:
            raise ValueError("Covarianza no positiva")
        return values.clamp_min(0),vectors
    values,vectors=eig(c)
    root=(vectors*values.sqrt())@vectors.T
    middle,_=eig(root@cov@root)
    result=float((m-mean).square().sum()+torch.trace(c)+torch.trace(cov)-2*middle.sqrt().sum())
    if result < -1e-7*max(1.,float(torch.trace(c)+torch.trace(cov))):
        raise ArithmeticError("FID negativo fuera de tolerancia")
    return max(0.,result)

def image_grid(pixels):
    canvas=Image.new("RGB",(128,128))
    for i,image in enumerate(pixels[:16]):
        canvas.paste(Image.fromarray(image),(32*(i%4),32*(i//4)))
    stream=io.BytesIO()
    canvas.save(stream,format="PNG")
    return "data:image/png;base64,"+base64.b64encode(stream.getvalue()).decode("ascii")

check=feature_fid(np.array([[-1.,0.],[1.,0.]]),torch.zeros(2,dtype=torch.float64),torch.eye(2,dtype=torch.float64))
assert np.isclose(check,4-2*np.sqrt(2),atol=1e-10)
print("Definiciones de p07-l03 cargadas; FID de control:",check)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

A short check with your checkpoint

Before generating ten thousand images per point, check the entire pipeline on a few. The cell loads the EMA of any p07-l03 checkpoint, including the smoke mode checkpoint, generates 16 images per method from the same starting noise, and saves one PNG grid per method to a directory you choose. Set P07_L04_QUICK_CHECKPOINT to the checkpoint path and P07_L04_QUICK_OUT to your directory. P07_L04_QUICK_INTERVALS changes the number of intervals (10 by default). It works on CPU, though slowly.

What to expect: with a smoke checkpoint (20 updates), the grids show unstructured patches and establish only that the pipeline works. With the checkpoint selected from the full training run, the four grids show approximately the same compositions because the initial noise is shared and the three deterministic methods integrate the same ODE. DDIM and Euler should agree except for rounding by a few grayscale levels. The cell prints the maximum difference, which was 4 out of 255 in a short verification with an untrained U-Net. Heun and DPM-Solver-2 with 10 intervals use 21 NFE versus 11; to compare equal cost, repeat DDIM with P07_L04_QUICK_INTERVALS=20.

[ ]Sample grids with few stepsLocal GPU
import os

def save_grid(pixels, path):
    side=int(np.ceil(np.sqrt(len(pixels))))
    canvas=Image.new("RGB",(32*side,32*side))
    for i,image in enumerate(pixels):
        canvas.paste(Image.fromarray(image),(32*(i%side),32*(i//side)))
    canvas.save(path)

@torch.inference_mode()
def quick_check(checkpoint, out_dir, intervals=10, count=16, seed=0):
    checkpoint,out_dir=pathlib.Path(checkpoint),pathlib.Path(out_dir)
    out_dir.mkdir(parents=True,exist_ok=True)
    device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
    saved=torch.load(checkpoint,map_location="cpu",weights_only=True)
    cfg=saved["config"]
    model=DiffusionUNet().to(device).eval()
    model.load_state_dict(saved["ema"],strict=True)
    del saved
    _,_,schedule=make_schedule(cfg["schedule"],cfg["diffusion_steps"])
    schedule=schedule.double().numpy()
    al,sv=coefficients(1,schedule)
    predict=lambda x,t: model(x,t).float()
    report={}
    try:
        for method in ("ddim","euler","heun","dpm"):
            generator=torch.Generator(device=device).manual_seed(seed)
            x=torch.randn((count,3,32,32),device=device,generator=generator)
            x,nfe=sample_images(predict,x,schedule,method,intervals)
            sample=(x-sv*predict(x,torch.ones(count,device=device)))/al
            nfe+=1
            pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
            path=out_dir/f"{method}-{intervals}intervalos-{nfe}nfe.png"
            save_grid(pixels,path)
            report[method]=pixels
            print(method,"NFE",nfe,"rejilla",path,flush=True)
    finally:
        del model
        if device.type=="cuda": torch.cuda.empty_cache()
    same=int(np.abs(report["ddim"].astype(int)-report["euler"].astype(int)).max())
    print("Diferencia máxima DDIM frente a Euler (niveles de gris 0 a 255):",same)
    return report

if os.environ.get("P07_L04_QUICK_CHECKPOINT"):
    quick_check(os.environ["P07_L04_QUICK_CHECKPOINT"],os.environ["P07_L04_QUICK_OUT"],
                intervals=int(os.environ.get("P07_L04_QUICK_INTERVALS","10")))
else:
    print("Comprobación omitida: define P07_L04_QUICK_CHECKPOINT y P07_L04_QUICK_OUT.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

One point on the FID-10k curve

The lesson experiment is FID-10k versus NFE from 10 to 1000 for DDPM, DDIM, Heun and DPM-Solver-2 with the trained p07-l03 U-Net and the p07-l02 reference and extractor. For each method find the smallest NFE with FID at most 1.1 times the best observed FID. This 10% threshold is an operational rule, not proof of equivalence. FID-10k has finite-sample bias: equal sample sizes control but do not eliminate it.

The following cell calculates one point per run and stores it in its own JSON, so an interrupted long run does not lose previous points. It needs the checkpoint selected by the full p07-l03 training run and its events.json in the same directory. The cell verifies that it is the best EMA FID checkpoint and that its fingerprint matches the record. Set absolute paths P07_L04_CHECKPOINT (checkpoint), P07_L04_REFERENCE (p07-l02 reference directory), and P07_L04_OUTPUT (a new JSON), then set P07_L04_RUN=1. Choose P07_L04_METHOD from ddpm, ddim, ddim1, euler, heun, and dpm. For methods that skip steps, P07_L04_INTERVALS sets the interval count and P07_L04_GRID the grid, either time or karras.

The protocol is the same for every point: EMA weights, the same initial noise by batch and seed (P07_L04_SEED, distinct from the seed p07-l03 used for checkpoint selection), and one shared final evaluation estimating x^0\hat x_0 from index 1. DDPM follows ancestral steps to index 1, producing one 1000-NFE point. The others cost the interval count plus one, or twice the count plus one for Heun and DPM-Solver-2. ddim uses η=0\eta=0 and ddim1 uses η=1\eta=1, which under skipped steps is the ancestral chain of the subgrid. Selecting the best point from the same curve introduces selection; a final report would repeat that configuration with new seeds.

Plan the cost: each point uses 10,000 images times NFE image evaluations plus Inception. At the p07-l03 sampling rate you measured, one point at 1000 NFE costs as much as an evaluation of one training variant, while sampling at 21 NFE costs about fifty times less (Inception costs the same in each). A reasonable sweep uses DDIM with 10, 20, 50, 100 and 200 intervals on both grids; Heun and DPM-Solver-2 with 5, 10, 25, 50 and 100 Karras intervals; ddim1 with 10, 50 and 200; and the DDPM point.

[ ]One FID-10k point from your checkpointLocal GPU
import os, pathlib, json, hashlib

def run_image_fid():
    import cleanfid
    import importlib.metadata
    paths=[pathlib.Path(os.environ[name]) for name in
           ("P07_L04_CHECKPOINT","P07_L04_REFERENCE","P07_L04_OUTPUT")]
    checkpoint,reference_dir,output=paths
    if not all(p.is_absolute() for p in paths):
        raise ValueError("Todas las rutas deben ser absolutas")
    if output.exists(): raise FileExistsError("Elige un archivo de salida nuevo")
    if not output.parent.is_dir(): raise FileNotFoundError("El directorio de salida debe existir")
    if not torch.cuda.is_available(): raise RuntimeError("Esta evaluación requiere CUDA")
    method=os.environ.get("P07_L04_METHOD","ddim")
    if method not in ("ddpm","ddim","ddim1","euler","heun","dpm"): raise ValueError("Método desconocido")
    intervals=int(os.environ.get("P07_L04_INTERVALS","49"))
    grid=os.environ.get("P07_L04_GRID","karras")
    if method!="ddpm" and (intervals<1 or grid not in ("time","karras")):
        raise ValueError("Intervalos o malla no válidos")
    batch=32
    seed=int(os.environ.get("P07_L04_SEED","10701"))
    device=torch.device("cuda")
    saved=model=mean=cov=extractor=beta=alpha=abar=None
    x=sample=features=pixels=images=prediction=terminal=None
    try:
        saved=torch.load(checkpoint,map_location="cpu",weights_only=True)
        cfg=saved["config"]
        if cfg["mode"]!="full" or saved["pending_eval"]:
            raise ValueError("Se requiere un checkpoint evaluado de la receta completa")
        digest=file_sha(checkpoint)
        events=json.loads((checkpoint.parent/"events.json").read_text(encoding="utf-8"))
        fid_records=[r for r in events["records"] if r["kind"]=="fid"]
        fid_steps=[r["step"] for r in fid_records]
        expected_steps=list(range(cfg["eval_every"],cfg["steps"]+1,cfg["eval_every"]))
        candidates=[r for r in events["checkpoints"]
                    if r["name"]==checkpoint.name and r["kind"]=="evaluated"
                    and not r["removed"] and r["sha256"]==digest and r["step"]==saved["step"]]
        if (not candidates or sorted(fid_steps)!=expected_steps
            or not all(np.isfinite(r["ema"]["fid"]) for r in fid_records)
            or min(fid_records,key=lambda r:r["ema"]["fid"])["step"]!=saved["step"]
            or events.get("selected_step")!=saved["step"] or events["config"]!=cfg):
            raise ValueError("El registro final no identifica este checkpoint como seleccionado")
        model=DiffusionUNet().to(device).eval()
        model.load_state_dict(saved["ema"],strict=True)
        def predict(x,t):
            with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
                return model(x,t).float()
        beta,alpha,abar=make_schedule(cfg["schedule"],cfg["diffusion_steps"],device)
        schedule_cpu=abar.cpu().double().numpy()
        mean,cov,extractor,resize,record=load_fid_reference(reference_dir,device)
        chunks=[]
        first_grid=None
        expected_nfe=1000 if method=="ddpm" else intervals*(2 if method in ("heun","dpm") else 1)+1
        for start in range(0,10000,batch):
            count=min(batch,10000-start)
            generator=torch.Generator(device=device).manual_seed(seed+start)
            x=torch.randn((count,3,32,32),device=device,generator=generator)
            with torch.inference_mode():
                if method=="ddpm":
                    for t in range(len(beta),1,-1):
                        times=torch.full((count,),t,device=device,dtype=torch.long)
                        prediction=predict(x,times)
                        x=ancestral_step(x,t,prediction,beta,alpha,abar,cfg["variance"],generator)
                    nfe=len(beta)-1
                else:
                    chosen="ddim" if method=="ddim1" else method
                    x,nfe=sample_images(predict,x,schedule_cpu,chosen,intervals,grid,
                                        eta=1. if method=="ddim1" else 0.,generator=generator)
                terminal=predict(x,torch.ones(count,device=device,dtype=torch.float32))
                al,sv=coefficients(1,schedule_cpu)
                sample=(x-sv*terminal)/al
                nfe+=1
                if nfe!=expected_nfe: raise AssertionError("NFE inconsistente")
                pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
                if first_grid is None: first_grid=image_grid(pixels)
                images=np.stack([resize(image) for image in pixels]).transpose(0,3,1,2)
                features=extractor(torch.from_numpy(images).to(device)).cpu().numpy()
                chunks.append(features)
            x=sample=features=pixels=images=prediction=terminal=None
            if start % 1024 == 0:
                print("Imágenes evaluadas:",start+count,flush=True)
        fid=feature_fid(np.concatenate(chunks),mean,cov)
        result={"method":method,"nfe":expected_nfe,"fid":fid,"count":10000,
                "batch":batch,"seed":seed,"grid":grid if method!="ddpm" else None,
                "times":image_grid_times(schedule_cpu,intervals,grid).tolist() if method!="ddpm" else list(range(len(beta),0,-1)),
                "terminal":"x0 predicho desde indice 1; una NFE",
                "variance":cfg["variance"] if method=="ddpm" else None,
                "weights":"ema","inference":"CUDA autocast bf16","checkpoint_sha256":digest,"checkpoint_step":saved["step"],
                "checkpoint_config":cfg,"train_sha256":record["train_sha256"],
                "extractor_sha256":record["extractor_sha256"],"grid_png":first_grid,
                "versions":{name:importlib.metadata.version(name) for name in ("torch","numpy","clean-fid")}}
        with output.open("x",encoding="utf-8") as f:
            json.dump(result,f,ensure_ascii=False,indent=2)
        print("FID",fid,"NFE",expected_nfe,"archivo",output)
    finally:
        saved=model=mean=cov=extractor=beta=alpha=abar=None
        x=sample=features=pixels=images=prediction=terminal=None
        torch.cuda.empty_cache()

if os.environ.get("P07_L04_RUN")=="1":
    run_image_fid()
else:
    print("Evaluación omitida: define las rutas P07_L04_* y P07_L04_RUN=1 para calcular un punto.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Once the points are calculated, put their absolute paths in a JSON list in P07_L04_POINTS and provide a new figure path in P07_L04_PLOT. The cell checks that all share checkpoint, weights, reference, extractor, seed, sample count, batch size, and versions. Grid and variance remain part of the compared treatment. The best FID is selected among the supplied points, so the threshold is only as good as the sweep performed.

[ ]Plot the curve and obtain the thresholdLocal GPU
def summarize_image_fid(paths, figure_path):
    import matplotlib.pyplot as plt
    records=[json.loads(pathlib.Path(p).read_text(encoding="utf-8")) for p in paths]
    if not records: raise ValueError("No hay puntos de evaluación")
    keys=("checkpoint_sha256","weights","inference","train_sha256","extractor_sha256","count","batch","seed","terminal","versions")
    identity=[records[0][key] for key in keys]
    if any([row[key] for key in keys]!=identity for row in records):
        raise ValueError("Los protocolos comunes no coinciden")
    group=lambda row:(row["method"],row["grid"],row["variance"])
    if len({(group(row),row["nfe"]) for row in records})!=len(records):
        raise ValueError("Hay puntos duplicados para una variante y NFE")
    if any(not np.isfinite(row["fid"]) or row["fid"]<0 for row in records):
        raise ValueError("FID inválido")
    figure_path=pathlib.Path(figure_path)
    if not figure_path.is_absolute() or figure_path.exists():
        raise ValueError("Usa una ruta absoluta de figura que no exista")
    best=min(row["fid"] for row in records)
    limit=1.1*best
    fig,ax=plt.subplots()
    for variant in sorted({group(row) for row in records},key=str):
        subset=sorted((row for row in records if group(row)==variant),key=lambda row:row["nfe"])
        label=" / ".join(str(value) for value in variant if value is not None)
        ax.plot([r["nfe"] for r in subset],[r["fid"] for r in subset],marker="o",label=label)
        eligible=[r["nfe"] for r in subset if r["fid"]<=limit]
        print(label,"menor NFE dentro del 10 %:",min(eligible) if eligible else "ninguno entre los puntos")
    ax.axhline(limit,color="grey",linestyle="--",label="1.1 × mejor observado")
    ax.set(xscale="log",xlabel="NFE por imagen",ylabel="FID-10k")
    ax.legend()
    fig.tight_layout()
    fig.savefig(figure_path)
    plt.close(fig)
    print("Mejor FID observado:",best,"umbral:",limit,"figura:",figure_path)

if os.environ.get("P07_L04_POINTS"):
    summarize_image_fid(json.loads(os.environ["P07_L04_POINTS"]),os.environ["P07_L04_PLOT"])
else:
    print("Curva omitida: define P07_L04_POINTS con las rutas de los JSON y P07_L04_PLOT.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To check the curve: DDIM and Euler points on the same grid should have the same FID except for bf16 rounding. The DDPM point at 1000 NFE should approximately match the EMA FID recorded by p07-l03 for that checkpoint, since the seed changes but the method does not. If Heun with few intervals trails DDIM at equal NFE, this is the same phenomenon seen in the second interactive.

Practice Heun’s order

Implement the integrator in Karras parameterization: strictly positive decreasing noise levels σ\sigma and slope (x−D(x,σ))/σ(x-D(x,\sigma))/\sigma with denoiser DD. The first test uses a problem with known solution, D(x,σ)=(1−σ)xD(x,\sigma)=(1-\sigma)x, whose slope is xx and whose solution between σ=1\sigma=1 and σ=0.1\sigma=0.1 is x(1) e−0.9x(1)\,e^{-0.9}. Doubling intervals divides the error of a second-order method by four. Quadratically falling error here does not establish that order for a nonsmooth network or outside the theorem’s assumptions.

CodeHeun on noise levels
Implement heun_sampler(denoiser, sigmas, x). It takes strictly decreasing positive levels, an array x, and denoiser(x,sigma). Use two evaluations per interval and return the final state without modifying x.
import numpy as np
def heun_sampler(denoiser, sigmas, x):
  pass
Shift+Enter to run
Key idea

Sampling a diffusion model integrates an ODE, and in coordinates y=x/αˉy=x/\sqrt{\bar\alpha}, s=(1−αˉ)/αˉs=\sqrt{(1-\bar\alpha)/\bar\alpha} the ODE is simply dy/ds=εθ\mathrm{d}y/\mathrm{d}s=\varepsilon_\theta. Deterministic DDIM, Euler in those coordinates, and DPM-Solver-1 are the same method. Heun and DPM-Solver-2 are second order and cost two evaluations per interval. Quality per cost depends on both the method and where steps are placed. Compare samplers at equal NFE under a fixed evaluation protocol.