Module contents
Stage 5 of 9Research 110 min

The EDM formulation and design ablations

Rewrite diffusion training with EDM preconditioning and compare DDPM, v and EDM at equal compute to attribute improvements experimentally.

After this lesson you can

  • Implement EDM preconditioning and weighted loss.
  • Implement v parametrization and relate it to noise and data prediction.
  • Design an equal-step, equal-image ablation with multiple seeds.
  • Attribute FID improvement to components using intervals.

Before you start

Which decision deserves which improvement?

The DDPM in p07-l03 follows the original recipe: the network predicts noise ε\varepsilon, time is sampled uniformly from 1 to 1000, and loss is unweighted squared error. Karras, Aittala, Aila and Laine rewrote that recipe in Elucidating the Design Space of Diffusion-Based Generative Models (EDM, 2022), reducing unconditional CIFAR-10 FID from 3.01 to 1.97. Their instructive table 2 changes one decision at a time on the VP architecture (DDPM++), using the same deterministic sampler with 35 evaluations per image:

Configuration (unconditional CIFAR-10, VP)FID
A. Starting point (Song et al., pretrained model)3.01
B. Retuned hyperparameters2.51
C. Redistributed network capacity2.31
D. EDM preconditioning2.29
E. EDM loss: λ(σ)\lambda(\sigma) weighting and σ\sigma distribution2.05
F. Non-leaking data augmentation1.97

Preconditioning alone barely moves the number (2.31 to 2.29; in the VE variant it worsens from 2.83 to 3.10). The authors state its main benefit is more robust training, enabling later loss redesign without adverse effects. The large gain comes from weighting and the noise-level distribution. Applying D and E together would have credited preconditioning for an improvement it did not produce. This lesson practices that discipline: understand how each decision changes the objective and measure its effect with a controlled ablation.

Start with the underlying question. A network can predict noise, clean image or a combination, and at fixed noise level those outputs convert exactly into one another. Losses differ: each parametrization allocates effort differently across noise levels, and the distribution used to sample levels reallocates it again. The figure calculates this allocation. Switch from “Lognormal” to “uniform t (DDPM)” and observe the mass column above σdata\sigma_{\rm data}.

InteractiveWhere each parametrization puts its weight
0.00.10.20.30.40.50.010.1110100σ (logarithmic scale)σ_dataeffective weight × density, normalized (area 1 in log σ)
  • Data (x₀)
  • Noise (ε)
  • v
  • EDM
