The Evolution of Attention Mechanisms for Long-Context Inference
This article traces how attention mechanisms evolved to make long-context inference practical, starting from the KV cache bottleneck that limits memory usage. It walks through the main optimization stages—sharing keys and values across heads with MQA and GQA, aggressive structural compression with low-rank projection and decoupled position encoding, and sparse or hybrid designs that cut compute—then offers selection guidance by context length and four evaluation metrics to track. Readers will learn why the KV cache dominates memory, how each technique trades quality for cost, and how to choose an approach for their scenario.
1. The Starting Point: Why Long Context Hits the Memory Wall First
If you break down a single autoregressive inference pass, only one component actually grows over time—the key-value cache (KV cache). For every new token generated, the model computes that token’s query vector (used once and discarded), computes and stores its key and value vectors, and then lets the current query attend to all historical keys and values. So the cache gains a row at every step, memory usage scales linearly with context length, and memory bandwidth gets saturated.
To get a feel for the scale (assuming a 67B-class baseline with 8 key-value head groups and half-precision storage):
Context length KV cache size4K ~20 GB32K ~160 GB128K ~640 GB ← no longer fits on a single 80GB card1M ~5 TB ← not feasible on a single machine
The conclusion is straightforward: without solving the cache problem, million-token context is just a feature on a demo slide. Every attention improvement since then is essentially a two-front effort: shrink the key-value cache and cut the attention compute.
2. Step One: Let Multiple Heads Share the Same Keys and Values
Original multi-head attention (MHA) maintains separate keys and values for each head, and the cache size can be written as:
cache = 2 · n · d · H · sizeof(dtype)
Here H is the number of heads, with one cache per head. This is the comparison baseline for all subsequent work.
The extreme compression approach is multi-query attention (MQA): all query heads share the same keys and values, so H disappears from the cache formula, the cache shrinks to 1/H of the original, and memory access drops substantially, noticeably improving decode-phase throughput. The cost is reduced representational capacity and worse training stability, especially on small models.
The middle-ground approach is grouped-query attention (GQA): split the query heads into several groups, share one set of keys and values within each group, and use the number of groups G to balance “quality” against “overhead”:
cache = 2 · n · d · (H / G) · sizeof(dtype)G = H degenerates to MHA, G = 1 degenerates to MQA
In practice, GQA has become the default starting point for long-context models: almost no loss in quality, while the cache drops by an order of magnitude.
3. Step Two: More Aggressive Structural Compression of the Cache
Sharing heads only solves “redundant storage”; it does not solve “the total is too large.” The next generation of ideas is low-rank compression: jointly project keys and values into a latent space much smaller than d, store only this compressed representation in the cache, and project it back up when needed. Cache complexity drops from being proportional to d to being proportional to the latent dimension, and the payoff at million-token context is on the order of magnitude level.
Paired with this is decoupled position encoding: position information is not mixed into the compressed representation but instead travels through a separate low-dimensional channel, avoiding compression that would destroy the distinguishability of relative positions. This point is often overlooked, but it determines whether long-context extrapolation stays stable.
4. Step Three: Sparsity and Hybrid Designs That Also Cut Compute
Once the cache is smaller, the bottleneck shifts to compute and memory access: attention itself is a computation that grows with the square of the length. The industry commonly uses two kinds of techniques:
- Learnable/native sparse attention: compute only the selected key-value blocks, reducing complexity to near-linear;
- Hybrid hierarchical structure: a local window handles nearby details, while a compressed global representation handles distant information, and the two results are fused.
A typical “compression + hybrid” pipeline can be summarized as:
1) Compress historical keys and values with low-rank projection and write them to the compressed cache2) Do exact attention within the local window to preserve fine-grained nearby detail3) Do global attention over the compressed cache to capture long-range dependencies4) Fuse the two outputs by gated weights, then feed into the feed-forward layer
The value of this structure is that memory usage is approximately linear, memory access in the decode phase stays controllable, and long-range tasks (cross-document retrieval, long-document summarization, repository-level code understanding) do not lose accuracy.
5. Deployment Recommendations and Evaluation Criteria
For selection, there is no need to jump straight to the most aggressive approach; you can progress by scenario:
- Small-to-medium context, cost-sensitive: grouped-query attention is enough;
- 32K–128K, high concurrency: low-rank compressed cache gives the most obvious benefit;
- Million-scale, mainly long-range tasks: compressed cache plus local–global hybrid, combined with paged cache management and prefix reuse.
For evaluation, it is recommended to fix four criteria to avoid looking at a single-point metric: long-context recall (such as multi-needle retrieval), first-token latency, decode throughput (tokens/s), and peak memory per million tokens. If you use general capabilities such as cloud container platforms, object storage, and monitoring/alerting to run stress tests and observe production, be sure to bring cache hit rate and bandwidth utilization onto the dashboard, otherwise the optimization direction can easily drift.
In one sentence: the decade-long evolution of attention mechanisms is about gradually turning “save and revisit the entire history for every token” into “save only the necessary information and look at only the necessary parts.”
