Training a DDPM on CIFAR-10
Train and evaluate a CIFAR-10 diffusion model with reproducible schedules, ancestral sampling, EMA checkpoints and resumable runs.
After this lesson you can
- Compare diffusion schedules and noise-prediction loss.
- Derive ancestral reverse sampling and compare fixed variances.
- Maintain EMA weights and evaluate paired checkpoints under a fixed FID protocol.
- Budget training and sampling computation.
- Save and restore training and random states.
Before you start
A loss that does not tell the whole story
In the previous lesson we built a diffusion U-Net and fixed an evaluation protocol with Inception features, after checking the entire mechanism in 2D toy diffusion. Now we train that network to invert image diffusion. Loss measures noise prediction on corrupted examples; FID measures image statistics after the entire reverse chain. These are different observations, and a declining loss curve alone does not certify good samples.
The DDPM training recipe takes image , chooses step , generates Gaussian noise and predicts that noise from : noise-prediction parameterization. As in the p07-l02 U-Net, images have three channels and 32 × 32 resolution. This lesson’s lab is the complete full-size recipe for running on your GPU over one or more nights; it also includes a short mode traversing the same circuit in minutes to check everything works before a long run.
Corruption, SNR and schedules
With and , the forward marginal satisfies
The marginal’s signal-to-noise ratio is . It is the ratio of the squared deterministic signal coefficient to added-noise variance, not a measure that itself accounts for actual pixel variance. The linear schedule of Ho and colleagues uses 1000 steps with between and 0.02. SNR falls from at to about at , where : is practically pure noise, justifying sampling from .
The cosine schedule of Nichol and Dhariwal starts with a continuous function of , normalizes it at zero and builds each as a ratio of consecutive values. Its maximum clip avoids singularities; after clipping, recompute effective from the product instead of continuing to use the unclipped continuous curve.
import numpy as np
def schedules(kind,steps=1000):
if kind=="linear":
beta=np.linspace(1e-4,.02,steps)
elif kind=="cosine":
t=np.linspace(0,steps,steps+1)/steps
desired=np.cos(((t+.008)/(1+.008))*np.pi/2)**2
desired/=desired[0]
beta=np.minimum(1-desired[1:]/desired[:-1],.999)
else:
raise ValueError("Calendario desconocido")
if np.any(beta<=0) or np.any(beta>=1):
raise ValueError("Varianzas fuera de (0,1)")
abar=np.r_[1.,np.cumprod(1-beta)]
return beta,abar
for kind in ("linear","cosine"):
b,a=schedules(kind)
print(kind,"pasos:",len(b),"beta mínima y máxima:",b.min(),b.max(),
"alpha acumulada final:",a[-1])No schedule is universally best for every metric. On CIFAR-10, Nichol and Dhariwal’s table 2, with 500,000 iterations (500.000 in the source) and 4000 diffusion steps, reports FID 2.90 for linear schedule and simplified loss, and 3.05 for cosine with the same loss; NLL values were 3.37 and 3.26 bits per dimension respectively. The row closest to our lab, linear schedule, simplified loss and 1000 diffusion steps, gives FID 3.29. All use 50,000 samples (50.000 in the source) for FID. These are that study’s configurations and architecture, not a prediction for the network trained here.
Loss and the reverse step
Ho’s simplified objective minimizes mean over chosen times and training data. One aggregate loss can hide different errors at each noise level. Logging loss by time band aids diagnosis, but FID depends on errors accumulated during sampling, checkpoint and evaluation. Thus visual quality or FID can improve while mean loss changes little; no monotonic relation is guaranteed.
At every update we randomly choose images and times and generate fresh noise. Per-example loss is averaged over channels and pixels, then over batch. The panel divides times into four intervals (band 1: from 1 to 250; band 2: 251 to 500; through band 4, 751 to 1000) and separately accumulates losses and example counts per interval. Expect band 1 to have highest loss throughout training: at low noise is almost the image and noise is a tiny perturbation to separate from fine detail; at high noise and predicting is nearly copying the input. A band with few examples can fluctuate heavily: values are not an independent validation curve and comparing them without counts misleads.
Horizontal flipping changes the training distribution, but must not be applied improvised to the FID reference set. p07-l02 statistics come from images without that augmentation. Both decisions are specified in the cells: the first defines what the network sees in learning, the second what generation is compared with. Conversion to and quantization of outputs to eight-bit RGB are also part of the protocol.
Ancestral sampling (the DDPM sampler) constructs from to with mean
Two common fixed variances are and . The first is posterior variance conditioned on clean data; the second is forward transition variance. Ho and colleagues note is optimal if and if is a fixed point: the two extremes upper- and lower-bound reverse entropy for data of unit variance per coordinate, and both performed similarly in their experiments. Since , the posterior adds slightly less noise each step. Both set added noise to zero on the final step. Neither makes the reverse exact for an arbitrary data distribution with finitely many steps.
The posterior formula comes from multiplying two Gaussians: the distribution of given and the transition of given . For , resulting precision is ; inverting gives . The mean has one term proportional to and another to . Replacing with the estimate derived from predicted noise leads to the mean above. At the posterior limit is degenerate and no noise is added.
Distinguish that posterior conditioned on known from the marginal reverse needed by the generator. In actual generation is unknown; the network approximates, at best, , the squared-error minimizer. Since posterior mean is affine in , replacing by gives the exact mean of true reverse ; its shape is approximated: the true reverse is not generally Gaussian and covariance depends on data. Low loss at one time therefore does not ensure all chain steps compose a correct distribution.
beta,abar=schedules("linear")
for t in (2,500,1000):
bt=beta[t-1]
posterior=bt*(1-abar[t-1])/(1-abar[t])
print("t:",t,"beta:",bt,"varianza posterior:",posterior)
assert 0 <= posterior <= btAveraging weights without losing current state
The exponential moving average and checkpoint selection maintains a copy with after each update (the weights’ EMA). With , the half-life of a past weight’s contribution is about 6931 updates and the effective window updates.
Why can this improve samples so much? At constant learning rate Adam does not converge to a point: the iterate oscillates around a good region with dispersion increasing with the rate. Averaging weights over the last ten thousand updates cancels much of that oscillation, as in Polyak–Ruppert averaging. In diffusion the effect may be more visible because the sampler applies the same network a thousand consecutive times and a small bias common to steps accumulates. Song and Ermon observed that without EMA FID fluctuates greatly during training and samples of one checkpoint tend to share a color shift changing between checkpoints; EMA stabilizes FID and removes that artifact. It does not guarantee better FID at every evaluation and can be worse early in training: EMA still carries initialization.
Ho and colleagues train CIFAR-10 with EMA 0.9999, random horizontal flips, dropout 0.1, batch 128 and Adam rate (fixed without a sweep), for 800.000 updates (800,000) of a 35.7-million-parameter network. Their published unconditional CIFAR-10 FID is 3.17, calculated with 50.000 samples (50,000) against training and taking the minimum during training. FID with 10.000 samples (10,000) and another architecture is not directly comparable. EMA also does not store optimizer state: both must be retained separately to resume.
Expanding the recurrence gives a weighted average of recent weights and an initialization contribution multiplied by . A rate nearer one retains memory for more updates and responds more slowly to a regime change. It should not be read as an average of images or proof EMA samples are always better. In comparison we keep the same initial noises so weight changes are not confounded with a different seed.
rho=.9999
print("rho:",rho,"semivida en actualizaciones:",np.log(.5)/np.log(rho))Reproducible implementation
The next cell reproduces the p07-l02 architecture with the same width, resolution, time embedding and attention: 35.0 million parameters, nearly the same as Ho’s CIFAR-10 model, though without dropout. Run it before training cells. Its definition is included here so this lesson does not depend on a kernel remaining open on another page.
import math
import torch
from torch import nn
import torch.nn.functional as F
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))
net=DiffusionUNet()
n_params=sum(p.numel() for p in net.parameters())
print("parámetros de la U-Net:",n_params)
with torch.no_grad():
y=net(torch.zeros(1,3,32,32),torch.tensor([10]))
assert y.shape==(1,3,32,32)
print("forma entrada y salida:",tuple(y.shape))
del net,y
npm run lab and open the connection link.The next cell also implements the schedule in PyTorch and maintains an independent copy of all state tensors. The context restores live weights even if evaluation fails. It neither creates a new optimizer nor alters Adam states. For integer buffers, the update copies the value rather than averaging it.
import copy, contextlib, math
import torch
from torch import nn
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()
class EMA:
def __init__(self,model):
self.shadow={key:value.detach().clone() for key,value in model.state_dict().items()}
@torch.no_grad()
def update(self,model,decay):
if not 0<=decay<1:
raise ValueError("decay debe estar en [0,1)")
state=model.state_dict()
if state.keys()!=self.shadow.keys():
raise ValueError("El estado del modelo no coincide")
for key,value in state.items():
if value.is_floating_point() or value.is_complex():
self.shadow[key].mul_(decay).add_(value.detach(),alpha=1-decay)
else:
self.shadow[key].copy_(value)
@contextlib.contextmanager
def applied(self,model):
original={key:value.detach().clone() for key,value in model.state_dict().items()}
try:
model.load_state_dict(self.shadow,strict=True)
yield model
finally:
model.load_state_dict(original,strict=True)
def state_dict(self):
return {key:value.detach().clone() for key,value in self.shadow.items()}
def load_state_dict(self,state):
if state.keys()!=self.shadow.keys():
raise ValueError("EMA incompatible")
for key in state:
self.shadow[key].copy_(state[key].to(self.shadow[key].device))
toy=nn.Linear(1,1,bias=False)
with torch.no_grad(): toy.weight.fill_(1)
ema=EMA(toy)
with torch.no_grad(): toy.weight.fill_(3)
ema.update(toy,.5)
try:
with ema.applied(toy):
assert torch.allclose(toy.weight,torch.tensor([[2.]]))
raise RuntimeError("control de restauración")
except RuntimeError:
pass
assert torch.allclose(toy.weight,torch.tensor([[3.]]))
print("EMA de control:",float(ema.shadow["weight"].item()),
"peso restaurado:",float(toy.weight.item()))npm run lab and open the connection link.The sampler uses an explicit random-number generator. Using the same seed and batch shapes for current and EMA weights pairs initial and added noises, though the network changes trajectories. Testing both variances needs no retraining, but each result must state which was used.
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
@torch.inference_mode()
def ancestral_samples(model,count,beta,alpha,abar,variance,seed,device):
generator=torch.Generator(device=device).manual_seed(seed)
x=torch.randn((count,3,32,32),device=device,generator=generator)
was_training=model.training
model.eval()
try:
for t in range(len(beta),0,-1):
times=torch.full((count,),t,device=device,dtype=torch.long)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16,enabled=device.type=="cuda"):
eps=model(x,times).float()
x=ancestral_step(x,t,eps,beta,alpha,abar,variance,generator)
finally:
model.train(was_training)
return x
b,a,ab=make_schedule("linear",1000)
x=torch.ones(2,3); eps=torch.zeros_like(x)
g=torch.Generator().manual_seed(8)
small=ancestral_step(x,1,eps,b,a,ab,"posterior",g)
large=ancestral_step(x,1,eps,b,a,ab,"beta",g)
assert torch.equal(small,large)
print("Último paso: ruido añadido cero en ambas opciones:",torch.equal(small,large))
g1=torch.Generator().manual_seed(19)
g2=torch.Generator().manual_seed(19)
small=ancestral_step(torch.zeros_like(x),2,eps,b,a,ab,"posterior",g1)
large=ancestral_step(torch.zeros_like(x),2,eps,b,a,ab,"beta",g2)
posterior=b[1]*(1-ab[1])/(1-ab[2])
assert torch.allclose(small,large*torch.sqrt(posterior/b[1]),atol=1e-7)
print("Paso anterior: escalas de ruido concuerdan con ambas varianzas:",True)npm run lab and open the connection link.Evaluating with the same reference
To compare EMA and live weights, we use 10.000 images (10,000) per evaluation, mode clean and training statistics from p07-l02. Sample count, image quantization, seed and reverse variance are part of the protocol. FID-10k is sampling-sensitive; repeatedly selecting the minimum across checkpoints also adds selection optimism (Ho’s 3.17 is also the minimum over training). Reserve another evaluation with new seeds and, if needed, a separate reference set for the final check.
The evaluation cell receives a directory with cifar10_reference.npz, train_features.npy, fid_results.json and inception-2015-12-05.pt generated by p07-l02. It checks weights and feature fingerprints before using statistics. A fingerprint verifies supplied files against the record; it does not itself prove extraction procedure, which previous lesson cells document and can regenerate.
import io, os, json, pathlib, hashlib, base64
import numpy as np
import torch
from PIL import Image
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")
@torch.inference_mode()
def evaluate_fid(model,ema,beta,alpha,abar,variance,reference_dir,device,seed=8701,batch=32):
mean=cov=extractor=None
try:
mean,cov,extractor,resize,record=load_fid_reference(reference_dir,device)
output={}
for label in ("live","ema"):
context=ema.applied(model) if label=="ema" else contextlib.nullcontext(model)
chunks=[]; grid=None
with context:
for start in range(0,10000,batch):
count=min(batch,10000-start)
samples=ancestral_samples(model,count,beta,alpha,abar,variance,seed+start,device)
pixels=((samples.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
if grid is None: 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)
del samples,pixels,images,features
if start % 1024 == 0:
print("evaluación",label,"imágenes:",min(start+count,10000),flush=True)
result=feature_fid(np.concatenate(chunks),mean,cov)
output[label]={"fid":result,"grid":grid}
output["protocol"]={"samples":10000,"seed":seed,"batch":batch,"variance":variance,
"train_sha256":record["train_sha256"],
"extractor_sha256":record["extractor_sha256"]}
return output
finally:
del mean,cov,extractor
torch.cuda.empty_cache()
print("Evaluación definida: FID de 10000 muestras por variante (pesos actuales y EMA).")
sample=np.array([[-1.,0.],[1.,0.]])
check=feature_fid(sample,torch.zeros(2,dtype=torch.float64),torch.eye(2,dtype=torch.float64))
expected=4-2*np.sqrt(2)
assert np.isclose(check,expected,atol=1e-10)
print("FID de control con covarianza singular:",check)npm run lab and open the connection link.Each batch uses a seed derived from the same base; when repeating with EMA, exactly the same seeds and shapes are restored. Changing batch size changes that sequence and must be recorded in the protocol. Evaluation adds ancestral noise at every step except the last. Grids illustrate the first samples and do not replace the full set used for FID.
The program selects checkpoints by EMA FID and retains live-weight FID too. A small difference may reflect the finite generated image set; paired seeds reduce one source of variation but do not turn one evaluation into a statistical test. Choosing the minimum across measurements reuses the same evidence. A final report should reevaluate the selected checkpoint with new seeds and state that the training reference is not a memorization audit.
Training and resumption
The full recipe below uses 200.000 updates (200,000), microbatch 32, Adam, random horizontal flip, linear schedule and bf16 mixed precision. Schedule can change via P07_L03_SCHEDULE to cosine and variance via P07_L03_VARIANCE to beta; defaults are linear and posterior. It saves a checkpoint every 10.000 steps (10,000) and evaluates both weight variants every 50.000 (50,000). These are experiment choices, not the paper’s: 200.000 updates of 32 images are 6.4 million examples, about 128 CIFAR-10 passes, versus Ho’s 102.4 million (2048 passes). Each evaluation is costly: each variant processes 10.000 images through 1000 reverse steps, ten million image evaluations by the U-Net in batches. The paired comparison sums both variants then runs Inception. Network calls are fewer because each processes a batch.
Mixed precision applies only to computation: weights, Adam moments and EMA reside in float32, forward runs under autocast in bfloat16 and output converts to float32 before loss. bfloat16 has the same 8 exponent bits as float32, avoiding gradient underflow and removing the need for loss scaling (GradScaler) required by float16; its 7 explicit mantissa bits instead give relative rounding error up to per operation, tolerable in activations but not a moving average with , hence retained in float32.
To budget hours, measure your GPU’s update rate per second at training batch and precision, and time to generate a full batch through 1000 steps. Each variant evaluation has 312 batches of 32 images and a final batch of 16. If is the final batch time and sums Inception and moment computation, an hour estimate is
The factor eight covers four evaluations for each of two variants. covers data reading, writes, preparation and pauses. Synchronize CUDA during measurement, include warmup and treat the estimate as load-dependent: a rate measured with another batch or without the optimizer does not characterize this experiment.
total_steps=200000
eval_interval=50000
images_per_variant=10000
eval_batch=32
print("evaluaciones de variantes:",(total_steps//eval_interval)*2)
print("lotes completos y tamaño del último:",
divmod(images_per_variant,eval_batch))
eval_images=(total_steps//eval_interval)*2*images_per_variant*1000
train_images=total_steps*32
print("evaluaciones de imagen del denoiser en FID:",eval_images)
print("imágenes procesadas en entrenamiento (adelante y atrás):",train_images)
print("cociente evaluación/entrenamiento en imágenes:",eval_images/train_images)A backward pass costs about two forward passes, so training equals about image forward passes versus for evaluations: with this protocol periodic FID consumes most of the budget. This is the practical reason to evaluate every 50.000 steps (50,000), not 10.000 (10,000), and not increase to 50.000 samples except for final evaluation.
The optional test below estimates throughput with the same network, optimizer, EMA, precision and microbatch, but uses synthetic tensors and omits image reading and corruption; it may overestimate actual training speed. To approximate reverse cost it measures a short step sequence and extrapolates to 1000; it excludes Inception extraction and FID calculation and does not exactly predict a long run. Run it without other own experiments on the GPU, with P07_L03_PROFILE=1 and the local kernel ready.
import os,time,torch
if os.environ.get("P07_L03_PROFILE")=="1":
if not torch.cuda.is_available(): raise RuntimeError("Se necesita CUDA")
device=torch.device("cuda")
net=opt=average=x=noise=t=beta=alpha=abar=None
try:
torch.manual_seed(2029)
net=DiffusionUNet().to(device).train()
opt=torch.optim.Adam(net.parameters(),lr=.0002)
average=EMA(net)
x=torch.randn(32,3,32,32,device=device)
noise=torch.randn_like(x)
t=torch.randint(1,1001,(32,),device=device)
beta,alpha,abar=make_schedule("linear",1000,device)
def update():
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
loss=F.mse_loss(net(x,t).float(),noise)
loss.backward(); opt.step(); average.update(net,.9999)
for _ in range(3): update()
torch.cuda.synchronize()
start=time.perf_counter()
for _ in range(20): update()
torch.cuda.synchronize()
rate=20/(time.perf_counter()-start)
net.eval()
def measure_sample_batch(batch):
gen=torch.Generator(device=device).manual_seed(8701)
state=torch.randn(batch,3,32,32,device=device,generator=gen)
torch.cuda.synchronize()
start=time.perf_counter()
with torch.inference_mode():
for step in range(1000,990,-1):
times=torch.full((batch,),step,device=device,dtype=torch.long)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
eps=net(state,times).float()
state=ancestral_step(state,step,eps,beta,alpha,abar,"posterior",gen)
torch.cuda.synchronize()
return (time.perf_counter()-start)*100
tau32=measure_sample_batch(32)
tau16=measure_sample_batch(16)
subtotal=(200000/rate+8*(312*tau32+tau16))/3600
print("actualizaciones/s:",rate,"estimación segundos por lote inverso de 32:",tau32,
"de 16:",tau16)
print("horas estimadas sin Inception, FID, E/S ni pausas:",subtotal)
finally:
del net,opt,average,x,noise,t,beta,alpha,abar
torch.cuda.empty_cache()
else:
print("Perfil omitido; establece P07_L03_PROFILE=1 para medirlo.")npm run lab and open the connection link.Mode smoke is a separate check of 20 updates with microbatch 4 and no FID. It detects integration errors and checks resume; it does not replace full training or assert quality. To run either mode, set P07_L03_OUT to a new absolute directory, P07_L02_REF to the directory produced in p07-l02, P07_L03_MODE to smoke or full and P07_L03_RUN=1 before starting the local kernel. Use the p07-l02 environment and PYTHONPATH. Training downloads the same CIFAR revision if needed.
For example, from the project root in PowerShell, if you retained directory p07-evaluacion from the previous lesson:
$env:P07_L02_REF=(Resolve-Path ./p07-evaluacion).Path
$env:PYTHONPATH=Join-Path $env:P07_L02_REF "vendor"
$env:P07_L03_OUT=Join-Path (Get-Location) "p07-entrenamiento"
$env:P07_L03_MODE="full"
$env:P07_L03_RUN="1"
npm run lab
The output directory of that first run must contain no prior logs or checkpoints. Use another directory for an smoke test. Stopping and restarting the kernel does not itself activate resumption: explicitly specify the chosen checkpoint.
Checkpoints contain network, EMA, optimizer, step, data-selection generator and CPU and CUDA random states. Configuration also records the SHA-256 fingerprint of local MDX code cells, and resumption requires matching fingerprints. This identifies the file read but does not prove nobody modified code in the editor before execution. The experiment log, events.json, records configuration, environment (versions and GPU), per-band losses, each evaluation with protocol and checkpoint list with fingerprints.
To limit disk use, all evaluated checkpoints and the two latest resume checkpoints are retained. Only after saving and recording a new checkpoint can previous checkpoints created by that run be removed: the manifest records their name and SHA-256, and code checks both before deleting. Files without their own entry or whose contents changed are retained. Before writing, free space is checked for checkpoint plus extra reserve; free space may change if other sessions use the disk.
To resume, set P07_L03_RESUME to the absolute path of the latest checkpoint from the same run and retain its output directory. Before discarding records after that point, the code saves a log copy; a failure between checkpoints thus does not leave a curve with duplicate steps. If evaluation is interrupted, the preceding checkpoint repeats it. The sequence reproduces under the same versions and deterministic conditions; different kernel implementations can introduce numerical differences. Load only your own or trusted checkpoints.
To test recovery in smoke mode, set P07_L03_STOP_AFTER=15: the check ends after logging step 15, with latest checkpoint at step 10. Then disable that variable and resume from the step-10 file. The original log is retained and the active curve regenerated from checkpoint. This check does not stop or reduce the full configuration.
import os, json, pathlib, uuid, hashlib, importlib.metadata, re, shutil
import numpy as np
import torch
import torch.nn.functional as F
def save_json_atomic(path,value):
temporary=path.with_name(path.name+"."+uuid.uuid4().hex+".tmp")
try:
temporary.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding="utf-8")
os.replace(temporary,path)
finally:
temporary.unlink(missing_ok=True)
def checkpoint_digest(path):
with path.open("rb") as f:
return hashlib.file_digest(f,"sha256").hexdigest()
def prune_owned_checkpoints(output,entries,owner,keep=2):
if keep<1: raise ValueError("Debe conservarse al menos un checkpoint")
output=pathlib.Path(output).resolve()
eligible=sorted((entry for entry in entries
if entry.get("owner")==owner and entry["kind"]=="before"
and not entry.get("removed",False)),key=lambda e:e["step"])
for entry in eligible[:-keep]:
name=entry["name"]
if pathlib.Path(name).name!=name or not name.startswith("checkpoint-"):
raise ValueError("Nombre de checkpoint no autorizado")
path=output/name
if path.is_symlink() or path.parent.resolve()!=output:
raise ValueError("Ruta de checkpoint no autorizada")
if path.exists():
if checkpoint_digest(path)!=entry["sha256"]:
raise ValueError("Checkpoint modificado; no se elimina")
path.unlink()
entry["removed"]=True
def tensor_bytes(value):
if torch.is_tensor(value): return value.numel()*value.element_size()
if isinstance(value,dict): return sum(tensor_bytes(x) for x in value.values())
if isinstance(value,(tuple,list)): return sum(tensor_bytes(x) for x in value)
return 0
def lesson_source_fingerprints():
override=os.environ.get("P07_L03_SOURCE")
if override:
path=pathlib.Path(override)
else:
here=pathlib.Path.cwd().resolve()
candidates=[parent/"src/content/lessons/p07/l03-ddpm-en-cifar10.mdx"
for parent in (here,*here.parents)]
path=next((candidate for candidate in candidates if candidate.is_file()),None)
if path is None or not path.is_file():
raise FileNotFoundError("Indica el MDX local con P07_L03_SOURCE")
source=path.read_text(encoding="utf-8")
fence=chr(96)*3
blocks=re.findall(r"(?m)^"+fence+r"python run[^\n]*\n([\s\S]*?)^"+fence,source)
markers={"unet":"class DiffusionUNet","ema":"class EMA:",
"sampler":"def ancestral_step","fid":"def load_fid_reference",
"training":"def run_ddpm"}
result={}
for name,marker in markers.items():
matches=[block for block in blocks
if marker in block and (name=="training" or "def run_ddpm" not in block)]
if len(matches)!=1:
raise ValueError("No hay una única celda de "+name)
result[name]=hashlib.sha256(matches[0].encode("utf-8")).hexdigest()
return result
def run_ddpm(mode,output,reference,resume=None):
from datasets import load_dataset
if mode not in ("smoke","full"):
raise ValueError("Modo desconocido")
if not torch.cuda.is_available():
raise RuntimeError("La receta está configurada para CUDA")
output,reference=pathlib.Path(output),pathlib.Path(reference)
if not output.is_absolute() or not reference.is_absolute():
raise ValueError("Las rutas deben ser absolutas")
output.mkdir(parents=True,exist_ok=True)
events_path=output/"events.json"
if resume is None and (events_path.exists() or list(output.glob("checkpoint-*.pt"))):
raise FileExistsError("Elige un directorio nuevo o reanuda un checkpoint existente")
cfg={"mode":mode,"batch":4 if mode=="smoke" else 32,
"steps":20 if mode=="smoke" else 200000,"diffusion_steps":1000,
"schedule":os.environ.get("P07_L03_SCHEDULE","linear"),"lr":.0002,"ema_decay":.9999,
"log_every":5 if mode=="smoke" else 100,
"checkpoint_every":10 if mode=="smoke" else 10000,
"eval_every":None if mode=="smoke" else 50000,
"variance":os.environ.get("P07_L03_VARIANCE","posterior"),"seed":2029,"eval_seed":8701,
"dataset_revision":"0b2714987fa478483af9968de7c934580d0bb9a2",
"source_fingerprints":lesson_source_fingerprints()}
if cfg["schedule"] not in ("linear","cosine") or cfg["variance"] not in ("posterior","beta"):
raise ValueError("Calendario o varianza no admitidos")
torch.manual_seed(cfg["seed"])
cpu_generator=torch.Generator(device="cpu").manual_seed(cfg["seed"]+1)
device=torch.device("cuda")
net=opt=ema=images=beta=alpha=abar=None
x=t=noise=scale=noisy=predicted=per_example=loss=None
try:
data=load_dataset("uoft-cs/cifar10",revision=cfg["dataset_revision"],
cache_dir=str(reference/"cache"/"datasets"),split="train")
if len(data)!=50000:
raise ValueError("Partición CIFAR inesperada")
images=np.stack([np.asarray(im.convert("RGB")) for im in data["img"]])
cfg["train_images_sha256"]=hashlib.sha256(images.tobytes()).hexdigest()
net=DiffusionUNet().to(device).train()
opt=torch.optim.Adam(net.parameters(),lr=cfg["lr"])
ema=EMA(net)
beta,alpha,abar=make_schedule(cfg["schedule"],cfg["diffusion_steps"],device)
start=0
pending=False
if resume:
saved=torch.load(resume,map_location="cpu",weights_only=True)
if saved["config"]!=cfg or pathlib.Path(saved["output"]).resolve()!=output.resolve():
raise ValueError("El checkpoint no corresponde a esta configuración, código y carpeta")
net.load_state_dict(saved["model"],strict=True)
opt.load_state_dict(saved["optimizer"])
ema.load_state_dict(saved["ema"])
cpu_generator.set_state(saved["data_rng"].cpu())
torch.set_rng_state(saved["cpu_rng"].cpu())
torch.cuda.set_rng_state(saved["cuda_rng"].cpu(),device)
start=int(saved["step"]); pending=bool(saved["pending_eval"])
del saved
events=json.loads(events_path.read_text(encoding="utf-8"))
later=[p for p in output.glob("checkpoint-*.pt")
if int(p.name.split("-")[1])>start]
if later:
raise ValueError("Hay checkpoints posteriores; reanuda el más reciente")
if pending and (output/f"checkpoint-{start:07d}-evaluated.pt").exists():
raise ValueError("La evaluación ya terminó; reanuda el checkpoint evaluado")
backup=output/("events-before-resume-"+uuid.uuid4().hex+".json")
with backup.open("x",encoding="utf-8") as f:
json.dump(events,f,ensure_ascii=False,indent=2)
events["records"]=[r for r in events["records"]
if r["step"]<start or
(r["step"]==start and not (pending and r["kind"]=="fid"))]
candidates=[r for r in events["records"] if r["kind"]=="fid"]
if candidates:
events["selected_step"]=min(candidates,key=lambda r:r["ema"]["fid"])["step"]
else:
events.pop("selected_step",None)
save_json_atomic(events_path,events)
else:
events={"schema":"p07-ddpm-v1","config":cfg,"records":[],"checkpoints":[],
"run_id":uuid.uuid4().hex,
"retention":"todos los evaluados y dos últimos before",
"environment":{"torch":torch.__version__,"numpy":np.__version__,
"datasets":importlib.metadata.version("datasets"),
"cuda":torch.version.cuda,"gpu":torch.cuda.get_device_name(device)}}
save_json_atomic(events_path,events)
def checkpoint(step,pending_eval,suffix):
path=output/f"checkpoint-{step:07d}-{suffix}.pt"
if path.exists():
raise FileExistsError("El checkpoint ya existe: "+str(path))
temp=path.with_name(path.name+"."+uuid.uuid4().hex+".tmp")
state={"config":cfg,"output":str(output.resolve()),"step":step,
"pending_eval":pending_eval,"model":net.state_dict(),
"optimizer":opt.state_dict(),"ema":ema.state_dict(),
"data_rng":cpu_generator.get_state(),"cpu_rng":torch.get_rng_state(),
"cuda_rng":torch.cuda.get_rng_state(device)}
try:
needed=int(tensor_bytes(state)*1.05)+64*1024**2
if shutil.disk_usage(output).free < needed+1024**3:
raise OSError("Espacio insuficiente para checkpoint y reserva de 1 GiB")
with temp.open("xb") as f:
torch.save(state,f)
os.link(temp,path)
entry={"owner":events["run_id"],"name":path.name,"kind":suffix,
"step":step,"sha256":checkpoint_digest(path),"removed":False}
events["checkpoints"].append(entry)
save_json_atomic(events_path,events)
prune_owned_checkpoints(output,events["checkpoints"],events["run_id"],keep=2)
save_json_atomic(events_path,events)
finally:
temp.unlink(missing_ok=True)
del state
print("checkpoint:",path,flush=True)
def do_eval(step):
values=evaluate_fid(net,ema,beta,alpha,abar,cfg["variance"],reference,
device,seed=cfg["eval_seed"],batch=cfg["batch"])
events["records"]=[r for r in events["records"] if not (r["kind"]=="fid" and r["step"]==step)]
events["records"].append({"kind":"fid","step":step,**values})
candidates=[r for r in events["records"] if r["kind"]=="fid"]
events["selected_step"]=min(candidates,key=lambda r:r["ema"]["fid"])["step"]
save_json_atomic(events_path,events)
print("FID",step,"vivo:",values["live"]["fid"],"EMA:",values["ema"]["fid"],flush=True)
if pending:
do_eval(start)
checkpoint(start,False,"evaluated")
sums=np.zeros(4,dtype=np.float64); counts=np.zeros(4,dtype=np.int64)
for step in range(start+1,cfg["steps"]+1):
indices=torch.randint(len(images),(cfg["batch"],),generator=cpu_generator)
flip=torch.rand(cfg["batch"],generator=cpu_generator)<.5
t_cpu=torch.randint(1,cfg["diffusion_steps"]+1,(cfg["batch"],),generator=cpu_generator)
x=torch.from_numpy(images[indices.numpy()].copy()).permute(0,3,1,2).to(device).float()/127.5-1
x=torch.where(flip.to(device)[:,None,None,None],x.flip(-1),x)
t=t_cpu.to(device)
noise=torch.randn_like(x)
scale=abar[t][:,None,None,None]
noisy=scale.sqrt()*x+(1-scale).sqrt()*noise
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
predicted=net(noisy,t).float()
per_example=(predicted-noise).square().mean(dim=(1,2,3))
loss=per_example.mean()
loss.backward()
opt.step()
ema.update(net,cfg["ema_decay"])
bands=((t_cpu-1)*4//cfg["diffusion_steps"]).numpy()
sample_losses=per_example.detach().cpu().numpy()
for band in range(4):
mask=bands==band
sums[band]+=float(sample_losses[mask].sum())
counts[band]+=int(mask.sum())
x=t=noise=scale=noisy=predicted=per_example=loss=None
if step%cfg["log_every"]==0:
record={"kind":"loss","step":step,"counts":counts.tolist(),
"bands":[float(sums[k]/counts[k]) if counts[k] else None for k in range(4)]}
events["records"].append(record)
save_json_atomic(events_path,events)
print("pérdida por bandas:",json.dumps(record),flush=True)
sums[:]=0;counts[:]=0
due=cfg["eval_every"] is not None and step%cfg["eval_every"]==0
if step%cfg["checkpoint_every"]==0:
checkpoint(step,due,"before")
if due:
do_eval(step)
checkpoint(step,False,"evaluated")
if mode=="smoke" and os.environ.get("P07_L03_STOP_AFTER")=="15" and step==15:
print("Control de interrupción en el paso",step,"reanuda desde el checkpoint anterior.")
return
print("fin del modo",mode,"pasos completados:",cfg["steps"],
"FID:", "no se calcula en smoke" if mode=="smoke" else "registrado en events.json")
finally:
del net,opt,ema,images,beta,alpha,abar,x,t,noise,scale,noisy,predicted,per_example,loss
torch.cuda.empty_cache()
if os.environ.get("P07_L03_RUN")=="1":
run_ddpm(os.environ["P07_L03_MODE"],os.environ["P07_L03_OUT"],
os.environ["P07_L02_REF"],os.environ.get("P07_L03_RESUME"))
else:
print("Entrenamiento omitido; configura P07_L03_RUN y las rutas indicadas.")npm run lab and open the connection link.To inspect the log without retraining, set P07_L03_SHOW=1 and P07_L03_OUT to the output directory. Reading displays figures and protocol; checkpoint files remain necessary to reproduce or continue the run.
import os,json,pathlib
if os.environ.get("P07_L03_SHOW")=="1":
path=pathlib.Path(os.environ["P07_L03_OUT"])
events=json.loads((path/"events.json").read_text(encoding="utf-8"))
if events["schema"]!="p07-ddpm-v1":
raise ValueError("Registro incompatible")
print("configuración:",json.dumps(events["config"],ensure_ascii=False))
print("entorno:",json.dumps(events["environment"],ensure_ascii=False))
records=events["records"] if events["config"]["mode"]=="smoke" else events["records"][-4:]
for record in records:
if record["kind"]=="loss":
print("pérdida:",json.dumps(record,ensure_ascii=False))
elif record["kind"]=="fid":
print("FID:",record["step"],"vivo:",record["live"]["fid"],
"EMA:",record["ema"]["fid"],"protocolo:",json.dumps(record["protocol"]))
print("checkpoint seleccionado por FID EMA:",events.get("selected_step","ninguno (sin evaluaciones FID)"))
else:
print("Lectura omitida; establece P07_L03_SHOW=1.")npm run lab and open the connection link.The opening panel shows a real smoke 20-step run on CIFAR-10, on a laptop RTX 4060: four blocks of per-band losses, without FID or images. With five updates of four images per block, each band averages 2 to 9 examples, explaining the irregular curves. Still, the expected pattern appears: band 1 starts at 2.01 and ends at 0.48, above the others (0.10 to 0.15 at step 20). This checks the circuit, not quality. With default configuration, the full run log has 2000 loss blocks and four evaluations at steps 50.000, 100.000, 150.000 and 200.000 (50,000 through 200,000); load it into the panel to see both variants’ FID-10k curves and paired grids.
What numbers should you expect? Sources cannot predict a number for this configuration, though they give context. Ho’s 3.17 uses 16 times more training examples, dropout, 50.000 samples (50,000) and the training minimum; with 200.000 updates (200,000) of 32 images your final FID-10k will be clearly above it and likely still decreasing between the third and fourth evaluations. Also FID with 10.000 samples (10,000) is biased upward relative to 50.000: row of fid_results.json’s size study (p07-l02) suggests the finite-sampling floor even between two real-data samples. According to Song and Ermon, EMA should yield a more stable curve and, after the first -update window, samples without the live weights’ shared color shift. Check both in paired grids.
To check resumption exactly reproduces a continuous run, perform the interruption at step 15 described above and also a continuous smoke run in another directory. Set P07_L03_OUT to the resumed run directory, P07_L03_CONTROL to the continuous one and P07_L03_COMPARE=1. The check requires exact equality for what resumption must restore without intervening arithmetic: configuration, step, CPU, CUDA and data-selection random states, and log steps and counts. For model, EMA and Adam tensors and logged losses it prints maximum difference. Zero indicates bitwise equality. A difference on the order of float32 rounding does not reveal a resume failure but nondeterministic kernels (some cuDNN algorithms and attention backpropagation accumulate in variable order); to eliminate it enable torch.use_deterministic_algorithms(True) with CUBLAS_WORKSPACE_CONFIG=:4096:8 in both runs at a speed cost. A failure in random states or steps does indicate incomplete restoration.
import os,pathlib,json,torch
if os.environ.get("P07_L03_COMPARE")=="1":
resumed=pathlib.Path(os.environ["P07_L03_OUT"])
control=pathlib.Path(os.environ["P07_L03_CONTROL"])
a=torch.load(resumed/"checkpoint-0000020-before.pt",map_location="cpu",weights_only=True)
b=torch.load(control/"checkpoint-0000020-before.pt",map_location="cpu",weights_only=True)
def max_diff(x,y):
inf=float("inf")
if torch.is_tensor(x):
if not torch.is_tensor(y) or x.shape!=y.shape or x.dtype!=y.dtype: return inf
if x.is_floating_point() and x.numel():
return float((x.double()-y.double()).abs().max())
return 0. if torch.equal(x,y) else inf
if isinstance(x,dict):
if not isinstance(y,dict) or x.keys()!=y.keys(): return inf
return max([max_diff(x[k],y[k]) for k in x],default=0.)
if isinstance(x,(list,tuple)):
if not isinstance(y,(list,tuple)) or len(x)!=len(y): return inf
return max([max_diff(u,v) for u,v in zip(x,y)],default=0.)
if isinstance(x,float) and isinstance(y,float): return abs(x-y)
return 0. if x==y else inf
for key in ("data_rng","cpu_rng","cuda_rng","config","step"):
ok=max_diff(a[key],b[key])==0
print(key,"idéntico:",ok)
assert ok
for key in ("model","ema","optimizer"):
print(key,"diferencia máxima:",max_diff(a[key],b[key]))
first=json.loads((resumed/"events.json").read_text(encoding="utf-8"))
second=json.loads((control/"events.json").read_text(encoding="utf-8"))
shape=lambda log:[(r["kind"],r["step"],r.get("counts")) for r in log["records"]]
assert shape(first)==shape(second)
print("pérdidas, diferencia máxima:",
max(abs(u-v) for r,s in zip(first["records"],second["records"])
for u,v in zip(r["bands"],s["bands"]) if u is not None))
backups=list(resumed.glob("events-before-resume-*.json"))
assert backups
histories=[[r["step"] for r in json.loads(p.read_text(encoding="utf-8"))["records"]]
for p in backups]
assert [5,10,15] in histories
print("pasos activos:",[r["step"] for r in first["records"]],
"copia anterior:",[5,10,15])
del a,b
else:
print("Comparación omitida; establece P07_L03_COMPARE=1.")npm run lab and open the connection link.Common mistakes
Exercises
import contextlib
import torch
class EMA:
def __init__(self, model):
pass
def update(self, model, decay):
pass
@contextlib.contextmanager
def applied(self, model):
yield modelNoise prediction, EMA and ancestral sampling are distinct parts of the experiment. A resumable checkpoint retains weights, optimizer and randomness; an FID comparison also retains extractor, split, seeds and sample count. A short run verifies the mechanism, not generative quality.