Apply classifier-free guidance with guidance rescale

Why it matters Guidance rescale is a common option in text-to-image pipelines to fix washed-out or over-saturated images at high guidance.

High classifier-free guidance scales make images over-saturated because the guided prediction's spread grows. Guidance rescale shrinks each sample's guided prediction back to the spread of the conditional one, then blends.

Write cfg_rescale(eps_uncond, eps_cond, w, phi). Inputs have shape (B, ...). Per sample b:
- cfg = u + w * (c - u)
- s_c = std of c[b] over all its elements, s_cfg = std of cfg[b] (population std)
- rescaled = cfg[b] * s_c / s_cfg
- out[b] = phi * rescaled + (1 - phi) * cfg[b]
Return an array of the input shape.

Signaturedef cfg_rescale(eps_uncond, eps_cond, w, phi)

Example

cfg_rescale([[0.0, 0.0]], [[1.0, -1.0]], 3.0, 0.5) gives array([[2., -2.]]).

Understand the idea

Classifier-free guidance pushes the model's prediction further in the direction of the prompt: cfg = u + w (c - u). With a large w the prediction's values spread out much more than anything the model saw in training, which shows up as burnt, over-saturated images. Guidance rescale keeps the direction of the guided prediction but shrinks its spread back to that of the conditional prediction, then mixes the two versions.

Example: u = [0, 0], c = [1, -1], w = 3. The guided prediction is [3, -3] with std 3, while c has std 1. Rescaled it becomes [1, -1]. With phi 0.5 the output is halfway: [2, -2].

Rules: cfg = u + w (c - u); rescaled = cfg * std(c) / std(cfg) per sample; out = phi * rescaled + (1 - phi) * cfg.

Values of phi around 0.7 are a common setting with high guidance scales.

Shapes and data flow

eps: (B, C, H, W) -> stds: (B, 1, 1, 1) -> out: (B, C, H, W)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecfg_rescale([[0.0, 0.0]], [[1.0, -1.0]], 3.0, 0.5)
  • Sample 2: batchcfg_rescale([[0.0, 0.0], [1.0, 1.0]], [[1.0, -1.0], [2.0, 3.0]], 2.0, 1.0)