Long-Context Attention: A Decade of KV Cache Optimization and Practical Tuning
This article traces the evolution of long-context attention over the past decade, centered on one bottleneck: the KV cache. It explains why the cache grows linearly with context length and saturates memory bandwidth during decoding, then walks through the three main optimization paths—MHA to MQA to GQA for capacity, sparse and linear attention for compute, and system-level techniques such as KV quantization, eviction, paged cache management, prefix reuse, and offloading for fragmentation and concurrency. It closes with a practical selection checklist and capacity estimation function for deciding whether and how to adopt long context.
Long-Context Attention: A Decade of Evolution and Optimization in Practice
Introduction: What Really Slows Down Long Context Is the KV Cache
Break autoregressive Transformer inference apart and attention itself is only a few operations, softmax(QKᵀ)V. Under long context, however, it strains three resources at once: memory capacity, memory bandwidth, and compute.
The reason is that the decode loop is fixed for every new token:
- Compute the current token’s Query, use it, and discard it; there is no need to store it.
- Compute the current token’s Key and Value, which must be written to a cache for reuse by later tokens.
- Run attention between the current Query and all historical Keys and Values.
“All historical Keys and Values” is the KV cache. Two properties of that cache determine the cost structure of long context:
- It grows linearly with context length: one row is appended per step, so a 100K context means 100K rows.
- It is read in full at every step: decoding is memory-bound, so bandwidth saturates before compute does.
For a rough sense of capacity, take a baseline model in the 67B range with grouped-query attention (GQA) using 8 groups (orders of magnitude only; actual figures vary with layer count, head dimension, and precision):
| Context length | KV cache size |
|---|---|
| 4K | ~20 GB |
| 32K | ~160 GB |
| 128K | ~640 GB (no longer fits in an 80 GB single GPU) |
| 1M | ~5 TB (not feasible on a single machine) |
The conclusion is direct: without addressing the KV cache, long context is a feature that exists only in slide decks. From multi-head attention (MHA) in 2017 to the compression-based and hybrid attention approaches the industry has explored over the past two years, the ten-year back-and-forth comes down to two intertwined lines of work: shrink the cache, and shrink the attention compute.
Chapter 1: MHA → MQA → GQA — Compressing the Cache in Three Steps
1.1 MHA (2017): The Baseline
Original multi-head attention uses H independent heads, each holding its own K and V:
# Pseudocode: each head keeps its own K/VQ = proj_q(x) # [n, d]K = proj_k(x).view(H, n, d // H)V = proj_v(x).view(H, n, d // H)cache_size = 2 * n * d * H * itemsize # one copy per head, the most expensive
It is the reference baseline for all later work: the most expressive, and the heaviest in cache.
1.2 MQA (2019): Extreme Sharing
Multi-query attention lets all query heads share a single K/V, shrinking the cache by a factor of H. The cost is that heads can no longer model different key spaces, which affects training stability and quality; this usually has to be compensated for with initialization strategies, extra regularization, or distillation.
1.3 GQA (around 2023): The Middle Ground
Grouped-query attention splits the H heads into G groups that share K/V within each group, reducing the cache to G/H of the original. G=1 degenerates to MQA and G=H degenerates to MHA, so G is a tunable quality-versus-cost knob—and the common default in today’s open-source models.
What this generation solved: cache capacity. What it left open: cache growth is still linear, so anything beyond 128K remains impractical, and every step still reads the entire cache, so bandwidth pressure is unresolved.
Chapter 2: Sparse and Linear Attention — Bringing Compute Down
The second technical path leaves the cache structure alone and instead reduces how many Keys each Query has to look at.
- Window attention: attend only to the most recent W tokens. Complexity is linear, but distant information can only travel layer by layer, so long-range dependencies decay quickly.
- Dilated/strided attention: skip sampling covers a wider span but leaves blind spots.
- Global token attention: keep a small number of “hub” tokens accessible to the whole network; simple and effective in engineering terms.
- Linear attention and state-space-style structures: rewrite attention as a recurrent state update, decoupling cache size from context length at inference time, though exact-retrieval tasks are typically weaker than with standard attention.
- Low-rank/kernel methods: replace softmax with an approximate kernel; theoretically elegant, but numerical stability and ecosystem support are the practical barriers to adoption.
What this solves: compute and per-step memory traffic. What it leaves open: most of these are approximations, so long-document exact retrieval and verbatim-copy tasks tend to lose accuracy; the cache itself does not get smaller.
Chapter 3: Quantization, Eviction, and Paging — Compression at the Systems Layer
Beyond algorithms, the engineering side offers a full set of techniques for moving the cache out and squeezing it down, usually layered on top of algorithmic optimizations:
- KV quantization: compress the cache from 16 bits to 8 bits or lower, with capacity dropping roughly linearly; watch for accuracy loss caused by outliers.
- Cache eviction/budget policies: drop historical entries by attention score or time decay; this is lossy compression.
- Paged cache management: split the cache into fixed-size blocks mapped on demand, sharply reducing fragmentation and reserved waste; a key lever for higher batch density.
- Prefix reuse: shared prefixes such as system prompts and long documents are computed once and shared across requests.
- Offloading and tiered storage: push cold cache down to host memory or even object storage, trading bandwidth for capacity, which needs to be coordinated with scheduling.
- Operator and parallelism optimization: fused attention kernels, tensor parallelism splitting the head dimension, sequence parallelism splitting the length.
An illustrative capacity estimation function for quick decisions during selection:
def kv_bytes(layers, kv_heads, head_dim, ctx, itemsize=2):# 2 = one copy each for K and Vreturn 2 * layers * kv_heads * head_dim * ctx * itemsize# 32 layers, 8 KV heads, head dim 128, FP16print(kv_bytes(32, 8, 128, 128 * 1024) / 1024**3) # ~8 GB
Chapter 4: Hybrid Attention — Making the “Global” Part Sparse
The mainstream industry approach of the past two years can be summarized as a hybrid structure of “a little global, a lot of local”: most layers use low-cost attention (windowed, compressed, low-rank), while a few layers keep dense global attention to preserve long-range exact retrieval. Three design points matter:
- Controllable sparsity: the share of global layers is the direct knob on quality versus cost.
- Choice of compressed blocks: aggregate fixed blocks or importance-weighted summaries into key-values; block granularity affects recall.
- Consistency between training and inference: if the sparse pattern exists during pretraining, no extra adaptation is needed at inference and results are more stable.
It is worth stressing that this class of structure is a general technical direction publicly explored in the industry; implementation details, parameter configurations, and performance figures should follow each approach’s own official documentation, and unverified numbers should not be used for capacity planning.
Chapter 5: A Practical Selection Checklist
For the question of whether to adopt long context, work through these steps in order:
- Do the math first: estimate cache usage at the target context with the formula above, multiply by concurrency, and compare against single-GPU memory.
- Look at memory traffic first: decoding is bandwidth-bound, so evaluate bytes read per step rather than peak compute alone.
- Prefer lossless techniques: paged management, prefix reuse, and KV quantization are usually the highest-value first step.
- Then add lossy techniques: pair eviction and compression with an evaluation set, especially long-document retrieval, multi-hop question answering, and repository-level code understanding.
- Tier and schedule: push cold data down to host memory or object storage, and pair it with elastic scaling on the container platform plus logging and monitoring/alerting for capacity observation.
- Establish a regression baseline: fix a set of long-context evaluation samples and rerun them after every change to sparsity, quantization bit width, or group count, so you avoid “average score up, long tail collapses.”
Conclusion
A decade of attention evolution is not about ever more complex formulas; it is about ever clearer constraints: capacity, bandwidth, and compute cannot all be free at the same time. MHA through GQA addressed capacity, sparse and linear approaches addressed compute, systems techniques addressed fragmentation and concurrency, and hybrid structures search for a trainable, inference-friendly balance between them. Understanding this main thread is more valuable in the long run than memorizing the structural details of any single model.
