Lab

How attention decides what matters

See how a token chooses which earlier tokens to look at, step by step, and why grouped-query attention shrinks the KV cache.

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

10 of 20 tokens · head size 12
Preset
Head
View
<s>8%
my0%
friend0%
zorblat0%
kix90%
came0%
over0%
.0%
later0%
zorblat0%

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.

Rows are queries (the token doing the looking), columns are keys (the tokens being looked at). Each row sums to 100%. Hatched cells are the future, hidden by the causal mask. Click a row or a token to pick a query. Weights are built by hand, not trained: see the sections below.

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.

Attention(Q,K,V)=softmax(QKTd+M)V

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

d = 12 · √d = 3.464
Head
Query token
1.00

1. Query vector q = x · W_Q for “more”

0.04.60.00.00.00.00.00.00.00.03.50.0

2–4. Score every key, scale, mask, softmax weight = softmax(q·k ÷ √12 ÷ T)

Keykq·k÷ √12Weight
<s>12.123.503.9%
the0.000.000.1%
more20.786.0047.7%
you0.000.000.1%
read0.000.000.1%
,0.000.000.1%
the0.000.000.1%
more20.786.0047.7%
you0.00masked0.0%
know0.00masked0.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.0
Top key
more 48%
Spread (entropy)
1.26 bits
max 3.00 bits for 8 keys
Output carries
more
cosine 1.00
Every number is computed live from the hand-built weights. Future keys are masked: their score becomes −∞, so softmax gives them exactly 0.

Five 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

seed 1 · 500 random pairs per size
128
Var(q·k)
…
theory 128
Var(q·k ÷ √d)
…
theory 1
0.11101001.0k10100head size dvariance of the scored = 128
raw q·kq·k ÷ √dtheory: d
key 1 0.00.0%
key 2 7.30.0%
key 3 12.02.5%
key 4 7.40.0%
key 5 15.697.5%
key 6 −9.80.0%
key 7 4.80.0%
key 8 −18.20.0%
key 1 0.07.2%
key 2 0.613.8%
key 3 1.120.8%
key 4 0.713.9%
key 5 1.428.8%
key 6 −0.93.0%
key 7 0.411.1%
key 8 −1.61.4%
Entropy, raw
0.18 bits
top key 97.5%
Entropy, scaled
2.64 bits
top key 28.8%
Most spread possible
3.00 bits
8 keys, equal weights
Query and key entries are drawn from a standard normal distribution (mean 0, variance 1). The dashed line is the theory: Var(q·k) = d.

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

12 tokens
Mask
4
swim
3
Pairs scored
42
54% of full causal (78)
“swim” sees
4 tokens
position 11, one layer
Reach after 3 layers
9 tokens back
3 × (4 − 1): each layer reads what the last gathered
<s><s>kiakiaoraora,,thethetidetideisisoutoutsosothethekidskidsswimswim
Filled cells are allowed query–key pairs. Every mask here is causal: nobody sees the future. A sliding window also forgets the distant past; global tokens are seen by everyone.

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

step 8 of 14
8
K,V rows computed so far
8
without a cache: 36
Scores this step
8
new query × every cached key
Same cache in Llama 3.1 8B
1 MiB
128 KiB per token, f16
KV<s>wedrovetoōhakuneforthesnowq
Each slab is one token’s key (K) and value (V) rows. The newest token’s K and V (amber slab) are computed once and laid on top; every earlier slab is read back from the cache, never recomputed. While Play runs, the dot carries the new token’s query (q) down the cache and outlines each key in turn as it is scored. Rows are the real K and V of the previous-token head; shade shows the size and sign of each number, as in the strips of “One query, step by step”.

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:

bytes per token=2×layers×KV heads×head size×bytes per value

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

32 layers · 32 query heads · 8 KV heads · head size 128
Attention
Cache precision
query heads (32)key/value heads (8)
MHA, per token
512 KiB
2 × 32 × 32 × 128 × 2 B
GQA, per token
128 KiB
2 × 32 × 8 × 128 × 2 B
MQA, per token
16 KiB
2 × 32 × 1 × 128 × 2 B
GQA keeps
a quarter of MHA
8 of 32 KV heads
Per token (f16)MHAGQAMQA
Llama 3.1 8B512 KiB128 KiB16 KiB
Llama 3.1 70B2.5 MiB320 KiB40 KiB
Mistral 7B v0.3512 KiB128 KiB16 KiB
Qwen2.5 7B392 KiB56 KiB14 KiB
Gemma 2 9B672 KiB336 KiB42 KiB
bytes per token = 2 × layers × KV heads × head size × bytes per value. GQA is each model as published; MHA and MQA are the same model imagined with 32 or 1 KV heads. Sizes are in binary units (1 KiB = 1,024 bytes).

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