Linear algebra for LLMsPart 5: Attention, one operation at a time
Scores and the √dₖ scaling
6 min
Every query against every key
is . Row is query , column is key : how much token is interested in token .
Write
One entry
“cat” asks with ; “cat” answers with . : the strongest match in the matrix.
✏️ Your turn
Score a row
Write “sat”’s scores against the three keys.
Work it out on paper, then go to the next card to check.
Answer:
Row 3 of . “sat” is most interested in “cat”.
Scale by
With , every score is divided by . The order inside each row doesn’t change; only the gaps shrink.
Write
Why , again
From Part 1: with unit-variance entries, a dot product of length has standard deviation . A real head has , 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
In PyTorch
scores = q @ k.transpose(-2, -1) / d_k ** 0.5 # (B, h, T, T)In a transformer
This matrix is 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
- , , .
- Example: .
- Scale by to keep the variance near 1.
Write