GPT from code · part 2 of 5

Q, K and V: three roles for every character

How each position of “marta” gets a query, a key and a value, and how they are split into 8 heads.

1x · 6 × 128
after RMSNorm
BOS
m
a
r
t
a
2Wq
128 × 128
learned weights
Q = x · Wq⊤ · 6 × 128





3Query · “what am I looking for?”
Position “r” asks which earlier letters help it guess what comes next.
Wk
128 × 128
learned weights
K = x · Wk⊤ · 6 × 128





Key · “what can I be matched on?”
Every position advertises what it holds, e.g. “I am a vowel”, “I am the start”.
Wv
128 × 128
learned weights
V = x · Wv⊤ · 6 × 128





Value · “what I pass on”
If a position gets attention, its value is the information that gets copied.
48 heads × 16 numbers (n_head = 8, head_dim = 16) · each head gets its own slice of Q, K and V
h1h2h3h4h5h6h7h8
5Search analogy: the query is what you type, the keys are the page titles, the values are the page contents. Attention returns a mix of values, weighted by how well each key matches the query.
reshape (6, 8, 16) → transpose (8, 6, 16)