AI State of the Art
SOTA/Advanced Attention Mechanisms/25 min
Section 80

Linear Attention and Sub-quadratic Alternatives

Listen as a podcast β†’

The fundamental problem with softmax

Standard Transformer attention:

Attention=softmax(QK⊀)Γ—V\text{Attention} = \text{softmax}(QK^\top) \times V

A reminder of the symbols: QQ, KK and VV are the queries, keys and values computed over the sequence, matrices with one row per token, so LL rows for a sequence of LL tokens. The softmax turns each row of scores into positive weights that sum to 1.

Softmax is the culprit. It ties together all token pairs (qi,kj)(q_i, k_j) in a global dependency. To compute the attention weight of a single token, you need to know the scores of ALL other tokens (because of the softmax normalization). Result: impossible to factorize the computation. We're stuck at O(L2)O(L^2).

For a sequence of 100K tokens, that's 101010^{10} operations just for attention. Linear attention proposes an elegant solution: replace softmax with something factorizable.

The trick: replace softmax with a kernel

Instead of softmax, we use a kernel function Ο†\varphi (here, "kernel" refers to a function that transforms Q and K vectors before multiplying them, not to be confused with the "kernel trick" from SVMs mentioned below) that transforms queries and keys independently:

LinAttn=Ο†(Q)Γ—Ο†(K)βŠ€Γ—Vnormalizer\text{LinAttn} = \frac{\varphi(Q) \times \varphi(K)^\top \times V}{\text{normalizer}}

So far, nothing has changed in terms of complexity. The real trick is to reorder the matrix multiplications. Once the softmax is gone, all that remains is a product of three matrices, and matrix products are associative: you can compute them in any order, the result is identical.

(Ο†(Q) φ(K)⊀) Vβ€…β€Š=β€…β€ŠΟ†(Q) (Ο†(K)⊀V)\big(\varphi(Q)\,\varphi(K)^\top\big)\, V \;=\; \varphi(Q)\,\big(\varphi(K)^\top V\big)

Same result, very different cost. Let's write out the dimensions:

BEFORE (parentheses on the left): Ο†(Q)\varphi(Q) is LΓ—dL \times d (one row per token) and Ο†(K)⊀\varphi(K)^\top is dΓ—Ld \times L. Their product Ο†(Q) φ(K)⊀\varphi(Q)\,\varphi(K)^\top is therefore an LΓ—LL \times L matrix, a score for every pair of tokens. For L=100,000L = 100{,}000, that's 10 billion cells to fill. This is exactly what standard attention does, softmax included: complexity O(L2Γ—d)O(L^2 \times d), the famous quadratic wall.

AFTER (parentheses on the right): you start with Ο†(K)⊀V\varphi(K)^\top V, the product of a dΓ—Ld \times L matrix by an LΓ—dL \times d matrix. Result: a small dΓ—dd \times d matrix, its size no longer depends on LL at all. You then multiply it by Ο†(Q)\varphi(Q) (LΓ—dL \times d). Each of the two products sweeps the LL tokens exactly once: complexity O(LΓ—d2)O(L \times d^2), linear in sequence length.

Here dd is the dimension of the vectors after the Ο†\varphi transformation (a few dozen to a few hundred), and LL the sequence length (potentially hundreds of thousands): trading a cost in L2L^2 for a cost in d2d^2 changes everything.

The small matrix Ο†(K)⊀V\varphi(K)^\top V acts as a "compressed summary" of all the key-value information. Each query only needs to consult this summary instead of looking at each token individually. And if the softmax blocked this reorganization, it's because it applies to each entire row of the LΓ—LL \times L matrix: you have to build the big matrix before you can compute it.

Diagram made of three-dimensional blocks standing for matrices, split into two halves by a struck-through equals sign topped with the letter E. On the left, boxed in red dashes and labelled attention mechanism, two blocks are multiplied together: a large light-blue block labelled A of size L by L, annotated with the complexity O of L squared times d, and a yellow block labelled V of size L by d. On the right, three blocks multiplied in sequence: a red block labelled Q prime of size L by r, annotated O of L times r times d, then, inside a blue dashed frame also annotated O of L times r times d, a green block labelled K prime transposed of size r by L and the same yellow block V of size L by d.
The reordering of the multiplications, in pictures. On the left, standard attention: the square L by L matrix A is built first, which costs O of L squared. On the right, the linear version: you start with the small product K prime transposed times V (the blue frame), which no longer depends on sequence length, and only then multiply by Q prime. Same result, but the huge L by L matrix is never materialised.Source : Performer paper, Rethinking Attention with Performers (figure 1), via A round-up of linear transformers
The kernel trick applied to attention

This is literally the kernel trick from kernel theory, applied to the attention mechanism. Instead of computing an explicit LΓ—LL \times L matrix, we go through an intermediate space of fixed dimension. The same idea that allows SVMs (Support Vector Machines, a classic family of classification algorithms) to work in infinite dimensions without exploding in computation.

Main approaches

Linear Transformer (ELU + 1)

The simplest version: use Ο†(x)=elu(x)+1\varphi(x) = \text{elu}(x) + 1 as the kernel.

