Inside attention: queries, keys, values and multi-head attention
Self-attention lets every token look at every other token and decide how much each one matters. For each token the model creates three small vectors: a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?). Matching queries with keys gives attention scores, and the scores decide how much of each value to blend in.
Everyday analogy
A library search. Your question is the query, the labels on the book spines are the keys, and the contents of the books are the values. You read most from the books whose labels best match your question.
Example
In "The cat sat on the mat because it was tired", the token it gives most of its attention to cat, so the model understands who was tired.
Attention in four steps
- Score: compare the token's query with every key (a dot product).
- Scale: divide by the square root of the key size, so the numbers don't get too large.
- Softmax: turn the scores into percentages that add up to 100%.
- Blend: mix the values using those percentages. The result is a new, context-aware version of the token.
Attention(Q, K, V) = softmax( Q·Kᵀ / √dₖ ) · V
Multi-head attention
Instead of one attention calculation, the model runs several heads in parallel, each with smaller vectors. One head may track grammar, another meaning, another links between distant words. Their outputs are joined and mixed back together, so the model sees several kinds of relationship at once.
Positional encoding: giving words an order
Attention on its own ignores word order: "dog bites man" and "man bites dog" would look the same. So position information is added to each token.
| Type | Used in |
|---|---|
| Fixed sine and cosine waves | The original 2017 transformer |
| Learned positions | BERT, GPT-2 |
| Relative positions | T5 |
| RoPE (rotary position encoding) | Llama and many modern LLMs; helps with long context windows |
Encoder, decoder or both?
| Encoder (e.g. BERT) | Decoder (e.g. GPT, Claude, Llama) | |
|---|---|---|
| Reads text | In both directions at once | Left to right; masked so it can't peek at future words |
| Best for | Understanding: search, classification | Generating: chat, writing, code |
| Both together | Encoder-decoder models such as T5 and the original transformer, often used for translation |
Remember: attention compares every token with every other token, so the work grows with the square of the text length. That is why very long context windows are expensive.
Try it yourself
About 10 minFind what attention links
- Ask an AI chatbot: In 'The trophy didn't fit in the bag because it was too small', what does 'it' refer to?
- Change small to big and ask again.
- Ask it to explain which words gave it the clue.
What you should see: One word changes what "it" points to. That linking of words is exactly what attention does.
Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.