Skip to content
Lineages2026-11-1215 min read

How attention works: a weighted lookup

Compute one attention step by hand, then follow the idea from 2013 to Gemma 4 and see what changed in the lookup, and why.

Key takeaways

  • 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 weights come only from queries and keys, so changing a value never moves them, while changing a key can.
  • Dividing scores by the square root of the width keeps the softmax from saturating. At d = 64, unscaled scores of 64 and 0 give the first item a weight above 0.999999, and scaled scores of 8 and 0 give it 0.9997.
  • Among the papers read, arXiv dates order Graves (August 2013), Mnih and colleagues (June 2014) and Bahdanau, Cho and Bengio (September 2014). Who first used attention in general is unsettled.
  • Since 2017 the three-step formula has mostly stayed. What changed is what is stored (grouped-query and latent attention), how position enters (rotary and linear-bias), the order of work (FlashAttention), which entries are read (sliding windows, sparse selection) and one gate after the formula.
  • Attention-free and hybrid models (Mamba, Jamba, Kimi Linear) report speed and memory gains. Those are the papers' own claims, and none is settled at much larger scale in the papers read.

Rod Rivera

Author

How attention works: a weighted lookup

Rod's note: read with a pencil; the margins are for you.

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 qq is what the current position is asking, a list of dd numbers. Each of the nn items has a key kjk_j, a list of dd numbers used for matching, and a value vjv_j, the numbers it hands back, for j=1,…,nj = 1, \dots, n.

First, a score sjs_j for each item:

sj=qβ‹…kjd.s_j = \frac{q \cdot k_j}{\sqrt{d}}.

The dot product qβ‹…kj=βˆ‘tqtkj,tq \cdot k_j = \sum_t q_t k_{j,t} is large when the two lists point the same way, so it measures how well the item matches the question.

Second, weights Ξ±j\alpha_j, by the softmax:

Ξ±j=esjβˆ‘l=1nesl.\alpha_j = \frac{e^{s_j}}{\sum_{l=1}^{n} e^{s_l}}.

The exponential makes every weight positive, and the division makes them add up to one.

Third, the output zz is the weighted average of the values:

z=βˆ‘j=1nΞ±jvj.z = \sum_{j=1}^{n} \alpha_j v_j.
The recipe: a query, scores, weights, an output. Query q; Scores: q dot k divided by sqrt d; Keys k; Weights: softmax, positive, sum to one; Output z: weighted average of values; Values v
The recipe: a query, scores, weights, an output
View full-size diagram

Because the weights are positive and sum to one, each entry of zz lies between the smallest and the largest value that entry takes among the vjv_j.

Check one with a pencil. Take k1=(1,0)k_1 = (1,0), k2=(0,1)k_2 = (0,1), k3=(1,1)k_3 = (1,1), values v1=(10,0)v_1 = (10,0), v2=(0,10)v_2 = (0,10), v3=(5,5)v_3 = (5,5), and query q=(2,0)q = (2,0). Here d=2d = 2. Find the three scores before you read on. The dot products are 2,0,22, 0, 2, so the scores are (1.4142,0,1.4142)(1.4142, 0, 1.4142). The weights are

Ξ±1=0.4458,Ξ±2=0.1084,Ξ±3=0.4458,\begin{aligned}\alpha_1 &= 0.4458,\\ \alpha_2 &= 0.1084,\\ \alpha_3 &= 0.4458,\end{aligned}

and the output is z=(6.6871,Β 3.3129)z = (6.6871,\ 3.3129). 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 xix_i (a list of numbers) plays all three roles. Three learned matrices turn it into a query, a key and a value:

qi=WQxi,ki=WKxi,vi=WVxi.\begin{aligned}q_i &= W_Q x_i,\\ k_i &= W_K x_i,\\ v_i &= W_V x_i.\end{aligned}

Each token asks, and every token (itself included) answers. Stack the qiq_i as the rows of a matrix QQ, and likewise KK and VV. Then every token's output at once is

Z=softmax⁑ ⁣(QK⊀d)V,Z = \operatorname{softmax}\!\left(\frac{Q K^{\top}}{\sqrt{d}}\right) V,

with the softmax taken along each row. Row ii of this is exactly the three steps above, with qiq_i as the query. The score of token ii for item jj is sij=qiβ‹…kj/ds_{ij} = q_i \cdot k_j / \sqrt d.

