Linear algebra for LLMsPart 5: Attention, one operation at a time
Mixing values
6 min
Weights times values
: . One output row per token.
Write
, shape .
One output row is a weighted average
Row view of a matrix product (Part 2): row of mixes the rows of with the weights in row of . The weights are positive and sum to 1, so the output is a weighted average of value vectors, never outside their range.
Write
with , .
✏️ Your turn
Mix the last row
Write .
Work it out on paper, then go to the next card to check.
Answer
With the unrounded weights, row 3 of is .
All of attention in one line
Project, score, scale, mask, softmax each row, mix the values. You have now computed every piece of it by hand.
Write
The shapes, start to finish
| Step | Shape |
|---|---|
| scores , weights | |
| output |
Write
What it costs
Both grow with . The projections cost each, linear in . For short contexts the projections dominate; for long contexts the terms take over.
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)📌 Recap
Mixing values in one card
- : each output row is a weighted average of value rows.
- .
- Example: .
- Cost per head for scores and mixing.
Write
The four lines above.