Guidance is how a diffusion model is made to follow its prompt more closely. A conditional diffusion model is given a condition, such as a class label or a text prompt, and asked for a sample that depicts it. Sampled in the plain way, it often returns images that are plausible but only loosely match the condition. Guidance fixes this with one change to the sampler. At every denoising step the network is asked twice, once with the condition and once without, and the step moves further in the direction in which the condition changed the answer. One number, the guidance scale, sets how much further. After the number of sampling steps, it is the setting that most changes what a diffusion model produces.
The effect is large. Dhariwal and Nichol (2021) trained a diffusion model on ImageNet images of 256×256 pixels, with the class label as an extra input. Sampled in the usual way, it scored an FID of 10.94. FID is a distance between the statistics of generated and real images, so lower is better (it is defined below). They then added one guidance term to every sampling step, without retraining the diffusion network, and the FID fell to 4.59. Soon after, Ho and Salimans (2022) got the same effect with no extra network at all. Text-to-image systems have used their version ever since. The Stable Diffusion pipelines of diffusers, Hugging Face's standard library of diffusion code, run it at a scale of 7.5 by default.
A new idea was needed because the obvious one fails. A language model is made to commit to its most likely tokens by lowering its temperature, which sharpens the distribution of the next token (§6.4). The diffusion analogs are to scale up the network's prediction or to add less noise at each step. Dhariwal and Nichol tried both and got blurry, smooth images. What works is Bayes rule, applied to gradients of log-densities, and the whole section follows from it.
We derive classifier guidance from Bayes rule, then classifier-free guidance from classifier guidance, and implement both. On a toy whose exact answers we can compute, we measure what the scale buys and what it costs. We then prove that guided samplers do not draw from the distribution they are usually said to draw from, and show what they do instead. The last parts cover the refinements that production systems use, and fine-tuning on rewards, which builds a similar push into the weights. Interviews for image, video, and audio generation teams ask about every one of these.
Four facts from earlier in the chapter carry the whole section.
The forward process. It turns clean data x0∈Rd into a noisy sample xt=αtx0+σtϵ (§33.1). Here ϵ∼N(0,I) is standard Gaussian noise and αt2+σt2=1. Time runs from clean data at t=0 to pure noise at t=T in discrete steps, or at t=1 when time is continuous.
The score. The score of a density p is the gradient ∇xlogp(x). It is an arrow at every point, pointing toward higher density, and it does not depend on the density's normalizing constant (§33.3).
Noise prediction is the score in other units. A noise predictor is a network trained to guess ϵ from xt. The best possible one is ϵ⋆=−σt∇logpt, minus σt times the score of the noisy data (§33.3).
Samplers. A sampler turns a noise predictor into samples by stepping from t=T down to 0. The ancestral sampler of §33.2, called DDPM (denoising diffusion probabilistic models), adds fresh noise at every step. The deterministic sampler of §33.4, called DDIM (denoising diffusion implicit models), adds none. Each DDIM step predicts the clean data, x^0=(xt−σtϵ^)/αt, and re-noises it to the next, smaller time with the same predicted noise ϵ^.
Conditional diffusion is denoising with one more input
A conditionc is what the sample should depict, such as a class label or a text prompt. Training data now come in pairs (x0,c), an image with its label or its caption. The forward process ignores c and noises x0 exactly as before. So once x0 is known, the noisy xt says nothing more about c. In symbols, c→x0→xt is a Markov chain.
In plain words, take the clean data of condition c and blur every point with Gaussian noise of the size that t sets. We write pt(x) for the same integral taken over all the data, with p(x0) in place of p(x0∣c). It is the unconditional noisy density. We write ∅ for the null condition, which means "no condition at all".
Nothing new needs proving. For each fixed c the loss is the simple loss of §33.2, on data drawn from p(x0∣c). A squared error is minimized by the conditional mean. The link between the best noise predictor and the score (§33.3) holds for every distribution, so it holds for pt(⋅∣c) too. In plain words, a conditional diffusion model is an ordinary one with the condition as an extra input, and at its optimum it outputs minus σt times the score of the noisy class.
How c enters the network does not matter in this section. A class label usually becomes a learned vector that is added to the embedding of the time. Dhariwal and Nichol's network does this. So do the Diffusion Transformer, or DiT, a Transformer that denoises patches of a compressed image (Peebles and Xie 2023), and the small network we train below. A text prompt is encoded by a text model and read through attention, as text conditioning explains.
With exact scores, sampling this model gives exactly p(x∣c), and there would be nothing to fix. Trained networks fall short. Their samples are plausible images that often do not commit to the label or the prompt. This is an empirical finding, and its cause is still debated. Bradley and Nakkiran (2024) call the reasons unclear. Karras et al. (2024) argue that a network of limited capacity spreads probability into regions where data are rare and it has learned little. Guidance is the fix that works in practice, and deriving it takes one identity.
Bayes rule turns a classifier into a score
The identity says that the score of one class is the unconditional score plus the gradient of a classifier's log-probability. Here it is at two points, by hand, before the general statement.
Proof. Bayes rule (§0.4) gives pt(x∣c)=pt(c∣x)pt(x)/p(c). Take the logarithm and the gradient in x. The term −logp(c) does not depend on x, so its gradient is zero. For the integral, p(c∣xt)=∫p(c∣x0,xt)p(x0∣xt)dx0. The Markov chain c→x0→xt gives p(c∣x0,xt)=p(c∣x0). □
In plain words, to turn an unconditional score into a conditional one, add the input gradient of a classifier that looks at the noisy image. The prior p(c) vanishes under the gradient, just as the normalizing constant of a density does in §33.3.
The noisy posterior pt(c∣x) is a different function at every noise level. At t=0 it is the ordinary classifier on clean data. As t grows, xt says less and less about x0. So pt(c∣x) flattens toward the prior p(c), and its gradient shrinks. To use the theorem we need a classifier for every noise level.
Classifier guidance adds a classifier's gradient to the score
Classifier guidance takes the identity and turns up the classifier term. It adds the classifier's gradient to the unconditional score, multiplied by a number that is usually larger than one.
The noise form follows from ϵ=−σts. Multiply the guided score by −σt. The first term becomes ϵθ(xt,t), and the second becomes −γσt∇logpϕ.
Forgetting the factor σt is a common bug. At high noise σt≈1, so the bug changes little there. Near the end of sampling σt is small, say 0.05, and the classifier term should be shrunk 20 times. Without the factor, guidance is 20 times too strong exactly where the fine detail of the image is decided. An interviewer who asks you to write this update will usually ask next where the σt comes from.
What a scale above one aims for
The guided score is the gradient of log[pt(x)pϕ(c∣x)γ]. The hope behind guidance is that the sampler then ends at the matching distribution of clean data. Using p(c∣x)=p(x∣c)p(c)/p(x), that distribution is
pγ(x∣c)∝p(x)p(c∣x)γ∝p(x∣c)γp(x)1−γ,
which we call the γ-powered distribution. In plain words, raising the classifier to a power γ>1 sharpens it. So pγ puts its mass where the classifier is most confident that a sample belongs to c.
The push past the class is a toy picture of what Ho and Salimans saw in images. Their strongly guided ImageNet samples have saturated colors, as if each class were exaggerated away from the others.
There is a catch, and a later part of this section is about it. Guidance does not power the clean data distribution once. At every step it powers the noisy distributions, pt(x∣c)γpt(x)1−γ. Noising and powering do not commute, so this sequence of fields is not the sequence of noised versions of pγ. The next cell checks this for the two Gaussians at the noise level αt2=0.5.
Python · cell 1
Powering the noised densities gives N(1.414,0.5). Noising the powered target gives N(1.061,0.625). They are different distributions. So the field that guidance follows at this noise level is not the score of the noised target. We will see that neither the deterministic nor the stochastic sampler with guidance draws from pγ.
Why the classifier must see noise
Bayes rule asks for pt(c∣xt), the posterior given a noisy input, which is a different function at every t. An off-the-shelf classifier trained on clean images answers a different question. It also sees inputs unlike anything it was trained on, so its gradient at high noise is meaningless. Dhariwal and Nichol therefore trained their classifiers on the same noising distribution as the diffusion model. Their denoising network is a U-Net, a convolutional network that shrinks the image to coarse features and then expands it back. The classifier is the shrinking half of a U-Net, with an attention-pooling layer at the 8×8 resolution. At 256×256 it has 54 million parameters, against the generator's 554 million.
A second worry led to the next idea. The input gradient of a classifier can raise its confidence without making the image more like the class, which is how adversarial examples work. Ho and Salimans asked whether classifier guidance improves the image metrics partly by fooling classifiers, since those metrics are themselves computed by a classifier. Classifier-free guidance settles the question, because it uses no classifier gradient at all.
What classifier guidance does on ImageNet
Every guidance paper reports the same few metrics, and each one says something different.
Three things stand out. First, guiding the unconditional model with scale 1 made FID worse, although a perfect classifier would then give the exact conditional score. The authors report that the classifier gave the requested class about 50 percent probability, yet the samples did not look like the class. They needed a scale well above 1. Second, the best results came from guiding a model that was already conditional (FID 4.59, against 12.00 for the best unconditional row). The conditional network's own knowledge of the class is worth keeping. Third, apart from that failed run at scale 1, more guidance raises precision and Inception Score and lowers recall. Guidance buys fidelity with diversity, and an interviewer will expect you to say which metric moves which way.
Classifier-free guidance needs no classifier
Classifier guidance needs a second network, trained on noisy data, whose gradients might be adversarial. Ho and Salimans removed it by reading Bayes rule for scores backward. Solve the theorem for the classifier's gradient,
∇xlogpt(c∣x)=∇xlogpt(x∣c)−∇xlogpt(x).
The right side needs no classifier, only the conditional and unconditional scores. It is the gradient of the log of the ratio pt(x∣c)/pt(x), which they call the implicit classifier. Substitute it into classifier guidance,
Here is the rule with numbers first. Say the network's prediction without the prompt is (0.2,−0.1), and with the prompt it is (0.5,0.3). The prompt moved the answer by (0.3,0.4). Guidance at γ=3 takes three times that move from the unconditional point, (0.2,−0.1)+3(0.3,0.4)=(1.1,1.1).
In plain words, ask the network twice, once with the prompt and once without, and step further along the direction in which the prompt changed its answer.
Papers write the same rule in three ways. Mixing them up silently changes the strength by one.
written as
used by
relation to our γ
ϵ∅+γ(ϵc−ϵ∅)
this book, diffusers' guidance_scale, DiT's s, Lin et al.'s w, Kynkäänniemi et al.'s w, Bradley and Nakkiran's γ
So the classifier-free guidance paper's best FID at 128×128, at w=0.3, is at γ=1.3, and its w=0 is no guidance at all.
Warm-up
The CFG combination and its two conventions
Write two functions.
cfg_combine(eps_cond, eps_uncond, gamma) returns the classifier-free guided prediction in this book's convention. It must broadcast, so gamma may be a scalar or an array, such as one scale per sample of shape (B, 1).
cfg_from_w(w) converts the w of the (1+w) convention into our γ.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
With exact scores, classifier guidance and classifier-free guidance are the same rule, because the implicit classifier is then the true noisy posterior. The next exercise checks this on two Gaussian classes, where the noisy posterior has a closed form.
Core
Classifier guidance with a logistic classifier on noisy inputs
Two classes in R2 are Gaussians with means μ0 and μ1 and one shared standard deviation in every direction. The prior is p(c=1)=0.3. For Gaussian classes of equal width the exact noisy posterior is logistic, pt(c=1∣xt)=sigmoid(xt⊤wt+bt). The setup's noisy_logistic(a, s) returns (wt,bt) at αt=a and σt=s.
Write classifier_guidance_eps(eps, x_t, c, w_t, b_t, sigma_t, gamma). Its inputs are the unconditional prediction eps of shape (B, 2), the noisy inputs x_t of shape (B, 2), and integer labels c in {0,1} of shape (B,). It returns the classifier-guided noise prediction of shape (B, 2). Compute the input gradient of logpt(c∣xt) by hand, for both labels. The tests compare your answer with classifier-free guidance built from the exact conditional and unconditional noise predictors, and the two must agree.
import numpy as np
def classifier_guidance_eps(eps, x_t, c, w_t, b_t, sigma_t, gamma):
return eps # placeholder, no guidance
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
One network learns both predictions
The unconditional model costs almost nothing extra. Give the network one more value of the condition, a learned null vector for a class label or the encoding of the empty prompt for text. During training, replace the true condition by it at random. This is called condition dropout.
Ho and Salimans trained ImageNet 64×64 models with puncond equal to 0.1, 0.2, and 0.5. The values 0.1 and 0.2 did about equally well. The value 0.5 was worse at every point of the trade-off between FID and Inception Score. Only a small share of the network's capacity needs to go to the unconditional task, and most systems use 0.1 to 0.2.
The price is paid at sampling time. The number of function evaluations (NFE) of a sampler is the number of network calls it makes per sample (§33.4). Every guided step needs two.
The CFG rule is written for noise predictions, but many networks predict something else, such as the clean image or a velocity. The rule still applies to their outputs whenever the output is an affine function of the noise prediction, a constant times the noise prediction plus a term that does not depend on it.
Proof. The left side is (1−γ)(atxt+btϵ^∅)+γ(atxt+btϵ^c). The weights 1−γ and γ sum to one, so the atxt terms combine to atxt. What remains is bt times the guided noise. □
The weights summing to one is the whole point. Multiplying a single prediction by γ, the literal temperature move, uses weights that do not sum to one, and it does not commute with these conversions. The theorem is why a model that predicts velocities, such as a rectified flow transformer (a Transformer trained to move noise to data along straight paths), can apply CFG to its own output with the same formula (§33.6).
Interview
Condition dropout and a CFG sampler
This exercise is all of classifier-free guidance, the training side and the sampling side. Write two functions.
drop_condition(c, p_uncond, rng, null_id) takes integer labels c of shape (B,). It returns a new array in which each label, independently, is replaced by null_id with probability p_uncond, using the generator rng.
cfg_ddim_sample(eps_model, c, gamma, x_T, alpha, sigma, ts, null_id) runs deterministic DDIM with the CFG prediction at every step and returns the final samples.
It starts from the noise x_T of shape (B, 2) and steps along the decreasing integer times ts, from T down to 0.
The model eps_model(x, t, labels) takes a batch x, one integer t, and integer labels of the same batch size, where null_id means unconditional.
The class c is one label for the whole batch.
One DDIM step from t to s is x^0=(xt−σtϵ~)/αt, then xs=αsx^0+σsϵ~ (§33.4).
The setup gives toy_eps, the exact noise predictor of this section's two-class toy (introduced below), and toy_class_of, its clean Bayes classifier.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
What the scale does, measured with exact scores
With images it is hard to separate what guidance does from what an imperfect network does. So we build a toy whose exact scores we can compute.
Two classes live in R2, and each is a mixture of two Gaussians with standard deviation 0.5.
Class A has modes at (−1.6,0) and (0.3,0), with equal weights.
Class B has modes at (1.4,0.9) and (1.4,−0.9), with weights 0.7 and 0.3.
The two classes are equally likely.
Class A's right-hand mode, the near mode, sits close to class B. Its left-hand mode, the far mode, is far from class B, and that will matter.
A noised mixture of Gaussians is again a mixture of Gaussians, with means αtμk and variances αt2⋅0.52+σt2 (§33.1). Its score has a closed form (§33.3). So ϵ⋆(x,t,c) and ϵ⋆(x,t,∅) are exact, and any gap between the samples and the class comes from guidance and the sampler alone. We use DDPM's linear schedule with T=1000, and deterministic DDIM with 100 steps.
Python · cell 2
The sampler below is DDIM with the CFG prediction. Its guide argument decides at which steps guidance is applied, which we use later for guidance intervals. Its neg argument replaces the unconditional pass by another condition, which we use later for negative prompts. Three numbers summarize a set of class-A samples.
The precision here is the fraction of samples that the clean Bayes classifier assigns to class A.
The spread is the trace of the sample covariance, the total variance over both coordinates.
The far-mode share is the fraction of samples nearer to the far mode (−1.6,0) than to the near one. It is 0.5 for the true class.
Python · cell 3
Python · cell 4
Read the table row by row. At γ=0 we sample the unconditional mixture, and only half the samples belong to class A. At γ=1 the sampler reproduces class A, up to the small error of 100 DDIM steps (precision 0.935 against the exact 0.925, spread 1.37 against 1.40). The 7.5 percent of class-A samples that the classifier calls class B are not mistakes. They are genuine class-A points in the overlap, and an exact model draws them.
Above γ=1 the two columns part ways. At γ=3 CFG has precision 1.000, but its spread has fallen to 0.51, less than half of the target's 1.16. And 94.5 percent of its samples are in the far mode, where the powered target puts only 59 percent. At γ=7.5 the near mode is gone and every sample is in the far mode, while the powered target still keeps 35 percent of its mass near (0.3,0).
The plot shows the samples on top of the powered target's contours.
Python · cell 5
At γ=7.5 the samples have not just left the near mode. They have also slid left of the far mode's center, past it and away from class B, to a mean horizontal position near −2.5 against the center's −1.6. That is the overshoot of the hand example, now in two dimensions.
The widget runs the same toy in your browser. The dots are 500 samples of one class from DDIM with guidance and exact scores, and the gray shading is the powered target. Drag γ and watch the two numbers on the right, the class precision and the share of samples in one mode, with the target's share beneath it.
What does turning up the guidance scale buy, and what does it cost?
500 samples of one class from guided DDIM with exact scores, over the shaded powered target.
Loading interactive figure…
Switch to class B, whose two modes are mirror images across the horizontal axis, so class A is equally close to both. There the powered target barely changes with γ, since its share in the heavier mode moves only from 0.69 toward 0.72. Yet CFG moves mass into the heavier mode as γ grows, a change of mode weights that the target does not have. The slider for the guidance window and the option "A against B" are explained later in the section.
The same experiment with a trained network
With exact scores, γ=1 is already perfect, and every γ>1 is a distortion. With a trained network, γ=1 is not perfect, and guidance makes up for some of the network's errors. The block below trains a small network with condition dropout (puncond=0.15) on samples from the toy, then samples it with CFG. It also reports the off-manifold rate, the fraction of samples more than three standard deviations from every mode center.
🔥 In PyTorchfor a machine with PyTorch
In our run the trained model at γ=1 reached a precision of only 0.88, below the exact 0.925. A small network trained for two thousand steps has not learned the class boundary exactly. Guidance at γ=3 took precision to 1.000, which is what practitioners want from guidance. The costs match the exact toy's. The far-mode share rose well above 0.5, and at γ=7.5 the near mode vanished.
A third cost appears only with a trained network. At large γ the extrapolated prediction leaves the region where the network was trained, and some samples land far from every mode. In our run the off-manifold rate went from 0.7 percent at γ=1 to about a quarter at γ=7.5, though the exact number depends on the seed. This is the toy version of the oversaturated, overcooked images that high guidance scales produce.
What guided samplers actually sample
The most common explanation of CFG says that it samples the powered distribution pγ(x∣c)∝p(x∣c)γp(x)1−γ. The toy showed that it does not. The next theorem says why, and what the exact guidance term would have to be. It covers any reweighting of the data, so we state it for a general weight function h.
Proof. By definition p~t(x)=∫q(x∣x0)p(x0)h(x0)dx0/Z. Multiply and divide by pt(x). By Bayes rule, q(x∣x0)p(x0)/pt(x)=p(x0∣xt=x). What remains is pt(x)∫p(x0∣xt=x)h(x0)dx0/Z. Take the log and the gradient, and Z drops out. □
In plain words, to sample data reweighted by h, add to the score the gradient of the log of the weight you expect the clean image to have, given the noisy one. Three cases follow, each in a line.
Bayes rule for scores is the case h(x0)=p(c∣x0). Then p~=p(⋅∣c) and E[p(c∣x0)∣xt]=pt(c∣xt), the theorem we started from.
The powered target is the case h(x0)=p(c∣x0)γ. Its exact guidance term is ∇logE[p(c∣x0)γ∣xt], the log of the expected power. Classifier guidance and CFG use γ∇logE[p(c∣x0)∣xt], the log of the power of the expectation. For γ>1 the map u↦uγ is strictly convex, so by Jensen's inequality the first expectation is at least the second power. They are equal only when p(c∣x0) is constant over the posterior of x0. At high noise that posterior is wide, and the ratio of the two varies with xt, so the gradients of their logs differ. The guided field becomes the score of the noised target only as t→0, where the posterior collapses onto a point.
Reward tilting is the case h=exp(r/βKL), for a reward r(x0). Maximizing expected reward minus βKL times the KL divergence to a reference model has the solution prefexp(r/βKL)/Z (§17.1, which writes πref and a plain β). Its exact guidance term is ∇logE[exp(r(x0)/βKL)∣xt], a soft value function of the noisy state. Estimating it is hard, which is one reason the last part of this section fine-tunes the network instead.
A case solved in closed form
Bradley and Nakkiran (2024) found a joint distribution for which the guided samplers can be solved exactly. Let c∼N(0,1) and x∣c∼N(c,1) in one dimension, and condition on c=0. Then p(x∣c=0)=N(0,1) and p(x)=N(0,2). By the precision rule of the hand example, the powered target is N(0,2/(γ+1)).
That last sentence should surprise you. In §33.3 the reverse SDE (the continuous-time limit of DDPM) and the probability flow ODE (the limit of DDIM) had the same marginals. That proof needed the field to be the score of the marginals of one forward process. The guided field is not such a score, so the proof does not apply, and the two samplers drift apart. Bradley and Nakkiran solve the variance exploding process. The derivation below solves the variance preserving one and gets the same answers.
∂ Solving the two guided samplers exactly
Work in the continuous time of the SDE view, with pure noise at t=1. Write a=αt2, which runs from 0 at t=1 to 1 at t=0. Noising gives pt(x)=N(0,2a+1−a)=N(0,1+a) and pt(x∣c)=N(0,a+1−a)=N(0,1). So the scores are −x/(1+a) and −x, and the CFG score is linear,
s~(x)=−k(a)x,k(a)=γ+1+a1−γ,1−k(a)=(1−γ)1+aa.
For the variance preserving SDE with rate β(t) (§33.3), a=exp(−∫0tβ), so da/dt=−β(t)a.
DDIM, the probability flow ODE. The ODE is dx/dt=−21β(t)(x+s~(x)). Divide by da/dt,
dadx=2ax+s~(x)=2a(1−k)x=21−γ1+ax.
So dlog∣x∣/da=21−γ⋅1+a1. Integrating from a=0 to a=1 gives x0=2(1−γ)/2xT. With xT∼N(0,1) the output variance is 21−γ.
The same steps work for any two zero-mean Gaussians, p(x∣c)=N(0,vc) and p(x)=N(0,vu). Noising gives variances 1+a(vc−1) and 1+a(vu−1), so now k(a)=γ/(1+a(vc−1))+(1−γ)/(1+a(vu−1)). Since (1−1/(1+a(v−1)))/a=(v−1)/(1+a(v−1)),
which integrates over [0,1] to 21(γlnvc+(1−γ)lnvu). So CFG with DDIM outputs variance vcγvu1−γ, a weighted geometric mean of the two variances. The powered target has variance 1/(γ/vc−(γ−1)/vu), set by a weighted arithmetic mean of the precisions. With r=vu/vc the first is below the second exactly when 1+γ(r−1)<rγ. That is Bernoulli's inequality, strict for every γ>1 and r=1. So whenever the powered target exists, DDIM with CFG is sharper than it for every pair of distinct variances, not only in this example.
DDPM, the reverse SDE. Run time backward with τ=1−t. The reverse SDE becomes dx=β(21−k)xdτ+βdW, a linear SDE, so x stays Gaussian with mean zero. Its variance V obeys dV/dτ=2β(21−k)V+β, since the drift contributes twice its coefficient times V and the noise contributes β. Since da/dτ=βa,
dadV=a(1−2k)V+1=(−a1+1+a2(1−γ))V+a1,
using 1−2k=−1+2(1−k)=−1+2(1−γ)a/(1+a). The integrating factor is μ(a)=a(1+a)2(γ−1), because μ′/μ=1/a+2(γ−1)/(1+a) is minus the coefficient of V. Then d(μV)/da=μ/a=(1+a)2γ−2, and since μ(0)=0,
a one-dimensional integral that the widget below evaluates numerically.
The cell runs both samplers with exact scores on all 1000 steps of DDPM's schedule and compares them with the closed forms.
Python · cell 6
The simulated variances match the closed forms to within a few percent. At γ=3, DDIM gives 0.249 against 0.250, and DDPM gives 0.377 against 0.388. DDPM's small gap comes from the discrete steps of the schedule and from Monte Carlo error with 20,000 samples. Neither is close to the target's 0.500. At γ=5 DDIM's variance is 0.062, less than a fifth of the target's 0.333.
Guidance as a prediction step plus a sharpening step
If CFG does not sample pγ, what is it doing? Bradley and Nakkiran give a clean answer for the DDPM version. It needs one tool from §33.3, Langevin dynamics. That is the update x←x+η∇logρ(x)+2ηz, with step size η and fresh noise z∼N(0,I). In the limit of small steps it leaves the distribution ρ unchanged, so repeating it many times draws samples from ρ. A sampler that alternates a denoising step (the predictor) with Langevin steps (the corrector) is called a predictor-corrector sampler (§33.3).
∂ Matching the two steps term by term
Write sc=∇logpt(x∣c) and su=∇logpt(x). Keep terms of first order in βt, away from the last few steps, so 1/1−βt≈1+21βt and σt−12/σt2≈1. The DDPM step of §33.2 with the CFG score s~=(1−γ)su+γsc, using ϵ~=−σts~, is
A DDIM step for the conditional, which is Euler's method on the probability flow ODE, adds 21βt(x+sc). A Langevin step of size η=21βt on the powered distribution with exponent γ′ adds 21βt((1−γ′)su+γ′sc)+βtz. Their sum is
x+21βtx+21βt(1−γ′)su+21βt(1+γ′)sc+βtz.
The noise terms already agree. Matching the coefficient of su needs 21(1−γ′)=1−γ, and matching sc needs 21(1+γ′)=γ. Both give γ′=2γ−1.
In plain words, each guided DDPM step denoises toward the right class, then takes a single Langevin step toward a sharpened version of the current noisy distribution. One Langevin step per noise level is far too few to reach the sharpened distribution. And the sharpening at one level is inherited by the next. So the end result is shaped by the whole path, not by any single target.
In the closed-form example the result lands between the two powered distributions involved. Its variance at γ=3 is 0.3875. That is between the γ-powered target's 0.5 and the (2γ−1)-powered one's 2/(2γ)=0.333. This reading also explains the guidance interval later in the section. Sharpening a noisy distribution that is still one blob picks modes, which does more damage than sharpening one that has already separated into its modes.
The widget draws the exact outputs of both samplers, in the limit of many small steps, for the class N(0,1) and an unconditional N(0,vu) with vu from 1 to 4. Beside them it draws the γ-powered and the (2γ−1)-powered distributions. The vertical scale stays fixed while γ moves, so a curve that narrows also grows taller.
Do guided samplers draw the distribution guidance aims at?
Exact outputs of guided DDIM and DDPM for a class N(0, 1) and a wider unconditional Gaussian.
Loading interactive figure…
With vu=2, the closed-form case, move γ from 1 to 6. The DDIM curve narrows exponentially, while the DDPM curve stays between the two powered ones. Then bring vu toward 1 and watch every curve converge. Guidance can only sharpen what distinguishes the class from the unconditional distribution.
Research
How far is CFG from the powered target, exactly
For zero-mean one-dimensional Gaussians the exact noise predictions are linear in x. So deterministic DDIM with CFG maps xT to x0 by multiplying it by a constant, and the output variance is exact, with no sampling at all. Write three functions.
cfg_ddim_variance(gamma, v_u, v_c, a2) returns the exact output variance of DDIM with CFG and exact scores.
The distributions are p(x)=N(0,vu) and p(x∣c)=N(0,vc).
The sampler starts from x∼N(0,1) at the first grid point.
The grid a2 is an increasing array of α2 values from 0 (pure noise) to 1 (clean data), with σ2=1−α2.
Each step from (αt,σt) to (αs,σs) is xs=αsx^0+σsϵ^ with ϵ^=(xt−αtx^0)/σt, where x^0 is the CFG combination of the two exact posterior means.
powered_variance(gamma, v_u, v_c) returns the variance of p(x∣c)γp(x)1−γ. You may assume that this distribution exists, which means γ/vc>(γ−1)/vu.
kl_cfg_to_powered(gamma, v_u, v_c, a2) returns DKL(CFG output∥powered target), the divergence of the distribution we get from the one we wanted (§0.5).
import numpy as np
def cfg_ddim_variance(gamma, v_u, v_c, a2):
return v_c # placeholder, as if CFG returned the class
def powered_variance(gamma, v_u, v_c):
return v_c
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
What the scale trades at real scale
On ImageNet the scale traces out a curve, not a point. Ho and Salimans swept their w from 0 to 4. They found the best FID at small guidance and the best Inception Score at the largest. Past the FID optimum, more guidance raised the Inception Score and worsened the FID at every step of the sweep.
FID compares the whole distribution of samples with the data, so it punishes the diversity that guidance removes. Its optimum sits at a gentle γ between 1.1 and 1.3. Inception Score rewards confident, class-typical images and keeps rising. Which end you want depends on the product.
Refinements that fix the costs of plain guidance
Production systems rarely use plain CFG. Each refinement below fixes one cost of the plain version, and a table at the end of this part compares them.
Negative prompts replace the unconditional pass
A negative promptc− describes what you do not want, such as "blurry, extra fingers, watermark". It replaces the unconditional pass,
ϵ~=ϵθ(xt,t,c−)+γ(ϵθ(xt,t,c)−ϵθ(xt,t,c−)).
In scores this is sc+(γ−1)∇log[pt(x∣c)/pt(x∣c−)]. In plain words, it pushes toward images that the prompt explains much better than the negative prompt does. It costs nothing extra, since the negative pass replaces the unconditional one. When no negative prompt is given, implementations encode the empty prompt, which is ∅ again.
Be honest about what this is. The ratio pt(x∣c)/pt(x∣c−) compares two particular conditions. It is not the posterior of any classifier, so the Bayes argument behind CFG does not apply. The rule follows the field of the product p(x∣c)γp(x∣c−)1−γ, which can sit far from the data. Negative prompts are a heuristic that works well in practice, at moderate scales.
The widget's option "A against B" shows how far it can go wrong. With class B as the negative condition for class A, the samples at γ=3 leave the data entirely, to a mean horizontal position near −7, and the product distribution goes with them. For two Gaussians of equal width that product is a Gaussian of the same width centered at γμc−(γ−1)μc−, which moves linearly with γ.
Plain CFG cannot run away like this. Its unconditional density contains the class with weight p(c), so the ratio p(x∣c)/p(x) never exceeds 1/p(c). The push toward the class levels off once x is typical of it. A real negative prompt usually describes something that overlaps the prompt (the same scene, but blurry), which keeps the push local.
Rescaling stops oversaturation
At large γ the guided prediction grows in magnitude. The images come out overexposed and oversaturated, and the effect is worst in a model with zero terminal SNR, one whose last noise level keeps no trace of the data (§33.1). The Imagen text-to-image model (Saharia et al. 2022) met the same problem in pixel space and fixed it with dynamic thresholding. At each sampling step, let s be a high percentile of the absolute pixel values of the predicted x^0. If s>1, clip x^0 to [−s,s] and divide it by s. This pulls a strongly guided prediction back inside the [−1,1] range of the training images. A latent has no such fixed range, so Lin et al. (2023) proposed a fix in the same spirit that also works for latent models.
In plain words, shrink the guided prediction back to the spread the conditional prediction had, but only most of the way. Lin et al. apply this to the output of a v-predicting model. The diffusers library applies the same function to whatever the network outputs, noise or v, under the name guidance_rescale, which defaults to 0.
Core
CFG rescale, per sample
Write cfg_rescale(x_cfg, x_cond, phi) for arrays of shape (B, ...) with any number of non-batch axes, such as (B, C, H, W) images or (B, d) vectors. Compute one standard deviation per sample, over every non-batch axis, never over the batch.
import numpy as np
def cfg_rescale(x_cfg, x_cond, phi):
raise NotImplementedError
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
Guidance only where it helps
Kynkäänniemi et al. (2024) asked at which noise levels guidance does its good and its harm. They found it harmful at high noise, largely unnecessary at low noise, and beneficial only in the middle. So they apply it only for noise levels in an interval (σlo,σhi] and use γ=1 outside it. The noise level here is σ=σt/αt, the scale used by the EDM family of models (Karras et al. 2022), and it is tied to the log-SNR λ=ln(αt2/σt2) by λ=−2lnσ (§33.1).
Our toy shows the mechanism. The cell applies γ=4 in different windows of time.
Python · cell 7
Guiding only the noisy steps (t>200, log-SNR below 0.66) does all the damage. It gives the same mode collapse as guiding everywhere (far-mode share 0.993 against 0.995). Guiding only the window 100<t≤200, log-SNR from 0.66 to 2.16, gives precision 1.000 with both modes intact (far-mode share 0.535). It also keeps most of the spread (1.04 against 1.37). Guiding only the cleanest steps, t≤100, works too in this toy (precision 0.999, far-mode share 0.513, spread 1.20), because its two classes still overlap there and the boundary is still being drawn. On images, Kynkäänniemi et al. found guidance at low noise largely unnecessary. The toy shows the other half of their finding, that the damage is done at high noise.
The reason is the order of events. At high noise the noisy distribution is still one blob, and the guided field decides which mode each sample heads for. Extrapolating it there steers samples to the class's most distinctive mode. By the middle of the chain the modes have separated, and guidance only sharpens the boundary between classes, which is the part we wanted. In the widget, set γ=4 and lower the upper end of the window from 1000 to 200. The far-mode share falls back from 99 percent to about 50, while the precision stays at 100 percent.
Guiding with a weaker copy of the model
CFG entangles two effects, better images and less variety. Karras et al. (2024) separated them with autoguidance. Instead of the unconditional model, they guide with a worse version of the same conditional model, smaller and trained for less time. Write ϵ1 for the main model and ϵ0 for this guide,
ϵ~=ϵ0(xt,t,c)+γ(ϵ1(xt,t,c)−ϵ0(xt,t,c)).
Their argument is that both models make the same kind of error in the same places, spreading into low-probability regions they have not learned, and the weaker one errs more. So their difference points from worse toward better. Extrapolating it corrects the main model's error without pushing away from other classes, and they report that it keeps much more variety than CFG.
The numbers are strong. With EDM2-S on ImageNet-512, a guide one size smaller (XS), trained on one sixteenth as many images, reached FID 1.34, against 2.23 for CFG and 2.56 with no guidance. EDM2-XXL guided by the medium-sized EDM2-M reached 1.25. Autoguidance also works for unconditional models, which CFG cannot guide at all, and took unconditional EDM2-S from FID 11.67 to 3.86. The price is a second model to train and store, though a small one.
Distilling guidance into one network call
CFG doubles the cost of every step. Meng et al. (2023) remove the doubling in two stages. First, they train a student ϵθ′(xt,t,c,w) that reproduces the teacher's guided prediction for a range of strengths w, in the (1+w) convention. It takes the strength as an extra input, embedded with Fourier features as the time is, and it halves the network calls. Second, they apply progressive distillation (§33.4), which repeatedly trains a student to do two of the previous model's steps in one, to cut the number of steps.
Their pixel-space students for ImageNet 64×64 and CIFAR-10 came close to the teacher's FID and Inception Score with as few as 4 to 16 steps. Latent models such as Stable Diffusion produced good images in 1 to 4 steps. Released models now often ship with guidance distilled in. FLUX.1 [dev], a 12-billion-parameter rectified flow transformer, is distributed as a guidance-distilled model. Its model card says it was trained using guidance distillation, and its example passes guidance_scale=3.5 as an input to a single network call per step.
Guidance carries over to flow models
Flow-matching models (§33.6) predict a velocity, the direction a sample moves along its path from noise to data. For a Gaussian path the velocity is affine in the noise prediction at fixed xt. By the affine-target theorem, CFG applied to velocities is the same CFG. So are negative prompts, intervals, and autoguidance, which are all mixes with weights that sum to one. CFG rescale is the exception. A standard deviation does not commute with the affine conversion, so rescaling the velocity and rescaling the noise prediction give different results. An implementation must say which output it rescales.
method
extra cost per step
what it fixes
what it costs or risks
classifier guidance
a classifier gradient (backward pass)
weak condition adherence
a separate noise-aware classifier, possibly adversarial gradients
CFG
one more network call
weak adherence, with no extra model
diversity, saturation at large γ, doubled NFE
negative prompt
none beyond CFG
unwanted content
a heuristic that can extrapolate off the data
CFG rescale
negligible
overexposure at large γ
flat-looking images if fully rescaled
guidance interval
fewer calls than CFG
mode dropping from early guidance
two more hyperparameters, σlo and σhi
autoguidance
one call to a small model
quality without the diversity loss
training and storing a guide model
guidance distillation
none (one call)
doubled NFE
a distillation run, fixed range of scales
Fine-tuning on rewards puts the push into the weights
Guidance pushes the sampler toward a classifier at sampling time. Often we want a push toward something no classifier provides, such as human preference, aesthetics, or correct object counts. And we would like it built into the weights, so that sampling stays cheap. The theorem on tilted targets says what the ideal is. For a reward r(x0,c), the KL-regularized optimum of §17.1 is the tilt pref(x0∣c)exp(r/βKL)/Z, where βKL is the weight on the KL penalty. Three methods learn it, each by borrowing a tool from the language-model chapters.
Denoising as a sequence of decisions
DDPO (Black et al. 2024) treats denoising as a sequence of decisions, the setting of reinforcement learning (§15.3).
The state is (c,t,xt), and the action is xt−1.
The policy is the learned reverse step pθ(xt−1∣xt,c).
The only reward, r(x0,c), arrives at the end.
Each reverse step is a Gaussian with mean μθ(xt,t,c) and fixed variance νt2. So its log-likelihood is exact and differentiable, logpθ(xt−1∣xt,c)=−∥xt−1−μθ∥2/(2νt2)+const.
The policy gradient raises the log-probability of each action in proportion to the reward that followed,
∇θJ=E[t=1∑T∇θlogpθ(xt−1∣xt,c)r(x0,c)].
The version that reuses each batch of samples for several updates adds importance ratios with the clipping of PPO (§15.6), which limits how far each update can move the policy. DDPO fine-tuned Stable Diffusion for four rewards.
JPEG compressibility, the file size after compression, and its opposite, incompressibility.
The LAION aesthetics predictor, a model of how much people like an image, trained on 176,000 human ratings.
Prompt alignment. A vision-language model (LLaVA) describes the image, and the description is compared with the prompt.
It also reported reward hacking of the kind §16.5 warns about, where the model finds an unintended way to score high. Asked for "n animals", the fine-tuned model learned to write text that looks like the number, which fooled the vision-language model, instead of drawing the right count. Trained for incompressibility long enough, it stopped drawing anything recognizable and produced high-frequency noise.
Preferences become a comparison of denoising errors
Diffusion-DPO (Wallace et al. 2024) adapts direct preference optimization, DPO (§17.2). DPO learns from pairs of a preferred and a rejected output. It raises the policy's log-likelihood ratio to a frozen reference model on the preferred output, relative to the rejected one. That needs the log-likelihood of a sample, which a diffusion model does not have in closed form. So Wallace et al. replace it with the variational bound of §33.2, which turns log-likelihood ratios into differences of denoising errors.
Take a preferred image x0w and a rejected one x0l. Noise each with its own noise, ϵw and ϵl, to the same time t. For an image x noised with ϵ, let
Δ(x,ϵ)=∥ϵ−ϵθ(xt,t)∥2−∥ϵ−ϵref(xt,t)∥2,
the policy's denoising error minus the reference's. The loss is
L(θ)=−E[logsigmoid(−βDPO(Δ(xw,ϵw)−Δ(xl,ϵl)))],
where βDPO collects the KL weight, the number of steps, and a weighting, as the derivation below shows. (The prompt c is an input to both networks and is left out of the notation.)
In plain words, get better than the reference at denoising the preferred image, and worse at denoising the rejected one. Here Δ<0 means the policy denoises that image better than the reference does. So the loss falls as Δ(xw,ϵw) goes down and Δ(xl,ϵl) goes up. When the policy equals the reference, every Δ is zero and the loss is log2=0.693.
∂ From DPO to a comparison of denoising errors
DPO minimizes, for a prompt c and a pair in which x0w is preferred to x0l,
Step 1, likelihoods by their bounds.§33.2 wrote the variational bound as a weighted sum of noise-prediction errors. Write its weights ωt (§33.2 writes wt, but in this section w is a guidance strength). Then −logpθ(x0)≤∑t=1TωtEϵ∥ϵ−ϵθ(xt,t)∥2+C(x0). The t=1 term is treated like the others, as the simple loss does, and C(x0) collects the terms that have no parameters. Treat the bound as if it were tight for both models. They share the forward process, so C is the same for both and cancels in the ratio. With t uniform on {1,…,T},
logpref(x0)pθ(x0)≈−TEt,ϵ[ωtΔ(x0,ϵ)].
This step is an approximation, not a bound, since the difference of two upper bounds bounds nothing.
Step 2, Jensen. Substituting puts an expectation over t and the noises inside the log-sigmoid, where one sample would give a biased gradient. The two expectations combine into one, E[ωtΔ(xw,ϵw)]−E[ωtΔ(xl,ϵl)]=E[ωt(Δ(xw,ϵw)−Δ(xl,ϵl))], with one t for the pair. The map u↦−logsigmoid(u) is convex, so Jensen's inequality gives −logsigmoid(E[z])≤E[−logsigmoid(z)]. Moving the expectation outside yields an upper bound whose gradient one draw of (t,ϵw,ϵl) per pair estimates without bias.
Step 3, a constant weight. As in the simple loss, replace ωt by a constant ω. Then βDPO=βKLTω, and the bound is the loss above.
Wallace et al. reach the same loss by a longer route through whole denoising chains. They approximate the model's reverse chain by the forward process, with a weighting ω(λt) that is constant in practice. The short route shows where each approximation enters.
Wallace et al. fine-tuned SDXL-1.0, an open latent text-to-image model, on Pick-a-Pic v2, a dataset of users' choices between pairs of generated images. After removing ties it has 851,293 pairs. On the PartiPrompts prompt set, human raters preferred the result 69 percent of the time over the larger SDXL pipeline with its refiner model. They found βDPO between 2000 and 5000 to work for both Stable Diffusion 1.5 and SDXL.
Interview
The Diffusion-DPO loss
Write diffusion_dpo_loss(eps_model, eps_ref, xw, xl, t, eps_w, eps_l, alpha, sigma, beta_dpo). It returns the loss above, averaged over a batch of B preference pairs, as a float. The inputs are these.
xw and xl are the preferred and the rejected images, of shape (B, ...) with any number of non-batch axes.
t is an integer array of shape (B,), one time per pair.
eps_w and eps_l are the noises of the two images, of the same shape as the images.
alpha and sigma are the schedule arrays, indexed by time.
The policy eps_model(x, t) and the frozen reference eps_ref(x, t) take a batch of noisy inputs and a time array of matching length. They return noise predictions of the same shape as x.
Noise each image with its own noise at its pair's time. Sum the squared errors over every non-batch axis, the ∥⋅∥2 of the text. Keep the loss finite for βDPO in the thousands. The setup gives DDPM's linear schedule as DPO_ALPHA and DPO_SIGMA, and two fixed linear stand-ins for the networks, eps_policy and eps_ref.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
Making flow sampling random enough for reinforcement learning
GRPO (§18.4) samples a group of outputs per prompt and scores each one. Each output's advantage is its reward minus the group's mean, divided by the group's standard deviation, so no learned value function is needed. Flow-GRPO (Liu et al. 2025) brings it to flow-matching models. The obstacle is that their samplers solve an ODE, which is deterministic. A deterministic step has no probability to put in a policy gradient.
The fix uses a fact from the SDE view of §33.3. A whole family of reverse-time processes has the same marginals, from the deterministic probability flow ODE to the reverse SDE, indexed by how much noise they inject. Flow-GRPO converts the flow's ODE into one of these SDEs. The score the SDE needs follows from the predicted velocity, by the conversions of §33.6. Every step then becomes a Gaussian policy, and the sampler keeps the original marginals. A group of images per prompt can be sampled and scored. The policy is updated with clipped ratios and a KL penalty to the reference model, which is closed-form between Gaussian steps.
∂ A family of samplers with the same marginals
For a forward SDE dx=fdt+gdw and any stochasticity level η≥0 (a noise multiplier, like DDIM's η in §33.4, not a step size), consider the reverse-time process
dx=[f−21+η2g2∇logpt]dt+ηgdwˉ.
At η=0 it is the probability flow ODE, and at η=1 it is the reverse SDE. Its Fokker-Planck equation, written in forward time, is
The diffusion term has a minus sign because a process run backward in time contributes its diffusion with the opposite sign. The second equality uses ∇⋅(p∇logp)=∇⋅∇p. The right side is the Fokker-Planck equation of the forward SDE, so every η gives the same marginals pt.
To save compute, Flow-GRPO collects training trajectories with only 10 denoising steps, while sampling with the full schedule at inference. It raised the GenEval accuracy of Stable Diffusion 3.5 Medium, an open rectified flow model, from 63 to 95 percent. GenEval checks object counts, colors, and positions with an object detector. Text-rendering accuracy rose from 59 to 92 percent. Without the KL term, image quality or diversity collapsed, which the authors describe as reward hacking. With a tuned KL term the gains held without that loss.
Rewards, preferences, and guidance are three handles on the same tilt. Guidance tilts at sampling time and pays in network calls. Fine-tuning tilts once, in the weights, and pays in training compute and in the reward-hacking risk that every learned reward carries.
Read more
Dhariwal & Nichol (2021). Diffusion Models Beat GANs on Image Synthesis. Classifier guidance, its derivation as a mean shift, the noise-aware classifier, and the precision and recall trade-off in Table 4.
Ho & Salimans (2022). Classifier-Free Diffusion Guidance. The implicit classifier, condition dropout, the (1+w) convention, and the FID and Inception Score sweeps.
🎬 But how do AI images and videos actually work? | Guest video by Welch Labs · 3Blue1Brown · starts at 26:37From 26:37 it animates conditioning, classifier-free guidance as vector fields, and negative prompts, the best visual companion to this section.🎬 DDPM - Diffusion Models Beat GANs on Image Synthesis (Machine Learning Research Paper Explained) · Yannic Kilcher · starts at 40:35From 40:35, a walk through Dhariwal and Nichol's classifier guidance, its derivation as a shifted Gaussian mean, and the scale experiments.🎬 Coding Stable Diffusion from scratch in PyTorch · Umar Jamil · starts at 22:20From 22:20, classifier-free guidance explained and then implemented in a full Stable Diffusion pipeline, with condition dropout and the two batched passes.