Why elu + 1? ELU (Exponential Linear Unit) is a standard activation function, smooth and differentiable everywhere (good for training), and adding 1 guarantees that values are strictly positive (necessary because attention weights must be non-negative).

Simple, elegant, easy to implement. The starting point for the entire family.

Performer (Random Fourier Features)

The Performer takes a more mathematically rigorous approach. It uses random features inspired by Fourier analysis (the decomposition of a signal into simple waves) to approximate the softmax:

softmax(QK⊀)β‰ˆΟ†(Q)Γ—Ο†(K)⊀\text{softmax}(QK^\top) \approx \varphi(Q) \times \varphi(K)^\top

In other words: Ο†\varphi isn't chosen freely, but designed so that the product of the transformed vectors reproduces, on average, what the softmax would have given.

The FAVOR+ algorithm (Fast Attention Via positive Orthogonal Random features) improves this approximation with orthogonal features to reduce variance. Complexity: O(Lmd)O(Lmd) where mm is the number of random features (typically mβ‰ͺLm \ll L, far fewer than the sequence length).

Performer: a rigorous approximation

The Performer shows that you can approximate the softmax kernel via random features with theoretical guarantees on approximation error. It's the most "mathematically clean" version of linear attention.

cosFormer

An approach that combines linear attention with a local positional bias:

Ai,j=ReLU(Qi)Γ—ReLU(Kj)Γ—cos⁑ ⁣(Ο€2β‹…iβˆ’jL)A_{i,j} = \text{ReLU}(Q_i) \times \text{ReLU}(K_j) \times \cos\!\left(\frac{\pi}{2} \cdot \frac{i-j}{L}\right)

In this formula, Ai,jA_{i,j} is the attention weight between the tokens at positions ii and jj, and ReLU (Rectified Linear Unit) is the function that zeroes out negative values, here it guarantees positive weights. The cosine term favors nearby tokens (small distance iβˆ’ji-j) and penalizes distant tokens. It's an elegant way to incorporate locality bias without going back to O(L2)O(L^2).

Gated Linear Attention (GLA)

The most promising evolution. A gate is added, inspired by RNNs (Recurrent Neural Networks, LSTM lesson):

state[t]=gate[t]βŠ™state[tβˆ’1]+K[t]⊀V[t]output[t]=Q[t]Γ—state[t]\begin{aligned} \text{state}[t] &= \text{gate}[t] \odot \text{state}[t-1] + K[t]^\top V[t] \\ \text{output}[t] &= Q[t] \times \text{state}[t] \end{aligned}

A few details on this formulation:

  • βŠ™\odot denotes the Hadamard product, i.e., element-wise multiplication between two matrices of the same dimension.
  • gate[t][t] is a learned vector (dependent on the input at step tt) whose each component is between 0 and 1. It controls how much of the previous state is retained at each position, this is exactly the role of the "forget gate" in an LSTM (Long Short-Term Memory). A gate close to 1 preserves memory, a gate close to 0 erases it.
  • K[t]⊀V[t]K[t]^\top V[t] injects the new key-value association into the state.

The intuition: this recurrence mimics attention by progressively accumulating key-value associations in a compressed state. Instead of recomputing attention over all past tokens (cost O(L2)O(L^2)), each new token updates a fixed-size summary. The query Q[t]Q[t] then queries this summary, just as it would query the full attention matrix in standard attention.

SSM and linear attention convergence

Recent work reveals that SSMs (State Space Models, like Mamba, dedicated lesson) and linear attention are fundamentally the same mathematical object, just formulated differently. Mamba-2 has indeed unified both in a single framework. GLA is linear attention that looks like an SSM. Mamba is an SSM that looks like linear attention.

The recurrent formulation

Linear attention can also be written as a recurrence, which is crucial for inference:

Sn=Snβˆ’1+Ο†(Kn)⊀Vnzn=znβˆ’1+Ο†(Kn)outputn=Ο†(Qn)Γ—SnΟ†(Qn)Γ—zn\begin{aligned} S_n &= S_{n-1} + \varphi(K_n)^\top V_n \\ z_n &= z_{n-1} + \varphi(K_n) \\ \text{output}_n &= \frac{\varphi(Q_n) \times S_n}{\varphi(Q_n) \times z_n} \end{aligned}

Let's detail each component:

  • SnS_n is the state matrix of dimension dφ×dvd_\varphi \times d_v. It accumulates transformed key-value associations: at each step, the term Ο†(Kn)⊀Vn\varphi(K_n)^\top V_n (an outer product of dimensions dφ×dvd_\varphi \times d_v) is added to it. SS encodes a compressed summary of all past context.
  • znz_n is the normalization vector of dimension dΟ†d_\varphi. It accumulates transformed keys Ο†(Kn)\varphi(K_n) across the sequence.
  • The division Ο†(Qn)Γ—SnΟ†(Qn)Γ—zn\frac{\varphi(Q_n) \times S_n}{\varphi(Q_n) \times z_n} plays the role of softmax in standard attention. The numerator computes the weighted sum of values, and the denominator normalizes so the effective weights sum to 1. This is exactly what softmax does, except here the normalization is done via the product Ο†(Q)Γ—z\varphi(Q) \times z instead of a global exponential.

