Requantize an int32 accumulator with a fixed-point multiplier

MediumQuantizationPro

Why it matters Integer-only kernels on phones and NPUs requantize every layer output this way, so getting the rounding right affects every activation.

Integer-only inference cannot multiply by a float scale. The real multiplier M = s_in * s_w / s_out (between 0 and 1) is stored as a 31-bit integer m0 and a right shift, and the int32 accumulator is rescaled with integer math.

Write requantize(acc, M, zero_point). Normalize M: shift = 0; while M < 0.5, double M and add 1 to shift. Then m0 = round(M * 2^31); if m0 == 2^31, halve it and subtract 1 from shift. For each accumulator value a (Python int), compute r = (a * m0 + 2^(30 + shift)) >> (31 + shift), which is a / 2^(31 + shift) * m0 rounded half up. Return (m0, shift, out) where out = clip(r + zero_point, -128, 127) as a list of ints.

Signaturedef requantize(acc, M, zero_point)

Example

acc [1000, -1000, 37], M 0.0123, zero_point 3 gives m0 1690499128, shift 6 and out [15, -9, 3].

Understand the idea

Integer chips cannot multiply by 0.0123, but they can multiply by a big integer and shift bits right. Shifting right by k divides by 2^k. So we write M = m0 / 2^(31 + shift) with m0 a 31-bit integer. Worked example: M = 0.0123. Doubling six times gives 0.7872, so shift = 6 and m0 = round(0.7872 x 2^31) = 1690499128. For a = 1000, a x M = 12.3; the integer recipe adds half of 2^37 before shifting and returns 12, then the zero point 3 makes 15. Rule: r = (a m0 + 2^(30 + shift)) >> (31 + shift), out = clip(r + zp, -128, 127). Adding half the divisor before shifting turns flooring into round-half-up, which matters most for negative values.

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

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

  • Sample 1: examplerequantize([1000, -1000, 37], 0.0123, 3)
  • Sample 2: saturaterequantize([100000, -100000, 0], 0.01, -5)