ParameterizationEffective weight at σMass with σ > σ_dataData (x₀)0.23571.0 %Noise (ε)0.05812.1 %v0.29419.5 %EDM1.00033.6 %
Training distribution of σ
−1.2
1.2
0.7
Selected σ2.0
Density of log σ0.095
Effective weight of each loss (in units of EDM's normalized target) multiplied by log σ density and normalized to area 1. The table gives weight at the selected σ and the fraction of total weight at levels where noise dominates signal. This is an analytical calculation, not a training measurement.

With EDM’s lognormal distribution, noise loss places only 12% of its weight where σ>σdata\sigma>\sigma_{\rm data}, versus EDM’s 34%: it mainly learns to remove small noise. With uniform DDPM time, however, the same noise loss rises to 34%, because the linear schedule spends many steps at high noise. This helps explain why original DDPM works well despite predicting noise: its distribution partly compensates for its weighting. Changing only one of the two can therefore worsen results even if the final combination is better.

EDM preconditioning scales input, residual skip and network output by noise level so the inner network sees unit-variance inputs and targets across the range, and uses this to set loss weight. A design ablation changes one component at a time with the rest of the protocol fixed (network, data, budget, sampler, metric and seeds), attributing each decision’s effect with an uncertainty measure. This lesson derives the scales, shows noise, data and vv parametrizations are the same loss with different weights, and builds a lab training four equally budgeted variants with multiple seeds and producing an FID table with intervals and per-noise-level loss.

Decomposing the denoiser

Let x0x_0 be a coordinate with mean zero and variance d2d^2 (EDM’s σdata\sigma_{\rm data}), independent n∼N(0,σ2)n\sim\Normal(0,\sigma^2) and y=x0+ny=x_0+n. This is the additive EDM formulation: noise is measured directly by σ\sigma, not time. EDM represents the denoiser as

Dθ(y,σ)=cskip(σ) y+cout(σ) Fθ(cin(σ) y,  cnoise(σ)),D_\theta(y,\sigma)=c_{\rm skip}(\sigma)\,y+c_{\rm out}(\sigma)\, F_\theta\big(c_{\rm in}(\sigma)\,y,\;c_{\rm noise}(\sigma)\big),

where FθF_\theta is the network (U-Net) and the four coefficients are fixed functions of σ\sigma. The idea is that FθF_\theta need not do what a formula already does well. The skip supplies a starting linear estimate, cskip yc_{\rm skip}\,y, and the network only corrects residual x0−cskipyx_0-c_{\rm skip}y, rescaled by coutc_{\rm out} to unit size. Thus the network’s effective target is

F⋆=x0−cskip(σ) ycout(σ).F^\star=\frac{x_0-c_{\rm skip}(\sigma)\,y}{c_{\rm out}(\sigma)}.

Which skip is appropriate? EDM chooses the one making coutc_{\rm out} as small as possible, so errors in FθF_\theta are amplified least when passing to DθD_\theta. Since coutc_{\rm out} normalizes the residual, this means minimizing variance of x0−cyx_0-cy. Expanding, Var⁡(x0−cy)=d2−2cd2+c2(d2+σ2)\operatorname{Var}(x_0-cy)=d^2-2cd^2+c^2(d^2+\sigma^2) is a parabola in cc with minimum at c=d2/(d2+σ2)c=d^2/(d^2+\sigma^2) and minimum value σ2d2/(d2+σ2)\sigma^2d^2/(d^2+\sigma^2). With that skip, output and input normalization are determined:

cin=1σ2+d2,cskip=d2σ2+d2,cout=σdσ2+d2,cnoise=14ln⁡σ.c_{\rm in}=\frac{1}{\sqrt{\sigma^2+d^2}},\quad c_{\rm skip}=\frac{d^2}{\sigma^2+d^2},\quad c_{\rm out}=\frac{\sigma d}{\sqrt{\sigma^2+d^2}},\quad c_{\rm noise}=\tfrac14\ln\sigma.

cinc_{\rm in} gives the input unit variance because Var⁡(y)=d2+σ2\operatorname{Var}(y)=d^2+\sigma^2, and coutc_{\rm out} gives F⋆F^\star unit variance. At the extremes: as σ→0\sigma\to0, cskip→1c_{\rm skip}\to1 and cout→0c_{\rm out}\to0, so the denoiser is almost identity and the network contributes only a tiny correction; as σ→∞\sigma\to\infty, cskip→0c_{\rm skip}\to0 and cout→dc_{\rm out}\to d, so the network predicts the clean image directly at data scale. Unit target variance alone does not determine cskipc_{\rm skip} (any skip admits a coutc_{\rm out} normalizing its residual); the minimum-amplification criterion does. Encoding cnoise=14ln⁡σc_{\rm noise}=\frac14\ln\sigma is the paper’s empirical choice, not a consequence of the derivation. Calculations use only means, variances and independence: Gaussian data are not required, and unit variance makes neither input nor target Gaussian.

ProofDerive skip, output and weight
Prove: Assume zero-mean x₀ with variance d², independent noise n with variance σ² and y = x₀ + n. For coefficient c consider residual x₀ − c·y. Derive c_skip, c_out and weight λ(σ) turning denoiser loss into squared error of the normalized target.
0
Minimize residual variance, normalize it and substitute D in λ‖D − x₀‖².

Step 1 of 4. What is covariance Cov(x₀, y)?

EDM loss is therefore λ(σ)∥Dθ(y,σ)−x0∥2\lambda(\sigma)\norm{D_\theta(y,\sigma)-x_0}^2 with λ=1/cout2=(σ2+d2)/(σd)2\lambda=1/c_{\rm out}^2=(\sigma^2+d^2)/(\sigma d)^2, and substituting the denoiser yields exactly ∥Fθ−F⋆∥2\norm{F_\theta-F^\star}^2: squared error whose target has unit variance regardless of σ\sigma. This is the loss weighting equalizing target scale across levels. On top of it, EDM samples training levels with ln⁡σ∼N(−1.2, 1.22)\ln\sigma\sim\Normal(-1.2,\,1.2^2) and uses d=0.5d=0.5.

That d=0.5d=0.5 is not universal: it is CIFAR-10’s standard deviation with pixels in [−1,1][-1,1]. Measured over all 50,000 training images (the same dataset revision used by the lab), joint pixel standard deviation is 0.503, mean −0.053-0.053; per channel, 0.494, 0.487 and 0.523. Normalize images to [0,1][0,1] and standard deviation halves to about 0.25, so σdata=0.5\sigma_{\rm data}=0.5 no longer describes your data. Always measure your dataset and state how channels are aggregated.

NumericSkip at σ = σ_data
For σ = 0.5 and σ_data = 0.5, calculate c_skip.
NumericOutput scale
For σ = 0.5 and σ_data = 0.5, calculate c_out.
NumericInput scale
For σ = 0.5 and σ_data = 0.5, calculate c_in.

The next cell checks coefficients and both unit variances by simulation, using Gaussian data of variance 0.25.

[ ]Check scales and momentsBrowser
import numpy as np
def coefficients_edm(s,d):
    if s<=0 or d<=0: raise ValueError("Escalas positivas")
    total=s*s+d*d
    return 1/np.sqrt(total),d*d/total,s*d/np.sqrt(total),np.log(s)/4
ci,cs,co,cn=coefficients_edm(.5,.5)
print("σ=0.5 d=0.5: c_in",ci,"c_skip",cs,"c_out",co,"c_noise",cn,"lambda",1/co**2)
rng=np.random.default_rng(510)
x=rng.normal(0,.5,200000)
noise=rng.normal(0,.5,len(x))
y=x+noise
print("varianza empírica entrada:",np.var(ci*y),
      "objetivo:",np.var((x-cs*y)/co))
assert abs(np.var(ci*y)-1)<.02 and abs(np.var((x-cs*y)/co)-1)<.02

The equality is population-level; empirical variances fluctuate by sample. Real images add two nuances: if channels have different means or variances, one constant does not whiten all of them, and normalized network inputs do not imply learning. Normalization improves conditioning; it does not solve the problem.

Four parametrizations, one loss

To compare objectives, express them in common coordinates. The additive form is y=x0+σεy=x_0+\sigma\varepsilon with ε∼N(0,I)\varepsilon\sim\Normal(0,I); the VP form of p07-l03 is z=αx0+βεz=\alpha x_0+\beta\varepsilon with α=1/1+σ2\alpha=1/\sqrt{1+\sigma^2} and β=σ/1+σ2\beta=\sigma/\sqrt{1+\sigma^2}, so z=αyz=\alpha y and noise-to-signal ratio β/α\beta/\alpha is precisely σ\sigma (the relation to schedule SNR is SNR=1/σ2\mathrm{SNR}=1/\sigma^2). Salimans and Ho’s v parametrization defines v=αε−βx0v=\alpha\varepsilon-\beta x_0. Since α2+β2=1\alpha^2+\beta^2=1, mapping (x0,ε)↦(z,v)(x_0,\varepsilon)\mapsto(z,v) is a rotation inverted by

x0=αz−βv,ε=βz+αv.x_0=\alpha z-\beta v,\qquad \varepsilon=\beta z+\alpha v.

With zz and level fixed, any predictor (of x0x_0, ε\varepsilon or vv) translates into estimate x^0\hat x_0, and prediction error into error δx0\delta x_0. Since ε^=(y−x^0)/σ\hat\varepsilon=(y-\hat x_0)/\sigma, error δx0\delta x_0 corresponds to δε=−δx0/σ\delta\varepsilon=-\delta x_0/\sigma; and since x^0=αz−βv^\hat x_0=\alpha z-\beta\hat v, it corresponds to δv=−δx0/β\delta v=-\delta x_0/\beta. Thus each parametrization’s simple squared loss, written in x0x_0 error, has weight

wx0=1,wε=1σ2,wv=1β2=1+σ2σ2,wEDM=λ=σ2+d2σ2d2.w_{x_0}=1,\qquad w_\varepsilon=\frac1{\sigma^2},\qquad w_v=\frac{1}{\beta^2}=\frac{1+\sigma^2}{\sigma^2},\qquad w_{\rm EDM}=\lambda=\frac{\sigma^2+d^2}{\sigma^2d^2}.

Comparing these weights directly is misleading because x0x_0 error has different size at different levels: tiny at low noise and of data order at high noise. The natural scale is EDM’s normalized target: D−x0=cout(F−F⋆)D-x_0=c_{\rm out}(F-F^\star), so a unit error in FF costs w cout2w\,c_{\rm out}^2. This is the effective weight written λ(σ)cout(σ)2\lambda(\sigma)c_{\rm out}(\sigma)^2 in EDM and set to one by its choice:

ParametrizationEffective weight w cout2w\,c_{\rm out}^2As σ→0\sigma\to0As σ→∞\sigma\to\infty
Data x0x_0σ2d2/(σ2+d2)\sigma^2d^2/(\sigma^2+d^2)→0\to0→d2\to d^2
Noise ε\varepsilond2/(σ2+d2)d^2/(\sigma^2+d^2)→1\to1→0\to0
vvd2(1+σ2)/(σ2+d2)d^2(1+\sigma^2)/(\sigma^2+d^2)→1\to1→d2\to d^2
EDM111111

The table summarizes the figure. Data prediction ignores low noise; noise prediction ignores high noise; vv and EDM cover both extremes. Now multiply by level density, as the interactive plots: density is per unit of ln⁡σ\ln\sigma (changing variable to σ\sigma introduces factor 1/σ1/\sigma), and each curve is normalized to unit area. This has a concrete rationale: with Adam, multiplying all loss by a constant leaves the update nearly unchanged because Adam divides each gradient by its typical scale. Relative allocation across levels matters, not absolute height.

Proof

With d=1d=1, EDM coefficients are cin=1/1+σ2=αc_{\rm in}=1/\sqrt{1+\sigma^2}=\alpha, cskip=1/(1+σ2)=α2c_{\rm skip}=1/(1+\sigma^2)=\alpha^2 and cout=σ/1+σ2=βc_{\rm out}=\sigma/\sqrt{1+\sigma^2}=\beta. Network input is ciny=αy=zc_{\rm in}y=\alpha y=z, the same. Also x^0=αz−βv^=α2y+β(−v^)=cskipy+coutFθ\hat x_0=\alpha z-\beta\hat v=\alpha^2y+\beta(-\hat v)=c_{\rm skip}y+c_{\rm out}F_\theta with Fθ=−v^F_\theta=-\hat v. For loss, EDM’s normalized target is F⋆=(x0−α2y)/βF^\star=(x_0-\alpha^2y)/\beta; since y=x0+σεy=x_0+\sigma\varepsilon and 1−α2=β21-\alpha^2=\beta^2, it follows F⋆=(β2x0−α2σε)/β=βx0−αε=−vF^\star=(\beta^2x_0-\alpha^2\sigma\varepsilon)/\beta=\beta x_0-\alpha\varepsilon=-v, using α2σ/β=α\alpha^2\sigma/\beta=\alpha. Hence ∥Fθ−F⋆∥2=∥−v^+v∥2\norm{F_\theta-F^\star}^2=\norm{-\hat v+v}^2. The only remaining difference is level encoding cnoisec_{\rm noise}, identical for both in the lab.

∎

The result has an immediate practical consequence: between a vv-trained and EDM-trained network with the same level distribution and encoding, the only difference is σdata\sigma_{\rm data}. For CIFAR in [−1,1][-1,1] this assumes data twice as dispersed as they are: network input has variance (σ2+0.25)/(1+σ2)(\sigma^2+0.25)/(1+\sigma^2), falling to 0.25 at low noise, and the skip trusts yy more than optimal. The lab measures the cost. Kingma and Gao complete this unification: all these losses can be written as a noise-level-weighted integral of the same basic loss, and when weight is monotone in level they are equivalent to an ELBO with Gaussian-noise augmentation.

The next cell reproduces the figure’s numbers under the same assumptions (d=0.5d=0.5; EDM lognormal and uniform-time DDPM linear-schedule distributions).

[ ]Weight allocation in the interactiveBrowser
import numpy as np
d=.5
l=np.linspace(-12,8,20001); s=np.exp(l)
weights={"datos":s*s*d*d/(s*s+d*d),"ruido":d*d/(s*s+d*d),
         "v":d*d*(1+s*s)/(s*s+d*d),"EDM":np.ones_like(s)}
lognormal=np.exp(-.5*((l+1.2)/1.2)**2)/(1.2*np.sqrt(2*np.pi))
beta=np.linspace(1e-4,.02,1000); abar=np.cumprod(1-beta)
log_sigma=.5*np.log((1-abar)/abar)
middle=(log_sigma[1:]+log_sigma[:-1])/2
ddpm=np.interp(l,middle,(1/999)/np.diff(log_sigma),left=0,right=0)
def integral(f): return float(np.sum((f[1:]+f[:-1])/2*np.diff(l)))
print("σ del DDPM lineal: de",round(float(np.exp(log_sigma[0])),4),"a",round(float(np.exp(log_sigma[-1])),1))
for name,density in (("lognormal",lognormal),("t uniforme",ddpm)):
    shares={k:integral(density*w*(s>d))/integral(density*w) for k,w in weights.items()}
    print(name,"fracción con σ > σ_data:",{k:round(v,3) for k,v in shares.items()})

When noise dominates signal, y≈σεy\approx\sigma\varepsilon and predicting ε\varepsilon becomes nearly identity: the network can return y/σy/\sigma and be correct. The problem arrives during reconstruction: x^0=y−σε^\hat x_0=y-\sigma\hat\varepsilon multiplies any ε^\hat\varepsilon error by σ\sigma, which starts at 80 in this lab’s sampler. A noise network making a small ε\varepsilon error there produces a huge image error, barely penalized by noise loss (its effective weight tends to zero). This is a conditioning problem, not a universal verdict: a schedule avoiding such high levels, or sufficient training, yields good noise-prediction models as DDPM itself shows. Salimans and Ho’s progressive distillation introduced vv to avoid it when generating in very few steps starting at high noise; their CIFAR-10 FID 3.0 with four steps is a distillation result, not merely training with vv.

Design the ablation before running

A naive DDPM-versus-EDM comparison changes three things at once: level distribution, parametrization with its weight, and σdata\sigma_{\rm data}. An FID difference cannot identify which caused it. The lab uses a four-variant ladder where each step changes one factor:

VariantPredictsLevels (and encoding)What changes
noiseε\varepsilonuniform tt in 1..10001..1000 (input tt)DDPM from p07-l03
epsε\varepsilonln⁡σ∼N(−1.2,1.22)\ln\sigma\sim\Normal(-1.2,1.2^2) (input 14ln⁡σ\tfrac14\ln\sigma)distribution and encoding
vvvas epsparametrization and weight
edmFF, d=0.5d=0.5as epsσdata\sigma_{\rm data} from 1 to 0.5

Consecutive differences eps − noise, v − eps and edm − v attribute total change edm − noise to factors and sum exactly to that total. This is one-factor-at-a-time ablation in a particular order: if factors interact (for example, vv weighting helps more under one distribution), attributed effects depend on order. Measuring interactions needs a factorial design (2×2×22\times2\times2 variants), twice the training runs. The first step combines distribution and encoding because integer time makes no sense outside the discrete schedule; this is declared.

Everything else is identical: the same 35-million-parameter U-Net, 10,000 updates of 32 images (320,000 images seen), Adam rate 2⋅10−42\cdot10^{-4}, mixed bf16 precision, horizontal flips and no EMA. For one seed all four variants receive the same images in the same order with the same flips, and eps, v and edm also receive the same σ\sigma levels. Equal update and image counts define “equal compute” here; FLOPs per update are nearly equal because the network is the same, though not identical (EDM adds a few elementary operations). Evaluation is also shared: the same EDM Heun sampler with 18 levels from 80 to 0.02 followed by zero (35 evaluations per image, as table 2), same initial noise and p07-l02 FID reference. Fixing the sampler is essential: changing it with parametrization mixes effects. The minimum level is 0.02 rather than EDM’s 0.002 because the discrete noise schedule starts at σ=0.0100\sigma=0.0100; below that the noise network would extrapolate.

How many seeds? FID noise is nontrivial. EDM calculates each FID with 50,000 images and estimates random variation around ±2 %\pm2\,\%; hence it reports the minimum of three evaluations. FID-10k has greater bias (fewer samples systematically raise estimated FID) and variance, compounded by variation across training seeds, usually dominant. The lab trains three seeds per variant (31, 32 and 33) and analyzes paired differences by seed, as in paired tests: seed pairing removes shared variation (data order, initial noise). With nn seeds and differences Δ1,…,Δn\Delta_1,\dots,\Delta_n, the 95% t interval is Δˉ±t0.975, n−1 sΔ/n\bar\Delta\pm t_{0.975,\,n-1}\,s_\Delta/\sqrt n, with t0.975,2=4.30t_{0.975,2}=4.30 for three seeds and t0.975,1=12.7t_{0.975,1}=12.7 for two. Three seeds give a useful but wide interval; two make it almost decorative. It assumes independent, approximately normal differences, untestable with so few replicates. An interval containing zero does not prove the factor unimportant: only that this budget cannot distinguish it.

What should you obtain? No results are published for this budget: 320,000 images seen is 625 times fewer than EDM’s 200 million, so FIDs will be much higher than table 2 and absolute values are not comparable. Sources and the analysis above do predict directions of some effects. In table 2, of the two objective changes, preconditioning (D) barely changes FID in full training and weight plus distribution (E) reduces it from 2.29 to 2.05; here E corresponds to the first two ladder steps combined. The figure analysis also suggests eps will struggle at high levels, where effective weight is minimal and its error is amplified by σ\sigma; the lab’s per-level loss will test this. With short budgets variant order may differ from long runs, a legitimate conclusion if carefully measured.

Wrapper and integration test

The preconditioning implementation accepts any network receiving a normalized tensor and scalar level per image. The control uses a network returning zeros: it checks scaling, per-image broadcasting and gradient flow, not training. If reusing weights, wrapping a noise-prediction network in EDMPrecond does not turn it into an EDM network because its output has a different meaning; it must be trained on the new target.

[ ]EDM preconditioning in PyTorchLocal GPU
import torch
from torch import nn

class EDMPrecond(nn.Module):
    def __init__(self,model,sigma_data=.5):
        super().__init__()
        if sigma_data<=0: raise ValueError("sigma_data debe ser positiva")
        self.model=model
        self.sigma_data=float(sigma_data)
    def forward(self,y,sigma):
        if sigma.ndim!=1 or len(sigma)!=len(y) or torch.any(sigma<=0):
            raise ValueError("Una sigma positiva por imagen")
        d=self.sigma_data
        shape=(len(y),)+(1,)*(y.ndim-1)
        s=sigma.reshape(shape)
        total=s.square()+d*d
        cin=total.rsqrt()
        skip=d*d/total
        cout=s*d*total.rsqrt()
        return skip*y+cout*self.model(cin*y,sigma.log()/4)

def edm_loss(wrapper,x,sigma,noise):
    shape=(len(x),)+(1,)*(x.ndim-1)
    s=sigma.reshape(shape)
    y=x+s*noise
    d=wrapper.sigma_data
    weight=(s.square()+d*d)/(s*d).square()
    return (weight*(wrapper(y,sigma)-x).square()).mean()

class ZeroNet(nn.Module):
    def forward(self,x,t): return torch.zeros_like(x)

wrapper=EDMPrecond(ZeroNet(),.5)
y=torch.ones(2,1,2,2,requires_grad=True)
sigma=torch.tensor([.5,1.])
output=wrapper(y,sigma)
output.sum().backward()
assert torch.allclose(output[:,0,0,0],torch.tensor([.5,.2]))
assert torch.isfinite(y.grad).all()
print("Control con red cero: saltos",output[:,0,0,0].detach().tolist(),
      "gradientes finitos",bool(torch.isfinite(y.grad).all()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With the zero network the denoiser reduces to the skip: cskip=0.25/0.5=0.5c_{\rm skip}=0.25/0.5=0.5 at σ=0.5\sigma=0.5 and 0.25/1.25=0.20.25/1.25=0.2 at σ=1\sigma=1, as printed by the cell.

Lab: four variants at equal budget

The lab has four cells: pieces reused from previous lessons, plan training, evaluation and table. None trains or evaluates by default; environment variables enable them, as in p07-l03. Everything produced goes to p07-l05/pasos-10000 inside the ATLAS_LAB_DIR environment-variable folder (default ~/atlas-lab), with one subdirectory per run (noise-s31, eps-s31, …).

Previous lessons’ requirement is the p07-l02 FID reference (the directory with cifar10_reference.npz, train_features.npy, fid_results.json and Inception weights, and vendor with clean-fid). CIFAR-10 downloads to Hugging Face cache if absent (about 130 MB); P07_L05_CACHE selects another folder. From project root in PowerShell, if p07-evaluacion was retained:

$env:P07_L02_REF=(Resolve-Path ./p07-evaluacion).Path
$env:PYTHONPATH=Join-Path $env:P07_L02_REF "vendor"
$env:P07_L05_TRAIN="1"     # entrena las 12 corridas que falten (4 variantes × 3 semillas)
$env:P07_L05_EVAL="1"      # después, evalúa las terminadas que no tengan evaluación
npm run lab

Run cells in order. The plan processes seeds one at a time, so the first four runs already give a complete one-seed comparison. Each run saves latest.pt (network, Adam and all four random states) every 1000 updates; after interruption, rerunning resumes there after checking code and configuration, skipping completed runs. Before the full plan, a short run with P07_L05_STEPS=300 and P07_L05_SEEDS=31 goes to another directory (pasos-300) and checks the pipeline end to end in minutes. To budget the full plan, use logged speed (updates per second): 120,000 updates total, plus 12 evaluations of 10,000 images at 35 network evaluations each.

First, the pieces: the same U-Net from p07-l02 and p07-l03, linear schedule, p07-l04’s conversion of σ\sigma to continuous time (to use the noise network at noninteger levels), and p07-l03 FID functions. They are repeated here so this lesson does not depend on a kernel open on another page.

[ ]Pieces from prior lessonsLocal GPU
import math, json, pathlib, hashlib
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

# U-Net de p07-l02 (idéntica a la de p07-l03).
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))

# Calendario lineal de p07-l03: abar[0]=1 y abar[t] para t=1..1000.
def linear_abar(steps=1000):
    beta=torch.linspace(1e-4,.02,steps,dtype=torch.float64)
    return torch.cat((torch.ones(1,dtype=torch.float64),torch.cumprod(1-beta,dim=0)))

# Tiempo continuo con la misma razón ruido/señal (p07-l04), interpolando -log abar.
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])

