Generative evaluation and the U-Net
Build a reproducible CIFAR-10 generative evaluation pipeline, analyze FID and KID, and implement and profile a time-conditioned diffusion U-Net.
After this lesson you can
- Compute stable Fréchet distances and explain finite-sample bias.
- Compare FID, KID, precision and recall under a fixed protocol.
- Extract and verify reference features and statistics.
- Explain the time-conditioned U-Net and its attention costs.
- Measure training compute and memory under stated conditions.
Before you start
- P07Toy 2D diffusion
- 19Fréchet Inception DistanceKernel Inception DistancePrecision and recall for generative modelsDiffusion U-NetNoise level conditioning
- 16Discrete 2D convolution and cross-correlationResidual block and shortcut connectionU-Net and skip connections
- 15Group and instance normalizationNormalization axes taxonomy
- 02Matrix square root
A number needs a protocol
In the previous lesson’s two-dimensional mixture we could calculate the exact score. For images, we generally lack the true density or an oracle. Comparing two image sets requires choosing a representation and statistic, fixing sample collection, and measuring uncertainty. No single number replaces image inspection or proves a generator does not memorize.
The generative evaluation pipeline (the fixed chain from images to metrics) transforms real and generated images with the same preprocessing and extractor, retains reference statistics and computes several metrics. This lesson establishes that contract before training the DDPM. The reference is CIFAR-10: its official splits contain 50 000 training and 10 000 test images, as documented by the original dataset source. Training and test statistics answer different questions and are not silently interchanged: the same DDPM of Ho and colleagues gets FID 3.17 against training, standard practice on CIFAR-10, and 5.24 against test.
The study by Parmar and colleagues illustrates why preprocessing is part of the metric. Their table 1 takes the same real FFHQ images, reduces them from 1024 to 299 pixels using PIL bicubic (reference) and other functions, and measures FID between versions: PIL bilinear gives 0.64; PyTorch bilinear, which produces aliasing, 4.36. For StyleGAN2 images FID against that reference changes from 2.98 to 7.45 solely by changing generated-image resizing. These numbers apply to particular versions and settings, not constants of current libraries, but the scale suffices: preprocessing generated images, without touching the model, multiplies FID by 2.5.
The interactive above anticipates another variation source, sample size: it compares two resamples of the same real data, whose population distance is zero, yet FID is 25.7 with 2000 images per side and 5.24 with 10 000: more than Ho’s DDPM result 3.17, the gray dashed line. On a log–log scale the three means nearly lie on a line of slope −1, the signature of a term . We return to it with theory.
Fréchet distance between features
FID from Heusel and colleagues approximates feature distributions by Gaussians with means and covariances . Squared Fréchet distance between those Gaussians is
Matrix is symmetric positive semidefinite (for any , with ), so its root is the matrix square root by eigendecomposition, not the elementwise root. The expression is often written with and the trace is the same: with and , products and have the same nonzero eigenvalues with the same multiplicity even if is singular. Those eigenvalues are real and nonnegative, and the FID term is . But is generally not symmetric, and a generic root algorithm cannot exploit symmetry. SciPy sqrtm used by clean-fid starts from a Schur decomposition; its result can be complex with rounding-sized imaginary parts (clean-fid checks they are small and discards them), and if the root is nonfinite because the product is nearly singular, clean-fid adds to both covariance diagonals, regularization announced only by a message. The symmetric formulation needs only eigh and treats singularity explicitly. Estimated covariances can be singular: with centered observations their rank is at most even in a higher-dimensional space. A tiny negative eigenvalue due to rounding may be set to zero after checking its scale; a significant negative signals invalid inputs.
The two terms help interpret the number. The first measures mean displacement in extractor space. The second compares dispersion and correlations, not merely coordinate variances: rotating variation directions can also change it. In one dimension the covariance part reduces to squared difference of standard deviations. In multiple dimensions replacing matrix product with diagonal product would ignore correlations.
The Gaussian fit simplifies features; it does not claim real images form a Gaussian. A different extractor redefines the comparison space. Thus “CIFAR FID” is insufficient: record network and weights, processing version, image format, split, samples and root implementation. With a stored reference, also retain the number of observations producing its moments and the data fingerprint.
import numpy as np
def psd_eigh(matrix, rtol=1e-8):
matrix = np.asarray(matrix,dtype=float)
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
raise ValueError("Se necesita una matriz cuadrada")
if not np.allclose(matrix,matrix.T,rtol=rtol,atol=rtol):
raise ValueError("La covarianza debe ser simétrica")
values,vectors = np.linalg.eigh((matrix+matrix.T)/2)
if values.min() < -rtol*max(1.,float(np.max(np.abs(values)))):
raise ValueError("La covarianza no es semidefinida positiva")
return np.maximum(values,0),vectors
def frechet_distance(mu1,s1,mu2,s2):
mu1,mu2 = np.asarray(mu1),np.asarray(mu2)
a,u = psd_eigh(s1)
psd_eigh(s2)
root = (u*np.sqrt(a))@u.T
middle = [email protected](s2)@root
eigen,_ = psd_eigh(middle)
value = float(np.sum((mu1-mu2)**2)+np.trace(s1)+np.trace(s2)-2*np.sqrt(eigen).sum())
if value < -1e-7*max(1.,float(np.trace(s1)+np.trace(s2))):
raise ArithmeticError("Resultado negativo fuera de tolerancia")
return max(0.,value)
s1=np.diag([1.,0.])
s2=np.diag([9.,0.])
print("FID gaussiano con covarianzas singulares:",frechet_distance([0,0],s1,[1,0],s2))
print("FID del conjunto consigo mismo:",frechet_distance([0,0],s1,[0,0],s1))The tolerance prevents treating rounding as negative variance; it is not undisclosed added regularization. In large dimensions the decomposition costs memory and computation. The code retains double-precision accumulators: subtracting large terms can lose precision in a shorter representation. The symmetric root and reference implementation should be compared numerically on the same features.
In practice we do not know or : we substitute sample mean and covariance of images, and published FID is estimator . It has positive bias, demonstrated without calculation in the extreme case. If distributions match, population FID is ; the estimator is always , being squared Fréchet distance between two Gaussians, and is only if samples have exactly equal means and covariances. With independent samples this does not happen with probability one (for a continuous distribution it has probability zero; for resamples of a finite set, as in the interactive, tiny probability). A nonnegative variable positive with positive probability has positive expectation: , and everything the interactive measures is bias.
How large is it? The mean term is exact. If and are means of independent observations from a distribution with covariance , has mean and covariance , and
The covariance term has bias of the same order to first approximation, but much larger in high dimension: is unbiased, whereas the two estimated covariances have independent errors, their principal directions differ and the trace of the root of falls below that of . With features and images there is not even full rank: each sample covariance has rank at most . The resulting model is
with constant depending on both distributions. Chong and Forsyth check this empirically and draw two conclusions: since depends on the generator, matching in two evaluations aids comparison but does not eliminate bias differences; fitting a line in at several can extrapolate to , which they call . A mean and deviation from repeated draws quantify observed variation under that procedure; they are not automatically a population confidence interval.
Two variation sources should not be mixed. Fixing one image set and changing only resamples measures sensitivity conditional on that empirical set. Retraining a generator with another seed also changes the model and output distribution. To compare methods, predefine both levels, record seeds and avoid retrospectively choosing the run with best FID. A single result in the favorable tail does not itself represent typical behavior.
KID and coverage: other questions
The previous lesson used MMD² to compare a known mixture. KID applies the unbiased MMD² estimator to features with polynomial kernel . Pairs of a point with itself are excluded from both within-set terms; all cross pairs are retained. Bińkowski and colleagues describe this estimator. One realization may be negative: an estimator fluctuation, not negative population MMD².
def kid_unbiased(x,y):
x,y=np.asarray(x,float),np.asarray(y,float)
if min(len(x),len(y))<2 or x.shape[1]!=y.shape[1]:
raise ValueError("Se necesitan dos muestras y dimensión común")
d=x.shape[1]
xx=([email protected]/d+1)**3; yy=([email protected]/d+1)**3; xy=([email protected]/d+1)**3
n,m=len(x),len(y)
return float((xx.sum()-np.trace(xx))/(n*(n-1))+
(yy.sum()-np.trace(yy))/(m*(m-1))-2*xy.mean())
def precision_recall(real,generated,k=3):
real,generated=np.asarray(real,float),np.asarray(generated,float)
if k<1 or min(len(real),len(generated))<=k:
raise ValueError("k debe ser menor que los dos tamaños")
def distance(a,b):
squared=(a*a).sum(1)[:,None]+(b*b).sum(1)[None,:]-2*[email protected]
return np.sqrt(np.maximum(0,squared))
def radii(x):
d=distance(x,x)
np.fill_diagonal(d,np.inf)
return np.partition(d,k-1,axis=1)[:,k-1]
cross=distance(real,generated)
precision=np.mean((cross<=radii(real)[:,None]).any(axis=0))
recall=np.mean((cross<=radii(generated)[None,:]).any(axis=1))
return float(precision),float(recall)
rng=np.random.default_rng(71)
real=rng.normal(size=(100,3))
generated=rng.normal(loc=.5,size=(100,3))
print("ejemplo sintético KID:",kid_unbiased(real,generated))
print("ejemplo sintético precisión y exhaustividad, k=3:",precision_recall(real,generated,3))Precision and recall proposed by Kynkäänniemi and colleagues represent each set as a union of balls in feature space. Each point’s radius reaches its -th neighbor in the same set, excluding itself. Precision is the fraction of generated images inside real balls; recall is the fraction of real images inside generated balls. They depend on , point count and extractor. They help distinguish images far from real support from lack of coverage, but are not human judgment or identification of individual memorized items.
Imagine a generator reproducing only a small plausible data region. Its points can fall inside real balls, giving high precision, while many real observations lie far from generated balls. Conversely, a widely dispersed set can cover real regions while containing points outside them. In high dimensions distances depend on representation and neighbor balls are local approximations: precision or recall is not a geometric property independent of extractor.
Expanding the kernel shows what KID compares: , so population MMD² is a weighted sum of for . It is zero exactly when all feature moments of orders 1, 2 and 3 match. This exceeds FID’s two moments and does not assume Gaussianity, but does not detect every difference: distributions with matching moments through order 3 have zero population KID. Its main advantage is statistical: the estimator is unbiased, so it does not carry the term dominating the FID table. That guarantee concerns independent samples from the distributions considered; it does not itself solve feature selection, data reuse or comparison with dependent samples. Retaining individual observations from each repetition permits recomputing means and examining spread rather than keeping only the best number.
A favorable FID can coexist with low diversity or training copies. FID compares only first and second moments in the chosen representation: different distributions can share them. Auditing memorization also requires nearest-neighbor searches, data separation and duplicate analysis.
Extracting CIFAR-10 features
Mode clean of clean-fid resizes each floating-point channel with PIL bicubic, clips the result to [0, 255] and uses NVIDIA’s distributed TorchScript Inception. It is not interchangeable with torchvision Inception or another resizing mode. The cell uses the same clean-fid function pair and calculates statistics and metrics separately. Weights must be in a directory you control; clean-fid can download them there. Pin library versions, data revision and extractor fingerprint before comparing runs.
The project lab starts Python from .venv, so creating another environment does not automatically change its interpreter. This recipe assumes .venv already contains CUDA-compatible PyTorch and torchvision, NumPy, Pillow and datasets. Add clean-fid and SciPy to an isolated directory and put it in PYTHONPATH before starting the lab. Version scipy==1.17.1 retains the root interface used by clean-fid 0.1.35; SciPy 1.18.1 no longer accepts argument disp and fails even for identity.
New-Item -ItemType Directory -Force ./p07-evaluacion | Out-Null
$env:P07_WORK=(Resolve-Path ./p07-evaluacion).Path
$env:PYTHONPATH=Join-Path $env:P07_WORK "vendor"
.\.venv\Scripts\python.exe -m pip install --no-deps --target $env:PYTHONPATH clean-fid==0.1.35 scipy==1.17.1
$env:P07_EXTRACT="1"; $env:P07_ANALYZE="1"; $env:P07_SHOW_RESULTS="1"
$env:P07_KID_VERIFY="1"; $env:P07_BENCH="1"
npm run lab
Dependency-free installation does not modify .venv, but clean-fid also needs tqdm and requests, which must already be in .venv. P07_WORK must be an absolute path with sufficient space (features occupy about 500 MB). Each variable activates a cell: P07_EXTRACT extracts features, P07_ANALYZE calculates reference and size study, P07_SHOW_RESULTS rereads the saved table, P07_KID_VERIFY checks KID, and P07_BENCH measures the network; run cells in order. The lab server inherits variables from the console where it starts and passes them to kernels: to change one, stop npm run lab, change it and restart (restarting only the kernel is insufficient). Extraction is skipped if both feature files exist, so repeating the sequence does not redo it. Data (about 130 MB) and Inception weights (about 100 MB) download if absent; respect their terms. Code shows fingerprints and versions and stores features separately by split.
import os, json, hashlib, pathlib, sys, importlib.metadata
import numpy as np
import torch
work_env = os.environ.get("P07_WORK","")
already = bool(work_env) and all((pathlib.Path(work_env)/(s+"_features.npy")).exists() for s in ("train","test"))
if os.environ.get("P07_EXTRACT") == "1" and already:
print("Características ya extraídas en",work_env,"; bórralas si quieres repetir la extracción.")
elif os.environ.get("P07_EXTRACT") == "1":
from datasets import load_dataset
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
if not os.environ.get("P07_WORK") or not pathlib.Path(os.environ["P07_WORK"]).is_absolute():
raise ValueError("P07_WORK debe ser un directorio absoluto elegido para esta prueba")
work = pathlib.Path(os.environ["P07_WORK"])
if not torch.cuda.is_available():
raise RuntimeError("Esta extracción está configurada para CUDA")
work.mkdir(parents=True,exist_ok=True)
revision = "0b2714987fa478483af9968de7c934580d0bb9a2"
data = load_dataset("uoft-cs/cifar10",revision=revision,cache_dir=str(work/"cache"/"datasets"))
assert len(data["train"])==50000 and len(data["test"])==10000
resize = build_resizer("clean")
model = batch = None
try:
model = InceptionV3W(str(work),download=True).eval().cuda()
weight_path=work/"inception-2015-12-05.pt"
print("dataset uoft-cs/cifar10 revisión solicitada:",revision)
print("sha256 extractor:",hashlib.sha256(weight_path.read_bytes()).hexdigest())
print("versiones:",{p:importlib.metadata.version(p) for p in
("torch","torchvision","numpy","scipy","Pillow","datasets","clean-fid")})
with torch.inference_mode():
for split in ("train","test"):
chunks=[]
for start in range(0,len(data[split]),32):
images=[resize(np.asarray(im.convert("RGB"))) for im in data[split][start:start+32]["img"]]
batch=torch.from_numpy(np.stack(images).transpose(0,3,1,2)).cuda()
chunks.append(model(batch).cpu().numpy())
del batch
if start % 3200 == 0:
print(split,"imágenes procesadas:",min(start+32,len(data[split])),flush=True)
features=np.concatenate(chunks)
np.save(work/(split+"_features.npy"),features)
print(split,"características:",features.shape,
"sha256:",hashlib.sha256((work/(split+"_features.npy")).read_bytes()).hexdigest())
del features,chunks
finally:
for name in ("model","batch"):
globals().pop(name,None)
torch.cuda.empty_cache()
else:
print("Extracción omitida; establece P07_EXTRACT=1 y P07_WORK para ejecutarla.")npm run lab and open the connection link.The Hub replica may order images differently from the original archive. To check content without requiring the same order, the next check compares multisets of pixel and label hashes by split. Download the official CIFAR-10 archive from the dataset page, set its absolute path in P07_CIFAR_TAR and enable P07_VERIFY_CIFAR=1. MD5 is checked against that published in torchvision code to detect a damaged download; the content check uses SHA-256.
import os,tarfile,pickle,hashlib,collections
import numpy as np
if os.environ.get("P07_VERIFY_CIFAR") == "1":
from datasets import load_dataset
path=os.environ["P07_CIFAR_TAR"]
if not os.path.isabs(path):
raise ValueError("P07_CIFAR_TAR debe ser una ruta absoluta")
with open(path,"rb") as f:
digest=hashlib.file_digest(f,"md5").hexdigest()
if digest != "c58f30108f718f92721af3b95e74349a":
raise ValueError("El archivo no coincide con el MD5 publicado")
work=os.environ["P07_WORK"]
data=load_dataset("uoft-cs/cifar10",revision="0b2714987fa478483af9968de7c934580d0bb9a2",
cache_dir=os.path.join(work,"cache","datasets"))
def fingerprint(image,label):
return hashlib.sha256(np.asarray(image,dtype=np.uint8).tobytes()+bytes([label])).digest()
with tarfile.open(path,"r:gz") as tar:
for split,names in (("train",[f"data_batch_{i}" for i in range(1,6)]),("test",["test_batch"])):
original=collections.Counter()
for name in names:
item=pickle.load(tar.extractfile("cifar-10-batches-py/"+name),encoding="bytes")
pixels=item[b"data"].reshape(-1,3,32,32).transpose(0,2,3,1)
original.update(fingerprint(image,label) for image,label in zip(pixels,item[b"labels"]))
replica=collections.Counter(fingerprint(row["img"],row["label"]) for row in data[split])
print(split,"original:",sum(original.values()),"réplica:",sum(replica.values()),
"multiconjunto igual:",original==replica,flush=True)
if original != replica:
raise ValueError("La partición no coincide")
else:
print("Comprobación opcional omitida; configura P07_VERIFY_CIFAR y P07_CIFAR_TAR.")npm run lab and open the connection link.Reference statistics are computed once per split and the result file includes the feature hash. The size study draws two independent resamples with replacement from the same training set. Even in the 50 000 row an image can repeat and sides can overlap: the population is the finite empirical set, not two new independent collections. Each repetition uses different seeds; all five share the same underlying set.
The following covariance and root calculations use float64. A symmetric matrix root uses eigendecomposition and clips negative eigenvalues only within an explicit relative tolerance. CUDA computation saves time for large matrices, but memory depends on implementation and concurrent load. In the verification run on a laptop RTX 4060, extraction of 60 000 images took about 6 minutes (limited by CPU resizing, not the network) and complete analysis just over a minute, peaking at 1.7 GB GPU memory: a 50 000-feature float64 resample occupies 0.8 GB and centering creates another copy. Comparison with clean-fid uses the same means and covariances, not a different extractor or resize.
import os, json, pathlib, hashlib, importlib.metadata
import numpy as np
import torch
if os.environ.get("P07_ANALYZE") == "1":
from cleanfid.fid import frechet_distance as clean_fid
if not os.environ.get("P07_WORK") or not pathlib.Path(os.environ["P07_WORK"]).is_absolute():
raise ValueError("P07_WORK debe ser un directorio absoluto elegido para esta prueba")
work=pathlib.Path(os.environ["P07_WORK"])
if not torch.cuda.is_available():
raise RuntimeError("Esta implementación de matrices grandes usa CUDA")
def kid_unbiased(x,y):
d=x.shape[1]
xx=([email protected]/d+1)**3; yy=([email protected]/d+1)**3; xy=([email protected]/d+1)**3
n,m=len(x),len(y)
return float((xx.sum()-np.trace(xx))/(n*(n-1))+
(yy.sum()-np.trace(yy))/(m*(m-1))-2*xy.mean())
def precision_recall(real,generated,k=3):
def distance(a,b):
d2=(a*a).sum(1)[:,None]+(b*b).sum(1)[None,:]-2*[email protected]
return np.sqrt(np.maximum(0,d2))
def radii(x):
d=distance(x,x)
np.fill_diagonal(d,np.inf)
return np.partition(d,k-1,axis=1)[:,k-1]
cross=distance(real,generated)
return (float((cross<=radii(real)[:,None]).any(axis=0).mean()),
float((cross<=radii(generated)[None,:]).any(axis=1).mean()))
train=np.load(work/"train_features.npy",mmap_mode="r")
test=np.load(work/"test_features.npy",mmap_mode="r")
def file_sha256(path):
with open(path,"rb") as f:
return hashlib.file_digest(f,"sha256").hexdigest()
train_hash=file_sha256(work/"train_features.npy")
test_hash=file_sha256(work/"test_features.npy")
weight_hash=file_sha256(work/"inception-2015-12-05.pt")
versions={p:importlib.metadata.version(p) for p in
("torch","numpy","scipy","Pillow","datasets","clean-fid")}
print("SHA-256 características train:",train_hash,"test:",test_hash)
print("SHA-256 extractor:",weight_hash)
print("versiones de análisis:",versions)
if train.shape != (50000,2048) or test.shape != (10000,2048):
raise ValueError("Las particiones o la dimensión no coinciden con el protocolo")
device=torch.device("cuda")
def moments(x):
z=torch.as_tensor(np.asarray(x).copy(),device=device,dtype=torch.float64)
mean=z.mean(0)
centered=z-mean
cov=centered.T@centered/(len(z)-1)
return mean,cov
def psd_root_eigen(matrix):
matrix=(matrix+matrix.T)/2
vals,vecs=torch.linalg.eigh(matrix)
scale=max(1.,float(vals.abs().max()))
if float(vals.min()) < -1e-8*scale:
raise ValueError("Matriz no semidefinida positiva dentro de tolerancia")
return vals.clamp_min(0),vecs
def gpu_fid(m1,c1,m2,c2):
vals,vecs=psd_root_eigen(c1)
root=(vecs*vals.sqrt())@vecs.T
middle=root@c2@root
ev,_=psd_root_eigen(middle)
value=(m1-m2).square().sum()+torch.trace(c1)+torch.trace(c2)-2*ev.sqrt().sum()
number=float(value)
if number < -1e-7*max(1.,float(torch.trace(c1)+torch.trace(c2))):
raise ArithmeticError("FID negativo fuera de tolerancia")
return max(0.,number)
try:
mt,ct=moments(train)
mv,cv=moments(test)
np.savez(work/"cifar10_reference.npz",mean_train=mt.cpu().numpy(),cov_train=ct.cpu().numpy(),
mean_test=mv.cpu().numpy(),cov_test=cv.cpu().numpy(),
train_sha256=train_hash,test_sha256=test_hash)
print("referencias train y test:",work/"cifar10_reference.npz",
"SHA-256:",file_sha256(work/"cifar10_reference.npz"))
own=gpu_fid(mt,ct,mv,cv)
print("FID train frente a test, propio:",own)
ref=clean_fid(mt.cpu().numpy(),ct.cpu().numpy(),mv.cpu().numpy(),cv.cpu().numpy())
print("FID train frente a test, clean-fid:",ref,"diferencia absoluta:",abs(own-ref))
if abs(own-ref)>1e-3:
raise ArithmeticError("Las dos implementaciones de FID difieren")
rng=np.random.default_rng(390)
i=rng.choice(len(train),1000,replace=False)
j=rng.choice(len(test),1000,replace=False)
x,y=np.asarray(train[i],dtype=np.float64),np.asarray(test[j],dtype=np.float64)
kid=kid_unbiased(x,y)
p,r=precision_recall(x,y,k=3)
print("KID train/test, 1000 por lado:",kid)
print("precisión y exhaustividad train/test, 1000 por lado, k=3:",p,r)
del mt,ct,mv,cv
rows=[]
progress={"train_sha256":train_hash,"test_sha256":test_hash,
"extractor_sha256":weight_hash,"rows":rows}
for n in (2000,10000,50000):
values=[]
row={"n":n,"values":values}
rows.append(row)
for repeat in range(5):
rng=np.random.default_rng(7000+n*10+repeat)
a=rng.integers(0,len(train),n)
b=rng.integers(0,len(train),n)
m1,c1=moments(train[a])
m2,c2=moments(train[b])
value=gpu_fid(m1,c1,m2,c2)
values.append(value)
(work/"fid_progress.json").write_text(json.dumps(progress,indent=2),encoding="utf-8")
print("n",n,"repetición",repeat,"FID",value,flush=True)
del m1,c1,m2,c2
row.update(mean=float(np.mean(values)),sd=float(np.std(values,ddof=1)))
print("resumen",json.dumps(row))
result={"protocol":"cifar10-train-bootstrap-clean-fid-0.1.35",
"train_sha256":train_hash,"test_sha256":test_hash,
"extractor_sha256":weight_hash,"versions":versions,
"dataset_revision":"0b2714987fa478483af9968de7c934580d0bb9a2",
"fid_train_test":own,"clean_fid":ref,"kid_1000":kid,
"precision_1000":p,"recall_1000":r,"rows":rows}
(work/"fid_results.json").write_text(json.dumps(result,indent=2),encoding="utf-8")
print("tabla para el interactivo:",work/"fid_results.json")
finally:
for name in ("mt","ct","mv","cv","m1","c1","m2","c2"):
globals().pop(name,None)
torch.cuda.empty_cache()
else:
print("Análisis omitido; establece P07_ANALYZE=1 tras extraer ambas particiones.")npm run lab and open the connection link.Once analysis is complete, this read displays the saved table without recomputing all roots. Check fingerprints before use: the table does not replace the feature file or itself establish how features were extracted.
import os,json,pathlib,hashlib
import numpy as np
if os.environ.get("P07_SHOW_RESULTS") == "1":
work=pathlib.Path(os.environ["P07_WORK"])
result=json.loads((work/"fid_results.json").read_text(encoding="utf-8"))
for filename,key in (("train_features.npy","train_sha256"),("test_features.npy","test_sha256"),
("inception-2015-12-05.pt","extractor_sha256")):
with (work/filename).open("rb") as f:
actual=hashlib.file_digest(f,"sha256").hexdigest()
if actual!=result[key]:
raise ValueError("Huella distinta: "+filename)
print("protocolo, revisión y versiones:",result["protocol"],result["dataset_revision"],result["versions"])
print("FID propio y clean-fid:",result["fid_train_test"],result["clean_fid"])
print("KID, precisión, exhaustividad:",result["kid_1000"],result["precision_1000"],result["recall_1000"])
for row in result["rows"]:
print("tabla",json.dumps(row))
# Descomposición del sesgo: término de medias esperado y modelo FID + c/n.
stats=np.load(work/"cifar10_reference.npz")
if str(stats["train_sha256"])!=result["train_sha256"]:
raise ValueError("La referencia no corresponde a las características")
trace=float(np.trace(stats["cov_train"]))
print("traza de la covarianza train:",trace)
n=np.array([row["n"] for row in result["rows"]],dtype=float)
mean=np.array([row["mean"] for row in result["rows"]])
for size,value in zip(n,mean):
print(f"n={size:.0f} FID medio={value:.4f} n·FID={size*value:.0f} "
f"término de medias esperado 2·tr/n={2*trace/size:.4f}")
intercept,slope=np.linalg.lstsq(np.stack([np.ones_like(n),1/n],1),mean,rcond=None)[0]
print("ajuste FID ≈ a + c/n con las tres filas: a =",intercept,"c =",slope)
two=(n[-1]*mean[-1]-n[-2]*mean[-2])/(n[-1]-n[-2])
print("extrapolación con las dos filas mayores:",two)
else:
print("Lectura omitida; establece P07_SHOW_RESULTS=1 después del análisis.")npm run lab and open the connection link.We can also check our KID against clean-fid on exactly the same points. Here num_subsets=1 and subset size matches both sets, so internal sampling only permutes points.
import os,pathlib,numpy as np
if os.environ.get("P07_KID_VERIFY") == "1":
from cleanfid.fid import kernel_distance
work=pathlib.Path(os.environ["P07_WORK"])
train=np.load(work/"train_features.npy",mmap_mode="r")
test=np.load(work/"test_features.npy",mmap_mode="r")
rng=np.random.default_rng(390)
x=np.asarray(train[rng.choice(len(train),1000,replace=False)],dtype=np.float64)
y=np.asarray(test[rng.choice(len(test),1000,replace=False)],dtype=np.float64)
d=x.shape[1]
xx=([email protected]/d+1)**3; yy=([email protected]/d+1)**3; xy=([email protected]/d+1)**3
own=float((xx.sum()-np.trace(xx))/(len(x)*(len(x)-1))+
(yy.sum()-np.trace(yy))/(len(y)*(len(y)-1))-2*xy.mean())
np.random.seed(390)
reference=kernel_distance(x,y,num_subsets=1,max_subset_size=1000)
print("KID propio:",own,"clean-fid:",reference,"diferencia absoluta:",abs(own-reference))
assert abs(own-reference)<1e-10
else:
print("Comparación KID omitida; establece P07_KID_VERIFY=1.")npm run lab and open the connection link.This cell’s precision and recall use 1000 points from each split to keep distance matrices manageable; they describe that sample and . Treating the test split as a perfect “generator” gives the protocol baseline: what a model sampling the exact data distribution would obtain at those sizes, and extractor. Keep sizes and seeds fixed when comparing a trained model, and record extractor version and fingerprint with each number.
In this lesson’s run (the reference reused by later lessons), with extractor SHA-256 starting f58cb9b6ec32, training versus test FID is 3.235621 by symmetric calculation and 3.235621 by clean-fid; full results differ by approximately , although clean-fid uses the nonsymmetric product root. Do not read this as a generator’s attainable minimum because it resembles Ho’s 3.17: the test split has 10 000 images, 3.17 used 50 000 samples and the size study shows finite-sample bias changes substantially. KID on the 1000 sample is , indistinguishable from zero as expected for an unbiased estimator between same-distribution samples. Precision and recall are 0.657 and 0.725: well below 1 although both sides are real images, because balls to the third neighbor, built from a finite sample in 2048 dimensions, exclude a substantial fraction of another same-distribution sample. Read model values against this baseline, not 1. A model can even exceed it in precision by concentrating samples in dense data regions; recall below baseline would reveal that.
| Images per resample | Mean FID | Sample deviation | Repetitions |
|---|---|---|---|
| 2000 | 25.723656 | 0.308455 | 5 |
| 10 000 | 5.241318 | 0.041177 | 5 |
| 50 000 | 1.059716 | 0.005271 | 5 |
Both resamples come from the same population, so population FID is zero and the entire table is bias. The inspection cell checks model : product is 51 447, 52 413 and 52 986 in the three rows, nearly constant while increases 25-fold. The mean term explains very little: with in Inception space, expected value is 0.188 with versus mean FID 25.72. Almost all bias comes from the covariance term, as the dimensional argument predicted. A line through the two larger rows extrapolates to and least-squares fit over three to : close to true zero but not exact, because higher-order terms matter in the 2.000 row and each mean has its own noise.
The model also explains training-versus-test FID. If each side with images contributes bias , with per the table (where both sides have ), a sample of versus one of should be apart even if both splits came from the same distribution. Measured 3.24 is almost all finite-sample bias: the real split difference is small.
The practical consequence is strong: two 10 000-image real CIFAR-10 samples already differ by 5.24 FID, greater than Ho and colleagues’ DDPM result 3.17 (calculated with 50 000 samples). When one side is the complete 50 000 reference, only one side contributes small-sample noise and the floor drops (about 3.1 with 10 000 generated samples, by the preceding calculation), but does not disappear. Hence compare with the same and reference, publish both and extrapolate in if bias must be separated.
A time-aware U-Net
The diffusion U-Net takes a noisy image and time and returns a prediction with the same shape as the noise. The encoder lowers resolution and increases channels; the decoder recovers detail by concatenating saved encoder activations. Skip connections are not clean-image leakage: during generation the input is the noisy state available at that step.
A sinusoidal embedding transforms scalar time into a frequency vector: with geometric frequencies , ,
High frequencies distinguish neighboring steps and low ones vary slowly over 1000 steps, so distinct times receive distinct codes and nearby times nearby codes; this is Transformer positional encoding applied to time. A small MLP projects it and each residual block adds it to activations as a per-channel bias. GroupNorm normalizes channel groups within each example and needs no batch statistics, useful for small microbatches. The block’s two convolutions learn a correction to a residual connection projected when channel count changes.
Attention is placed at 16 × 16 resolution. Its attention products scale quadratically with position count: going from 16 × 16 to 32 × 32 quadruples positions and multiplies pairs per head by sixteen. Total attention also includes projections and depends on channels, batch and kernel; extrapolating this factor to total runtime is incorrect.
The following explicit CIFAR-10 architecture is not a reproduction of Ho and colleagues’. Their U-Net has four resolutions (32, 16, 8 and 4), 128 channels with multipliers (1, 2, 2, 2), two residual blocks per resolution, dropout and 35.7 million parameters. Ours reaches a similar count with less depth and more width: three resolutions and one block per resolution.
| Resolution | Encoder blocks | Channels | Decoder blocks | Attention |
|---|---|---|---|---|
| 32 × 32 | stem, down0 | 224 | up0 (input 448 + 224) | no |
| 16 × 16 | down1 | 448 | up1 (input 672 + 448) | yes, 4 heads |
| 8 × 8 | down2, mid | 672 | no |
The cell prints each module’s parameters. Over half, 18.2 million, are at 8 × 8 (reduce1, down2 and mid), where channels are wider; computation is distributed the other way. Using PyTorch’s operation counter (torch.utils.flop_counter), a forward pass costs 14.3 GFLOP per image: 41 % at 32 × 32, 44 % at 16 × 16 (including both attentions, 1.06 GFLOP) and only 15 % at 8 × 8. A convolution costs its parameter count times positions, and 8 × 8 has sixteen times fewer positions than 32 × 32.
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))
torch.manual_seed(0)
net=DiffusionUNet() # modo entrenamiento: así una normalización por lote haría fallar el test
n_params=sum(p.numel() for p in net.parameters())
print("parámetros de la U-Net:",n_params)
for name,module in net.named_children():
print(f" {name:10s} {sum(p.numel() for p in module.parameters()):>10,d}")
with torch.no_grad():
x=torch.randn(2,3,32,32)
y=net(x,torch.tensor([10,500]))
alone=net(x[:1],torch.tensor([10]))
other_t=net(x,torch.tensor([900,500]))
# Tests de formas y de condicionamiento.
assert y.shape==x.shape, "La salida debe tener la forma del ruido"
assert torch.allclose(y[:1],alone,atol=1e-4), "GroupNorm no debe mezclar ejemplos del lote"
assert not torch.allclose(y[0],other_t[0],atol=1e-4), "El tiempo debe cambiar la predicción"
for bad in ((torch.zeros(2,3,28,28),torch.tensor([1,2])),(x,torch.tensor([1]))):
try:
net(*bad)
raise AssertionError("Debe rechazar formas incorrectas")
except ValueError:
pass
print("forma entrada y salida:",tuple(x.shape),"->",tuple(y.shape))
print("cambio relativo de la salida al pasar de t=10 a t=900:",
float((y[0]-other_t[0]).norm()/y[0].norm()))
del net,x,y,alone,other_tnpm run lab and open the connection link.The integer time step becomes a vector; training uses the noise schedule fixed in the next lesson. Cell tests check three properties a wiring error could silently break: output has noise shape, each example is processed without observing others in the batch (the network is tested in training mode, and BatchNorm instead of GroupNorm would fail), and changing changes prediction (if the embedding failed to reach blocks, the network would ignore noise level). They still do not test denoiser quality: to verify the complete path we must compute loss, backpropagate and update weights.
The embedding is not a semantic class: it states how much noise was applied so the same weights handle several levels. Concatenating each skip doubles or expands the up-block’s input channels, so that branch’s convolutions must explicitly declare dimensions. In the attention block, queries, keys and values are formed per position and head; PyTorch attention may avoid materializing the whole matrix depending on device and kernel. Pair complexity still explains why resolution matters, although observed peak memory depends on implementation.
Compute budget on the RTX 4060
Before measuring performance, verify gradients reach the model and the optimizer step finishes. Measure after warmup updates to include AdamW states created lazily, synchronize CUDA around the measured segment and declare microbatch and precision. The cell measures with the next lesson’s recipe microbatch, 32 images (P07_BENCH_BATCH changes it), in bf16 autocast and float32, to show the benefit of mixed precision. The allocator may reserve reusable blocks exceeding live tensors. A memory figure need not include memory occupied by other processes or all driver reservations.
import os, time
if os.environ.get("P07_BENCH") == "1":
if not torch.cuda.is_available():
raise RuntimeError("Se necesita CUDA para esta medición")
batch=int(os.environ.get("P07_BENCH_BATCH","32"))
steps=int(os.environ.get("P07_BENCH_STEPS","20"))
print("dispositivo:",torch.cuda.get_device_name(0),"torch:",torch.__version__)
print("microlote:",batch,"pasos medidos:",steps,"parámetros, gradientes y AdamW en fp32")
for precision in ("bf16","fp32"):
torch.manual_seed(271)
net=opt=x=target=t=loss=None
try:
net=DiffusionUNet().cuda().train()
opt=torch.optim.AdamW(net.parameters(),lr=1e-4)
x=torch.randn(batch,3,32,32,device="cuda")
target=torch.randn_like(x)
t=torch.randint(1,1001,(batch,),device="cuda")
def step():
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16,enabled=precision=="bf16"):
loss=F.mse_loss(net(x,t).float(),target)
loss.backward()
opt.step()
return loss.detach()
for _ in range(3):
step()
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
start=time.perf_counter()
for _ in range(steps):
loss=step()
torch.cuda.synchronize()
rate=steps/(time.perf_counter()-start)
print(f"{precision}: pérdida {float(loss):.3f} pasos/s {rate:.2f} imágenes/s {rate*batch:.0f} "
f"pico asignado {torch.cuda.max_memory_allocated()/2**20:.0f} MiB "
f"pico reservado {torch.cuda.max_memory_reserved()/2**20:.0f} MiB "
f"200 000 pasos ≈ {200000/rate/3600:.1f} h")
finally:
del net,opt,x,target,t,loss
torch.cuda.empty_cache()
else:
print("Medición omitida; establece P07_BENCH=1 para medir pasos de entrenamiento con CUDA.")npm run lab and open the connection link.Input and target tensors are artificial noise: they measure a training step, not generated-image quality. Three warmup updates initialize AdamW states and kernels before resetting the peak counter. Allocated and reserved are PyTorch allocator metrics, not all system CUDA memory.
Fixed memory is calculated without running anything: weights, gradients and two AdamW moments in float32 are bytes per parameter, MB, independent of microbatch and activation precision. The remainder of peak consists of activations saved for backpropagation, growing linearly with microbatch.
In this lesson’s verification run on a laptop RTX 4060 with microbatch 32 and 20 measured steps, the cell gave:
| Precision | Steps per second | Images per second | Peak allocated | 200 000 steps |
|---|---|---|---|---|
| autocast bf16 | 5.71 | 183 | 1622 MiB | 9.7 h |
| float32 | 3.66 | 117 | 1713 MiB | 15.2 h |
A complete forward and backward step costs about 42.8 GFLOP per image according to the same counter, so 183 images per second equals about 7.8 sustained TFLOP/s. Mixed precision is 1.56 times faster; it barely reduces peak because GroupNorm runs in float32 under autocast and backpropagation retains both float32 inputs and bf16 copies received by convolutions. The right column budgets the next lesson’s recipe (200 000 updates of 32 images): about ten GPU hours in training steps alone, before FID evaluations, which generate images with 1000 network passes each. These figures come from a short run on one machine: time depends on driver, laptop cooling and GPU load, and your own measurement with P07_BENCH=1 is what matters.
Common mistakes
Exercises
import numpy as np
def frechet_distance(mu1, s1, mu2, s2):
passSummary
FID is a protocol’s number: extractor, resizing, reference and sample count form part of its definition. Its estimator has positive bias of order which, on CIFAR-10, already exceeds a good model’s FID, so compare only numbers measured with the same protocol.
- Fréchet distance between Gaussians uses the square root of symmetric matrix , which has the same nonzero eigenvalues as and accommodates singular covariances with
eigh. - . Between CIFAR-10 training resamples, is nearly constant and nearly all bias comes from the covariance term.
- KID is an unbiased MMD² estimator with cubic polynomial kernel, comparing feature moments of orders 1, 2 and 3. Precision and recall separate fidelity and coverage and are read against the baseline between real samples.
- None of these metrics detects memorization: search for nearest neighbors in the training set.
- The 35.0-million-parameter U-Net alternates time-conditioned residual blocks, GroupNorm and attention at 16 × 16. The next lesson trains this network.