This is for people who read papers on large models and can follow algebra, but have never computed one attention step by hand. By the end you will compute one and say what it keeps, and you will know which earlier papers have a claim on the idea, and which claims the sources do not let us settle.
Almost every large language model you will read about uses attention. It is the one operation that lets a position in a sequence look at other positions. So let us find out exactly what it computes.
The point
Attention is a lookup with soft edges. Compare a question with every item, turn the comparisons into weights that are positive and sum to one, and return the weighted average of what the items hold.
The problem it solved
In 2014 the recently proposed neural translation models read a whole source sentence into a single fixed-length vector, and wrote the translation from that vector alone. Bahdanau, Cho and Bengio conjectured that this vector is a bottleneck: a long sentence has to be squeezed into as many numbers as a short one. Their change was to let the network look back at the source words while it writes each target word, choosing where to look by comparing its own state with each source word's state. They called the result an alignment, learned together with the translator, and they used the word attention for it.
The computation, by hand
Name the parts. A query is what the current position is asking, a list of numbers. Each of the items has a key , a list of numbers used for matching, and a value , the numbers it hands back, for .
First, a score for each item:
The dot product is large when the two lists point the same way, so it measures how well the item matches the question.
Second, weights , by the softmax:
The exponential makes every weight positive, and the division makes them add up to one.
Third, the output is the weighted average of the values:

flowchart LR
Q[Query q] --> S[Scores: q dot k divided by sqrt d]
K[Keys k] --> S
S --> W[Weights: softmax, positive, sum to one]
W --> Z[Output z: weighted average of values]
V[Values v] --> Z
Because the weights are positive and sum to one, each entry of lies between the smallest and the largest value that entry takes among the .
Check one with a pencil. Take , , , values , , , and query . Here . Find the three scores before you read on. The dot products are , so the scores are . The weights are
and the output is . The two items that match share most of the weight, and the item that does not match keeps a little.
Where the query, the key and the value come from
In a transformer, every token (a list of numbers) plays all three roles. Three learned matrices turn it into a query, a key and a value:
Each token asks, and every token (itself included) answers. Stack the as the rows of a matrix , and likewise and . Then every token's output at once is
with the softmax taken along each row. Row of this is exactly the three steps above, with as the query. The score of token for item is .

