Availit World How AI really works, in your language

Lesson 15 of 4615 minFacts checked October 20, 2026

Attention: how tokens look at each other

Attention is the idea that made modern AI work. Each token asks a question, every earlier token holds up a label, and dot products decide who listens to whom. You will compute it by hand, and then see why it becomes expensive at a million tokens.

In this lesson you will

  • Explain queries, keys and values, and what each one is for
  • Compute attention for three tokens by hand: scores, scaling, softmax and the weighted sum
  • Say why language models hide the future from each token (the causal mask)
  • Understand multi-head, grouped-query and latent attention, and why attention gets expensive with long text
On this page
  1. The question each token asks
  2. Queries, keys and values
  3. Attention by hand
  4. No peeking: the causal mask
  5. Many heads, and how they share
  6. The cost of looking at everything
  7. Remember
  8. Check yourself

The question each token asks

Read this sentence: “The animal didn’t cross the street because it was too tired.” What does “it” mean? You know at once: the animal, because streets do not get tired. To understand “it”, you looked back at the other words and picked the one that mattered.

Attention gives a model the same ability. For every token, it computes how much to look at each earlier token, and then mixes their information into its own vector. After attention, the vector for “it” carries information about “animal”.

Try itWhere does each word look?

The bars show how much attention a word pays to the words up to and including itself (illustrative numbers, in the spirit of what real models do). “it” looks mostly at “animal”. Tap other words; notice that no word can look at words after it.

This interactive part needs JavaScript.

Queries, keys and values

Each token’s vector is multiplied by three different learned matrices, giving three new vectors:

  • Query (q): what this token is looking for. Made by the q_proj matrix you counted in the matrices lesson.
  • Key (k): what this token offers to others, as a label to be matched. Made by k_proj.
  • Value (v): the information this token passes on if someone attends to it. Made by v_proj.

The match between a query and a key is their dot product: large when they point the same way. This is why the vectors lesson called the dot product the most important operation in AI.

Attention by hand

Three tokens, “the cat sat”, with tiny 2-number vectors. We work out what the last token, “sat”, takes from the others.

The vectors (already multiplied by the three matrices)
TokenKeyValue
the[0, 1][1, 0]
cat[2, 1][0, 3]
sat[1, 0][2, 2]

The query of “sat” is [1, 2].

Four steps
1. scores = q · k = [2, 4, 1]

[1, 2]·[0, 1] = 2 for “the”, [1, 2]·[2, 1] = 4 for “cat”, [1, 2]·[1, 0] = 1 for “sat” itself.

2. scaled = scores ÷ √2 = [1.41, 2.83, 0.71]

Divide by the square root of the vector length (here 2). This keeps scores from growing too large in long vectors, which would make the softmax all-or-nothing.

3. weights = softmax(scaled) = [0.18, 0.73, 0.09]

“sat” pays 73 % of its attention to “cat”: the one doing the sitting.

4. output = 0.18×[1, 0] + 0.73×[0, 3] + 0.09×[2, 2] = [0.35, 2.38]

A weighted average of the values. This is what gets added to the vector of “sat”.

The same thing as one formula
Attention(Q, K, V) = softmax(Q·Kᵀ ÷ √d) · V

Equation 1 of “Attention Is All You Need” (2017). Q, K and V are matrices with one row per token, so all tokens are computed at once. Kᵀ means K turned on its side, so that every query meets every key.

Quick check

If the key of “the” had been [4, 4], which token would “sat” attend to most?

Show the answer

Answer: “the” Its score would be [1, 2]·[4, 4] = 12, far above cat’s 4, so after softmax almost all the weight would go to “the”.

No peeking: the causal mask

In a language model, a token may only look at itself and the tokens before it. Before the softmax, every score for a later token is set to minus infinity, which softmax turns into exactly 0. This is the causal mask, and the demo above shows it as the greyed-out words.

Why? Because of how training works. A model learns by predicting every next token in a text. If position 5 could see position 6, it could simply copy the answer. With the mask, one pass over a text of 4,096 tokens gives 4,096 honest predictions at once, all in parallel. That parallelism is the transformer’s great advantage over the old recurrent networks.

Many heads, and how they share

A single attention can only look for one kind of thing at a time. So each layer runs several in parallel, each with its own smaller queries, keys and values. These are attention heads. Llama 3.1 8B has 32 heads per layer, each working with vectors of 128 numbers (32 × 128 = 4,096). Their outputs are joined and mixed by the o_proj matrix.

