460. 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)Example 1
Input: str(quantize_int8(W)[0].dtype)
Output: "int8"
Example 2
Input: quantize_int8(W)[1]
Output: [0.01, 100.0 / 127]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Scale per row is max(abs(row)) / 127.
Hint 2
Divide, round, clip to [-127, 127], cast to int8.
Hint 3
Dequantize by multiplying back.
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.
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).
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.
Companies1
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
From public interview reports and guides. Not affiliated with or endorsed by these companies.