flowchart LR
X[Token x_i] --> WQ[W_Q] --> Qi[q_i]
X --> WK[W_K] --> Ki[k_i]
X --> WV[W_V] --> Vi[v_i]
Qi --> Z[Z = softmax of Q K transposed over sqrt d, times V]
Ki --> Z
Vi --> Z
One more piece. Vaswani and colleagues run copies of this in parallel, called heads, each with its own , , . They join the outputs end to end and pass the result through one more learned matrix. Different heads can weight different tokens for the same query.
A query compares with three keys, turns scores into weights, then averages three values. Predict which items a new query will favor. After checking, edit a query, key or value; compare a second head and a causal mask.
and determine ; softmax makes . The determine what gets averaged into . Here d = 2 coordinates.
Head 1
Query q = (2, 0); width d = 2. All three items are available.
Item 1: weight 0.4458
Item 2: weight 0.1084
Item 3: weight 0.4458
Bar length: weight from 0 to 1. The weights sum to 1; numeric values above are rounded.
| Item | Key k | q Β· k | Scaled score | Weight Ξ± | Value v | Weighted value Ξ±v |
|---|---|---|---|---|---|---|
| 1 | (1, 0) | 2 | 1.4142 | 0.4458 | (10, 0) | (4.4581, 0) |
| 2 | (0, 1) | 0 | 0 | 0.1084 | (0, 10) | (0, 1.0838) |
| 3 | (1, 1) | 2 | 1.4142 | 0.4458 | (5, 5) | (2.229, 2.229) |
Head 1 output z = (6.6871, 3.3129), the sum of the weighted values.
Choose a prediction before editing the lookup.
Why scale a width-64 dot product?
In the article's separate example of a query of 64 ones and keys of all ones or all zeros, unscaled scores are 64 and 0. The first weight is above 0.999999 (it rounds to 1 in double precision); the other weight is about 1.604e-28. Dividing by β64 gives scores 8 and 0 and first weight 0.9997. This example is separate from the editable width-2 lookup.
Hand-set, three-item, width-2 illustration, not a trained transformer or measured model output. We edit q, k and v directly, omit their learned projection matrices, and omit the final output matrix after concatenation. The mask is only this three-item query-at-token-2 example. Stable softmax subtracts the largest allowed score before exponentiating; masked weights are exactly zero. Values never enter the weight calculation. Displayed numbers are rounded to four decimal places; all arithmetic uses full JavaScript precision.
It opens on the pencil example above: three items, the same keys, values and query, so the board shows weights and output . Now you try. Guess first: if you change the query to , which items share most of the weight? Then change one number in the query, a key or a value, and see what moves. A key or query change can move the weights. A value change never does, because the weights come only from queries and keys.
Two more steps on the same board. Heads: a second head with the same query and values but keys gives weights and output , so the two heads weight different items for the same query. The board joins the two outputs end to end: from the first head, then from the second head, four numbers in all, and leaves out the final learned matrix. Mask: switch the mask on and treat the query as the second token, so item 3 comes later and is forbidden. The weights become and the output .
Change a value and only the output moves. Change a query or a key and the weights can move too.
Work out the three dot products first; the width is still 2.
Check the query
Why items 2 and 3
The dot products of (0, 2) with the keys are 0, 2 and 2, so the scores are 0, 1.4142 and 1.4142. The weights are 0.1084, 0.4458 and 0.4458, and the output is (3.3129, 6.6871).
Why divide by the square root of the width
Vaswani and colleagues suspect that for large the dot products grow, pushing the softmax into regions where its gradients are extremely small. If the entries of and are independent with mean and variance , the dot product has mean and variance , so scores spread out by . Dividing by undoes that. Try with a query of sixty-four ones, one key of ones and one key of zeros. Unscaled, the scores are and and the first item gets weight above . Scaled, they are and and it gets .
| Width 64, one key of ones and one key of zeros | Scores | Weight on the first item |
|---|---|---|
| Unscaled | 64 and 0 | above 0.999999 |
| Divided by the square root of 64 | 8 and 0 | 0.9997 |
Scroll horizontally to view columns.
A short note works the same point through the variance of a dot product: why attention divides by the square root of d.
The mask
A model that writes one token at a time must not let token read tokens after it. We set for before the softmax, so those weights are exactly zero. Change a later token, and every earlier output stays the same.
| Query token | Item 1 | Item 2 | Item 3 |
|---|---|---|---|
| 1 | read | hidden | hidden |
| 2 | read | read | hidden |
| 3 | read | read | read |
Scroll horizontally to view columns.
A hidden entry has a score of minus infinity, so its weight is exactly zero.
Where the idea came from
I cannot say who first used attention in general; that is unsettled. Among the papers I read, the arXiv dates settle the order of three: Graves (August 2013), Mnih and colleagues (June 2014), then Bahdanau, Cho and Bengio (September 2014). Bahdanau's is the first of the three with content-based weights over the whole input. Graves (2013) built a handwriting generator that reads its text through a soft window that can only move forward. His paper does not use the word attention. Bahdanau, Cho and Bengio (2014) made the weights depend on content, so they can fall anywhere in the source, and they name Graves's approach as a similar earlier one. Mnih and colleagues (2014), submitted before Bahdanau's first version, used attention as a hard glimpse at one place in an image, trained by reinforcement learning. Schmidhuber's fast weight programmers of 1991 and 1992 are a further thread, which this article does not cover. Schlag, Irie and Schmidhuber (2021) show that a linearized form of self-attention is formally equivalent to a fast-weight controller, which makes linear attention a formal relative of those early fast weights. They do not show that the transformer came from it.
What Vaswani and colleagues (2017) added is a model whose only way of mixing positions is attention, with no recurrence and no convolution. They credit earlier attention inside a sentence and call theirs the first transduction model relying entirely on self-attention. That is the claim I will make.
Since 2017: the same lookup, made cheaper, longer and challenged
Three of the changes below have their own short notes: FlashAttention, grouped-query attention and rotary embeddings.

