Combine conditional and unconditional noise with classifier-free guidance
Text-to-image diffusion models usually run the denoiser twice per step, once with the prompt and once with an empty prompt, then extrapolate away from the unconditional prediction. The guidance scale w trades prompt adherence for diversity.
To save a call, the two passes are batched: the model output eps_batched has shape (2B, ...), where the FIRST B rows are unconditional and the LAST B rows are conditional.
Write cfg_combine(eps_batched, w) returning eps_uncond + w * (eps_cond - eps_uncond), shape (B, ...), as a NumPy float array.
w = 0 returns the unconditional prediction and w = 1 the conditional one.
def cfg_combine(eps_batched, w)Example
eps_batched = [[0.0], [1.0]], w = 3 gives [[3.0]].
Understand the idea
A text-to-image diffusion model predicts noise twice per step: once with the prompt and once with an empty prompt. Classifier-free guidance starts from the unconditional guess and moves further in the direction the prompt pushes, scaled by w. A bigger w follows the prompt more closely but gives less variety. Here both passes are run in one batch: the first B rows are unconditional, the last B rows are conditional. Worked example: B = 1, eps_batched = [[0.2], [0.5]], w = 2. eps_uncond = 0.2, eps_cond = 0.5. Guided = 0.2 + 2 * (0.5 - 0.2) = 0.2 + 0.6 = 0.8. With w = 0 you get 0.2, and with w = 1 you get 0.5. Rule: split the batch in half along the first axis, uncond = first half, cond = second half, return uncond + w * (cond - uncond) as a float array of shape (B, ...). Swapping the halves guides away from the prompt. Used at every sampling step of Stable Diffusion style image and video generators, often with w around 5 to 8.