Attention Mechanisms in Large Language Models: From MHA to Million-Token Contexts

    This article traces the evolution of attention mechanisms in large language models and explains why system-level co-optimization now matters more than isolated structural novelty. It compares MHA, MQA, grouped-query sharing, and low-rank latent compression through a single KV cache formula, then breaks million-token context into concrete engineering problems: memory budgeting, chunked attention with online normalization, position encoding extrapolation, prefix caching, chunked prefill, sparse retrieval, and observability. Readers will find a practical framework for evaluating architecture changes by measuring memory, bandwidth, cache hit rate, and operator efficiency.

    1. Why Attention Is Back in Focus

    The open-source LLM community has recently produced a wave of mutually reinforcing work: restructuring attention, improving optimizer states, and coordinating compilers with operator kernels. These efforts look scattered, but they point to the same conclusion: the marginal return of isolated structural innovation is declining, while the value of system-level co-optimization is rising.

    The reason is straightforward. As model parameters scale from hundreds of billions toward trillions, the dominant cost of inference is no longer floating-point operations but memory capacity and memory bandwidth. Attention is the clearest example: its compute grows quadratically with sequence length, while the KV cache it repeatedly reads and writes grows linearly. When the context window expands from 32K to 1M, the KV cache becomes the one bottleneck that parallelism cannot hide.

    One trend is worth noting. The industry widely assumed that mainstream open-source architectures had converged on a single low-rank compression scheme, with only minor refinements to follow. Yet a new generation of very large models has returned to the older multi-query path, which shows that architectures are far from converged. The rest of this article unpacks that line of evolution.

    2. What Actually Separates the Three Attention Approaches

    2.1 Original Multi-Head Attention (MHA)

    Every attention head maintains its own Key and Value. Expressiveness is strong, but KV cache size scales with the number of heads:

    1. KV_bytes = 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes

    The factor of 2 accounts for K and V. This formula is the baseline metric for every optimization discussed below.

    2.2 Multi-Query Attention (MQA)

    All query heads share a single set of K/V, meaning kv_heads = 1. The gain is that kv_heads collapses to 1 in the formula above, reducing the bandwidth needed to read the cache during decoding by roughly the number of heads. The cost is reduced expressiveness, which typically has to be compensated for through training strategy and structural adjustments.

    2.3 Grouped Query and Low-Rank Latent Compression

    One approach shares K/V across groups, trading between MHA and MQA. The other projects K/V into a low-dimensional latent space before caching, using the low-rank property of the matrix to compress the cache and reconstructing it at compute time. Both do the same thing: reduce the effective dimensionality of the KV cache. The difference is whether compression happens along the head dimension or the feature dimension.

    With that in mind, abandoning one scheme for a simpler one is not a step backward. When model scale, training data mixture, and operator implementations all change at once, a plain sharing structure is often easier to align with parallelism strategies, cache reuse, and quantization. Architecture choices must be evaluated inside the three-way constraint of model, operator, and deployment; judging them apart from the deployment shape is meaningless.

    3. Turning Million-Token Context into Computable Engineering

    3.1 Start With the Memory Budget

    Run the formula with concrete numbers: 60 layers, head_dim of 128, FP16, batch size 1, sequence length 1M.

    • MHA (64 heads): about 1.97 GB
    • Grouped sharing (8 groups): about 0.25 GB
    • Single-group sharing: about 31 MB

    Same model, same length, and the cache footprint differs by nearly two orders of magnitude. This is why long-context capability is first a memory and bandwidth problem, and only second an algorithmic one.

    2.2 Chunking Attention and Online Normalization

    Quadratic complexity cannot be removed, but it can be partitioned. Split the sequence into chunks, compute them one by one, and maintain a running maximum and running sum across chunks. This yields an equivalent result without materializing the full attention matrix. Three engineering concerns matter: matching chunk size to operator efficiency, recomputation strategy during backpropagation, and numerical stability.

    3.3 Extrapolating Position Encodings

    Length extrapolation cannot rely on interpolation alone. Common practices include scaling the frequency dimension, assigning different extrapolation strengths per layer, and progressive training that goes short before long. The key point: long-context capability must exist during training. Long windows obtained only through inference-time tricks usually come with significant loss of information in the middle.

    4. Four Deployment Practices That Make Long Context Usable

    • Prefix caching and hit-based pricing: repeated prefixes dominate long-context workloads, and cache hits can change cost by an order of magnitude. Treat cache hit rate as a first-class metric to monitor when choosing a setup.
    • Chunked prefill: split prefill of a long prompt into chunks so a single oversized computation does not block scheduling, and decoding requests queue fairly.
    • Sparse and hierarchical retrieval: not all history needs full attention. Summarizing per chunk and fetching on demand can cut overhead substantially at acceptable accuracy loss.
    • Observability: build monitoring and alerts for time to first token, cached bytes per request, and peak memory, closing the loop with logging and alerting capabilities instead of tuning parameters by intuition.

    5. Methodology: How to Evaluate an Architecture Change

    1. Establish baseline metrics: peak memory, decoding bandwidth, long-document task accuracy, cache hit rate.
    2. Run ablations: change one variable at a time to separate structural gains from implementation gains.
    3. Re-check from the operator perspective: if the theoretical compression ratio cannot be realized by actual operators, the benefit shrinks sharply.
    4. Validate end to end: run full-pipeline load tests on general infrastructure such as container platforms and object storage, and confirm the bottleneck has not simply moved elsewhere.

    6. Conclusion

    The biggest lesson from this round of attention changes is that there is no endpoint for architecture, only an optimal solution under constraints. Rather than chasing the label of some advanced structure, developers are better off quantifying four metrics clearly: memory, bandwidth, cache hit rate, and operator efficiency. When you can account for where every byte of memory goes, million-token context stops being a marketing claim and becomes a deliverable engineering capability.