flowchart TB
L[The lookup: scores, weights, output]
L --- C[What is stored: shared, grouped or compressed keys and values]
L --- P[Where a token sits: rotary or linear-bias positions]
L --- O[Order of work: blocks, same output]
L --- E[Which entries: sliding window, local and global layers, top k]
L --- G[After the formula: a sigmoid gate]
L --- M[Mixing with other layers: Mamba, or linear attention with a fixed-size memory]
In the papers I read, the formula above has mostly stayed; one paper adds a gate after it. What people changed is what surrounds it.
Cost of writing one token at a time
During straightforward full-attention decoding, a new token reads cached keys and values from earlier positions. Overall inference performance also depends on compute, memory capacity and bandwidth, communication and workload; prefill and decoding can behave differently. Shazeer (2019) proposed multi-query attention: all the heads share one set of keys and values. In his translation runs the decoder took 46 microseconds per token with the usual heads and 3.8 with shared ones, at a small loss in quality. Ainslie and colleagues (2023) kept a middle path, grouped-query attention, with one set of keys and values for each group of query heads. In their T5-XXL runs, usual heads took 1.51 units of time per sample at an average score of 47.2, shared took 0.24 at 46.6, and eight groups took 0.28 at 47.1 (the paper's figure labels the unit milliseconds, its table labels it seconds, so I give the ratios, not the unit).
Where a token sits
Order. The formula never looks at where an item sits in the sequence, so position has to be put in. Su and colleagues (2021) rotate the query and the key by an angle that grows with position, so that their dot product depends on the two positions only through the difference . Press, Smith and Lewis (2021) skip rotation and subtract a penalty from each score in proportion to the distance. They report that a 1.3 billion parameter model trained on sequences of length 1024 reaches, on sequences of length 2048, the perplexity of a sinusoidal-position model trained on 2048, while training 11% faster and using 11% less memory.
The same numbers, in a different order
The same numbers, in a different order. The scores form an table, and for long sequences the table is what costs. Dao and colleagues (2022) compute exactly the same output without ever storing the table: they work in blocks and carry the softmax's running totals from block to block. They report up to 3 times faster training of GPT-2 at length 1024 than the HuggingFace implementation. The sequel (Dao, 2023) keeps the output the same and splits the work better across the chip, for about twice the speed of the first, as the paper reports.
Long context
Long context. When the table of scores grows with the square of the length, one answer is to look at less of it. Mistral 7B (2023) lets each token attend only to the previous 4096 tokens in each layer; because layers stack, in theory, information can still travel about 131 thousand tokens by the last layer. Gemma 3 (2025) alternates: five layers with a 1024-token window for each layer that looks at everything, and reports a 128 thousand token context. Ring attention (Liu and colleagues, 2023) goes the other way and splits the sequence across devices, passing keys and values around a ring while each device works on its block; the paper reports sequences up to the number of devices times longer than prior memory-efficient transformers could handle.
A challenger, and an answer to it
A challenger, and an answer to it. Gu and Dao (2023) build a model with no attention at all, in which the rule for carrying information forward depends on the current token. They report five times the inference throughput of a transformer of similar size and, at 3 billion parameters, results that match a transformer twice its size. As of the papers I opened, the answer on offer is a mixture, and Kimi Linear (below) is a second one. Jamba (2024) interleaves attention layers with Mamba layers at one attention layer to seven, and reports a 256 thousand token context and a store of keys and values eight times smaller than a plain transformer's, with 12 billion active parameters out of 52 billion. Whether pure attention-free models, or mixtures, win at much larger scale is not settled in what I read.
Looking at fewer entries
Looking at fewer entries. Sparse attention keeps the formula and shrinks the set it runs over. DeepSeek-V3.2 (2025) adds a small scoring step, called a lightning indexer, that gives each earlier token a cheap score for the current query; the model then runs ordinary attention over only the top entries by that score. The score of earlier token for query token is , a small sum over indexer heads, with the query part and the weights computed from token and the key part from token . The paper says this cuts the cost of the main attention from order to order , where is the length and is much smaller; in its continued training . The indexer itself still costs order , but far less than the main step.

flowchart LR
T[Query token t] --> I[Lightning indexer scores every earlier token]
I --> TK[Keep the top k scores]
TK --> A[Ordinary attention over only those entries]
A gate after the formula
A gate after the formula. Qiu and colleagues (Qwen team, 2025) tested 30 variants of attention with gates, in 15 billion parameter mixture-of-experts models and 1.7 billion parameter dense models trained on 3.5 trillion tokens. Their central finding is that a sigmoid gate applied to each head's output, , where is the attention output, holds the token's hidden state and is a learned matrix, consistently improves results (the paper's best variant is a sigmoid gate on each head's output with its own gate values for each head and each dimension; a version with one number per head also helped), helps training stability, and reduces the "attention sink", a known pattern in which a few tokens draw outsized weight. They attribute the gain to two things: the gate adds a nonlinearity, and its scores are sparse and depend on the query. This one changes the three-step recipe slightly, by one step after it.
Two more designs from 2025 and 2026
Fewer entries, a different way. Kimi Linear (Kimi Team, 2025) mixes a linear attention layer, one that carries a fixed-size memory instead of all keys and values, with latent attention layers. At 3 billion active of 48 billion total parameters, with the same training recipe, their abstract says it beats a full latent-attention model across all evaluated tasks, while using up to 75% less stored keys and values and up to 6 times the decoding throughput at a 1 million token context. Their own short-context tables are less absolute: MATH is a tie (54.7 for both) and LiveBench is a small loss (45.2 against 45.7), and its tables show the full latent-attention model ahead on EvalPlus (62.6 against 61.0) in the short-context table and on three long-context columns: LongBench V2, Frames and Long Code Arena Commit (33.2 against 32.7). So I read the claim as better on almost every task they tested, not all.
Gemma 4 (2026) keeps Gemma 3's pattern of five local sliding-window layers per global layer (four per global in its smallest model) and adds three things, some of them depending on model size: a position scheme the report calls p-RoPE, with on the global layers; for the two smallest models, shared stored keys and values; and for the larger ones, reusing the keys as values in the global layers. The report's introduction says these cut the global stored keys and values by up to 37.5%.
In use
In use. Models that people read about show the line in practice. The Llama 3 paper (2024) lists grouped-query attention with 8 key-value heads among its few modifications compared with Llama 2, to speed up decoding and shrink the stored keys and values. The DeepSeek-V3 paper (2024) goes a different way, multi-head latent attention, first set out in DeepSeek-V2 (2024): it stores a short compressed vector per token, plus a small positional key, and rebuilds the keys and values from the compressed vector. Against its dense predecessor DeepSeek 67B, DeepSeek-V2 reports a 93.3% smaller store of keys and values and 5.76 times the peak generation throughput; the paper credits that figure to this attention together with FP8 weights and a quantized cache, not to attention alone. The DeepSeek-V3 paper reports performance comparable to ordinary multi-head attention. Qwen3 (2025) takes the older route: grouped-query attention, rotary positions, and a normalization of the queries and keys before the dot product. Notice what the first three of these have in common. Nothing in the three-step formula changed there; they change what is stored and reused around it. Qwen3's normalization changes the scores, to keep training stable.
What each token stores
| Method | Year | What it changes | Reported number | Source |
|---|---|---|---|---|
| Multi-query attention | 2019 | All heads share one set of keys and values | Decoder 46 to 3.8 microseconds per output token | Shazeer, arXiv 1911.02150, Table 2 |
| Grouped-query attention | 2023 | One set of keys and values per group of query heads | T5-XXL time per sample 1.51 (multi-head), 0.24 (multi-query), 0.28 (8 groups); average score 47.2, 46.6, 47.1. The paper's table and figure give different units, so the ratios are what counts | Ainslie and colleagues, arXiv 2305.13245, Table 1 |
| Latent attention | 2024 | Store a short compressed vector per token plus a small positional key, and rebuild keys and values from it | Against DeepSeek 67B: 93.3% smaller store of keys and values and 5.76 times the peak generation throughput, credited to this attention together with FP8 weights and a quantized cache | DeepSeek-V2, arXiv 2405.04434 |
| Grouped-query attention in use | 2024 | 8 key-value heads | No figure quoted | Llama 3, arXiv 2407.21783 |
| Shared and reused keys and values | 2026 | Depending on size, shared stored keys and values (two smallest models) or keys reused as values in global layers | Global stored keys and values cut by up to 37.5% | Gemma 4, arXiv 2607.02770 |
Scroll horizontally to view columns.
Where a token sits; which entries are read
| Method | Year | What it changes | Reported number | Source |
|---|---|---|---|---|
| Rotary positions | 2021 | Rotate the query and key by an angle that grows with position, so the score depends on the positions only through their difference | No figure quoted | Su and colleagues, arXiv 2104.09864 |
| Linear-bias positions (ALiBi) | 2021 | Subtract a penalty from each score in proportion to the distance | A 1.3 billion parameter model trained at length 1024 matches a sinusoidal model trained at 2048, with 11% faster training and 11% less memory | Press, Smith and Lewis, arXiv 2108.12409 |
| Sliding-window attention | 2023 | Each token attends only to the previous 4096 tokens in each layer | In theory, information can travel about 131 thousand tokens by the last layer | Mistral 7B, Jiang and colleagues, arXiv 2310.06825 |
| Ring attention | 2023 | Split the sequence across devices, passing keys and values around a ring | Sequences up to the number of devices times longer than prior memory-efficient transformers | Liu, Zaharia and Abbeel, arXiv 2310.01889 |
| Local and global layers | 2025 | 5 local sliding-window layers of 1024 tokens for each global layer | 128 thousand token context (32 thousand for the 1B model) | Gemma 3, arXiv 2503.19786 |
| DeepSeek Sparse Attention | 2025 | An indexer scores earlier tokens and attention runs over only the top k | Main cost from order L squared to order L k, with k = 2048 | DeepSeek-V3.2, arXiv 2512.02556 |
Scroll horizontally to view columns.
The same output computed in a different order, other kinds of layer, and a gate after the formula.
| Method | Year | What it changes | Reported number | Source |
|---|---|---|---|---|
| FlashAttention | 2022 | Same output, computed in blocks without storing the score table | Up to 3 times faster GPT-2 training than the HuggingFace implementation | Dao and colleagues, arXiv 2205.14135 |
| FlashAttention-2 | 2023 | Same output, better split of the work | About 2 times faster than FlashAttention | Dao, arXiv 2307.08691 |
| Mamba | 2023 | No attention; the rule for carrying information forward depends on the current token | 5 times the inference throughput of a transformer; the 3 billion parameter model matches a transformer twice its size | Gu and Dao, arXiv 2312.00752 |
| Jamba | 2024 | One attention layer to seven Mamba layers | 256 thousand token context; stored keys and values 8 times smaller than a plain transformer's; 12 billion active of 52 billion parameters | Lieber and colleagues, arXiv 2403.19887 |
| Gated attention | 2025 | A sigmoid gate on each head's output, with its own values for each head and each dimension | Better results and training stability and less attention sink; no single number quoted | Qiu and colleagues, arXiv 2505.06708 |
| Kimi Linear | 2025 | Linear attention layers mixed with latent attention layers | Up to 75% less stored keys and values and up to 6 times the decoding throughput at 1 million tokens, as reported; better on almost every task they tested | Kimi Team, arXiv 2510.26692 |
Scroll horizontally to view columns.
What I did and did not open: for the papers named here I read the abstract, the introduction and the passages that give the numbers I quote, not every section. The latest paper I opened is the Gemma 4 technical report (2026). I did not open reports for Qwen 3.6, Kimi 3 or Mistral 3, nor anything dated after July 2026, so I make no claim about them.
Sources
- Graves, arXiv 1308.0850 (read in full).
- Bahdanau, Cho and Bengio, arXiv 1409.0473 (read in full).
- Mnih and colleagues, arXiv 1406.6247 (abstract).
- Schlag, Irie and Schmidhuber, arXiv 2102.11174 (abstract).
- Shazeer, arXiv 1911.02150 (abstract, introduction and the passages with the quoted numbers).
- Ainslie and colleagues, arXiv 2305.13245 (abstract, introduction and the passages with the quoted numbers).
- Su and colleagues, arXiv 2104.09864 (abstract, introduction and the passages with the quoted numbers).
- Press, Smith and Lewis, arXiv 2108.12409 (abstract, introduction and the passages with the quoted numbers).
- Dao and colleagues, arXiv 2205.14135 (abstract, introduction and the passages with the quoted numbers).
- Gu and Dao, arXiv 2312.00752 (abstract and introduction).
- Llama Team, arXiv 2407.21783 (the architecture section).
- DeepSeek-AI, arXiv 2412.19437 (the section on multi-head latent attention).
- DeepSeek-AI, arXiv 2405.04434 (abstract and the multi-head latent attention section).
- Dao, arXiv 2307.08691 (abstract).
- Jiang and colleagues, arXiv 2310.06825 (the sliding window section).
- Liu, Zaharia and Abbeel, arXiv 2310.01889 (abstract).
- Gemma Team, arXiv 2503.19786 (the long-context passage).
- Lieber and colleagues, arXiv 2403.19887 (abstract, introduction and Table 1).
- Qwen Team, arXiv 2505.09388 (the architecture passage).
- Qiu and colleagues, arXiv 2505.06708 (abstract and introduction).
- DeepSeek-AI, arXiv 2512.02556 (abstract and the section on sparse attention).
- Kimi Team, arXiv 2510.26692 (abstract and the result tables, Tables 3 to 5).
- Gemma Team, arXiv 2607.02770 (the long-context passage).
- Vaswani and colleagues, arXiv 1706.03762 (read in full; Section 3.2.1 and its footnote).
See how model size and training tokens trade off under a fixed compute budget.

