Rúben GalvãoThe Rabbit Hole

The Rabbit Hole / AI and machine learning / Language models / Alternative language-model architectures

Linear attention: a fixed-size memory instead of a growing cache

Can we collect the writes before a query arrives, so the conversation grows without growing a cache in every layer?

Ordinary attention projects token representations into queries, keys and values. The query–key scores go through a causal mask and softmax; the resulting weights mix the values. Wₒ projects the result back into the residual stream.

The whole attention block and the residual streamThe residual stream runs uninterrupted down the left. A branch reads its token vectors. Learned Wq, Wk and Wv matrices produce queries, keys and values. Query–key dot products produce scores; masking sets future scores to negative infinity; softmax produces the attention map. Its weights collect the values. The output projection Wo expands the collected information. The update is added back to the residual stream.Residual streamToken representationsEarlier context is dimmed; outlined columns are current.Current token computation.7,168192WqEarlier context is dimmed; outlined columns are current.Current token computation.Queries7,168192WkEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.Keys7,168128WvEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.ValuesDot productsMask: −∞SoftmaxAttention mapWeighted sumof valuesEarlier context is dimmed; outlined columns are current.Current token computation.Collected1287,168WₒUpdate+Enriched token representationsCLCLCL7,168192192128128
Attention reads the token representations, collects information, and adds its update to the residual stream.

For each new token, that middle calculation needs every earlier key and value. As the conversation grows, we store more pairs and compare the new query with more keys.

Could we change that part of attention so each new query does not need to revisit the whole history? The query should still be able to request useful information from earlier tokens.

Could we just add the values together?

Instead of keeping every value, add each one to a running total and discard the pair. That would keep the memory fixed. What happens to the answers?

Use two coordinates for every query, key and value. The three tokens have values [2, 1], [8, 2] and [4, 5]. Their keys are [1, 0], [0, 1] and [1, 0]. Compare ordinary attention with the running total, using the same two queries on both sides:

Token 3 of 3 · append pair; add value directly to total
A fixed diagram with values flowing through the operationsIncoming token 3k10v45from the learned key/value projectionsOrdinary attentionFixed memory · plain sumKV cachekvToken 11021kvToken 20182kvToken 310453 pairs · 12 stored numbersRunning total1482 stored numbersScore → scale → softmaxMix cached valuesStored pairs stay available for each queryReturn total; ignore queryqOutput103.992.8qOutput10148qOutput015.522.5qOutput01148102101822 pairs · 8 stored numbers1033.981.331036.021.67103104545
Each token appends its key/value pair to the cache on the left. Its value goes directly into the running total on the right. There is no intermediate operation: the total changes when the value arrives.

The running total stays small, but both queries receive [14, 8]. Attention gives them different answers because they match the keys differently. We saved memory by throwing away the information the query needed to choose values.

Could we keep some of that information without keeping every pair?

Could we use the keys while adding?

Keep a pair of totals for each value coordinate, with one column per key feature. The first token’s key [1, 0] directs its value [2, 1] into the first column. The second token’s key [0, 1] directs [8, 2] into the second column. The third adds [4, 5] to the first column.

Token 3 of 3 · Accumulate the product
A fixed diagram with values flowing through the operationsIncoming token 3k10v45from the learned key/value projectionsOrdinary attentionFixed memory · weighted sumsKV cachekvToken 11021kvToken 20182kvToken 310453 pairs · 12 stored numbers10kᵀ45v4050Current write: v × kᵀKeep weighted totals68624 stored numberscarried to the next tokenValue totalsScore → scale → softmaxMix cached valuesStored pairs stay available for each queryRead weighted totals with qqOutput103.992.8qOutput1066qOutput015.522.5qOutput018228123.981.33216.021.67824050
The diagram stays fixed. Watch the value and key flow into multiplication, their product flow into addition with the previous total, and the result flow into the state.

The first column now holds [6, 6], and the second holds [8, 2]. The two queries select those different columns. Memory stays a 2 × 2 matrix, however many tokens arrive.

But these answers are sums. The first contains two contributions; the second contains one. Repeating the first and third tokens would increase the first answer even though we had only repeated the same information. Attention returns a weighted average, so we still need to account for how much contributed.

Could we keep the contribution amounts too?

Keep the weighted-total matrix from the previous attempt. Add one new vector, updated by adding each incoming key. After the three tokens it holds [2, 1]: two contributions to the first column, one to the second. The diagram now has two pieces of memory on the right. Read both with the query, then divide the value total by the contribution amount.

