4.5.14Generative Models

Classifier-free guidance

2,730 words12 min readdifficulty · medium4 backlinks

What Problem Does It Solve?

Conditional diffusion models (like text-to-image systems) often produce samples that are high-quality but don't strongly follow the conditioning signal (text, class label, etc.). Early approaches used a separate classifier gradient to steer generation, but this required training an extra noise-robust classifier.

Classifier-free guidance eliminates the classifier entirely by training a single model to handle both conditional and unconditional generation, then combining their predictions at sampling time.


The Mathematical Framework

Derivation from First Principles

STEP 1: What are we trying to achieve?

We want to sample from p(xc)p(\mathbf{x} | \mathbf{c}) but make it more strongly reflect the conditioning c\mathbf{c}. In classifier guidance, we modified the score with xtlogp(cxt)\nabla_{\mathbf{x}_t} \log p(\mathbf{c} | \mathbf{x}_t). Here we'll derive an equivalent effect without a classifier.

STEP 2: Rewrite the conditional score

By Bayes' rule: logp(xtc)=logp(xt)+logp(cxt)logp(c)\log p(\mathbf{x}_t | \mathbf{c}) = \log p(\mathbf{x}_t) + \log p(\mathbf{c} | \mathbf{x}_t) - \log p(\mathbf{c})

Taking gradients: xtlogp(xtc)=xtlogp(xt)+xtlogp(cxt)\nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t | \mathbf{c}) = \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t) + \nabla_{\mathbf{x}_t} \log p(\mathbf{c} | \mathbf{x}_t)

WHY this step? The last term logp(c)\log p(\mathbf{c}) doesn't depend on xt\mathbf{x}_t, so it vanishes under the gradient. This splits the conditional score into unconditional score + classifier gradient.

STEP 3: Amplify the conditioning signal

To make the sample follow c\mathbf{c} more strongly, we scale up the classifier term by a factor ww: xtlogp~(xtc)=xtlogp(xt)+wxtlogp(cxt)\nabla_{\mathbf{x}_t} \log \tilde{p}(\mathbf{x}_t | \mathbf{c}) = \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t) + w \cdot \nabla_{\mathbf{x}_t} \log p(\mathbf{c} | \mathbf{x}_t)

WHY? When w=1w = 1, we get the true conditional. When w>1w > 1, we "overshoot" toward the conditioning, making outputs more specific to c\mathbf{c} at the cost of diversity.

STEP 4: Express in terms of the model's predictions

Rearrange the Bayes gradient: xtlogp(cxt)=xtlogp(xtc)xtlogp(xt)\nabla_{\mathbf{x}_t} \log p(\mathbf{c} | \mathbf{x}_t) = \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t | \mathbf{c}) - \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t)

Substitute into the guided score: xtlogp~(xtc)=xtlogp(xt)+w[xtlogp(xtc)xtlogp(xt)]\nabla_{\mathbf{x}_t} \log \tilde{p}(\mathbf{x}_t | \mathbf{c}) = \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t) + w \cdot [\nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t | \mathbf{c}) - \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t)]

=(1w)xtlogp(xt)+wxtlogp(xtc)= (1 - w) \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t) + w \, \nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t | \mathbf{c})

STEP 5: Convert to noise prediction

In diffusion models, the score relates to predicted noise: xtlogp(xt)ϵθ(xt,t)\nabla_{\mathbf{x}_t} \log p(\mathbf{x}_t) \propto -\epsilon_\theta(\mathbf{x}_t, t). So:

ϵ~θ=(1w)ϵθ(xt,t,)+wϵθ(xt,t,c)\boxed{\tilde{\epsilon}_\theta = (1 - w) \epsilon_\theta(\mathbf{x}_t, t, \emptyset) + w \, \epsilon_\theta(\mathbf{x}_t, t, \mathbf{c})}

WHY this form? It's a linear interpolation and extrapolation. When w=0w = 0, purely unconditional. When w=1w = 1, normal conditional. When w>1w > 1, we extrapolate beyond the conditional toward "more c\mathbf{c}."


Figure — Classifier-free guidance

Training Procedure

