Skip to content
ImagineWorld

Beyond Quadratic Attention

node_idnode-book_building-frontier-llm-from-scratch_chapter-37-beyond-quadratic-attention
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num37
chapter_titleBeyond Quadratic Attention
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part X — The Research Frontier

Attention, for all its power, carries a cost that scales with the square of the sequence length: every token attends to every other, so doubling the context quadruples the work and the memory. For a 1,000-token prompt this is invisible; for the million-token contexts of Chapter 38’s frontier models it is the dominant expense. Removing that quadratic wall is among the most active architectural frontiers in the field, and three broad families of approaches compete to do it. This chapter examines each — what it changes, what it gives up, and why the answer increasingly looks like a hybrid rather than a single winner.

Recall from Chapter 7 the heart of attention: scores = QK⊤, a matrix of shape (T, T) for a sequence of length T. Forming and applying that matrix is O(T²d) work and, naively, O(T²) memory. FlashAttention (Chapter 14) removed the memory term by never materializing the full matrix, but the compute remains quadratic. At T = 1M, T² is a trillion — per layer, per head. The KV cache compounds the problem: autoregressive decoding stores every past key and value, so memory grows linearly with context and bandwidth becomes the bottleneck. MLA (Chapter 12) and sparse attention (Chapter 14) attack these costs from within attention; the approaches in this chapter ask whether attention itself can be replaced by something cheaper.

The first family rewrites the attention computation so its cost grows linearly. The trick is associativity. Standard attention computes softmax(QK⊤)V — the softmax forces you to build QK⊤ first. If you replace the softmax with a kernel feature map φ, so that similarity is φ(q)·φ(k), the parentheses can move: instead of (φ(Q)φ(K)⊤)V, compute φ(Q)(φ(K)⊤V). The right-hand grouping never forms a (T, T) matrix; it maintains a running sum of size (d, d), turning the cost from O(T²d) into O(Td²):

# standard: O(T^2) — build the full score matrix
scores = (q @ k.transpose(-2, -1)) / d**0.5 # (T, T)
out = scores.softmax(-1) @ v
# linear: O(T) — never form (T, T); keep a running (d, d) state
qf, kf = feature_map(q), feature_map(k) # phi(.) >= 0
kv = (kf.transpose(-2, -1) @ v) # (d, d) summary of the past
out = (qf @ kv) / (qf @ kf.sum(-2, keepdim=True).transpose(-2, -1))

Python — the associativity trick behind linear attention

The catch is quality. The softmax is not just a normalizer; its sharp, data-dependent weighting is much of what makes attention work, and no fixed kernel reproduces it exactly. Early linear-attention models trailed transformers noticeably. Modern variants — with gating, decay, and better feature maps (the line running through Linear Attention, RetNet, and Gated Linear Attention) — have closed much of the gap, and the running-state view connects them directly to the recurrent models of the next section.

The second family abandons attention entirely. State-space models (SSMs) process a sequence the way a recurrent network does — carrying a fixed-size hidden state forward one step at a time — but are formulated so the recurrence can also be computed in parallel during training. The state hh is updated by a learned linear dynamical system, ht=A⋅ht−1+B⋅xth^t = A \cdot h^{t-1} + B \cdot x^t, and the output read off as yt=C⋅hty^t = C \cdot h^t. Because the state is a fixed size regardless of sequence length, inference is O(T)O(T) in time and O(1)O(1) in memory per step — no KV cache that grows with context.

The Mamba line made SSMs competitive by making the dynamics selective: the A, B, and C matrices become functions of the input, so the model can choose what to remember and what to forget at each step — the property a fixed linear system lacks and that attention gets for free. A Mamba layer matches transformer quality on many tasks at a fraction of the long-sequence cost, and processes arbitrarily long sequences in constant memory per token. The open question is whether a pure SSM can match attention’s precise, content-based recall — the ability to reach back and copy an exact token from far away — which remains attention’s signature strength.

