Linear Attention
By replacing the softmax with a kernel function, attention can be rewritten so keys and values are accumulated into a fixed-size running state, making the computation linear in sequence length rather than quadratic.
Why Does This Exist?
Attention complexity establishes that the softmax step forces an computation: every query scores against every key, giving compute and memory for the score matrix. Sparse attention avoids some cells; FlashAttention tiles them more efficiently. But neither changes the fundamental compute — they reduce constants or memory bandwidth, not the asymptotic cost.
Linear attention is a fundamentally different approach. The idea, going back to Katharopoulos et al. (2020), is to replace the softmax with a kernel function that satisfies a simple decomposition property, then rearrange the order of matrix multiplications. If you can write the attention score as rather than , then the matrix multiplication can be reordered: instead of computing (which needs the full matrix), compute , where the inner product can be accumulated one key-value pair at a time into a state matrix. Cost drops from to — linear in .
Think of It Like This
Tallying scores versus computing every pairwise comparison
Imagine ranking 1,000 students by comparing every pair — 500,000 comparisons. Or: compute a feature vector for each student once, then tally how well each student's features match a query profile, by multiplying the query against a running total of feature×score pairs. If the features compose additively, you never need the 500,000-pair table. The tally is a fixed-size intermediate that grows only in feature dimensionality, not in the number of students.
That's linear attention's trick. Instead of materialising all scores, accumulate a running sum of as each key arrives. When a query comes, dot it against the accumulated state. The state is , independent of how many tokens have passed.
How It Actually Works
The kernel decomposition
Standard attention:
Linear attention replaces with for some feature map (e.g., elu(x) + 1, or a random Fourier feature approximation). This gives:
The two sums (a matrix) and (a -vector) can be accumulated incrementally. For autoregressive generation, this is exactly a recurrent form: at each new token, update and with the new key-value pair, then compute the output with the current query.
The quality gap
The approximation is the price. Softmax has a property called "peakiness" — it concentrates weight on a small number of high-scoring keys. Kernel approximations tend to spread weight more evenly, losing the sharp focus that makes standard attention powerful for tasks that require attending to a specific relevant token. The gap shows up most clearly in retrieval tasks and long documents where finding a specific needle in a haystack matters.
RWKV, Mamba (with its selective SSM), and RetNet all explore different ways to get the speed of the recurrent form while recovering some of the quality.
Show Me the Code
Running a linear-attention pass with the elu + 1 feature map, and checking the output against standard attention.
import numpy as np
rng = np.random.default_rng(3)n, d = 8, 16 # tiny sequence and head dimension
Q = rng.standard_normal((n, d)) * 0.1K = rng.standard_normal((n, d)) * 0.1V = rng.standard_normal((n, d)) * 0.1
def phi(x: np.ndarray) -> np.ndarray: """elu(x) + 1 feature map — non-negative, positive-definite kernel.""" return np.where(x >= 0, x + 1, np.exp(x))
Qf, Kf = phi(Q), phi(K)
# Linear attention output (parallel form, not causal)S = Kf.T @ V # (d, d) accumulated KV statez = Kf.sum(0) # (d,) accumulated K sumout_linear = (Qf @ S) / (Qf @ z)[:, None]
# Standard softmax attention for comparisonscores = Q @ K.T / d**0.5scores -= scores.max(-1, keepdims=True)weights = np.exp(scores)weights /= weights.sum(-1, keepdims=True)out_softmax = weights @ V
diff = np.abs(out_linear - out_softmax).mean()print(f"Mean absolute difference: {diff:.4f}")# ~0.05-0.15 — approximation error, not numerical noiseThe outputs differ by a measurable amount — the approximation gap in practice. On tasks where sharp focus on a specific key matters, that gap matters too.
Watch Out For
Confusing linear complexity with exact quality
Linear attention is not an efficient implementation of softmax attention. It's a different algorithm with a different (worse) quality profile on many tasks. You don't get the O(N) speed for free — you pay in output accuracy. If your task needs sharp retrieval over long contexts, the quality gap can be the deciding factor.
Assuming the recurrent form and parallel form always give the same answer
In the causal (autoregressive) case, linear attention runs as a recurrence. The parallel training form and the sequential inference form are mathematically equivalent given the same kernel, but small floating-point differences accumulate differently. If your training and inference use different code paths, verify they agree on a small example before trusting the production output.
The Quick Version
- Linear attention replaces the softmax with a kernel function , enabling the computation to be rewritten as a running state matrix rather than an score matrix.
- Complexity drops from to — linear in sequence length.
- The recurrent form makes autoregressive inference exactly as fast as processing one token: constant compute per generated token.
- The quality gap relative to softmax attention is real and task-dependent; tasks requiring sharp focus on specific keys suffer most.
- RWKV and similar architectures build on linear attention's recurrent form while adding selective mechanisms to recover some of the lost quality.
What to Read Next
- Attention Complexity explains the cost that linear attention's kernel trick eliminates.
- State Space Models take the recurrent form idea further — a fixed-size state updated per token, but derived from control theory rather than kernel approximations.
- Self-Attention is the exact softmax mechanism linear attention approximates.
- Sparse Attention is the alternative approach — keep exact softmax but compute only a subset of cells.
- Sliding Window Attention restricts which cells are computed; linear attention changes the computation itself.