Classifier Gradient Guidance Step
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:
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
print(classifier_guidance([0.0, 0.0], [1.0, -1.0], 0.75, 2.0))
[-1.0, 1.0]
- 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 by the scaling factor: .
- Compute the guided noise for the first dimension by subtracting the scaled gradient from the predicted noise: .
- Compute the guided noise for the second dimension by subtracting the scaled gradient from the predicted noise: .
- 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.