AI Wiki中文/EN

Classifier-free guidance: stronger conditions change the distribution

无分类器引导

Compare scale conventions, null-condition training and a normalized fixed-time guidance experiment.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A stronger instruction can move the distribution

Imagine two overlapping clouds of measurements, labelled positive and negative. A conditional generator should reproduce the positive cloud, including the points near the overlap. If we instead reward points that are especially easy to classify as positive, we move probability away from that overlap. The output can become more distinctive while representing the original conditional distribution less faithfully.

Classifier-free guidance (CFG) makes such a trade-off using conditional and unconditional predictions from a generative model. Ho and Salimans presented a short version at a NeurIPS 2021 workshop; the paper used here was posted in July 2022. “Classifier-free” means that sampling does not require a separately trained classifier. It does not mean that training needs no conditioning information. Read DDPM and score matching first.

A fixed-time density calculation shows how guidance moves and narrows probability mass.
A fixed-time density calculation shows how guidance moves and narrows probability mass.

Train both branches, then combine their predictions

For a noise level with xt=αt x0+σt ε, a mean-squared-error noise predictor estimates a conditional expectation. The corresponding ideal score is a spatial derivative:

xt=αtx0+σtϵ,ϵ∼N(0,I),s∗(xt,t,c)=−E[ϵ∣xt,t,c]σt.x_t=\alpha_t x_0+\sigma_t\epsilon,\qquad \epsilon\sim\mathcal N(0,I),\qquad s^*(x_t,t,c)=-\frac{\mathbb E[\epsilon\mid x_t,t,c]}{\sigma_t}.

Use a special null condition ∅ to train the unconditional branch. With probability pdrop, replace the condition by ∅, but retain the original clean example and noise target. The objective is:

L=Ex0,c,t,ϵ,c~∥ϵθ(αtx0+σtϵ,t,c~)−ϵ∥2,c~={∅with probability pdrop,cotherwise.L=\mathbb E_{x_0,c,t,\epsilon,\widetilde c}\|\epsilon_\theta(\alpha_t x_0+\sigma_t\epsilon,t,\widetilde c)-\epsilon\|^2,\qquad \widetilde c=\begin{cases}\varnothing&\text{with probability }p_{\rm drop},\\c&\text{otherwise.}\end{cases}

The null condition is a learned representation, not an instruction to replace the noisy input by zeros. The paper’s Algorithm 1 shares network parameters between these branches. At inference, obtain both predictions at the same state and time:

ϵ^=ϵu+s(ϵc−ϵu).\widehat\epsilon=\epsilon_u+s(\epsilon_c-\epsilon_u).

Here s=0 gives the unconditional branch, s=1 the ordinary conditional branch, and s>1 extrapolates beyond it. The paper uses a different parameter w:

ϵ^=(1+w)ϵc−wϵu,s=1+w.\widehat\epsilon=(1+w)\epsilon_c-w\epsilon_u,\qquad s=1+w.

Thus “zero guidance” is ambiguous without the convention. The fixed LDM sampler uses s: its value 1 bypasses the unconditional evaluation. Otherwise it concatenates the two conditions along the batch dimension and splits the predictions. Batching can reduce overhead, but it does not turn two branches into the arithmetic cost of one branch.

What the idealized density interpretation does—and does not—say

For exact scores at a fixed time, the same linear combination is the gradient of a log-density tilt. Bayes’ rule gives two equivalent expressions, up to normalization:

qs(x∣c)∝p(x∣c)sp(x)1−s∝p(x)p(c∣x)s,∇xlog⁡qs=s∇xlog⁡p(x∣c)+(1−s)∇xlog⁡p(x).q_s(x\mid c)\propto p(x\mid c)^s p(x)^{1-s}\propto p(x)p(c\mid x)^s,\qquad \nabla_x\log q_s=s\nabla_x\log p(x\mid c)+(1-s)\nabla_x\log p(x).

This explains the preference for highly classifiable points. It is a fixed-time identity under exact, compatible densities. Approximate neural vector fields need not be gradients of any scalar density, a limitation explicitly discussed in Section 3.2. Nor does defining a normalized tilt at every time prove that those tilts form the marginal path of a chosen guided reverse sampler. Do not turn this local interpretation into an exact final-sample guarantee.

For our original example, the clean classes are equally likely Gaussians with means ±1 and variance .25. At retained signal power A=.5, each noisy component has mean ±m and variance v:

m=A,v=A(0.25)+1−A,sc(x)=−x−mv,su(x)=−x−mtanh⁡(mx/v)v.m=\sqrt A,\qquad v=A(0.25)+1-A,\qquad s_c(x)=-\frac{x-m}{v},\qquad s_u(x)=-\frac{x-m\tanh(mx/v)}{v}.

The mixture formula follows by averaging the two component scores using their posterior responsibilities. At x=0 those responsibilities are equal, so the unconditional score is zero while the positive-class score is m/v. Their difference is also the gradient of the implicit log classifier probability.

Measure a fixed-time guidance trade-off

Save as classifier_free_guidance.py with Python 3.12 and NumPy 1.26.4. It implements stable mixture log densities, exact scores, prediction blending and numerical normalization of the tilted density. It does not train a network or simulate a full image sampler. The quadrature integrates over [−10,10]; increasing both order and range independently checks that the reported smooth moments are stable. The negative-half-space mass is a quadrature estimate with an indicator discontinuity, so it is reported approximately.

For Q quadrature nodes and K guidance scales the calculation costs O(KQ), excluding node construction, with O(Q) working arrays. In a neural sampler the substantial cost is the two denoiser branches per guided step, plus solver and batching overhead. Our scalar operation count does not predict image latency.

"""Original fixed-noise-level CFG geometry; analytic scores, no image network."""
import json
import numpy as np

A,DATA_VAR=.5,.25

def parameters(scale):
    if not np.isfinite(scale) or not 0<=scale<=12:raise ValueError('Guidance scale in[0,12] required.')
    return np.sqrt(A),A*DATA_VAR+1-A

def log_densities(x):
    x=np.asarray(x,float)
    if not np.all(np.isfinite(x)) or np.max(abs(x))>100:raise ValueError('Finite coordinates of magnitude<=100 required.')
    mean,var=parameters(1)
    positive=-.5*(x-mean)**2/var-.5*np.log(2*np.pi*var)
    negative=-.5*(x+mean)**2/var-.5*np.log(2*np.pi*var)
    return positive,np.logaddexp(positive,negative)-np.log(2)

def scores(x,scale=1.):
    mean,var=parameters(scale);x=np.asarray(x,float);log_densities(x)
    conditional=-(x-mean)/var
    unconditional=-(x-mean*np.tanh(mean*x/var))/var
    return unconditional+scale*(conditional-unconditional)

def potential(x,scale):
    parameters(scale);conditional,unconditional=log_densities(x)
    return scale*conditional+(1-scale)*unconditional

def moments(scale,order=256,limit=10.):
    parameters(scale)
    if type(order) is not int or not 32<=order<=1024 or not 6<=limit<=20:raise ValueError('Bounded quadrature required.')
    z,w=np.polynomial.legendre.leggauss(order);x=limit*z;w=limit*w
    lp=potential(x,scale);peak=lp.max();mass=w*np.exp(lp-peak);total=mass.sum();prob=mass/total
    mean=float(prob@x);var=float(prob@((x-mean)**2))
    return dict(mean=mean,variance=var,log_normalizer=float(np.log(total)+peak),mass_negative=float(prob[x<0].sum()))

def blend_noise(unconditional,conditional,scale):
    parameters(scale);u=np.asarray(unconditional,float);c=np.asarray(conditional,float)
    if u.shape!=c.shape or not np.all(np.isfinite(u)) or not np.all(np.isfinite(c)):raise ValueError('Matching finite predictions required.')
    return u+scale*(c-u)

def demo():
    result={str(s):moments(s) for s in [0,1,3,7]}
    x=np.array([-1.,0.,1.]);result['scores_at_minus1_0_1']={str(s):scores(x,s).tolist() for s in [0,1,3]}
    result['scope']='Normalized fixed-time density tilt, not a proof of a full guided sampler marginal or an image-quality benchmark.'
    return result

if __name__=='__main__':print(json.dumps(demo(),indent=2))

At s=0 the noisy mixture has mean zero and variance 1.125. At s=1 the positive conditional has mean .70710678 and variance .625. At s=3 the normalized tilt has mean 1.08905646 and variance .40241271; at s=7 these become 1.35095320 and .30995297. The fraction below zero falls from about .1853 at s=1 to .00147 at s=7.

The conditional cloud has not merely been sampled more accurately: it has been altered. The checks independently differentiate the log potential, verify the Bayes score identity, recover the two known Gaussian/mixture moments, and compare quadrature resolution and tails. The numbers establish this synthetic fixed-time effect, not improvements in human preference, text alignment or image diversity.

Guidance amplifies model differences too

Large s magnifies errors in the conditional-minus-unconditional prediction. It can change coverage, shift means and create undesirable artifacts in image models; the specific threshold depends on model, conditioning, scheduler and parameterization. This article does not prescribe a universal scale. A formula designed for noise predictions must be converted consistently if a model predicts velocity or clean data instead.

Null conditions must match training. A negative prompt supplies another condition and is not generally the same distribution as an unconditional branch. A conditional model trained without any null examples does not automatically provide a calibrated unconditional prediction. The original two-branch method, its fixed-time idealization and later implementation variants should remain distinguishable.

Which distribution are you asking for?

  1. Convention. The paper sets w=2. What s should the displayed implementation use? Answer: s=3. Both yield 3εc−2εu; confusing the conventions changes the sampling rule.
  2. Hand calculation. If εu=.2 and εc=.8, what is the prediction at s=3? Answer: .2+3(.8−.2)=2. It lies beyond both predictions because this is extrapolation, not a convex average.
  3. Counterexample. Does increasing s necessarily recover the true positive-class distribution better? Answer: No. At s=1 its mean is .7071; at s=7 the example’s tilted mean is 1.351. Stronger class preference changes the target itself.
  4. Implementation. Is dropping the condition equivalent to dropping the training example or setting xt to zero? Answer: Neither. Keep the same noisy input and noise target; replace only the conditioning representation with the trained null condition.

Read the scale convention before comparing results

Read Algorithms 1–2 and Section 3.2, then compare the fixed LDM prediction blend. The former establishes the method and its approximate-score qualification; the latter makes the s-versus-w convention concrete. We read selected method sections, not a complete experimental reproduction. The LDM source is a later implementation reference, not evidence that it introduced CFG.

Make a prediction, then check

Which scale gives ordinary conditioning in uncond+s(cond-uncond)?

Choose one answer

Learning objectives

  • Derive the conditional/unconditional blend.
  • Translate s and w conventions.
  • Check the exact-score density interpretation.
  • Measure guidance-induced changes in moments.

Prerequisites & connections

Explore related knowledge →

References

  1. Classifier-Free Diffusion Guidance (v1)
    Jonathan Ho; Tim Salimans · 2022
  2. ldm-cfg method reference at a506df5
    CompVis/latent-diffusion contributors · 2022

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked CFG selected section3 and algorithms1/2, plus fixed CompVis DDIM guidance code. Six paired equations and four explained exercises; original exact two-Gaussian fixed-time density tilt, Bayes score identity, normalized moments, quadrature and scale convention. Not a learned null-condition network or proof of complete guided sampler marginals.

  • Single AI author checked CFG selected section3 and algorithms1/2, plus fixed CompVis DDIM guidance code. Six paired equations and four explained exercises; original exact two-Gaussian fixed-time density tilt, Bayes score identity, normalized moments, quadrature and scale convention. Not a learned null-condition network or proof of complete guided sampler marginals.
  • Four computed SVG variants per topic. Eleven numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Mobile-title and cost-axis corrections preserved. Full article acceptance recorded separately.

Source locations checked:

  • Classifier-Free Diffusion Guidance (v1) · Read selected Section3, algorithms1-2 and score-field caveat; PDF page5 viewed. July2022 preprint acknowledges2021 workshop short version. No image reproduction.
  • ldm-cfg method reference at a506df5 · Read 165-177: same-state condition batching and uncond+s(cond-uncond). MIT license read. Fixed public commit; reference only, no copied/executed code.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.