Home Knowledge Base Linear Attention and Subquadratic Alternatives

Linear Attention and Subquadratic Alternatives are the efficient attention mechanisms that reduce the O(N²) computational and memory cost of standard Transformer self-attention to O(N) or O(N log N) — enabling processing of extremely long sequences (100K+ tokens) that would be prohibitively expensive with quadratic attention, with architectures like RWKV, RetNet, and Mamba offering Transformer-competitive quality at a fraction of the inference cost for long contexts.

The Quadratic Attention Problem

Subquadratic Architectures

ArchitectureComplexityMechanismQuality vs. Transformer
Standard attentionO(N²)Full pairwiseBaseline
Linear attentionO(N)φ(Q)φ(K)^T trick90-95%
RWKVO(N)RNN-like recurrence + attention95-98%
RetNetO(N)Retentive network, decaying attention95-98%
Mamba/S4O(N)Selective state space model97-100%
Mamba-2O(N)Structured SSM = linear attention98-100%

Linear Attention

Standard:  Attn = softmax(QK^T) V       → O(N²d)

Linear:    Attn = φ(Q)(φ(K)^T V)         → O(Nd²)

Key insight: Compute (K^T V) first → this is d×d matrix (not N×N)
Then multiply Q × (K^T V) → O(Nd²)
When d << N, this is O(N) in sequence length

RWKV (Receptance Weighted Key Value)

RetNet (Retentive Network)

Retention = (Q × K^T ⊙ D) × V
where D[i,j] = γ^(i-j) for i ≥ j, else 0

- γ < 1 → exponential decay → recent tokens matter more
- Training: Parallel (matrix form) → efficient on GPU
- Inference: Recurrent (O(1) per token)
- Chunk mode: Hybrid for moderate-length processing

Inference Cost Comparison (2048 tokens)

ModelPrefillPer-token decodeMemory
Transformer (7B)100 ms15 ms14 GB + KV cache
RWKV-7 (7B)80 ms8 ms14 GB (no KV cache)
Mamba-2 (7B)60 ms6 ms14 GB (no KV cache)

Trade-offs

Linear attention and subquadratic alternatives are the architectures that will enable truly long-context AI — while Transformers with FlashAttention handle sequences up to 128K tokens practically, processing million-token documents, full codebases, or hours of audio will require O(N) architectures, making RWKV, Mamba, and their successors essential for the next generation of context-hungry AI applications.

linear attentionrwkvretnetsubquadratic attentionefficient attention alternative

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.