Linear algebra for LLMsPart 5: Attention, one operation at a time

Scores and the √dₖ scaling

6 min

Every query against every key

=

S=QK⊤S = QK^\top is (T×dk)(dk×T)=T×T(T \times d_k)(d_k \times T) = T \times T. Row ii is query ii, column jj is key jj: how much token ii is interested in token jj.

Write

S=QK⊤S = QK^\top, T×TT \times T. Sij=qi⋅kjS_{ij} = q_i \cdot k_j.

One entry

=

“cat” asks with q=[0,2]q = [0, 2]; “cat” answers with k=[1,2]k = [1, 2]. 0⋅1+2⋅2=40 \cdot 1 + 2 \cdot 2 = 4: the strongest match in the matrix.

✏️ Your turn

Score a row

qsat=[1,1]q_{\text{sat}} = [1, 1]

Write “sat”’s scores against the three keys.

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

Answer: [1,3,2][1, 3, 2]

[1,1]⋅[1,0]=1,[1,1]⋅[1,2]=3,[1,1]⋅[1,1]=2\displaystyle [1,1] \cdot [1,0] = 1, \quad [1,1] \cdot [1,2] = 3, \quad [1,1] \cdot [1,1] = 2

Row 3 of SS. “sat” is most interested in “cat”.

Scale by 1/dk1/\sqrt{d_k}

S2=\dfrac{S}{\sqrt{2}} =

With dk=2d_k = 2, every score is divided by 2≈1.414\sqrt 2 \approx 1.414. The order inside each row doesn’t change; only the gaps shrink.

Write

S/dkS / \sqrt{d_k}: here 2\sqrt 2.

Why dk\sqrt{d_k}, again

Var⁡(q⋅k)=dk  ⇒  Var⁡ ⁣(q⋅kdk)=1\displaystyle \operatorname{Var}(q \cdot k) = d_k \;\Rightarrow\; \operatorname{Var}\!\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = 1

From Part 1: with unit-variance entries, a dot product of length dkd_k has standard deviation dk\sqrt{d_k}. A real head has dk=128d_k = 128, so raw scores would swing by about 11, and softmax would hand nearly all the weight to one key with tiny gradients for the rest. Dividing brings the spread back to about 1, for any head width.

Write

Dividing by dk\sqrt{d_k} keeps score variance ≈ 1, so softmax doesn’t saturate.

In PyTorch

scores = q @ k.transpose(-2, -1) / d_k ** 0.5    # (B, h, T, T)

In a transformer

This matrix is T×TT \times T per head: at 8,192 tokens that’s 67 million scores per head per layer. Storing them all is what FlashAttention avoids (Part 9).

📌 Recap

Scores and scaling in one card

  • S=QK⊤S = QK^\top, T×TT \times T, Sij=qi⋅kjS_{ij} = q_i \cdot k_j.
  • Example: S=[2 2 2; 0 4 2; 1 3 2]S = [2\ 2\ 2;\ 0\ 4\ 2;\ 1\ 3\ 2].
  • Scale by 1/dk1/\sqrt{d_k} to keep the variance near 1.

Write

The three lines above.