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

Mixing values

6 min

Weights times values

=

O=AVO = AV: (T×T)(T×dv)=T×dv(T \times T)(T \times d_v) = T \times d_v. One output row per token.

Write

O=AVO = AV, shape T×dvT \times d_v.

One output row is a weighted average

ocat=0.056 vthe+0.944 vcat+0 vsat\displaystyle o_{\text{cat}} = 0.056\,v_{\text{the}} + 0.944\,v_{\text{cat}} + 0\,v_{\text{sat}}
=0.056 [1,1]+0.944 [0,1]=[0.056,1]\displaystyle = 0.056\,[1, 1] + 0.944\,[0, 1] = [0.056, 1]

Row view of a matrix product (Part 2): row ii of AVAV mixes the rows of VV with the weights in row ii of AA. The weights are positive and sum to 1, so the output is a weighted average of value vectors, never outside their range.

Write

oi=∑jAij vjo_i = \sum_j A_{ij}\, v_j with Aij≥0A_{ij} \ge 0, ∑jAij=1\sum_j A_{ij} = 1.

✏️ Your turn

Mix the last row

Asat≈[0.14,0.58,0.28]A_{\text{sat}} \approx [0.14, 0.58, 0.28]

Write osato_{\text{sat}}.

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

Answer

0.14 [1,1]+0.58 [0,1]+0.28 [1,0]\displaystyle 0.14\,[1,1] + 0.58\,[0,1] + 0.28\,[1,0]
≈[0.42,0.72]\displaystyle \approx [0.42, 0.72]

With the unrounded weights, row 3 of OO is [0.42,0.72][0.42, 0.72].

All of attention in one line

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V\displaystyle \operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

Project, score, scale, mask, softmax each row, mix the values. You have now computed every piece of it by hand.

Write

softmax⁡(QK⊤/dk+M) V\operatorname{softmax}(QK^\top/\sqrt{d_k} + M)\,V

The shapes, start to finish

Step Shape
XX T×dT \times d
Q,K,VQ, K, V T×dkT \times d_k
scores QK⊤QK^\top, weights AA T×TT \times T
output AVAV T×dvT \times d_v

Write

T×d→T×dk→T×T→T×dvT \times d \to T \times d_k \to T \times T \to T \times d_v

What it costs

QK⊤ ⁣:  2 T2dkAV ⁣:  2 T2dv\displaystyle QK^\top\!: \; 2\,T^2 d_k \qquad AV\!: \; 2\,T^2 d_v

Both grow with T2T^2. The projections cost 2Td dk2Td\,d_k each, linear in TT. For short contexts the projections dominate; for long contexts the T2T^2 terms take over.

out = F.scaled_dot_product_attention(q, k, v, is_causal=True)

📌 Recap

Mixing values in one card

  • O=AVO = AV: each output row is a weighted average of value rows.
  • Attention⁡=softmax⁡(QK⊤/dk+M) V\operatorname{Attention} = \operatorname{softmax}(QK^\top/\sqrt{d_k} + M)\,V.
  • Example: O≈[1 1; 0.06 1; 0.42 0.72]O \approx [1\ 1;\ 0.06\ 1;\ 0.42\ 0.72].
  • Cost ≈4T2dk\approx 4T^2 d_k per head for scores and mixing.

Write

The four lines above.