AI ENGINEERING · LLM FOUNDATIONS · FOUNDATIONS · 5 OF 35

Attention and Transformers Explained Simply: Queries, Keys, Values and the KV Cache

How a transformer lets every token look back at earlier tokens to decide what matters. Queries, keys and values as a soft lookup, a worked softmax over attention scores, many heads and many layers, the causal mask, positional information with RoPE, why attention cost grows with the square of the context, how the KV cache makes generation fast, and why this design scales.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Query meets keys
  • softmax weights
  • blend values
  • heads and layers
  • look back only
  • n² cost
  • KV cache

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.

The cat was hungry, so it…
  • 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.

A soft lookup
  • 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.

Scores for "it"
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.

The new vector for "it"
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.

Where Q, K and V come from
  • 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.

Multi-head attention
  • 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.

One transformer block
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.

Stack the blocks
  • 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.

Causal mask
         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.

Where order comes from
  • 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.

Cost grows with n squared
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, then decode
  • 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.

KV cache size
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.

Why transformers won
  • 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.

Common mistakes
  • ✗ "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.

Ballpark numbers
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.

In the interview
  • "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."

Interview questions

Q1What is attention in a transformer, in plain terms?

For each token, the model scores how relevant every earlier token is, turns the scores into weights with softmax, and replaces the token's vector with a weighted mix of those tokens' information. It is how "it" picks up the meaning of "the cat".

Q2What are queries, keys and values?

Three vectors computed from each token by learned weight matrices. The query says what the token is looking for, the key says what a token offers to be matched on, and the value is what it passes on. Scores come from query-key dot products; the output is a weighted sum of values.

Q3Why use multiple attention heads?

One head produces one set of weights, so it can only focus on one kind of relationship at a time. Many heads with their own weights can track different things in parallel, such as coreference, the previous word or syntax, and their outputs are combined.

Q4What does the causal mask do?

It sets the scores for future positions to minus infinity before softmax, so each token can only attend to itself and earlier tokens. That matches left-to-right generation and lets training predict every next token in a sequence in parallel.

Q5How do transformers know word order?

Attention itself is order-agnostic, so position is injected. Early models added position vectors to embeddings; most current models use rotary position embeddings (RoPE), which rotate queries and keys by position so scores depend on relative distance.

Q6Why is attention quadratic in sequence length?

Every token computes a score against every earlier token, so n tokens need on the order of n squared scores per head per layer. Ten times the context means roughly a hundred times the attention work, which is why long prompts are slow and expensive.

Q7What is the KV cache and why does it help?

During generation the keys and values of earlier tokens never change because of the causal mask, so they are stored after prefill and reused. Each new token only computes its own query, key and value, instead of recomputing the whole prefix. The trade-off is GPU memory that grows with every token.

Q8Why did transformers replace recurrent networks?

They process all positions in parallel during training, map onto GPU-friendly matrix multiplications, connect any two tokens in one step instead of a long chain, and scale predictably as you add layers, width and data.