Attention Mechanism Variants in LLMs: A Complete Overview of MHA, GQA, MQA, and Sliding Window Attention

    This article maps the landscape of attention mechanism variants used in modern large language models, starting from self-attention and multi-head attention (MHA) and extending to grouped-query attention (GQA), multi-query attention (MQA), and sliding window attention. For each variant, it explains the bottleneck being addressed, the new cost introduced, and the scenarios where adoption makes sense. Readers will also find a four-dimension framework for comparing variants across quality, memory, throughput and latency, and implementation complexity, plus practical guidance on running small-scale ablation studies before capacity planning.

    1. Introduction: Why Attention Keeps Getting Reinvented

    Attention has remained one of the most active areas of innovation in the architecture of contemporary large language models. One pattern stands out: over the past few years, academia and industry have proposed a large number of attention variants, yet only a handful of them, typically the ones that balance engineering practicality and model quality best, have been widely adopted in open-weight models. Understanding the design motivation behind these variants is more valuable than memorizing their formulas.

    This article starts from multi-head attention and expands outward to several mainstream variants in use today, focusing on three questions: what bottleneck does it solve, what new cost does it introduce, and in what scenarios is it worth adopting?

    2. The Starting Point: Self-Attention and Multi-Head Attention (MHA)

    The core idea of self-attention is to let every token in a sequence directly “see” the other visible tokens, computing relevance weights to build a new representation that carries contextual information. Multi-head attention (MHA) is the standard implementation of this idea in the Transformer: it runs multiple self-attention heads in parallel, each with its own projection matrices, then concatenates and fuses the head outputs, so that different dependency patterns can be modeled simultaneously across multiple representation subspaces.

    2.1 Historical Context: Attention Predates the Transformer

    The prototype of attention predates the Transformer. Its direct background was the encoder-decoder recurrent neural network used for machine translation. The encoder reads the source tokens one by one, compressing information into a sequence of hidden states (in the simplest version, keeping only a single final state); the decoder then generates the target sentence based on this “summary.”

    The problem is that a hidden state of fixed dimension cannot carry unlimited information. When the key clue needed to generate a particular output word sits at the far end of the input sequence, the information bottleneck shows up directly as a drop in translation quality. Allowing the decoding stage to “look back” and directly access the full input sequence was the fundamental motivation for introducing attention.

    2.2 Where the Compute Cost of MHA Comes From

    Standard self-attention computes relevance between every pair of tokens, so its time and memory footprint grow quadratically with sequence length. In addition, each attention head must store its own set of key (K) and value (V) projections, and during inference the K/V of historical tokens must be cached, producing memory usage that grows linearly with context length. These two factors are the optimization targets for nearly every variant that followed.

    3. The Inference Memory Bottleneck: Grouped-Query Attention and Multi-Query Attention

    During autoregressive inference, KV cache capacity often becomes a bottleneck before compute does. To ease this, the industry developed the idea of letting multiple query heads share the same set of key-value heads:

    • Multi-query attention (MQA): all query heads share one set of K/V, shrinking the KV cache to a fraction of its original size, at the cost of reduced representational capacity.
    • Grouped-query attention (GQA): a compromise between the two, dividing query heads into several groups that share K/V within each group. It retains most of the quality while significantly reducing cache overhead, which makes it one of the most common choices in current open-weight models.

    The grouping logic can be understood schematically as follows:

    1. # Pseudocode: key-value head reuse in GQA
    2. num_q_heads = 32 # number of query heads
    3. num_kv_heads = 8 # number of key-value heads, usually far fewer than query heads
    4. group_size = num_q_heads // num_kv_heads
    5. # Query head i uses key-value group i // group_size
    6. kv_head_index = lambda i: i // group_size

    Selection guidance: if the deployment scenario involves long contexts and many concurrent requests, evaluate GQA first; if memory is extremely constrained and the task does not demand high representational precision, consider MQA.

    4. Sparsifying Long Sequences: Sliding Window Attention

    Another class of variants leaves the head-sharing strategy unchanged and instead limits how far each token can see. Sliding window attention restricts each position to a local window of fixed length, reducing complexity from quadratic to roughly linear. The cost is that global dependencies must be passed indirectly through stacked layers, and long-range information is weakened when there are not enough layers.

    A common engineering practice is a hybrid pattern of “local window plus a few global tokens”: most layers use local windows to control cost, while a few layers keep global attention to aggregate long-range information.

    5. How to Compare These Variants Systematically

    Developers are advised to build an evaluation framework around four dimensions:

    1. Quality: whether it matches the baseline on the target task;
    2. Memory: changes in KV cache and activation footprint;
    3. Throughput and latency: time to first token and decoding speed;
    4. Implementation complexity: whether custom kernels or specific hardware support are required.

    A practical approach is to first run small-scale ablation experiments at the target model size, then do capacity planning in combination with production traffic characteristics such as average input length and concurrency. For large-scale training or inference, elastic scaling and observability can be built on general-purpose cloud capabilities such as container platforms, object storage, and monitoring and alerting.

    6. Conclusion

    The proliferation of attention variants is not a case of “newer is better,” but a continuous balancing act around the triangle of constraints formed by memory, compute, and quality. Grasping the baseline semantics of MHA, then understanding the sharing idea behind GQA and the sparsification idea behind sliding window attention, is enough to cover the design choices of most current open-weight architectures, and gives selection and tuning decisions a solid basis.