Skip to content

← Generative Models step 8 of 11

Medium Primitives

Classifier-Free Guidance

Classifier-free guidance combines two noise predictions for the same noisy sample at the same diffusion timestep. One prediction uses conditioning, such as a text prompt; the other does not. The difference between them provides a direction for adjusting the prediction without a separate classifier.

Implement cfg_combine(eps_uncond, eps_cond, guidance_scale). The predictions are already supplied: this function only combines them. It does not run a model, draw random noise or perform a denoising step.

Inputs and output

  • eps_uncond: unconditional noise predictions, shape (N, d).
  • eps_cond: conditional noise predictions, also shape (N, d).
  • guidance_scale: a finite, nonnegative Python float, shared by all elements.

The two tensors have the same floating-point dtype and device. Return a tensor with the same shape, dtype and device, leaving both inputs unchanged.

Combination rule

eps_guided = eps_uncond + guidance_scale * (eps_cond - eps_uncond)

Apply this elementwise. Do not average across the batch or feature axis, normalize the difference, or clamp the result.

Scale Result
0 The unconditional prediction
Between 0 and 1 A point between the two predictions
1 The conditional prediction
Greater than 1 A point beyond the conditional prediction in the same direction

For eps_uncond=[[1, 4]] and eps_cond=[[3, 2]], the difference is [[2, -2]]. A scale of 0.5 gives [[2, 3]], while a scale of 2 gives [[5, 0]]. Notice that guidance can decrease an element as well as increase it. If the predictions are equal, the difference is zero and the result does not change with the scale.

A larger scale amplifies the conditioning difference. It is not a guarantee of better generated samples; guidance involves a quality-diversity tradeoff. There is no model-specific default scale in this exercise.

See Ho and Salimans, Classifier-Free Diffusion Guidance.