Guidance & Conditioning
Classifier and classifier-free guidance, autoguidance and steering generation with text and images.
Sample a conditional diffusion model exactly as it was trained, and its images often follow the prompt only loosely. So most text-to-image systems spend a second network evaluation per step and push the prediction away from an unconditional one. This trick, guidance, works remarkably well, and it provably does not sample the distribution it was derived from.
What you’ll learn
- Compare the ways a condition enters a denoiser (adaptive normalization, cross-attention, concatenation, zero-initialized control branches), and prove that a zero-initialized branch leaves a pretrained model unchanged yet receives gradient.
- Derive classifier guidance from Bayes' rule and the perturbed-Gaussian reverse step, and explain what the gradient scale does to fidelity and diversity.
- Derive classifier-free guidance from an implicit classifier, compute guided predictions in both common conventions, and explain why large guidance oversaturates.
- Prove in a Gaussian example that guided sampling does not sample the tilted target, and assess guidance intervals and autoguidance.
Getting the condition into the network
A conditional denoiser estimates the score of , the noised data restricted to condition (a class, a caption, a depth map). Bayes' rule splits that score in two, because does not depend on :
| Mechanism | How enters | Typical conditions | Examples |
|---|---|---|---|
| Embedding with adaptive normalization | is embedded and added to the step embedding; each block regresses a scale and shift applied after normalization, | class labels, pooled text embeddings, noise level | ADM (Dhariwal & Nichol, 2021); DiT's adaLN-Zero (Peebles & Xie, 2023) |
| Cross-attention | image positions query the token vectors of a text encoder | prompts | latent diffusion, Imagen |
| Concatenation | an image-shaped condition is stacked onto the noisy input's channels | low-resolution image, mask | super-resolution stages of cascades; inpainting |
| Control branch | a trainable copy of the encoder reads a spatial condition and adds its features back through zero-initialized convolutions | edges, depth, pose, segmentation | ControlNet (Zhang, Rao & Agrawala, 2023) |
ControlNet and adaLN-Zero share one design rule: a new pathway starts as a no-op. DiT regresses, besides a scale and shift, a gate on each residual branch and initializes it to zero, so every block begins as the identity. ControlNet locks the pretrained network and connects the trainable copy through convolutions whose weights and biases start at zero, so on the first step the system is exactly the pretrained model, whatever the condition. Why does such a branch ever learn?
Classifier guidance
Classifier guidance (Dhariwal & Nichol, 2021, building on Sohl-Dickstein et al., 2015, and Song et al., 2021) uses the classifier term directly. Train a classifier on images noised to every level (an ordinary classifier has never seen such inputs), then bias every reverse step toward images it assigns to class .
The class-conditional reverse step is the unconditional one reweighted by the classifier at the new point, with a normalizer :
The step is narrow, so over its width the log-classifier is nearly linear: expand it to first order around , with :
Add the Gaussian's log-density and complete the square. The product is again Gaussian with the same covariance and a shifted mean:
In practice a gradient scale multiplies the shift, giving . Since , a scale guides toward a sharpened classifier. For deterministic samplers the same correction is made on the noise prediction, using the score form of Diffusion Models:
In practice the scale mattered more than the derivation suggests. Guiding an unconditional ImageNet model with produced samples to which the classifier gave about 50% probability for the requested class, yet which did not look like that class; fixed it. Guiding a model that was already class-conditional worked best:
| ImageNet | Scale | FID ↓ | Inception Score ↑ | Precision ↑ | Recall ↑ |
|---|---|---|---|---|---|
| Unconditional model | none | 26.21 | 39.70 | 0.61 | 0.63 |
| Unconditional model | 10 | 12.00 | 95.41 | 0.76 | 0.44 |
| Conditional model | none | 10.94 | 100.98 | 0.69 | 0.63 |
| Conditional model | 1 | 4.59 | 186.70 | 0.82 | 0.52 |
| Conditional model | 10 | 9.11 | 283.92 | 0.88 | 0.32 |
Why can't classifier guidance simply use an off-the-shelf ImageNet classifier?
- Its gradient with respect to the input image cannot be computed
- Guidance needs at every noise level, and a classifier trained on clean images gives meaningless predictions and gradients on heavily noised inputs
- The classifier must share the diffusion model's weights
- Classifier gradients are zero for correctly classified images
Show the answer
B. Guidance needs at every noise level, and a classifier trained on clean images gives meaningless predictions and gradients on heavily noised inputs
The correction uses the classifier on , which for most of the chain is mostly noise. Dhariwal & Nichol trained classifiers on the same noising distribution as the diffusion model. Training-free variants instead apply a clean-image classifier or loss to the denoised estimate and backpropagate through the denoiser, as diffusion posterior sampling does for inverse problems (Chung et al., 2023).
Classifier-free guidance
Classifier guidance needs a second network trained on noisy data, and stepping along a classifier's input gradient resembles an adversarial attack on it, which raised the question whether its gains on classifier-based scores such as Inception Score and FID reflected better images at all. Classifier-free guidance (Ho & Salimans, 2022) removes the classifier. One network is trained as usual, except that is replaced by a null token with probability , so it also learns the unconditional prediction .
Bayes' rule defines a classifier from the two densities the network models, and its score is a difference of their scores; with exact noise predictors :
Apply classifier guidance with weight to the conditional model, using this implicit classifier:
Multiply by and substitute the network for the exact predictors. This is Ho & Salimans's guided prediction; the second form, with scale , is the one most software and later papers use:
Read as a density, the guided score belongs to : the conditional tilted toward points the implicit classifier finds unambiguous, the reading taken in the Artificial Intelligence course's Deep Layer lesson on diffusion. Two caveats: a trained network's difference need not be the gradient of any classifier, and, as the next step proves, the sampler does not reach the tilted density anyway.
At one pixel, the conditional prediction is and the unconditional one is . With Ho & Salimans's (scale ), what is the guided noise estimate at that pixel?
Show the answer
-0.3
, or equivalently . The condition moved the prediction by ; guidance multiplies that difference by , landing outside the interval between the two predictions. Guidance extrapolates.
Ho & Salimans's ImageNet sweep shows the trade-off cleanly (; 0.1 and 0.2 performed about equally, 0.5 worse). FID, which rewards both fidelity and coverage, is best with a little guidance and then degrades, while Inception Score, which rewards confident, class-typical images, rises throughout:
- : FID 1.80, IS 53.7
- : FID 1.55, IS 66.1
- : FID 12.6, IS 170.1
- : FID 26.2, IS 260.2
Text-to-image systems typically run far stronger guidance than the FID optimum, trading coverage for prompt adherence and polish: Imagen relied on large guidance weights, and Lin et al. (2024) used in their Stable Diffusion experiments. Two practical variants follow from the formula. A negative prompt replaces the unconditional prediction with the prediction for an unwanted description, so every step moves away from it. And since each step costs two evaluations, guidance distillation (Meng et al., 2023) trains a student that takes as an input and reproduces the guided output in one evaluation (Few-Step Generation).
What guidance samples, and better guides
The tilted-density reading suggests that guided sampling draws from , . It does not. At each noise level the sampler follows , but that is not the score of blurred to the same noise level: tilting and adding noise do not commute (Chidambaram et al., 2024). A one-dimensional Gaussian example makes the gap exact.
Use the noise-level form of the probability-flow ODE, , for data blurred to (the form that The Design Space of Diffusion Models works with). Let the unconditional density be and the conditional . Blurring adds to each variance, so the guided score is linear in :
The ODE is linear, so Gaussian inputs give Gaussian outputs, and the variance of the samples obeys . Integrate from , where sampling starts from , down to :
So the guided sampler outputs a variance that interpolates the two variances geometrically, while the tilted target, a product of Gaussian densities raised to the powers and , interpolates their precisions arithmetically:
For the two agree only at and : is linear in while is strictly convex, so for every at which the target is normalizable the sampler is narrower than the target. With , and , the sampler's standard deviation is , while the tilted target's is : for the guided variance shrinks exponentially in , the target's only like . Bradley & Nakkiran (2024) solved the case , in closed form, against , and integrating the ODE numerically reproduces .
The gap is not a Gaussian quirk. If two classes have disjoint supports, is 0 or 1, so the tilted target equals the plain conditional for every . Yet Chidambaram et al. (2024) prove, for two classes on mirror-image disjoint intervals, that guided probability flow with large lands, with probability , within a relative distance of the class's outermost point, far from the other class, and that with any nonzero score error a large enough pushes samples off the support altogether. For Gaussian mixtures, Wu et al. (2024) prove, under conditions on the mixture, that guidance raises the classifier's confidence in the samples under both DDPM and DDIM sampling and lowers their differential entropy under DDIM; with three aligned components, they find that strong guidance with discretized sampling can split one component in two. Bradley & Nakkiran (2024) show that guidance interacts differently with stochastic and deterministic samplers, and that in the continuous-time limit stochastic guided sampling is equivalent to a conditional denoising step alternated with Langevin corrector steps on a sharpened, powered distribution.
Two refinements, both found by measuring where guidance helps:
- Guidance intervals (Kynkäänniemi et al., 2024). Guidance at high noise levels drives samples toward a handful of template compositions per prompt, at low noise levels it is largely unnecessary, and only in between does it help. Applying it only for improved the largest EDM2 model's ImageNet-512 FID from 1.81 to 1.40, and saves the second evaluation elsewhere.
- Autoguidance (Karras et al., 2024). Guide the model with a deliberately worse version of itself, , smaller and trained for less time but with the same conditioning: , where means no guidance. A finite network trained by score matching spreads probability into regions it has not learned well; a weaker model makes the same kind of errors more strongly, so extrapolating away from it pulls samples toward well-learned regions without CFG's class-driven narrowing. On ImageNet-512 with EDM2-S, FID went from 2.56 unguided and 2.23 with CFG to 1.34 (1.25 with EDM2-XXL), and an unconditional model, which CFG cannot guide at all, went from 11.67 to 3.86.
Key takeaways
- Bayes' rule splits the conditional score: . Conditions enter by adaptive normalization, cross-attention, concatenation or zero-initialized control branches, which start as no-ops yet receive gradient.
- Classifier guidance shifts each Gaussian reverse step's mean by using a classifier trained on noisy inputs; targets a sharpened classifier, raising precision and lowering recall.
- Classifier-free guidance trains one network with condition dropout and samples with , at two evaluations per step; FID is best at small , and large oversaturates unless thresholded or rescaled.
- Guided samplers do not sample the tilted target: for Gaussians, guided probability flow outputs variance instead of , and with disjoint classes samples drift to the far edges of the support.
- Guiding only at middle noise levels, or guiding with a weaker copy of the model itself (autoguidance), improves quality while giving up less diversity than plain CFG.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Two classes have disjoint supports, so . As the guidance weight grows, what happens to the tilted target , and to guided samples?
- Both stay the same: guidance has no effect when classes do not overlap
- Both concentrate on the class's most typical point, its mode
- The target narrows toward the boundary between the classes, and samples follow it
- The target is unchanged for every , but guided samples drift toward the far edge of the class's support
Show the answer
D. The target is unchanged for every , but guided samples drift toward the far edge of the class's support
Raising a 0/1 likelihood to any positive power changes nothing, so the tilted target is the plain conditional. Guided probability flow, however, uses noised scores, for which tilting and noising do not commute, and it pushes samples away from the other class, toward extreme points (Chidambaram et al., 2024).
Where in the sampling chain did Kynkäänniemi et al. (2024) find classifier-free guidance useful?
- At high noise levels, where it fixes the composition, and nowhere else
- At middle noise levels; at high noise it collapses compositions toward templates, and at low noise it adds little
- At low noise levels only, where it sharpens fine detail
- Uniformly: the benefit is the same at every noise level
Show the answer
B. At middle noise levels; at high noise it collapses compositions toward templates, and at low noise it adds little
Limiting guidance to a middle interval of kept the variety of compositions that high-noise guidance destroys, and improved ImageNet-512 FID from 1.81 to 1.40 for the largest EDM2 model, while saving network evaluations outside the interval.
What does autoguidance use in place of CFG's unconditional prediction?
- A smaller, less-trained version of the same model with the same conditioning
- A noise-aware classifier's gradient
- The prediction for a negative prompt
- The same model evaluated at a higher noise level
Show the answer
A. A smaller, less-trained version of the same model with the same conditioning
Extrapolating from a weaker copy, , removes the errors the two share in kind, improving image quality without CFG's narrowing toward class-typical images. It also works for unconditional models, where CFG has nothing to contrast against.
A ControlNet branch is connected to a frozen diffusion model through convolutions initialized to zero. What is true at the first training step?
- The combined model's output is random, because the branch is untrained
- No parameter can ever learn, because every gradient through a zero layer is zero
- The output equals the pretrained model's, the zero convolutions' weights get nonzero gradients, and the branch's own weights start receiving gradient once those weights move
- The frozen model's weights are updated first, then the branch's
Show the answer
C. The output equals the pretrained model's, the zero convolutions' weights get nonzero gradients, and the branch's own weights start receiving gradient once those weights move
is nonzero because the branch's features are nonzero, while vanishes only until leaves zero. Training thus starts from the pretrained behavior exactly.
Further reading
- P. Dhariwal & A. Nichol, "Diffusion models beat GANs on image synthesis," NeurIPS (2021).
- J. Ho & T. Salimans, "Classifier-free diffusion guidance," arXiv:2207.12598 (2022); a short version appeared at the NeurIPS 2021 Workshop on Deep Generative Models and Downstream Applications.
- L. Zhang, A. Rao & M. Agrawala, "Adding conditional control to text-to-image diffusion models," ICCV (2023).
- T. Karras, M. Aittala, T. Kynkäänniemi, J. Lehtinen, T. Aila & S. Laine, "Guiding a diffusion model with a bad version of itself," NeurIPS (2024).
- M. Chidambaram, K. Gatmiry, S. Chen, H. Lee & J. Lu, "What does guidance do? A fine-grained analysis in a simple setting," NeurIPS (2024).