How Long-Context Attention Evolved and How KV Cache Optimization Works in Practice

    Long-context capability is not just a larger window. This article traces attention from MHA to MQA and GQA, then to compressed sparse and hierarchical hybrid designs, covering KV cache cost, compute and bandwidth trade-offs, and a practical evaluation checklist.

    Long-context capability does not end when you raise the window size. Once inference starts, a practical bottleneck appears: history must be stored, read, and used in computation. That cost grows linearly with context length and eventually saturates GPU memory and bandwidth. Attention still looks like softmax(QK^T)V, but at extreme lengths it becomes a systems problem of cache management, memory bandwidth, compute scheduling, and precision trade-offs. This article follows how each generation of methods addressed the previous generation’s limits, and focuses on combining compressed sparse attention with hierarchical hybrid attention.

    1. Why the KV cache becomes a bottleneck

    Autoregressive decoding does three things for each new token:

    1. Compute the current token’s Q, use it once, then drop it.
    2. Compute the current token’s K and V, and append them to the history cache.
    3. Attend with the current Q over all historical K/V.

    That history is the KV cache. Each generated token adds a row; longer context means a larger cache. During decoding, every new token also reads historical K/V from GPU memory. The cache occupies memory and continuously consumes bandwidth.

    A general size estimate is:

    1. KV cache bytes = 2 × L × n_ctx × H_kv × d_head × b

    Where:

    • 2 is K and V;
    • L is the number of layers;
    • n_ctx is context length;
    • H_kv is the number of KV heads;
    • d_head is the per-head dimension;
    • b is bytes per element (for example, 2 for FP16).

    For a typical setup of 80 layers, 8 KV groups, 128 dimensions per head, and FP16, KV cache is about 320 KiB per token. Cache-only estimates:

    Context length KV cache estimate
    4K about 1.25 GiB
    32K about 10 GiB
    128K about 40 GiB
    1M about 320 GiB

    This excludes weights, activations, scratch buffers, and framework overhead. Beyond 128K, single-machine memory is tight; at million-token context, stacking more GPU memory is not a scalable plan. The first optimization track is compressing the KV cache; the second is reducing attention compute and memory traffic.

    2. MHA → MQA → GQA: three steps of structural compression

    1. MHA: independent per-head cache

    Multi-head attention (MHA) keeps separate K and V for each head. If hidden size is d and head count is H, each head has dimension d/H. Cache size is:

    1. KV cache(MHA) = 2 × L × n_ctx × d × b

    Expressiveness is high, but so is cache cost. Later designs ask whether every query head needs its own K/V.

    2. MQA: one shared K/V for all query heads

    Multi-query attention (MQA) shares one K/V set across all query heads:

    1. KV cache(MQA) = 2 × L × n_ctx × (d/H) × b

    Versus MHA, cache is theoretically H times smaller. Decoding bandwidth is low, but sharing one key-value representation can reduce expressiveness and may need more careful training.

    3. GQA: grouped sharing as a compromise

    Grouped-query attention (GQA) splits query heads into groups that share K/V. With G KV groups:

    1. KV cache(GQA) = 2 × L × n_ctx × G × (d/H) × b

    Cache shrinks by H/G versus MHA, while keeping more capacity than MQA. GQA is a common long-context trade-off. Simplified pseudocode:

    1. def gqa_attend(q_heads, k_cache, v_cache, group_size):
    2. outputs = []
    3. for h, q in enumerate(q_heads):
    4. g = h // group_size
    5. k = k_cache[g]
    6. v = v_cache[g]
    7. score = softmax(q @ k.T())
    8. outputs.append(score @ v)
    9. return concat(outputs)

    MHA keeps capacity at high cache cost; MQA compresses aggressively at possible quality cost; GQA balances the two. GQA only answers whether heads share K/V. Decoding still scans all historical K/V. Head sharing alone is not enough as context keeps growing.

    3. Compressing the cache is not enough: compute and bandwidth

    Long-context attention has two cost axes:

    • Cache capacity: how much memory historical K/V uses;
    • Access cost: how much history is read per generated token, and how much QK^T work prefilling does.

    Prefill attention cost grows roughly with the square of context length. Decode compute grows linearly per step, but repeated cache reads keep bandwidth pressure high. A second family of ideas avoids equal-precision attention over every past token: local windows, block summaries, sparse selection, and mixed patterns across layers or heads.

    Common techniques:

    1. Local window attention: keep exact K/V for recent tokens.
    2. Block compression: pool, low-rank project, or summarize historical K/V by block.
    3. Sparse retrieval: coarse scores pick top-k blocks, then exact attention on those blocks.
    4. Global tokens: keep a few tokens as global anchors.
    5. Hierarchical mixing: different layers or heads use different patterns—shallow layers more local, deeper layers more global.

    These methods are orthogonal to MHA/MQA/GQA. You can reduce KV heads with GQA, shorten cache length with block compression, then reduce blocks read with sparse selection.

    4. Combining compressed sparse and hierarchical hybrid attention

    A notable direction in recent public designs is combining compressed sparse attention with hierarchical hybrid attention. This is a general design pattern, not a product-specific claim.

    Compressed sparse attention does not attend to every historical token. History is split into blocks with compressed representations. Queries score block summaries, select the most relevant blocks, then run exact attention on those blocks, while keeping a recent exact window. Pseudocode:

    1. def compressed_sparse_attention(q, kv_cache, block_size=128, window=512, top_k=8):
    2. recent_k, recent_v = kv_cache[-window:]
    3. history = kv_cache[:-window]
    4. blocks = split_blocks(history, block_size)
    5. summary_k = pool_k(blocks)
    6. coarse_score = q @ summary_k.T()
    7. selected_idx = topk(coarse_score, top_k)
    8. selected_k = gather_k(blocks, selected_idx)
    9. selected_v = gather_v(blocks, selected_idx)
    10. final_k = concat([recent_k, selected_k])
    11. final_v = concat([recent_v, selected_v])
    12. return softmax(q @ final_k.T()) @ final_v

    Hierarchical hybrid attention assigns different jobs to different layers. Shallow layers can focus on local windows; deeper layers can use compressed summaries or sparse retrieval for long-range information. Heads can also specialize: some model local detail, others retrieve global summaries. Local detail and long-range dependence can be kept without a full history cache.

    Potential benefits:

    1. Cache: keep summaries and a few exact blocks instead of all historical K/V.
    2. Compute: scan a window plus top-k blocks instead of the full sequence.
    3. Bandwidth: decode reads only selected blocks and the recent window.
    4. Precision: exact locally, compressed globally, with layered routing.

    Costs are real: compressors, routers, and block selection add training and tuning; top-k can be unstable; kernels are complex; long-tail retrieval and cross-block multi-hop reasoning need dedicated evaluation. This is not a free lunch; more complex systems buy long-context scalability.

    5. Engineering checklist: how to evaluate and ship

    Suggested order:

    First, build a cost model. Capture context-length distribution, P99 length, time to first token, generation throughput, and memory budget. Estimate weights, KV cache, activations, and scratch separately for prefill and decode.

    Second, prefer structural compression. If the model can change, GQA or similar grouped sharing is often a high-ROI first step, then KV quantization and paged cache management.

    Third, add block compression and sparse selection. Do not start with a full hybrid design. Try a subset of layers or heads and watch recall on long-document retrieval, multi-hop QA, summarization, and codebase understanding.

    Fourth, instrument the system. Track KV occupancy, bytes read per step, block-selection distribution, top-k coverage, compressed-block hit rate, latency breakdown, and long-tail failures. For production, use standard containers, monitoring, alerts, and logging.

    Fifth, run quality regression. The typical failure is “short text looks fine, long-text local recall drops.” Eval should cover recall at different positions, cross-block reasoning, noise, and ultra-long summarization.

    6. Conclusion

    From MHA to MQA to GQA, structural work compresses the KV cache. From local windows and block summaries to compressed sparse and hierarchical hybrid attention, the second track cuts compute and memory traffic. Long-context attention evolution answers one question: how to store, read, and compute less historical K/V without dropping critical information. The lineage matters more than any single structure.