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 at and ends at . The dashed reference is the same ODE integrated by Heun with 1024 intervals.
With Euler and 12 intervals, the endpoint is units from the reference; Heun with the same 12 intervals ends 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 to 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 , where . 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 , we have , hence . The step has a simple interpretation. The process of Song and colleagues defines as the Gaussian with mean and covariance . The sampler substitutes for , making exactly . Thus the step points to the position of at noise level and reuses the noise direction seen by the network.
The exercise asks for the key property: the process preserves the training marginals for any .
Step 1 of 4. Under the induction hypothesis, what is the law of ε given x₀?
What does each endpoint of recover? With , is the variance of the posterior of the original forward Markov process between and , whose transition is . If and are consecutive, 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 , no noise is added: the step is deterministic, and all randomness is in . 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.
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, with , the probability-flow ODE of Song and colleagues is
Its solutions transport into for every . They share marginals with the reverse SDE, while their trajectories differ. Integration uses decreasing , so increments are negative. Its form depends on the parameterization. A change of variables makes it almost trivial. Let and define the noise-to-signal ratio , which falls from to as noise is removed. Using the Tweedie score, , where is learned by the noise predictor.
In coordinates the ODE has no linear part: its slope is only the predicted noise. Integrating the probability-flow ODE advances from to along a grid with steps , evaluating the network at . Euler uses . This reveals why DDIM matched Euler in the interactive.
Proof
Divide the DDIM step with by and use :
This is the Euler step with .
∎The result is exact rather than asymptotic: both rules are the same function of , so their trajectories coincide point by point. Euler has global error if the slope is Lipschitz in and sufficiently smooth in . Heun’s method (explicit trapezoid) predicts with Euler, evaluates the network again at the endpoint, and averages:
Its local error is and global error is if the slope is in and Lipschitz in (as seen in Runge-Kutta). It costs two evaluations per interval. In the parameterization of Karras and colleagues, the slope is with a denoiser . It is singular at , so a grid ending at zero noise uses Euler for the last interval. Here the grids end at and Heun uses two evaluations in every interval.
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, , so is constant, and . 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 appears neutral but is not: the field 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 :
with in their paper. For the grid approaches a geometric grid (uniform in ); with it is uniform in . In the 12-interval example, the last Karras jump goes from to (ratio 2.1), while the grid uniform in jumps from to (ratio 7.8), precisely where the field bends most.
The next interactive compares error with cost. For 32 fixed initial states , integrate each method with several interval counts and plot mean endpoint error against NFE on log-log axes. A straight line with slope means error : the empirically measured method order, as in empirical order verification.
On the Karras grid, Euler’s slope is close to and those of Heun and DPM-Solver-2 are close to : 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 : at the same NFE errors are several times larger and slopes stabilize much later. The cell reproduces the table with another seed.
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 , the VP ODE has a linear part with an exact solution given by a scale factor. Direct Euler integration in 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 , , and the half-log SNR . The exact solution between and is
No additional derivation is needed: this is the ODE in written in terms of , because and . Multiply by . Freezing at its initial value makes the integral with . This is DPM-Solver-1 and, by the preceding theorem, it is again DDIM: Euler in , deterministic DDIM, and the first-order exponential solver are the same method.
The second-order solver evaluates the predictor at the midpoint in , , that is, at the geometric mean :
Here is the VP deviation at , not the ratio . Dividing by reveals the structure: is Euler to the midpoint, and is the midpoint method with a geometric node.
Proof
In the step is with . By Taylor expansion, the exact solution satisfies and the step gives . With , , hence and local error . Lipschitz continuity propagates local errors with a bounded factor, giving global error , as for any consistent second-order one-step method.
∎Lu and colleagues prove the analogous result for DPM-Solver- in under similar regularity assumptions. The constant grows when , and 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 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.
The Karras convention counts differently: 18 positive levels followed by zero give 18 intervals and 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.
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 achieves FID 13.36, 6.84, 4.67 and 4.16 at 10, 20, 50 and 100 steps, while achieves 41.07, 18.36, 8.01 and 5.78. At 1000 steps the order reverses: reaches 4.04 and ancestral sampling with larger variance () 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 , 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 . 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 fails in a specific way. The midpoint follows , and a high-dimensional Gaussian norm concentrates: with fluctuations of order one. For CIFAR-10, : endpoint norms are near and the midpoint near , a region where the network has almost never seen . Spherical interpolation follows the arc between directions. For unit vectors at angle ,
which has unit norm for every . 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.
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.
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 indexed from 0 to . It linearly interpolates 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 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.
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))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.
@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)))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.
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)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.
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.")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 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 and ddim1 uses , 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.
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.")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.
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.")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 and slope with denoiser . The first test uses a problem with known solution, , whose slope is and whose solution between and is . 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.
import numpy as np
def heun_sampler(denoiser, sigmas, x):
passSampling a diffusion model integrates an ODE, and in coordinates , the ODE is simply . 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.