Quantize activations to uint8 with a scale and zero point

Activations after ReLU or GELU are mostly positive, so a symmetric int8 grid wastes half its codes. Asymmetric quantization maps the range [lo, hi] onto 0..255 and stores a zero point so that the real value 0.0 lands exactly on a code. Padding and ReLU zeros then dequantize to exactly 0.

Write quantize_uint8(x) for a 1D float array x. Steps:
- lo = min(x.min(), 0.0), hi = max(x.max(), 0.0). The range must always contain 0.
- If hi == lo (all zeros), return (array of zeros as int, 1.0, 0).
- scale = (hi - lo) / 255
- zero_point = int(np.round(-lo / scale)), clipped to [0, 255]
- q = clip(np.round(x / scale) + zero_point, 0, 255) as int
Return (q, scale, zero_point). Dequantization is (q - zero_point) * scale.

Signaturedef quantize_uint8(x)

Example

x = [-1.0, 0.0, 2.0] gives scale = 3/255, zero_point = 85, q = [0, 85, 255].

Understand the idea

Asymmetric quantization maps a real range [lo, hi] onto the 256 codes 0 to 255. A zero point says which code stands for the real value 0. Forcing the range to include 0 guarantees that 0.0 lands exactly on a code, so ReLU zeros and padding come back as exact zeros. Worked example: x = [-0.5, 2.0]. lo = -0.5, hi = 2.0, scale = 2.5 / 255 = 0.009804. zero_point = round(0.5 / 0.009804) = round(51) = 51. q(-0.5) = round(-51) + 51 = 0. q(2.0) = round(204) + 51 = 255. q(0.0) = 51, which dequantizes to (51 - 51) * scale = 0 exactly. For all-positive data like [0.5, 1.0], lo is still 0, so the zero point is 0. Rule: lo = min(min(x), 0), hi = max(max(x), 0); if equal return zeros with scale 1 and zero point 0; scale = (hi - lo) / 255; zero_point = round(-lo / scale) clipped to [0, 255]; q = clip(round(x / scale) + zero_point, 0, 255). Used for int8 activation quantization in mobile and server inference.

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

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplequantize_uint8([-1.0, 0.0, 2.0])
  • Sample 2: all positive activationsquantize_uint8(_act)
  • Test 3: all zerosquantize_uint8([0.0, 0.0, 0.0])
  • Test 4: zero dequantizes exactly(lambda r: float((r[0][1] - r[2]) * r[1]))(quantize_uint8([0.3, 0.0, 1.7, 2.4]))