Type at least 2 letters. Enter opens the first result, Esc closes.

    Generative Models · Lesson 11 · Control, speed and scale

    Guidance: classifier guidance and classifier-free guidance

    Advanced 75 min 3 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 08 (the score and the noise prediction, score =−ε^/σt= -\hat\varepsilon/\sigma_t, Tweedie's formula) and lesson 09 (the reverse SDE, the probability-flow ODE, DDIM). You also need Bayes' rule and Bayesian inference (posterior ∝\propto likelihood ×\times 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 7.57.5 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 yy be a condition. Bayes' rule gives p(x∣y)=p(y∣x) p(x)/p(y)p(x \mid y) = p(y \mid x)\,p(x)/p(y). Take the logarithm and the gradient with respect to xx. The term log⁡p(y)\log p(y) does not depend on xx, so it disappears:

    ∇xlog⁡p(x∣y)=∇xlog⁡p(x)+∇xlog⁡p(y∣x).\nabla_x \log p(x \mid y) = \nabla_x \log p(x) + \nabla_x \log p(y \mid x).

    In words: the conditional score is the unconditional score plus the gradient of a classifier p(y∣x)p(y \mid x). The classifier gradient points to where xx looks more like class yy.

    The simplest case: two classes in 1D #

    Take two classes y∈{+,−}y \in \{+, -\} with p(+)=p(−)=12p(+) = p(-) = \tfrac12 and Gaussian classes x∣±∼N(±0.5, 0.25)x \mid \pm \sim \mathcal N(\pm 0.5,\ 0.25). The log-ratio of the two class densities is

    log⁡N(x;0.5,0.25)N(x;−0.5,0.25)=(x+0.5)2−(x−0.5)22⋅0.25=2x0.5=4x.\log\frac{\mathcal N(x; 0.5, 0.25)}{\mathcal N(x; -0.5, 0.25)} = \frac{(x + 0.5)^2 - (x - 0.5)^2}{2 \cdot 0.25} = \frac{2x}{0.5} = 4x .

    So the classifier is logistic: p(+∣x)=sigmoid(4x)p(+ \mid x) = \mathrm{sigmoid}(4x). Its log-gradient is 4 (1−sigmoid(4x))4\,(1 - \mathrm{sigmoid}(4x)). It pushes xx to the right. The push is strong where xx looks like the other class (x<0x < 0) and weak far to the right, where the classifier is already sure.

    Turning up the classifier. Multiply the classifier term by a guidance scale ss. The new score is the score of the density ∝p(x) p(y∣x)s\propto p(x)\,p(y \mid x)^{s}. For s=0s = 0 this is p(x)p(x). For s=1s = 1 it is p(x∣y)p(x \mid y). For s>1s > 1 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 ptp_t (lesson 09). So it needs the classifier of noisy inputs, pt(y∣xt)p_t(y \mid x_t). In our example with VP noising xt=atx0+σtεx_t = a_t x_0 + \sigma_t\varepsilon (at=αˉta_t = \sqrt{\bar\alpha_t}, σt2=1−αˉt\sigma_t^2 = 1 - \bar\alpha_t), each class is again Gaussian: xt∣±∼N(±0.5 at, vt)x_t \mid \pm \sim \mathcal N(\pm 0.5\,a_t,\ v_t) with vt=0.25 at2+σt2v_t = 0.25\,a_t^2 + \sigma_t^2. The same computation as above gives a logistic classifier pt(+∣xt)=sigmoid(ktxt)p_t(+ \mid x_t) = \mathrm{sigmoid}(k_t x_t) with slope

    kt=2⋅0.5 atvt=at0.25 αˉt+1−αˉt.k_t = \frac{2 \cdot 0.5\,a_t}{v_t} = \frac{a_t}{0.25\,\bar\alpha_t + 1 - \bar\alpha_t} .

    The slope is 4.04.0 at αˉ=1\bar\alpha = 1 (clean data), then 1.131.13, 0.340.34 and 0.100.10 at αˉ=0.5,0.1,0.01\bar\alpha = 0.5, 0.1, 0.01. At high noise the class is hard to tell from xtx_t, so the noisy classifier is almost flat and its gradient is small.

    Interactive figure: loading…

    Move the noise level αˉ\bar\alpha 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 ss (bottom). The orange guided density ∝p(x) p(+∣x)s\propto p(x)\,p(+ \mid x)^s equals the blue class density at s=1s = 1. For s>1s > 1 it gets narrower and moves right, and P(x>0)P(x > 0) approaches 1. Everything is computed exactly, not learned.

    There are two ways to get ∇log⁡pt(y∣xt)\nabla \log p_t(y \mid x_t) 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.

    Quick check

    In the two-class example, what is the slope of the noisy classifier at αˉ=0.1\bar\alpha = 0.1, and what does it mean for guidance at that noise level?

    3. Definitions and main results #

    Theorem 1 (the conditional score at each noise level) #

    For every tt,

    ∇xlog⁡pt(x∣y)=∇xlog⁡pt(x)+∇xlog⁡pt(y∣x),pt(y∣xt)=∫p(y∣x0) p(x0∣xt) dx0.\nabla_{x}\log p_t(x \mid y) = \nabla_{x}\log p_t(x) + \nabla_{x}\log p_t(y \mid x), \qquad p_t(y \mid x_t) = \int p(y \mid x_0)\,p(x_0 \mid x_t)\,dx_0 .

    Proof.

    1. Bayes' rule for the pair (y,xt)(y, x_t): pt(x∣y)=pt(y∣x) pt(x)/p(y)p_t(x \mid y) = p_t(y \mid x)\,p_t(x)/p(y). Noising xx does not change the distribution of yy, so p(y)p(y) is the same at every tt.
    2. Take the log and the gradient in xx. The term log⁡p(y)\log p(y) does not depend on xx, so its gradient is 0.
    3. Marginalize over the clean data: pt(y∣xt)=∫p(y∣x0,xt) p(x0∣xt) dx0p_t(y \mid x_t) = \int p(y \mid x_0, x_t)\,p(x_0 \mid x_t)\,dx_0. Given x0x_0, the noisy xtx_t is x0x_0 plus independent noise, so it carries no extra information about yy: p(y∣x0,xt)=p(y∣x0)p(y \mid x_0, x_t) = p(y \mid x_0). ■\blacksquare

    Step 3 says that the noisy classifier averages the clean classifier over the denoising posterior p(x0∣xt)p(x_0 \mid x_t). A clean classifier evaluated at xtx_t 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 pϕ(y∣xt,t)p_\phi(y \mid x_t, t) on noisy inputs and samples with the score of pt(x) pϕ(y∣x)sp_t(x)\,p_\phi(y \mid x)^{s}:

    ∇log⁡pt(x)+s ∇log⁡pϕ(y∣x).\nabla \log p_t(x) + s\,\nabla \log p_\phi(y \mid x) .

    Multiply by −σt-\sigma_t to get the guided noise prediction (score =−ε^/σt= -\hat\varepsilon/\sigma_t):

    ε~=ε^θ(xt,t)−s σt ∇xtlog⁡pϕ(y∣xt).\tilde\varepsilon = \hat\varepsilon_\theta(x_t, t) - s\,\sigma_t\,\nabla_{x_t} \log p_\phi(y \mid x_t) .

    This is their equation 14, used inside DDIM. (For ancestral sampling their algorithm 1 instead shifts the mean of each step by s Σ ∇log⁡pϕs\,\Sigma\,\nabla \log p_\phi.) Their classifier is the downsampling half of the U-Net, trained on the same noising distribution. With s=1s = 1 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 ss fixed this. The cost: a second network trained on noisy data, and a backward pass through it at every step.

    Quick check

    At one step, σt=0.6\sigma_t = 0.6, the unconditional prediction is ε^=0.2\hat\varepsilon = 0.2 (1D), the classifier gradient is ∇xtlog⁡pϕ(y∣xt)=0.5\nabla_{x_t}\log p_\phi(y \mid x_t) = 0.5 and the scale is s=2s = 2. What is the guided noise prediction?

    Classifier-free guidance #

    Classifier-free guidance (Ho and Salimans 2022) needs no classifier.

    • Training (their algorithm 1). Train one network ε^θ(xt,t,c)\hat\varepsilon_\theta(x_t, t, c). In each training example, replace the condition cc by the null token ∅\varnothing with probability puncondp_{\text{uncond}}. This is called condition dropout. They found 0.10.1 and 0.20.2 equally good and 0.50.5 worse. The network learns the conditional and the unconditional model at the same time.
    • Sampling (their algorithm 2). At each step evaluate both ε^c\hat\varepsilon_c and ε^u\hat\varepsilon_u (one batch of two, so 2 NFE per step) and use ε~=ε^u+w (ε^c−ε^u)\tilde\varepsilon = \hat\varepsilon_u + w\,(\hat\varepsilon_c - \hat\varepsilon_u) in any sampler of lesson 09.

    Theorem 2 (CFG is the conditional model plus implicit-classifier guidance) #

    Let g=∇log⁡pt(x∣y)−∇log⁡pt(x)g = \nabla \log p_t(x \mid y) - \nabla \log p_t(x) be the implicit classifier gradient (=∇log⁡pt(y∣x)= \nabla \log p_t(y \mid x) by Theorem 1). For exact noise predictions, g=−(ε^c−ε^u)/σtg = -(\hat\varepsilon_c - \hat\varepsilon_u)/\sigma_t and

    ε^u+w (ε^c−ε^u)=ε^c−(w−1) σt g.\hat\varepsilon_u + w\,(\hat\varepsilon_c - \hat\varepsilon_u) = \hat\varepsilon_c - (w - 1)\,\sigma_t\,g .

    Proof.

    1. Both scores are −ε^/σt-\hat\varepsilon/\sigma_t of their prediction, so g=−(ε^c−ε^u)/σtg = -(\hat\varepsilon_c - \hat\varepsilon_u)/\sigma_t.
    2. Rearrange: ε^u+w(ε^c−ε^u)=ε^c+(w−1)(ε^c−ε^u)\hat\varepsilon_u + w(\hat\varepsilon_c - \hat\varepsilon_u) = \hat\varepsilon_c + (w - 1)(\hat\varepsilon_c - \hat\varepsilon_u).
    3. Substitute ε^c−ε^u=−σt g\hat\varepsilon_c - \hat\varepsilon_u = -\sigma_t\,g from step 1. The result is the classifier-guidance formula applied to the conditional model, with scale s=w−1s = w - 1 and classifier gradient gg.
    4. In score form the guided score is (1−w)∇log⁡pt(x)+w∇log⁡pt(x∣y)=∇log⁡[pt(x∣y) pt(y∣x)w−1](1 - w)\nabla \log p_t(x) + w\nabla \log p_t(x \mid y) = \nabla \log\big[p_t(x \mid y)\,p_t(y \mid x)^{w-1}\big]. This is also classifier guidance with scale ww on the unconditional model. ■\blacksquare

    So no classifier is trained: the generative model is the classifier, through pt(y∣x)∝pt(x∣y)/pt(x)p_t(y \mid x) \propto p_t(x \mid y)/p_t(x). Ho and Salimans add a caveat: a real network's ε^\hat\varepsilon fields are not exactly gradients of anything, so in general no classifier exists whose gradient gives the guided field.

    Interactive figure: loading…

    Move the guidance weight ww. The 8 Gaussians are split into a target class yy (blue) and another class (grey). The scores are exact, not learned, and the orange samples come from the guided probability-flow ODE. At w=0w = 0 about half of the samples are in the wrong class; at w=1w = 1 (exact conditional model) all are right. For w>1w > 1 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 w=1w = 1 gives.

    Quick check

    In Ho and Salimans' convention a paper reports guidance weight w′=2w' = 2. Which weight ww is this in the convention ε~=ε^u+w(ε^c−ε^u)\tilde\varepsilon = \hat\varepsilon_u + w(\hat\varepsilon_c - \hat\varepsilon_u), and what does w=1w = 1 mean there?

    What guidance does to the sampled distribution #

    At noise level tt the guided score is the score of

    πt∝pt(x)1−w pt(x∣y)w=pt(x∣y) pt(y∣x)w−1⋅const.\pi_t \propto p_t(x)^{1-w}\,p_t(x \mid y)^{w} = p_t(x \mid y)\,p_t(y \mid x)^{w-1}\cdot\text{const}.

    It is tempting to conclude that the sampler returns π0∝p(x)1−w p(x∣y)w\pi_0 \propto p(x)^{1-w}\,p(x \mid y)^{w}, the tilted target. It does not, except for w=0w = 0 and w=1w = 1:

    1. 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 πt\pi_t is π0\pi_0 convolved with the noise kernel (lesson 09).
    2. Noising (a convolution with a Gaussian) and tilting (powers and products of densities) do not commute. So πt\pi_t is not the noised π0\pi_0. The worked example in section 4(b) shows this with numbers.
    3. 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 π0\pi_0 (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 p(x)=N(0,vu)p(x) = \mathcal N(0, v_u) and the conditional density p(x∣y)=N(mc,vc)p(x \mid y) = \mathcal N(m_c, v_c) with vc<vuv_c < v_u (for example the posterior of a Gaussian prior after a noisy observation). Use VE noising xσ=x+σnx_\sigma = x + \sigma n, so pσ(x)=N(0,vu+σ2)p_\sigma(x) = \mathcal N(0, v_u + \sigma^2) and pσ(x∣y)=N(mc,vc+σ2)p_\sigma(x \mid y) = \mathcal N(m_c, v_c + \sigma^2). Let w≥1w \ge 1. The guided PF-ODE, started from N(0,σmax⁡2)\mathcal N(0, \sigma_{\max}^2) with σmax⁡→∞\sigma_{\max} \to \infty, ends at a Gaussian with variance vc w vu 1−wv_c^{\,w}\,v_u^{\,1-w}. The tilted target π0\pi_0 has variance 1/((1−w)/vu+w/vc)1/\big((1-w)/v_u + w/v_c\big).

    Proof of Proposition 3
    1. The guided score is (1−w)⋅−xvu+σ2+w⋅mc−xvc+σ2=−λ(σ) x+w mcvc+σ2(1-w)\cdot\frac{-x}{v_u + \sigma^2} + w\cdot\frac{m_c - x}{v_c + \sigma^2} = -\lambda(\sigma)\,x + \frac{w\,m_c}{v_c + \sigma^2} with λ(σ)=1−wvu+σ2+wvc+σ2\lambda(\sigma) = \frac{1-w}{v_u+\sigma^2} + \frac{w}{v_c+\sigma^2}. Since vc<vuv_c < v_u, λ>0\lambda > 0.
    2. The VE PF-ODE is dx/dσ=−σ×scoredx/d\sigma = -\sigma \times \text{score}. It is affine in xx, so a Gaussian start stays Gaussian, and the variance VV obeys dV/dσ=2σλ(σ)VdV/d\sigma = 2\sigma\lambda(\sigma)V.
    3. Note 2σλ(σ)=ddσ[(1−w)ln⁡(vu+σ2)+wln⁡(vc+σ2)]2\sigma\lambda(\sigma) = \frac{d}{d\sigma}\big[(1-w)\ln(v_u+\sigma^2) + w\ln(v_c+\sigma^2)\big]. Integrate from σmax⁡\sigma_{\max} down to 0: V(0)=V(σmax⁡) (vu+σmax⁡2)w−1(vc+σmax⁡2)−w vu1−wvcwV(0) = V(\sigma_{\max})\,(v_u + \sigma_{\max}^2)^{w-1}(v_c + \sigma_{\max}^2)^{-w}\,v_u^{1-w}v_c^{w}.
    4. With V(σmax⁡)=σmax⁡2V(\sigma_{\max}) = \sigma_{\max}^2, the factor in front of vu1−wvcwv_u^{1-w}v_c^{w} tends to 1 as σmax⁡→∞\sigma_{\max} \to \infty. ■\blacksquare

    The ODE interpolates the variances geometrically. The tilted target interpolates the precisions (inverse variances) linearly. For w>1w > 1 and vc<vuv_c < v_u the ODE result is always the narrower one: guidance overshoots even the tilted target.

    Quick check

    In Proposition 3 take vu=0.5v_u = 0.5, vc=0.25v_c = 0.25 and w=2w = 2. Which variances do the guided PF-ODE result and the tilted target have?

    The fidelity–diversity trade-off #

    • Numbers (Dhariwal and Nichol, table 4, conditional ImageNet 256×256256\times256, classifier scale ss). No guidance: FID 10.94, precision 0.69, recall 0.63. s=1s = 1: FID 4.59, precision 0.82, recall 0.52. s=10s = 10: 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 w′=0.1w' = 0.1 on ImageNet 64×6464\times64 and w′=0.3w' = 0.3 on 128×128128\times128 (w=1.1w = 1.1 and 1.31.3). The Inception score kept rising up to the largest value they tested, w′=4w' = 4.
    • Oversaturation. A large ww 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 ϕ=0.7\phi = 0.7).
    • 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 w>1w > 1 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 σ→∞\sigma \to \infty the centre of πσ\pi_\sigma tends to w mcw\,m_c, so at high noise guidance pulls every sample toward one extrapolated point. This removes diversity before the details are decided.

    Interactive figure: loading…

    Move the interval ends σlo\sigma_{\text{lo}} and σhi\sigma_{\text{hi}}. 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 σ\sigma in the yellow band, and the plain conditional model elsewhere. Notice that guidance at high noise (move σlo\sigma_{\text{lo}} 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: ε~=ε^bad+w (ε^good−ε^bad)\tilde\varepsilon = \hat\varepsilon_{\text{bad}} + w\,(\hat\varepsilon_{\text{good}} - \hat\varepsilon_{\text{bad}}). 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).

    Quick check

    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?

    Answers to section 1. (1) Neither, for w=3w = 3. The samples are not from p(x∣y)p(x \mid y) (that needs w=1w = 1). 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 (1−w) score+w score(1 - w)\,\text{score} + w\,\text{score} is the unguided score. The variance stays 0.250.25 in the example of section 4(c).

    4. Worked example #

    (a) One CFG step and its two readings. 2D, αˉ=0.64\bar\alpha = 0.64, so σt=1−0.64=0.6\sigma_t = \sqrt{1 - 0.64} = 0.6. Take ε^u=(0.1,0.4)\hat\varepsilon_u = (0.1, 0.4), ε^c=(0.3,0.1)\hat\varepsilon_c = (0.3, 0.1) and w=4w = 4.

    1. ε^c−ε^u=(0.3−0.1, 0.1−0.4)=(0.2,−0.3)\hat\varepsilon_c - \hat\varepsilon_u = (0.3 - 0.1,\ 0.1 - 0.4) = (0.2, -0.3).
    2. ε~=(0.1,0.4)+4 (0.2,−0.3)=(0.1+0.8, 0.4−1.2)=(0.9,−0.8)\tilde\varepsilon = (0.1, 0.4) + 4\,(0.2, -0.3) = (0.1 + 0.8,\ 0.4 - 1.2) = (0.9, -0.8).
    3. Ho and Salimans' convention: w′=w−1=3w' = w - 1 = 3, and 4 ε^c−3 ε^u=(1.2−0.3, 0.4−1.2)=(0.9,−0.8)4\,\hat\varepsilon_c - 3\,\hat\varepsilon_u = (1.2 - 0.3,\ 0.4 - 1.2) = (0.9, -0.8) ✓.
    4. Implicit classifier gradient: g=−(0.2,−0.3)/0.6=(−0.3333, 0.5)g = -(0.2, -0.3)/0.6 = (-0.3333,\ 0.5).
    5. Theorem 2: ε^c−(w−1) σt g=(0.3,0.1)−3⋅0.6⋅(−0.3333,0.5)=(0.3+0.6, 0.1−0.9)=(0.9,−0.8)\hat\varepsilon_c - (w - 1)\,\sigma_t\,g = (0.3, 0.1) - 3 \cdot 0.6 \cdot (-0.3333, 0.5) = (0.3 + 0.6,\ 0.1 - 0.9) = (0.9, -0.8) ✓.

    (b) Three different answers. Proposition 3's model with vu=0.5v_u = 0.5, vc=0.25v_c = 0.25, mc=0.5m_c = 0.5 (the posterior of the prior N(0,0.5)\mathcal N(0, 0.5) after observing y=1y = 1 with noise variance 0.50.5). Take w=3w = 3.

    1. Tilted target π0\pi_0. Precision (1−3)/0.5+3/0.25=−4+12=8(1 - 3)/0.5 + 3/0.25 = -4 + 12 = 8, so the variance is 1/8=0.1251/8 = 0.125. The mean is (precision-weighted) (3⋅0.5/0.25)/8=6/8=0.75(3 \cdot 0.5/0.25)/8 = 6/8 = 0.75.
    2. The guided field at σ=1\sigma = 1 is the score of π1\pi_1 with precision λ(1)=−2/1.5+3/1.25=−1.3333+2.4=1.0667\lambda(1) = -2/1.5 + 3/1.25 = -1.3333 + 2.4 = 1.0667: variance 0.93750.9375, mean (3⋅0.5/1.25)/1.0667=1.2/1.0667=1.125(3 \cdot 0.5/1.25)/1.0667 = 1.2/1.0667 = 1.125. The noised target π0∗N(0,1)\pi_0 * \mathcal N(0, 1) has variance 0.125+1=1.1250.125 + 1 = 1.125 and mean 0.750.75. They differ: noising and tilting do not commute.
    3. Guided PF-ODE (DDIM-type). Variance vc3vu−2=0.015625⋅4=0.0625v_c^3 v_u^{-2} = 0.015625 \cdot 4 = 0.0625; mean 1.001.00 (numerical solve, section 5).
    4. Guided reverse SDE (DDPM-type). Mean 0.8750.875, variance 0.09690.0969 (section 5).

    The conditional model itself (w=1w = 1) gives N(0.5,0.25)\mathcal N(0.5, 0.25). All three guided answers are narrower and shifted to the right, by different amounts.

    (c) The two-class toy of section 2. Classes N((±0.5,0), 0.25 I)\mathcal N((\pm 0.5, 0),\ 0.25\,I) in 2D, w=3w = 3, the exact guided PF-ODE. The first coordinate ends with mean about 1.011.01, variance about 0.1060.106 and P(x1>0)≈1.00P(x_1 > 0) \approx 1.00. For w=1w = 1 it would be mean 0.50.5, variance 0.250.25 and P=Φ(1)=0.841P = \Phi(1) = 0.841. The tilted target has mean 0.720.72 and variance 0.1610.161 (the same as the guided density with s=3s = 3 in the first figure). The second coordinate keeps variance 0.250.25.

    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 g2=2σg^2 = 2\sigma), the mean mm and the variance VV of the guided samples obey simple ODEs in σ\sigma, which SciPy integrates from σmax⁡=104\sigma_{\max} = 10^4 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 −2σ-2\sigma term: noise of variance 2σ ∣dσ∣2\sigma\,|d\sigma| 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 ∅\varnothing 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 w=1w = 1 is the natural default. If you use w>1w > 1, check the spread with CRPS, rank histograms and the spread–skill ratio (lesson 14). In section 4(b), w=3w = 3 cut the variance from 0.250.25 to 0.06250.0625.
    • Inverse problems and data assimilation (lesson 15). Replace the class by an observation: ∇log⁡pt(x∣yobs)=∇log⁡pt(x)+∇log⁡pt(yobs∣x)\nabla \log p_t(x \mid y_{\text{obs}}) = \nabla \log p_t(x) + \nabla \log p_t(y_{\text{obs}} \mid x). 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) w=1w = 1 means no guidance; in Ho and Salimans' convention w′=0w' = 0 does. The diffusers default 7.57.5 is w′=6.5w' = 6.5.
    • A clean classifier for classifier guidance. The classifier must be trained on xtx_t, with tt as an input (Theorem 1, step 3).
    • Wrong factor or sign in the ε\varepsilon form. The classifier gradient enters as −s σt ∇log⁡pϕ-s\,\sigma_t\,\nabla \log p_\phi, because ε\varepsilon points away from the data.
    • "Guided samples come from p(x)1−wp(x∣y)wp(x)^{1-w}p(x \mid y)^w." 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 ε^u\hat\varepsilon_u does not exist. A dropout probability of 0.50.5 wastes capacity.
    • Counting NFE. CFG doubles the cost of each guided step.

    8. Check yourself #

    1. 1D, αˉ=0.36\bar\alpha = 0.36, ε^u=0.2\hat\varepsilon_u = 0.2, ε^c=−0.1\hat\varepsilon_c = -0.1, w=2.5w = 2.5. Compute ε~\tilde\varepsilon, the implicit classifier gradient, and w′w' in Ho and Salimans' convention.
      Answerε^c−ε^u=−0.3\hat\varepsilon_c - \hat\varepsilon_u = -0.3, so ε~=0.2+2.5⋅(−0.3)=−0.55\tilde\varepsilon = 0.2 + 2.5 \cdot (-0.3) = -0.55. σt=0.64=0.8\sigma_t = \sqrt{0.64} = 0.8, so g=0.3/0.8=0.375g = 0.3/0.8 = 0.375. Check with Theorem 2: −0.1−1.5⋅0.8⋅0.375=−0.1−0.45=−0.55-0.1 - 1.5 \cdot 0.8 \cdot 0.375 = -0.1 - 0.45 = -0.55 ✓. w′=1.5w' = 1.5.
    2. Why must the classifier in classifier guidance see noisy inputs?
      AnswerThe sampler needs ∇log⁡pt(y∣xt)\nabla \log p_t(y \mid x_t), and pt(y∣xt)=∫p(y∣x0) p(x0∣xt) dx0p_t(y \mid x_t) = \int p(y \mid x_0)\,p(x_0 \mid x_t)\,dx_0 averages the clean classifier over the denoising posterior. A clean classifier evaluated at xtx_t is a different function; on noisy inputs it is out of distribution and its gradients are not meaningful.
    3. Show that CFG with weight ww equals classifier guidance with scale ww on the unconditional model.
      Answer(1−w)∇log⁡pt(x)+w∇log⁡pt(x∣y)=∇log⁡pt(x)+w(∇log⁡pt(x∣y)−∇log⁡pt(x))=∇log⁡pt(x)+w ∇log⁡pt(y∣x)(1-w)\nabla \log p_t(x) + w\nabla \log p_t(x \mid y) = \nabla \log p_t(x) + w\big(\nabla \log p_t(x \mid y) - \nabla \log p_t(x)\big) = \nabla \log p_t(x) + w\,\nabla \log p_t(y \mid x) by Theorem 1.
    4. In Proposition 3's model with vc=0.25v_c = 0.25, vu=0.5v_u = 0.5 and w=3w = 3: what is the mean of the guided field's density πσ\pi_\sigma as σ→∞\sigma \to \infty, if mc=0.5m_c = 0.5?
      AnswerThe mean of πσ\pi_\sigma is w mc/(vc+σ2)λ(σ)\frac{w\,m_c/(v_c + \sigma^2)}{\lambda(\sigma)}. For large σ\sigma, λ(σ)≈(1−w+w)/σ2=1/σ2\lambda(\sigma) \approx (1 - w + w)/\sigma^2 = 1/\sigma^2 and w mc/(vc+σ2)≈w mc/σ2w\,m_c/(v_c + \sigma^2) \approx w\,m_c/\sigma^2, so the mean tends to w mc=1.5w\,m_c = 1.5: three times the conditional mean.
    5. Why does limited-interval guidance skip the highest noise levels?
      AnswerAt high noise the guided density is centred at an extrapolated point (w mcw\,m_c 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.
    6. What does autoguidance use instead of the unconditional model, and why does that keep diversity?
      AnswerA weaker version (smaller or shorter-trained) of the same conditional model: ε~=ε^bad+w(ε^good−ε^bad)\tilde\varepsilon = \hat\varepsilon_{\text{bad}} + w(\hat\varepsilon_{\text{good}} - \hat\varepsilon_{\text{bad}}). 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.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write the conditional score in terms of the unconditional score and a classifier.

    2. What is the noisy classifier pt(y∣xt)p_t(y \mid x_t) in terms of the clean classifier?

    3. Why must a guidance classifier be trained on noisy inputs?

    4. Give the classifier-guided noise prediction with scale ss.

    5. Give the CFG formula (convention with w=1w = 1 = no guidance).

    6. Convert Ho and Salimans' weight w′w' to the weight ww of ε^u+w(ε^c−ε^u)\hat\varepsilon_u + w(\hat\varepsilon_c - \hat\varepsilon_u).

    7. How is a CFG model trained?

    8. Why does CFG trade diversity for fidelity?

    9. Do CFG samples follow p(x)1−wp(x∣y)wp(x)^{1-w}p(x \mid y)^w?

    10. What is limited-interval guidance?

    Open the review →

    9. Interview angle #

    • "Explain classifier-free guidance." — Drop the condition in 10–20% of training examples. At sampling use ε^u+w(ε^c−ε^u)\hat\varepsilon_u + w(\hat\varepsilon_c - \hat\varepsilon_u), 2 NFE per step. It is classifier guidance with the implicit classifier pt(x∣y)/pt(x)p_t(x \mid y)/p_t(x).
    • "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 ww grows?" — Precision rises and recall falls; FID measures both, so it is best at a moderate ww.
    • "Do guided samples follow p(x)1−wp(x∣y)wp(x)^{1-w}p(x \mid y)^w?" — 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?" — w=1w = 1, or a small ww 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.

    1. Compute the noisy-classifier slope as a function of αˉ\bar\alpha and check the four numbers 4.0,1.13,0.34,0.104.0, 1.13, 0.34, 0.10.
    2. Build the exact noisy classifier pt(y∣x)p_t(y \mid x) of the two-class 8 Gaussians and check that its log-gradient equals the difference of the conditional and the unconditional scores.
    3. Write the CFG denoiser, sample with the guided PF-ODE, and sweep ww: measure class accuracy, mean radius and spread.
    4. Compute the tilted target p(x) p(y∣x)wp(x)\,p(y \mid x)^{w} on a grid for the 1D two-class toy with w=3w = 3 and show that the CFG samples have a different mean and variance.
    5. Add a guidance interval to the sampler and compare the effective number of class modes with guidance at every level.

    11. Watch and read #

    Derives guidance from Bayes' rule for scores and shows how CFG is trained with a null condition; compare its convention for the weight with the one used here.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The chapter "Guidance techniques" explains classifier guidance, CFG and why guidance works so well in practice.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The chapter "Guidance and conditioning" connects guidance to temperature and to the fidelity–diversity trade-off.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play