Highlights

Contents

Part VI
06

Queries, Keys and Values

A token needs information from other positions. Matching and supplied content are different jobs. Queries, keys, and values separate them before softmax blends the relevant contributions.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 33Every Token Plays Three Roles

Attention lets one position obtain information from other positions. In The cat sat because it was tired, it can help the representation of it use information about cat.

The names attention uses come from searching a library or a database, so let us start there. You walk into a library with a question written on a slip of paper: “who is it?”. That is your query. Every book has a label on its spine, like cat or because. Those labels are the keys. You compare your question with the spines and find the best match. Then you open that book and read what is inside. That is the value.

QUERY, KEY, VALUE AS A LIBRARY VISITquery"who is it?"thecatsatbecauseitkeys: the labels on the spineshow much of each book you readvalues: what is insidefurry, purrs,did the sittingattention reads a little of every book, most of the best match
Figure 1.43Query, key and value as a library visit. The query is compared with every spine label (key); the contents (values) are read in proportion to how well each label matched.

There is one big difference from a real library. Attention does not pick a single book. It reads a little from every book, a lot from the good matches and only a trace from the poor ones, and blends what it read into one answer. That blending is what makes attention trainable: a smooth mixture can be nudged a little at a time during training, whereas a hard “pick one” cannot.

The deep idea is that every token plays all three roles at once. it asks a question with its query. But it also has a key and a value, so that later tokens, was and tired, can find it and borrow from it. Every token is simultaneously a reader with a question, a book with a label, and the contents of that book.

#Section 34Making Q, K and V

Where do the three vectors come from? Each one is the token’s vector multiplied by a different learned weight matrix. Same input, three different views of it:

Q=xWQK=xWKV=xWVQ = x W_Q \qquad K = x W_K \qquad V = x W_V

The input has one feature vector per position. Three learned projections produce queries, keys, and values. Sharing each projection across positions applies the same operation to every token.

A matrix projection forms new features by taking weighted sums of the input features. Training adjusts those weights so matching features and useful content can differ.

ONE INPUT, THREE LEARNED LENSES (FINCH-19, ONE LAYER, OUR 7-TOKEN SENTENCE)x7 × 512WQ512 × 512=Q7 × 512what am I looking for?WK512 × 512=K7 × 512what do I contain?WV512 × 512=V7 × 512what will I hand over?per head: 7 × 64(8 heads side by side)same x, three differentlearned views of it
Figure 1.44One input, three projections. The 7 × 512 input is multiplied by three different learned 512 × 512 matrices, producing the queries, keys and values for all seven tokens at once.

Separate projections learn what to seek, how to be found, and what to contribute. Finch-19 also uses a learned bias, a fixed vector added to each projection's output.

In code it is three linear layers, or more commonly one fused layer three times as wide whose output is cut into three:

python
qkv = nn.Linear(512, 3 * 512)(x)       # x: (B, T, 512) -> (B, T, 1536)
q, k, v = qkv.split(512, dim=-1)       # each (B, T, 512)
EVERY TOKEN MAKES ALL THREE: IT ASKS, IT ADVERTISES, IT OFFERSTheqkv␠catqkv␠satqkv␠becauseqkv␠itqkv␠wasqkv␠tiredqkv"it" asks with its q, and is also asked about through its k
Figure 1.45Every token produces its own query, key and value. it asks with its q, and it can also be found, by later tokens, through its k and v.

#Section 35Matching: The Score

Now we use them. To decide how much token ii should attend to token jj, compare token ii's query with token jj's key using the dot product from Section 12: multiply them entry by entry and add up the results. A large positive score means "this key matches what I am looking for".

sij=qi⋅kjs_{ij} = q_i \cdot k_j

The figure compares it's query with the visible keys. A larger dot product means a stronger match; it does not yet give a normalized weight.

Softmax exponentiates scores and divides by their sum, producing positive weights that sum to one. Here cat receives the strongest weight.

THE QUERY OF “IT” AGAINST EVERY KEY IT CAN SEE (TOY 4-NUMBER VECTORS)scores qit · kj0.12The2.00␠cat0.46␠sat0.24␠because0.68␠itsoftmaxweights (sum to 1)0.084The0.554␠cat0.119␠sat0.095␠because0.148␠it55% of the attention goes to "cat"
Figure 1.46The query of it scored against every key it can see (left), then turned into weights by softmax (right). More than half of the attention, 0.554, goes to cat. (Toy vectors.)

The tallest bar is cat. The model has learned to make the query of a pronoun match the key of a recently mentioned noun of the right kind. Nobody wrote that rule. Training found matrices WQW_Q and WKW_K that produce queries and keys with this property, because resolving it correctly helps predict what comes next (was tired is about the cat, so it predicts purring better than parking).

(Part VII adds one step we have skipped: the scores are divided by dk\sqrt{d_k} before the softmax. With our tiny 4-number vectors it would not change the story.)

#Section 36Mixing: The Weighted Sum of Values

Now the weights do their job. Each token's value vector is scaled by its weight, and the scaled values are added up into one output vector for the asking token:

oi=∑jwij vjo_i = \sum_j w_{ij} \, v_j

