v9.1.1
Menu

Classifier Gradient Guidance Step

mediumPROGuidance and Latent DiffusionDiffusion ModelsDiffusion Models 1

Problem Statement

Before classifier-free guidance, Dhariwal & Nichol used an external classifier's gradient to nudge the noise prediction. Implement that guided-noise update.

Background

Classifier guidance shifts the predicted noise by the gradient of the classifier's log-probability of the target class, scaled by the noise level and a strength s:

ε^=ε−s 1−αˉt  ∇xtlog⁡pϕ(y∣xt)\hat{\varepsilon} = \varepsilon - s\,\sqrt{1 - \bar{\alpha}_t}\; \nabla_{x_t} \log p_\phi(y \mid x_t)

The sqrt(1 - alpha_bar_t) factor converts a score shift into a noise shift. The gradient is supplied.

Your Task

Implement:

def classifier_guidance(eps, grad_log_p, alpha_bar_t, s):

Return the guided noise as a list rounded to 4 decimals.

Input Format

  • eps, grad_log_p: lists of equal length D.
  • alpha_bar_t (float) in (0, 1), s (float): guidance strength.

Output Format

  • A list of D floats rounded to 4 decimals.

Sample

print(classifier_guidance([0.0, 0.0], [1.0, -1.0], 0.75, 2.0))

Output:

[-1.0, 1.0]

Example

Input
print(classifier_guidance([0.0, 0.0], [1.0, -1.0], 0.75, 2.0))
Output
[-1.0, 1.0]
Reasoning
  • Calculate the noise scaling factor derived from the time step, which converts the score shift into a noise shift: \sqrt{1 - \alpha_{\text{bar}}_t} = \sqrt{1 - 0.75} = \sqrt{0.25} = 0.5.
  • Determine the effective guidance magnitude by multiplying the strength ss by the scaling factor: 2.0×0.5=1.02.0 \times 0.5 = 1.0.
  • Compute the guided noise for the first dimension by subtracting the scaled gradient from the predicted noise: 0.0−(1.0×1.0)=−1.00.0 - (1.0 \times 1.0) = -1.0.
  • Compute the guided noise for the second dimension by subtracting the scaled gradient from the predicted noise: 0.0−(1.0×−1.0)=1.00.0 - (1.0 \times -1.0) = 1.0.
  • The final output is [-1.0, 1.0]

Constraints

  • len(eps) == len(grad_log_p), 0 < alpha_bar_t < 1.
  • eps_guided = eps - s*sqrt(1-alpha_bar_t)*grad.
  • Round to 4 decimals; avoid -0.0.

Learn this in

More from Diffusion Models 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.