Why Replace Attention? The Softmax Bottleneck and the Path to Linear Time
Why softmax is the bottleneck that every attention variant leaves untouched — and how rewriting attention as a kernel exposes an associativity trick that collapses the O(n²) cost to O(n) and turns the transformer into an RNN.
Every change made to attention so far has touched the periphery — which keys participate, how they are stored, what wraps the block — but left the formula
This blog asks the next question: what if the softmax is the problem? The exponential and the denominator force every query to see every key before producing an output. That is what makes attention quadratic. Drop the softmax and the algebra changes — multiplication becomes associative, and a different grouping turns O(n2) into O(n) with constant memory per token. The transformer becomes an RNN.
The core paper for this blog is Katharopoulos et al. (2020), “Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention,” supplemented by the taxonomy from the Efficient Transformers survey (Tay et al., 2022).
The Running Example
We continue with the same model parameters from the series:
For cost analysis, we use n=16 tokens (same sequence from the Sparse Factorization, Sliding Window, and DeepSeek Sparse Attention blogs) and scale up to n=128,000 to show how costs grow.
For the kernel and associativity derivations, we need to trace every matrix entry by hand. We use a tiny example:
n=4 tokens, dk=dv=2, single head
with concrete query, key, and value matrices:
Q=10120110,K=01101012,V=10120110
Each row is one token. Q has 4 rows (one per query), K has 4 rows (one per key), V has 4 rows (one per value). All matrices are 4×2.
1. The Cost Ledger After Twelve Blogs
1.1 What we modified, axis by axis
Every blog in the series made a change to exactly one axis of the taxonomy from the Taxonomy blog. Here is the complete map:
Blog
Topic
Axis
What changed
1–3
Attention basics
—
Setup and motivation
4
Taxonomy
—
The five-axis framework
5
Residuals
5
Skip connections
6
MQA / KV Bottleneck
2
Shared KV across heads
7
GQA
2
Grouped KV sharing
8
MLA
2
Low-rank KV compression
9
Sparse Transformer
3
Fixed factorized patterns
10
Sliding Window
3
Local windows + global tokens
11
DeepSeek Sparse
3
Learned token selection
12
Gated Attention
5
Gated residuals and SwiGLU FFN
Axes 2, 3, and 5 have been thoroughly explored. Axis 1 (number of heads) is implicitly handled by GQA. Axis 4 (KV cache and storage) was touched by MLA’s compressed latent.
1.2 What remains unchanged
Despite all these modifications, every blog preserved two things:
The softmax normalization. Every variant computes exp(qi⊤kj/dk) for the query-key pairs that participate, then normalizes by the sum of exponentials. This forces the model to evaluate all participating pairs before producing any output.
The per-query dependence on all keys. Even in the sparse variants, the attention output for query i depends on the full set of selected keys through the softmax denominator. You cannot compute the output for token i without knowing the scores for all tokens in its connectivity set.
These two properties have a direct consequence: the attention operation cannot be decomposed into independent per-token computations. Every query must “see” its full key set before producing an output. This is the fundamental difference between attention and recurrence.
2. The Cost at Scale
2.1 Training: FLOPs per attention layer
For one head of standard causal attention on n tokens with head dimension dk, the dominant operations are:
Step 1: Compute QK⊤. This is an (n×dk)×(dk×n) matrix multiplication, producing an n×n matrix. The number of multiply-add operations is:
n×n×dk=n2dk
Step 2: Apply softmax. This requires exponentiation and normalization over each row — O(n) per row, O(n2) total. Dominated by the matrix multiply.
Step 3: Compute AV. This is an (n×n)×(n×dv) matrix multiplication, producing an n×dv matrix:
n×dv×n=n2dv
With dk=dv, the total per-head cost is:
FLOPs per head=2n2dk
Across h heads:
FLOPs per layer=h×2n2dk=2n2(hdk)=2n2dmodel
The last step uses hdk=dmodel, the identity that has appeared throughout this series.
2.2 Numerical check
With n=16, dmodel=512:
2×162×512=2×256×512=262,144 FLOPs per layer
With n=128,000:
2×128,0002×512=2×1.6384×1010×512=1.678×1013 FLOPs per layer
That is 16.78 trillion FLOPs per layer for a single forward pass on 128K tokens. Across L=12 layers:
12×1.678×1013=2.01×1014 FLOPs
This is just the attention — the FFN adds a comparable amount (2×dmodel×dff×n=2×512×2048×128,000≈2.68×1011 per layer, much smaller than the attention cost at this sequence length). At n=128,000, attention dominates.
2.3 The crossover point
The FFN cost per layer is 2dmodeldffn, which is linear in n. The attention cost is 2n2dmodel, which is quadratic in n. Setting them equal:
2n2dmodel=2dmodeldffn
The 2dmodel cancels from both sides:
n2=dffn
Divide both sides by n (valid since n>0):
ncrossover=dff
With dff=2048, the crossover is at n=2,048 tokens. For sequences shorter than 2,048 tokens, the FFN costs more than attention. For sequences longer than 2,048 tokens, attention dominates — and it dominates more with every additional token.
At n=128,000: attention is 1.678×1013, FFN is 2.68×1011. The ratio is 1.678×1013/2.68×1011≈62.6×. Attention costs 63 times more than the FFN.
2.5 What sparse methods achieve
Our sparse methods from the Sparse Factorization, Sliding Window, and DeepSeek Sparse Attention blogs reduce the attention cost:
Method
Attention FLOPs per layer
At n=128,000
Full
2n2dmodel
1.678×1013
Sparse Transformer (O(nn))
2n3/2dmodel⋅c
∼4.7×1010
Sliding window (w=512)
2nwdmodel
∼6.71×1010
DSA (k=2,048)
2nkdmodel
∼2.68×1011
These are enormous improvements. But notice: even the cheapest method (Sparse Transformer) still has a cost that grows super-linearly with n. And all three methods still require the softmax over the selected pairs — the O(∣St∣) normalization per query token. The cost is reduced but the mechanism is the same.
2.6 Interpretation
Sparse methods do not change the nature of the computation. They reduce how many pairs participate, but each participating pair still requires the full softmax pipeline: exponentiate, sum, normalize, multiply by values. The question this blog asks is: can we change the mechanism itself to eliminate the need for pairwise computation entirely?
3. The KV Cache Wall
3.1 Memory during autoregressive generation
During training, we pay the quadratic cost once for the full sequence. During inference (autoregressive generation), the cost is paid incrementally: each new token computes attention against all previous tokens.
For token t (the t-th generated token), the attention computation requires loading all previous key and value vectors from the KV cache. Each token stores:
Bytes per token=2×h×dk×2=4hdk=4dmodel bytes
The factor of 2 at the front accounts for both keys and values. The factor of 2 at the end is for fp16 (2 bytes per element). We simplify using hdk=dmodel.
Across L layers:
Bytes per token, all layers=4dmodelL
3.2 Numerical check
With dmodel=512 and L=12:
4×512×12=24,576 bytes=24 KB per token
After generating n tokens, the KV cache occupies:
Total KV cache=4dmodelLn
At n=128,000:
4×512×12×128,000=3.15×109 bytes≈3.15 GB
For a model with dmodel=512, this is manageable. But real models are much larger. For a model with dmodel=8,192 (comparable to GPT-4 class models) and L=80 layers:
4×8,192×80×128,000=3.36×1011 bytes≈336 GB
That is 336 GB just for the KV cache — more than the memory of most GPUs. This is the KV cache wall: the point where the memory required to store past keys and values exceeds available GPU memory.
3.3 The per-token generation cost
When generating token t, the attention computation for one head involves:
Compute qt⊤kj for all j∈{1,…,t}: t×dk multiply-adds
Apply softmax over t scores: O(t) operations
Compute weighted sum ∑jαjvj: t×dv multiply-adds
Total per head: 2tdk. Across all heads and layers:
FLOPs for token t=2tdk×h×L=2tdmodelL
The cost to generate token t grows linearly with t — each new token is slower than the last.
3.4 Numerical check
Generating the 128,000th token:
2×128,000×512×12=1.57×109 FLOPs
Generating the 1st token:
2×1×512×12=12,288 FLOPs
The last token costs 128,000× more than the first. In wall-clock time, this means generation slows down as the sequence gets longer — each successive token takes more time to produce.
3.5 The total generation cost
To generate all n tokens:
Total FLOPs=t=1∑n2tdmodelL=2dmodelLt=1∑nt=2dmodelL⋅2n(n+1)=dmodelLn(n+1)
The sum ∑t=1nt=2n(n+1) is Gauss’s summation formula. For large n:
Total generation FLOPs≈dmodelLn2
Quadratic in n, again.
3.6 What an RNN gives you
Contrast this with a recurrent neural network. An RNN maintains a fixed-size hidden state ht∈Rd and updates it at each step:
ht=f(ht−1,xt)
The cost to generate each token is constant — O(d2) for the matrix-vector multiplication in f, regardless of position t. The total cost for n tokens is O(nd2) — linear in n. The memory is O(d) — constant, regardless of how many tokens have been generated.
Property
Attention
RNN
State size at step t
O(t⋅d) — grows
O(d2) — constant
Cost per token at step t
O(t⋅d) — grows
O(d2) — constant
Total cost for n tokens
O(n2d) — quadratic
O(nd2) — linear
Can access token 1 from token n?
Yes, directly
Only through state
The last row is the tradeoff. Attention pays a growing cost because it maintains direct access to every past token. An RNN pays a constant cost because it compresses all past information into a fixed-size state — but that compression is lossy.
The question is: can we get the best of both worlds? Linear cost like an RNN, but with the expressivity of attention?
The answer begins with examining why the softmax makes the cost quadratic.
4. The Softmax Bottleneck
4.1 The attention output for one query
Let us write the attention output for a single query token i in full generality. For a single head:
This is a weighted average of the value vectors vj, where the weight on vj is proportional to exp(qi⊤kj/dk).
Let us define sim(q,k) as the similarity function between a query and a key:
sim(q,k)=exp(dkq⊤k)
Then the attention output becomes:
oi=∑j=1nsim(qi,kj)∑j=1nsim(qi,kj)vj
This is the form we will work with for the rest of this blog. The specific choice of similarity function determines everything.
4.2 Why softmax forces pairwise computation
This is the part that is easy to gloss over but is the crux of the entire blog.
With the exponential similarity sim(q,k)=exp(q⊤k/dk), the weight for the pair (i,j) depends on the specific combination of qi and kj. The exponential of a dot product cannot be factored:
exp(qi⊤kj/dk)=f(qi)⋅g(kj)
for any scalar functions f and g. The reason is that the dot product qi⊤kj=∑mqi,mkj,m mixes the components of qi and kj inside the exponential, and exp(a+b)=exp(a)exp(b) only factors when the argument is a sum — but the sum is over the dk dimensions, not over the queries and keys.
To be precise: exp(qi⊤kj/dk)=exp(∑mqi,mkj,m/dk)=∏mexp(qi,mkj,m/dk). Each factor in the product involves both qi,m and kj,m multiplicatively inside the exponential. There is no way to separate this into “a function of qi only” times “a function of kj only” using a finite number of terms.
This means we must compute sim(qi,kj) for every pair (i,j) separately. There are n2 such pairs. No algebraic rearrangement can avoid this.
4.3 Numerical illustration
Let us verify this with our running example. Take query q1=(1,0) and compute its similarity with all 4 keys (using dk=2):
Each similarity score is different and depends on both q1 and the specific key. We had to compute 4 exponentials — one per key. For all 4 queries, we would need 4×4=16 exponentials. In general: n2.
4.4 The denominator forces full evaluation
Even if we only cared about one value in the output oi, we would still need all n similarity scores for query i because of the denominator ∑j=1nsim(qi,kj). The denominator is a sum over all keys — you cannot know the correct normalization without evaluating every key.
This is the fundamental constraint. The softmax denominator couples all keys together for each query. It prevents streaming or incremental computation of the output.
4.5 What if we could factor the similarity?
Suppose instead we had a similarity function that could be written as:
sim(q,k)=ϕ(q)⊤ϕ(k)
for some feature mapϕ:Rdk→Rdϕ that maps each query or key independently into a new space of dimension dϕ. Then:
oi=∑j=1nϕ(qi)⊤ϕ(kj)∑j=1nϕ(qi)⊤ϕ(kj)vj
Now ϕ(qi)⊤ϕ(kj) is a scalar (a dot product in the feature space), so ϕ(qi)⊤ϕ(kj)vj is a scalar times a vector. The sum ∑jϕ(qi)⊤ϕ(kj)vj involves ϕ(qi) interacting with the ϕ(kj) vectors, and crucially, we can rearrange this sum. This rearrangement is the key to everything that follows.
5. Attention as a Kernel Function
5.1 The kernel interpretation
The formulation sim(q,k)=ϕ(q)⊤ϕ(k) is a kernel function from the theory of reproducing kernel Hilbert spaces. A kernelκ(x,y) is any function that can be written as an inner product in some (possibly high-dimensional) feature space:
κ(x,y)=⟨ϕ(x),ϕ(y)⟩
The function ϕ is called the feature map. It transforms inputs from the original space into a feature space where inner products correspond to similarities.
This is the connection to kernel methods in machine learning — the same mathematical framework behind support vector machines and Gaussian processes. The survey by Tay et al. (2022) categorizes Linear Transformers (Katharopoulos et al., 2020) and Performers (Choromanski et al., 2020) under the “Low Rank / Kernels” class of efficient transformers, precisely because they exploit this kernel structure.
5.2 Can softmax attention be written as a kernel?
The softmax similarity sim(q,k)=exp(q⊤k/dk) is indeed a valid kernel. It can be written as an inner product in a feature space — but that feature space is infinite-dimensional. By the Taylor expansion of the exponential function:
exp(q⊤k/dk)=m=0∑∞m!(q⊤k/dk)m
Each term (q⊤k)m can be expanded as a sum of products of components of q and k, which corresponds to a feature map that includes all monomials of degree m in the components of q (and similarly for k). The full feature map includes monomials of all degrees — an infinite-dimensional vector.
So the softmax kernel has a feature map ϕ, but ϕ(q) is an infinite-dimensional vector. We cannot compute ϕ(q)⊤ϕ(k) by first computing ϕ(q) and ϕ(k) separately — the vectors have infinitely many entries. We are forced to compute the kernel value exp(q⊤k/dk) directly, which brings us back to pairwise computation.
5.3 The key idea: use a different kernel
Katharopoulos et al. (2020) propose a simple solution: replace the softmax kernel with a kernel that has a finite-dimensional feature map. Instead of sim(q,k)=exp(q⊤k/dk), use:
sim(q,k)=ϕ(q)⊤ϕ(k)
where ϕ:Rdk→Rdϕ is a finite-dimensional feature map. Their specific choice is:
ϕ(x)=elu(x)+1
where elu is the exponential linear unit (Clevert et al., 2015):
elu(x)={xex−1if x>0if x≤0
Applied element-wise to a vector x∈Rdk, this gives ϕ(x)∈Rdk — the feature map has the same dimension as the input (dϕ=dk). The +1 ensures that all components of ϕ(x) are non-negative, which guarantees that the similarity ϕ(q)⊤ϕ(k)≥0 — a necessary property since attention weights must be non-negative.
5.4 Why non-negativity matters
In softmax attention, exp(q⊤k/dk)>0 always — the exponential function is strictly positive. This guarantees positive attention weights, which means the output is a proper weighted average of the value vectors.
If we replace the similarity with ϕ(q)⊤ϕ(k) and ϕ maps to non-negative outputs, then the dot product of two non-negative vectors is non-negative: ϕ(q)⊤ϕ(k)=∑mϕ(q)mϕ(k)m≥0 since every term is a product of non-negative numbers. This preserves the weighted-average interpretation.
5.5 Numerical example: computing the feature map
Let us apply ϕ(x)=elu(x)+1 to the queries and keys from our running example.
Queries:
ϕ(q1)=ϕ(10)=(elu(1)+1elu(0)+1)=(1+10+1)=(21)
For x>0, elu(x)=x, so ϕ(x)=x+1. For x=0, elu(0)=0, so ϕ(0)=0+1=1.
5.6 Numerical check: kernel similarity vs dot product
Let us verify that ϕ(qi)⊤ϕ(kj) gives a reasonable similarity measure. Compare with the softmax similarity from Section 4.3 for q1:
Pair
ϕ(q1)⊤ϕ(kj)
exp(q1⊤kj/2)
(1,1)
(2)(1)+(1)(2)=4
1.000
(1,2)
(2)(2)+(1)(1)=5
2.028
(1,3)
(2)(2)+(1)(2)=6
2.028
(1,4)
(2)(1)+(1)(3)=5
1.000
The rankings differ: the kernel similarity ranks key 3 highest (score 6) while softmax gives keys 2 and 3 equal scores (both 2.028). The two similarity functions are not identical — they define different attention distributions. The question is whether the kernel version, despite being different, can still produce useful representations. Katharopoulos et al. (2020) show empirically that it can, with competitive performance on language modeling and speech recognition tasks.
5.7 The generalized attention formula
With the kernel similarity, the attention output for query i becomes:
oi=∑j=1nϕ(qi)⊤ϕ(kj)∑j=1nϕ(qi)⊤ϕ(kj)vj
This looks identical to the softmax version, just with a different similarity function. The cost appears to be the same: n2 dot products in the feature space. But there is a crucial algebraic difference that we have not yet exploited.
6. The Associativity Trick
6.1 The rearrangement
This is the core mathematical insight of the entire blog. It is a single algebraic step, but it changes the complexity from quadratic to linear.
Consider the numerator for query i:
numi=j=1∑nϕ(qi)⊤ϕ(kj)vj
The term ϕ(qi)⊤ϕ(kj) is a scalar (a dot product of two dϕ-dimensional vectors). We can write it as:
ϕ(qi)⊤ϕ(kj)=m=1∑dϕϕ(qi)mϕ(kj)m
Substituting into the numerator:
numi=j=1∑nm=1∑dϕϕ(qi)mϕ(kj)mvj
Now we swap the order of summation. The sum over j and the sum over m are both finite, so we can exchange them by Fubini’s theorem (interchanging finite sums):
numi=m=1∑dϕϕ(qi)m(j=1∑nϕ(kj)mvj)
The inner sum ∑j=1nϕ(kj)mvj does not depend on i at all — it is a fixed vector that combines all keys and values, independent of which query we are computing.
6.2 The matrix form
To see this more cleanly, let us write the numerator in matrix notation. The value vj is a row vector in Rdv, so ϕ(kj)vj⊤ is an outer product: a dϕ×dv matrix. Define:
S=j=1∑nϕ(kj)vj⊤∈Rdϕ×dv
Then the numerator becomes:
numi=ϕ(qi)⊤S∈R1×dv
This is a single matrix-vector product: the dϕ-dimensional vector ϕ(qi) multiplied by the dϕ×dv matrix S.
Similarly, the denominator:
deni=j=1∑nϕ(qi)⊤ϕ(kj)=ϕ(qi)⊤(j=1∑nϕ(kj))
Define:
z=j=1∑nϕ(kj)∈Rdϕ
Then:
deni=ϕ(qi)⊤z
And the full attention output is:
oi=ϕ(qi)⊤zϕ(qi)⊤S
6.3 Why this changes the complexity
This is the moment the complexity drops.
The standard way (softmax attention): Compute the n×n matrix A where Aij=sim(qi,kj), then multiply A×V. The bottleneck is the n×n matrix: O(n2dk) to compute QK⊤, then O(n2dv) to multiply by V. Total: O(n2dk).
The new way (linear attention): First compute S=∑jϕ(kj)vj⊤ and z=∑jϕ(kj). Then for each query i, compute ϕ(qi)⊤S and ϕ(qi)⊤z.
The costs:
Computing S: sum n outer products, each dϕ×dv. Cost: O(ndϕdv).
Computing z: sum n vectors of dimension dϕ. Cost: O(ndϕ).
Computing all n outputs: for each query, one matrix-vector product ϕ(qi)⊤S of cost O(dϕdv), and one dot product ϕ(qi)⊤z of cost O(dϕ). Total: O(ndϕdv).
Grand total:
O(ndϕdv)
With dϕ=dk (as in the elu+1 feature map), this is O(ndkdv)=O(ndk2). Compare to the standard O(n2dk).
When is the new way cheaper? When ndk2<n2dk, which simplifies to dk<n. Since dk=64 and n can be 128,000, this condition is overwhelmingly satisfied for long sequences.
6.4 What happened algebraically
The trick is a change of association in matrix multiplication. The standard attention computes:
Standard: (ϕ(Q)ϕ(K)⊤)V
The parentheses indicate that we first multiply ϕ(Q)×ϕ(K)⊤ to get the n×n attention matrix, then multiply by V.
The linear attention computes:
Linear: ϕ(Q)(ϕ(K)⊤V)
We first multiply ϕ(K)⊤×V, which is a dϕ×n times n×dv product, giving a dϕ×dv matrix — this is our S. Then we multiply each row of ϕ(Q) by S.
Matrix multiplication is associative: (AB)C=A(BC) for any compatible matrices A, B, C. This is a fundamental property of matrix multiplication. The two computations produce exactly the same result. But the intermediate matrix has different size:
Standard: intermediate is n×n (the attention matrix)
Linear: intermediate is dϕ×dv (the state matrix S)
Since dϕ,dv≪n for long sequences, the linear version avoids ever materializing the n×n matrix.
6.5 Numerical verification
Let us verify both computations produce the same result for our running example (unmasked attention, n=4, dk=dv=2).
The standard way computed a 4×4 intermediate matrix. The linear way computed a 2×2 intermediate matrix S. Both produced the same output. But the 2×2 matrix is fixed-size — it does not grow with n.
7. The Recurrent Form
7.1 Causal masking
Everything in Section 6 assumed unmasked (bidirectional) attention — each query attends to all keys. For autoregressive (causal) language modeling, query i can only attend to keys j≤i. The attention output becomes:
oi=∑j=1iϕ(qi)⊤ϕ(kj)∑j=1iϕ(qi)⊤ϕ(kj)vj
Applying the same associativity trick, define the causal versions of the state matrix and normalizer:
Si=j=1∑iϕ(kj)vj⊤,zi=j=1∑iϕ(kj)
Then:
oi=ϕ(qi)⊤ziϕ(qi)⊤Si
7.2 The recurrence
This is where the connection to RNNs becomes explicit. The causal sums Si and zi satisfy:
Si=Si−1+ϕ(ki)vi⊤zi=zi−1+ϕ(ki)
with initial conditions S0=0 (the zero matrix) and z0=0 (the zero vector).
At each step i, we:
Compute ϕ(ki) and vi from the current token’s hidden state
Update Si by adding the outer product ϕ(ki)vi⊤ (a rank-1 update)
Update zi by adding ϕ(ki)
Compute the output oi=ϕ(qi)⊤Si/ϕ(qi)⊤zi
This is a recurrent neural network. The hidden state is the pair (Si,zi). The update rule is additive — each new token contributes an outer product to S and a vector to z. The output is a function of the current query and the accumulated state.
7.3 Tracing the recurrence
Let us trace the recurrence for our running example with causal masking.
Numerical check: query 2 attends to keys 1 and 2 with similarities ϕ(q2)⊤ϕ(k1)=(1)(1)+(2)(2)=5 and ϕ(q2)⊤ϕ(k2)=(1)(2)+(2)(1)=4. Total: 5+4=9. Weights: 5/9≈0.556 and 4/9≈0.444.
Notice: S4 is exactly the same S matrix we computed in Section 6.5 for unmasked attention! This must be the case — when the causal sum reaches the last token, it includes all tokens, so Sn=S.
7.4 Memory and compute per step
At each step of the recurrence:
State size:Si is dϕ×dv and zi is dϕ. Total: dϕdv+dϕ=dϕ(dv+1).
With dϕ=dk=64 and dv=64: 64×65=4,160 elements per head. Across h=8 heads and L=12 layers, in fp16:
8×12×4,160×2=798,720 bytes≈0.8 MB
Compare to the KV cache for n=128,000 tokens: 4×512×12×128,000≈3.15 GB. The recurrent state is 3,940× smaller.
Compute per step: Computing ϕ(ki)vi⊤ is a dϕ×dv outer product: dϕdv multiplications. Computing ϕ(qi)⊤Si is a 1×dϕ times dϕ×dv product: dϕdv multiplications. Total per head: O(dϕdv)=O(dk2).
This is constant — it does not depend on i or on how many tokens have been generated. Every token costs the same, regardless of position.
7.5 The complete cost comparison
Property
Softmax attention
Linear attention (recurrent)
State size per head
2×t×dk (KV cache, grows with t)
dk×dv+dk (constant)
Compute per token (generation)
O(tdk) (grows with t)
O(dk2) (constant)
Total cost for n tokens (generation)
O(n2dk)
O(ndk2)
Training (full sequence)
O(n2dk)
O(ndk2) with scan; O(n2dk) naive
7.6 Numerical cost comparison
For generation of n=128,000 tokens, per head (dk=64):
Linear attention:n×dk2=128,000×642=5.24×108 multiply-adds.
Ratio: 5.24×1011/5.24×108=1,000×. The linear version is three orders of magnitude cheaper.
This matches the claim of Katharopoulos et al. (2020): “The model has been shown to improve inference speeds up to three orders of magnitude without much loss in predictive performance.”
7.7 The training parallelism issue
This is the part that confuses almost everyone when they first encounter linear attention.
During inference (generation), the recurrent form is strictly better: constant memory, constant compute per token. But during training, there is a catch.
Training processes the full sequence at once (teacher forcing). The softmax attention computes all n outputs in parallel using matrix multiplication — QK⊤ and then AV. These are large, dense matrix multiplications that GPUs execute extremely efficiently.
The recurrent form computes outputs sequentially: S1→o1, then S2→o2, then S3→o3, and so on. Each step depends on the previous state Si−1. This is a sequential dependency — you cannot compute o3 until S2 is done. On a GPU with thousands of parallel cores, this sequential dependency means most cores sit idle.
The asymptotic complexity is better (O(ndk2) vs O(n2dk)), but the wall-clock time can be worse because of low GPU utilization. This is a crucial practical distinction noted by the Efficient Transformers survey (Tay et al., 2022): “running unidirectional (causal) implementation of kernel-based attention on an autoregressive task can be several times slower than vanilla Transformer during parallelized training due to the need to do a left to right pass (i.e., scan operation) in similar spirit to Recurrent neural networks.”
The resolution is the parallel scan algorithm (Blelloch, 1990), which computes prefix sums in O(logn) parallel steps instead of n sequential steps. Modern implementations (like those in Mamba and RWKV) use optimized scan operations to achieve competitive training throughput.
8. What We Gain and What We Lose
8.1 What we gain
Constant memory during generation. The recurrent state (S,z) has size O(dk2) per head per layer, independent of sequence length. For our running model: 0.8 MB total vs 3.15 GB for the KV cache at 128K tokens. This eliminates the KV cache wall entirely.
Constant compute per token during generation. Each new token requires O(dk2) operations per head, regardless of how many tokens preceded it. The 128,000th token is no more expensive than the 1st.
Linear total cost. Generating n tokens costs O(ndk2), linear in n. This enables generation at sequence lengths that are impractical with softmax attention.
8.2 What we lose
Exact softmax attention. The elu+1 kernel is not equivalent to the softmax kernel. The attention distributions are different (as we saw in Section 5.6), and this can affect model quality. Empirically, Katharopoulos et al. (2020) report competitive but not identical performance to softmax transformers on language modeling and speech recognition.
Information capacity of the state. The recurrent state S∈Rdk×dv must compress all information from all past tokens into a fixed-size matrix. With dk=dv=64, this is 64×64=4,096 numbers. Compare to the KV cache, which stores 2×dk=128 numbers per past token — 128,000 tokens would require 128×128,000=16,384,000 numbers per head. The recurrent state compresses this by a factor of 4,000×.
This compression is necessarily lossy. If token 50,000 contained critical information that token 128,000 needs, the softmax attention can retrieve it directly from the KV cache. The recurrent state can only access what survived 78,000 rank-1 updates to the state matrix S.
Training parallelism (naive implementation). As discussed in Section 7.7, the sequential nature of the recurrence reduces GPU utilization during training. Modern implementations mitigate this with parallel scan, but the engineering complexity is higher.
8.3 The landscape after linear attention
The kernel-based linear attention of Katharopoulos et al. (2020) was one of the first rigorous demonstrations that the attention mechanism could be fundamentally replaced. It showed that the mathematical structure of attention — the softmax, the pairwise comparisons, the n×n matrix — is not sacred. What matters is the function computed: a weighted combination of values based on query-key relevance. The softmax is one way to define relevance. The kernel feature map is another. And once you have the feature map, the associativity of matrix multiplication gives you linear cost for free.
This insight opened the door to a family of architectures that blur the line between transformers and RNNs: RetNet (Sun et al., 2023), RWKV (Peng et al., 2023), Mamba (Gu and Dao, 2023), and others. Each proposes a different way to define the recurrent state and the update rule, with the shared goal of constant-time, constant-memory token generation without sacrificing the quality that made transformers dominant.
The Efficient Transformers survey (Tay et al., 2022) presciently noted: “It is then a question of whether that new xformer will still be a Transformer.” The kernel view of attention suggests the answer: the boundary between transformers and RNNs was always algebraic, not architectural.
Summary
After twelve blogs of modifying attention — reducing KV heads, compressing representations, sparsifying patterns, gating residuals and activations — the softmax normalization remained untouched, and with it the quadratic cost of computing pairwise query-key similarities. This blog derived the exact costs that persist (the O(n2dmodel) attention FLOPs that dominate beyond n=dff tokens, the linearly growing KV cache that reaches hundreds of gigabytes at long contexts, the per-token generation cost that makes the last token n times more expensive than the first), identified the softmax as the root cause (its infinite-dimensional feature map prevents factoring the similarity into independent query and key functions), replaced it with a finite-dimensional kernel (ϕ(x)=elu(x)+1), applied the associativity of matrix multiplication to change the computation order from (ϕ(Q)ϕ(K)⊤)V to ϕ(Q)(ϕ(K)⊤V), and showed that the result is an RNN with state (Si,zi) that achieves constant memory (dk×dv per head), constant compute per token (O(dk2)), and linear total generation cost (O(ndk2)) — three orders of magnitude faster than softmax attention at 128K tokens, at the price of compressing all past information into a fixed-size state matrix.