Guidance: classifier guidance and classifier-free guidance
Before this lesson: lesson 08 (the score and the noise prediction, score , Tweedie's formula) and lesson 09 (the reverse SDE, the probability-flow ODE, DDIM). You also need Bayes' rule and Bayesian inference (posterior likelihood prior). Time: about 75 minutes, plus the notebook.
Why this matters #
Most text-to-image diffusion models sample with classifier-free guidance. In the diffusers library the Stable Diffusion pipeline uses a guidance weight of by default. Without guidance, the same models give images that match the prompt poorly. Guidance is the standard example of a training trick (randomly dropping the condition) that gives a control knob at sampling time.
The knob has a price. Every guided step needs two network evaluations, and guidance reduces the diversity of the samples. In science this matters: an ensemble of weather or ground-motion samples is useful only if its spread is right, and guidance makes the spread too small. The same Bayes split of the score is also the starting point of diffusion methods for inverse problems and data assimilation (lesson 15), where the "classifier" is the likelihood of an observation.
1. Predict first #
2. The picture #
Bayes' rule for scores #
Let be a condition. Bayes' rule gives . Take the logarithm and the gradient with respect to . The term does not depend on , so it disappears:
In words: the conditional score is the unconditional score plus the gradient of a classifier . The classifier gradient points to where looks more like class .
The simplest case: two classes in 1D #
Take two classes with and Gaussian classes . The log-ratio of the two class densities is
So the classifier is logistic: . Its log-gradient is . It pushes to the right. The push is strong where looks like the other class () and weak far to the right, where the classifier is already sure.
Turning up the classifier. Multiply the classifier term by a guidance scale . The new score is the score of the density . For this is . For it is . For the classifier acts as if it were sharper (like a lower temperature), so mass moves to where the class is clear: fewer ambiguous samples and less diversity.
Diffusion needs the classifier at every noise level #
A diffusion sampler does not use the score of the data; it uses the scores of the noisy densities (lesson 09). So it needs the classifier of noisy inputs, . In our example with VP noising (, ), each class is again Gaussian: with . The same computation as above gives a logistic classifier with slope
The slope is at (clean data), then , and at . At high noise the class is hard to tell from , so the noisy classifier is almost flat and its gradient is small.
Move the noise level and watch the noisy classifier (top) flatten as the noise grows; the dashed grey curve is the clean classifier, which is the wrong function to use on noisy inputs. Then move the classifier scale (bottom). The orange guided density equals the blue class density at . For it gets narrower and moves right, and approaches 1. Everything is computed exactly, not learned.
There are two ways to get for a real model. Train a separate classifier on noisy inputs (classifier guidance), or take the difference of a conditional and an unconditional score from one network (classifier-free guidance). Section 3 derives both.
In the two-class example, what is the slope of the noisy classifier at , and what does it mean for guidance at that noise level?
. At high noise carries little information about the class, so the correct noisy classifier is flat. Using the clean classifier would give a confident but wrong gradient.
3. Definitions and main results #
Theorem 1 (the conditional score at each noise level) #
For every ,
Proof.
- Bayes' rule for the pair : . Noising does not change the distribution of , so is the same at every .
- Take the log and the gradient in . The term does not depend on , so its gradient is 0.
- Marginalize over the clean data: . Given , the noisy is plus independent noise, so it carries no extra information about : .
Step 3 says that the noisy classifier averages the clean classifier over the denoising posterior . A clean classifier evaluated at is a different function; on noisy inputs it is also out of distribution, so its gradients are not meaningful.
Classifier guidance #
Classifier guidance (Dhariwal and Nichol 2021, section 4) trains a classifier on noisy inputs and samples with the score of :
Multiply by to get the guided noise prediction (score ):
This is their equation 14, used inside DDIM. (For ancestral sampling their algorithm 1 instead shifts the mean of each step by .) Their classifier is the downsampling half of the U-Net, trained on the same noising distribution. With on an unconditional ImageNet model, the classifier gave the target class about 50% probability, but the samples did not look like the class; a larger fixed this. The cost: a second network trained on noisy data, and a backward pass through it at every step.
At one step, , the unconditional prediction is (1D), the classifier gradient is and the scale is . What is the guided noise prediction?
The guided score is score . Converting to multiplies by , so the classifier term enters as . The noise points away from the data, so a push toward the class lowers .
Classifier-free guidance #
Classifier-free guidance (Ho and Salimans 2022) needs no classifier.
- Training (their algorithm 1). Train one network . In each training example, replace the condition by the null token with probability . This is called condition dropout. They found and equally good and worse. The network learns the conditional and the unconditional model at the same time.
- Sampling (their algorithm 2). At each step evaluate both and (one batch of two, so 2 NFE per step) and use in any sampler of lesson 09.
Theorem 2 (CFG is the conditional model plus implicit-classifier guidance) #
Let be the implicit classifier gradient ( by Theorem 1). For exact noise predictions, and
Proof.
- Both scores are of their prediction, so .
- Rearrange: .
- Substitute from step 1. The result is the classifier-guidance formula applied to the conditional model, with scale and classifier gradient .
- In score form the guided score is . This is also classifier guidance with scale on the unconditional model.
So no classifier is trained: the generative model is the classifier, through . Ho and Salimans add a caveat: a real network's fields are not exactly gradients of anything, so in general no classifier exists whose gradient gives the guided field.
Move the guidance weight . The 8 Gaussians are split into a target class (blue) and another class (grey). The scores are exact, not learned, and the orange samples come from the guided probability-flow ODE. At about half of the samples are in the wrong class; at (exact conditional model) all are right. For the samples move outward past the modes (the mean radius grows above 2). Switch to "two halves" and watch the middle modes of the class take more samples than the edge modes. Switch to the weak conditional model (80% on the class) to see guidance raise the accuracy above what gives.
In Ho and Salimans' convention a paper reports guidance weight . Which weight is this in the convention , and what does mean there?
, so . With the formula returns : the conditional model, no guidance. returns .
What guidance does to the sampled distribution #
At noise level the guided score is the score of
It is tempting to conclude that the sampler returns , the tilted target. It does not, except for and :
- The PF-ODE and the reverse SDE reproduce the marginals of a diffusion only if the scores belong to one diffusion path, that is, if each is convolved with the noise kernel (lesson 09).
- Noising (a convolution with a Gaussian) and tilting (powers and products of densities) do not commute. So is not the noised . The worked example in section 4(b) shows this with numbers.
- So the guided fields belong to no single diffusion path, and the result depends on the sampler. DDIM-type (ODE) and DDPM-type (SDE) sampling with CFG give different distributions, and neither is (Bradley and Nakkiran 2024 analyze CFG as a predictor–corrector method).
Proposition 3 (guided PF-ODE in a linear-Gaussian model). In 1D, let the unconditional density be and the conditional density with (for example the posterior of a Gaussian prior after a noisy observation). Use VE noising , so and . Let . The guided PF-ODE, started from with , ends at a Gaussian with variance . The tilted target has variance .
Proof of Proposition 3
- The guided score is with . Since , .
- The VE PF-ODE is . It is affine in , so a Gaussian start stays Gaussian, and the variance obeys .
- Note . Integrate from down to 0: .
- With , the factor in front of tends to 1 as .
The ODE interpolates the variances geometrically. The tilted target interpolates the precisions (inverse variances) linearly. For and the ODE result is always the narrower one: guidance overshoots even the tilted target.
In Proposition 3 take , and . Which variances do the guided PF-ODE result and the tilted target have?
ODE: . Tilted target: . The ODE result is narrower than the tilted target, and both are narrower than .
The fidelity–diversity trade-off #
- Numbers (Dhariwal and Nichol, table 4, conditional ImageNet , classifier scale ). No guidance: FID 10.94, precision 0.69, recall 0.63. : FID 4.59, precision 0.82, recall 0.52. : FID 9.11, precision 0.88, recall 0.32. Precision (how many samples look real) rises, recall (how much of the data distribution is covered) falls, and FID, which measures both, is best in between (lesson 14). With CFG, Ho and Salimans found the best FID at on ImageNet and on ( and ). The Inception score kept rising up to the largest value they tested, .
- Oversaturation. A large extrapolates far beyond both predictions and gives over-exposed, oversaturated images. Two remedies: dynamic thresholding (Imagen, in pixel space) and CFG rescale (Lin et al. 2024, section 3.4): rescale the guided prediction so that its standard deviation matches that of the conditional prediction, then mix it with the unrescaled one (factor ).
- Cost. 2 NFE per step: guidance doubles every NFE count of lesson 09.
Recent fixes (as of 2024) #
Limited-interval guidance (Kynkäänniemi et al., NeurIPS 2024). The authors found that guidance is "clearly harmful toward the beginning of the chain (high noise levels), largely unnecessary toward the end (low noise levels), and only beneficial in the middle". So they use only in a band of noise levels. On ImageNet-512 this improved the record FID from 1.81 to 1.40. Steps outside the band also cost only 1 NFE. Proposition 3's model shows why high noise is harmful: as the centre of tends to , so at high noise guidance pulls every sample toward one extrapolated point. This removes diversity before the details are decided.
Move the interval ends and . Both panels use the same weak conditional model (80% of its mass on the class) and the same starting noise; the scores are exact. Left: guidance at every level. Right: guidance only for in the yellow band, and the plain conditional model elsewhere. Notice that guidance at high noise (move above 2) mainly moves samples to the two middle modes of the class: the effective number of modes drops. Guidance only in the middle band keeps the modes balanced and still gives high accuracy, at a lower NFE.
Autoguidance (Karras et al., NeurIPS 2024). Guide with a smaller or shorter-trained version of the same conditional model instead of the unconditional model: . The two models make similar errors, so the difference points toward better samples instead of away from the unconditional distribution. It improves quality without the same loss of variation (record FIDs 1.01 on ImageNet-64 and 1.25 on ImageNet-512 with public networks).
A text-to-image pipeline uses 30 sampler steps with CFG at every step. How many network evaluations does it need, and what changes with limited-interval guidance on 12 of the steps?
Each guided step evaluates the conditional and the unconditional prediction (2 NFE). Steps outside the guidance interval use only the conditional prediction (1 NFE). For a second-order sampler such as Heun, multiply the evaluations per step accordingly.
Answers to section 1. (1) Neither, for . The samples are not from (that needs ). They are not from the tilted density either, because tilting does not commute with noising. Section 4(b) gives three different answers for the tilted target, the ODE and the SDE. (2) Nothing changes. Along a direction where both classes have the same Gaussian, the conditional and the unconditional scores are equal, so is the unguided score. The variance stays in the example of section 4(c).
4. Worked example #
(a) One CFG step and its two readings. 2D, , so . Take , and .
- .
- .
- Ho and Salimans' convention: , and ✓.
- Implicit classifier gradient: .
- Theorem 2: ✓.
(b) Three different answers. Proposition 3's model with , , (the posterior of the prior after observing with noise variance ). Take .
- Tilted target . Precision , so the variance is . The mean is (precision-weighted) .
- The guided field at is the score of with precision : variance , mean . The noised target has variance and mean . They differ: noising and tilting do not commute.
- Guided PF-ODE (DDIM-type). Variance ; mean (numerical solve, section 5).
- Guided reverse SDE (DDPM-type). Mean , variance (section 5).
The conditional model itself () gives . All three guided answers are narrower and shifted to the right, by different amounts.
(c) The two-class toy of section 2. Classes in 2D, , the exact guided PF-ODE. The first coordinate ends with mean about , variance about and . For it would be mean , variance and . The tilted target has mean and variance (the same as the guided density with in the first figure). The second coordinate keeps variance .
5. In code #
NumPy and SciPy check the noisy classifier against Bayes' rule, the CFG algebra, and the numbers of section 4(b). For the PF-ODE and the reverse SDE in VE form (diffusion coefficient ), the mean and the variance of the guided samples obey simple ODEs in , which SciPy integrates from down to 0.
import numpy as np
from scipy.integrate import solve_ivp
from scipy.special import expit
from scipy.stats import norm
# (1) Noisy classifier of the two-class toy: Bayes' rule vs the closed-form logistic
mu, s2 = 0.5, 0.25
for ab in (1.0, 0.5, 0.1, 0.01):
a, v = np.sqrt(ab), ab * s2 + 1 - ab
x = np.linspace(-2, 2, 9)
bayes = norm.pdf(x, a * mu, np.sqrt(v)) / (norm.pdf(x, a * mu, np.sqrt(v)) + norm.pdf(x, -a * mu, np.sqrt(v)))
k = 2 * a * mu / v
print(ab, round(k, 3), np.allclose(bayes, expit(k * x)))
# 1.0 4.0 True / 0.5 1.131 True / 0.1 0.342 True / 0.01 0.101 True
# (2) Worked example (a): one CFG step, both conventions and Theorem 2
eu, ec, w, sig_t = np.array([0.1, 0.4]), np.array([0.3, 0.1]), 4.0, 0.6
g = -(ec - eu) / sig_t
print(eu + w * (ec - eu), (1 + (w - 1)) * ec - (w - 1) * eu, ec - (w - 1) * sig_t * g)
# [ 0.9 -0.8] [ 0.9 -0.8] [ 0.9 -0.8]
# (3) Worked example (b): tilted target vs guided PF-ODE vs guided reverse SDE
vu, vc, mc, w = 0.5, 0.25, 0.5, 3.0
prec = (1 - w) / vu + w / vc
print(1 / prec, w * mc / vc / prec) # 0.125 0.75
lam = lambda s: (1 - w) / (vu + s**2) + w / (vc + s**2)
print(1 / lam(1.0), w * mc / (vc + 1) / lam(1.0)) # 0.9375 1.125 (noised target: 1.125, 0.75)
def guided_moments(c):
"""c = 1: PF-ODE dx = -s*score ds; c = 2: reverse SDE dx = -2s*score ds + noise."""
def rhs(s, u):
m, V = u
dV = 2 * s * lam(s) * V if c == 1 else 4 * s * lam(s) * V - 2 * s
return [c * s * (lam(s) * m - w * mc / (vc + s**2)), dV]
smax = 1e4
sol = solve_ivp(rhs, (smax, 0.0), [0.0, smax**2 + vu], method="LSODA", rtol=1e-11, atol=1e-12)
return sol.y[:, -1]
print(np.round(guided_moments(1), 4), vc**w * vu**(1 - w)) # [1. 0.0625] 0.0625
print(np.round(guided_moments(2), 4)) # [0.875 0.0969]
In the SDE the variance gets an extra term: noise of variance is injected at each step, while the drift, twice as strong as in the ODE, contracts.
6. Where it shows up #
- Text-to-image and latent diffusion (lesson 13). Train with the text embedding dropped in 10–20% of the examples and sample with CFG. Negative prompts replace by the embedding of an unwanted prompt, so guidance pushes away from it.
- Conditional generators in science. A ground-motion generator conditioned on magnitude, distance and site parameters, or a weather model conditioned on the current state, should give a calibrated distribution, not a typical sample. So is the natural default. If you use , check the spread with CRPS, rank histograms and the spread–skill ratio (lesson 14). In section 4(b), cut the variance from to .
- Inverse problems and data assimilation (lesson 15). Replace the class by an observation: . The second term is a noisy likelihood. Theorem 1 is the exact statement behind these methods.
- Few-step models (lesson 12). Distilled models often include the guidance weight as an input, so that one evaluation per step gives a guided prediction.
7. Common mistakes #
- Mixing the conventions. In ours (and in diffusers) means no guidance; in Ho and Salimans' convention does. The diffusers default is .
- A clean classifier for classifier guidance. The classifier must be trained on , with as an input (Theorem 1, step 3).
- Wrong factor or sign in the form. The classifier gradient enters as , because points away from the data.
- "Guided samples come from ." They do not (section 4b); the result even depends on the sampler.
- Strong guidance for ensembles or uncertainty. It makes the ensemble too narrow.
- No condition dropout in training. Then does not exist. A dropout probability of wastes capacity.
- Counting NFE. CFG doubles the cost of each guided step.
8. Check yourself #
- 1D, , , , . Compute ,
the implicit classifier gradient, and in Ho and Salimans' convention.
Answer
, so . , so . Check with Theorem 2: ✓. . - Why must the classifier in classifier guidance see noisy inputs?
Answer
The sampler needs , and averages the clean classifier over the denoising posterior. A clean classifier evaluated at is a different function; on noisy inputs it is out of distribution and its gradients are not meaningful. - Show that CFG with weight equals classifier guidance with scale on the unconditional model.
Answer
by Theorem 1. - In Proposition 3's model with , and : what is the mean of the guided
field's density as , if ?
Answer
The mean of is . For large , and , so the mean tends to : three times the conditional mean. - Why does limited-interval guidance skip the highest noise levels?
Answer
At high noise the guided density is centred at an extrapolated point ( in Proposition 3's model), so guidance pulls all samples the same way and removes diversity before the details are decided. At low noise the class is already decided, so guidance does little. The middle band gives the benefit, and skipping guidance outside it also saves the second NFE. - What does autoguidance use instead of the unconditional model, and why does that keep diversity?
Answer
A weaker version (smaller or shorter-trained) of the same conditional model: . Both models share the condition, so the difference does not push away from other classes; it points away from the errors of the weaker model. This improves quality without narrowing the conditional distribution as much.
Write the conditional score in terms of the unconditional score and a classifier.
; drops out because it does not depend on .
What is the noisy classifier in terms of the clean classifier?
: the clean classifier averaged over the denoising posterior.
Why must a guidance classifier be trained on noisy inputs?
The sampler needs , which is a different function from the clean classifier; a clean classifier on is out of distribution and gives wrong gradients.
Give the classifier-guided noise prediction with scale .
.
Give the CFG formula (convention with = no guidance).
, where uses the null token.
Convert Ho and Salimans' weight to the weight of .
, because .
How is a CFG model trained?
One network with the condition replaced by a null token in a random 10–20% of the training examples (condition dropout), so it learns both and .
Why does CFG trade diversity for fidelity?
It sharpens the implicit classifier, so samples move to regions where the class is clear: precision rises, recall falls, and FID is best at a moderate .
Do CFG samples follow ?
No (except ): tilting does not commute with noising, so the guided scores belong to no single diffusion path, and the result depends on the sampler.
What is limited-interval guidance?
Use only in a middle band of noise levels and elsewhere; guidance at high noise harms diversity and at low noise does little.
9. Interview angle #
- "Explain classifier-free guidance." — Drop the condition in 10–20% of training examples. At sampling use , 2 NFE per step. It is classifier guidance with the implicit classifier .
- "Derive it from Bayes." — Theorem 1 (the score split at every noise level), then Theorem 2.
- "Why does FID first improve and then get worse as grows?" — Precision rises and recall falls; FID measures both, so it is best at a moderate .
- "Do guided samples follow ?" — No: tilting does not commute with noising; the answer even depends on the sampler (ODE vs SDE).
- "You need calibrated conditional ensembles. Guidance or not?" — , or a small chosen on a calibration metric (CRPS, spread–skill), possibly only in a limited noise interval.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution. Everything uses the exact Gaussian-mixture scores; no network is trained.
- Compute the noisy-classifier slope as a function of and check the four numbers .
- Build the exact noisy classifier of the two-class 8 Gaussians and check that its log-gradient equals the difference of the conditional and the unconditional scores.
- Write the CFG denoiser, sample with the guided PF-ODE, and sweep : measure class accuracy, mean radius and spread.
- Compute the tilted target on a grid for the 1D two-class toy with and show that the CFG samples have a different mean and variance.
- Add a guidance interval to the sampler and compare the effective number of class modes with guidance at every level.
11. Watch and read #
- Ho and Salimans, Classifier-Free Diffusion Guidance (2022): section 3.2 (the implicit classifier, algorithms 1 and 2), section 4 (sweeps over and ).
- Dhariwal and Nichol, Diffusion Models Beat GANs on Image Synthesis (2021): section 4 (classifier guidance, equation 14, table 4).
- Sander Dieleman, Guidance: a cheat code for diffusion models (2022): classifier guidance, CFG and temperature, with pictures.
- Kynkäänniemi et al., Applying Guidance in a Limited Interval Improves Sample and Distribution Quality in Diffusion Models (2024).
- Karras et al., Guiding a Diffusion Model with a Bad Version of Itself (autoguidance, 2024): section 3 has a 2D toy that explains why CFG improves quality.
- Bradley and Nakkiran, Classifier-Free Guidance is a Predictor-Corrector (2024): what distribution CFG really samples.
- Lin et al., Common Diffusion Noise Schedules and Sample Steps are Flawed (2024): section 3.4, CFG rescale.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.