# FID con la referencia de p07-l02 (mismas comprobaciones que p07-l03).
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")
    mean=torch.as_tensor(stats["mean_train"],device=device,dtype=torch.float64)
    cov=torch.as_tensor(stats["cov_train"],device=device,dtype=torch.float64)
    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)

abar=linear_abar()
sigma_t=((1-abar[1:])/abar[1:]).sqrt()
print("σ del calendario DDPM: de",float(sigma_t[0]),"a",float(sigma_t[-1]))
assert abs(time_from_ratio(float(sigma_t[499]),abar.numpy())-500)<1e-6
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)
net=DiffusionUNet()
print("Parámetros de la U-Net:",sum(p.numel() for p in net.parameters()))
del net
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The training cell defines four ladder losses in common coordinates y=x0+σεy=x_0+\sigma\varepsilon. Variants noise, eps and v feed the network z=αyz=\alpha y, as in p07-l03; edm uses cinyc_{\rm in}y. A final zero-predictor check verifies all four losses by hand: for x0=1x_0=1, ε=0\varepsilon=0 and σ∈{0.5,1}\sigma\in\{0.5,1\}, v gives mean β2\beta^2, (0.2+0.5)/2=0.35(0.2+0.5)/2=0.35, and edm gives mean λ(1−cskip)2\lambda(1-c_{\rm skip})^2, (8⋅0.25+5⋅0.64)/2=2.6(8\cdot0.25+5\cdot0.64)/2=2.6. Each run’s log stores a source fingerprint of relevant functions and library versions; the final table refuses to mix different fingerprints.

