Search for an activation-aware per-channel scale before int4 rounding

MediumQuantizationPro

A few input channels of an LLM layer carry much larger activations than the rest. Rounding errors on the weights that multiply those channels hurt the output the most. Activation-aware methods scale those weight columns up before quantizing (so they get relatively finer steps) and divide the scale back out after dequantizing. The output error, not the weight error, decides the best scale.

Write best_awq_alpha(W, X, alphas). W has shape (out, in), X has shape (n, in) with no all-zero column, alphas is a list of floats.
- s = mean of |X| over rows, shape (in,)
- For each alpha: sc = s ** alpha. Ws = W * sc (scale column j by sc[j]).
- Quantize each ROW of Ws to symmetric int4: step = max|row| / 7 (use 1.0 if the row is all zeros), q = clip(np.round(Ws / step), -8, 7).
- Dequantize and undo the scale: Wd = q * step / sc.
- err = mean((X @ W.T - X @ Wd.T) ** 2)
Return (best_alpha, errs) where errs is the list of errors in alphas order and best_alpha has the smallest error (ties: the earliest alpha). alpha = 0 is plain per-row int4.

Signaturedef best_awq_alpha(W, X, alphas)

Understand the idea

In an LLM layer a few input channels carry much bigger activations than the rest, so rounding errors on the weights that multiply them hurt the output most. The idea is to scale those weight columns up before rounding, giving them finer steps relative to their size, then divide the scale back out afterwards. A sweep over alpha picks how strongly to scale, judged by output error. Worked example on one row of int4: W row [1.4, 0.3]. Plain int4: step = 1.4 / 7 = 0.2, codes [7, 2] (0.3 / 0.2 = 1.5 rounds to 2), rebuilt [1.4, 0.4], an error of 0.1 on column 2. If column 2 is important with scale 4: scaled row [1.4, 1.2], step 0.2, codes [7, 6], rebuilt [1.4, 1.2] / [1, 4] = [1.4, 0.3], exact. Rule: s = mean |X| per column; sc = s ** alpha; Ws = W * sc; per row step = max|row| / 7 (1.0 if zero), q = clip(round(Ws / step), -8, 7); Wd = q * step / sc; err = mean((X W^T - X Wd^T)^2). Pick the alpha with the smallest err, earliest on ties. This is the AWQ idea.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: outlier channelsbest_awq_alpha(_W, _X, [0.0, 0.25, 0.5, 0.75, 1.0])
  • Sample 2: no outliersbest_awq_alpha(_W2, _X2, [0.0, 0.5, 1.0])