The Evolution of LLM Attention Mechanisms and the Practice of Million-Token Contexts

    This article explains why scaling the context window to one million tokens is a memory and bandwidth problem rather than a configuration change, walks through the trade-offs among MHA, MQA, GQA, and MLA, and shows how attention design couples with KV cache layout, operator kernels, parallelism, paging, and scheduling. It also covers practical engineering levers for long-context inference and a six-point checklist for choosing an attention design.

    1. Where the Problem Starts: Million-Token Context Is Not a “Window Parameter”

    Stretching the context window from a few thousand tokens to the million scale looks like changing a single configuration item. In practice, it shifts the pressure on the inference system from the compute side to the memory capacity and memory bandwidth side. Understanding this is the prerequisite for understanding why attention mechanisms have been iterated on repeatedly over the past two years.

    During autoregressive decoding, every newly generated token must interact with the keys (Key) and values (Value) of all historical tokens. The historical K/V must stay resident in GPU memory, forming the KV cache. Its size is proportional to the number of layers, the number of attention heads, the per-head dimension, the sequence length, and the number of concurrent requests. When the sequence length grows by two orders of magnitude, the KV cache goes from “negligible” to the main bottleneck, becoming larger than the model weights themselves.

    A common approximation is as follows (illustrative, in bytes):

    1. KV_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes

    The 2 accounts for the two tensors, K and V. With 60 layers, head_dim 128, and FP16, if the number of KV heads is 96, the sequence length is 1 million, and there is a single request, the KV cache alone reaches roughly 23 GB; if the number of KV heads is compressed to 8, it drops to around 2 GB. The same formula explains why “reducing the number of KV heads” and “compressing the per-head dimension” have become the two most direct levers in long-context design.

    2. The Trade-Off Logic of Three Attention Forms

    1. Original Multi-Head Attention (MHA)

    Each attention head maintains its own K/V, giving the strongest expressive power but the largest KV cache. This is not a problem in short-context, compute-rich scenarios; once you move into long context and high concurrency, memory and bandwidth quickly become the bottleneck.

    2. Multi-Query Attention (MQA)

    All query heads share the same K/V, shrinking the KV cache to 1/number-of-heads of the original and significantly reducing memory access pressure, with a clear improvement in decoding throughput. The cost is reduced expressive power and harder training stability and convergence, which usually calls for more careful initialization and learning rate strategies.

    3. Grouped-Query Attention (GQA)

    A compromise between MHA and MQA: query heads are split into several groups, and K/V is shared within each group. It is currently the most common engineering default, because it turns the “memory versus quality” curve into an adjustable knob.

    4. Multi-Head Latent Attention (MLA)

    The idea differs from the three above: instead of directly compressing the number of heads, it projects K/V into a low-dimensional latent space, caches the latent vectors rather than the full K/V, and up-projects them back when needed. It substantially reduces cache usage while retaining strong expressive power, but it places higher demands on operator implementation, quantization schemes, and parallel partitioning strategies in the inference framework, with clearly tighter engineering coupling than the previous options.

    It is worth noting that the industry once assumed architectures had converged on a single option, with only local fine-tuning to follow. Yet some recent large-scale models have returned to a minimal shared-K/V route, showing that architectures are far from converged: when model scale, training data mixture, and the inference system all change at once, the attention form that was once “optimal” may no longer be optimal.

    3. The Key Insight: System-Level Coupled Optimization Is Harder Than a Single-Point Innovation

    A single-point innovation can be measured clearly in a paper, for example how much the cache shrinks or how much throughput improves. But getting an attention redesign into production at hyperscale requires simultaneous changes to the training parallelism strategy, operator kernels, quantization schemes, cache paging management, prefix reuse, and scheduling. If any one link does not match, the gains are cancelled out, and you can even end up with “better metrics, slower in production.”

    A typical coupling chain looks like this:

    1. attention form → KV layout → operator kernel → parallel partitioning → cache paging → scheduling and reuse

    For example, latent vector caching requires the operator to complete “fetch latent vector — up-project — score” within the same kernel, otherwise extra memory round trips are introduced; meanwhile, a shared-K/V layout changes how tensor parallelism is partitioned, which in turn affects communication volume. Such changes cannot be delivered by a single team; they require model, training framework, inference framework, and operations sides to move together.

    4. Engineering Levers for Long-Context Inference

    • Paged KV management: split the cache into fixed-size blocks, allocate on demand, reduce fragmentation, and make cross-request sharing easier.
    • Prefix cache reuse: stable prefixes such as system prompts, long documents, and tool definitions can be hit across requests, significantly reducing repeated computation and time to first token.
    • Quantization and compression: apply low-bit quantization to K/V, or use sparse/windowed attention so that only key segments participate in computation.
    • Continuous batching and priority scheduling: make dynamic trade-offs between throughput and latency, and avoid long requests blocking short ones.
    • Observability: build monitoring and alerting for cache hit rate, memory watermarks, and memory access per token, so that capacity planning has a basis.

    When deploying on the cloud, these are typically combined: a container platform hosts the inference service, object storage holds long documents and model artifacts, a message queue smooths out request peaks, and logging plus monitoring and alerting provide end-to-end tracing. Baidu AI Cloud offers standard support for these general-purpose capabilities, but the specific selection should still be based on your own workload characteristics.

    5. Selection Checklist

    1. What are the target context length and concurrency? Compute the KV cache upper bound first.
    2. Is the decoding stage bandwidth-bound or compute-bound? This determines whether to prioritize compressing the cache or optimizing operators.
    3. Can you tolerate a loss of expressive power? If not, prefer latent-space compression over reducing the number of heads.
    4. Does the inference framework natively support the chosen form? The rework for unsupported forms is often underestimated.
    5. Do you have prefix reuse and paging management in place? This often affects actual cost more than the model itself does.
    6. Establish a baseline benchmark: look at time to first token, output tokens per second per user, and cost per request at the same time.

    6. Conclusion

    Million-token context has become real not because of any single attention trick, but as the result of years of accumulated coordination among model architecture, training methods, operator implementation, and the service system. For developers, the judgment worth building is this: look at the hard constraints of memory and bandwidth first, then discuss architectural choices; quantify the coupling cost first, then evaluate single-point gains.