[ ]Train the ablation planLocal GPU
import os, json, pathlib, hashlib, uuid, shutil, inspect, time, importlib.metadata
import numpy as np
import torch

LAB=pathlib.Path(os.environ.get("ATLAS_LAB_DIR",pathlib.Path.home()/"atlas-lab")).expanduser()/"p07-l05"
MODES=("noise","eps","v","edm")
SEEDS=tuple(int(s) for s in os.environ.get("P07_L05_SEEDS","31,32,33").split(","))
STEPS=int(os.environ.get("P07_L05_STEPS","10000"))
BATCH,LR,SIGMA_DATA=32,2e-4,.5
CHECKPOINT_EVERY=1000
REVISION="0b2714987fa478483af9968de7c934580d0bb9a2"
PLAN_DIR=LAB/f"pasos-{STEPS}"

def publish_json(path,data):
    """Escribe un JSON sin sustituir uno existente (falla si ya está)."""
    path=pathlib.Path(path)
    tmp=path.parent/("json-"+uuid.uuid4().hex+".tmp")
    try:
        with tmp.open("x",encoding="utf-8") as f:
            json.dump(data,f,ensure_ascii=False,indent=2)
        os.link(tmp,path)
    finally:
        tmp.unlink(missing_ok=True)

def target_loss(net,mode,x,eps,sigma,t=None,sigma_data=SIGMA_DATA):
    s=sigma[:,None,None,None]
    y=x+s*eps
    if mode=="noise":      # DDPM de p07-l03: ε, t entero uniforme, entrada VP
        prediction=net(y*torch.rsqrt(1+s.square()),t.float())
        target=eps
    elif mode=="eps":      # ε con σ lognormal y c_noise = ln σ / 4
        prediction=net(y*torch.rsqrt(1+s.square()),sigma.log()/4)
        target=eps
    elif mode=="v":        # v = α ε − β x₀: EDM con σ_data = 1
        alpha=torch.rsqrt(1+s.square())
        prediction=net(alpha*y,sigma.log()/4)
        target=alpha*eps-s*alpha*x
    elif mode=="edm":      # λ(σ)·‖D − x₀‖² = ‖F − F*‖²
        prediction=EDMPrecond(net,sigma_data)(y,sigma)
        weight=(s.square()+sigma_data**2)/(s*s*sigma_data**2)
        return (weight*(prediction-x).square()).mean()
    else:
        raise ValueError("Variante desconocida")
    return (prediction-target).square().mean()

