882. Per-row int8 quantization at speed
Why it matters Weight-only int8 and int4 quantization is how large models fit on small GPUs. Per-row (per-channel) scales are the standard choice.
quantize_rows(W) applies symmetric per-row int8 quantization. For each row: scale = max(abs(row)) / 127, or 1.0 if the row is all zeros. q = clip(np.round(row / scale), -127, 127) as integers. np.round rounds halves to even.
Inputs: W is a list or ndarray of shape (n, d).
Return a tuple (q, scales): q is an ndarray of ints with shape (n, d), scales an ndarray of floats with shape (n,).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 40 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def quantize_rows(W)Example 1
Input: quantize_rows([[1.0, -0.5, 0.25], [0.0, 0.0, 0.0]])
Output: ([[127, -64, 32], [0, 0, 0]], [0.0079, 1.0])
Example 2
Input: W = [[254.0, 1.0, -127.0]]
Output: ([[127, 0, -64]], [2.0])
Example 3
Input: W = [[-3.0], [2.0]]
Output: ([[-127], [127]], [0.023622, 0.015748])
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Row max: np.abs(W).max(axis=1).
Hint 2
Replace zero maxima with a scale of 1.0 using np.where.
Hint 3
Divide by scales[:, None], round, clip, cast.
Common mistakes
- Using one scale for the whole matrix.
- Python round, which also rounds half to even but only works on scalars.
- Dividing by 128 instead of 127.
Understand the idea
Take the absolute max of every row at once with axis=1, turn it into a scale vector and broadcast it back with s[:, None]. np.where handles zero rows without a branch. In the example row [254, 1, -127] the scale is 2, so 1 / 2 = 0.5 rounds to 0 and -127 / 2 = -63.5 rounds to -64 (half to even).
Shapes and data flow
W: (n, d). scales: (n,). q: (n, d).