How can softmax attention be written as a kernel smoother? Why does replacing exp⁡(q⊤k) by a feature-map kernel ϕ(q)⊤ϕ(k) reduce the cost from O(n2d) to O(nd2)? How can causal linear attention be computed as an RNN, and what is lost?

Sequence models and transformers, Efficient attention
Level L4 Advanced. Length Medium. Nature Mat Mathematical.

What's being asked

Whether you can use the associativity of matrix products to avoid forming the n×n matrix, and understand what this costs in expressiveness.

Key idea

A kernel smoother outputs a weighted average of values, with weights from a similarity function (the kernel). With a feature map ϕ, oi=∑jϕ(qi)⊤ϕ(kj) vj∑jϕ(qi)⊤ϕ(kj)=S⊤ϕ(qi)z⊤ϕ(qi), with S=∑jϕ(kj)vj⊤ and z=∑jϕ(kj). The sums S and z are computed once and shared by all queries.

Steps

  1. Kernel form of softmax attention: oi=∑jκ(qi,kj) vj∑jκ(qi,kj) with κ(q,k)=exp⁡(q⊤k/d). Computing all κ(qi,kj) costs O(n2d).
  2. Replace κ by ϕ(q)⊤ϕ(k), where ϕ:Rd→R≥0r maps to r non-negative features. Pull ϕ(qi) out of the sums: ∑jϕ(qi)⊤ϕ(kj) vj=(∑jvjϕ(kj)⊤)ϕ(qi)=S⊤ϕ(qi).
  3. Cost, with dv the value dimension: S∈Rr×dv takes O(nrdv), and each output O(rdv), so O(nrd) in total. This is linear in n (O(nd2) when r≈d). In matrix form, compute ϕ(Q)(ϕ(K)⊤V) instead of (ϕ(Q)ϕ(K)⊤)V.
  4. Causal case: use prefix sums. Si=Si−1+ϕ(ki)vi⊤, zi=zi−1+ϕ(ki), oi=Si⊤ϕ(qi)zi⊤ϕ(qi). This is an RNN with a matrix-valued state of fixed size r×dv, so generation needs constant memory per step.
  5. Choices of ϕ: elu⁡(x)+1 (Katharopoulos et al., 2020), or positive random features that approximate exp⁡(q⊤k) without bias (Performer).
  6. What is lost: the attention matrix ϕ(Q)ϕ(K)⊤ has rank at most r and cannot be as sharply peaked as softmax, so exact recall from a long context gets worse. A fixed-size state cannot store an unbounded history. This motivates gated variants and state-space models.

Common mistakes

How long your answer should be

Half a page; 5 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: What is the sinusoidal positional encoding, and why is PEpos+k a linear function of PEpos? How do rotary position embeddings (RoPE) make attention scores depend only on relative position?
Next in Sequence models and transformers: A transformer block can be written post-LN, xl+1=LN(xl+Fl(xl)), or pre-LN, xl+1=xl+Fl(LN(xl)). How do gradients flow back through L layers in the two, and why does post-LN usually need learning-rate warm-up?