Search the clipping range that minimizes quantization error

MediumQuantizationPro

Why it matters Calibration tools search clipping ranges like this for activations and weights before deploying 4-bit and 8-bit models.

Using the absolute max as the quantization range wastes levels on rare outliers. Clipping a little tighter often lowers the total error, because the many ordinary values get a finer grid.

Write best_clip(x, bits, ratios). x is a 1-D array. For each ratio r in ratios, let c = r * max|x|, scale = c / (2^(bits - 1) - 1), q = clip(round(x / scale), -(2^(bits - 1) - 1), 2^(bits - 1) - 1), and the error is mean((q * scale - x)^2). Return (best_ratio, best_mse), ties going to the earlier ratio in the list. If max|x| is 0 return (ratios[0], 0.0).

Signaturedef best_clip(x, bits, ratios)

Example

x [0.2, -0.2, 0.2, -0.2, 0.2, -0.2, 0.2, -0.2, 1.0], bits 3, ratios [1.0, 0.7, 0.4] gives (0.7, 0.010987654320987655).

Understand the idea

Quantization error has two parts that pull in opposite directions. A wide range covers every value but spaces the levels far apart, so ordinary values are rounded coarsely. A narrow range gives fine levels but chops off the big values. The best range balances the two. Worked example: eight values of plus or minus 0.2 and one 1.0, with 3 bits (levels -3 to 3). With range 1.0 the step is 0.33, so every 0.2 becomes 0.33 and the mean error is 0.0158. With range 0.7 the step is 0.23: each 0.2 is off by only 0.03, while 1.0 is clipped to 0.7 and loses 0.3, giving a lower mean error of 0.011. With range 0.4 the clipping loss on 1.0 is too big. Rule: for each candidate c, scale = c / qmax, error = mean((clip(round(x / scale)) scale - x)^2); pick the smallest. Real calibration uses a few hundred samples of activations from a model.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplebest_clip([0.2, -0.2, 0.2, -0.2, 0.2, -0.2, 0.2, -0.2, 1.0], 3, [1.0, 0.7, 0.4])
  • Sample 2: gaussianbest_clip(_x, 4, [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4])