When a language model reads “my friend Zorblat Kix came over. Later Zorblat…”, how does it know the next word is probably “Kix”? It has never seen the name before, so it cannot have memorised it. It has to look back through the text, find the earlier “Zorblat”, and copy what came after it.
The part of a transformer that does the looking back is called attention. Every token asks a question, every earlier token offers an answer, and the closest matches win most of the token’s attention. A model repeats this across dozens of layers and heads.
This page shows attention working on real numbers. Instead of trained weights, we built the heads below by hand, each to do one job that researchers have found heads doing inside trained models. By the end you will be able to see why a head looks where it does, why attention scores are divided by √d, and why the memory for “what was said earlier” grows with every token.
Before this: How a model picks the next token explains softmax, How text becomes tokens explains tokens, and Meaning as a map shows the vectors a model gives each token.
Attention map
Induction. Finds where the current word appeared before and looks at the word that came next. A second-layer head: it reads what the previous-token head wrote.
“zorblat” (position 9) gives 90% of its attention to “kix” (position 4). Its output carries “kix” (cosine 1.00): a guess that “kix” comes next.
Attention is a soft lookup
Think of each token as carrying three short vectors, all computed from the same internal state by three different weight matrices:
- a query, q: what this token is looking for,
- a key, k: what this token can be found by,
- a value, v: what this token hands over if it is chosen.
To decide where to look, a token takes the dot product of its query with every earlier key. A big dot product means “this key matches what I am looking for”. These attention scores are divided by √d (d is the head size, 12 here), turned into weights that add up to 1 with softmax, and used to average the values. It is the same softmax that turns a model’s logits into next-token probabilities in how a model picks the next token. Real attention has no temperature dial: dividing by √d plays that role. The next figure adds one anyway, so you can see what sharpening does.
M is the mask: 0 where looking is allowed, −∞ where it is not. In a model that writes text left to right, a token may not look at the future, so every cell above the diagonal is −∞ and gets exactly zero weight after softmax.
The next figure runs that formula for one query at a time. Every number is computed live from the hand-built weights.
One query, step by step
1. Query vector q = x · W_Q for “more”
0.04.60.00.00.00.00.00.00.00.03.50.02–4. Score every key, scale, mask, softmax weight = softmax(q·k ÷ √12 ÷ T)
| Key | q·k | ÷ √12 | Weight |
|---|---|---|---|
| <s> | 12.12 | 3.50 | 3.9% |
| the | 0.00 | 0.00 | 0.1% |
| more | 20.78 | 6.00 | 47.7% |
| you | 0.00 | 0.00 | 0.1% |
| read | 0.00 | 0.00 | 0.1% |
| , | 0.00 | 0.00 | 0.1% |
| the | 0.00 | 0.00 | 0.1% |
| more | 20.78 | 6.00 | 47.7% |
| you | 0.00 | masked | 0.0% |
| know | 0.00 | masked | 0.0% |
5. Weighted sum of values output = Σ weight × v (each v carries its word’s identity)
0.01.00.00.00.00.00.00.00.00.00.00.0Five heads: four built by hand, one random
A real attention layer runs many heads side by side: 32 in Llama 3.1 8B. Each head has its own W_Q, W_K and W_V, so each asks its own question of the same tokens and gets its own pattern. Their outputs are joined and mixed by one more matrix, W_O, before the next layer. The All heads view in the first figure is this idea in miniature: five heads, one sentence, five different patterns. The “query heads” and “KV heads” later on this page are these heads.
Each token in our toy model is a list of 26 numbers (its residual stream): a constant 1, a flag that is 1 only for the first token, two pairs of sine and cosine that encode position, ten numbers for the word’s identity (real models learn these vectors; see Meaning as a map), and ten empty slots that a head can write into. Every head projects those 26 numbers down to vectors of 12 with its own W_Q, W_K and W_V. All the patterns come from what those matrices pick out.
Previous token. The query matrix takes the position code of token i and rotates it back by one step, so it becomes the position code of i − 1. The key matrix copies each token’s position code unchanged. The dot product is largest where the two codes agree: at the token just before. It never looks at the words at all. Trained models have heads like this too, and the induction head below depends on one.
First token (sink). Every query asks the same thing (“are you the first token?”), via the constant 1, and only <s> answers yes, via the first-token flag. So every row puts 90% or more of its weight on <s> in short sentences. Xiao and colleagues (2023) found that trained models pour a large share of attention onto the first few tokens even when those tokens mean nothing, and called them attention sinks. Because softmax must add up to 1, a head needs somewhere harmless to put attention when it has nothing to do. In our model <s> carries no word, so looking at it adds almost nothing to the output.
Same word. Query and key are both the word’s identity, so a word’s query matches every copy of itself, earlier copies included. A small pull towards <s> gives it somewhere to rest when there is no copy.
Induction. This one needs two layers. First, the previous-token head writes “the word before me” into each token’s empty slots. Then the induction head’s query asks “who has my word in their ‘word before me’ slot?” In “… zorblat kix … zorblat”, the token “kix” has “zorblat” in that slot, so the second “zorblat” attends to “kix”, and the value it copies is “kix”: a prediction of the next word. Olsson and colleagues (2022) found heads doing exactly this in trained transformers, made from a previous-token head working with a later head. They present evidence, much of it early and indirect for large models, that induction heads drive much of in-context learning: the ability to continue patterns that appear only in the prompt.
Why divide by √d
The √d in the formula looks like a detail, but leave it out and attention stops working well in large models.
If the entries of q and k are random with variance 1, then q·k is a sum of d products, each with variance 1. The variance of the sum is d. In a real model d is 64 to 256, so raw attention scores are typically spread over ±10 or more. Softmax then exaggerates those differences: almost all the weight lands on the single largest score, and training gets very small gradients for every other key. Dividing by √d brings the variance back to 1, whatever the head size.
Why divide by √d
Softmax of raw scores, d = 128
Softmax of scaled scores (÷ √128 = ÷ 11.3)
Masks decide who may look at whom
A causal mask scores every pair (query, earlier key): 78 pairs for 12 tokens, and about n²/2 in general. That quadratic growth is why long contexts are expensive. Many models cut it down by limiting how far back a head can look.
Masks: who may look at whom
Sharing keys and values
When a model writes text, it does not recompute the keys and values of the words it has already processed. It keeps them in the KV cache and only computes them for the new token. The new token’s query is then scored against every cached key.
The KV cache during generation
The cache saves a great deal of compute: after 12 tokens it has computed 12 rows of keys and values instead of 78. But it costs memory, and the memory grows with every token. For each token it stores a key and a value for every layer and every key/value head:
The original transformer gave every query head its own keys and values (multi-head attention, MHA). Shazeer (2019) suggested sharing one key/value head across all query heads (multi-query attention, MQA). Grouped-query attention (GQA, Ainslie and colleagues, 2023) sits in between: a few groups of query heads, each sharing one key/value head. All five models below use GQA.
Sharing keys and values: MHA, GQA, MQA
| Per token (f16) | MHA | GQA | MQA |
|---|---|---|---|
| Llama 3.1 8B | 512 KiB | 128 KiB | 16 KiB |
| Llama 3.1 70B | 2.5 MiB | 320 KiB | 40 KiB |
| Mistral 7B v0.3 | 512 KiB | 128 KiB | 16 KiB |
| Qwen2.5 7B | 392 KiB | 56 KiB | 14 KiB |
| Gemma 2 9B | 672 KiB | 336 KiB | 42 KiB |
DeepSeek-V2 goes further with multi-head latent attention (MLA): it stores one small compressed vector per token and layer and rebuilds the keys and values from it. Its authors report a KV cache 93.3% smaller than their earlier 67B model; we do not model it here.
What this means for local AI
- GQA keeps a quarter of the cache. Llama 3.1 8B shares each of its 8 KV heads between 4 query heads, so every token of context costs a quarter of what MHA would. That saving is a big part of why long contexts are practical on home hardware.
- How much fits on your machine depends on the weights plus this cache: Will it run on my machine? works it out for your hardware. Storing either at lower precision is quantisation.
- Compare models by their KV heads, not just their size. Gemma 2 9B uses head size 256, so it stores 336 KiB per token at
f16, more than double Llama 3.1 8B. Qwen2.5 7B stores 56 KiB. Similar sizes can hide a sixfold difference. - Attention sinks matter for long chats. Runtimes that drop old tokens to make room should keep the first few. Throwing away the sink makes some models fall apart.
What we simplified
- Hand-built, not trained. Every weight is set by hand to demonstrate a mechanism found in trained models. Real heads are learned, overlap in what they do, and are rarely this clean.
- Word tokens. Real models split text into subword tokens: see How text becomes tokens. Our toy tokeniser splits on spaces and punctuation, lower-cases everything, and stops at 20 tokens.
- Tiny vectors. 26 numbers per token and head size 12, compared with thousands and 128 in real models. Our ten identity numbers give each of up to 20 words its own direction: two different words are either unrelated (at right angles) or exact opposites, so they never half-match. Real models squeeze far more words than dimensions, so their words do overlap partly.
- Missing parts. No layer normalisation, no feed-forward layers, and no output projection except the single write that feeds the induction head. The real models below have 28 to 80 layers, each with many heads.
- Positions. We use fixed sine and cosine pairs. Most current models use rotary position embeddings (RoPE), which rotate q and k by position in a similar spirit.
- Cache sizes. The formula counts keys and values only; Gemma 2’s sliding-window layers and runtime tricks can shrink the real cache.
Next: Will it run on my machine? sizes this cache, together with the weights, for your hardware.
Inspired by, and worth your time
- Transformer Explainer by Polo Club of Data Science, Georgia Tech
- The Illustrated Transformer by Jay Alammar
- A Visual Guide to Attention Variants in Modern LLMs by Sebastian Raschka
- LLM Visualization by Brendan Bycroft