Heads specialise during training. Researchers have found heads that look at the previous token, heads that link a pronoun to its noun, and induction heads, which spot that the current text repeats an earlier pattern and predict that it will continue the same way. Induction heads are a big part of how models learn from examples placed in their prompt.

Keys and values have to be kept in memory for every earlier token (the KV cache, which has its own lesson). Giving every head its own keys and values is expensive, so newer models share them:

Ways to share keys and values
DesignIdeaExample
Multi-head attention (MHA)Every query head has its own key and value headThe original 2017 transformer
Multi-query attention (MQA, 2019)All query heads share one key and value headFastest, with some loss of quality
Grouped-query attention (GQA, 2023)Groups of query heads share a key and value headLlama 3.1 8B: 32 query heads, 8 key-value heads. Qwen3.8-27B: 24 and 4
Multi-head latent attention (MLA, 2024)Keys and values are compressed into one small vector per token, and expanded when neededDeepSeek-V2 and later: 93 % less cache than its earlier 67B model

Query, key or value?

0 of 6 sorted
  • What this token is looking for

    Answer: Query

  • The label other tokens match against

    Answer: Key

  • The information passed on to whoever attends

    Answer: Value

  • Made by k_proj

    Answer: Key

  • Averaged together, using the attention weights

    Answer: Value

  • Dotted with every earlier key

    Answer: Query

The cost of looking at everything

Attention compares each token with every earlier token. For a text of n tokens that is about n² ÷ 2 pairs, in every head of every layer. The cost grows with the square of the length:

Query–key pairs for one head in one layer
Text lengthPairs
1,000 tokensabout 500,000
128,000 tokensabout 8 billion
1,000,000 tokensabout 500 billion

Ten times longer text means a hundred times more attention work.

And all those keys and values must stay in memory while the model writes. For Llama 3.1 8B that is 128 KiB per token, or 16 GiB for a 128,000-token conversation: as much as the model’s weights. This is why long context is one of the hottest research areas, with three main lines of attack you will meet in the long-context lesson:

  • Better kernels such as FlashAttention: the same exact maths, with far fewer trips to memory.
  • Sparse attention: each token looks only at the earlier tokens most likely to matter, as in DeepSeek’s sparse attention and GLM-5.3.
  • Linear attention layers with a fixed-size memory, mixed with a few full attention layers, as in Qwen3.8 and Kimi K3.

Remember

  • Attention lets each token gather information from earlier tokens, weighted by how relevant they are.
  • Each token makes a query (what it wants), a key (its label) and a value (what it passes on). Scores are query·key dot products.
  • softmax(Q·Kᵀ ÷ √d)·V: score, scale, softmax, weighted average of values.
  • The causal mask stops tokens seeing the future, so training makes every prediction in parallel.
  • Many heads run at once. GQA and MLA shrink the key-value memory. Cost grows with the square of the length.

Words to know

Attention
A way for each token to gather information from others, weighted by relevance.
Query
The vector that says what a token is looking for.
Key
The vector that labels what a token offers, to be matched against queries.
Value
The vector of information a token passes on when attended to.
Causal mask
The rule that a token cannot attend to tokens after it.
Attention head
One of several attentions running side by side in a layer, each learning its own job.
Induction head
A head that spots a repeated pattern and predicts it will continue.
GQA
Grouped-query attention: several query heads share one key and value head, to save memory.
MLA
Multi-head latent attention: DeepSeek’s method of compressing keys and values into a small vector.
Encoder and decoder
Models that see the whole text both ways, and models that write and only look back.

Go to the source

This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

What is the attention score between a query and a key?

Show the answer

Answer: Their dot product (then scaled) Scores are dot products, divided by the square root of the vector length before the softmax.

After the softmax, what are the attention weights used for?

Show the answer

Answer: To take a weighted average of the values Each value vector is multiplied by its weight and the results are added up. That mixture is the attention output.

Why do language models use a causal mask?

Show the answer

Answer: So that a position cannot see the token it is meant to predict Without the mask, a position could look at the next token and copy it. The mask keeps every prediction honest, so all of them can be trained in parallel.

Llama 3.1 8B has 32 query heads but only 8 key-value heads. What does that save?

Show the answer

Answer: Memory for the keys and values of every token (the KV cache) With GQA, only 8 sets of keys and values are stored per token instead of 32, so the cache is 4 times smaller.

A text gets 10 times longer. Roughly how much more work does full attention do?

Show the answer

Answer: 100 times Every token compares with every earlier token, so the work grows with the square of the length: 10² = 100.

Lesson complete

Answer every question above to complete this lesson.

Your progress is saved on this device only.

Next lessonThe transformer: putting it all together
Previous lesson All lessons

Choose your language