def load_cifar(split):
    from datasets import load_dataset
    ds=load_dataset("uoft-cs/cifar10",revision=REVISION,split=split,
                    cache_dir=os.environ.get("P07_L05_CACHE"))
    images=np.stack([np.asarray(im.convert("RGB")) for im in ds["img"]])
    expected=(50000 if split=="train" else 10000,32,32,3)
    if images.shape!=expected: raise ValueError("Partición inesperada")
    return images

def train_variant(mode,seed,images,output,steps=STEPS):
    if mode not in MODES: raise ValueError("Variante fuera del plan")
    if not torch.cuda.is_available(): raise RuntimeError("El entrenamiento requiere CUDA")
    output=pathlib.Path(output)
    if (output/"model.pt").exists():
        print("Ya terminada:",output); return
    output.mkdir(parents=True,exist_ok=True)
    device=torch.device("cuda")
    sources=[target_loss,EDMPrecond.__init__,EDMPrecond.forward,DiffusionUNet.__init__,DiffusionUNet.forward,
             Residual.__init__,Residual.forward,Attention.__init__,Attention.forward,
             time_embedding,linear_abar,train_variant]
    source_sha=hashlib.sha256("\n".join(inspect.getsource(f) for f in sources).encode("utf-8")).hexdigest()
    identity={"mode":mode,"seed":seed,"steps":steps,"batch":BATCH,"lr":LR,"sigma_data":SIGMA_DATA,
              "precision":"autocast bf16","flip_probability":.5,"ema":None,
              "distribution":"t uniforme en 1..1000" if mode=="noise" else "ln σ ~ N(-1.2, 1.2²)",
              "dataset_revision":REVISION,"train_images_sha256":hashlib.sha256(images.tobytes()).hexdigest(),
              "source_sha256":source_sha,
              "versions":{n:importlib.metadata.version(n) for n in ("torch","numpy","datasets")}}
    torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
    data_rng=torch.Generator(device="cpu").manual_seed(seed+100)   # mismo orden y volteos en las 4 variantes
    level_rng=torch.Generator(device="cpu").manual_seed(seed+200)  # mismas σ en eps, v y edm
    noise_rng=torch.Generator(device=device).manual_seed(seed+300)
    net=DiffusionUNet().to(device).train()
    optimizer=torch.optim.Adam(net.parameters(),lr=LR)
    abar=linear_abar().float()
    losses,start=[],0
    if (output/"latest.pt").exists():                              # reanudar tras una interrupción
        saved=torch.load(output/"latest.pt",map_location="cpu",weights_only=True)
        if saved["identity"]!=identity: raise ValueError("Checkpoint de otro código o configuración")
        net.load_state_dict(saved["model"],strict=True)
        optimizer.load_state_dict(saved["optimizer"])
        for g,key in ((data_rng,"data_rng"),(level_rng,"level_rng"),(noise_rng,"noise_rng")):
            g.set_state(saved[key])
        torch.set_rng_state(saved["cpu_rng"]); torch.cuda.set_rng_state(saved["cuda_rng"],device)
        start,losses=int(saved["step"]),saved["losses"]
        del saved
        print("Reanudando",output.name,"desde la actualización",start)
    def save_checkpoint(step):
        if shutil.disk_usage(output).free<2*1024**3:
            raise OSError("Se requieren 2 GiB libres para guardar el checkpoint")
        tmp=output/("checkpoint-"+uuid.uuid4().hex+".tmp")
        state={"identity":identity,"step":step,"model":net.state_dict(),"optimizer":optimizer.state_dict(),
               "data_rng":data_rng.get_state(),"level_rng":level_rng.get_state(),
               "noise_rng":noise_rng.get_state(),"cpu_rng":torch.get_rng_state(),
               "cuda_rng":torch.cuda.get_rng_state(device),"losses":losses}
        try:
            torch.save(state,tmp)
            os.replace(tmp,output/"latest.pt")
        finally:
            tmp.unlink(missing_ok=True)
    clock=time.perf_counter()
    for step in range(start+1,steps+1):
        index=torch.randint(len(images),(BATCH,),generator=data_rng)
        flip=torch.rand(BATCH,generator=data_rng)<.5
        x=torch.from_numpy(images[index.numpy()]).permute(0,3,1,2).to(device).float()/127.5-1
        x=torch.where(flip.to(device)[:,None,None,None],x.flip(-1),x)
        eps=torch.randn(x.shape,device=device,generator=noise_rng)
        if mode=="noise":
            t=torch.randint(1,1001,(BATCH,),generator=level_rng)
            sigma=((1-abar[t])/abar[t]).sqrt().to(device); t=t.to(device)
        else:
            sigma=torch.exp(-1.2+1.2*torch.randn(BATCH,generator=level_rng)).to(device); t=None
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
            loss=target_loss(net,mode,x,eps,sigma,t)
        loss.backward()
        optimizer.step()
        if step%100==0 or step==steps:
            torch.cuda.synchronize()
            rate=(step-start)/(time.perf_counter()-clock)
            losses.append({"step":step,"loss":float(loss.detach())})
            print(f"{mode} s{seed} actualización {step}/{steps} pérdida del lote {losses[-1]['loss']:.4f} "
                  f"({rate:.1f} act./s)",flush=True)
        if step%CHECKPOINT_EVERY==0 or step==steps:
            save_checkpoint(step)
    tmp=output/("model-"+uuid.uuid4().hex+".tmp")
    try:
        torch.save({"model":net.state_dict(),"config":identity,"losses":losses},tmp)
        os.link(tmp,output/"model.pt")
    finally:
        tmp.unlink(missing_ok=True)
    (output/"latest.pt").unlink(missing_ok=True)
    print("Terminada:",output,"imágenes vistas:",steps*BATCH)
    del net,optimizer
    torch.cuda.empty_cache()