Read it out loud: the output for token ii is the sum, over every token jj it can see, of the weight from ii to jj times jj's value. Take toy 3-number values. cat's value is [0.9,0.8,0.1][0.9, 0.8, 0.1], and scaling it by its weight 0.554 gives [0.498,0.443,0.055][0.498, 0.443, 0.055]. sat's value [0.1,0.0,0.7][0.1, 0.0, 0.7] scaled by 0.119 gives [0.012,0.000,0.083][0.012, 0.000, 0.083]. Doing the same for all five and adding them up gives the output [0.540,0.485,0.163][0.540, 0.485, 0.163].

THE OUTPUT FOR “IT” = WEIGHTED SUM OF THE VALUES (TOY 3-NUMBER VALUES)The0.084×0.00.10.0=0.0000.0080.000␠cat0.554×0.90.80.1=0.4980.4430.055␠sat0.119×0.10.00.7=0.0120.0000.083␠because0.095×0.00.20.1=0.0000.0190.010␠it0.148×0.20.10.1=0.0300.0150.015sum0.5400.4850.163mostlycat's value
Figure 1.47Mixing the values. Each value is scaled by its weight and the results are summed. The output for it is dominated by cat's value, with a little of everything else mixed in.

The result is a blend, not a copy of the strongest value. Even a smaller attention weight can contribute information from another token.

#Section 37Why Keys and Values Are Separate

Why have both a key and a value? Couldn't one vector do both jobs?

Look at the box for cat. The label on the outside, the key, might encode "singular animal noun, grammatical subject". That is what helps a pronoun find it. The contents, the value, might encode "furry, purrs, the one who did the sitting". That is what is useful once you have found it. What makes you findable and what you have to offer are different things. A library would be useless if a book's spine label had to be its entire contents.

WHY KEY AND VALUE ARE DIFFERENT VECTORS“␠cat”VALUE (inside the box)furry, purrs, did the sittingKEY (the label)singularanimal noun,subjectwhat makesyou findablewhat you areworth once found
Figure 1.48A token's key is the label that makes it findable; its value is what it contributes once found. Two separate vectors let the model learn each without compromise.

Two separate matrices, WKW_K and WVW_V, let the model learn each role without compromise. Queries and keys must have the same length, because they are dotted together, but values can be a different length, because they are only ever scaled and summed. In standard multi-head attention all three are the same size (64 per head in Finch), but nothing forces it.

Shapes, to scale

Here is the whole computation for one head, as shapes. QQ is T×dkT \times d_k. KK turned on its side, K⊤K^\top, is dk×Td_k \times T. Multiplying them gives S=QK⊤S = QK^\top, a T×TT \times T grid holding one score for every pair of tokens: row ii, column jj is qi⋅kjq_i \cdot k_j. Softmax along each row turns SS into the weight grid WW, still T×TT \times T. Then WW times VV (shape T×dvT \times d_v) gives the output OO, shape T×dvT \times d_v, one row per token again.

SHAPES, DRAWN TO SCALE (T = 7 TOKENS, d_k = d_v = 4, ONE HEAD)Q 7 × 4×Kᵀ 4 × 7=S 7 × 7→ softmax →W 7 × 7×V 7 × 4one score for every pair of tokens: T × T grows with the square of the lengthoutput O = W V has shape 7 × 4: one row per token again
Figure 1.49The shapes of one attention head, drawn to scale for seven tokens and four-number heads. The score grid is T × T, one entry per pair of tokens.

The T×TT \times T grid matters. It grows with the square of the text length: 49 entries for our sentence, a million for a thousand tokens, ten billion for a hundred thousand. Part X is entirely about it.

Self-attention and cross-attention

In self-attention, the version in GPT-style models and in Finch, the queries, keys and values all come from the same sequence: the text looks at itself. In cross-attention, the queries come from one sequence and the keys and values from another. The original 2017 Transformer was built for translation and used cross-attention in its decoder: the sentence being written asked questions of the sentence being translated. Decoder-only models such as GPT, Llama and Finch use only self-attention.

WHERE THE QUESTIONS AND ANSWERS COME FROMself-attentionsame sequence: Qsame sequence: K, VQK3 × 3 = 9 scorescross-attentiontarget sequence: Qsource sequence: K, VQK2 × 4 = 8 scoresa score grid can be rectangular, too
Figure 1.50Self-attention takes Q, K and V from one sequence. Cross-attention takes Q from the target and K and V from the source. Illustrative lengths give 3 × 3 = 9 scores and 2 × 4 = 8 scores; masking, if needed, happens after scoring.

Sharp edges of Q, K and V

Scores are not symmetric. How much it attends to cat is not the same as how much cat attends to it, because the first uses it’s query and cat’s key, and the second uses cat’s query and it’s key. Read attention maps row by row: one row is one token’s point of view.

Tokens attend to themselves. A token’s query is also scored against its own key, and tokens often give themselves a sizeable weight (0.148 for it above). That is normal and useful.

Attention weights are not explanations. A large weight does not prove the model “used” that token for its final answer; many other parts of the model also shape the result. Treat attention maps as clues, not proof.

Biases or no biases. Finch-19 and GPT-2 put biases on the projections. Llama and most modern models drop them. Qwen keeps them on Q, K and V only. Loading weights into code that expects the other choice either crashes or silently gives wrong answers.