Linear algebra for LLMsPart 9: Numbers on real hardware

Quantization

7 min

Scale, round, scale back

s=max⁡i∣xi∣127,qi=round⁡(xi/s),x^i=s qi\displaystyle s = \frac{\max_i |x_i|}{127}, \qquad q_i = \operatorname{round}(x_i / s), \qquad \hat x_i = s\, q_i

Symmetric INT8 quantization: pick one scale so the largest value lands on ±127\pm 127, store the rounded integers plus the scale, and multiply back when needed.

Write

INT8: s=max⁡∣x∣/127s = \max|x|/127, q=round⁡(x/s)q = \operatorname{round}(x/s), x^=sq\hat x = sq.

INT8 by hand

s=0.01s = 0.01 →

The largest magnitude, 1.27, sets s=0.01s = 0.01. Every value is stored as a whole number of hundredths; 0.031 becomes 3, so it comes back as 0.03. Rounding never moves a value by more than s/2s/2.

Write

Error per entry ≤s/2\le s/2.

INT4: only 15 levels

s=1.27/7≈0.181s = 1.27/7 \approx 0.181 →

With levels −7…7-7 \dots 7 the steps are 18× coarser: 0.42 comes back as 0.363, and 0.031 vanishes to 0. INT4 halves the memory again, at a real cost in accuracy unless it’s done carefully.

One outlier ruins the scale

s=10/127≈0.079s = 10/127 \approx 0.079 →

The 10 forces a big step, so the small values get one to three levels each: 0.1 comes back as 0.079, a 21% error. LLM activations and some weights do have such outliers.

Write

One outlier sets a coarse scale for everyone.

Per-channel and per-group scales

one scale per 128 weights\displaystyle \text{one scale per } 128 \text{ weights}
4+16128=4.125 bits per weight\displaystyle 4 + \tfrac{16}{128} = 4.125 \text{ bits per weight}

Give each output channel, or each group of 128 consecutive weights, its own scale. An outlier then only coarsens its own group. A 16-bit scale per 128 four-bit weights adds an eighth of a bit per weight.

Scales factor out of the matmul

yj=x⋅Wj,:=x⋅(sj Qj,:)=sj (x⋅Qj,:)\displaystyle y_j = x \cdot W_{j,:} = x \cdot (s_j\, Q_{j,:}) = s_j\,(x \cdot Q_{j,:})

With one scale per output row, the dot product can run on the integers and be rescaled once at the end. That’s how quantized kernels avoid converting every weight back to floating point first.

✏️ Your turn

Quantize to INT4

Use s=max⁡∣x∣/7s = \max|x|/7. Write ss, qq and x^\hat x.

Work it out on paper, then go to the next card to check.

Answer

s=1.4/7=0.2\displaystyle s = 1.4 / 7 = 0.2
q=[3,−7,1],x^=[0.6,−1.4,0.2]\displaystyle q = [3, -7, 1], \qquad \hat x = [0.6, -1.4, 0.2]

0.62/0.2=3.1→30.62/0.2 = 3.1 \to 3 and 0.25/0.2=1.25→10.25/0.2 = 1.25 \to 1. Both errors are under s/2=0.1s/2 = 0.1.

📌 Recap

Quantization in one card

  • s=max⁡∣x∣/qmax⁡s = \max|x|/q_{\max}, q=round⁡(x/s)q = \operatorname{round}(x/s), x^=sq\hat x = sq; error ≤s/2\le s/2.
  • INT4 has 15 levels: much coarser than INT8’s 255.
  • Outliers coarsen a shared scale; per-channel or per-group scales contain them.
  • Per-row scales factor out of the dot product.

Write

The four lines above.