Chapter 02

Attention, per decode step

What a new token needs from the past.

tokensThe␣capital␣of␣France␣is

Same five tokens, one forward pass. This time we watch what one attention layer does with them.

The math, once

For one head, with Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V:

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

MM is the causal mask from step 7: Mij=−∞M_{ij} = -\infty for j>ij > i and 00 otherwise, so softmax gives a later key zero weight. Row ii of the result only uses row ii of QQ, but every row ≤i\le i of KK and VV. That asymmetry is the whole next chapter.