Multiply int8 activations by int8 weights and dequantize

MediumQuantizationPro

Why it matters W8A8 kernels roughly double matmul throughput on GPUs with int8 tensor cores, and the per-token, per-channel scheme is the standard layout.

W8A8 inference quantizes both activations and weights to int8, multiplies them with integer arithmetic, and converts back with two scales.

Write w8a8_matmul(X, W). X is (M, K), W is (K, N). Use a symmetric per-token scale for X: sx[m] = max|X[m, :]| / 127, and a symmetric per-output-channel scale for W: sw[n] = max|W[:, n]| / 127. A scale of 0 (all-zero row or column) becomes 1. Quantize with q = clip(round(v / scale), -127, 127) as integers. Accumulate acc = qX @ qW in integers, then return (acc as an int array, Y = acc * sx[:, None] * sw[None, :]).

Signaturedef w8a8_matmul(X, W)

Example

X [[1, -2]], W [[2, 0], [1, 4]] gives acc [[0, -16129]] and Y [[0.0, -8.0]] (sx = 2/127, sw = [2/127, 4/127]).

Understand the idea

Integer matmul works because scales can be pulled out of a sum when they do not depend on the summed index. A row of X shares one scale, and a column of W shares one scale, so in y[m, n] = sum_k X[m, k] W[k, n] both scales sit outside the sum over k. Worked example: X = [1, -2] gives sx = 2/127 and qX = [64, -127] (1 / (2/127) = 63.5 rounds to 64). Column 1 of W is [0, 4], scale 4/127, q = [0, 127]. acc = 64 x 0 + (-127) x 127 = -16129, and -16129 x (2/127) x (4/127) = -8, exactly the float answer 1 x 0 + (-2) x 4. Rule: y = (qX @ qW) * sx[m] * sw[n]. Scales along K would not factor out, which is why weights are scaled per output channel.

Shapes and data flow

X (M, K) sx (M,)  W (K, N) sw (N,)  acc = qX @ qW (M, N)  Y = acc * sx[:, None] * sw[None, :]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplew8a8_matmul([[1, -2]], [[2, 0], [1, 4]])
  • Sample 2: randomw8a8_matmul(_X, _W)[1]