Search

Search papers and lessons

Linear Attention

Level 3 · 8 min read

Linear attention replaces the softmax similarity with a product of feature maps, so attention can be computed in time linear in sequence length instead of quadratic.

On this page

  • Colour = topic mix
  • Linear algebra
  • Architectures
  • Neural network basics
  • Discrete math
  • Efficiency
  • Probability
  • Sign in to see your progress

TL;DR

Standard attention compares every token with every other token, so the cost grows with the square of the sequence length. Linear attention changes the comparison to a product of two feature maps, ϕ(q)⊤ϕ(k)\phi(\mathbf{q})^{\top}\phi(\mathbf{k}). That product lets you sum the keys and values first and reuse the sum for every query, so the cost grows only linearly with length. The price is that the comparison is no longer the sharp softmax, and the model keeps less exact recall.

Where you'll see it: long-context language models and efficient transformer variants, and in the causal form, where a transformer is run token by token like a recurrent network with a fixed-size state.

Intuition

Filing cards instead of comparing every pair

Suppose you must answer questions about a long set of notes. The softmax way is to read every question against every note, one pair at a time. The linear way is to first build a single index card that adds up what all the notes say, weighted by their keys, and then answer each question by reading only that card. The second method does one pass over the notes plus one lookup per question, and never builds the full table of pairs.

The card has a fixed size, the same no matter how many notes you add. That is the point, and also the limit: the card can summarise the notes but cannot hold every detail separately.

Why the idea exists

For a sequence of NN tokens, softmax attention builds an N×NN \times N matrix of scores. Doubling the length quadruples the work and the memory for that matrix. Models that read books or long code need many thousands of tokens, so the quadratic term becomes the bottleneck. Linear attention removes the matrix, so the cost depends on NN only once.

The math

Definition: Softmax attention

Given queries, keys and values qi,kj∈Rd\mathbf{q}_i, \mathbf{k}_j \in \mathbb{R}^{d} and vj∈Rdv\mathbf{v}_j \in \mathbb{R}^{d_v}, the output at position ii is

oi=∑j=1Nexp⁡ ⁣(qi⊤kj/d) vj∑j=1Nexp⁡ ⁣(qi⊤kj/d).\mathbf{o}_i = \frac{\sum_{j=1}^{N} \exp\!\left(\mathbf{q}_i^{\top}\mathbf{k}_j / \sqrt{d}\right)\, \mathbf{v}_j}{\sum_{j=1}^{N} \exp\!\left(\mathbf{q}_i^{\top}\mathbf{k}_j / \sqrt{d}\right)}.

Here NN is the sequence length and dd the key dimension. The weights are positive and sum to 1 over jj.

