Per-channel vs per-tensor int8: measure the error
A weight matrix often has a few rows (output channels) with much larger values. Giving each row its own scale shrinks the quantization error a lot.
Write int8_error(W, per_channel) for a 2D matrix. Use symmetric int8: scale = max|x| / 127 over the whole matrix (per_channel False) or over each row (True), q = clip(round(x / scale), -127, 127), dequant = q * scale. Treat a zero scale as 1.0. Return the mean squared error between W and the dequantized matrix as a float.
def int8_error(W, per_channel)Understand the idea
In symmetric int8 quantization, scale = max|x| / 127, and every value is rounded to a multiple of that scale. If one row of a matrix has huge values, a single shared scale becomes coarse, and small rows get only a few levels. Giving each row (output channel) its own scale fixes this. Like weighing gold and potatoes on separate scales. Worked example: W = [[100, 40], [1, -0.4]]. Per-tensor scale = 100 / 127 = 0.787. Then 1 becomes 1 level (0.787) and -0.4 becomes -1 level (-0.787), big errors. Mean squared error over all four values is about 0.055. Per-row: row 2 has scale 1 / 127, so 1 is exact and -0.4 maps to -51 levels, -0.4016. MSE drops to about 0.0062, nearly 9 times smaller. Rule: per_channel uses max over each row; otherwise over the whole matrix; q = clip(round(x / scale), -127, 127); MSE = mean((W - q scale)^2); zero scale becomes 1.0. LLM quantization tools use per-channel scales for weights.