Dynamic Thresholding of the Predicted x0
Problem Statement
Imagen's dynamic thresholding prevents saturated images at high guidance by clamping the predicted x0 to a percentile-derived range each step. Implement it.
Background
Given the predicted x0 and a percentile p (e.g. 99.5), compute s = percentile(|x0|, p) over all elements. If s < 1, set s = 1 (never shrink below the natural [-1, 1] range). Then clip x0 to [-s, s] and rescale by dividing by s, pushing saturated pixels back inward:
Use linear interpolation for the percentile (NumPy's default).
Your Task
Implement:
def dynamic_threshold(x0, p):
Return the thresholded values as a list rounded to 4 decimals.
Input Format
- x0: list of floats.
- p (float): percentile in [0, 100].
Output Format
- A list of floats rounded to 4 decimals.
Sample
print(dynamic_threshold([2.0, -2.0, 0.5, 0.0], 50.0))
Output:
[1.0, -1.0, 0.4, 0.0]
Example
print(dynamic_threshold([2.0, -2.0, 0.5, 0.0], 50.0))
[1.0, -1.0, 0.4, 0.0]
- Compute the absolute values of the input list to get , which are then sorted as to prepare for percentile calculation.
- Determine the 50th percentile (median) of these absolute values using linear interpolation; with 4 elements, the median is the average of the two middle values: .
- Apply the lower bound constraint by taking the maximum of the calculated percentile and 1: , ensuring the threshold never shrinks the range below .
- Clip each original value in to the range ; since all values () are within this range, the clipped list remains .
- Rescale the clipped values by dividing each by to normalize them: , , , and .
- The final output is [1.0, -1.0, 0.4, 0.0]
Constraints
1 <= len(x0) <= 100000,0 <= p <= 100.s = max(percentile(|x0|, p), 1.0)(linear-interpolation percentile).- Clip to
[-s, s], divide bys; round to 4 decimals; avoid-0.0.