Skip to content

Two Ways Out of the Quadratic Attention Trap

#long-context #attention #kv-cache #subquadratic-attention #state-space-models #inference-efficiency

Two Ways Out of the Quadratic Attention Trap ​

Where long context actually gets expensive ​

Every token a decoder-only model generates has to read the entire key-value cache built before it. At 128K context that's 128,000 key-value pairs per layer, per step. The arithmetic is the cheap part. The gather is what hurts.

I've watched long-context serving jobs where decode throughput fell off a cliff past 100K tokens while GPU utilization sat low, because the memory system was saturated and the tensor cores were waiting on it. Nothing was wrong with the model or the kernel. The workload had simply moved from a compute-bound regime into a bandwidth-bound one, and nobody had re-tuned the batch size for it.

The cost driver is the read over the cache on every new token, and that read grows linearly with T. Total prefill work grows with T². Push a deployment from 128K to 1M and the per-token read grows 8x while your HBM bandwidth stays exactly where it was.

Two recent preprints attack this from opposite ends. Zyphra Hierarchical Attention keeps the full KV cache and makes the routing subquadratic. The Dynamical Memory Transformer throws out the token history the decoder reads from and replaces it with fixed-size recurrent memory.

Two attacks on one bottleneck ​

The design space here is well mapped and mostly disappointing.

Sliding-window attention is cheap and forgets everything outside the window. Linear attention and state-space models compress the past into a fixed-size state, which gives you constant-cost decode but kills addressability: you can't point at token 340,000 and pull it back verbatim. Sparse attention keeps the cache but needs an indexer to decide which keys matter, and the indexer usually scores every key. That's quadratic again. You get a constant factor and a new failure mode.

ZHA's argument is that the indexer is the thing worth rebuilding. DMT's argument is that the decoder shouldn't be reading token history at all.

Quick take: ZHA is a retrofit you can distill onto an existing checkpoint in days, and DMT is a new architecture whose constant-cost decode is exactly what long-running agents want, once its language modeling gap closes.

ZHA: a tree over the KV cache ​

ZHA builds a tree of recursively compressed key summaries on top of the KV cache. Leaves are blocks of real keys. Internal nodes are summaries of their children, compressed again at each level up. A new query walks down from the root, scoring children at each level and keeping only the top few.

The depth of the tree is grown iteratively during training, so the root stays coarse and the leaves stay precise. The paper reports the method is tolerant of tree geometry, including trees six levels deep.

Six levels sounds like a lot of routing. It isn't. A query makes a few dozen comparisons on the way down, then runs exact attention over a few hundred selected keys instead of 128,000. The traversal is the cheap part by two orders of magnitude.

The scaling argument, in numbers ​

Here's the piece that separates ZHA from earlier sparse attention. Per-token cost is routing plus exact attention. Routing scales with depth times fanout, which is logarithmic in sequence length. Exact attention scales with the number of selected leaves, which you hold fixed. So per-token cost grows sublinearly in T, and total work grows superlinear but subquadratic. That's the whole trick, and it's the reason the crossover point lands where it does.

The paper's performance model puts the point where ZHA clearly beats competing sparse methods beyond 1M tokens. That number matters practically. Below it you're paying routing overhead and kernel complexity for a win that may not materialize, so don't adopt this for a 32K deployment and expect a speedup.

The retrofit path is the part I'd actually budget for. ZHA applies to an existing pretrained model with a short KL distillation stage over a few billion tokens. A few billion tokens is a rounding error next to a pretraining corpus in the trillions, so this is days of compute on a modest cluster rather than a new pretraining run. The catch is in the next section.

DMT: separate the writing from the reading ​

DMT splits sequence encoding from information reading. The encoder is a set of memory units, each a dynamical system with a complex diagonal recurrent matrix, plus an input-dependent leak rate that decides how much old state to keep at each step. The decoder runs attention over the memory units' outputs at the current position. It never touches the token history.

The recurrence is written so it can be computed with an associative scan: O(T) total work at O(log T) parallel depth, with fixed dimensions throughout. During autoregressive inference the recurrent states and the convolution cache stay the same size no matter how long the conversation gets. That's the whole point of a flat line on the chart above.

On results, the picture is mixed and the authors say so. DMT beat both Mamba and a Transformer on several cognitive tasks, landed close to the Transformer on language modeling but behind Mamba, and extrapolated better on selective copy. The specific capability being claimed is holding and manipulating state across long sequences. The language modeling deficit means this is a research direction, not a serving swap.

Side by side ​

PropertyFull attentionSliding windowZHAMambaDMT
Per-token cost as context growsLinear in TFlatGrows with tree depthFlatFlat
Total workO(T²)O(T·w)Superlinear, subquadraticO(T)O(T), O(log T) depth
What the model can point back toAny tokenLast w tokensSparse subset chosen by treeCompressed state onlyFixed set of memory units
Retrofit to an existing checkpointn/aNeeds finetuningKL distillation over a few billion tokensNeeds pretrainingNeeds pretraining
Reported LM qualityBaselineDegrades past windowMatches baseline on retrieval and reasoning evalsClose to TransformerClose to Transformer, behind Mamba

Key numbers from both papers: 6 is the deepest tree ZHA was validated on, so routing stays shallow even at extreme lengths. A few billion distillation tokens is the retrofit bill for ZHA. O(T) work at O(log T) parallel depth is what DMT's scan costs during training. Fixed size is what DMT's recurrent state stays at during decode, independent of history length.

What trips people up in practice ​

Measuring average cost instead of tail cost. Tree routing with top-b selection has data-dependent control flow. On a GPU that means ragged batch shapes and load imbalance across the batch. Benchmark at your real concurrent-request count, not at batch size 1, or you'll ship something that looks fast in a notebook and stalls under load.

Assuming distillation is free. KL distillation over a few billion tokens needs teacher logits at every position on long sequences. That's a data pipeline problem before it's a GPU-hour problem: generating, storing, and streaming teacher outputs for multi-hundred-thousand-token documents is its own engineering project.

Comparing at equal nominal context instead of equal accuracy. A sparse method that hits 90% retrieval accuracy at 1M tokens does not beat full attention at 128K if your task needs 99%. Build your own needle test at your deployment length before you trust a curve from a paper.

Treating a fixed-state model as a drop-in for verbatim recall. DMT and Mamba compress history by design. If your workload needs the exact API signature from 200K tokens ago, compression will lose it. Pair a fixed-state model with retrieval instead of arguing with it.

Tuning tree geometry on short sequences. Depth only pays off past the length where flat attention breaks down. Every ablation you run at 8K will tell you to use a shallower tree than you actually want.

One thing to remember ​

Both papers are solving the read path, and the read path is where your latency budget goes. ZHA keeps the cache and makes the lookup cheap. DMT removes the lookup and keeps a summary. Which one you want depends entirely on whether your application needs to retrieve a specific span of text verbatim, and that question is answerable today, before either method ships in your stack.

What this means for your stack ​

If you already have a trained long-context model and your pain is decode throughput past 500K tokens, prototype ZHA's distillation stage. It's the only one of the two that doesn't require you to throw away your checkpoint, and the few-billion-token budget is small enough to justify as an experiment.

If you're building agent loops with unbounded conversation history and the model mostly needs to track state rather than quote text, watch DMT closely. Constant cost per token is the property that makes a 10-hour agent session economically viable, but the language modeling gap versus Mamba means you shouldn't plan a production migration this quarter.

If your context is under 128K, skip both. The routing overhead and kernel complexity will eat the theoretical win, and a well-tuned full-attention kernel with paged KV cache will serve you better until you actually cross the crossover point.

Sources ​