Attention Variants in Modern LLMs: A Complete Walkthrough and Practical Selection Guide
Over the past two years, open-weight model architectures have followed a clear trajectory. The Transformer backbone has largely stabilized, and architectural innovation has concentrated on attention variants, including multi-query attention (MQA), grouped-query attention (GQA), cross-layer key/value sharing, low-rank KV compression, sliding-window attention, and interleaved global layers. These designs do not increase the theoretical expressiveness of a single forward pass. Instead, they aim to shrink the key/value cache (KV Cache) overhead of autoregressive decoding, support longer contexts, and strike a better balance between throughput and generation quality. This article breaks down each variant by motivation, mechanism, cost, and selection criteria, and provides KV cache estimation methods, a decision checklist, and engineering recommendations you can put into practice.
1. Starting Point: Self-Attention and Multi-Head Attention
Self-attention lets every position in a sequence read the other positions it is allowed to see. It then aggregates their information by relevance to produce a new, context-aware representation. The computation breaks down into four steps:
- Linear projection: Three sets of learnable weights map the input hidden state to queries (Q), keys (K), and values (V).
- Similarity scoring: The dot product of Q and K is divided by the square root of the head dimension. This scaling keeps the variance of the dot product from growing with dimensionality, which would otherwise saturate Softmax and make gradients vanish.
- Masking and normalization: Decoder models apply a causal mask so that each position cannot see future tokens. A Softmax then converts the masked scores into attention weights.
- Weighted sum: The weights are applied to V, producing the output for each position. An output projection layer then combines these outputs.
Multi-head attention (MHA) runs this process in parallel across several heads, each with its own projection matrices. This lets different heads specialize in patterns such as local adjacency, long-distance coreference, and syntactic structure. The outputs of all heads are then concatenated. This “parallel multi-view plus final fusion” structure is the standard configuration in most of today’s large models.
The following illustrative, framework-agnostic pseudocode shows only tensor semantics:
# x: [batch, seq_len, d_model]q = x @ Wq # [batch, seq_len, n_heads * head_dim]k = x @ Wkv = x @ Wvscores = (q @ k.transpose(-1, -2)) / sqrt(head_dim) # [b, n_heads, L, L]scores = scores + causal_mask # mask future positions with -infattn = softmax(scores, dim=-1)out = (attn @ v).reshape(b, L, d_model) @ Wo
One often-overlooked fact deserves emphasis. Attention long predates both the Transformer and the multi-head structure. Its direct predecessor was the attention mechanism in encoder–decoder recurrent networks built for machine translation.
- A recurrent encoder compressed the source sentence step by step into a limited sequence of hidden states.
- The decoder could rely only on that “summary” to generate the target sentence.
- When critical information appeared far away in a long input, this created an information bottleneck.
Attention was introduced so that the decoder could look back at the full input on demand.
This history illuminates a hidden assumption shared by every variant discussed below. Attention derives its value from the ability to look back. It incurs its cost from the need to store everything that might be looked back at.
2. The Core Conflict: Why the KV Cache Becomes the Engineering Bottleneck
During training, Q, K, and V are computed in parallel from the full sequence in a single pass, so there is no caching problem. During autoregressive decoding, however, attention would have to be recomputed for every token generated. To avoid re-projecting past tokens over and over, implementations cache the K and V tensors that have already been computed and reuse them.
This cache grows linearly with sequence length, and its size can be estimated with the following formula:
KV_bytes = 2 × n_layers × n_kv_heads × head_dim × seq_len × batch × bytes_per_elem
The factor of 2 accounts for the two tensors, K and V. Consider a model with 32 layers, a head dimension of 128, a sequence length of 8192, a batch size of 1, and half precision:
- With a standard multi-head setup of 32 key/value heads, the cache is roughly 4 GiB.
- Reducing this to 8 key/value heads cuts the cache to about 1 GiB.
At this scale, three consequences follow directly:
- Squeezed batching capacity. The cache takes up GPU memory that could otherwise hold more requests, so the achievable batch concurrency shrinks and throughput is capped.
- Memory-bandwidth-bound decoding. Memory bandwidth, rather than compute, becomes the bottleneck during decoding. Every generated token requires reading the entire cache, so memory traffic and latency are tightly coupled.
- Deployment cost driven by the cache. In long-context scenarios, the cache can exceed the model weights themselves and become the main driver of deployment cost.
For these reasons, nearly all mainstream open-weight architectures in recent years have pursued the same goal: reducing the number of keys and values that must be cached and moved around.
3. First Family of Optimizations: KV Head Sharing (MQA and GQA)
The most direct idea is to let multiple query heads share the same key/value projections. In the extreme case, only one set of keys and values is kept. This is query-sharing attention, commonly known as multi-query attention (MQA).
- Memory savings: Cache size shrinks in proportion to the ratio of key/value heads to query heads.
- Throughput gains: With 32 query heads and only 1 key/value head, the cache shrinks to about 1/32 of its original size. The volume of memory reads during decoding drops accordingly, and benchmarks often show clear improvements in throughput and latency.
The trade-off is a loss of expressiveness:
- Every query head faces the exact same set of keys and values, so the heads can no longer form complementary views.
- Training stability and downstream quality typically degrade to some degree.
- The model tends to be more sensitive to tasks such as repetition and long-distance coreference.
Grouped-query attention (GQA) is a compromise designed to address this issue:
- Mechanism: It keeps multiple query heads and partitions them into groups. Each group shares one set of key/value projections.
- Tunable knob: When the number of key/value heads equals the number of query heads, GQA becomes standard multi-head attention. When there is only one key/value head, it becomes MQA.
- Typical configuration: 8 key/value heads paired with 32 query heads, so each group of 4 query heads shares one set of keys and values. This cuts the cache by roughly 4×, while the quality loss is often acceptable.
GQA is also the most mainstream choice among open-weight models of medium scale and above.
In the pseudocode, the only key difference is that the query heads must be reordered by group before scoring:
# n_q_heads = 32, n_kv_heads = 8, group_size = n_q_heads // n_kv_headsq = q.reshape(b, L, n_kv_heads, group_size * head_dim)q = q.reshape(b, L, n_kv_heads, group_size, head_dim) \.transpose(1, 2) # [b, n_kv_heads, group_size, L, d]k = k.transpose(1, 2).unsqueeze(2) # [b, n_kv_heads, 1, L, d]v = v.transpose(1, 2).unsqueeze(2)# Attention is computed per group via broadcasting; the output is then# restored to the concatenation of all n_q_heads heads
One engineering caveat applies here. Regrouping changes the memory layout, and a poorly implemented kernel can introduce extra transposes and copies. These can offset the savings from the smaller cache. In production, therefore, use fused attention kernels that handle grouped layouts efficiently.
4. Second Family of Optimizations: Cross-Layer Sharing and Low-Rank Compression
GQA only reduces redundancy within each layer, yet adjacent layers also exhibit highly similar key/value patterns.
Cross-layer sharing. One approach is cross-layer sharing:
- Mechanism: Several adjacent layers reuse the same key/value projection results, or later layers use the keys and values already computed by earlier layers. The number of layers whose key/value data must be cached is reduced accordingly.
- Advantages: It is simple to implement and does not change the mathematics of attention.
- Limitation: It compromises layer independence and requires coordination during training. Introducing it on its own during post-training usually does not work well.
Low-rank compression. The other approach is low-rank compression:
- Mechanism: Instead of caching full keys and values, the model jointly compresses them into a low-dimensional latent vector much smaller than
head_dim × n_heads. This latent vector is what gets cached, and it is up-projected back when needed. - Why it works: Because attention scores depend only on the compressed latent representation, in principle there is no need to reconstruct the full keys and values.
- Benefits: It reduces both GPU memory usage and memory traffic during decoding, and it typically achieves higher compression ratios than GQA.
- Requirements: It requires modifying the internal computation path of the attention kernel. This places higher demands on the inference engine and makes such methods less general and less portable than GQA.
5. Third Family of Optimizations: Sparsification and Localization (Sliding Windows and Global-Layer Interleaving)
The approaches above compress the key/value dimensions stored at each position. A different family of methods instead limits the range of keys and values each position can see.
Causal attention is fully connected across the lower triangle of the score matrix, so both computation and caching grow superlinearly with sequence length. Sliding-window attention restricts each position to a fixed window of preceding tokens, often a few thousand tokens wide. This brings per-layer attention complexity down from quadratic to linear. The cache can also be recycled on a rolling basis, once entries fall outside the window.
Using sliding windows alone has a major drawback. Information beyond the window cannot propagate across layers. In practice, this is addressed with a hybrid layout that interleaves local layers with global layers:
- Most layers use sliding windows for local modeling.
- A few layers keep full attention and act as an information backbone that connects windows.
This design is effective because, in principle, information needs only a few layers to hop from window to window. The model can therefore approach global awareness while keeping complexity linear.
The diagram below shows a typical layout. Each cell represents one layer (□ = local window layer, ■ = global layer):
Layer: 1 2 3 4 5 6 7 8Type: □ □ ■ □ □ ■ □ □Scope: small small full small small full small small
Three caveats apply to hybrid layouts:
- Positional encoding must be tuned jointly. Local and global layers differ in how sensitive they are to the scale of positional information, so the positional encoding scheme needs to be adjusted to match.
- Global layers remain bottlenecks. They are still hotspots for GPU memory and latency, so their share needs to be tuned against the target context length.
- Window boundaries cause abrupt shifts. Attention weight distributions can change abruptly at window boundaries. Training therefore needs sufficiently long samples to avoid quality collapse when inference sequences exceed the lengths seen in training.
6. Supporting Mechanisms: Attention Sinks, Positional Bias, and Cache Quantization
Long-context capability depends not only on the choice of attention variant, but also on several supporting designs.
Attention Sinks
Research has found that models tend to assign large amounts of attention to a few tokens at the beginning of the sequence. These tokens appear to act as a kind of no-op “pressure-relief valve.”
- Problem: A sliding window that simply discards the earliest tokens breaks this pattern and can cause a sharp drop in generation quality.
- Solution: Permanently keep the cache of a few leading tokens from being evicted, alongside the recent window. This yields an “anchor plus sliding window” structure.
Positional Bias and Extrapolation
Besides mainstream approaches such as rotary position embeddings (RoPE), some methods add a penalty term linked to relative distance directly onto the attention scores. This makes the model naturally favor nearby information, so it extrapolates more easily to lengths not seen during training.
Other techniques include nonlinearly scaling position indices and adjusting them in segments by frequency component. Such methods leave the cache structure unchanged, but they strongly affect stability on long inputs and need to be tuned jointly with the sliding-window size.
Cache Quantization
Storing the cache at lower precision, such as 8-bit integers or lower, can be combined orthogonally with all of the variants above. It further reduces GPU memory and bandwidth pressure proportionally.
Two caveats apply:
- Keys and values have different numerical distributions, so keys usually warrant a more conservative quantization strategy.
- You should evaluate how sensitive the model’s retrieval-style tasks are to quantization, and keep a few high-precision outlier channels if necessary.
7. Selection Checklist
For a concrete workload, work through these cases in order:
- Lower memory and higher throughput are the top priorities, and the model can be retrained. Choose GQA first. Start with 8 key/value heads and run small-scale controlled experiments to confirm that the quality loss is acceptable before finalizing the configuration.
- You need maximum cache compression and can accept a specialized inference engine. Evaluate low-rank compression approaches and confirm engine and kernel support in advance.
- You need very long contexts (hundreds of thousands of tokens). Use a hybrid sliding-window plus few-global-layers layout with an anchor-retention strategy. Tune extrapolation for your target length range.
- The model is already trained and its structure cannot be changed. The only options are on the deployment side, such as cache quantization, paged cache management, request-prefix reuse, and prefix cache sharing. These reduce repeated computation and memory fragmentation.
- Short contexts and low concurrency. The quality advantage of standard multi-head attention is often worth keeping. The cache is not the bottleneck here, so there is no need to chase variants.
A practical evaluation framework records three metrics together:
- Cache bytes per token
- Per-token latency during decoding
- Relative quality difference on the same set of downstream benchmarks
Optimizing any one of these in isolation will lead to misleading conclusions.
8. Engineering Deployment and Cloud Operations
Paged Cache Management
Splitting the cache into fixed-size blocks that are allocated on demand can substantially reduce GPU memory fragmentation caused by variable-length requests. It also makes prefix sharing straightforward: cache blocks for shared prefixes, such as system prompts and few-shot examples, can be reused across requests instead of being recomputed during prefill.
Scheduling and Batching
Because the KV cache is the main variable in GPU memory usage, the maximum concurrency of a batch is effectively determined by the distribution of context lengths in current traffic. In production, bucket requests by length and schedule long and short requests separately. This prevents long requests from blocking the short-request queue and causing tail-latency spikes.
Observability
At a minimum, collect these metrics:
- Cache hit rate
- Cache block occupancy and eviction counts
- Share of time spent in prefill versus decoding
- Average and P99 output length
- Per-token latency bucketed by sequence length
These metrics help pinpoint performance inflection points. They also let you check, against real traffic, whether an attention variant delivers the expected gains.
General Infrastructure Practices
General infrastructure practices are similar across deployments:
- Model storage: Model weights and versioned artifacts are well suited to object storage with versioning.
- Inference services: Inference services typically run on a container platform with elastic scaling to absorb traffic fluctuations.
- Logging and monitoring: A logging service captures request-level trace data, while alerting sets thresholds on metrics such as cache occupancy, GPU memory utilization, and tail latency.
Baidu AI Cloud offers products for these general capabilities. They can support an end-to-end pipeline from model hosting to canary releases. Specific configurations should be sized against your workload’s length distribution and concurrency profile.
9. Conclusion
Viewed together, these variants are really answering just two questions:
- How much key/value information does each position need to keep?
- How many keys and values is each position allowed to see?
GQA and low-rank compression address the first question. Sliding windows and global-layer interleaving address the second. Attention sinks and cache quantization supplement and refine both.
No attention design is universally optimal. What matters is the combination that fits your context length, concurrency level, latency budget, and quality requirements.
For developers, the most valuable workflow is:
- Use the cache estimation formula to calculate your GPU memory and bandwidth budget.
- Narrow the choice to two or three candidate variants.
- Run controlled experiments with a shared benchmark suite and a realistic traffic distribution.
- Complete the optimization loop with deployment-side techniques: paged caching, prefix reuse, and quantization.
