Modern LLM Attention Variants: A Complete Guide and Selection Framework
This article reviews why attention variants matter in the decoder-only era, builds a reference MHA implementation, and explains the main trade-offs behind MQA, GQA, sliding-window attention, attention sinks, positional encoding, and numerical stability. It then offers a unified configuration model and a practical selection and evaluation checklist for choosing and testing attention designs in production LLM systems.
1. Why revisit attention variants?
The history of attention mechanisms predates today’s dominant Decoder-only architecture. Attention was not originally designed for large models. It was first introduced to fix a structural weakness of “encoder-decoder recurrent neural networks” in machine translation: the encoder reads the source sentence word by word and compresses the whole sentence into a sequence of hidden states (in the simplest version, only the last state), and the decoder then generates the translation from that limited summary. Short sentences work fine, but once key information is far from the beginning of the input, the compressed summary quickly becomes an information bottleneck.
Attention provided a simple answer: do not compress the input once during encoding; instead, look back at the entire input on demand at every decoding step. This replaced the “fixed-length summary” with “addressable global memory,” and gave models, for the first time, the ability to model long-range dependencies. All variants today, no matter how different their forms, still run on this basic logic.
But over the past two to three years, the focus of discussion has shifted: from “can we model long dependencies” to “can we model long dependencies cheaply.” The reason is that the inference pattern has changed. During autoregressive decoding, every newly generated token must re-read all historical key-value pairs, so attention has degraded from a compute-intensive operation into a bandwidth-intensive operation. As a result, KV cache size, batch concurrency, time-to-first-token latency, and long-context cost have all become first-class concerns in architecture design. Understanding the various attention variants is essentially understanding which “knobs” each one turns.
2. Establishing a reference: the complete minimal view of self-attention
Multi-head attention (MHA) is the standard Transformer form of this idea. To explain the differences among variants, we first give a reference implementation without any optimization. All later variants can be viewed as modifications to some lines of this code.
def scaled_dot_product_attention(q, k, v, causal=True):"""q: [B, Hq, T, D] queryk: [B, Hkv, T, D] keyv: [B, Hkv, T, D] value"""scale = q.shape[-1] ** -0.5scores = (q @ k.transpose(-1, -2)) * scale # [B, Hq, T, T]if causal:scores = scores + causal_mask(scores.shape[-2:]) # set the upper triangle to -infweights = softmax(scores, dim=-1)return weights @ v # [B, Hq, T, D]
Three quantities determine the entire cost of this module, and they are also the battlefield on which all variants compete:
- Compute: the attention score matrix is
T × Tand grows quadratically with sequence length; - KV cache size: during decoding, historical K/V must be retained and accumulated layer by layer and token by token;
- Arithmetic intensity: during batched decoding, each new token contributes only one query row but must read back all KV, so the compute-to-memory ratio is extremely low.
The design intent of MHA itself goes beyond the third point: it runs multiple self-attention heads in parallel, each with different learned projections, allowing the model to model different relation patterns (syntactic dependencies, coreference, local collocations, etc.) in multiple representation subspaces simultaneously. The outputs are concatenated and then projected once to produce a richer context-aware representation than a single head.
The cost is equally clear: KV cache grows linearly with the number of heads. The cache bytes per token per layer can be approximated as
bytes_per_token_per_layer = 2 × n_kv_heads × head_dim × bytes_per_elementtotal_kv_bytes = bytes_per_token_per_layer × n_layers × seq_len × batch_size
In production scenarios with long context and high concurrency, this product often exceeds the GPU memory occupied by the weights themselves. Almost all subsequent variants revolve around this formula.
3. MQA and GQA: trading sharing for bandwidth
3.1 Multi-Query Attention (MQA)
The most aggressive step is to let all query heads share the same K/V projection, i.e., n_kv_heads = 1. The cache size drops directly to 1/H of the original (where H is the number of query heads), and the KV read volume during decoding drops by the same ratio. In online serving, this often translates directly into throughput gains.
The problem is also direct: representational capacity is compressed, training can be unstable early on, and convergence quality may degrade on some tasks. It is more like an extreme point that “trades capacity for efficiency” rather than a general default option.
3.2 Grouped-Query Attention (GQA)
GQA is a continuous interpolation between the two: query heads are divided into G groups, and heads within a group share one K/V. When G = H, it degenerates into MHA; when G = 1, it degenerates into MQA.
def repeat_kv(kv, n_rep):"""kv: [B, Hkv, T, D] -> [B, Hkv * n_rep, T, D]"""b, h, t, d = kv.shapekv = kv[:, :, None].expand(b, h, n_rep, t, d)return kv.reshape(b, h * n_rep, t, d)def gqa_attention(q, k, v, n_q_heads, causal=True):n_rep = n_q_heads // k.shape[1]k = repeat_kv(k, n_rep)v = repeat_kv(v, n_rep)return scaled_dot_product_attention(q, k, v, causal=causal)
In practice, setting n_q_heads = 32 and n_kv_heads = 8 is a common configuration, meaning 4 query heads share one key-value group. The empirical rule is: with a 75% reduction in cache, quality loss is usually difficult to detect in normal evaluations. When the number of groups is further reduced to 2 or 4, returns diminish while risk increases.
3.3 A migration path that is easy to overlook
GQA spread quickly partly because it supports conversion from already-trained MHA weights: take the K/V projection outputs of multiple heads that originally belonged to the same group, average-pool them along the head dimension, and use the result as the shared initialization for that group. A small amount of continued pretraining is then enough to recover performance. This path greatly lowers the migration cost for the entire ecosystem, and it is a typical case where “engineering feasibility” wins over “theoretical optimality” in architecture evolution.
Engineering constraints: the number of query heads must be divisible by the number of KV heads; the number of groups should not exceed the range allowed by the head dimension; the conversion script must synchronously handle the independent application of rotary position encoding inside each head, otherwise it will introduce hard-to-locate quality regressions.
4. Sliding-window attention: reducing quadratic complexity to linear
4.1 Core assumption and implementation
The second orthogonal dimension is visibility range. Sliding-window attention restricts each query to see only itself and a fixed number of tokens to its left. The attention matrix becomes banded, theoretical complexity drops from O(T²) to O(T × W), and the KV cache becomes bounded.
def build_local_mask(seq_len, window):"""Left sliding window + causal constraint; window is the window width"""mask = full((seq_len, seq_len), value=-inf)for i in range(seq_len): # query positionlo = max(0, i - window + 1) # left boundary of the windowfor j in range(lo, i + 1): # only allow attending to history within the windowmask[i][j] = 0.0return mask
4.2 Effective receptive field and stacking depth
A single window of size W can only cover W tokens, but after stacking multiple layers, information can propagate outward layer by layer. L layers of homogeneous local attention have a theoretical receptive field of about L × W. This leads to a clear implication: local attention transfers the burden of “context length” from memory to network depth. If the model is not deep enough while the window is too narrow, remote information will be repeatedly compressed and attenuated during layer-wise propagation, manifesting as a collapse in mid-document retrieval ability for long documents.
4.3 Mainstream compromise: hybrid layer design
Therefore, pure sliding-window attention is uncommon in general-purpose models. A more common approach is hierarchical mixing: most layers use local windows for fine-grained local modeling, while a few layers (for example, once every several layers) retain global attention and act as a “highway” for long-range information. The advantage of this design is that memory and compute are controllable while preserving a short path between any two points. The difficulty lies in tuning the layer ratio, and in the different KV cache management strategies between local and global layers: the former can be evicted in a rolling manner, while the latter must be retained completely.
5. Attention sinks: the most easily overlooked correctness trap
The output of softmax necessarily sums to 1, so the model cannot “look at nothing.” Research has found that a large amount of attention probability is dumped onto a few tokens at the very beginning of the sequence, even when those tokens have no semantic information. These positions are therefore called attention sinks, and their role is closer to a “low-information trash can” or a “no-op register.”
This phenomenon has a direct impact on engineering practice: if sliding-window cropping removes the first few tokens, or if cache eviction is too aggressive, perplexity can suddenly deteriorate significantly, and during troubleshooting it is easy to misjudge this as a problem with the model itself.
There are three common mitigation directions:
- Retain prefix tokens: during window sliding, always keep a few positions at the beginning of the sequence. The cost is that the cache is no longer strictly bounded (though usually only a very small number of positions need to be kept);
- Introduce learnable sink tokens: add virtual tokens near the beginning of the sequence that do not participate in semantics and are specifically designed to absorb excess probability;
- Rewrite the normalization form: add a learnable bias/gating term outside softmax so that “looking less” becomes an expressible choice, reducing reliance on real tokens.
It is important to emphasize that this is a high-leverage point at the implementation-detail level: the change is small, but its impact on stability in long-context scenarios is significant.
6. Coupling factors with attention: positional encoding and numerical stability
Attention variants are never chosen in isolation. Two coupling factors must also be considered together.
Positional encoding: moving from absolute positional embeddings to rotary relative positional encoding means attention scores naturally carry relative distance information. This is the foundation of long-context extrapolation, but it also means the key vectors stored in the KV cache are strongly bound to positions. Once historical KV is cropped, compressed, or reordered, position relationships must be handled synchronously; otherwise extrapolation ability will fail. Position interpolation or frequency-scaling strategies adopted to extend the context window also change the effective receptive field under different layers and attention patterns, and need to be jointly tuned with window width.
Numerical stability: in long sequences, the dynamic range of the attention score matrix becomes larger, and softmax is prone to overflow or underflow. The common industry practice is online normalization (chunked computation, maintaining a running maximum and running denominator), combined with low-precision storage and high-precision accumulation. The value of such fused kernels lies not in the algorithm but in reducing HBM reads and writes—it pushes attention back from the “memory-bound” region toward the “compute-bound” region, and is one of the prerequisites for making long-context training and inference feasible.
7. Unified abstraction: describing all variants with one configuration
The above variants can be consolidated into a minimal configuration structure, which is also the recommended design approach for engineering implementation:
@dataclassclass AttentionConfig:n_q_heads: int # number of query headsn_kv_heads: int # = n_q_heads -> MHA; = 1 -> MQA; otherwise -> GQAwindow: int | None # None -> global attention; positive int -> sliding-window widthsink_tokens: int = 0 # number of prefix tokens always retainedglobal_every: int = 0 # enable global attention every N layers; 0 means disableduse_qk_norm: bool = False # normalize Q/K to suppress attention entropy collapse late in training
With a comparison table, the selection logic becomes very clear:
| Dimension | MHA | GQA | MQA | Sliding Window |
|---|---|---|---|---|
| KV cache | baseline | 1/G | 1/H | bounded (≈W) |
| Decode bandwidth pressure | high | medium | low | low |
| Long-range exact retrieval | strong | strong | strong | depends on stacking and global layers |
| Training stability | baseline | good | requires extra techniques | good |
| Migration cost from MHA | — | low (pooled initialization) | medium | requires continued training |
8. Practical recommendations: how to choose and test
The recommended decision order is:
- First locate the bottleneck. If the online bottleneck is memory capacity and decode bandwidth (typical of long context and high-concurrency small batches), prioritize changing the number of KV heads and visibility range. If the bottleneck is pretraining compute or short-sequence throughput, the gains are limited, and you should not change things recklessly.
- Then set the number of KV heads. Start with GQA, run small-scale controlled experiments with query/key-value head ratios from 4:1 to 8:1, and gradually go down one level before quality begins to degrade measurably.
- Then set the window and mixing ratio. First fix the number of global layers (to ensure a short path exists for any long distance), then reduce the window width of local layers.
- Finally handle attention sinks and position extrapolation. These two items often have a greater impact on long-context stability than the capacity adjustments above.
Evaluation must be layered; a single metric will hide problems:
- Short-context perplexity and downstream task benchmarks (verify that basic ability has not degraded);
- Long-context retrieval tasks (place key information at different depth positions and test mid-document recall);
- Service metrics: time-to-first-token, per-token latency during decoding, peak KV cache usage, and maximum concurrency when reaching the target throughput;
- Stability: the perplexity difference before and after window cropping, and before and after cache eviction is enabled, as a regression defense line.
For deployment, it is recommended to explicitly expose the attention configuration as a service parameter, and to include KV cache usage, queue waiting time, and actual batch fill rate in monitoring and alerting. On cloud platforms such as Baidu AI Cloud, you can typically run inference services on a container platform, use logging and monitoring/alerting to cover the above metrics, and use object storage to manage multiple weight versions, thereby keeping the cost of comparing architectural experiments within an acceptable range.
Three common pitfalls to remember: first, treating GQA as a “free lunch”—on very small models or very short sequences, the gains will be offset by implementation complexity; second, adjusting only the window without adjusting depth, resulting in an insufficient effective receptive field; third, ignoring the interaction between KV cache quantization and attention-structure variants—low-precision caches amplify long-range retrieval errors, and the two need to be validated jointly.
9. Summary
The evolution of attention variants can be summarized as a clear main line: while keeping the core capability of “looking back on demand” unchanged, continuously reducing its three cost sources. MHA established the paradigm of parallel modeling in multiple subspaces; MQA and GQA compress cache and bandwidth along the direction of “reducing key-value copies”; sliding-window attention reduces complexity to linear along the direction of “limiting visibility range”; attention sinks, positional encoding, and numerical stability remind us that efficiency optimization is never pure subtraction—the deleted parts need new mechanisms to compensate.
For developers, what is truly valuable is not memorizing which variant is “best,” but mastering this analysis framework: first calculate the memory and bandwidth budget, then decide which knob to turn, and finally quantify each trade-off with layered evaluation. This method also applies to future variants—they will most likely also present new compromise points on these three dimensions.