Replace the exponential similarity with κ(q,k)=ϕ(q)⊤ϕ(k)\kappa(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^{\top}\phi(\mathbf{k}), where ϕ\phi is a feature map that sends each dd-vector to a vector of positive numbers. Katharopoulos et al. use ϕ(x)=elu⁡(x)+1\phi(x) = \operatorname{elu}(x) + 1, which is always positive. Then

oi=ϕ(qi)⊤∑jϕ(kj) vj⊤ϕ(qi)⊤∑jϕ(kj).\mathbf{o}_i = \frac{\phi(\mathbf{q}_i)^{\top} \sum_{j} \phi(\mathbf{k}_j)\,\mathbf{v}_j^{\top}}{\phi(\mathbf{q}_i)^{\top} \sum_{j} \phi(\mathbf{k}_j)}.

The two sums do not depend on ii. Define

S=∑j=1Nϕ(kj) vj⊤∈Rd×dv,z=∑j=1Nϕ(kj)∈Rd.\mathbf{S} = \sum_{j=1}^{N} \phi(\mathbf{k}_j)\,\mathbf{v}_j^{\top} \in \mathbb{R}^{d \times d_v}, \qquad \mathbf{z} = \sum_{j=1}^{N} \phi(\mathbf{k}_j) \in \mathbb{R}^{d}.

Then oi=ϕ(qi)⊤Sϕ(qi)⊤z\mathbf{o}_i = \dfrac{\phi(\mathbf{q}_i)^{\top}\mathbf{S}}{\phi(\mathbf{q}_i)^{\top}\mathbf{z}}. Computing S\mathbf{S} and z\mathbf{z} takes O(Nddv)O(N d d_v) work once. Each output then takes O(ddv)O(d d_v). The total is linear in NN, because dd is fixed.

The causal case

A language model may only look at earlier tokens. Then the sums run up to ii, and they can be updated one token at a time:

Si=Si−1+ϕ(ki) vi⊤,zi=zi−1+ϕ(ki).\mathbf{S}_i = \mathbf{S}_{i-1} + \phi(\mathbf{k}_i)\,\mathbf{v}_i^{\top}, \qquad \mathbf{z}_i = \mathbf{z}_{i-1} + \phi(\mathbf{k}_i).

This is the recurrent form. The state has fixed size d×dvd \times d_v plus a vector, whatever the length. It is why linear attention is related to the recurrent network in the paper's title.

Cost comparison

Softmax attention forms N2N^2 scores, each a dot product of length dd, so the score work is N2dN^2 d. Linear attention forms S\mathbf{S}, which costs Nd2N d^2 when dv=dd_v = d. The ratio of the two is

N2dNd2=Nd.\frac{N^2 d}{N d^2} = \frac{N}{d}.

So linear attention is cheaper once the sequence is longer than the key dimension.

Worked examples

Example
A tiny causal example by hand

Use scalars, so d=1d = 1, and take the feature map ϕ(x)=x+1\phi(x) = x + 1. For positive xx this matches elu⁡(x)+1\operatorname{elu}(x) + 1. Let the keys be k1=1,k2=2,k3=3k_1 = 1, k_2 = 2, k_3 = 3, so ϕ(kj)=2,3,4\phi(k_j) = 2, 3, 4. Let the values be v1=1,v2=3,v3=5v_1 = 1, v_2 = 3, v_3 = 5. Let every query be qi=1q_i = 1, so ϕ(qi)=2\phi(q_i) = 2 for each ii. Because the feature of the query is a common factor in numerator and denominator, the outputs reduce to a weighted average of values.

  1. Output at i=1i = 1 uses only j=1j = 1:   y1=2⋅12=1\;y_1 = \dfrac{2 \cdot 1}{2} = 1.
  2. Output at i=2i = 2 uses j=1,2j = 1, 2:   y2=2⋅1+3⋅32+3=115=2.2\;y_2 = \dfrac{2 \cdot 1 + 3 \cdot 3}{2 + 3} = \dfrac{11}{5} = 2.2.
  3. Output at i=3i = 3 uses j=1,2,3j = 1, 2, 3:   y3=2⋅1+3⋅3+4⋅52+3+4=319≈3.44\;y_3 = \dfrac{2 \cdot 1 + 3 \cdot 3 + 4 \cdot 5}{2 + 3 + 4} = \dfrac{31}{9} \approx 3.44.

Check with the recurrent form. Start with S0=0S_0 = 0 and z0=0z_0 = 0. After token 1, S1=2⋅1=2S_1 = 2 \cdot 1 = 2 and z1=2z_1 = 2, so y1=2/2=1y_1 = 2/2 = 1. After token 2, S2=2+9=11S_2 = 2 + 9 = 11 and z2=5z_2 = 5, so y2=11/5y_2 = 11/5. After token 3, S3=11+20=31S_3 = 11 + 20 = 31 and z3=9z_3 = 9, so y3=31/9y_3 = 31/9. The two methods agree.

Interpretation: each output is a running weighted average of the values seen so far. Later tokens with larger features pull the average toward their values.

Example
Long sequence, realistic sizes

Take N=4096N = 4096 tokens and key dimension d=64d = 64.

  1. Softmax score work: N2d=40962×64=16,777,216×64≈1.07×109N^2 d = 4096^2 \times 64 = 16{,}777{,}216 \times 64 \approx 1.07 \times 10^{9} multiply-adds.
  2. Linear attention work: Nd2=4096×4096=16,777,216≈1.68×107N d^2 = 4096 \times 4096 = 16{,}777{,}216 \approx 1.68 \times 10^{7} multiply-adds.
  3. Ratio: N/d=4096/64=64N / d = 4096 / 64 = 64.

Interpretation: at this length the linear form does about 64 times less of the main work. The gap grows as NN grows, and it is the same whatever the hardware, since it counts operations, not time. Real speedups also depend on memory traffic and on how well the code is written.

Tradeoffs and failure modes

SituationProblemBetter choice
Very long input, memory limitedSoftmax matrix does not fitLinear attention, or a sparse or windowed method
Task needs exact recall of one earlier tokenFixed-size state blurs individual tokensSoftmax attention, or a hybrid with some softmax layers
Short sequences, NN not much larger than ddLittle or no speed gainSoftmax attention, which is also well optimised
Feature map gives a near-zero denominatorDivision is unstable, outputs blow upChoose a positive, bounded feature map; add a small constant
Autoregressive generationNeed a cache that grows with lengthThe recurrent form, whose state does not grow

The main failure is quality, not speed. Softmax concentrates weight on a few tokens, while the feature map spreads it over many, so tasks that need sharp retrieval can suffer. How large that gap is depends on the task and the feature map; this lesson does not quote a figure for it.

The method is also sensitive to how the feature map interacts with position information. A position term added before the projections does not split cleanly into the product form, and the RoPE paper argues that this is why rotary embeddings suit linear attention better. See Rotary Position Embedding.

History

Attention with a weighted sum over a sequence came from machine translation work by Bahdanau, Cho and Bengio in 2014, and the softmax form became standard with the transformer of Vaswani and colleagues in 2017. The quadratic cost of that form was known from the start, and many variants followed to reduce it.

Linear attention was introduced by Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas and François Fleuret, who published "Transformers are RNNs" at ICML in 2020. They showed the causal recurrent form and the speed gain on long sequences. In their experiments on image generation and speech recognition, the linear transformer reached quality close to the softmax transformer while generating images orders of magnitude faster (up to 4,000 times in their CIFAR-10 setup, which the paper attributes to the constant-size state).

Check yourself

QuestionWhy does the cost of softmax attention grow quadratically with sequence length, and what does linear attention change?Show answer

Softmax attention compares every query with every key, which forms an N×NN \times N matrix. Linear attention replaces the similarity with ϕ(q)⊤ϕ(k)\phi(\mathbf{q})^{\top}\phi(\mathbf{k}), so the sums over keys and values can be computed once as S\mathbf{S} and z\mathbf{z} and reused for every query. The matrix is never formed, so the cost is linear in NN for fixed dd.

QuestionUsing the feature map ϕ(x)=x+1\phi(x) = x + 1 with keys 1,21, 2, values 1,31, 3, and a query with ϕ(q)=2\phi(q) = 2, compute the output at the second position with causal masking.Show answer

Keys 1,21, 2 give ϕ(k)=2,3\phi(k) = 2, 3. The output is 2⋅1+3⋅32+3=115=2.2\dfrac{2 \cdot 1 + 3 \cdot 3}{2 + 3} = \dfrac{11}{5} = 2.2. The query feature cancels from numerator and denominator, so the output is a weighted average of the values, using the key features as weights.

QuestionWhy is the state of the causal form useful for generation, and what does it cost?Show answer

Each new token updates S\mathbf{S} and z\mathbf{z} in constant size, so memory does not grow with the number of tokens generated. The cost is that the whole past is squeezed into a fixed d×dvd \times d_v matrix, so exact recall of one earlier token is weaker than with a cache of all keys and values.

QuestionA team has sequences of 128 tokens with key dimension 64 and wants to switch to linear attention for speed. Is this a good idea?Show answer

Not on speed grounds. The ratio of score work is N/d=128/64=2N / d = 128 / 64 = 2, so the gain is at most about two times, and the implementation overhead can cancel it. A softmax baseline is likely to be faster in practice and better in quality at this length. Linear attention pays off when NN is many times dd.

Sources