Notes
The idea
Read this: the cat was hungry, so it. You know instantly that it means the cat. A model has to work that out too, and attention is how. For every token, the model asks which earlier tokens matter right now. Here, it looks back, finds cat a strong match and hungry a weaker one, and pulls in their meaning. Every token does this, in every layer.
- what does "it" refer to?
- you know at once: the cat
- attention is how a model
- works that out: for every token, ask which earlier tokens matter now, then pull in their meaning
- every token, every layer
Query, key, value
Think of a hash map. You bring a key, it must match exactly, and you get one value. Attention is a soft version. Each token produces three vectors. A query: what am I looking for. A key: what do I contain. A value: what I pass on if chosen. The query of it is compared with the key of every earlier token, giving a score for each, and the result is a blend of all their values.
- hash map: key must match exactly, you get one value
- attention: every token has query what am I looking for? key what do I contain? value what do I pass on?
- score = how well query fits key
- result = blend of all values
A worked example
Now the numbers, on a toy context of four tokens: cat, was, hungry, it. Each score is the dot product of the query of it with one key, scaled down by the square root of the vector size. Say the scores are four, two, one and one. Softmax turns them into weights: raise e to each score and divide by the total. Cat gets zero point eight one, hungry zero point one one, and the other two about zero point zero four each, adding up to one.
toy context: cat was hungry it score = query(it) · key, scaled token score e^score weight cat 4.0 54.6 0.81 hungry 2.0 7.4 0.11 was 1.0 2.7 0.04 it 1.0 2.7 0.04 total 67.4 1.00
Blending values
The output for it is a weighted mix of the values: eighty one percent of cat, eleven percent of hungry, and a little of the rest. So the vector for it now carries the meaning of a hungry cat. Same size as before, only richer, and it moves on to the next layer. That is all attention is: score, softmax, blend. Real patterns are messier, but the mechanism is exactly this.
new_it = 0.81 × value(cat)
+ 0.11 × value(hungry)
+ 0.04 × value(was)
+ 0.04 × value(it)
same size as before,
richer content: "it" now
carries "a hungry cat"
score → softmax → blend Where Q, K, V come from
Where do queries, keys and values come from? Each token starts as an embedding, a list of numbers. The model multiplies it by three learned weight matrices, one each for query, key and value. Nobody writes them by hand. Training adjusts them over billions of examples until the scores help predict the next token. Rules like pronouns look for nouns are never programmed. They emerge.
- each token starts as a vector (its embedding)
- query = vector × Wq
- key = vector × Wk
- value = vector × Wv
- Wq, Wk, Wv are learned in training, not written by hand
Many heads
One attention pass can only look for one kind of thing. So each layer runs many heads side by side, each with its own query, key and value weights. One head might link pronouns to nouns, another look at the previous word, another match brackets in code. Their outputs are joined and mixed back into one vector per token. Many questions, asked in parallel.
- a layer runs many heads side
- by side, each with its own
- Wq, Wk and Wv
- head A: links pronouns to nouns
- head B: looks at the last word
- head C: matches code brackets
- outputs joined into one vector
One transformer block
Attention is half of a transformer block. The other half is a feed forward network that processes each token on its own. Attention lets tokens talk to each other, and the feed forward part lets each token think about what it heard. Much of the model's stored knowledge lives in those feed forward weights. Each half adds its result to a running vector instead of replacing it, which is called a residual connection.
x = x + attention(norm(x))
tokens share information
x = x + feedforward(norm(x))
each token processed alone
"x +" is the residual path:
each step adds a refinement,
it never starts from scratch Many layers
A model stacks this block many times, from a few dozen to over a hundred layers, each refining every token's vector a little more. Roughly, early layers handle spelling and grammar, and later layers handle meaning and what should come next. After the last layer, the vector at the last position becomes a score for every token in the vocabulary. That is the list the sampler picks from.
- block 1 → block 2 → … → block N
- early layers: spelling, nearby words, grammar
- later layers: meaning, facts, what should come next
- last layer, last position: a score for every token in the vocabulary → next token
The causal mask
Language models write left to right, so a token may only look back. This is the causal mask. Before the softmax, every score for a later token is set to minus infinity, so its weight becomes zero. In the table, each row can see itself and everything before it, never after. That is also what lets training predict every next token in a sentence at once, without cheating by peeking ahead.
cat was hungry it cat ✓ · · · was ✓ ✓ · · hungry ✓ ✓ ✓ · it ✓ ✓ ✓ ✓ row = token looking column = token looked at future score = −∞ → weight 0
Positional information
Here is a surprise. The attention maths by itself has no sense of order. Dog bites man and man bites dog hold the same tokens, so the scores would match. Position has to be added. Early transformers added a position vector to each embedding. Most models today use rotary position embeddings, called RoPE, which rotate each query and key by its position, so scores reflect how far apart tokens are.
- the score maths ignores order: "dog bites man" and "man
- bites dog" hold the same tokens
- so position is added: early models: add a position vector to each embedding most today: RoPE rotates queries and keys by position so scores see distance
The quadratic cost
Now the cost. Every token scores every earlier token, so n tokens need about n squared scores, in every head of every layer. A thousand tokens means a million scores. A hundred thousand means ten billion. Ten times the prompt means about a hundred times the attention work, while the rest of the model grows only ten times. FlashAttention makes it faster and avoids storing the whole table, but the work still grows with the square.
n tokens, each looks at up to n → ~n² scores per head, per layer context scores 1,000 1 million 10,000 100 million 100,000 10 billion 10× longer → ~100× attention (the rest grows only ~10×)
The KV cache
Generation has two phases. In prefill, the whole prompt goes through the model in one parallel pass, and every token's keys and values, in every layer, are saved. That is the K V cache. In decode, the model makes one token per step, computing only that token's query, key and value and attending to the cached ones. Because earlier tokens cannot see later ones, they never change. So the first token waits for the whole prompt, and the rest stream quickly.
- prefill: the whole prompt in one parallel pass; save every key and value
- decode: one new token a step compute only its q, k, v; attend to the cached ones
- without a cache: redo every earlier token for each new one
Cache memory
The cache is not free. Per token, it holds keys and values for every layer and every key value head. For a mid sized model that is around a hundred and twenty eight kilobytes per token, so a hundred thousand token conversation holds about thirteen gigabytes of GPU memory. Grouped query attention lets several heads share one set of keys and values to shrink it. Cache memory, more than compute, often limits how many users a server handles at once.
per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per number e.g. 2 × 32 × 8 × 128 × 2 bytes = 128 KB per token × 100,000 tokens ≈ 13 GB GQA: heads share K and V, so the cache shrinks
Why it scales
Why did this design win? Older recurrent networks read text one word at a time, which is slow to train, and information from far back faded. A transformer trains on every position at once, using matrix multiplication that GPUs are built for. Any token reaches any earlier token in one step. And because it is one block stacked many times, you can grow it with more layers, width and data, and quality improves fairly predictably. Those are the scaling laws.
- training is parallel: every position at once, unlike older models, word by word
- mostly matrix multiplication, which GPUs do extremely well
- any token reaches any earlier token in a single step
- one block, stacked: grow it with layers, width and data
- quality rises predictably with scale (scaling laws)
Common mistakes
Common mistakes. Thinking the model rereads the whole prompt for every new token. It does not, thanks to the K V cache. Thinking long context is free. Attention grows with the square, and the cache eats memory. Treating attention weights as a full explanation of an answer. They are a clue, not proof. And assuming every position is used equally well. Details in the middle of long inputs often get missed.
- ✗ "it rereads the whole prompt for every new token" → the KV cache prevents it
- ✗ "long context is free" → n² attention + cache memory
- ✗ "attention weights explain the answer" → only a clue
- ✗ "attention = understanding" → it is a weighted average
- ✗ "every position counts the same" → middles get missed
Numbers worth knowing
Numbers worth knowing, all rough. About twenty to over a hundred layers, with tens of heads per layer. Ten times the prompt means about a hundred times the attention work. The K V cache costs roughly a tenth of a megabyte to a megabyte per token. Decode streams at twenty to two hundred tokens a second, while prefill is many times faster per token. And in a dense model, about two thirds of the weights are in the feed forward layers.
layers ~20 to 120+
heads per layer ~16 to 128
attention vs prompt ~n²: 10× → 100×
KV cache per token ~0.1 to 1 MB
decode speed ~20-200 tok/s
prefill many × faster
per token
feed-forward weights ~2/3 (dense)
first token: grows with prompt
later tokens: steady stream Say it like this
How to say it. Each token makes a query, a key and a value. Its query is scored against earlier keys, softmax turns the scores into weights, and the token takes a weighted mix of their values. Many heads and many layers repeat this, with a causal mask so tokens only look back, and rotary embeddings for order. Cost grows with the square of the context, and the K V cache makes each new token cheap.
- "Each token makes a query, key and value. Its query is scored against earlier keys, softmax gives weights, and it takes a weighted mix of their values. Many heads, many layers, a causal mask, RoPE for order. Cost is n² in context; the KV cache makes decoding cheap."