Conditioning and classifier-free guidance
Condition diffusion on class, implement classifier-free guidance, and sweep its scale to measure the fidelity–diversity tradeoff.
After this lesson you can
- Add class conditioning with an embedding and condition dropout.
- Implement classifier-free guidance and quantify its evaluation cost.
- Sweep guidance scale and plot FID, precision and recall.
- Compare with a noisy-image classifier in a reduced experiment.
Before you start
Ask for an airplane and get an airplane
The previous lesson’s EDM generates CIFAR-10 images without letting us choose the result: airplane, frog or truck in data proportions. To request a class, in principle provide the label to the network and train on (image, class) pairs. This conditioned model learns and, if perfect, its “airplane” samples would be exactly as varied as training-set airplanes.
In practice there is an awkward problem: conditioned models without extra help produce many samples that barely resemble their class. The network spreads capacity and the label, one vector among thousands of pixels, carries little weight. Almost all current conditioned systems, from ImageNet to text-to-image models, address this using guidance: at every sampling step they push the state toward greater class probability, with a user-chosen scale . This is the most important and most treacherous conditioned-sampling control: raising it yields more typical samples, but beyond a point makes them all alike.
This lesson builds both forms of guidance, with and without an external classifier, proves which distribution they target and what they do not guarantee, and provides a full CIFAR-10 lab sweeping scale while measuring FID, precision and recall.
Start with guidance on a density that can be calculated completely. The population has two equiprobable classes on a line, and . Guidance at scale replaces class density with “tilted” density , justified below. Move the scale: recovers the class exactly; moves mass away from the other class and narrows it; returns to the full mixture.
Two observations guide the lesson. With mean shifts from to and standard deviation from to : guidance not only removes ambiguous samples, it also shifts the class outward and removes variance present in the data. Mass on the wrong side falls from at to at : samples are more “unmistakable.” More class fidelity at the expense of diversity is the tradeoff measured on images.
import numpy as np
x=np.linspace(-6,6,241)
positive=np.exp(-.5*(x-1)**2)/np.sqrt(2*np.pi)
negative=np.exp(-.5*(x+1)**2)/np.sqrt(2*np.pi)
marginal=(positive+negative)/2
posterior=positive/(positive+negative)
def quadrature(v):
return np.sum((v[:-1]+v[1:])*.025) # trapecios con paso 0.05
for w in (0,1,2,3,5):
raw=marginal*posterior**w
z=quadrature(raw)
mean=quadrature(x*raw)/z
sd=np.sqrt(quadrature((x-mean)**2*raw)/z)
wrong=quadrature(np.where(x<0,raw,0))/z
print(f"w={w}: media {mean:.3f} desviación {sd:.3f} masa en x<0 {wrong:.3f} pico {np.max(raw/z):.3f}")
if w==1:
assert np.allclose(raw,.5*positive) # con w=1 la inclinada es la claseThe conditional score from Bayes
Recall the previous lesson’s additive representation: with , and denoiser wrapped with EDM preconditioning. By Tweedie’s identity, noisy-marginal score is , and the sampler integrates probability-flow ODE .
The conditioned model gives score and the unconditioned one the score of marginal . Bayes’ theorem, applied at every noise level, connects them.
Proof
By Bayes, , positive and differentiable by assumption. Taking logarithms, . The last term does not depend on and vanishes on differentiation. For the assumptions always hold: is convolution of a distribution with a Gaussian, hence positive and .
∎This is the conditional-score decomposition: to move from marginal to class, add a classifier gradient. But not just any classifier: is class probability given the noisy image at level . A classifier trained on clean images knows nothing of , almost pure noise, and its gradient there is meaningless.
Classifier guidance
Classifier guidance (Dhariwal and Nichol, 2021) separately trains a classifier on images corrupted with the same noise distribution as the diffusion model, and samples using
where the second form follows by multiplying the first by and adding . With and an exact classifier this is the theorem above. Surprisingly does not work well: the authors observed that guiding an unconditional ImageNet model at scale 1 made the classifier assign around 50% to the requested class but images did not resemble it; at scales above 1 probability rose near 100% and images did belong to the class. Their interpretation matches the interactive: , so scale samples a “sharpened” class proportional to .
Their table 4 quantifies the tradeoff on ImageNet 256×256 with a conditioned model: no guidance, FID 10.94, precision 0.69 and recall 0.63; scale 1, FID 4.59, precision 0.82 and recall 0.52; scale 10, FID 9.11, precision 0.88 and recall 0.32. Precision rises throughout, recall falls throughout and FID has an intermediate minimum.
Classifier guidance has three practical problems:
- A second model. A classifier robust across all noise levels must be trained, unavailable in pretrained model collections because almost-noise images are not ordinarily classified.
- A backward pass per evaluation. The input gradient requires backpropagation through the classifier at every field evaluation, with autograd enabled during sampling.
- Suspicious gradients. Pushing an image toward higher classifier confidence resembles a gradient-based adversarial attack. Ho and Salimans note this raises the question whether guidance improves classifier-based metrics such as FID and IS merely by exploiting those classifiers. That doubt motivated guidance without classifier gradients.
Classifier-free guidance
Ho and Salimans’s (2022) idea fits in one line. By the theorem, the implicit classifier gradient is the difference of two scores a single conditioned model can provide if it can also operate without a condition:
Thus is the unconditioned model, the conditioned one without extrapolation, and extrapolates beyond the conditioned model in the direction separating it from the unconditioned one. Dropout independence matters: if the null marker appeared more in some classes, branch would learn a biased marginal and the difference would no longer be the gradient of . If , the null branch is never trained and is whatever a random embedding produces. Ho and Salimans tried on ImageNet 64×64: 0.1 and 0.2 perform nearly equally and 0.5 is worse across the frontier, so a small fraction of training for the null branch suffices.
Beware conventions. The original paper writes , making its the conditioned model without guidance. Expanding, : our scale is . Current libraries usually use ours (guidance_scale in diffusers), but write the formula before comparing values between papers.
Any parametrization works if consistent. In VP diffusion, ; in additive diffusion, . Both are affine in score with coefficients depending only on and level, and an affine combination with weights summing to one, , commutes with any affine map. Thus combining , or gives the same sampler, provided both branches use the same parametrization and the same and . Do not mix a noise prediction with a data prediction without conversion.
Proof
By the preceding theorem, . Thus . Constant , finite by integrability, does not depend on and does not change the gradient. Since , integrability is automatic for : .
∎This is exactly the first interactive’s blue curve and why guidance “sharpens” the class: with penalizes regions where the class is merely likely and rewards those where it is nearly certain.
Step 1 of 3. What is the difference s_y − s₀ between conditional and marginal scores?
What the formula does not guarantee
It would be convenient to read the theorem as “CFG samples .” That is false. The sampler traverses family from to zero, but that family is not obtained by adding noise to the clean tilt: raising to a power and convolving with a Gaussian do not commute. A Gaussian case, explicit throughout, measures the difference.
Proof
The pair is Gaussian with , and . Conditioning gives with and . Write , so . Guided score is affine in :
where the last equality follows by combining fractions: . With an affine field, ODE is linear, maps Gaussians to Gaussians, and variance satisfies . Changing to with gives , integrated between and :
Initial variance is that of , , and as . Rearranging, . For the clean tilt, has precision , hence variance . Finally, and ; by Bernoulli’s inequality, for and , with the reverse for and equality for .
∎With and , guided ODE variance ends at , four times smaller than the clean tilt . Strong guidance compresses diversity more than its naive reading suggests. The cell checks this by numerically integrating the ODE without using the closed form.
import numpy as np
from scipy.integrate import solve_ivp
def guided_ode(tau2,y,w,smax=1000.):
a=1+tau2
def field(s,state):
mu,var=state
u=1+s*s
P=1/u+w/(u*(a*u-1))
b=w*y/(a*u-1)
return [s*(P*mu-b),2*s*P*var] # dx/dσ = σ(P x − b)
U=1+smax**2
P0=1/U+w/(U*(a*U-1))
start=[w*y/(a*U-1)/P0,1/P0] # la inclinada exacta en σ_max
sol=solve_ivp(field,(smax,0.),start,method="LSODA",rtol=1e-11,atol=1e-13)
return sol.y[0,-1],sol.y[1,-1]
for tau2,y,w in ((.5,1.,1.),(.5,1.,3.),(1.,1.,2.),(1.,1.,.5)):
mu,var=guided_ode(tau2,y,w)
closed=(tau2/(1+tau2))**w
assert abs(var-closed)<1e-6*max(1,closed)
print(f"τ²={tau2}, w={w}: EDO media {mu:.4f} varianza {var:.5f} (fórmula {closed:.5f}) | "
f"inclinación limpia media {w*y/(tau2+w):.4f} varianza {tau2/(tau2+w):.5f}")Means differ too: at the ODE ends at and clean tilt at . Neither mean nor variance matches the distribution the formula appears to define. Images also add approximate scores and 35-evaluation discretization, so the only reliable course is to measure the output.
Cost: two branches per evaluation
Each guided-field evaluation requires and : twice the network passes. Two separate calls can be avoided. Concatenate null and conditioned batches with the same images and levels into one batch of size , then split output halves. For small batches that do not fill the GPU, a double batch is much faster than two sequential calls; for saturating batches latency approaches double. In all cases total compute is two evaluations per image and activation memory also doubles. If the double batch does not fit, split into microbatches without changing the formula.
There are several ways to reduce this cost, worth knowing because they appear in large systems:
- Skip the unused branch. With only conditioned is needed, and with only null; a sweep including these points costs half there.
- Guide only over a noise interval. Kynkäänniemi and coauthors (2024) find guidance harmful at high noise, reducing diversity, and almost irrelevant at low noise; applying it only over an intermediate interval improves both quality and FID, and one branch suffices outside.
- Distill guidance. Meng and coauthors (2023) train a student receiving as input to reproduce the teacher’s guided output in one pass, then further reduce steps.
Classifier guidance is not cheaper: every evaluation requires a model pass, a classifier pass and backpropagation through the classifier to input. Compare times by measurement, not call counts.
Sweeping the scale
Scale cannot be chosen from the formula: the Gaussian theorem shows its actual effect depends on model and sampler. Choose by measurement. A classifier-free guidance sweep evaluates one model on a scale grid holding everything else fixed: weights, sampler and NFE, paired initial-noise seeds, image count per class, and p07-l02’s evaluation pipeline with its extractor. Each scale gives three numbers:
- FID, Fréchet distance between Gaussians fitted to Inception features of samples and data. It penalizes both poor samples and missing variety because it compares means and covariances.
- Precision, fraction of generated samples inside the approximate real-data manifold: the union of balls centered on each real feature with radius equal to distance to its th neighbor (Kynkäänniemi and coauthors, 2019, with ). Measures fidelity.
- Recall, the same with roles reversed: fraction of real data inside the approximate sample manifold. Measures coverage.
The guidance tradeoff predicts curve shape: increasing precision, decreasing recall and intermediate-scale FID minimum, because atypical samples weigh on the left and lost diversity on the right. Ho and Salimans measured this on ImageNet 64×64 with 50,000 samples per scale (): FID 1.80 without guidance, 1.55 at their (our ), and 12.6 at their (our ), with Inception Score growing with scale. They did not publish precision or recall; the reference for those is Dhariwal and Nichol’s table above.
Before images, examine a full sweep on a fully checkable problem. Data comprise three classes in the plane, each an equally weighted mixture of three Gaussians with standard deviation . The “model” is an explicit mixture with two typical real-network flaws: each component is slightly wider than truth (variance ), and the conditioned branch is poorly conditioned, reserving 30% of its mass for the all-class marginal. Denoisers are exact posterior means of this mixture, the sampler is EDM Heun with 35 evaluations, and metrics compare 1000 class-0 samples with 1000 class-0 data points. In two dimensions there is no Inception: instead of FID use the same Fréchet distance on coordinates.
import numpy as np
MEANS=np.array([[-2.2,-.6],[-1.4,.5],[-2.6,.7],[2.2,-.6],[1.4,.5],[2.6,.7],
[0.,2.2],[.9,3.],[-.9,3.]])
CLASS=np.repeat(np.arange(3),3)
V=.3**2+.2**2 # varianza de cada componente del modelo (los datos tienen 0.3²)
LEAK=.3 # fracción de la marginal dentro de la rama condicionada
def denoise(x,sigma,weights):
# E[x0 | x] para la mezcla del modelo a nivel de ruido sigma
d2=((x[:,None,:]-MEANS[None])**2).sum(-1)
logits=np.log(weights)-d2/(2*(V+sigma**2))
r=np.exp(logits-logits.max(1,keepdims=True))
r/=r.sum(1,keepdims=True)
return r@MEANS+V/(V+sigma**2)*(x-r@MEANS)
UNCOND=np.full(9,1/9)
def cond_weights(y): return (1-LEAK)*(CLASS==y)/3+LEAK/9
def edm_levels(n=18,smax=80.,smin=.002,rho=7):
i=np.arange(n)/(n-1)
return np.append((smax**(1/rho)+i*(smin**(1/rho)-smax**(1/rho)))**rho,0.)
def cfg_heun(z,y,w):
x=80*z
wc=cond_weights(y)
def D(x,s):
u=denoise(x,s,UNCOND)
return u+w*(denoise(x,s,wc)-u)
s=edm_levels()
for a,b in zip(s[:-1],s[1:]):
d=(x-D(x,a))/a
trial=x+(b-a)*d
x=trial if b==0 else x+(b-a)*(d+(trial-D(trial,b))/b)/2
return x
def frechet(a,b):
ca,cb=np.cov(a.T),np.cov(b.T)
ev=np.linalg.eigvals(ca@cb).real.clip(0)
return float(((a.mean(0)-b.mean(0))**2).sum()+np.trace(ca)+np.trace(cb)-2*np.sqrt(ev).sum())
def precision_recall(real,gen,k=3):
def dist(a,b): return np.sqrt(np.maximum(0,(a*a).sum(1)[:,None]+(b*b).sum(1)[None]-2*[email protected]))
def radii(x):
d=dist(x,x); np.fill_diagonal(d,np.inf)
return np.partition(d,k-1,axis=1)[:,k-1]
c=dist(real,gen)
return float((c<=radii(real)[:,None]).any(0).mean()),float((c<=radii(gen)[None]).any(1).mean())
rng=np.random.default_rng(6)
n=1000
real=MEANS[rng.integers(0,3,n)]+.3*rng.standard_normal((n,2)) # datos de la clase 0
z=rng.standard_normal((n,2)) # el mismo ruido inicial en todas las escalas
scales=[0,.5,1,1.5,2,2.5,3,3.5,4,5,6,8]
rows=[]
for w in scales:
g=cfg_heun(z,0,w)
p,r=precision_recall(real,g)
rows.append((w,frechet(g,real),p,r))
print(f"w={w:<4} Fréchet={rows[-1][1]:.3f} precisión={p:.3f} exhaustividad={r:.3f}")
print("Mínimo de la distancia de Fréchet en w =",min(rows,key=lambda t:t[1])[0])The interactive shows the first 300 samples with curves. Under “Your sweep,” load the file produced by the CIFAR-10 lab below to see the same with images: a grid of 16 airplanes generated from the same initial noise at every scale and FID, precision and recall curves.
Sweep the scale and notice three phases:
- From to : the model’s conditioned branch drops samples into other classes (at , 21% of samples are nearer other-class components). Guidance retrieves them: precision rises from to and Fréchet distance falls from to minimum at . Guidance compensates a model defect, exactly as with images.
- From to : guidance starts emptying the class-0 group nearest other classes, at , which falls from one-third of samples to 10% already at . Metrics barely see it yet. Recall even rises from to between and : as samples spread, their neighbor radii grow and cover more data. This is estimator artifact, not a diversity gain, and a reminder these metrics have their own variance and bias.
- From : that group vanishes and recall falls to , and . Precision also falls, to at , because extrapolation pushes samples outside data support, away from other classes: the two-dimensional analogue of oversaturated images from excessive guidance.
Fréchet distance, looking only at means and covariances, is minimized at even though the class has already lost much of one mode. A serious sweep therefore inspects all three metrics and samples, not FID alone.
Lab: classifier-free guidance on CIFAR-10
The lab conditions p07-l05’s EDM, fine-tunes with label dropout, trains a noisy-image classifier for comparison, and sweeps both guidance scales using FID-10k, precision and recall. It runs on your GPU with runtime=local; each cell defines functions and trains or evaluates only when its environment variable is enabled, so they can be read and run without that cost. All outputs go to directories you choose.
Pieces from previous lessons
The cell combines p07-l03’s U-Net, used by p07-l05’s EDM, and p07-l03 FID functions reading the feature reference created by p07-l02. They are repeated here so this lesson’s kernel does not depend on another.
import io, os, json, math, pathlib, hashlib, base64, uuid, shutil, inspect, copy, importlib.metadata
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from PIL import Image
def time_embedding(t,dim):
half=dim//2
scales=torch.exp(-math.log(10000)*torch.arange(half,device=t.device,dtype=torch.float32)/(half-1))
phase=t.float()[:,None]*scales[None,:]
return torch.cat((phase.sin(),phase.cos()),dim=1)
class Residual(nn.Module):
def __init__(self,cin,cout,tdim):
super().__init__()
self.n1=nn.GroupNorm(32,cin)
self.c1=nn.Conv2d(cin,cout,3,padding=1)
self.time=nn.Linear(tdim,cout)
self.n2=nn.GroupNorm(32,cout)
self.c2=nn.Conv2d(cout,cout,3,padding=1)
self.skip=nn.Identity() if cin==cout else nn.Conv2d(cin,cout,1)
def forward(self,x,t):
h=self.c1(F.silu(self.n1(x)))
h=h+self.time(F.silu(t))[:,:,None,None]
return self.skip(x)+self.c2(F.silu(self.n2(h)))
class Attention(nn.Module):
def __init__(self,channels,heads=4):
super().__init__()
assert channels%heads==0
self.heads=heads
self.norm=nn.GroupNorm(32,channels)
self.qkv=nn.Conv2d(channels,3*channels,1)
self.out=nn.Conv2d(channels,channels,1)
def forward(self,x):
b,c,h,w=x.shape
q,k,v=self.qkv(self.norm(x)).reshape(b,3,self.heads,c//self.heads,h*w).unbind(1)
q,k,v=(z.transpose(-1,-2) for z in (q,k,v))
h1=F.scaled_dot_product_attention(q,k,v).transpose(-1,-2).reshape(b,c,h,w)
return x+self.out(h1)
class DiffusionUNet(nn.Module):
def __init__(self,width=224):
super().__init__()
a,b,c=width,2*width,3*width
self.width=width
self.temb=nn.Sequential(nn.Linear(width,4*width),nn.SiLU(),nn.Linear(4*width,4*width))
self.stem=nn.Conv2d(3,a,3,padding=1)
self.down0=Residual(a,a,4*width)
self.reduce0=nn.Conv2d(a,a,3,stride=2,padding=1)
self.down1=Residual(a,b,4*width)
self.attn_down=Attention(b)
self.reduce1=nn.Conv2d(b,b,3,stride=2,padding=1)
self.down2=Residual(b,c,4*width)
self.mid=Residual(c,c,4*width)
self.up1=Residual(c+b,b,4*width)
self.attn_up=Attention(b)
self.up0=Residual(b+a,a,4*width)
self.final=nn.Sequential(nn.GroupNorm(32,a),nn.SiLU(),nn.Conv2d(a,3,3,padding=1))
def forward(self,x,t):
if x.ndim!=4 or x.shape[1:]!=(3,32,32) or t.shape!=(x.shape[0],):
raise ValueError("Se esperan imágenes (B,3,32,32) y tiempos (B,)")
t=self.temb(time_embedding(t,self.width))
h0=self.down0(self.stem(x),t)
h1=self.attn_down(self.down1(self.reduce0(h0),t))
h2=self.mid(self.down2(self.reduce1(h1),t),t)
up=F.interpolate(h2,scale_factor=2,mode="nearest")
up=self.attn_up(self.up1(torch.cat((up,h1),dim=1),t))
up=F.interpolate(up,scale_factor=2,mode="nearest")
return self.final(self.up0(torch.cat((up,h0),dim=1),t))
def file_sha(path):
with open(path,"rb") as f:
return hashlib.file_digest(f,"sha256").hexdigest()
def load_fid_reference(path,device):
from cleanfid.inception_torchscript import InceptionV3W
from cleanfid.resize import build_resizer
path=pathlib.Path(path)
record=json.loads((path/"fid_results.json").read_text(encoding="utf-8"))
if record["protocol"]!="cifar10-train-bootstrap-clean-fid-0.1.35":
raise ValueError("Protocolo de referencia incompatible")
if file_sha(path/"inception-2015-12-05.pt")!=record["extractor_sha256"]:
raise ValueError("Huella del extractor distinta")
if file_sha(path/"train_features.npy")!=record["train_sha256"]:
raise ValueError("Huella de características train distinta")
stats=np.load(path/"cifar10_reference.npz")
if str(stats["train_sha256"])!=record["train_sha256"]:
raise ValueError("La referencia no corresponde a las características")
features=np.load(path/"train_features.npy",mmap_mode="r")
if features.shape!=(50000,2048):
raise ValueError("Forma de referencia inesperada")
mean=torch.zeros(2048,device=device,dtype=torch.float64)
for start in range(0,len(features),4096):
chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)
mean+=chunk.sum(0)
mean/=len(features)
cov=torch.zeros((2048,2048),device=device,dtype=torch.float64)
for start in range(0,len(features),4096):
chunk=torch.as_tensor(np.array(features[start:start+4096],copy=True),device=device,dtype=torch.float64)-mean
cov+=chunk.T@chunk
cov/=len(features)-1
if not np.allclose(mean.cpu().numpy(),stats["mean_train"],rtol=1e-7,atol=1e-7):
raise ValueError("Media de referencia no coincide")
if not np.allclose(cov.cpu().numpy(),stats["cov_train"],rtol=1e-7,atol=1e-7):
raise ValueError("Covarianza de referencia no coincide")
del chunk,features
extractor=InceptionV3W(str(path),download=False).eval().to(device)
return mean,cov,extractor,build_resizer("clean"),record
def feature_fid(samples,mean,cov):
z=torch.as_tensor(samples,device=mean.device,dtype=torch.float64)
m=z.mean(0); centered=z-m
c=centered.T@centered/(len(z)-1)
def eig(x):
values,vectors=torch.linalg.eigh((x+x.T)/2)
scale=max(1.,float(values.abs().max()))
if float(values.min()) < -1e-8*scale:
raise ValueError("Covarianza no positiva")
return values.clamp_min(0),vectors
values,vectors=eig(c)
root=(vectors*values.sqrt())@vectors.T
middle,_=eig(root@cov@root)
result=float((m-mean).square().sum()+torch.trace(c)+torch.trace(cov)-2*middle.sqrt().sum())
if result < -1e-7*max(1.,float(torch.trace(c)+torch.trace(cov))):
raise ArithmeticError("FID negativo fuera de tolerancia")
return max(0.,result)
def image_grid(pixels):
canvas=Image.new("RGB",(128,128))
for i,image in enumerate(pixels[:16]):
canvas.paste(Image.fromarray(image),(32*(i%4),32*(i//4)))
stream=io.BytesIO()
canvas.save(stream,format="PNG")
return "data:image/png;base64,"+base64.b64encode(stream.getvalue()).decode("ascii")
print("Parámetros de la U-Net:",sum(p.numel() for p in DiffusionUNet().parameters()))npm run lab and open the connection link.The conditioned model and two branches
Use integer label 10 as null marker for CIFAR-10’s ten classes. To condition the U-Net without changing residual blocks, add an 11-entry class embedding to the noise-level embedding already reaching every block. Thus weight keys are U-Net’s plus class_embedding.weight, and the model can start from p07-l05’s EDM checkpoint with only this embedding new. Preconditioning is EDM with .
NULL_CLASS=10
def make_conditional_unet(base_class):
class ConditionalUNet(base_class):
def __init__(self,width=224):
super().__init__(width=width)
self.class_embedding=nn.Embedding(NULL_CLASS+1,4*width)
def forward(self,x,t,labels):
if x.ndim!=4 or x.shape[1:]!=(3,32,32) or t.shape!=(len(x),) or labels.shape!=(len(x),):
raise ValueError("Se esperan imágenes, tiempos y clases por lote")
if torch.any((labels<0)|(labels>NULL_CLASS)):
raise ValueError("Clase fuera de rango")
embedding=self.temb(time_embedding(t,self.width))+self.class_embedding(labels)
h0=self.down0(self.stem(x),embedding)
h1=self.attn_down(self.down1(self.reduce0(h0),embedding))
h2=self.mid(self.down2(self.reduce1(h1),embedding),embedding)
up=F.interpolate(h2,scale_factor=2,mode="nearest")
up=self.attn_up(self.up1(torch.cat((up,h1),dim=1),embedding))
up=F.interpolate(up,scale_factor=2,mode="nearest")
return self.final(self.up0(torch.cat((up,h0),dim=1),embedding))
return ConditionalUNet
class ConditionalEDM(nn.Module):
def __init__(self,net,sigma_data=.5):
super().__init__()
if sigma_data<=0: raise ValueError("sigma_data positiva")
self.net=net
self.sigma_data=sigma_data
def forward(self,x,sigma,labels):
if sigma.shape!=(len(x),) or labels.shape!=(len(x),) or torch.any(sigma<=0):
raise ValueError("Niveles y clases por imagen")
s=sigma.reshape((len(x),)+(1,)*(x.ndim-1))
d=self.sigma_data
total=s.square()+d*d
return d*d/total*x+s*d*total.rsqrt()*self.net(total.rsqrt()*x,sigma.log()/4,labels)
def dropped_labels(labels,probability,generator):
# Abandono independiente de la imagen, la clase y el nivel de ruido.
if not 0<=probability<=1: raise ValueError("Probabilidad fuera de [0,1]")
if torch.any((labels<0)|(labels>=NULL_CLASS)): raise ValueError("Clase real fuera de rango")
mask=torch.rand(labels.shape,device=labels.device,generator=generator)<probability
return torch.where(mask,torch.full_like(labels,NULL_CLASS),labels)
def cfg_denoise(model,x,sigma,labels,w):
b=len(x)
outputs=model(torch.cat((x,x)),torch.cat((sigma,sigma)),
torch.cat((torch.full_like(labels,NULL_CLASS),labels)))
uncond,cond=outputs[:b],outputs[b:]
return uncond+w*(cond-uncond)
# Control con una red de juguete que devuelve la etiqueta: la nula vale 10.
class FakeConditioned(nn.Module):
def forward(self,x,t,labels):
return torch.ones_like(x)*labels.reshape((len(x),)+(1,)*(x.ndim-1))
test=ConditionalEDM(FakeConditioned())
x=torch.zeros(2,1,1,1)
sigma=torch.full((2,),.5)
labels=torch.tensor([1,3])
for w in (0.,1.,2.):
print("w =",w,"salidas del denoiser guiado:",cfg_denoise(test,x,sigma,labels,w).flatten().tolist())
g=torch.Generator().manual_seed(12)
dropped=dropped_labels(torch.tensor([0,1,2,3]),1.,g)
assert torch.equal(dropped,torch.full((4,),10))
rate=(dropped_labels(torch.zeros(100000,dtype=torch.long),.1,g)==NULL_CLASS).float().mean().item()
print("Abandono con p = 0.1 en 100000 etiquetas:",round(rate,4))npm run lab and open the connection link.With and , preconditioning gives , so the toy network outputs times the label: in the null branch, and in conditioned branches. Guided outputs are linear combinations of these, and at extrapolation already gives a negative value for class 1: guidance is extrapolation, not a weighted average.
Guided sampling and noisy-image classifier
The comparison classifier is small: three convolutions with pooling and a noise-level embedding added to features. It trains on the denoiser’s lognormal level distribution. Classifier guidance starts from the same denoiser’s null branch, so both methods share marginal model, initial noise and evaluation, differing only in the class term’s source. The sampler is p07-l05 Heun: 18 positive levels from 80 to 0.02 with , plus zero, 35 field evaluations.
def classifier_gradient(classifier,x,sigma,labels):
with torch.enable_grad():
variable=x.detach().requires_grad_(True)
with torch.autocast(device_type=variable.device.type,dtype=torch.bfloat16,
enabled=variable.device.type=="cuda"):
logits=classifier(variable,sigma)
if logits.dtype in (torch.float16,torch.bfloat16):
logits=logits.float()
selected=F.log_softmax(logits,dim=1).gather(1,labels[:,None]).sum()
gradient=torch.autograd.grad(selected,variable)[0]
return gradient.detach()
def gaussian_classifier(x,sigma):
# Clases equiprobables N(+1,1) y N(-1,1): logits (x, -x), posterior sigmoide(2x).
return torch.cat((x,-x),dim=1)
points=torch.tensor([[-1.],[0.],[.7]],dtype=torch.float64)
sigma=torch.ones(len(points),dtype=torch.float64)
labels=torch.zeros(len(points),dtype=torch.long)
gradient=classifier_gradient(gaussian_classifier,points,sigma,labels)
posterior=torch.sigmoid(2*points)
score_positive=-(points-1)
score_marginal=posterior*score_positive+(1-posterior)*(-(points+1))
error=(gradient-(score_positive-score_marginal)).abs().max().item()
assert error<1e-12
print("∇ log p(y|x) del clasificador:",[round(v,6) for v in gradient[:,0].tolist()],
"| diferencia de scores, error máximo:",error)npm run lab and open the connection link.The cell checks on the first interactive’s mixture that classifier gradient is exactly the score difference , which CFG estimates without a classifier. Implementation detail: do not wrap classifier sampling in torch.inference_mode(), because enable_grad() does not recover autograd on tensors created in that mode. Freeze classifier parameters and use torch.no_grad() for the denoiser.
class NoisyClassifier(nn.Module):
def __init__(self):
super().__init__()
self.features=nn.Sequential(
nn.Conv2d(3,32,3,padding=1),nn.SiLU(),nn.AvgPool2d(2),
nn.Conv2d(32,64,3,padding=1),nn.SiLU(),nn.AvgPool2d(2),
nn.Conv2d(64,128,3,padding=1),nn.SiLU(),
nn.AdaptiveAvgPool2d(1),nn.Flatten())
self.level=nn.Sequential(nn.Linear(1,128),nn.SiLU(),nn.Linear(128,128))
self.output=nn.Linear(128,10)
def forward(self,x,sigma):
scaled=x/torch.sqrt(.25+sigma[:,None,None,None].square()) # varianza aproximadamente unitaria
return self.output(self.features(scaled)+self.level(sigma.log()[:,None]/4))
def guided_denoise(model,x,sigma,labels,w,method,classifier=None):
amp=dict(device_type=x.device.type,dtype=torch.bfloat16,enabled=x.device.type=="cuda")
if method=="cfg":
with torch.no_grad(), torch.autocast(**amp):
if w==1: return model(x,sigma,labels).float() # una sola rama
if w==0: return model(x,sigma,torch.full_like(labels,NULL_CLASS)).float()
return cfg_denoise(model,x,sigma,labels,w).float()
if method=="classifier":
if classifier is None: raise ValueError("Falta el clasificador")
with torch.no_grad(), torch.autocast(**amp):
base=model(x,sigma,torch.full_like(labels,NULL_CLASS)).float()
if w==0: return base
grad=classifier_gradient(classifier,x,sigma,labels)
s=sigma.reshape((len(x),)+(1,)*(x.ndim-1))
return base+w*s.square()*grad
raise ValueError("Método desconocido")
def guided_heun(model,x,labels,w,method="cfg",classifier=None):
levels=np.append(np.linspace(80**(1/7),.02**(1/7),18)**7,0.)
x=x.detach().float().clone()
calls=0
for s,q in zip(levels[:-1],levels[1:]):
sigma=torch.full((len(x),),float(s),device=x.device)
d=guided_denoise(model,x,sigma,labels,w,method,classifier)
slope=(x-d)/s
trial=x+(q-s)*slope
calls+=1
if q>0:
sigma2=torch.full((len(x),),float(q),device=x.device)
d2=guided_denoise(model,trial,sigma2,labels,w,method,classifier)
x=x+(q-s)*(slope+(trial-d2)/q)/2
calls+=1
else:
x=trial
return x,calls
sample,calls=guided_heun(ConditionalEDM(FakeConditioned()),torch.zeros(2,1,1,1),torch.tensor([1,3]),2.)
assert calls==35 and torch.isfinite(sample).all()
print("Control del muestreador: evaluaciones del campo",calls,"| evaluaciones de red por imagen con w=2:",2*calls)npm run lab and open the connection link.At the sampler evaluates one branch, as explained under cost; the result equals the general formula up to rounding. On CUDA passes use bf16 autocast and integration uses float32, as in p07-l05.
Train the conditioned denoiser and classifier
The cell prepares two separate training runs: cfg fine-tunes the conditioned denoiser with dropout , and classifier trains the noisy-image classifier. Both use the same CIFAR-10 revision as earlier lessons, pixels in , horizontal flip probability 0.5, levels , batches of 32 and Adam rate ; the denoiser uses EDM weighted loss and additionally saves an exponential moving average (EMA) of weights with decay 0.9999, which is evaluated.
Environment variables:
P07_L06_MODE:cfgorclassifier.P07_L06_OUT: new absolute directory for checkpoints and final model.P07_L06_CACHE: absolutedatasetscache directory (reuse p07-l05’s).P07_L06_BASE(optional,cfgonly): absolute path to p07-l05edmvariant’smodel.pt. If provided, U-Net starts from those weights and only class embedding starts from scratch; otherwise training starts from scratch.P07_L06_STEPS(optional): number of updates. Default 200,000 forcfg(6.4 million images, about 128 epochs) and 50,000 forclassifier. With 20, check the full pipeline in minutes before long training; this is how the cell was verified, along with both guided samplers, evaluation and viewer assembly.P07_L06_RESUME=1resumes after interruption from the checkpoint saved every 1000 steps.P07_L06_TRAIN=1starts training.
Load only your own checkpoints: torch.load with weights_only=True reduces code-deserialization risk, and the recorded SHA-256 identifies bytes, but neither certifies a third-party file’s origin.
DEFAULT_STEPS={"cfg":200000,"classifier":50000}
def publish_exclusive(path,write):
# Escribe en un temporal y lo enlaza con el nombre final sin sobrescribir nada.
path=pathlib.Path(path)
temporary=path.parent/("pending-"+uuid.uuid4().hex+".tmp")
owned=False
try:
with temporary.open("xb") as f:
owned=True
write(f)
os.link(temporary,path)
finally:
if owned: temporary.unlink(missing_ok=True)
def training_source_digest():
sources=[make_conditional_unet,ConditionalEDM.__init__,ConditionalEDM.forward,
NoisyClassifier.__init__,NoisyClassifier.forward,dropped_labels,
DiffusionUNet.__init__,DiffusionUNet.forward,
Residual.__init__,Residual.forward,Attention.__init__,Attention.forward,
time_embedding,load_cifar_train,train_conditioned,publish_exclusive,training_source_digest]
return hashlib.sha256("\n".join(inspect.getsource(f) for f in sources).encode("utf-8")).hexdigest()
def load_cifar_train(cache):
from datasets import load_dataset
ds=load_dataset("uoft-cs/cifar10",revision="0b2714987fa478483af9968de7c934580d0bb9a2",
cache_dir=str(cache),split="train")
images=np.stack([np.asarray(im.convert("RGB")) for im in ds["img"]])
labels=np.asarray(ds["label"],dtype=np.int64)
if images.shape!=(50000,32,32,3) or labels.shape!=(50000,):
raise ValueError("Partición inesperada")
return images,labels
def train_conditioned(mode,output,cache,base=None,resume=False,steps=None):
if mode not in ("cfg","classifier"): raise ValueError("Modo desconocido")
steps=DEFAULT_STEPS[mode] if steps is None else int(steps)
if steps<1: raise ValueError("Al menos una actualización")
output,cache=pathlib.Path(output),pathlib.Path(cache)
if not output.is_absolute() or not cache.is_absolute():
raise ValueError("Rutas absolutas obligatorias")
if base is not None:
base=pathlib.Path(base)
if not base.is_absolute() or mode!="cfg": raise ValueError("Base incompatible")
if resume and not (output/"latest.pt").is_file(): raise FileNotFoundError("Sin checkpoint")
if not resume and output.exists(): raise FileExistsError("El directorio debe ser nuevo")
if resume and (output/"model.pt").exists(): raise FileExistsError("Ya existe el modelo final")
if not torch.cuda.is_available(): raise RuntimeError("El entrenamiento requiere CUDA")
if not resume: output.mkdir(parents=True)
device=torch.device("cuda")
model=ema=optimizer=images=x=y=eps=sigma=loss=core=noisy=prediction=actual=weight=final=s=state=None
try:
images,labels=load_cifar_train(cache)
images_sha=hashlib.sha256(images.tobytes()).hexdigest()
labels_sha=hashlib.sha256(labels.tobytes()).hexdigest()
identity={"mode":mode,"steps":steps,"batch":32,"seed":47,"lr":.0002,
"sigma_data":.5,"dropout":.1 if mode=="cfg" else None,"ema_decay":.9999 if mode=="cfg" else None,
"flip_probability":.5,"log_sigma_mean":-1.2,"log_sigma_std":1.2,
"dataset_revision":"0b2714987fa478483af9968de7c934580d0bb9a2",
"images_sha256":images_sha,"labels_sha256":labels_sha,
"base_sha256":file_sha(base) if base else None,"source_sha256":training_source_digest(),
"versions":{name:importlib.metadata.version(name) for name in ("torch","numpy","datasets")}}
torch.manual_seed(47)
torch.cuda.manual_seed_all(47)
data_rng=torch.Generator(device="cpu").manual_seed(147)
level_rng=torch.Generator(device="cpu").manual_seed(247)
noise_rng=torch.Generator(device=device).manual_seed(347)
drop_rng=torch.Generator(device=device).manual_seed(447)
if mode=="cfg":
core=make_conditional_unet(DiffusionUNet)()
if base:
saved_base=torch.load(base,map_location="cpu",weights_only=True)
if saved_base["config"]["mode"]!="edm":
raise ValueError("La base debe ser la variante EDM de p07-l05")
if saved_base["config"]["train_images_sha256"]!=images_sha:
raise ValueError("Los datos de la base no coinciden")
keys=core.load_state_dict(saved_base["model"],strict=False)
if keys.missing_keys!=["class_embedding.weight"] or keys.unexpected_keys:
raise ValueError("Arquitectura base incompatible")
del saved_base
print("U-Net inicializada desde",base)
else:
print("Sin P07_L06_BASE: el denoiser empieza desde cero")
model=ConditionalEDM(core).to(device)
ema=copy.deepcopy(model).eval().requires_grad_(False)
else:
model=NoisyClassifier().to(device)
model.train()
optimizer=torch.optim.Adam(model.parameters(),lr=.0002)
start=0
losses=[]
if resume:
state=torch.load(output/"latest.pt",map_location="cpu",weights_only=True)
if state["identity"]!=identity: raise ValueError("Checkpoint incompatible")
model.load_state_dict(state["model"],strict=True)
if ema is not None: ema.load_state_dict(state["ema"],strict=True)
optimizer.load_state_dict(state["optimizer"])
for gen,key in ((data_rng,"data_rng"),(level_rng,"level_rng"),(noise_rng,"noise_rng"),(drop_rng,"drop_rng")):
gen.set_state(state[key])
torch.set_rng_state(state["cpu_rng"])
torch.cuda.set_rng_state(state["cuda_rng"],device)
start=int(state["step"])
losses=state["losses"]
state=None
def save_checkpoint(step):
if shutil.disk_usage(output).free<2*1024**3:
raise OSError("Se requieren 2 GiB libres")
temporary=output/("checkpoint-"+uuid.uuid4().hex+".tmp")
owned=False
state={"identity":identity,"step":step,"model":model.state_dict(),
"ema":ema.state_dict() if ema is not None else None,
"optimizer":optimizer.state_dict(),"data_rng":data_rng.get_state(),
"level_rng":level_rng.get_state(),"noise_rng":noise_rng.get_state(),
"drop_rng":drop_rng.get_state(),"cpu_rng":torch.get_rng_state(),
"cuda_rng":torch.cuda.get_rng_state(device),"losses":losses}
try:
with temporary.open("xb") as f:
owned=True
torch.save(state,f)
os.replace(temporary,output/"latest.pt")
finally:
if owned: temporary.unlink(missing_ok=True)
for step in range(start+1,steps+1):
index=torch.randint(len(images),(32,),generator=data_rng).numpy()
x=torch.from_numpy(images[index]).permute(0,3,1,2).to(device).float()/127.5-1
flip=(torch.rand(32,generator=data_rng)<.5).to(device)
x=torch.where(flip[:,None,None,None],x.flip(3),x)
y=torch.from_numpy(labels[index]).to(device)
sigma=torch.exp(-1.2+1.2*torch.randn(32,generator=level_rng)).to(device)
eps=torch.randn(x.shape,device=device,generator=noise_rng)
noisy=x+sigma[:,None,None,None]*eps
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda",dtype=torch.bfloat16):
if mode=="cfg":
actual=dropped_labels(y,.1,drop_rng)
prediction=model(noisy,sigma,actual)
s=sigma[:,None,None,None]
weight=(s.square()+.25)/(s*.5).square() # peso de EDM
loss=(weight*(prediction.float()-x).square()).mean()
else:
loss=F.cross_entropy(model(noisy,sigma).float(),y)
loss.backward()
optimizer.step()
if ema is not None:
with torch.no_grad():
for e,p in zip(ema.parameters(),model.parameters()): e.lerp_(p,1-.9999)
if step%100==0 or step==steps:
losses.append({"step":step,"loss":float(loss.detach())})
print(mode,"paso",step,"de",steps,"pérdida",round(losses[-1]["loss"],4),flush=True)
if step%1000==0: save_checkpoint(step)
final={"identity":identity,"model":(ema if ema is not None else model).state_dict(),"losses":losses}
publish_exclusive(output/"model.pt",lambda f:torch.save(final,f))
print("Modelo guardado:",output/"model.pt")
finally:
model=ema=optimizer=images=x=y=eps=sigma=loss=core=noisy=prediction=actual=weight=final=s=state=None
torch.cuda.empty_cache()
if os.environ.get("P07_L06_TRAIN")=="1":
train_conditioned(os.environ["P07_L06_MODE"],os.environ["P07_L06_OUT"],
os.environ["P07_L06_CACHE"],os.environ.get("P07_L06_BASE"),
os.environ.get("P07_L06_RESUME")=="1",os.environ.get("P07_L06_STEPS"))
else:
print("Para entrenar: P07_L06_TRAIN=1, P07_L06_MODE=cfg|classifier, P07_L06_OUT y P07_L06_CACHE.")npm run lab and open the connection link.To calibrate expectations: EDM with a larger network and about 200 million training images reaches FID 1.79 on conditioned CIFAR-10 with 35 evaluations and no guidance (Karras and coauthors, 2022). With 6.4 million images starting from p07-l05’s model your FID will be much higher; the shape of curves against , not their level, matters here. Denoiser loss should fall rapidly in the first few thousand steps and stabilize; classifier loss remains high because no network can distinguish classes at high noise.
Evaluate one sweep point
Each run evaluates one scale and writes a new JSON, so interruption does not lose measured points. It needs p07-l02’s FID reference (directory with fid_results.json, train_features.npy and Inception extractor) and installed clean-fid.
P07_L06_MODEL:model.ptfromcfgtraining.P07_L06_REF: p07-l02 reference directory.P07_L06_CACHE:datasetscache.P07_L06_RESULT: new absolute JSON result path in an existing folder.P07_L06_METHOD:cfg(default) orclassifier; withclassifieralso setP07_L06_CLASSIFIERto the classifier’smodel.pt.P07_L06_SCALE: scale .P07_L06_SAMPLES(optional): FID image count, default 10,000 (1000 per class, multiples of 10).P07_L06_EVAL=1starts evaluation.
FID compares class-balanced samples with statistics of the 50,000 training images. Precision and recall use the first 1000 generated samples (100 per class) versus 1000 real images (first 100 per class), with and the same extractor. Initial-noise seeds depend only on image position, so all scales start from exactly the same noise. Viewer grid uses 16 fixed class-0 (airplane) noises.
def precision_recall_cfg(real,generated,k=3):
# Bolas de radio igual a la distancia al k-ésimo vecino, sin contar el propio punto (p07-l02).
real=np.asarray(real,dtype=np.float64)
generated=np.asarray(generated,dtype=np.float64)
if (real.ndim!=2 or generated.ndim!=2 or real.shape[1]!=generated.shape[1]
or not np.isfinite(real).all() or not np.isfinite(generated).all()
or not 0<k<min(len(real),len(generated))):
raise ValueError("Características o k inválidos")
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()))
def evaluate_guidance(model_path,reference,cache,result_path,method,w,classifier_path=None,samples=10000):
model_path,reference,cache,result_path=map(pathlib.Path,(model_path,reference,cache,result_path))
if not all(p.is_absolute() for p in (model_path,reference,cache,result_path)):
raise ValueError("Rutas absolutas obligatorias")
if result_path.exists() or not result_path.parent.is_dir():
raise ValueError("El resultado debe ser nuevo y su carpeta debe existir")
if method not in ("cfg","classifier") or not np.isfinite(w) or w<0:
raise ValueError("Método o escala inválidos")
if samples<1000 or samples%10: raise ValueError("Al menos 1000 muestras, múltiplo de 10")
if method=="classifier":
if not classifier_path: raise ValueError("Falta la ruta del clasificador")
classifier_path=pathlib.Path(classifier_path)
if not classifier_path.is_absolute(): raise ValueError("Ruta absoluta del clasificador")
else:
classifier_path=None
if not torch.cuda.is_available(): raise RuntimeError("La evaluación requiere CUDA")
device=torch.device("cuda")
saved=classifier_saved=core=model=classifier=mean=cov=extractor=None
initial=sample=pixels=features=labels_batch=chosen=parameter=None
try:
saved=torch.load(model_path,map_location="cpu",weights_only=True)
identity=saved["identity"]
if identity["mode"]!="cfg": raise ValueError("El modelo no es el denoiser condicionado")
if identity["source_sha256"]!=training_source_digest():
raise ValueError("El código vigente no coincide con el del entrenamiento")
core=make_conditional_unet(DiffusionUNet)()
model=ConditionalEDM(core).to(device).eval()
model.load_state_dict(saved["model"],strict=True)
if method=="classifier":
classifier_saved=torch.load(classifier_path,map_location="cpu",weights_only=True)
classifier_identity=classifier_saved["identity"]
if classifier_identity["mode"]!="classifier":
raise ValueError("El checkpoint no es un clasificador")
keys=("images_sha256","labels_sha256","dataset_revision","log_sigma_mean","log_sigma_std","source_sha256","versions")
if any(classifier_identity[key]!=identity[key] for key in keys):
raise ValueError("Datos o distribución de ruido distintos")
classifier=NoisyClassifier().to(device).eval()
classifier.load_state_dict(classifier_saved["model"],strict=True)
for parameter in classifier.parameters(): parameter.requires_grad_(False)
_,labels=load_cifar_train(cache)
if hashlib.sha256(labels.tobytes()).hexdigest()!=identity["labels_sha256"]:
raise ValueError("Las etiquetas no coinciden con el entrenamiento")
indices=np.concatenate([np.flatnonzero(labels==c)[:100] for c in range(10)])
mean,cov,extractor,resize,record=load_fid_reference(reference,device)
if record["dataset_revision"]!=identity["dataset_revision"]:
raise ValueError("Revisión de referencia distinta")
real=np.array(np.load(reference/"train_features.npy",mmap_mode="r")[indices],dtype=np.float32)
chunks=[]
for start in range(0,samples,32):
count=min(32,samples-start)
labels_batch=torch.as_tensor(np.arange(start,start+count)%10,device=device,dtype=torch.long)
generator=torch.Generator(device=device).manual_seed(67000+start)
initial=80*torch.randn((count,3,32,32),device=device,generator=generator)
sample,calls=guided_heun(model,initial,labels_batch,w,method,classifier)
if calls!=35: raise AssertionError("NFE inesperado")
pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
resized=np.stack([resize(im) for im in pixels]).transpose(0,3,1,2)
with torch.no_grad():
features=extractor(torch.from_numpy(resized).to(device)).cpu().numpy()
chunks.append(features)
initial=sample=pixels=features=None
if (start+count)%1024==0 or start+count==samples:
print("Evaluadas",start+count,"de",samples,"imágenes",flush=True)
generated=np.concatenate(chunks)
fid=feature_fid(generated,mean,cov)
precision,recall=precision_recall_cfg(real,generated[:1000],3)
generator=torch.Generator(device=device).manual_seed(98003)
initial=80*torch.randn((16,3,32,32),device=device,generator=generator)
chosen=torch.zeros(16,device=device,dtype=torch.long)
sample,calls=guided_heun(model,initial,chosen,w,method,classifier)
pixels=((sample.clamp(-1,1)+1)*127.5).round().byte().permute(0,2,3,1).cpu().numpy()
eval_sources=[guided_heun,guided_denoise,cfg_denoise,classifier_gradient,
precision_recall_cfg,evaluate_guidance,load_fid_reference,feature_fid,image_grid]
eval_sha=hashlib.sha256("\n".join(inspect.getsource(f) for f in eval_sources).encode("utf-8")).hexdigest()
result={"method":method,"scale":w,"fid":fid,"precision":precision,"recall":recall,
"samples":samples,"precision_samples":1000,"k":3,"batch":32,
"class_grid":0,"grid_seed":98003,"sample_seed":67000,"nfe_fields":35,
"guidance_formula":"uncond+w*(cond-uncond)" if method=="cfg" else "uncond+w*sigma^2*grad log p(y|x)",
"model_sha256":file_sha(model_path),
"classifier_sha256":file_sha(classifier_path) if classifier_path else None,
"train_features_sha256":record["train_sha256"],"extractor_sha256":record["extractor_sha256"],
"dataset_revision":identity["dataset_revision"],"grid_png":image_grid(pixels),
"sampler":"Heun 18 positivos y cero","initial":"80 veces normal",
"precision_mode":"CUDA autocast bf16, integración float32","eval_source_sha256":eval_sha,
"cuda_version":torch.version.cuda,"device":torch.cuda.get_device_name(device),
"versions":{name:importlib.metadata.version(name) for name in
("torch","numpy","datasets","clean-fid","Pillow","scipy")}}
publish_exclusive(result_path,lambda f:f.write(json.dumps(result,ensure_ascii=False,indent=2).encode("utf-8")))
print("w =",w,"FID",round(fid,3),"precisión",precision,"exhaustividad",recall,"->",result_path)
finally:
saved=classifier_saved=core=model=classifier=mean=cov=extractor=None
initial=sample=pixels=features=labels_batch=chosen=parameter=None
torch.cuda.empty_cache()
if os.environ.get("P07_L06_EVAL")=="1":
evaluate_guidance(os.environ["P07_L06_MODEL"],os.environ["P07_L06_REF"],
os.environ["P07_L06_CACHE"],os.environ["P07_L06_RESULT"],
os.environ.get("P07_L06_METHOD","cfg"),float(os.environ["P07_L06_SCALE"]),
os.environ.get("P07_L06_CLASSIFIER"),int(os.environ.get("P07_L06_SAMPLES","10000")))
else:
print("Para evaluar una escala: P07_L06_EVAL=1 con P07_L06_MODEL, P07_L06_REF, P07_L06_CACHE, P07_L06_RESULT y P07_L06_SCALE.")npm run lab and open the connection link.A reasonable CFG grid is ; for classifier guidance, . Choose the grid before seeing results; if retaining the best scale, choose it on these measurements and confirm with different generation seeds (change 67000 in sample_seed): the minimum of a finite-noise sweep is downward biased.
Assemble the sweep for the viewer
The final cell combines JSONs of one guidance family into the file read by the interactive, checking shared model, classifier, reference, seeds, sampler and versions. Set P07_L06_POINTS to a JSON list of absolute paths and P07_L06_SWEEP to the new output path. To compare CFG and classifier guidance, generate two files and load them one after the other.
def assemble_sweep(paths,output):
paths=[pathlib.Path(p) for p in paths]
output=pathlib.Path(output)
if not paths or not all(p.is_absolute() for p in paths) or not output.is_absolute():
raise ValueError("Rutas absolutas y al menos un punto")
if output.exists() or not output.parent.is_dir(): raise ValueError("La salida debe ser nueva")
rows=[json.loads(p.read_text(encoding="utf-8")) for p in paths]
keys=("method","samples","precision_samples","k","batch","class_grid","grid_seed","sample_seed",
"nfe_fields","guidance_formula","model_sha256","classifier_sha256","train_features_sha256",
"extractor_sha256","dataset_revision","sampler","initial","precision_mode",
"eval_source_sha256","cuda_version","device","versions")
if any([row[key] for key in keys]!=[rows[0][key] for key in keys] for row in rows):
raise ValueError("Los protocolos no coinciden")
if len({row["scale"] for row in rows})!=len(rows): raise ValueError("Escalas duplicadas")
if len(rows)>30: raise ValueError("Demasiados puntos para el visor")
if any(not np.isfinite(row[key]) for row in rows for key in ("scale","fid","precision","recall")):
raise ValueError("Valores no finitos")
if any(row["scale"]<0 or row["fid"]<0 or not 0<=row["precision"]<=1
or not 0<=row["recall"]<=1 or not str(row["grid_png"]).startswith("data:image/png;base64,")
for row in rows):
raise ValueError("Métricas o cuadrícula inválidas")
digests={row["scale"]:file_sha(path) for row,path in zip(rows,paths)}
rows.sort(key=lambda row:row["scale"])
result={"schema":"p07-cfg-sweep-v1","method":rows[0]["method"],
"protocol":{key:rows[0][key] for key in keys},
"input_sha256":[digests[row["scale"]] for row in rows],
"rows":[{key:row[key] for key in ("scale","fid","precision","recall","grid_png")} for row in rows]}
publish_exclusive(output,lambda f:f.write(json.dumps(result,ensure_ascii=False,indent=2).encode("utf-8")))
print("Puntos",len(rows),"| método",result["method"],"| escalas",[r["scale"] for r in rows],"->",output)
if os.environ.get("P07_L06_POINTS"):
assemble_sweep(json.loads(os.environ["P07_L06_POINTS"]),os.environ["P07_L06_SWEEP"])
else:
print("Para reunir el barrido: P07_L06_POINTS (lista JSON de rutas) y P07_L06_SWEEP.")npm run lab and open the connection link.Expected results and checks
Sources suggest a CFG sweep should show the 2D mixture pattern: precision rising with , recall falling, and FID improving from to a somewhat larger scale then worsening under strong guidance. On ImageNet 64×64 Ho and Salimans’s minimum is at our , FID moving from 1.80 unguided to 12.6 at ; on CIFAR-10 with a weaker model the minimum is expected at a somewhat higher scale, as in the mixture, because guidance compensates more model error. Your measurement decides the exact position. Concrete checks:
- CFG point is the conditioned model without guidance; its FID should be close to p07-l05’s model if you started from it.
- Point is unconditioned; its precision should be lowest in the sweep.
- In grids, high scales should give airplanes increasingly similar to one another, with more saturated colors and uniform backgrounds.
- Classifier guidance here starts from the unconditioned branch. Dhariwal and Nichol observed scale 1 does not suffice for clearly class-like samples when guiding an unconditional model; expect the same and a classifier this small to trail CFG.
Implement guidance in one batch
import torch
def cfg_denoise(model,x,sigma,y,w):
passCommon mistakes
Summary
A conditioned model with label dropout gives two scores whose difference is the gradient of an implicit noisy-image classifier. Classifier-free guidance extrapolates in that direction with scale : at each level it targets tilted density , but the sampler’s final law is not the clean-data tilt (in the Gaussian case, concentrates still more). It costs two branches per evaluation, grouped in one batch. Choose scale by sweep: precision rises, recall falls and FID has a moderate-scale minimum.
The same guidance with text instead of class controls multimodal text-to-image models; typical scale there is much higher than on ImageNet and the text-fidelity versus diversity tradeoff is the same.