Rotate activations with a Hadamard matrix before 4-bit quantization
Why it matters Rotation-based 4-bit quantization of activations and KV caches uses Hadamard transforms because they remove outliers cheaply and exactly preserve the layer output.
An orthogonal rotation spreads one huge channel across all channels, so a per-row 4-bit grid fits better. Because the rotation is orthogonal, (X H)(H^T W) = X W, so the model output is unchanged before quantization.
Write hadamard_quant_error(X). X is (M, n) with n a power of two (raise ValueError otherwise). Build the n x n Hadamard matrix by the Sylvester recipe (H1 = [[1]], H2k = [[Hk, Hk], [Hk, -Hk]]) and normalize it by 1 / sqrt(n) so it is orthogonal. Define quant4(A) as symmetric per-row 4-bit: scale = max|row| / 7 (0 becomes 1), q = clip(round(A / scale), -7, 7), return q * scale. Return (err_plain, err_rot) where err_plain = mean((quant4(X) - X)^2) and err_rot = mean((quant4(X H) H^T - X)^2).
def hadamard_quant_error(X)Example
X [[10, 1, 1, 1]] gives (0.13775510204081637, 0.015306122448979546).
Understand the idea
A single giant value in a row forces a coarse quantization grid on every other value in that row. A rotation mixes all channels together, like stirring a drop of ink into a glass so no single spot is dark. The Hadamard matrix is a rotation made only of +1 and -1 entries (scaled by 1 / sqrt(n)), so it is cheap and exactly reversible. Worked example: row [10, 1, 1, 1]. Plain 4-bit has step 10 / 7 = 1.43, so each 1 rounds to 1.43 and the mean error is 0.138. After rotating, the row becomes [6.5, 4.5, 4.5, 4.5]: the largest value is now close to the others, the step is 6.5 / 7 = 0.93, and after rotating back the mean error is only 0.015. Rule: x_rot = x H, quantize, x_hat = quant(x_rot) H^T. Because (X H)(H^T W) = X W, the rotation can be folded into the weights offline.
Shapes and data flow
X (M, n) @ H (n, n) -> (M, n) rotated; quant4 per row; @ H.T -> (M, n)