Clip predicted clean images with dynamic thresholding
Why it matters Text-to-image samplers use dynamic thresholding to allow high guidance weights without saturated colours.
With strong guidance, a diffusion model's predicted clean image x0 can drift far outside the valid pixel range [-1, 1]. Dynamic thresholding picks a per-sample clip level from a percentile of absolute values.
Write dynamic_threshold(x0, p). x0 has shape (B, ...). For each sample: s = np.percentile(|x0[b]|, p) over all its elements, then s = max(s, 1.0). Clip x0[b] to [-s, s] and divide by s. Return an array of the input shape.
def dynamic_threshold(x0, p)Example
dynamic_threshold([[0.5, -2.0, 4.0, 1.0]], 75) gives array([[0.2, -0.8, 1., 0.4]]).
Understand the idea
During sampling, a diffusion model often predicts what the clean image x_0 looks like. Pixels are supposed to be in [-1, 1], but at high guidance the prediction can go far outside, and simply clipping at 1 flattens big regions into pure white or black. Dynamic thresholding is gentler: look at how large the values are for this sample, pick a level s that covers most of them, then squash everything into [-s, s] and rescale by s.
Example: values [0.5, -2, 4, 1] with p = 75. The absolute values sorted are 0.5, 1, 2, 4, and the 75th percentile is 2.5. Clipping gives [0.5, -2, 2.5, 1]; dividing by 2.5 gives [0.2, -0.8, 1, 0.4], all inside [-1, 1] with the shape of the image kept.
Rule: s = max(1, percentile(|x0|, p)); x0 = clip(x0, -s, s) / s.
It was introduced for photorealistic text-to-image models that use very high guidance weights.
Shapes and data flow
x0: (B, ...) -> flat: (B, D) -> s: (B, 1, ...) -> out: (B, ...)