def run_plan():
    images=load_cifar("train")
    for seed in SEEDS:                 # semilla a semilla: tras la primera ya hay una comparación completa
        for mode in MODES:
            train_variant(mode,seed,images,PLAN_DIR/f"{mode}-s{seed}")

# Control algebraico con un predictor cero (no entrena nada).
cx,ceps=torch.ones(2,1,2,2),torch.zeros(2,1,2,2)
csigma,ct=torch.tensor([.5,1.]),torch.tensor([1,2])
control=[float(target_loss(ZeroNet(),m,cx,ceps,csigma,ct)) for m in MODES]
assert np.allclose(control,[0.,0.,.35,2.6],atol=1e-6)
print("Pérdidas con predictor cero (noise, eps, v, edm):",control)
print("Plan:",len(MODES),"variantes ×",len(SEEDS),"semillas,",STEPS,"actualizaciones de",BATCH,
      "imágenes; resultados en",PLAN_DIR)
if os.environ.get("P07_L05_TRAIN")=="1":
    run_plan()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Three decisions deserve comment. Logged batch loss cannot compare variants: each measures error on a different scale (noise, vv, normalized target), so evaluation uses a common scale. There is no EMA: over 10,000 updates, p07-l03’s decay 0.9999 EMA would have a half-life near 6900 updates and mostly average poorly trained weights; omitting it hurts absolute FID, but equally for all four variants. And σdata=0.5\sigma_{\rm data}=0.5 is fixed, not estimated per run: it is the paper’s value and matches CIFAR-10’s measured standard deviation in [−1,1][-1,1] (0.503).

Evaluation has two parts. First measure denoiser error by level: for 1000 test images (unseen in training) and eight fixed levels from 0.02 to 20, per-coordinate mean squared error of x^0\hat x_0 against x0x_0. This scale is common because all four variants convert to x^0\hat x_0 in the same coordinates, and is the “loss by noise level” showing where each wins or loses. As reference, the best coordinatewise linear denoiser cskipyc_{\rm skip}y has error cout2=σ2d2/(σ2+d2)c_{\rm out}^2=\sigma^2d^2/(\sigma^2+d^2) per coordinate (approximately, since CIFAR mean is not exactly zero); a network exploiting image structure should lie below it. Second, generate 10,000 images using p07-l04’s Heun sampler and compute FID against the training reference. Each evaluation saves evaluation-10000.json and a 32-sample grid muestras.png in the run directory without replacing an earlier evaluation.

[ ]Evaluate FID-10k and error by levelLocal GPU
import os, json, pathlib, importlib.metadata
import numpy as np
import torch

SAMPLES=int(os.environ.get("P07_L05_SAMPLES","10000"))
BAND_LEVELS=(.02,.05,.12,.3,.8,2.,5.,20.)
SAMPLE_SEED=87010

def denoise_variant(net,mode,y,sigma,abar):
    """Estimación de x₀ de las cuatro variantes en las mismas coordenadas y = x₀ + σ ε."""
    s=torch.full((len(y),),float(sigma),device=y.device)
    scale=s[:,None,None,None]
    if mode=="edm":
        return EDMPrecond(net,SIGMA_DATA)(y,s).float()
    alpha=torch.rsqrt(1+scale.square())
    z=alpha*y
    if mode=="noise":
        times=torch.full((len(y),),time_from_ratio(float(sigma),abar),device=y.device)
        return y-scale*net(z,times).float()
    if mode=="eps":
        return y-scale*net(z,s.log()/4).float()
    if mode=="v":
        return alpha*z-scale*alpha*net(z,s.log()/4).float()
    raise ValueError("Variante desconocida")

