Attention Mechanism Variants in LLMs: MHA vs. MQA vs. GQA vs. Sliding Window, and How to Choose
This article walks through how modern attention mechanisms evolved from the sequence-compression bottleneck of RNNs, then builds a unified self-attention formulation that every variant derives from. It explains the trade-offs behind multi-head attention (MHA), multi-query attention (MQA), grouped-query attention (GQA), sliding window attention, and related designs such as cross-attention, query/key normalization, output gating, and state-space or hybrid architectures. The core focus is the balance between representational capacity and KV cache cost, including the cache-size formula, a GQA grouping implementation, and a practical engineering pitfall where materializing repeated keys defeats the memory savings. It closes with a step-by-step selection checklist, three common mistakes to avoid, and deployment guidance covering batching, KV cache quantization, and observability.
1. Why Attention Exists: The Bottleneck of Sequence Compression
When recurrent networks dominated sequence modeling, the encoder had to read an entire sentence step by step and compress it into a hidden state, after which the decoder generated output from that “summary.” This design carries a strong implicit assumption: every piece of necessary information can be squeezed into a state of limited dimension. It works well on short sentences. But as soon as the key evidence for the target output lies far away in the input, the model must rely on an information channel that grows thinner at every step. Long-range dependencies decay, and training becomes progressively harder to parallelize.
That was the original motivation for attention. Instead of letting information flow in one direction through a fixed-capacity state, the current computation position is allowed to directly and differentiably “look back” at all visible positions of the input sequence and aggregate them with relevance-based weights. This downgrades serial dependency to local dependency, opens the door to parallel training, and forms the foundation of today’s Transformer-family architectures.
It is worth stressing that “attention” names a family of mechanisms, not a single algorithm. The differences among modern open-weight models usually lie not in whether they use attention at all, but in three things: how queries and keys/values are organized across multiple heads, how wide a range each position can see, and how the continuously growing KV cache is handled during inference.
2. A Unified Self-Attention Formulation: Every Variant Derives From It
Given an input token sequence, the model first produces queries, keys, and values with three linear projections:
Q = X · W_q # [batch, heads, seq, head_dim]K = X · W_k # [batch, kv_heads, seq, head_dim]V = X · W_v # [batch, kv_heads, seq, head_dim]
The attention output is a scaled dot-product weighted aggregation of the values:
scores = Q · Kᵀ / sqrt(head_dim)scores = scores + mask # causal mask: -inf blocks future positionsattn = softmax(scores)out = attn · V
Dividing by sqrt(head_dim) keeps the variance of the dot products under control, so the softmax does not saturate too early and gradients do not vanish. The causal mask guarantees that position t only aggregates context up to and including t, which is a necessary condition for autoregressive language modeling. Every attention variant that follows essentially changes one of three things: the relationship between heads and kv_heads, the range of visible positions, or how the output is processed after the softmax.
3. Multi-Head Attention (MHA): The Most Expressive Baseline
Multi-head attention runs several independent sets of projections in parallel, each computing attention in its own subspace, then concatenates all head outputs and applies one final linear mix. Its value lies in “division of representational labor”: different heads can spontaneously learn different emphases, such as local syntactic collocations, coreference relations, or position-proximity patterns, making the concatenated representation richer than a single head could produce.
Take a medium-sized dense model as an example. If the hidden dimension is d_model and the number of heads is n_heads, each head has dimension d_model / n_heads. The cost of this design only truly shows up during inference: every decoding step needs all historical keys and values, so they must be cached in GPU memory. Under MHA, the KV cache size is:
kv_bytes = 2 × layers × n_heads × head_dim × seq_len × batch × bytes_per_value
The factor 2 in the formula accounts for the two caches, keys and values. As batch size, sequence length, and layer count grow, this term often becomes a memory bottleneck before the weights do, directly capping the concurrency you can serve. This is the primary motivation behind the variants that follow.
4. Multi-Query Attention (MQA): Pushing the Cache to the Limit
The most direct approach is to let all query heads share a single set of keys and values, i.e. kv_heads = 1. At inference time the KV cache shrinks to 1 / n_heads of its original size, memory pressure drops sharply, and the volume of key/value loading inside the attention computation falls as well, so decoding throughput improves markedly.
The cost comes from representational capacity. Every head is forced to retrieve information from the same key/value representation, so the retrieval targets of different heads conflict with one another. Quality regressions appear on some downstream tasks, and training stability depends more heavily on tuning. For this reason, pure single-query designs are rarely used on their own in today’s general-purpose models.
5. Grouped-Query Attention (GQA): The Current Mainstream Compromise
Grouped-query attention divides the query heads into several groups, with each group sharing one set of keys and values, so kv_heads takes a value between 1 and n_heads. It forms a continuously adjustable spectrum: kv_heads = n_heads degenerates into MHA, kv_heads = 1 degenerates into MQA, and intermediate values trade quality against cost roughly linearly. In practice, setting kv_heads to around 8 typically recovers quality close to MHA while cutting the KV cache down to a fraction of its size.
Implementation requires no change to the attention formula. You only need to align each group’s keys and values to the corresponding query heads when reading from the history cache:
# Illustrative code: GQA group alignment logic (scaling and mask details omitted)def grouped_attention(q, k, v, causal=True):# q: [batch, heads, seq, head_dim]# k: [batch, kv_heads, seq, head_dim]heads, kv_heads = q.shape[1], k.shape[1]group = heads // kv_headsk = repeat_interleave(k, group, dim=1) # expand along the head dim to align with qv = repeat_interleave(v, group, dim=1)scores = matmul(q, transpose(k, -2, -1)) / sqrt(q.shape[-1])if causal:scores = scores + causal_mask(scores.shape[-2:]) # set the upper triangle to -infreturn matmul(softmax(scores), v)
One important engineering detail: the replication should happen only at computation time, while the cache still stores just kv_heads copies of keys and values. If you replicate first and then write to the cache on the decoding path, the memory savings are completely erased. The common practice is to adjust the attention kernel so that it indexes the shared keys and values by group directly, rather than materializing the expanded tensors.
6. Sliding Window Attention: Trading Global Reach for Local Reach
Grouped-query attention addresses “how much KV to store”; sliding window attention addresses “how far each position can see.” Local attention restricts the visible range to a fixed width W before the current position (or symmetrically before and after it), which reduces the attention complexity of a single layer from quadratic in sequence length to linear, cutting both memory and computation substantially under long context. Local windows also pair well with positional encodings and routing-style modules, and they capture short-range dependencies more thoroughly than global attention does.
The direct consequence of localization is a limited receptive field: after layer L, the effective receptive field of a position is roughly L × W. A purely local scheme therefore needs enough layers to cover long-range information. A common mitigation is to alternate across layers: some layers use a sliding window for local refinement, while others keep global attention for cross-segment aggregation, forming a “local-global” hybrid layout. Another approach is to introduce a small number of learnable global aggregation positions, letting distant information be relayed through a few hub nodes.
7. Other Variants and Supporting Designs Worth Knowing
Cross-attention aligns information between two sequences. The typical case is a decoder reading the encoder’s keys and values, seen in translation and image-conditioned generation tasks. It does not appear in purely autoregressive language models, but is common in multimodal fusion modules.
Changes on the output side also affect quality and stability. Normalizing queries and keys alleviates the problem of overly sharp attention score distributions. Introducing a learnable gate after the softmax lets the model decay attention weights adaptively per position, which helps suppress “meaningless high-weight positions” from consuming the attention budget. In addition, the choice of positional encoding scheme, such as rotary position embedding, and its interpolation and extrapolation strategies, has a major impact on whether a model works stably on contexts longer than its training length.
One layer further out are the routes that go beyond addressable attention. State-space models maintain a fixed-size state in recurrent form and offer a linear-complexity advantage on long sequences. What is more common in practice is hybrid architecture: a small number of attention layers handle precise retrieval, while a large number of linear or state-space layers handle cheap long-range information transfer. Approximation schemes such as sparse attention and linear attention follow similar thinking; all of them trade controllable loss of expressiveness for reduced complexity.
8. Selection Principles and a Verification Checklist
When choosing, work through the following order:
- Set latency and concurrency targets first, then derive the KV cache budget you can afford, instead of picking a structure first.
- Within that budget, prefer grouped-query attention, and treat
kv_headsas a tunable hyperparameter, sweeping values such as 4 and 8 in small-scale validation experiments. - If long context is required, evaluate a “layer-wise global/local hybrid” before full global attention at every layer, and record how the layer allocation affects long-range tasks.
- Any change must be validated on three fronts simultaneously: quality (perplexity, downstream task scores), long-context capability (long-distance retrieval, multi-hop reasoning), and inference metrics (peak memory, per-request time to first token, in-batch throughput).
- Pay particular attention to cache-path consistency: a custom attention kernel and the naive implementation must be compared element by element on identical inputs, to avoid the hidden defect of “training looks fine, inference drifts.”
There are three common misconceptions. First, treating attention variants as pure inference optimizations while ignoring their effect on pretraining stability and downstream quality. Second, looking only at the theoretical complexity of a single forward pass while ignoring that memory bandwidth is the main constraint during decoding. Third, drawing conclusions from perplexity alone, when long-range retrieval tasks often reveal differences only at contexts tens of thousands of tokens long.
9. Additional Advice for Production Deployment
Once the architecture is settled, real deployment still requires work in several areas: use dynamic batching and paged KV cache management to improve memory utilization, and continuous batching to raise decoding throughput; quantize the KV cache on demand to compress its footprint further, and confirm through offline evaluation that the resulting quality loss is acceptable; and build a complete observability system that brings queue wait time, batch size distribution, cache hit rate, timeouts, and error rates into logs, monitoring, and alerting, with thresholds that trigger alerts so capacity planning rests on data rather than rough estimates. On cloud platforms such as Baidu AI Cloud, this kind of training and inference pipeline can be assembled from general-purpose capabilities including container platforms, object storage, log services, and monitoring and alerting; the emphasis is on fixing your capacity model, evaluation baseline, and canary release process in place.
In one sentence: the main line of evolution in modern attention mechanisms is the search for a sustainable balance between “representational capacity” and “KV cache cost.” Grouped-query attention, local windows, and global-local hybrids together form the shared foundation of most current open-weight architectures, and understanding the reasoning behind their trade-offs matters more than memorizing any specific configuration.
