Quantize weights to int8 and measure the error
Storing weights in 8-bit integers instead of 32-bit floats cuts memory by 4x. Symmetric per-row quantization gives each row of a weight matrix its own scale.
Write quantize_int8(W) for a 2D array W. For each row, scale = max(abs(row)) / 127 (use scale 1.0 for a row of all zeros). q = round(row / scale), clipped to [-127, 127], as np.int8. Return (q, scales) where scales has shape (rows,).
Write dequantize(q, scales) that returns q * scale per row as floats.
Write max_abs_error(W): the largest absolute difference between W and dequantize(*quantize_int8(W)). It is at most half a step, scale / 2, per row.
def quantize_int8(W)Understand the idea
Quantization stores each weight as a small integer plus a shared scale, cutting memory by 4 times compared with float32. Symmetric per-row quantization gives each row its own scale so its largest absolute value maps to 127. Think of choosing a ruler for each row so the longest value just fits. Worked example: row [0.5, -1.27, 0.2]. Max absolute value is 1.27, so scale = 1.27 / 127 = 0.01. Then q = round([50, -127, 20]) = [50, -127, 20], and dequantizing gives the row back exactly. A harder row [1.0, 0.3]: scale = 1/127 = 0.007874, and 0.3 / scale = 38.1, which rounds to 38. Dequantized it is 0.29921, an error of 0.00079, below half a step (0.0039). Rule: scale = max|row| / 127 (use 1.0 for all zeros), q = clip(round(row / scale), -127, 127), back = q * scale. Round, do not truncate. LLM inference libraries use int8 weights to fit big models on smaller GPUs.
Similar problems
Part of the advanced LLM architecture track.