To enable classifier-free guidance, we train a single model that handles both conditional and unconditional denoising:

  1. During training, randomly drop the conditioning c\mathbf{c} with probability puncondp_{\text{uncond}} (typically 10-20%).

    • When dropped, replace c\mathbf{c} with a null token \emptyset (empty string for text, zero embedding, etc.).
  2. Loss remains the same: L=Et,x0,ϵ,c[ϵϵθ(xt,t,c)2]\mathcal{L} = \mathbb{E}_{t, \mathbf{x}_0, \epsilon, \mathbf{c}} \left[ \| \epsilon - \epsilon_\theta(\mathbf{x}_t, t, \mathbf{c}) \|^2 \right] where c\mathbf{c} is sometimes \emptyset.

WHY this works: The model learns to denoise both with and without conditioning in the same parameters. At inference, we can call it twice (once with c\mathbf{c}, once with \emptyset) to get both predictions.


Worked Examples




Common Mistakes




Connections to Other Concepts

  • Score-based diffusion models: CFG manipulates the score function by combining conditional and unconditional scores.
  • Classifier guidance: The predecessor approach that used a separate classifier p(cxt)p(\mathbf{c} | \mathbf{x}_t); CFG derives the same effect without classifier.
  • DDPM sampling: CFG modifies the noise prediction ϵθ\epsilon_\theta used in the DDPM reverse process.
  • Conditional generation: CFG is a technique to strengthen conditioning signals in conditional generative models.
  • Prompt engineering: Higher guidance scales make prompt wording more critical (overfitting to text).
  • Negative prompting: Often combined with CFG to push away from unwanted features.

Recall Explain It Like I'm 12

Imagine you're drawing a picture and someone gives you a hint: "draw a dragon." You can choose to follow that hint a little or a lot.

Classifier-free guidance is like having two artists in your brain:

  1. One artist draws what they'd normally draw (no hint).
  2. Another artist draws specifically following the "dragon" hint.