Token 3 of 3 · Accumulate the product
A fixed diagram with values flowing through the operationsIncoming token 3k10v45from the learned key/value projectionsOrdinary attentionFixed memory · weighted averagesKV cachekvToken 11021kvToken 20182kvToken 310453 pairs · 12 stored numbers10kᵀ45v4050Current write: v × kᵀWeighted totals + amounts68626 stored numberscarried to the next tokenValue totalsAmounts (new)21Score → scale → softmaxMix cached valuesStored pairs stay available for each queryRead totals ÷ read amountsqOutput103.992.8qTotal ÷ 21033qOutput015.522.5qTotal ÷ 10182112812Total ÷ 13.981.3321Total ÷ 16.021.6782405010
The weighted-total matrix is unchanged from the previous attempt. The new amount vector receives each key. Each query reads both, then divides the value totals by the contribution amount. Both arrays keep the same shape.

The answers are now [6, 6] ÷ 2 = [3, 3] and [8, 2] ÷ 1 = [8, 2]. We can select and average whole value vectors using six stored numbers: four in the matrix and two contribution amounts, regardless of the number of tokens.

The comparison still shows different answers from ordinary attention. That is the tradeoff: we have replaced softmax weighting with a rule we can compute from running totals. We have not found a smaller cache that reproduces softmax exactly.

The complete linear-attention block

Put the last comparison back into the attention block we started with. Wq, Wk and Wv still produce a query, key and value from each token. The cache and softmax path are replaced by the two pieces of running memory:

  • H is the matrix of weighted value totals.
  • z is the vector of contribution amounts.

Learned keys can contribute to several columns at once. The write and read operations stay the same. To keep the query–key weights positive, this example applies ReLU then adds 1 to the learned queries and keys; the diagram’s q and k are the resulting vectors.

Calculated valuesLearned weights
The whole linear-attention blockWq, Wk and Wv project the current token. ReLU plus one maps queries and keys to positive features. The value-key outer product is added to H; the key is added to z. The query reads the updated H and z. Divide the weighted sum by the total weight, apply Wₒ, and add the update to the residual stream. H and z are carried to the next token.Residual streamCurrent token representationEarlier context is dimmed; outlined columns are current.Current token computation.7,168192WqEarlier context is dimmed; outlined columns are current.Current token computation.Query7,168192WkEarlier context is dimmed; outlined columns are current.Current token computation.Key7,168128WvEarlier context is dimmed; outlined columns are current.Current token computation.ValueReLU + 1qReLU + 1kvkᵀValue × key featuresHₜ₋₁+zₜ₋₁+Hₜzₜq×·Hqz · q÷Weighted average1287,168WₒUpdate+Enriched token representations7,168192192128128
Linear attention replaces the score, mask and softmax path with two state updates and a normalised read. Wq, Wk, Wv, Wₒ and the residual path keep their roles. Dashed loops carry each head’s H and z to the next token. Cells illustrate shapes. Blue/orange cells identify calculated values, including all-positive vectors; violet boxes are learned projections. Cell colours identify roles here, not numerical signs.

Each token adds vkᵀ to H and k to z. Its query reads Hq for the weighted value total and z · q for the contribution amount. Dividing gives the output, just as we divided by 2 or 1 in the comparison. Wₒ projects that output back into the residual stream.

Start H and z at zero for a new sequence and keep them between tokens. Update before reading so the current token can contribute to its own output. Each head in each layer has its own state.

Why the cost is linear

Every token updates and reads the same-sized H and z. A longer conversation needs more updates, but no larger state. At fixed head dimensions, the attention work grows in proportion to the number of tokens.

Different tokens’ writes overlap in that state, so it cannot generally recover individual key/value pairs. The model must be trained with this attention rule.

The next problem is what to write. Adding a fact again strengthens it again, even if nothing changed. Gated DeltaNet starts by checking what the memory already predicts. Mamba keeps the write/read structure and asks how each token can control the strength of its write and how much old state to retain.

Sources and assumptions
  • Transformers are RNNs, Katharopoulos and colleagues, 2020: feature-map attention and its causal H/z recurrence. Their experiments use ELU + 1; the full-block diagram uses ReLU + 1 as a simple positive map.
  • Lightning Attention-2, Qin and colleagues, 2024: chunked matrix computation with inter-chunk recurrence.
  • MiniMax-M1, 2025: a deployed hybrid using Lightning Attention.

The comparisons use two coordinates per vector. The complete block uses the same model-dimension labels as the ordinary-attention diagram; its cells illustrate array shapes. State rows are value coordinates, so H = Σvkᵀ; the paper also uses the transposed convention. Reads include the current token.

With m value coordinates and d key features, the attention calculation costs O(Tmd) across T tokens and keeps md + d state entries per head. Efficient training implementations use matrix work within chunks and carry the state between them. Lightning Attention uses this broad approach with its own decay and normalisation choices; MiniMax-M1 uses that family of layers.

← Browse all subjectsBack to the beginning ↑