ApproachSequence costPer-token memoryMain weakness
Full attentionO(T²)grows with T (KV cache)cost at long context
Linear attentionO(T)fixed (d×d state)weaker than softmax
State-space (Mamba)O(T)fixed (state)exact recall
Sparse attention (DSA)O(T·k)grows, but cappedindexer overhead

Table 37.1 — Three routes past quadratic attention

The most important practical development is that these need not be exclusive. Exact attention excels at precise recall but is expensive; linear and state-space layers are cheap but blurrier. A hybrid interleaves a few full-attention layers among many cheap ones — say, one attention layer for every six or seven SSM or linear layers — keeping most of attention’s quality at a fraction of its cost. Several flagship models now ship with hybrid stacks, and the sparse-attention route of Chapter 14 (and GLM-5.2’s IndexShare in Chapter 44) is itself a hybrid in spirit: dense where it matters, sparse where it does not. The lesson echoes the whole of Part IV — the frontier is rarely a single clean idea, but a careful budget of expensive and cheap components, each placed where it earns its keep.

Several questions remain genuinely unsettled, and progress on any of them would reshape the field. How much exact attention is truly necessary — could the ratio fall to one layer in twenty, or zero? Do hybrids and SSMs hold up at frontier scale and at million-token contexts, where most published comparisons do not yet reach? Can a successor to the transformer block emerge that is both cheaper and uncompromised, or is some quadratic core irreducible for the recall that reasoning depends on? These are not engineering footnotes; they bear on whether the next generation of models can serve book-length and repository-length contexts affordably. They are also approachable on modest compute, because architecture research rewards insight over scale — which is precisely why a reader who has built attention from scratch is positioned to contribute.

The shape of the question Attention’s quadratic cost is not a bug to be patched but a fundamental trade-off between expressiveness and efficiency. Linear attention keeps the form and cheapens the math; state-space models replace attention with a recurrence; hybrids mix both with a little exact attention for recall. None has yet rendered the transformer obsolete, and the most likely near-term outcome is not replacement but composition — the same pattern by which MLA, MoE, and sparse attention were folded into the architecture you built.

37.6 Worked Example: When Linear Attention Wins

Section titled “37.6 Worked Example: When Linear Attention Wins”

The case for linear attention is asymptotic, and seeing the crossover in numbers keeps it honest. Softmax attention costs on the order of T2⋅dT^2 \cdot d — quadratic in sequence length TT, linear in head dimension dd. Linear attention rewrites the computation to cost T⋅d2T \cdot d^2 — linear in TT, quadratic in dd. The break-even point is therefore where T≈dT \approx d.

With a head dimension of 128, the theoretical crossover sits around a mere 128 tokens — yet in practice softmax attention stays faster well into the thousands, because a decade of kernel engineering (FlashAttention and its successors) has made the quadratic operation extraordinarily efficient on real hardware, while linear-attention kernels carry larger constants. The decisive advantage of the linear and state-space forms is not the asymptotic FLOP count at moderate length; it is twofold and shows up elsewhere: at extreme context (hundreds of thousands of tokens) the quadratic term finally dominates everything, and in the recurrent formulation the model carries a fixed-size state instead of a growing KV cache (Section 27.7), making the memory cost of generation constant in sequence length. That is the property — not raw FLOPs — that draws frontier models toward hybrids.

The win is memory, not just FLOPs Linear and state-space attention matter most because their recurrent form holds a constant-size state rather than a KV cache that grows with every token. At very long context that turns an impossible memory bill into a fixed one — which is why hybrids, not pure linear models, are winning.

State-space models offered the linear cost and constant-memory generation of Section 37.6, but early versions carried a fatal weakness: their state transitions were fixed, content-blind, unable to decide what was worth remembering. Mamba’s contribution was to make the recurrence selective by letting the transition parameters depend on the input, so the model can choose, token by token, what to retain and what to forget:

dt = softplus(x @ W_dt) # input-dependent timestep
A_bar = torch.exp(dt * A) # per-token state decay
state = A_bar * state + dt * (x @ B)
y = state @ C # read out fixed-size state

Python — ssm/mamba.py: an input-dependent recurrence (illustrative)

That single change — an input-dependent timestep and decay — gave state-space models the content-awareness that attention has by construction, closing much of the quality gap while preserving the linear scaling and the fixed-size recurrent state. The catch is that input-dependent transitions break the simple convolutional form that made earlier SSMs fast to train, which Mamba recovers with a hardware-aware parallel scan. The result reframed the architecture conversation: the field’s leading long-context models are now hybrids (Section 37.4) that interleave selective-SSM layers with a few attention layers, taking the linear memory of the former and the precise recall of the latter.

Selectivity closed the gap Making the state transition depend on the input gave SSMs the content-awareness they lacked, at linear cost. That is why state-space layers, once a curiosity, now appear alongside attention in frontier hybrids.

A second route past attention’s quadratic cost (Section 7.5), distinct from the state-space models of Section 37.7, attacks the ‘softmax directly. The quadratic term comes from forming the full QKTQK^T score matrix before the softmax. Linear attention replaces the softmax with a kernel feature map φ\varphi, so that attention becomes φ(Q)(φ(K)TV)\varphi(Q)(\varphi(K)^TV) — and crucially, by the associativity of matrix multiplication, the right-hand product φ(K)TV\varphi(K)^TV can be computed first.

That reordering is the whole trick. The product φ(K)TV\varphi(K)^TV is a fixed-size matrix — its dimensions do not grow with sequence length — so accumulating it and then multiplying by φ(Q)\varphi(Q) costs time linear in the number of tokens rather than quadratic. The fixed-size accumulator even doubles as a recurrent state, giving linear attention the same constant-memory generation that makes SSMS attractive. The historical catch is quality: the softmax’s sharp, content-dependent weighting is hard for a fixed kernel to match, and early linear-attention models traded away too much accuracy for their speed. Closing that gap — recovering softmax-like selectivity at linear cost — is precisely the program that selective state-space models (Section 37.7) and modern linear-attention variants pursue, and it is why the two lines of work have largely converged on the same hybrid designs.

Reorder the product, lose the quadratic Replacing softmax with a kernel lets attention be computed as φ(Q)(φ(K)TV)\varphi(Q)(\varphi(K)^TV), and computing the fixed-size right product first makes the cost linear. The challenge is matching softmax’s sharpness — the same goal selective SSMs chase.

The choice between full attention (high quality, quadratic cost) and its efficient alternatives — state-space models, linear attention (Sections 37.7 and 37.8) — turns out to be a false one. The most promising frontier designs do not choose; they interleave. Most layers use an efficient mechanism, while a few, placed at intervals, use full attention.

The division of labor is the point. Pure linear or state-space models struggle with precise, content-based recall — reaching back to an exact earlier token — which is exactly what softmax attention does best. By keeping a minority of full-attention layers, a hybrid retains that precise recall where it matters, while the majority of efficient layers handle the bulk of the processing at linear cost. Empirically this captures most of the efficiency of the alternatives with most of the quality of attention, which is why interleaved designs have become an increasingly common frontier pattern. The lesson generalizes beyond this specific trade: the framing is rarely “attention or its replacement” but “what is the right mix,” and the same compositional instinct that built long context from several techniques (Section 14.7) applies here — combine mechanisms with complementary strengths rather than seeking a single one that does everything. The future of the attention frontier looks less like a winner and more like a recipe.

Mix mechanisms, do not choose one Hybrid models interleave a few full-attention layers (for precise recall) among many efficient ones (for cheap bulk processing), capturing most of the efficiency with most of the quality. The question is the right mix, not attention versus its replacement.