@torch.inference_mode()
def heun_edm(net,mode,abar,initial):
    # 18 niveles ρ=7 de 80 a 0.02 y después 0: 17 pasos de Heun y uno de Euler, 35 evaluaciones.
    levels=np.append(np.linspace(80**(1/7),.02**(1/7),18)**7,0.)
    y,nfe=initial.clone(),0
    for s,q in zip(levels[:-1],levels[1:]):
        with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
            d=denoise_variant(net,mode,y,s,abar)
        slope=(y-d)/s
        predicted=y+(q-s)*slope; nfe+=1
        if q>0:
            with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
                d2=denoise_variant(net,mode,predicted,q,abar)
            y=y+(q-s)*(slope+(predicted-d2)/q)/2; nfe+=1
        else:
            y=predicted
    return y,nfe

@torch.inference_mode()
def noise_bands(net,mode,abar,test_images,device):
    """MSE del denoiser por coordenada en 1000 imágenes de prueba y niveles fijos (escala común)."""
    bands=[]
    for index,s in enumerate(BAND_LEVELS):
        gen=torch.Generator(device=device).manual_seed(2400+index)
        total=0.
        for start in range(0,1000,50):
            x=torch.from_numpy(test_images[start:start+50]).permute(0,3,1,2).to(device).float()/127.5-1
            eps=torch.randn(x.shape,device=device,generator=gen)
            with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
                prediction=denoise_variant(net,mode,x+s*eps,s,abar)
            total+=float((prediction-x).square().sum())
        bands.append({"sigma":s,"mse":total/(1000*3*32*32)})
    return bands

