The long read
Attention: how a model uses the rest of your text
You paste a long tenancy agreement into a chat and ask whether your landlord can keep the deposit. The reply quotes a clause from page two. To do that, the model had to link your question to text far back in the chat. The step inside the model where tokens take in information from other tokens is called attention. This piece shows what it does, with numbers you can check by hand, and why it shapes the cost, memory and speed of long chats.
Key ideas, in nine lines
- Attention updates each token's list of numbers with information from other tokens, so one word can carry different meanings in different texts.
- Each head makes a query, a key and a value for every token; query-key scores become attention weights that add up to 1, and those weights mix the values.
- In a chat model, a token may use only itself and earlier tokens; this rule is the causal mask.
- Each layer runs many attention heads, joins their outputs back to the token's list length, then runs a feed-forward step.
- Attention ignores word order unless position information is added; many models turn queries and keys by position (RoPE).
- With full attention, every token is compared with every earlier one, so twice the tokens means about four times the comparisons; sliding-window layers and total work grow less.
- The KV cache keeps earlier tokens' keys and values in each layer, so a longer conversation needs more memory.
- A model's config.json lists its layers, query heads, key-value heads and any sliding window; fewer key-value heads mean a smaller cache.
- Names with “attention” in them solve different problems, such as FlashAttention computing faster and PagedAttention storing the cache, and several can be in use at once.
No code or AI account is needed. The sentences and numbers in the worked examples are invented illustrations; the configuration excerpt is real and dated. Select text to keep a pencil note in this browser.
What attention does
Before a model works on your text, the text is cut into tokens, small pieces such as a word or part of a word. Each token is swapped for a long list of numbers called an embedding. That starting list depends only on which token it is: “bank” gets the same list in “river bank” and in “savings bank”.
The meaning still has to change with the sentence. The 3Blue1Brown lesson uses “mole”: an animal, a unit in chemistry, a spot on the skin. Its starting list is the same in all three. In a transformer, the design behind most current language models, “It's only in the next step of the transformer, the attention block, when the surrounding embeddings have the chance to pass information into the mole embedding” (3Blue1Brown on attention).
The one sentence to keep: attention is the step where each token's list of numbers is updated with information from other tokens in the text. After it, “bank” next to “river” has a different list from “bank” next to “savings”.
Attention is arithmetic, not focus in the human sense: each token mixes in information from others in measured amounts called attention weights. These are worked out afresh for every text, unlike the model's own weights, the learned numbers fixed in training before release. The Transformer paper calls the result “a weighted sum of the values”. A transformer repeats this step in stacked rounds called layers. You can now say what attention does.
A question, a label and a content
For attention, each token's long list is used to make three shorter lists. A model does this many times side by side, in units called heads, which a later section explains; for now, follow one head. A loose way to picture the three lists:
- Query. A question: what this position is looking for in other tokens.
- Key. A label: what this token can offer to a question.
- Value. The content this token passes on when it is drawn on.
The model learned how to make these lists during training, the long process before release in which its numbers were adjusted on huge amounts of text. Each position follows four steps, worked in full in Figure 1:
- Score. Compare this position's query with each allowed key. A bigger score is a better match.
- Scale. Divide each score by the square root of the list length, so long lists do not give huge scores.
- Weigh. A rule called softmax turns the scores into weights that add up to 1, like the next-token probabilities in the chatbot piece.
- Mix. Multiply each value by its weight and add. The result is this head's output, a short list.
Figure 1 · Illustration · One head, three tokens, worked by hand
The text is three tokens: “the”, “river”, “bank”. We follow one head at the last position, “bank”. In this toy head, queries and keys hold 4 numbers and values hold 2. In the real model shown later, each head's lists hold 64 numbers, while a token's own list holds 2,880. These numbers are invented to fit in your head.
Given: the query for “bank” is [2, 2, 0, 0]. The keys are “the” [0, 0, 1, 0], “river” [1, 1, 0, 0] and “bank” [0, 1, 0, 0]. The values are “the” [0, 0], “river” [10, 0] and “bank” [5, 5]; pretend a value's first number means “about water” and its second “about money”.
- Score. For each key, multiply it number by number with the query and add the four products. For “river”: 2 × 1 + 2 × 1 + 0 × 0 + 0 × 0 = 4. Done the same way, “the” scores 0 and “bank” scores 2.
- Scale. Divide each score by 2, the square root of the list length 4. The scores become 0, 2 and 1.
- Weigh. Raise the number e, about 2.718, to each scaled score (a calculator's eˣ key): 1, 7.39 and 2.72. Add them: 11.11. Divide each by that total: 0.09, 0.67 and 0.24, which add up to 1.
- Mix. Multiply each value by its weight and add: 0.09 × [0, 0] + 0.67 × [10, 0] + 0.24 × [5, 5] = [7.9, 1.2]. This head's output leans towards water.
Notice three things. “river” gets most of the weight because its key best matches the query. “the” still gets a little, because softmax never gives exactly zero. And “bank” draws on itself. Real lists carry no labels such as “about water”, and [7.9, 1.2] is only one head's output: the heads section shows how it reaches the token's own list.
Going deeper: where the three lists come from
Each token's list is multiplied by three grids of learned numbers to make its query, key and value. The same grids serve every position in that layer, and they are part of the model's parameters, the learned numbers it stores (also called weights). The comparison itself is fixed arithmetic called a dot product. The paper's recipe is to “compute the dot products of the query with all keys, divide each by” the square root of the key length, “and apply a softmax function to obtain the weights on the values” (Attention Is All You Need).
Values need not be the same length as queries and keys; the paper names them separately, as “queries and keys of dimension” dk and “values of dimension” dv. The paper's reason, offered as a suspicion, is that with long lists “the dot products grow large in magnitude”, pushing softmax into a range where training learns very slowly.
You can now trace one position from scores to weights to a mixed value, and check every number with a calculator.
Only earlier tokens: the causal mask
A chat model writes one token at a time, and each token must be predicted without seeing what follows. So a token may use itself and earlier tokens, never later ones: the causal mask, also called masked self-attention. In the Transformer paper's decoder, the part that writes output, attention layers “allow each position in the decoder to attend to all positions in the decoder up to and including that position” (Vaswani and colleagues).
| Position | the | river | bank |
|---|---|---|---|
| the | ✓ | ✗ | ✗ |
| river | ✓ | ✓ | ✗ |
| bank | ✓ | ✓ | ✓ |
Read each row as one position asking. A tick means it may use that column's token; a cross means the mask hides it. The ticks form a triangle, 6 of 9 cells; Figure 1 worked the bottom row. Hidden scores are set to minus infinity before softmax, so their weights are exactly zero.
Do not confuse this with the loss mask in fine-tuning, extra training that teaches a finished model a behaviour. The causal mask decides which tokens a position may use as context. Loss masking decides which predictions count towards the training penalty. Some runs score only the assistant's reply: the prompt is still read through the causal mask, just not scored. Others score every token. The causal mask applies in both.
Going deeper: two other kinds of mask
Not every model is causal. The original Transformer also had an encoder, the half that reads the input for translation, and there “Each position in the encoder can attend to all positions in the previous layer of the encoder.” It sees both sides of each word.
In code you will also meet a setting called the attention mask. Hugging Face's glossary describes it as “an optional argument used when batching sequences together”: it hides padding added to make texts the same length. Libraries apply it alongside the causal rule (Hugging Face glossary).
You can now draw this grid for any short sentence and say which tokens each position may use.
Many heads, many layers
One head gives one pattern of connections. Models therefore run many heads side by side, each with its own learned grids, so different heads can pick up different relations. GPT-3 “uses 96 attention heads inside each block” (3Blue1Brown); gpt-oss-20b, the model in Read the attention lines of a config, has 64 per layer.
Each head ends with a short output for each token, like Figure 1's [7.9, 1.2]. The outputs “are concatenated and once again projected”, in the paper's words: joined end to end, then multiplied by one more learned grid that brings them back to the token's list length. In gpt-oss-20b, 64 heads of 64 numbers make 4,096, which the grid turns into 2,880 (gpt-oss model card). That change is added to the token's list. Models stack many layers, gpt-oss-20b 24 of them, each run in this order:
- Attention. Each token takes in information from the tokens it may use, through many heads; their joined, resized output is added to its list.
- Feed-forward. Each token's list is transformed on its own, with no mixing between tokens.
- Hand on. The updated lists go to the next layer. After the last layer, the final position's list becomes the next-token scores.
The feed-forward step, also called the MLP, “is applied to each position separately and identically”. It holds most of the parameters, the learned numbers stored in the model: the gpt-oss model card lists 0.64 billion for attention in gpt-oss-20b and 19.12 billion for its feed-forward blocks. Those blocks are a mixture of experts: each layer holds 32 of them, and each token uses 4.
A picture of attention weights is not an explanation of why the model answered as it did. One weight shows how much one head mixed in one token at one layer, among dozens of heads and layers, with the feed-forward steps left out. The step-by-step reasoning text some models show before answering needs the same caution.
Going deeper: the debate about attention as explanation
Jain and Wallace concluded that “standard attention modules do not provide meaningful explanations and should not be treated as though they do”. Wiegreffe and Pinter replied that this “depends on one's definition of explanation”. Both tested 2019 models, not today's chatbots.
You can now name the parts of a layer, say how the heads' outputs reach the token's list, and say what an attention picture cannot show.
How word order gets in
The arithmetic so far ignores order: a score compares a query with a key, and nothing in that sum says where the key sits. In one attention step with no position information, “said” in “dog bites man, said Ana” would get exactly the same mix as in “man bites dog, said Ana”. The Transformer paper says the model “must inject some information about the relative or absolute position of the tokens”.
The original design added a position pattern to each token's starting list. Many current models, gpt-oss-20b among them, instead use rotary position embeddings, RoPE: each query and key is turned by an amount set by its position, so a score depends on how far apart two tokens are. The RoPE paper “encodes the absolute position with a rotation matrix”; Raschka's architecture comparison (April 2026) notes the shift “from absolute to rotational (RoPE)”. More in Positional encoding.
Knowing positions is not using every position equally well: models can still miss a fact in the middle of a long text (effective context length). You can now say how order gets into the calculation.
Why long inputs cost more
Look back at the triangle. With full causal attention, each position compares its query with its own key and every earlier key. Three tokens need 3 + 2 + 1 = 6 comparisons; n tokens need n × (n + 1) ÷ 2, for one head in one layer.
| Tokens | Comparisons per head, per layer, full attention |
|---|---|
| 3 | 6 |
| 1,000 | 500,500 |
| 2,000 | 2,001,000 |
| 4,000 | 8,002,000 |
Doubling the input from 1,000 to 2,000 tokens multiplies those comparisons by about four: twice as many positions, each looking back about twice as far. A sliding-window layer differs. Once its window is full (128 tokens in the model in the config section), each new token adds a fixed number of comparisons, so its total grows only in step with the length.
Comparisons are work; holding their scores is memory, a separate cost. Standard attention “materializes the full attention matrix in memory”, says Hugging Face's attention backends guide, so that memory also grows with the square. FlashAttention gets the same result without storing the whole table; its paper reports memory “linear in sequence length”. The comparisons remain.
This work happens in two phases, which the inference guide separates:
- Prefill. The whole prompt's triangle is computed at once, before the first token appears, so a longer prompt delays the start (time to first token).
- Decode. Each new token adds one row. With full attention it compares one query with every key so far, so each step has more cached keys and values to read than the last.
So with full attention a long chat costs more twice over: a bigger triangle before the reply, and a longer row for every token of it. You can now say when twice the text means four times the comparisons, and when it does not.
Going deeper: the rest of the model grows more slowly
Making queries, keys and values, and the feed-forward step, happen once per token, so their work only doubles when the input doubles. The comparisons grow with the square. Total work therefore rises by between two and four times, and which part dominates depends on the model's size and the length. Counting arithmetic operations under its stated training assumptions, the book How to Scale Your Model finds that attention's comparisons outweigh the rest only once the text is more than eight times longer than each token's list. For lists of about 8,000 numbers, that is about 64,000 tokens.
What is saved between steps
During decode, rebuilding every earlier token's key and value at each step would waste effort, and the causal mask makes it unnecessary: an earlier token never sees later ones, so its keys and values never change. Hugging Face's caching guide: “Once a token is processed, its representation never changes with respect to future tokens”. So the serving engine, the software that runs the model for its users, keeps them in the key-value cache, or KV cache.
| Item | At each new step |
|---|---|
| Earlier keys and values, every layer | Read from the cache, not recomputed |
| New token's query, key and value | Computed in every layer |
| Scores and weights | Computed afresh: new query against every saved key |
| Mix and feed-forward step | Computed for the new token |
| New key and value | Added to the cache for the next step |
Old queries are never needed again, and attention weights are not stored, since each new query produces fresh ones. So “saved attention calculations” means saved keys and values.
The cache trades memory for speed, and the memory grows: every token adds a key and a value in each layer, once per key-value head, a set of keys and values that several heads share (the config section counts them). Twice the conversation means twice the cache; two conversations at once hold two caches. More in Why a longer chat can need more memory.
Within one reply, the engine keeps the cache from token to token. Your next chat message is a new request: its earlier work is reused only if the server kept it and the prompt starts with exactly the same tokens, which is called prefix caching (Reuse the beginning; prompt caching). The cache is working data, not your chat history. You can now say what the cache stores and why memory grows.
Read the attention lines of a config
Open-weight models, whose learned numbers anyone can download, come with a small file, config.json, recording the model's shape. Here are the attention lines of gpt-oss-20b, released by OpenAI in August 2025, as published on Hugging Face when checked on 19 November 2026 (repository last changed 26 August 2025).
Figure 2 · Real excerpt · gpt-oss-20b config.json
"head_dim": 64
"hidden_size": 2880
"layer_types": ["sliding_attention", "full_attention", ...]
"max_position_embeddings": 131072
"num_attention_heads": 64
"num_hidden_layers": 24
"num_key_value_heads": 8
"sliding_window": 128
| Field | What it tells you |
|---|---|
| num_hidden_layers | 24 layers, each attention then feed-forward |
| num_attention_heads | 64 query heads in every layer |
| num_key_value_heads | 8 key-value heads, each shared by 64 ÷ 8 = 8 query heads |
| head_dim | 64 numbers in each head's query, key and value |
| hidden_size | 2,880 numbers in each token's own list |
| layer_types, sliding_window | 12 layers see the latest 128 tokens; 12 see all |
| max_position_embeddings | Positions up to 131,072 tokens |
Now the count that matters for memory. In each full-attention layer, every token saves a key and a value for each of 8 key-value heads, 64 numbers each: 2 × 8 × 64 = 1,024 numbers per token per layer. If all 64 query heads had their own, it would be 2 × 64 × 64 = 8,192, eight times as many; that saving is what grouped-query attention buys. The sliding layers need only the latest 128 tokens, so their cache can stop growing.
Going deeper: what the model card adds
The gpt-oss model card agrees: attention blocks “alternate between banded window and fully dense patterns”, “where the bandwidth is 128 tokens”, with grouped-query attention and “8 key-value heads”. It uses rotary position embeddings and extends “the context length of dense layers” to 131,072 tokens with a method called YaRN. YaRN is “a compute-efficient method to extend the context window” of RoPE models, which otherwise “fail to generalize past the sequence length they were trained on”. The config records it under rope_scaling, with an original length of 4,096.
Bytes, the units of computer memory, depend on the number format the engine uses for the cache, meaning how many bytes each stored number takes; this file does not state it. Estimate the KV cache carries the counts through. The larger gpt-oss-120b has 36 layers; its other attention lines match these. You can now find the attention lines in a config and say what each changes.
Sort the names by the problem they solve
Many names contain “attention”. Sort them by the problem each solves. Similar names are not alternatives, and a model and its serving engine can use several at once.
| Name | Problem it solves, and where it is set |
|---|---|
| Full attention | Which tokens connect: all earlier ones. Set in the model's design. |
| Sliding-window attention | Which connect: only the latest few. Set in the model's design. |
| Sparse attention | Which connect: a selected subset. Set in the model's design. |
| FlashAttention | Same result, computed faster. Set in how the calculation is run. |
| Multi-query and grouped-query attention | Smaller cache: heads share keys and values. Set in the model's design. |
| Multi-head latent attention | Smaller cache: keys and values compressed. Set in the model's design. |
| PagedAttention | Cache stored in blocks, less waste. Set in the serving engine. |
| RadixAttention | Shared beginnings reused across requests. Set in the serving engine. |
Going deeper: where each name comes from
Which tokens connect. Sliding-window attention limits some layers to the latest tokens; Mistral 7B used it “to effectively handle sequences of arbitrary length with a reduced inference cost”. Sparse attention keeps a subset chosen by a pattern or a learned selector, as in the Sparse Transformer and DeepSeek Sparse Attention. Both change which scores exist, so a model is trained with them (Sliding-window attention).
The same attention, faster. FlashAttention, “an IO-aware exact attention algorithm”, gives the same result while moving less data between the large, slower memory and the small, fast memory of the GPU, the graphics processor that runs the model. As Hugging Face's attention backends guide says, “All attention implementations perform the same computation.” More in FlashAttention.
How much is cached per token. Multi-query attention shares one set of keys and values across all query heads; grouped-query attention shares each set within a group. Multi-head latent attention, from DeepSeek-V2, instead compresses the cache “into a latent vector”: one problem, two mechanisms.
How cache storage is managed. vLLM and SGLang are two open-source serving engines. PagedAttention, the basis of vLLM, manages each request's cache in blocks, “inspired by the classical virtual memory and paging techniques in operating systems”. RadixAttention, in SGLang, lets requests sharing a beginning reuse saved work. Neither changes the model (What vLLM does, What SGLang does).
One deployment can combine four: gpt-oss-20b uses sliding windows and grouped-query attention, and on the vLLM serving engine its cache sits in PagedAttention blocks, possibly with FlashAttention. You can now place a new attention-named term by the problem it solves.
Sources and further reading
Sources were checked on 19 November 2026. Links beside each claim lead to the papers, model cards and documentation they quote. The three-token example, the causal grid and the comparison counts are invented teaching material or arithmetic, not measurements. The gpt-oss-20b configuration is quoted as published on that date.
- Vaswani and colleagues, Attention Is All You Need (2017) defines queries, keys, values, the mask, heads and the feed-forward step.
- 3Blue1Brown, Attention in transformers is a visual walk through the same mechanism.
- Hugging Face, Caching explains what the KV cache stores and why.
- OpenAI, gpt-oss-120b and gpt-oss-20b model card (2025) describes the attention design quoted here.
- gpt-oss-20b config.json on Hugging Face is the file in Figure 2.
- Jain and Wallace, Attention is not Explanation (2019) and Wiegreffe and Pinter's reply (2019) set out the debate on reading attention weights.
- Dao and colleagues, FlashAttention (2022), Ainslie and colleagues, GQA (2023) and Kwon and colleagues, PagedAttention (2023) are the primary papers for three names in the table.
Ready to see where the KV cache sits beside the weights in GPU memory?