Skip to content
BytePatterns

Int8 Quantization Round Trip

EasyAI & ML#quantization#scale-and-round~15m

Problem

Quantization stores model weights as small integers plus one float scale. Implement symmetric int8 quantization for a list of weights: the scale is the largest absolute weight divided by 127, each weight becomes round(w / scale) clamped to the range -127 to 127, and dequantizing multiplies back by the scale. Return the integer codes, the scale rounded to 6 decimals, and the largest absolute error between a weight and its dequantized value, also rounded to 6 decimals. If every weight is 0, use a scale of 1.0.

Examples

Input:  [0.4, -2.54, 0.013, 1.0]
Output: ([20, -127, 1, 50], 0.02, 0.007)
Why:    the scale is 2.54 / 127 = 0.02, so 0.013 lands on 1 step and comes back as 0.02
Input:  [0.01, 0.02, -0.03, 10.0]
Output: ([0, 0, 0, 127], 0.07874, 0.03)
Why:    one outlier stretches the scale, and every small weight collapses to 0
Input:  [0.0, 0.0]
Output: ([0, 0], 1.0, 0.0)
Why:    edge case, an all-zero list has no largest weight to divide, so a scale of 1.0 avoids dividing by zero

Hints

0 / 3

Stuck on the idea rather than the code? Quantization covers it.