def save_grid(pixels,path):
    from PIL import Image
    canvas=Image.new("RGB",(256,128))
    for i,image in enumerate(pixels[:32]):
        canvas.paste(Image.fromarray(image),(32*(i%8),32*(i//8)))
    canvas.save(path)

def evaluate_variant(run_dir,reference_dir,test_images,samples=SAMPLES):
    run_dir=pathlib.Path(run_dir)
    output=run_dir/f"evaluation-{samples}.json"
    if output.exists():
        print("Ya evaluada:",output); return
    device=torch.device("cuda")
    saved=torch.load(run_dir/"model.pt",map_location="cpu",weights_only=True)
    config=saved["config"]
    net=DiffusionUNet().to(device).eval()
    net.load_state_dict(saved["model"],strict=True)
    abar=linear_abar().numpy()
    bands=noise_bands(net,config["mode"],abar,test_images,device)
    mean,cov,extractor,resize,record=load_fid_reference(reference_dir,device)
    chunks=[]
    for start in range(0,samples,32):
        count=min(32,samples-start)
        gen=torch.Generator(device=device).manual_seed(SAMPLE_SEED+start)   # mismos ruidos en todas las variantes
        sample,nfe=heun_edm(net,config["mode"],abar,80*torch.randn((count,3,32,32),device=device,generator=gen))
        if nfe!=35: raise AssertionError("NFE inconsistente")
        pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
        if start==0: save_grid(pixels,run_dir/"muestras.png")
        resized=np.stack([resize(image) for image in pixels]).transpose(0,3,1,2)
        with torch.inference_mode():
            chunks.append(extractor(torch.from_numpy(resized).to(device)).cpu().numpy())
        if (start//32)%50==0: print(run_dir.name,"imágenes generadas:",start+count,flush=True)
    result={"config":config,"fid":feature_fid(np.concatenate(chunks),mean,cov),"bands":bands,
            "samples":samples,"batch":32,"sample_seed":SAMPLE_SEED,"nfe":35,
            "sampler":"Heun determinista, 18 niveles ρ=7 de 80 a 0.02 y cero",
            "train_features_sha256":record["train_sha256"],"extractor_sha256":record["extractor_sha256"],
            "versions":{n:importlib.metadata.version(n) for n in ("torch","numpy","clean-fid")}}
    publish_json(output,result)
    print(run_dir.name,"FID:",round(result["fid"],2),"→",output)
    del net,extractor,mean,cov
    torch.cuda.empty_cache()

def run_evaluations():
    reference=os.environ.get("P07_L02_REF")
    if not reference or not pathlib.Path(reference).is_absolute():
        raise ValueError("P07_L02_REF debe ser el directorio absoluto de la referencia de p07-l02")
    runs=sorted(p.parent for p in PLAN_DIR.glob("*/model.pt"))
    if not runs: raise FileNotFoundError("No hay modelos terminados en "+str(PLAN_DIR))
    test_images=load_cifar("test")
    for run in runs:
        evaluate_variant(run,reference,test_images)

levels=np.append(np.linspace(80**(1/7),.02**(1/7),18)**7,0.)
print("Niveles del muestreador:",np.round(levels,3).tolist())
print("Evaluaciones por imagen:",2*(len(levels)-2)+1)
if os.environ.get("P07_L05_EVAL")=="1":
    run_evaluations()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All four variants use exactly the same integrator: conversion to x^0\hat x_0 alone depends on variant. For noise, σ\sigma is translated to continuous time with the same αˉ\bar\alpha by interpolating −ln⁡αˉ-\ln\bar\alpha as in p07-l04; the network was trained at integer times, so interpolates its embedding between them, which works well in practice but merits checking on the sample grid. Initial state is 80 ε80\,\varepsilon: at σ=80\sigma=80 signal standard deviation 0.5 is negligible relative to noise, and starting without it is an excellent prior approximation.

The final cell assembles the table. It finds plan evaluations, requires identical seeds across four variants (at least two) and shared evaluation protocol, budget, data and code fingerprint. It prints each variant’s mean and cross-seed FID standard deviation, paired ladder differences with 95% t intervals, and error by level averaged over seeds. It saves ablacion-10000.json and level-error figure bandas-10000.png with linear denoiser reference curve cout2c_{\rm out}^2.

[ ]Ablation table with intervalsLocal GPU
import json, pathlib
import numpy as np

STAIRS=(("eps","noise","distribución de σ y codificación del nivel"),
        ("v","eps","parametrización y peso (ε → v)"),
        ("edm","v","σ_data = 0.5 en lugar de 1"),
        ("edm","noise","total"))

def summarize_ablation(plan_dir=PLAN_DIR,samples=SAMPLES):
    from scipy.stats import t as student_t
    rows=[json.loads(p.read_text(encoding="utf-8")) for p in sorted(pathlib.Path(plan_dir).glob(f"*/evaluation-{samples}.json"))]
    keyed={(r["config"]["mode"],r["config"]["seed"]):r for r in rows}
    seeds=sorted({seed for _,seed in keyed})
    missing=[f"{m}-s{s}" for m in MODES for s in seeds if (m,s) not in keyed]
    if len(seeds)<2 or missing:
        raise ValueError(f"Faltan evaluaciones: {missing or 'se necesitan al menos 2 semillas'}")
    protocol=("samples","batch","sample_seed","nfe","sampler","train_features_sha256","extractor_sha256","versions")
    training=("steps","batch","lr","sigma_data","precision","flip_probability","dataset_revision",
              "train_images_sha256","source_sha256","versions")
    first=rows[0]
    if any([r[k] for k in protocol]!=[first[k] for k in protocol] for r in rows):
        raise ValueError("Protocolos de evaluación distintos")
    if any([r["config"][k] for k in training]!=[first["config"][k] for k in training] for r in rows):
        raise ValueError("Presupuestos o código de entrenamiento distintos")
    fid={m:np.array([keyed[m,s]["fid"] for s in seeds]) for m in MODES}
    n=len(seeds); q=student_t.ppf(.975,df=n-1)
    print(f"FID con {samples} muestras, {first['config']['steps']} actualizaciones, semillas {seeds}")
    for m in MODES:
        print(f"  {m:6s} media {fid[m].mean():7.2f}  desviación {fid[m].std(ddof=1):6.2f}  por semilla {np.round(fid[m],2).tolist()}")
    summary={"seeds":seeds,"fid":{m:fid[m].tolist() for m in MODES},"steps":[]}
    print("Diferencias emparejadas por semilla (negativo = mejora), IC t del 95 %:")
    for new,old,label in STAIRS:
        diff=fid[new]-fid[old]; sd=diff.std(ddof=1)
        half=q*sd/np.sqrt(n) if sd>0 else float("nan")
        print(f"  {new}−{old} ({label}): {diff.mean():+.2f} ± {half:.2f}  valores {np.round(diff,2).tolist()}")
        summary["steps"].append({"cambio":f"{new}-{old}","factor":label,"diferencias":diff.tolist(),
                                 "media":float(diff.mean()),"semiancho_95":float(half)})
    levels=[b["sigma"] for b in first["bands"]]
    bands={m:np.mean([[b["mse"] for b in keyed[m,s]["bands"]] for s in seeds],axis=0) for m in MODES}
    print("MSE del denoiser por nivel (media de semillas), σ =",levels)
    for m in MODES:
        print(f"  {m:6s}",np.array2string(bands[m],precision=4))
    summary["bands"]={"sigma":levels,**{m:bands[m].tolist() for m in MODES}}
    out=pathlib.Path(plan_dir)/f"ablacion-{samples}.json"
    out.write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding="utf-8")
    import matplotlib; matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig,ax=plt.subplots(figsize=(6,4))
    for m in MODES: ax.loglog(levels,bands[m],marker="o",label=m)
    ax.loglog(levels,[s*s*SIGMA_DATA**2/(s*s+SIGMA_DATA**2) for s in levels],"k--",lw=1,label="denoiser lineal $c_{out}^2$")
    ax.set_xlabel("σ"); ax.set_ylabel("MSE por coordenada"); ax.legend(); fig.tight_layout()
    fig.savefig(pathlib.Path(plan_dir)/f"bandas-{samples}.png",dpi=150); plt.close(fig)
    print("Resumen y figura en",plan_dir)
    return summary

found=sorted(PLAN_DIR.glob(f"*/evaluation-{SAMPLES}.json"))
print("Evaluaciones encontradas en",PLAN_DIR,":",len(found),"de",len(MODES)*len(SEEDS))
if len(found)>=2*len(MODES):
    summarize_ablation()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Before interpreting the table, check that the results make sense:

  • Pipeline. The short run should finish all four runs, print 35 evaluations per image and leave a grid in each directory. Interrupt and restart midway and the log should report resuming from the last multiple of 1000 updates.
  • Error by level. With the full plan all variants should lie below cout2c_{\rm out}^2 at intermediate levels; otherwise conversion to x^0\hat x_0 or level encoding is wrong. Examine separation: weight analysis predicts eps worst at high levels.
  • Samples. Uniform blotches or saturated colors in one variant often indicate a sign or scale error in its conversion, not poor training.
  • Table. First inspect cross-seed deviation for each variant: it is the minimum difference size you can attribute. Then read ladder steps with intervals. An interval crossing zero leaves the effect undecided at this budget.

A short run already teaches something, cautiously. After only 40 updates with seed 31, per-coordinate error at σ=20\sigma=20 was 19.2 for noise and 46.1 for eps, versus 0.25 for linear denoiser cskipyc_{\rm skip}y: with an undertrained noise network, conversion’s factor σ\sigma dominates high-noise error, as weight analysis predicts. At σ=0.02\sigma=0.02 both gave 0.0004, matching cout2c_{\rm out}^2. These numbers come from one minimal run: they check pipeline and conversions behave as expected, not rank variants. Resuming after interruption should reproduce a continuous run; with all four random states and Adam restored, final weights match bit for bit on CPU and on GPU can differ only due to nondeterminism in some cuDNN operations.

Common mistakes

Exercises

CodeImplement preconditioning
Implement EDMPrecond(model, sigma_data). forward(y, sigma) receives a batched tensor and one positive sigma per element, calculates c_in, c_skip, c_out and c_noise according to EDM, and returns denoiser D = c_skip·y + c_out·model(c_in·y, c_noise). Preserve gradients. Tests check scaling with an identity network and that network input and normalized target have variance near one.
import torch
from torch import nn
class EDMPrecond(nn.Module):
  def __init__(self,model,sigma_data):
      super().__init__()
  def forward(self,y,sigma):
      pass
Shift+Enter to run
Numericv weight versus EDM
With σ_data = 0.5, calculate effective weight w·c_out² of v loss at σ = 2 (EDM is 1 at all levels).
Quiz
With very little signal (for example σ = 50), what problem does a noise ε predictor have?
Quiz
In the lab ladder, which comparison isolates using σ_data = 0.5 instead of 1?
Quiz
A colleague trains DDPM for 200,000 steps and EDM for 100,000 with double batch size, evaluates DDPM using 1000-step ancestral sampling and EDM using 35-step Heun, and concludes EDM preconditioning improves FID by 1.5 points. What is most defensible?

Summary

Key idea

EDM decomposes the denoiser into a linear skip, a network with unit-variance inputs and targets, and weight λ=1/cout2\lambda=1/c_{\rm out}^2 giving all levels the same error scale. Data, noise and vv parametrizations are the same loss with a different effective weight, and vv is exactly EDM with σdata=1\sigma_{\rm data}=1. What changes the result is where effort goes, depending on both weight and level distribution. To learn which decision improves FID, change them one at a time with the protocol otherwise fixed and measure paired differences across seeds.