Long Context Attention: A Decade of Evolution and Practical KV Cache Optimization
This article traces ten years of attention mechanism evolution, from multi-head to multi-query and grouped-query attention, and explains why the KV cache—not compute—is the real bottleneck for long context inference. It covers cache compression, sparse and hybrid attention designs, a practical deployment optimization checklist, and three questions to evaluate any new long-context approach.
Long Context Attention: A Decade of Evolution and Practical KV Cache Optimization
Introduction: The Real Bottleneck Is the Linearly Growing Cache
When you break down a single autoregressive inference step, one component stands out: its size grows linearly with context length and gradually overtakes compute as the primary bottleneck—the KV cache.
Generating each new token requires the model to do three things:
- Compute the current token’s Query (used once and then discarded);
- Compute the current token’s Key and Value, and write them to the cache for reuse by later tokens;
- Apply attention weighting using the current Query against all historical Keys/Values.
“All historical Keys/Values” is the KV cache. Every generated token adds one more row to the cache; at a 100K context, that means a hundred thousand rows of cache. The result is that GPU memory gets maxed out and memory bandwidth gets saturated, while compute growth becomes a secondary concern.
Here is a sense of scale (using a common 67B-class baseline configuration with 8 KV groups and FP16, for illustration only):
Context length KV cache size (illustrative)4K ~20 GB32K ~160 GB128K ~640 GB ← no longer fits on a single 80GB GPU1M ~5 TB ← not feasible on a single machine
The conclusion is straightforward: without solving the KV cache, long context is just a feature on a slide. From the introduction of multi-head attention in 2017 to the “compression + hybrid” attention architectures widely adopted across the industry around 2026, this evolutionary thread is essentially the interplay of two things: how to shrink the KV cache, and how to reduce attention compute.
Chapter 1: Multi-Head → Multi-Query → Grouped-Query: Three Steps to Save Cache
1.1 Multi-Head Attention: The Baseline for Everything
Classic multi-head attention (introduced in 2017, see arXiv:1706.03762) uses H independent heads, each holding its own K and V:
# Pseudocode: each head holds its own K/VQ = x @ Wq # [n, d]for i in range(H):Ki, Vi = x @ Wk[i], x @ Wv[i] # each [n, d/H]out_i = softmax(Q_i @ Ki.T / sqrt(d/H)) @ Vi
The cache size is 2 · n · d · H · sizeof(dtype), one copy per head. This is the baseline against which all subsequent schemes are measured.
1.2 Multi-Query Attention: Compressing K/V to a Single Copy
The “single write head” idea proposed in 2019 (arXiv:1911.02150) shares K/V in an extreme way: all query heads share the same K and V. The cache drops directly to 1/H of the original, and bandwidth pressure during decoding is greatly reduced.
The cost is equally clear: sharing a single copy of K/V weakens representational capacity, and training stability and downstream metrics usually require additional compensation.
1.3 Grouped-Query Attention: The Compromise That Became the Standard
Grouped-query attention splits query heads into G groups, with each group sharing one copy of K/V. G=1 degenerates to multi-query, and G=H degenerates to multi-head. It compresses the cache to 1/G while retaining most of the representational capacity, which is why it became the most commonly adopted compromise for years afterward.
One thing to remember in practice: the KV cache depends only on the number of “KV heads,” not the number of query heads. When estimating capacity, first confirm how many KV groups the model has, then multiply by the number of layers, the dimension, the byte size, and 2 (one copy each for K and V).
Chapter 2: After Cache Compression: Making “Who to Compute With” Cheaper Too
Grouped-query attention solves “how much to store” but not “how much to compute.” When the context reaches the hundreds of thousands, the complexity of attention itself grows quadratically with length, and the memory access volume on long sequences far exceeds the compute volume, leaving the GPU in a “waiting for data” state. So the second wave of ideas turns to sparsity and compression:
- Sliding-window local attention: interact only with the most recent W tokens, reducing complexity from quadratic to linear, at the cost of long-range information needing to be passed indirectly through stacked layers;
- Global + local hybrid: a small number of global tokens handle cross-segment retrieval while the rest go through local windows, balancing long-range dependencies and overhead;
- Sparse/block-based selection: score blocks and then compute only the selected ones, trading controllable approximation for throughput;
- Low-rank or compressed cache: compress historical K/V into a shorter representation (such as block aggregation or low-rank projection), trading a small amount of information loss for memory and bandwidth.
These schemes are not mutually exclusive, and real systems often stack them together.
Chapter 3: Hybrid Architectures: Dividing Mechanisms by Layer
A common trend in publicly available technical reports over the past two years is no longer pursuing a single attention mechanism throughout, but instead a hybrid design with division of labor by layer: some layers use high-compression-ratio attention responsible for “broad and coarse” global perception, some layers retain higher-fidelity attention responsible for local detail, supplemented by sparse selection to control long-sequence overhead.
The value of this design is that it separates the conflicts: global layers solve “information cannot be lost,” local layers solve “details cannot be blurred,” and sparsity and compression solve “it cannot run.” When evaluating such architectures, it is recommended to focus on four dimensions rather than just the nominal context length:
- The decay curve of accuracy on long-context retrieval tasks as length increases;
- First-token latency and decoding-phase throughput (corresponding to the prefill and memory-access bottlenecks, respectively);
- The memory lower bound brought by cache compression, and whether the target length fits on the target hardware;
- Whether there is a regression loss on short-context tasks.
Chapter 4: A Deployment Optimization Checklist
If the goal is to run long context stably in your own service, you can proceed in the following order:
1) Quantify first: measure KV cache usage and bandwidth levels at the target length2) Then select: prioritize grouped-query-class architectures; fewer KV groups save more memory3) Add cache reuse: share the cache for identical prefixes to avoid repeated prefill4) Do batch scheduling: continuous batching improves utilization and prevents long requests from blocking short ones5) Add sparsity and windows: reduce attention overhead within acceptable accuracy loss6) Define quantization strategy: evaluate accuracy impact of cache and weights separately, and validate layer by layer7) Build observability: connect memory, bandwidth, latency, and failure rates to logging services and monitoring alerts
When deploying in the cloud, a common approach is to run model services on a container platform with elastic scaling, host models and datasets on object storage, use message queues to smooth out peaks and fill valleys, and use logging services and monitoring alerts to locate long-tail latency. Baidu AI Cloud’s relevant product categories also offer a similar combination of capabilities, which teams can choose according to their existing tech stack.
Conclusion
A decade of evolution can be condensed into a single causal chain: multi-head brings representational power but an expensive cache → multi-query compresses the cache to the extreme but harms representational power → grouped-query strikes a balance → sparsity, compression, and hybrid architectures further reduce the cost of “compute.” Understanding this chain is more useful than memorizing any single formula: when facing a new long-context scheme, just ask three questions—how much is the cache reduced, how much is the compute reduced, and where is the accuracy loss—and you can quickly judge whether it fits your scenario.