You look at both drawings, see the difference between them (that's the "dragon-ness"), and then you push your final drawing even MORE in that dragon direction. It's like someone saying "make it MORE dragon!" So you exaggerate the dragon features—bigger wings, fiercer claws—to make sure your picture really screams "DRAGON!"

The "guidance scale" (ww) is how much you exaggerate. A little bit (w=2w = 2) gives you a normal dragon. A lot (w=10w = 10) gives you a SUPER obvious dragon, but maybe it looks a bit cartoonish because you pushed too hard.



When to Use CFG

Use classifier-free guidance when:

  • You want strong adherence to text/class conditioning without training a separate classifier
  • You're building text-to-image, text-to-video, or class-conditional models
  • You need a tunable knob for prompt strength

Avoid or tune down when:

  • You want maximum sample diversity (high ww causes mode collapse)
  • Compute cost is critical (requires 2× model evaluations per step)
  • You're generating unconditional samples (just use w=0w = 0 or skip CFG)

#flashcards/ai-ml

What is the core idea behind classifier-free guidance?
It amplifies conditioning by running the model twice—once with conditioning and once without—then extrapolating beyond the conditional prediction by scaling up the difference between them.
What is the CFG formula for guided noise prediction?
ϵ~θ=ϵθ(xt,t,)+w[ϵθ(xt,t,c)ϵθ(xt,t,)]\tilde{\epsilon}_\theta = \epsilon_\theta(\mathbf{x}_t, t, \emptyset) + w \cdot [\epsilon_\theta(\mathbf{x}_t, t, \mathbf{c}) - \epsilon_\theta(\mathbf{x}_t, t, \emptyset)] or equivalently ϵ~θ=(1w)ϵuncond+wϵcond\tilde{\epsilon}_\theta = (1-w)\epsilon_\text{uncond} + w\epsilon_\text{cond}
What does the guidance scale ww control?
ww controls how strongly the sample follows the conditioning. w=1w=1 is normal conditional generation, w>1w>1 amplifies prompt adherence, w=0w=0 ignores conditioning entirely.
How do you train a model to enable classifier-free guidance?
During training, randomly drop the conditioning input with probability puncond0.1p_{\text{uncond}} \approx 0.10.20.2, replacing it with a null token, so the model learns both conditional and unconditional distributions.
What is the "conditioning direction" in CFG?
Δϵ=ϵθ(xt,t,c)ϵθ(xt,t,)\Delta\epsilon = \epsilon_\theta(\mathbf{x}_t, t, \mathbf{c}) - \epsilon_\theta(\mathbf{x}_t, t, \emptyset), the difference between conditional and unconditional predictions, representing the influence of the conditioning signal.
Why does CFG require two model evaluations per sampling step?
Because you need separate predictions—ϵθ(xt,t,c)\epsilon_\theta(\mathbf{x}_t, t, \mathbf{c}) and ϵθ(xt,t,)\epsilon_\theta(\mathbf{x}_t, t, \emptyset)—to compute their difference and scale it by ww.
What happens if you use w<1w < 1 in CFG?
You interpolate toward the unconditional distribution, reducing the effect of conditioning below the trained level, which is usually not desired.
What is the tradeoff of using high guidance scales (w1w \gg 1)?
High ww improves prompt fidelity and specificity but reduces sample diversity, can cause over-saturation or artifacts, and concentrates probability mass (mode collapse tendency).
How does CFG relate to classifier guidance?
CFG achieves the same effect as classifier guidance (amplifying logp(cxt)\nabla \log p(\mathbf{c}|\mathbf{x}_t)) but without needing a separate noise-robust classifier, by leveraging the model's own conditional/unconditional predictions.
What is the typical range for ww in Stable Diffusion text-to-image models?
w[7,10]w \in [7, 10] for strong prompt adherence with good quality; lower values like w=1.5w=1.533 for subtle guidance.

Concept Map

weak conditioning

requires

solved by

eliminated by

trains single model for

derives

amplify direction

combine at sampling

scales

amplifies

Conditional Diffusion

Problem: samples ignore prompt

Classifier Guidance

Extra noise-robust classifier

Classifier-free Guidance

Conditional + Unconditional

Bayes rule split

Score = uncond + classifier grad

Guided prediction eps-tilde

Guidance scale w

Prompt-following samples

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalो, ise ek simple tarike se samajhte hain. Jab hum text-to-image model se bolते hain "golden retriever dikhao", toh model ki taraf se aane wala output kai baar strong nahi hota — thoda dog-ish blob type ho jaata hai jo prompt ko theek se follow nahi karta. Classifier-free guidance ka core idea yeh hai ki hum do parallel predictions banaate hain: ek jo tumhare prompt ko jaanti hai (conditional), aur ek jo prompt ko ignore karti hai (unconditional). In dono ka difference nikaal ke humein woh "direction" milti hai jo sirf tumhara text prompt add kar raha hai — matlab "golden retriever-ness" ki direction. Fir hum us direction ko guidance scale ww se multiply karke amplify kar dete hain, jaise ek "prompt volume knob" ko upar ghumana.

Ab yeh kyun kaam karta hai, iske peeche Bayes rule ki simple math hai. Conditional score ko hum unconditional score plus classifier gradient mein tod sakte hain. Purane methods mein log ek alag classifier train karte the jo isi direction ko provide karta tha, lekin woh extra kaam aur noise-robust classifier maangta tha. Classifier-free guidance mein hum ek hi model ko dono kaam — conditional aur unconditional — sikha dete hain, aur sampling ke time inke predictions ko combine kar lete hain. Formula seedha yeh ban jaata hai: ϵ~=(1w)ϵ+wϵc\tilde{\epsilon} = (1-w)\epsilon_\emptyset + w\,\epsilon_c. Jab w=1w=1 ho toh normal conditional milta hai, aur w>1w>1 pe hum thoda "overshoot" karte hain jisse output prompt ko aur strongly follow karta hai.

Yeh matter isliye karta hai kyunki aaj ke saare bade text-to-image systems — Stable Diffusion, DALL-E jaise — isi trick pe chalte hain. Iske bina generated images sundar toh hoti hain par tumhare prompt ko theek se match nahi karti. Bas dhyaan rakhna: ww zyada badha doge toh prompt-following strong ho jaayega lekin diversity kam ho jaayegi (outputs ek jaise dikhne lagenge). Toh yeh ek trade-off hai — quality aur prompt-matching versus variety ke beech ka balance, jise hum ek single knob se control kar sakte hain, bina koi extra classifier train kiye.

Go deeper — visual, from zero

Test yourself — Generative Models

Connections