Self-attention: every token plays all three roles. Token x_i; W_Q; q_i; W_K; k_i; W_V; v_i; Z = softmax of Q K transposed over sqrt d, times V
Self-attention: every token plays all three roles
View full-size diagram

One more piece. Vaswani and colleagues run hh copies of this in parallel, called heads, each with its own WQW_Q, WKW_K, WVW_V. They join the hh outputs end to end and pass the result through one more learned matrix. Different heads can weight different tokens for the same query.

Attention as a weighted lookup

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.

sj=qΒ·kjd Ξ±j=esjβˆ‘i=13esi z=βˆ‘j=13Ξ±jvj

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.

Scores, weights and value contributions
ItemKey kq Β· kScaled scoreWeight Ξ±Value vWeighted value Ξ±v
1(1, 0)21.41420.4458(10, 0)(4.4581, 0)
2(0, 1)000.1084(0, 10)(0, 1.0838)
3(1, 1)21.41420.4458(5, 5)(2.229, 2.229)

Head 1 output z = (6.6871, 3.3129), the sum of the weighted values.

Predict for the original keys and values
Explore the lookup
Edit first-head keys and the shared values

Query and key coordinates: βˆ’4 to 4, quarter steps. Value coordinates: βˆ’20 to 20, integer steps. The second head's keys stay fixed. Both heads share the query, values and mask.

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 0.4458,0.1084,0.44580.4458, 0.1084, 0.4458 and output (6.6871,3.3129)(6.6871, 3.3129). Now you try. Guess first: if you change the query to (0,2)(0, 2), 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 (0,1),(1,0),(1,1)(0,1), (1,0), (1,1) gives weights 0.1084,0.4458,0.44580.1084, 0.4458, 0.4458 and output (3.3129,6.6871)(3.3129, 6.6871), so the two heads weight different items for the same query. The board joins the two outputs end to end: (6.6871,3.3129)(6.6871, 3.3129) from the first head, then (3.3129,6.6871)(3.3129, 6.6871) 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 0.8044,0.1956,00.8044, 0.1956, 0 and the output (8.0443,1.9557)(8.0443, 1.9557).

What a value change can and cannot do

Change a value and only the output moves. Change a query or a key and the weights can move too.

Quick check β€” Keep the three keys and values from the pencil example, but change the query to (0, 2). Which items now share most of the weight?

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 dd the dot products grow, pushing the softmax into regions where its gradients are extremely small. If the entries of qq and kk are independent with mean 00 and variance 11, the dot product has mean 00 and variance dd, so scores spread out by d\sqrt d. Dividing by d\sqrt d undoes that. Try d=64d = 64 with a query of sixty-four ones, one key of ones and one key of zeros. Unscaled, the scores are 6464 and 00 and the first item gets weight above 0.9999990.999999. Scaled, they are 88 and 00 and it gets 0.99970.9997.

Width 64, one key of ones and one key of zerosScoresWeight on the first item
Unscaled64 and 0above 0.999999
Divided by the square root of 648 and 00.9997

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 ii read tokens after it. We set sij=βˆ’βˆžs_{ij} = -\infty for j>ij > i before the softmax, so those weights are exactly zero. Change a later token, and every earlier output stays the same.

Query tokenItem 1Item 2Item 3
1readhiddenhidden
2readreadhidden
3readreadread

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.

Six places the papers change the same lookup. The lookup: scores, weights, output; What is stored: shared, grouped or compressed keys and values; Where a token sits: rotary or linear-bias positions; Order of work: blocks, same output; Which entries: sliding window, local and global layers, top k; After the formula: a sigmoid gate; Mixing with other layers: Mamba, or linear attention with a fixed-size memory
Six places the papers change the same lookup
View full-size diagram

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 mβˆ’nm - n. 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 nΓ—nn \times n 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 kk entries by that score. The score of earlier token ss for query token tt is It,s=βˆ‘j=1HIwt,j ReLU⁑(qt,jIβ‹…ksI)I_{t,s} = \sum_{j=1}^{H_I} w_{t,j}\,\operatorname{ReLU}(q^{I}_{t,j} \cdot k^{I}_{s}), a small sum over HIH_I indexer heads, with the query part and the weights wt,jw_{t,j} computed from token tt and the key part from token ss. The paper says this cuts the cost of the main attention from order L2L^2 to order LkLk, where LL is the length and kk is much smaller; in its continued training k=2048k = 2048. The indexer itself still costs order L2L^2, but far less than the main step.