At each new token, you update SS and zz in O(d2)O(d^2), then compute the output. No need for a KV cache that grows with the sequence: the state has a constant size.

This is exactly the structure of an RNN/SSM: a hidden state updated recursively. Linear attention and SSMs are two sides of the same coin.

Figure split into three boxed panels. Left panel, titled Linear Parallel Form: the matrices K transposed of size d by N and V of size N by d are multiplied, step 1, giving a state H of size d by d, which the matrix Q of size N by d then multiplies, step 2, to produce the output O of size N by d. Middle panel, titled Recurrent Form: the outer product of k t transposed, of size d by 1, and v t, of size 1 by d, is added to the previous state H t minus 1, step 1, yielding H t of size d by d, step 2; the vector q t of size 1 by d then multiplies H t to produce the output o t of size 1 by d, step 3. Right panel, titled Chunkwise Form: a chunk output is the sum of an inter-chunk term obtained by multiplying Q of chunk i by the state H of the previous chunk and an intra-chunk term obtained by multiplying Q of chunk i by K of chunk i transposed under a mask M, then by V of chunk i; on the right, the update of the state H of chunk i as the sum of H of the previous chunk and the product of K of chunk i transposed by V of chunk i.
The two formulations described above, side by side. On the left the parallel form, used during training: the state H is computed in one shot from the whole sequence. In the middle the recurrent form, used at inference: at each token an outer product is added to the state and the query reads it back, exactly the recurrence S n equals S n minus 1 plus phi of K n transposed times V n. On the right, the chunkwise form, the compromise actually used on GPUs: the sequence is processed in chunks so that large matrix products are preserved while the state stays fixed-size.Source : Efficient Attention Methods survey (Zhang et al., Tsinghua, UC Berkeley, MIT)

The major problem: quality

Despite its complexity advantages, linear attention is systematically less performant than softmax on language tasks. Why?

Softmax creates a peaked distribution: it puts a lot of weight on a few key tokens and near-zero on the rest. This is extremely effective for "selecting" precisely the relevant information in a long sequence.

Linear kernels produce more diffuse and uniform distributions. The model struggles to ignore irrelevant tokens. It's like trying to follow a conversation in a noisy room without being able to "filter out" the background voices.

Chart titled Attention Distribution Sharpness. The horizontal axis shows entropy in nats, from 0 to about 3.5; the vertical axis shows density, from 0 to over 25. A blue curve labelled Softmax Attention forms a very low, very wide carpet spanning the whole range from 0 to about 2.3. A red curve labelled Linear Attention (ELU) instead forms a narrow, very tall spike peaking near 25, just to the left of a grey dashed vertical line labelled Max entropy (log 32) located around 3.45.
Selectivity, measured. The entropy of an attention distribution tells you how spread out it is: low when the model concentrates on a few tokens, maximal when it spreads its weight uniformly. Softmax (blue) sweeps the whole range, from very peaked to diffuse, depending on what it needs. Linear attention (red) stays pinned to the theoretical maximum: it is almost always diffuse, and so has no way of saying I am listening to this token only.Source : Michael Brenndoerfer, Linear Attention: Breaking the Quadratic Bottleneck with Kernel Feature Maps
Selectivity: the Achilles' heel

With softmax, a token can say "I'm listening ONLY to that specific token, zero weight on all others." With a linear kernel, this perfect selectivity is mathematically impossible. The model must learn to ignore distractions indirectly, which costs expressiveness and performance.

Comparative benchmarks

ApproachComplexityQuality vs softmaxInference state
Standard softmaxO(L^2)ReferenceO(L) cache (KV cache)
Linear TransformerO(L)Clearly behindFixed state
PerformerO(Lm)Behind (approximation)Fixed state
GLAO(L)Closest to the referenceFixed state

(The exact gap depends on tasks and model sizes; the ordering, though, is constant across the literature: softmax first, GLA ahead of ungated kernels.)

Current relevance

Pure linear attention? It lost the battle against softmax for LLMs. It's been superseded by selective SSMs (Mamba) that restore selectivity while remaining at linear complexity.

But linear attention concepts are alive and omnipresent:

  • GLA appears in modern hybrid architectures
  • RetNet combines linear attention with a temporal decay factor
  • Mamba-2 formally unifies SSMs and linear attention
The legacy of linear attention

Linear attention revealed a deep truth: the bottleneck of attention isn't really the O(L2)O(L^2) complexity, it's the selectivity that softmax provides. Successors (selective SSMs, hybrid architectures) learned this lesson and solve the problem differently, restoring selectivity without going through softmax.

Check your understanding0 / 4

1. Once the softmax is gone, linear attention merely reorders the matrix multiplications. What does that reordering actually change?

2. Why does linear attention remain systematically weaker than softmax on language tasks?

3. At inference time, what advantage does the recurrent formulation of linear attention bring?

4. In Gated Linear Attention, what is the gate added to the recurrence for?