Few-step generation and memorization audit
Distill a diffusion teacher into few evaluations and audit generated images for memorization.
After this lesson you can
- Explain and implement consistency distillation and its boundary condition.
- Compare few-step generation with the teacher under a matched FID protocol.
- Audit memorization with calibrated nearest-neighbor tests and held-out controls.
Before you start
Two questions FID cannot answer
The p07-l05 EDM teacher generates an image by integrating an ODE with 35 network evaluations. This project closes with two questions requiring different experiments. The first concerns cost: can that integration be compressed into one to four evaluations without losing too much quality? The second concerns provenance: are generated images new or do they reproduce training examples? FID does not answer the latter. It summarizes the mean and covariance of Inception features for two distributions and does not examine where each image comes from: a generator returning exact copies of the training set would get excellent FID against that same set.
We start with provenance because its basic tool, nearest neighbors in the training set, has pitfalls visible without training anything. The viewer uses only real CIFAR-10 images. The “Real test” queries are the first eight test images, absent from train. The other two are copies of the first eight train images whose answers we know: shifted 2 pixels down and right with replicated borders, or recolored with . This lets us check whether each distance finds the original.
All distances are square roots of mean squared error with intensities in , , the normalization used by Carlini and colleagues. “Pixels” compares the RGB coordinates. “8×8 blocks” compares the 48 means per block and channel: it retains coarse structure but is not a validated perceptual measure. “Pixels ±2 px” compares the central of each reference with the query’s 25 windows and keeps the minimum distance. and are distances to the nearest and second-nearest neighbors.
The control shows the following, using the figures printed by the cell:
- A shifted copy fools pixel distance. Against all 50,000 train images, the shifted copy’s nearest neighbor is its original in 1 of 8 queries, and lies between 0.10 and 0.20, the same range as test images (0.13 to 0.23). With 8×8 blocks it recovers the original in 3 of 8. Shift-aware search recovers it in 8 of 8 at distance 0 because the shifted window exactly matches the original’s center.
- A recolored copy is found, but does not stand out. Using pixels against all 50,000 images, the original appears in 8 of 8 with between 0.04 and 0.09; nevertheless ranges from 0.38 to 0.97, and none of the eight falls below under any representation or reference size.
- Reference size changes the minimum. For test images, falls when moving from 1,000 to 50,000 references (for the first, from 0.193 to 0.175 with pixels), although no model has seen those images: the minimum over a larger set cannot be greater.
Consistency distillation trains a student to assign the same output to neighboring states along a teacher ODE trajectory, so one evaluation takes noise to an image. A memorization audit uses a protocol, representations and threshold fixed before inspection to find and examine generations unusually close to training examples. The GPU lab has two parts: distill p07-l05 EDM and measure its FID with 1, 2 and 4 evaluations against the teacher and p07-l07 rectified flow under the p07-l02 protocol; and train the same EDM on only 1,000 images to audit samples from both models.
A constant output along a trajectory
We write the teacher using its denoiser from EDM preconditioning. For , the probability-flow ODE in noise coordinates is with . If is continuous and Lipschitz in , a unique trajectory passes through each point and trajectories do not cross. Sampling follows the trajectory starting at noise to minimum level . If a network could jump from any point on a trajectory to its endpoint, one evaluation would suffice. This is the idea behind consistency models.
The equivalence is immediate: if satisfies both, . The function depends on the teacher ODE, not directly on the data: the student can only aspire to copy the teacher, flaws included.
We parameterize , with the U-Net. For and , Song and colleagues use
with . These are EDM coefficients with shifted to (except the denominator of , which retains ). At the first is one and the second zero, so for any finite network output: the boundary holds by construction and the network need not learn an approximate identity. When , the coefficients approach EDM’s, so the student can start with teacher weights, as in the paper. The parameterization says nothing about self-consistency at higher levels: that must be learned.
Step 1 of 3. What is c_skip(ε)?
Why adjacent pairs suffice
Fix a grid . Distillation does not know the exact consistency function: it can only take a teacher integrator step from to . If the student achieves in every interval, the boundary anchors the chain at and consistency propagates upward. The price is accumulation of errors from each integrator step. The following result, theorem 1 of the paper, quantifies this.
Proof
Let and . By both functions’ boundary condition, . The point is on the same trajectory as , so self-consistency of gives . By (iii),
By (i) and (ii), the bracket has norm at most and the second term at most . Thus and, summing from ,
∎Assumption (iii) is what “zero loss” means. The loss is an expectation over , which has positive density everywhere due to Gaussian noise. If weight is positive, the distance vanishes only for equal points and the functions are continuous, zero expectation forces equality for all . There are three practical readings. The bound compares against the teacher ODE, not the data. A higher-order integrator (Heun, ) reduces target bias relative to Euler (). And loss is never exactly zero, so the bound describes the limit of a perfect student, not the one you will train.
The next cell checks this in the only fully exact case: one-dimensional data. There , the ODE is linear, is conserved and . The zero-loss student is built by composing teacher steps, which are linear here, on the Karras grid with used in p07-l05.
import numpy as np
s, eps, T = .5, .02, 80.
def grid(N, rho=7): # niveles crecientes eps=t_1<...<t_N=T (malla de Karras)
return (eps**(1/rho)+np.arange(N)/(N-1)*(T**(1/rho)-eps**(1/rho)))**rho
def field(x, t): # dx/dσ=(x-D)/σ con D(x,σ)=s²x/(s²+σ²)
return t*x/(s*s+t*t)
def step(x, hi, lo, method): # un paso del maestro de hi a lo
d1=field(x,hi)
if method=='euler': return x+(lo-hi)*d1
trial=x+(lo-hi)*d1
return x+(lo-hi)*(d1+field(trial,lo))/2
exact=np.sqrt(s*s+eps*eps)/np.sqrt(s*s+T*T) # f(x,T)=exact·x
for method in ('euler','heun'):
prev=None
for N in (18,36,72,144,288):
t=grid(N); c=1. # contorno: f(x,t_1)=x
for n in range(N-1): c=step(c,t[n+1],t[n],method) # f(x,t_{n+1})=f(Φ_n(x),t_n)
err=abs(c-exact)/exact; dt=np.diff(t).max()
rate='' if prev is None else f' orden observado {np.log(prev[0]/err)/np.log(prev[1]/dt):.2f}'
print(f'{method:5s} N={N:3d} Δt máx={dt:7.3f} error relativo en T={err:.2e}{rate}')
prev=(err,dt)Observed order tends to 1 with Euler and 2 with Heun, as the theorem predicts. The first Heun row is the lab configuration, : even with an exact teacher, the perfect student deviates 4% from the true endpoint in this example because the grid’s longest interval has length 20. Refining the grid reduces that bias but lengthens the chain of pairs to learn, and the paper chose based on FID.
The distillation objective
Given data , noise and an index uniform on , form and a teacher Heun step gives . The distillation loss is
The target is computed without gradients: no backpropagation goes through the teacher or target network. Target network is a moving average of the student with rate ; with it is the student itself with stopped gradient. Another, much slower moving average is saved for evaluation; these are distinct mechanisms. Each pair costs two teacher evaluations (Heun), one target-network evaluation and one student evaluation with gradients. This is knowledge distillation in which the teacher provides a local ODE step rather than the final answer. Unlike progressive distillation, which halves steps each round, here there is one round; and without a teacher, consistency training replaces with using the same .
For CIFAR-10, the paper’s hyperparameter table gives distillation: LPIPS distance, Heun, , , learning rate , batch 512, 800,000 iterations, evaluation average with rate 0.9999 and initialization from EDM weights. Our lab retains Heun, , , evaluation average and initialization, and changes the rest to fit an 8 GB GPU: squared error instead of LPIPS (which requires a pretrained VGG), batch 32, rate , the p07-l02 U-Net and p07-l05 grid from 80 to (the paper uses ). At defaults the lab processes about 1.3 million examples, roughly 0.3% of the paper’s 410 million: it is a variant, not a replication.
In the paper’s table 1 for CIFAR-10, consistency distillation achieves FID 3.55 with one evaluation and 2.93 with two, versus reference EDM FID 2.04 with 35 evaluations. In the same table progressive distillation achieves 8.34 with one and 5.58 with two, and distilled rectified flow achieves 6.18 with one evaluation after one reflow (1-rectified flow), 4.85 after two and 5.21 after three. These use the paper’s models and budgets. Your p07-l05 teacher, with 10,000 updates of 32 images, will have much higher FID, and the student cannot reliably outperform its teacher: what matters is the gap and how it changes from 1 to 4 evaluations.
To generate with one evaluation, start at and apply . With more evaluations, alternate: add noise with standard deviation to the result so its level is , and apply , with . The paper chooses one by one using ternary search over FID, assuming FID is unimodal in the next level. The lab does the same over the 18-level grid with 2,000 samples and a selection seed distinct from the evaluation seed: choosing levels with the same samples used to report FID would make the result optimistic.
Lab: distill and measure
The lab’s code is self-contained: the first cell repeats the necessary pieces of p07-l02, p07-l03 and p07-l05 (U-Net, EDM preconditioning, the 35-evaluation Heun sampler and FID functions), so you need not open other lessons. It does need two of their outputs: the p07-l02 FID reference, whose directory is specified by P07_L02_REF (with its vendor folder in PYTHONPATH for clean-fid), and the teacher, model.pt from the p07-l05 edm run with seed 31, sought in ~/atlas-lab/p07-l05/pasos-10000/edm-s31/ (P07_L09_TEACHER changes the path). You also need faiss-cpu==1.13.2 and scipy. All this lesson’s outputs go to ~/atlas-lab/p07-l09/ (or ATLAS_LAB_DIR/p07-l09). Each stage is activated by an environment variable; without them cells only define functions and run small checks. If interrupted, repeating a stage resumes its last checkpoint after checking code and configuration match, and skips finished work. From the project root in PowerShell:
$env:P07_L02_REF="C:\ruta\a\la\referencia\de\p07-l02"
$env:PYTHONPATH=Join-Path $env:P07_L02_REF "vendor"
$env:P07_L09_DISTILL="1" # destila el maestro: 40.000 actualizaciones
$env:P07_L09_EVAL="1" # después, FID con 1, 2 y 4 evaluaciones
$env:P07_L09_SUBSET="1" # EDM con 1000 imágenes: 10.000 actualizaciones
$env:P07_L09_MEMO="1" # auditoría del EDM completo y del de 1000 imágenes
npm run lab
Each loop prints its speed (updates per second) every 100 steps: multiply by the number of steps to budget the remainder. Before a full run, a short pass with P07_L09_STEPS=200 and P07_L09_SUBSET_STEPS=200 is useful; it writes to separate directories (consistencia-200, edm-1000-200) and exercises the entire circuit.
import os, copy, json, math, time, uuid, hashlib, inspect, pathlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
LAB=Path(os.environ.get('ATLAS_LAB_DIR',Path.home()/'atlas-lab')).expanduser()
L09=LAB/'p07-l09'
TEACHER=Path(os.environ.get('P07_L09_TEACHER',LAB/'p07-l05'/'pasos-10000'/'edm-s31'/'model.pt'))
CIFAR_REVISION='0b2714987fa478483af9968de7c934580d0bb9a2'
SIGMA_DATA=.5
# U-Net de p07-l02 (idéntica a la de p07-l03 y p07-l05).
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))
# Precondición, pérdida y Heun de 35 evaluaciones de p07-l05 (solo la variante edm).
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
return d*d/total*y+s*d*total.rsqrt()*self.model(total.rsqrt()*y,sigma.log()/4)
def edm_target_loss(net,x,eps,sigma,sigma_data=SIGMA_DATA):
s=sigma[:,None,None,None]
prediction=EDMPrecond(net,sigma_data)(x+s*eps,sigma)
weight=(s.square()+sigma_data**2)/(s*s*sigma_data**2)
return (weight*(prediction-x).square()).mean()
@torch.inference_mode()
def heun_edm(net,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.)
teacher=EDMPrecond(net,SIGMA_DATA)
y,nfe=initial.clone(),0
for s,q in zip(levels[:-1],levels[1:]):
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
d=teacher(y,torch.full((len(y),),float(s),device=y.device)).float()
slope=(y-d)/s
predicted=y+(q-s)*slope; nfe+=1
if q>0:
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
d2=teacher(predicted,torch.full((len(y),),float(q),device=y.device)).float()
y=y+(q-s)*(slope+(predicted-d2)/q)/2; nfe+=1
else:
y=predicted
return y,nfe
# FID con la referencia de p07-l02 (mismas comprobaciones que p07-l03 y p07-l05).
def file_digest(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=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_digest(path/"inception-2015-12-05.pt")!=record["extractor_sha256"]:
raise ValueError("Huella del extractor distinta")
if file_digest(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)
def image_grid(pixels):
import io, base64
from PIL import Image
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')
# Datos y escritura segura.
def load_cifar_uint8(split):
from datasets import load_dataset
ds=load_dataset('uoft-cs/cifar10',revision=CIFAR_REVISION,split=split,cache_dir=os.environ.get('P07_L09_CACHE'))
images=np.stack([np.asarray(im.convert('RGB')) for im in ds['img']]).transpose(0,3,1,2).copy()
if images.shape!=({'train':50000,'test':10000}[split],3,32,32): raise ValueError('Partición inesperada')
return images # uint8, N×3×32×32
def subset_indices(count,seed,total=50000):
if not 0<count<=total: raise ValueError('Tamaño de subconjunto inválido')
return np.sort(np.random.default_rng(seed).permutation(total)[:count])
def sha_array(a):
return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()
def publish_atomic(path,write,overwrite=False):
# Escribe en un temporal y renombra: un corte nunca deja un archivo a medias.
path=Path(path)
if path.exists() and not overwrite: raise FileExistsError(path)
tmp=path.parent/(path.name+'-'+uuid.uuid4().hex+'.tmp')
created=False
try:
with tmp.open('xb') as f:
created=True; write(f)
os.replace(tmp,path)
finally:
if created: tmp.unlink(missing_ok=True)
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)
loss=edm_target_loss(lambda z,t:torch.zeros_like(z),torch.ones(2,1,2,2),torch.zeros(2,1,2,2),torch.tensor([.5,1.]))
assert abs(float(loss)-2.6)<1e-6 # el control de p07-l05 con predictor cero
idx=subset_indices(1000,909)
assert len(set(idx.tolist()))==1000 and np.array_equal(idx,subset_indices(1000,909))
print('controles de FID y pérdida EDM correctos; subconjunto de 1000: primeros índices',idx[:5].tolist(),
'huella',sha_array(idx)[:16],'| resultados en',L09)npm run lab and open the connection link.The next cell defines the student, teacher Heun step, loss and multi-evaluation sampling, and checks them with tiny networks: exact boundary and isolated target gradient.
import copy, math
import torch
from torch import nn
class Consistency(nn.Module):
def __init__(self, net, epsilon=.02, sigma_data=.5):
super().__init__()
if epsilon<=0 or sigma_data<=0: raise ValueError('Escalas positivas requeridas')
self.net=net; self.epsilon=float(epsilon); self.sigma_data=float(sigma_data)
def forward(self,x,sigma):
if sigma.ndim!=1 or len(sigma)!=len(x) or torch.any(sigma<self.epsilon):
raise ValueError('Un nivel válido por ejemplo')
shape=(len(x),)+(1,)*(x.ndim-1)
s=sigma.reshape(shape); offset=s-self.epsilon; sd=self.sigma_data
skip=sd**2/(offset.square()+sd**2)
out=sd*offset/torch.sqrt(sd**2+s.square())
cin=torch.rsqrt(sd**2+s.square())
return skip*x+out*self.net(cin*x,sigma.log()/4)
def teacher_heun(teacher,x,high,low):
shape=(len(x),)+(1,)*(x.ndim-1)
h=high.reshape(shape); l=low.reshape(shape)
if torch.any(low<=0) or torch.any(high<=low): raise ValueError('Niveles inválidos')
d1=(x-teacher(x,high))/h
trial=x+(l-h)*d1
d2=(trial-teacher(trial,low))/l
return x+(l-h)*(d1+d2)/2
def consistency_loss(student, target, teacher, clean, high, low, noise):
shape=(len(clean),)+(1,)*(clean.ndim-1)
x_high=clean+high.reshape(shape)*noise
with torch.no_grad():
x_low=teacher_heun(teacher,x_high,high,low)
expected=target(x_low,low)
return (student(x_high,high)-expected).square().mean()
@torch.no_grad()
def update_target(target,student,decay):
if not 0<=decay<=1: raise ValueError('La media móvil requiere 0≤decay≤1')
for target_p,student_p in zip(target.parameters(),student.parameters(),strict=True):
target_p.mul_(decay).add_(student_p,alpha=1-decay)
@torch.no_grad()
def consistency_sample(student,x,levels,generator):
if not levels or any(s<=student.epsilon for s in levels): raise ValueError('Niveles > ε requeridos')
if any(a<=b for a,b in zip(levels,levels[1:])): raise ValueError('Niveles estrictamente decrecientes')
for i,sigma in enumerate(levels):
if i:
noise=torch.randn(x.shape,device=x.device,dtype=x.dtype,generator=generator)
x=x+math.sqrt(sigma*sigma-student.epsilon**2)*noise
x=student(x,torch.full((len(x),),sigma,device=x.device,dtype=x.dtype))
return x
class TinyNet(nn.Module):
def __init__(self): super().__init__(); self.weight=nn.Parameter(torch.tensor(.1))
def forward(self,x,t): return self.weight*x
class IdentityTeacher(nn.Module):
def forward(self,x,sigma): return x
student=Consistency(TinyNet()); target=copy.deepcopy(student); teacher=IdentityTeacher()
x=torch.tensor([[1.,-1.],[.5,.1]])
assert torch.equal(student(x,torch.full((2,),.02)),x)
loss=consistency_loss(student,target,teacher,x,torch.ones(2),torch.full((2,),.5),torch.ones_like(x))
loss.backward()
assert student.net.weight.grad is not None and target.net.weight.grad is None
print('contorno exacto:',True,'gradiente del objetivo:',target.net.weight.grad,'pérdida de control:',float(loss.detach()))npm run lab and open the connection link.Student and target must be copies with independent parameters; do not reuse the same object. The next function creates teacher, student, target network and evaluation average from p07-l05’s model.pt. The file must be yours: weights_only=True limits object types PyTorch accepts when loading, but does not verify provenance, and the recorded SHA-256 fingerprint detects changes against a reference, not origin. A training step computes loss in bfloat16 where PyTorch permits, updates only the student optimizer and then both averages.
def build_consistency_from_edm(path, device='cuda', epsilon=.02):
saved=torch.load(Path(path),map_location='cpu',weights_only=True)
cfg=saved['config']
if cfg.get('mode')!='edm' or cfg.get('sigma_data')!=.5:
raise ValueError('Se necesita un modelo EDM de p07-l05 (mode edm, sigma_data 0.5)')
net=DiffusionUNet()
net.load_state_dict(saved['model'],strict=True)
teacher=EDMPrecond(copy.deepcopy(net),.5).to(device).eval().requires_grad_(False)
student=Consistency(net,epsilon=epsilon,sigma_data=.5).to(device).train()
target=copy.deepcopy(student).eval().requires_grad_(False)
ema=copy.deepcopy(student).eval().requires_grad_(False)
return teacher,student,target,ema,cfg
def consistency_train_step(student,target,ema,teacher,optimizer,clean,high,low,noise,mu,ema_decay):
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type=clean.device.type,dtype=torch.bfloat16,enabled=clean.device.type=='cuda'):
loss=consistency_loss(student,target,teacher,clean,high,low,noise)
loss.backward()
optimizer.step()
update_target(target,student,mu) # red objetivo θ⁻
update_target(ema,student,ema_decay) # media para evaluar
return float(loss.detach().cpu())
# Control en CPU: con μ=0 el objetivo copia al estudiante; la media de evaluación apenas se mueve.
s=Consistency(TinyNet()); t=copy.deepcopy(s).requires_grad_(False); e=copy.deepcopy(s).requires_grad_(False)
opt=torch.optim.SGD(s.parameters(),lr=.1)
x=torch.tensor([[1.,-1.],[.5,.1]])
consistency_train_step(s,t,e,IdentityTeacher(),opt,x,torch.ones(2),torch.full((2,),.5),torch.ones_like(x),0.,.9999)
assert torch.equal(t.net.weight,s.net.weight) and not torch.equal(e.net.weight,s.net.weight)
print('peso estudiante',s.net.weight.item(),'objetivo',t.net.weight.item(),'media de evaluación',e.net.weight.item())npm run lab and open the connection link.The next loop traverses all CIFAR-10 with the p07-l05 grid: 18 Karras levels with between 0.02 and 80, i.e. 17 uniformly selected intervals. It saves a checkpoint every save_every updates with student, target, evaluation average, optimizer, random generators and losses, and finally publishes student.pt in p07-l09/consistencia/ (consistencia-<pasos> if you change P07_L09_STEPS). Experiment identity includes teacher, data and code fingerprints: if resumption does not match the checkpoint, the cell stops instead of mixing experiments.
def karras_levels(count=18,low=.02,high=80.,rho=7):
return (low**(1/rho)+np.arange(count)/(count-1)*(high**(1/rho)-low**(1/rho)))**rho # crecientes
def train_consistency(images, teacher_path, output, steps=40000, batch=32, seed=0, mu=0., ema_decay=.9999,
lr=2e-4, save_every=1000, device='cuda'):
images=np.asarray(images)
if images.dtype!=np.uint8 or images.ndim!=4 or images.shape[1:]!=(3,32,32) or not len(images):
raise ValueError('Se requieren imágenes uint8 N×3×32×32')
if steps<1 or batch<1 or save_every<1 or not 0<=mu<1 or not 0<=ema_decay<1:
raise ValueError('Configuración de entrenamiento inválida')
output,teacher_path=Path(output),Path(teacher_path)
if (output/'student.pt').exists(): print('Ya terminada:',output); return
if not teacher_path.is_file(): raise FileNotFoundError(f'No está el maestro {teacher_path}: entrena edm-s31 en p07-l05')
output.mkdir(parents=True,exist_ok=True)
resume=(output/'latest.pt').is_file()
code='\n'.join(inspect.getsource(f) for f in (Consistency.__init__,Consistency.forward,
DiffusionUNet.__init__,DiffusionUNet.forward,EDMPrecond.forward,teacher_heun,consistency_loss,
update_target,build_consistency_from_edm,consistency_train_step,karras_levels,train_consistency))
levels=karras_levels()
identity={'teacher':file_digest(teacher_path),'data':sha_array(images),
'source':hashlib.sha256(code.encode('utf-8')).hexdigest(),'torch':str(torch.__version__),
'steps':steps,'batch':batch,'seed':seed,'mu':mu,'ema_decay':ema_decay,'lr':lr,
'save_every':save_every,'levels':[float(v) for v in levels],'epsilon':.02,'distance':'mse',
'precision':'autocast bf16'}
teacher=student=target=ema=optimizer=None
try:
torch.manual_seed(seed)
if str(device).startswith('cuda'): torch.cuda.manual_seed_all(seed)
teacher,student,target,ema,_=build_consistency_from_edm(teacher_path,device)
optimizer=torch.optim.Adam(student.parameters(),lr=lr)
data_rng=torch.Generator().manual_seed(seed+1)
noise_rng=torch.Generator(device=device).manual_seed(seed+2)
grid=torch.tensor(levels,dtype=torch.float32)
start,losses=0,[]
if resume:
ck=torch.load(output/'latest.pt',map_location='cpu',weights_only=True)
if ck['identity']!=identity: raise ValueError('Identidad incompatible con el checkpoint')
for module,key in ((student,'student'),(target,'target'),(ema,'ema')): module.load_state_dict(ck[key])
optimizer.load_state_dict(ck['optimizer'])
data_rng.set_state(ck['data_rng']); noise_rng.set_state(ck['noise_rng'])
torch.set_rng_state(ck['cpu_rng'])
if str(device).startswith('cuda'): torch.cuda.set_rng_state(ck['cuda_rng'],device)
start,losses=ck['step'],ck['losses']; del ck
print('Reanudando',output.name,'desde la actualización',start)
clock=time.perf_counter()
for step in range(start+1,steps+1):
ix=torch.randint(len(images),(batch,),generator=data_rng)
n=torch.randint(len(grid)-1,(batch,),generator=data_rng)
low,high=grid[n].to(device),grid[n+1].to(device)
clean=torch.from_numpy(images[ix.numpy()]).to(device).float()/127.5-1
noise=torch.randn(clean.shape,device=device,generator=noise_rng)
loss=consistency_train_step(student,target,ema,teacher,optimizer,clean,high,low,noise,mu,ema_decay)
if step%100==0 or step==steps:
losses.append({'step':step,'loss':loss})
print(f'actualización {step}/{steps} pérdida {loss:.5f} ({(step-start)/(time.perf_counter()-clock):.2f} act./s)',flush=True)
if step%save_every==0 or step==steps:
state={'identity':identity,'step':step,'student':student.state_dict(),'target':target.state_dict(),
'ema':ema.state_dict(),'optimizer':optimizer.state_dict(),'losses':losses,
'data_rng':data_rng.get_state(),'noise_rng':noise_rng.get_state(),'cpu_rng':torch.get_rng_state(),
'cuda_rng':torch.cuda.get_rng_state(device) if str(device).startswith('cuda') else None}
publish_atomic(output/'latest.pt',lambda f:torch.save(state,f),overwrite=True); state=None
final={'ema':ema.state_dict(),'student':student.state_dict(),'config':identity,'losses':losses}
publish_atomic(output/'student.pt',lambda f:torch.save(final,f),overwrite=True)
print('estudiante',output/'student.pt','huella',file_digest(output/'student.pt'))
finally:
teacher=student=target=ema=optimizer=None
if str(device).startswith('cuda'): torch.cuda.empty_cache()
levels=karras_levels()
assert len(levels)==18 and abs(levels[0]-.02)<1e-12 and abs(levels[-1]-80)<1e-9
print('malla (crecientes):',np.round(levels,3).tolist())
DISTILL_STEPS=int(os.environ.get('P07_L09_STEPS','40000'))
STUDENT_DIR=L09/('consistencia' if DISTILL_STEPS==40000 else f'consistencia-{DISTILL_STEPS}')
if os.environ.get('P07_L09_DISTILL')=='1':
train_consistency(load_cifar_uint8('train'),TEACHER,STUDENT_DIR,steps=DISTILL_STEPS)
else:
print('Destilación definida. Para lanzarla: P07_L09_DISTILL=1 (maestro:',TEACHER,')')npm run lab and open the connection link.The full circuit was checked with a short run using these same functions with a reduced U-Net (width 32), batch 16 and a substitute extractor rather than Inception: 60 updates of the 1,000-image EDM as teacher, 20 of distillation with checkpoints every 10, a deliberate interruption at update 11 and resumption, 1-, 2- and 4-evaluation assessment with level search, the shared table and an audit of 128 generations. Resumption reproduced student.pt from the continuous run bit for bit (same SHA-256 fingerprint). Some cuDNN convolutions are nondeterministic, so on another GPU differences in the last decimal places after resumption do not imply a faulty checkpoint. That test teacher was barely trained, so its FIDs do not indicate quality and are not reported.
Evaluation generates 10,000 images per configuration with seed 90901 and computes FID with the same functions as p07-l03, p07-l05 and p07-l07 against the P07_L02_REF reference. For two and four evaluations it first chooses intermediate levels by ternary FID search using 2,000 samples and seed 70707. With P07_L09_EVAL=1 it evaluates the preceding stage’s student.pt and publishes one JSON per configuration in p07-l09/evaluacion/ (or evaluacion-<pasos>), consistency-nfe1.json, -nfe2.json and -nfe4.json, with FID, levels, selection log, fingerprints and a grid of 16 samples; already published configurations are skipped.
KARRAS=karras_levels()[::-1].copy() # decrecientes: 80, ..., 0.02
def load_student(path,device):
saved=torch.load(Path(path),map_location='cpu',weights_only=True)
model=Consistency(DiffusionUNet(),epsilon=saved['config']['epsilon'],sigma_data=.5)
model.load_state_dict(saved['ema'],strict=True)
return model.to(device).eval().requires_grad_(False),saved['config']
@torch.no_grad()
def consistency_pixels(model,levels,count,seed,device,batch=64):
for start in range(0,count,batch):
n=min(batch,count-start)
gen=torch.Generator(device=device).manual_seed(seed+start)
x=levels[0]*torch.randn((n,3,32,32),device=device,generator=gen)
with torch.autocast(device_type=device.type,dtype=torch.bfloat16,enabled=device.type=='cuda'):
sample=consistency_sample(model,x,list(levels),gen)
yield ((sample.float().clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
@torch.no_grad()
def inception(pixels,extractor,resize,device):
resized=np.stack([resize(im) for im in pixels]).transpose(0,3,1,2)
return extractor(torch.from_numpy(resized).to(device)).cpu().numpy()
def fid_of_levels(model,levels,count,seed,ref,device):
mean,cov,extractor,resize,_=ref
feats=[inception(p,extractor,resize,device) for p in consistency_pixels(model,levels,count,seed,device)]
return feature_fid(np.concatenate(feats),mean,cov)
def choose_levels(model,nfe,count,seed,ref,device,log):
chosen,last=[float(KARRAS[0])],0
for k in range(1,nfe):
lo,hi=last+1,len(KARRAS)-2-(nfe-1-k) # excluye ε y deja sitio a los niveles restantes
scores={}
def score(i):
if i not in scores:
scores[i]=fid_of_levels(model,chosen+[float(KARRAS[i])],count,seed,ref,device)
log.append({'levels':chosen+[float(KARRAS[i])],'fid':scores[i]}); print('selección',log[-1],flush=True)
return scores[i]
while hi-lo>2: # búsqueda ternaria sobre índices de la malla
m1,m2=lo+(hi-lo)//3,hi-(hi-lo)//3
if score(m1)<score(m2): hi=m2-1
else: lo=m1+1
last=min(range(lo,hi+1),key=score)
chosen.append(float(KARRAS[last]))
return chosen
def evaluate_consistency(student_path,reference,output,nfes=(1,2,4),count=10000,seed=90901,
select_count=2000,select_seed=70707):
student_path,reference,output=map(Path,(student_path,reference,output))
if not all(p.is_absolute() for p in (student_path,reference,output)): raise ValueError('Rutas absolutas obligatorias')
if not torch.cuda.is_available(): raise RuntimeError('La evaluación requiere CUDA')
output.mkdir(parents=True,exist_ok=True)
device=torch.device('cuda'); model=ref=None
try:
model,cfg=load_student(student_path,device)
ref=load_fid_reference(reference,device); record=ref[4]
for nfe in nfes:
if (output/f'consistency-nfe{nfe}.json').exists(): print('Ya evaluada: NFE',nfe); continue
log=[]
levels=choose_levels(model,nfe,select_count,select_seed,ref,device,log) if nfe>1 else [float(KARRAS[0])]
feats,grid=[],None
for pixels in consistency_pixels(model,levels,count,seed,device):
if grid is None: grid=image_grid(pixels)
feats.append(inception(pixels,ref[2],ref[3],device))
result={'family':'consistency','nfe':nfe,'levels':levels,'fid':feature_fid(np.concatenate(feats),ref[0],ref[1]),
'samples':count,'seed':seed,'selection':{'samples':select_count,'seed':select_seed,'log':log},
'model_sha256':file_digest(student_path),'training_identity':cfg,
'train_sha256':record['train_sha256'],'extractor_sha256':record['extractor_sha256'],'grid_png':grid}
text=json.dumps(result,ensure_ascii=False,indent=2).encode('utf-8')
publish_atomic(output/f'consistency-nfe{nfe}.json',lambda f:f.write(text))
print('NFE',nfe,'niveles',[round(v,3) for v in levels],'FID',round(result['fid'],2),flush=True)
finally:
model=ref=None; torch.cuda.empty_cache()
EVAL_DIR=L09/STUDENT_DIR.name.replace('consistencia','evaluacion')
if os.environ.get('P07_L09_EVAL')=='1':
evaluate_consistency(STUDENT_DIR/'student.pt',os.environ['P07_L02_REF'],EVAL_DIR)
else:
print('Evaluación definida. Para lanzarla: P07_L09_EVAL=1 y P07_L02_REF; resultados en',EVAL_DIR)npm run lab and open the connection link.A fair comparison with the teacher uses its established sampling: evaluation-10000.json left by p07-l05 beside each model.pt, with 18-level Heun and 35 evaluations. Rectified flow is evaluated with p07-l07’s “FID and velocity deviation of one stage” cell on the model after one reflow, with 1, 2 and 4 Euler steps; since you choose each JSON path there, pass them as a JSON list in P07_L09_FLOW. With P07_L09_COMPARE=1 the next cell gathers those files with this lesson’s and p07-l05 edm evaluations, checks common reference features, extractor and sample count, and sorts the table. Noise seeds differ across families; to attribute a small difference, repeat each evaluation with another seed.
import tempfile
def compare_runs(paths):
rows,protocol=[],None
for p in map(Path,paths):
r=json.loads(p.read_text(encoding='utf-8'))
key=(r.get('train_sha256') or r.get('train_features_sha256'),r['extractor_sha256'],r['samples'])
if protocol is None: protocol=key
elif key!=protocol: raise ValueError(f'Protocolo distinto en {p}: {key} frente a {protocol}')
detail=r.get('sampler') or r.get('solver') or ' '.join(f'{v:.3g}' for v in r.get('levels',[]))
rows.append((r.get('family','edm'),int(r['nfe']),float(r['fid']),detail,p.name))
rows.sort(key=lambda row:(row[0],row[1]))
print(f"{'familia':12s} {'NFE':>4s} {'FID':>8s} detalle")
for family,nfe,fid,detail,name in rows: print(f'{family:12s} {nfe:4d} {fid:8.2f} {detail} ({name})')
return rows
if os.environ.get('P07_L09_COMPARE')=='1':
paths=sorted(EVAL_DIR.glob('consistency-nfe*.json'))+sorted((LAB/'p07-l05'/'pasos-10000').glob('edm-s*/evaluation-10000.json'))
compare_runs(paths+[Path(p) for p in json.loads(os.environ.get('P07_L09_FLOW','[]'))])
else:
with tempfile.TemporaryDirectory() as tmp: # control con archivos sintéticos
base={'extractor_sha256':'e','samples':10}
files={'a.json':{**base,'train_features_sha256':'t','nfe':35,'fid':9.,'sampler':'Heun'},
'b.json':{**base,'train_sha256':'t','family':'consistency','nfe':1,'fid':20.,'levels':[80.]}}
for name,value in files.items(): (Path(tmp)/name).write_text(json.dumps(value),encoding='utf-8')
assert [r[1] for r in compare_runs([Path(tmp)/n for n in files])]==[1,35]
(Path(tmp)/'c.json').write_text(json.dumps({**files['b.json'],'samples':5}),encoding='utf-8')
try: compare_runs([Path(tmp)/'a.json',Path(tmp)/'c.json']); raise AssertionError('debía fallar')
except ValueError as e: print('protocolo distinto detectado:',str(e)[:40])npm run lab and open the connection link.Audit memorization
A defensive audit fixes the reference set, representations, criterion and generation count in advance. We use three published pieces. Carlini and colleagues define extraction: example is extracted if an algorithm that does not receive it produces with ; with the normalized norm above they use in Stable Diffusion. On CIFAR-10 they find an absolute threshold fails (with 0.05, nearly all alerts are blue skies or green landscapes) and calibrate per image with , where are the 50 nearest train neighbors and . Gu and colleagues, following Yoon and colleagues, consider a generation memorized if in train, an empirical threshold aligned with human perception. Both calibrated criteria compare the neighbor distance with other nearby images; that is what the viewer illustrates with test images: none approaches . They are practical forms of memorization detection.
Regarding dataset size, Gu and colleagues train EDM on CIFAR-10 subsets without augmentation and measure the fraction of 10,000 generations meeting the criterion. With 20,000 or 10,000 images it stays near zero; with 5,000 or 2,000 appreciable memorization appears; with 1,000 images and training ten times longer than EDM’s it exceeds 90%. The fraction also grows with training epochs. Kadkhodaie and colleagues reach a compatible conclusion from another angle: networks trained on disjoint sets generate almost identical images when each set is large enough (about images in their examples), and memorize with small sets; this is studied in generalization mechanisms. Neither paper establishes a universal size: the threshold depends on data, model and training time.
CIFAR control with known copies
This cell generates viewer data. It reads CIFAR-10 at the p07-l02 revision, constructs shifted and recolored copies of train 0 to 7, searches exhaustively with faiss.IndexFlatL2 and recomputes candidate distances in float64. For shift-aware distance it traverses the 25 windows of each query and keeps the minimum for each train image; the exact neighbor under that minimum is always among the first candidates of the window achieving it. Set P07_L09_AUDIT=1 and P07_L09_RESULT to a new path.
import os
if os.environ.get('P07_L09_AUDIT') != '1':
print('Control CIFAR omitido: define P07_L09_AUDIT=1 y P07_L09_RESULT.')
else:
import base64, hashlib, io, json
from pathlib import Path
import numpy as np
from datasets import load_dataset
import faiss
from PIL import Image
REVISION='0b2714987fa478483af9968de7c934580d0bb9a2'
out=Path(os.environ['P07_L09_RESULT'])
if not out.is_absolute() or out.exists(): raise ValueError('P07_L09_RESULT: ruta absoluta y nueva')
data=load_dataset('uoft-cs/cifar10',revision=REVISION)
def pix(image):
return np.asarray(image.convert('RGB'),dtype=np.float32)/255
train=np.stack([pix(im) for im in data['train']['img']])
labels_train=np.array(data['train']['label'])
first=data['test'].select(range(8))
test=np.stack([pix(im) for im in first['img']]); labels_test=np.array(first['label'])
def shifted(a): # contenido 2 px abajo y 2 a la derecha, borde replicado
return np.pad(a,((2,0),(2,0),(0,0)),mode='edge')[:32,:32]
def recolored(a): # contraste 0.75 y brillo +0.15
return np.clip(.75*a+.15,0,1)
queries={'test':test,'shift':np.stack([shifted(a) for a in train[:8]]),
'color':np.stack([recolored(a) for a in train[:8]])}
def represent(metric,images):
if metric=='pixel': return [images.reshape(len(images),-1)]
if metric=='pooled': return [images.reshape(len(images),4,8,4,8,3).mean(axis=(2,4)).reshape(len(images),48)]
# 'shift': las 25 ventanas 28×28 de la consulta frente al centro 28×28 de la referencia
return [images[:,dy:dy+28,dx:dx+28].reshape(len(images),-1) for dy in range(5) for dx in range(5)]
def two_nearest(metric,ref_images,query_images,k=8):
ref=represent(metric,ref_images[:,2:30,2:30] if metric=='shift' else ref_images)[0]
index=faiss.IndexFlatL2(ref.shape[1]); index.add(np.ascontiguousarray(ref,dtype=np.float32))
best=[{} for _ in range(len(query_images))]
for view in represent(metric,query_images):
_,idx=index.search(np.ascontiguousarray(view,dtype=np.float32),k)
for i,cands in enumerate(idx):
diff=ref[cands].astype(np.float64)-view[i].astype(np.float64)
for j,d in zip(cands.tolist(),np.sqrt((diff*diff).mean(axis=1)).tolist()):
best[i][j]=min(d,best[i].get(j,np.inf)) # mínimo sobre desplazamientos
return [sorted(b.items(),key=lambda item:item[1])[:2] for b in best]
def png(a):
buf=io.BytesIO(); Image.fromarray(np.rint(a*255).clip(0,255).astype('uint8')).save(buf,format='PNG')
return 'data:image/png;base64,'+base64.b64encode(buf.getvalue()).decode('ascii')
rows=[]; images={}
for kind,q in queries.items():
for n in (1000,50000):
for metric in ('pixel','pooled','shift'):
for i,((n1,d1),(n2,d2)) in enumerate(two_nearest(metric,train[:n],q)):
rows.append({'kind':kind,'query':i,'count':n,'metric':metric,
'n1':n1,'d1':round(d1,6),'n2':n2,'d2':round(d2,6)})
images.setdefault(str(n1),png(train[n1]))
hits=sum(r['n1']==r['query'] for r in rows[-8:]) if kind!='test' else '-'
print(f'{kind:5s} n={n:5d} {metric:6s} d1',[round(r["d1"],3) for r in rows[-8:]],
'd1/d2',[round(r['d1']/r['d2'],2) for r in rows[-8:]],'original hallado',hits)
query_meta=[{'kind':kind,'query':i,'source':None if kind=='test' else i,
'label':int(labels_test[i] if kind=='test' else labels_train[i]),'image':png(q[i])}
for kind,q in queries.items() for i in range(8)]
payload={'kind':'control-cifar-real-sin-generador','data_revision':REVISION,
'sources':'test 0-7; copias de train 0-7','queries':query_meta,'neighbors':images,
'labels':{k:int(labels_train[int(k)]) for k in images},'rows':rows}
out.parent.mkdir(parents=True,exist_ok=True)
with out.open('x',encoding='utf-8') as f: json.dump(payload,f,ensure_ascii=False,separators=(',',':'))
print('filas',len(rows),'vecinos distintos',len(images),'sha256 JSON',hashlib.sha256(out.read_bytes()).hexdigest())npm run lab and open the connection link.The output feeding the viewer has SHA-256 fingerprint 055c16098d6b310fe9823f0cbd2d844a23045e42e9f0601553c46012d45e2e94; regenerating with the same versions should match it. IndexFlatL2 distance is a sum of squares in float32: we therefore recompute in float64 and divide by the coordinate count before the square root. Approximate search (IVF or HNSW indexes) would first require measuring recall against this exact search.
Train the same EDM on 1,000 images
The full model is p07-l05 EDM: 10,000 updates of 32 images on all 50,000 train images. The next cell trains the same network with the same recipe (edm objective, lognormal levels, horizontal flip with probability 0.5, Adam rate , bfloat16) on a fixed subset of 1,000 images, with the same number of updates. Same compute, fifty times less data: each image is seen about 320 times instead of 6.4. This is a far smaller budget than Gu and colleagues’, so your measured memorization need not resemble theirs; P07_L09_SUBSET_STEPS extends it. With P07_L09_SUBSET=1 it writes a model.pt in p07-l05 format to p07-l09/edm-1000/, also recording subset indices.
def train_edm_subset(output,count=1000,subset_seed=909,steps=10000,batch=32,seed=31,
save_every=1000,device='cuda'):
output=Path(output)
if (output/'model.pt').exists(): print('Ya terminada:',output); return
output.mkdir(parents=True,exist_ok=True)
resume=(output/'latest.pt').is_file()
indices=subset_indices(count,subset_seed)
images=load_cifar_uint8('train')[indices]
code='\n'.join(inspect.getsource(f) for f in (edm_target_loss,EDMPrecond.forward,DiffusionUNet.__init__,
DiffusionUNet.forward,train_edm_subset))
identity={'mode':'edm','sigma_data':.5,'steps':steps,'batch':batch,'lr':2e-4,'seed':seed,
'train_count':count,'subset_seed':subset_seed,'train_indices_sha256':sha_array(indices),
'train_images_sha256':sha_array(images),'flip_probability':.5,'distribution':'lognormal -1.2,1.2',
'precision':'autocast bf16','dataset_revision':CIFAR_REVISION,
'source_sha256':hashlib.sha256(code.encode('utf-8')).hexdigest()}
net=optimizer=None
try:
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
data_rng=torch.Generator().manual_seed(seed+100)
level_rng=torch.Generator().manual_seed(seed+200)
noise_rng=torch.Generator(device=device).manual_seed(seed+300)
net=DiffusionUNet().to(device).train()
optimizer=torch.optim.Adam(net.parameters(),lr=2e-4)
start,losses=0,[]
if resume:
ck=torch.load(output/'latest.pt',map_location='cpu',weights_only=True)
if ck['identity']!=identity: raise ValueError('Identidad incompatible con el checkpoint')
net.load_state_dict(ck['model']); optimizer.load_state_dict(ck['optimizer'])
for g,key in ((data_rng,'data_rng'),(level_rng,'level_rng'),(noise_rng,'noise_rng')): g.set_state(ck[key])
torch.set_rng_state(ck['cpu_rng']); torch.cuda.set_rng_state(ck['cuda_rng'],device)
start,losses=ck['step'],ck['losses']; del ck
print('Reanudando',output.name,'desde la actualización',start)
clock=time.perf_counter()
for step in range(start+1,steps+1):
ix=torch.randint(count,(batch,),generator=data_rng)
flip=torch.rand(batch,generator=data_rng)<.5
x=torch.from_numpy(images[ix.numpy()]).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)
sigma=torch.exp(-1.2+1.2*torch.randn(batch,generator=level_rng)).to(device)
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
loss=edm_target_loss(net,x,eps,sigma)
loss.backward(); optimizer.step()
if step%100==0 or step==steps:
losses.append({'step':step,'loss':float(loss.detach())})
print(f"actualización {step}/{steps} pérdida {losses[-1]['loss']:.4f} ({(step-start)/(time.perf_counter()-clock):.2f} act./s)",flush=True)
if step%save_every==0 or step==steps:
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}
publish_atomic(output/'latest.pt',lambda f:torch.save(state,f),overwrite=True); state=None
final={'model':net.state_dict(),'config':{**identity,'train_indices':indices.tolist(),'losses':losses}}
publish_atomic(output/'model.pt',lambda f:torch.save(final,f),overwrite=True)
print('modelo',output/'model.pt','huella',file_digest(output/'model.pt'))
finally:
net=optimizer=None; torch.cuda.empty_cache()
SUBSET_STEPS=int(os.environ.get('P07_L09_SUBSET_STEPS','10000'))
SUBSET_DIR=L09/('edm-1000' if SUBSET_STEPS==10000 else f'edm-1000-{SUBSET_STEPS}')
if os.environ.get('P07_L09_SUBSET')=='1':
train_edm_subset(SUBSET_DIR,steps=SUBSET_STEPS)
else:
print('Entrenamiento con 1000 imágenes definido. Para lanzarlo: P07_L09_SUBSET=1; resultado en',SUBSET_DIR)npm run lab and open the connection link.Generate and audit
The audit generates images from a model (EDM with p07-l05’s 35-evaluation Heun; the consistency student with one evaluation) and searches its own training set. Since both EDMs were trained with flips, the reference includes each flipped train image too, and a neighbor and its mirror count as the same image. For each generation it computes , , Gu and colleagues’ ratio and Carlini and colleagues’ calibrated ratio, in pixels and, if you provide the p07-l02 reference directory, in Inception features too. It reports the fraction with and its 95% Clopper-Pearson interval.
The decisive control is a held-out set of the same size. If the criterion triggers as often against train as against test images the model never saw, it detects simple images (skies, flat backgrounds), not copies. The search is therefore repeated with train images and test images drawn with a fixed seed. For the 1,000-image model comparison uses its entire train set; for the full model, a sample of 10,000 of 50,000. It also saves candidatos.png with the 16 most suspicious pairs for visual review. With P07_L09_MEMO=1 it audits the full teacher and 1,000-image EDM, leaving audit.json and candidatos.png in p07-l09/auditoria/<modelo>/; if P07_L02_REF is set it adds Inception features. P07_L09_MODEL audits another model.pt or student.pt, and P07_L09_SAMPLES changes the default 10,000 generations.
import importlib.util
def knn_rms(reference,queries,k,batch=1024):
# Vecinos exactos con FAISS; distancias RMS por coordenada, recalculadas en float64 para los dos primeros.
import faiss
ref=np.ascontiguousarray(reference,dtype=np.float32); qry=np.ascontiguousarray(queries,dtype=np.float32)
if ref.ndim!=2 or qry.ndim!=2 or ref.shape[1]!=qry.shape[1] or not len(ref) or not len(qry):
raise ValueError('Matrices no vacías con el mismo número de columnas')
if not (np.isfinite(ref).all() and np.isfinite(qry).all()): raise ValueError('Valores no finitos')
index=faiss.IndexFlatL2(ref.shape[1]); index.add(ref)
dist,idx=index.search(qry,min(k,len(ref)))
dist=np.sqrt(np.maximum(dist,0)/ref.shape[1]).astype(np.float64)
for s in range(0,len(qry),batch):
diff=ref[idx[s:s+batch,:2]].astype(np.float64)-qry[s:s+batch,None,:].astype(np.float64)
dist[s:s+batch,:2]=np.sqrt((diff*diff).mean(axis=2))
return idx,dist
def distinct(idx,dist,n_images,k):
# Un vecino y su espejo (índice + n_images) cuentan como la misma imagen.
out_i,out_d=[],[]
for row_i,row_d in zip(idx,dist):
seen={}
for j,d in zip(row_i.tolist(),row_d.tolist()):
if j%n_images not in seen: seen[j%n_images]=(j,d)
if len(seen)==k: break
pairs=sorted(seen.values(),key=lambda p:p[1]); out_i.append([p[0] for p in pairs]); out_d.append([p[1] for p in pairs])
return out_i,np.array(out_d)
def scores(queries,reference_images,with_mirror=True,k=50):
n=len(reference_images)
ref=np.concatenate([reference_images,reference_images[:,:,::-1]]) if with_mirror else reference_images # N×H×W×C
idx,dist=knn_rms(ref.reshape(len(ref),-1),queries.reshape(len(queries),-1),2*k)
nn,d=distinct(idx,dist,n,k)
return {'nn':[row[0] for row in nn],'d1':d[:,0],'ratio':d[:,0]/d[:,1],'carlini':d[:,0]/(.5*d[:,:k].mean(axis=1))}
def clopper_pearson(hits,n,level=.95):
from scipy.stats import beta
a=1-level
return (0. if hits==0 else float(beta.ppf(a/2,hits,n-hits+1)),1. if hits==n else float(beta.ppf(1-a/2,hits+1,n-hits)))
def summarize(s):
hits=int((s['ratio']<1/3).sum()); n=len(s['ratio'])
return {'fraction':hits/n,'hits':hits,'n':n,'ci95':clopper_pearson(hits,n),
'median_d1':float(np.median(s['d1'])),'min_carlini':float(s['carlini'].min())}
@torch.no_grad()
def generate(model_path,count,seed,device,batch=64):
saved=torch.load(Path(model_path),map_location='cpu',weights_only=True)
if 'ema' in saved: # estudiante de consistencia
model=Consistency(DiffusionUNet(),epsilon=saved['config']['epsilon'],sigma_data=.5)
model.load_state_dict(saved['ema'],strict=True); model=model.to(device).eval()
chunks=list(consistency_pixels(model,[80.],count,seed,device,batch)); indices=None
else: # EDM de p07-l05 o de la celda anterior
net=DiffusionUNet(); net.load_state_dict(saved['model'],strict=True); net=net.to(device).eval()
chunks=[]
for start in range(0,count,batch):
gen=torch.Generator(device=device).manual_seed(seed+start)
initial=80*torch.randn((min(batch,count-start),3,32,32),device=device,generator=gen)
sample,_=heun_edm(net,initial)
chunks.append(((sample.float().clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy())
indices=saved['config'].get('train_indices')
return np.concatenate(chunks),indices,file_digest(model_path) # N×32×32×3 uint8
def audit_model(model_path,output,count=10000,seed=31337,reference=None,device='cuda'):
output=Path(output)
if (output/'audit.json').exists(): print('Ya auditado:',output); return
output.mkdir(parents=True,exist_ok=True)
device=torch.device(device)
samples,indices,model_sha=generate(model_path,count,seed,device)
train=load_cifar_uint8('train').transpose(0,2,3,1)
if indices is not None: train=train[np.asarray(indices)]
test=load_cifar_uint8('test').transpose(0,2,3,1)
m=min(len(train),len(test)); rng=np.random.default_rng(seed+1)
train_m=train[np.sort(rng.choice(len(train),m,replace=False))] if m<len(train) else train
test_m=test[np.sort(rng.choice(len(test),m,replace=False))]
pixels=lambda a:a.astype(np.float32)/255
full=scores(pixels(samples),pixels(train))
report={'model_sha256':model_sha,'samples':count,'seed':seed,'train_count':len(train),'heldout_count':m,
'pixel':{'train':summarize(full),'train_m':summarize(scores(pixels(samples),pixels(train_m))),
'heldout_m':summarize(scores(pixels(samples),pixels(test_m)))}}
if reference is not None:
_,_,extractor,resize,_=load_fid_reference(reference,device)
feats=lambda a:np.concatenate([inception(a[s:s+256],extractor,resize,device) for s in range(0,len(a),256)])
fs,ft,fh=feats(samples),feats(train_m),feats(test_m)
mirror=lambda a:feats(a[:,:,::-1])
fs_ref_t=np.concatenate([ft,mirror(train_m)]); fs_ref_h=np.concatenate([fh,mirror(test_m)])
report['inception']={}
for name,ref in (('train_m',fs_ref_t),('heldout_m',fs_ref_h)):
idx,dist=knn_rms(ref,fs,100); _,d=distinct(idx,dist,m,50)
report['inception'][name]=summarize({'d1':d[:,0],'ratio':d[:,0]/d[:,1],'carlini':d[:,0]/(.5*d.mean(axis=1))})
order=np.argsort(full['ratio'])[:16] # pares más sospechosos para revisar a ojo
from PIL import Image
canvas=Image.new('RGB',(2*32*4+12,32*4))
mirrored=np.concatenate([train,train[:,:,::-1]])
for r,i in enumerate(order):
x0=(r%4)*(64+4); y0=(r//4)*32
canvas.paste(Image.fromarray(samples[i]),(x0,y0)); canvas.paste(Image.fromarray(mirrored[full['nn'][i]]),(x0+32,y0))
publish_atomic(output/'candidatos.png',lambda f:canvas.save(f,format='PNG'))
report['candidates']=[{'sample':int(i),'train_row':int(full['nn'][i])%len(train),'mirror':bool(full['nn'][i]>=len(train)),
'd1':float(full['d1'][i]),'ratio':float(full['ratio'][i])} for i in order]
text=json.dumps(report,ensure_ascii=False,indent=2).encode('utf-8')
publish_atomic(output/'audit.json',lambda f:f.write(text))
for space in ('pixel','inception'):
for name,value in report.get(space,{}).items():
print(f"{space:9s} {name:9s} d1/d2<1/3: {value['hits']}/{value['n']} IC95 {np.round(value['ci95'],4).tolist()} mediana d1 {value['median_d1']:.3f}")
return report
if importlib.util.find_spec('faiss') and importlib.util.find_spec('scipy'): # control sin GPU
a=np.array([[0.,0.],[2.,2.],[2.,2.1]]); idx,dist=knn_rms(a,np.array([[1.9,2.]]),3)
assert idx[0,0]==1 and abs(dist[0,0]-np.sqrt(.01/2))<1e-6 # la consulta se guarda en float32
i,d=distinct(np.array([[4,1,0]]),np.array([[.1,.2,.3]]),3,2)
assert i==[[4,0]] and np.allclose(d,[[.1,.3]])
print('control del buscador: vecino',int(idx[0,0]),'distancia',float(dist[0,0]),'| Clopper-Pearson 0/200:',clopper_pearson(0,200))
else:
print('Instala faiss-cpu==1.13.2 y scipy para el control del buscador.')
if os.environ.get('P07_L09_MEMO')=='1':
count=int(os.environ.get('P07_L09_SAMPLES','10000'))
models=[Path(os.environ['P07_L09_MODEL'])] if os.environ.get('P07_L09_MODEL') else [TEACHER,SUBSET_DIR/'model.pt']
for path in models:
name=path.parent.name+('' if count==10000 else f'-{count}')
print('== auditoría de',path); audit_model(path,L09/'auditoria'/name,count=count,reference=os.environ.get('P07_L02_REF'))
else:
print('Auditoría definida. Para lanzarla: P07_L09_MEMO=1; resultados en',L09/'auditoria')npm run lab and open the connection link.In the short check, none of the test teacher’s 128 generations met the criterion against either train or held-out data, and median pixel was 0.195 against train and 0.196 against test: no detectable memorization, as expected from a barely trained model, with a 2.8% upper interval bound showing how little 128 generations tell us. The result sought with full models has three readings. If the 1,000-image model memorizes, its fraction against train will be clearly higher than against an equally sized held-out set, and candidatos.png pairs will be almost identical. If the full model does not memorise detectably, both fractions will be similarly low; zero among 10,000 generations still leaves a one-sided 95% upper bound of 0.03%, not proof of absence. If both fractions are similarly high, the criterion is detecting simple images and must be tightened or the representation changed, rather than drawing conclusions about the model.
Interpret a close match
A nearby neighbor is a hypothesis, not a verdict. Inspect every candidate visually and consider crops, shifts, flips and color changes: the viewer shows that one representation can miss a copy detected by another, and that a small distance may result from a simple image with many similar neighbors. A match does not prove which example training saw; if the dataset contains duplicates, several train images can explain the same generation. Fix threshold and representation before viewing results: picking a threshold after seeing a striking case turns the audit into a search for confirmation.
Report the two populations and denominators separately: generation count and reference size . The minimum mechanically falls as grows, so model comparisons use equal-sized references and an equally sized held-out set. A fraction based on few generations has a wide interval: with 200 generations and no cases, the one-sided 95% upper bound still allows a rate near 1.5%.
For unconditionally generated images, the model supplies no class: if one is added it comes from a classifier or other annotation. A label mismatch with the neighbor may be due to classifier or annotation error and does not alone decide whether two images are copies. Memorization is also a privacy risk: Carlini and colleagues show that training data can be extracted from diffusion models and that membership inference works better with longer training. Their defensive recommendations include deduplicating training data, differentially private training and audits with canary examples. If an audit finds sensitive candidates, limit their distribution and retain only the minimum necessary evidence.
Exercises
import torch
def consistency_distillation_loss(student, ema_student, teacher_step, x, sigmas):
return student(x,sigmas[0]).square().mean()