Sparse attention: score cheaply, then read only the top k. Query token t; Lightning indexer scores every earlier token; Keep the top k scores; Ordinary attention over only those entries
Sparse attention: score cheaply, then read only the top k
View full-size diagram

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, Yβ€²=YβŠ™Οƒ(XWΞΈ)Y' = Y \odot \sigma(X W_\theta), where YY is the attention output, XX holds the token's hidden state and WΞΈW_\theta 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 p=0.25p = 0.25 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

MethodYearWhat it changesReported numberSource
Multi-query attention2019All heads share one set of keys and valuesDecoder 46 to 3.8 microseconds per output tokenShazeer, arXiv 1911.02150, Table 2
Grouped-query attention2023One set of keys and values per group of query headsT5-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 countsAinslie and colleagues, arXiv 2305.13245, Table 1
Latent attention2024Store a short compressed vector per token plus a small positional key, and rebuild keys and values from itAgainst 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 cacheDeepSeek-V2, arXiv 2405.04434
Grouped-query attention in use20248 key-value headsNo figure quotedLlama 3, arXiv 2407.21783
Shared and reused keys and values2026Depending on size, shared stored keys and values (two smallest models) or keys reused as values in global layersGlobal stored keys and values cut by up to 37.5%Gemma 4, arXiv 2607.02770

Where a token sits; which entries are read

MethodYearWhat it changesReported numberSource
Rotary positions2021Rotate the query and key by an angle that grows with position, so the score depends on the positions only through their differenceNo figure quotedSu and colleagues, arXiv 2104.09864
Linear-bias positions (ALiBi)2021Subtract a penalty from each score in proportion to the distanceA 1.3 billion parameter model trained at length 1024 matches a sinusoidal model trained at 2048, with 11% faster training and 11% less memoryPress, Smith and Lewis, arXiv 2108.12409
Sliding-window attention2023Each token attends only to the previous 4096 tokens in each layerIn theory, information can travel about 131 thousand tokens by the last layerMistral 7B, Jiang and colleagues, arXiv 2310.06825
Ring attention2023Split the sequence across devices, passing keys and values around a ringSequences up to the number of devices times longer than prior memory-efficient transformersLiu, Zaharia and Abbeel, arXiv 2310.01889
Local and global layers20255 local sliding-window layers of 1024 tokens for each global layer128 thousand token context (32 thousand for the 1B model)Gemma 3, arXiv 2503.19786
DeepSeek Sparse Attention2025An indexer scores earlier tokens and attention runs over only the top kMain cost from order L squared to order L k, with k = 2048DeepSeek-V3.2, arXiv 2512.02556

The same output computed in a different order, other kinds of layer, and a gate after the formula.

MethodYearWhat it changesReported numberSource
FlashAttention2022Same output, computed in blocks without storing the score tableUp to 3 times faster GPT-2 training than the HuggingFace implementationDao and colleagues, arXiv 2205.14135
FlashAttention-22023Same output, better split of the workAbout 2 times faster than FlashAttentionDao, arXiv 2307.08691
Mamba2023No attention; the rule for carrying information forward depends on the current token5 times the inference throughput of a transformer; the 3 billion parameter model matches a transformer twice its sizeGu and Dao, arXiv 2312.00752
Jamba2024One attention layer to seven Mamba layers256 thousand token context; stored keys and values 8 times smaller than a plain transformer's; 12 billion active of 52 billion parametersLieber and colleagues, arXiv 2403.19887
Gated attention2025A sigmoid gate on each head's output, with its own values for each head and each dimensionBetter results and training stability and less attention sink; no single number quotedQiu and colleagues, arXiv 2505.06708
Kimi Linear2025Linear attention layers mixed with latent attention layersUp 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 testedKimi Team, arXiv 2510.26692

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

Read the scaling-laws worked example

See how model size and training tokens trade off under a fixed compute budget.

Learn the mechanism. Test the claim.

Join the Prof Rod newsletter for one educational lesson a week, with worked examples attached. It is free to register for and separate from the Zero Employee community.