Modern LLM Attention Variants: Principles, Selection, and Engineering Practice
Attention mechanisms have spawned a large family of variants in just a few years. This guide organizes the major variants around three design dimensions—how key/value projections are shared, what each token can attend to, and how masking and positional encoding express causality and order. It covers the MHA/MQA/GQA spectrum, sliding window and local-global attention, cross-attention and multimodal fusion, and includes a unified comparison table, a KV-cache memory-estimation formula, worked examples, and practical engineering guidance on masks, prefix reuse, cache compression, and scheduling. Use it as a reference for choosing an attention variant for a given workload and for estimating inference memory and throughput.
Why You Need a Map of Attention Variants
Attention mechanisms have spawned a large number of variants in just a few years. Reading the papers in isolation makes it hard to see how they relate to one another. Placing them on the same map for comparison is key to understanding modern large language model (LLM) architecture.
These variants can be grouped along three core design dimensions:
- Sharing scheme: whether multiple query heads share the same key/value projections;
- Visibility scope: which positions each token is allowed to attend to;
- Masking and positional encoding: how causality, locality, and order information are expressed.
Once you grasp these three points, seemingly scattered variants can be placed on the same map and compared.
Baseline: Self-Attention and Multi-Head Attention
Attention lets every token in a sequence “look at” other visible tokens, assign them weights, and build a new, context-aware representation. The core computation is:
Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k)·V
Here Q, K, and V are the query, key, and value, all obtained by linearly projecting the input sequence. The dot product measures the correlation between two tokens; the scaling factor √d_k suppresses the numerical blow-up of the dot product as the dimension grows; and softmax normalizes the correlations into weights.
Multi-Head Attention (MHA) is the standard Transformer realization of this idea. It runs several self-attention heads in parallel, each with its own projection matrices to learn a different representation subspace, then concatenates the head outputs and applies one final output projection. Different heads can capture different kinds of dependencies—syntactic structure, coreference, local collocations, and so on.
Self-attention’s computational cost grows quadratically with sequence length. But what really constrains inference cost and the context window is often not the training-time compute, but the historical keys and values that must be cached during inference—the KV cache. The KV cache grows linearly with context length, and in long-context, high-concurrency scenarios it can occupy more GPU memory than the model weights themselves. Most subsequent variants are aimed at either “how to shrink the KV cache with minimal quality loss” or “how to control attention cost over long sequences.”
Multi-Query Attention and Grouped-Query Attention
Since storing a separate set of keys and values per head is the main source of overhead, the most direct fix is to let multiple query heads share the key/value projections.
1. Multi-Query Attention (MQA): all query heads share a single set of K and V, compressing the KV cache to 1/number-of-heads of its original size. In a 32-head model this means several-fold memory savings, at the cost of reduced expressiveness: heads can no longer form independent key/value representations, which can cause accuracy loss on some tasks.
2. Grouped-Query Attention (GQA): split the query heads into several groups, each sharing one set of K and V, with the number of groups denoted G. When G equals the number of heads, it degenerates to MHA; when G equals 1, it is exactly MQA. All three sit on the same continuous spectrum, and in practice GQA has become the mainstream choice for many open-weight models.
Take 32 heads as an example: with G=8 the KV cache drops to 1/4; with G=4 it drops to 1/8; with G=1 it is MQA’s 1/32. Empirically, a G of 4–8 often strikes a good balance between accuracy and memory, but the optimal value must be determined by evaluating the specific task—neither larger nor smaller is inherently better.
3. Where the gains come from: during decoding, each step generates a single token, and the bottleneck is reading weights and the KV cache from GPU memory. Once the KV-cache read volume drops, memory-bandwidth pressure eases, and decode throughput usually improves accordingly. The replicated key/value projections in GQA require no extra computation; at inference time each query head simply reuses the K and V of its group.
Sliding Window Attention and Local-Global Hybrids
MQA and GQA compress the number of keys and values. Sliding Window Attention (SWA) approaches the problem from another direction: it restricts each token to attend to only a fixed number of preceding tokens—the window size w.
1. Compute and cache cost: attention complexity drops from O(n²) to O(n·w), roughly linear in sequence length. Combined with a ring buffer, inference only needs to retain the keys and values within the window, turning KV-cache memory from unbounded growth with context into a controllable upper bound.
2. Receptive field and inter-layer propagation: in theory, after L layers a token’s receptive field is about L×w. But every hop passes through projections and nonlinear transformations, so distant information keeps decaying. Deep models therefore often need a larger window, or a few global layers.
3. Local-global hybrids: let a few layers keep global attention while the rest use sliding windows. The global layers integrate information across windows, while the local layers efficiently extract nearby features—balancing long-range modeling with inference efficiency.
4. Engineering considerations:
- Attention sinks: during autoregressive decoding, the first few tokens of the sequence often persistently receive large attention weights. A naive “keep only the most recent w tokens” eviction can discard this important information. Common mitigations include retaining the first token or sink tokens, introducing an attention sink, or using learnable sink tokens—preserving the key anchors when trimming the cache.
- Cross-request isolation: local windows must explicitly distinguish tokens belonging to different requests or turns in multi-turn dialogues and prefix-reuse scenarios to avoid cross-talk.
- Positional encoding: with relative positional encoding, window constraints usually hold naturally; with an extrapolatable absolute positional encoding, you must evaluate how positions beyond the window are encoded.
Cross-Attention, Non-Causal Attention, and Multimodal Fusion
1. Cross-Attention: in self-attention, Q, K, and V come from the same sequence. Cross-attention lets one sequence’s queries attend to another sequence’s keys and values—a typical use is a decoder reading the encoder’s full output through cross-attention at each layer. This continues the problem attention was originally meant to solve: early encoder-decoder RNNs compressed the entire source sentence into a fixed-length hidden state, creating a bottleneck for any information located elsewhere in the input. Attention lets the decoder directly retrieve from the source sentence at every step, structurally eliminating that bottleneck.
2. Non-causal attention: standard language models use a causal mask, where each position can only attend to itself and earlier positions; encoder-style models typically use bidirectional attention. Masking is essentially another way of expressing visibility scope, and the same computation can be constructed as causal, bidirectional, or block-mixed masks as needed.
3. Multimodal fusion: one approach concatenates text tokens with other modalities’ tokens (e.g., visual) into a single unified sequence that interacts within the same attention layers—simple to implement, but the KV cache grows under longer sequences. Another approach keeps each modality’s own backbone and aligns them through cross-attention at some layers—more flexible structurally, but more complex to train and deploy.
A Unified Comparison of Mainstream Attention Variants
| Variant | Key/value sharing | Visibility scope | Attention compute | KV cache | Typical trade-off |
|---|---|---|---|---|---|
| MHA | Each query head independent | Full sequence or causal | Grows quadratically with sequence length | Largest | Strong expressiveness, high inference cost |
| MQA | All query heads share one set | Full sequence or causal | Grows quadratically with sequence length | Down to ~1/number-of-heads | Most memory-efficient, possible accuracy loss |
| GQA | Each group of query heads shares one set | Full sequence or causal | Grows quadratically with sequence length | Down to ~1/number-of-groups | Balance of memory and accuracy, widely adopted |
| Sliding window | Independent or shared | Local window (can mix global layers) | Roughly linear in sequence length | Trimmable to window size | Efficient for long context, must handle long-range dependencies |
| Cross-attention | Query and keys/values from different sequences | All positions of the other sequence | Depends on source sequence length | Implementation-dependent | Suited to cross-modal and sequence-to-sequence tasks |
Selection Strategy: Decide Around the Memory Budget
When choosing an attention variant, don’t start by comparing paper metrics—start by working out the memory budget. The KV-cache memory can be estimated as:
KV cache memory = 2 × num_layers × num_kv_heads × head_dim × context_length × batch_size × bytes_per_element
The factor 2 accounts for the two caches—keys and values. Take a hidden dimension of 4096, 64 heads, head dimension of 64, 32 layers, fp16 (2 bytes per element), 32 concurrent requests, and an 8192 context as an example:
- MHA (num_kv_heads=64): about 128 GiB;
- GQA (num_kv_heads=8): about 16 GiB;
- MQA (num_kv_heads=1): about 2 GiB.
In the same scenario, the three differ by about 64× in KV-cache memory, while the model weights are identical. If you expand the context from 8K to 128K, the absolute memory gap scales by 128K/8K ≈ 16× accordingly. This is also why the same model family is often released in multiple versions with different attention variants.
On top of that, you can pick a starting point across four typical scenarios:
| Scenario | Prioritize | Key acceptance criteria |
|---|---|---|
| Single-turn generation | MHA or GQA | Per-output quality and latency meet targets |
| Multi-turn dialogue | GQA + prefix reuse | Cache hit rate, concurrent throughput |
| Long documents / long context | Sliding window or local-global hybrid | Long-range recall, positional extrapolation stability |
| Strict memory limits | MQA or large-G GQA | Peak memory under control, accuracy regression within threshold |
The general decision order is: determine the generation pattern → estimate peak memory → check factual accuracy and reasoning-depth requirements → evaluate long-context handling and positional-encoding extrapolation → fix the variant during pretraining or continued training. Swapping the attention variant abruptly at inference time introduces noticeable distribution shift.
Engineering Implementation: From Masks to Inference Serving
1. A minimal implementation of masks and caching
The pseudocode below shows how to construct causal and sliding-window masks in a unified way. Here q_pos and k_pos are 0-based position indices, dtype is integer, and window must be ≥ 1:
def build_mask(q_pos, k_pos, window=None):# q_pos / k_pos: 0-based query and key position indices (integer tensors)# Causal constraint: a query can only see itself and earlier positionsmask = k_pos.unsqueeze(0) <= q_pos.unsqueeze(1)# Sliding window: limit look-back to at most window-1 positions (window must be >= 1)if window is not None:assert window >= 1mask = mask & (q_pos.unsqueeze(1) - k_pos.unsqueeze(0) < window)return mask # Boolean matrix of shape [n_query, n_key]
In inference implementations, keys and values are usually stored in a ring buffer or a paged cache; during training, a banded mask is typically constructed directly to reduce memory usage and compute cost.
2. Key optimizations for inference serving
- KV-cache management: use paged cache management to reduce memory fragmentation and support on-demand allocation and reclamation;
- Prefix reuse: reuse existing KV caches for identical system prompts, few-shot examples, or multi-turn dialogue history to avoid redundant prefilling;
- Cache compression: low-bit quantization of the KV cache or evicting low-importance entries can further reduce memory, but quantization and eviction may cause accuracy loss. Always run a small-scale evaluation after compression to verify the accuracy regression, and roll out gradually via canary release—confirming key metrics stay within bounds before full rollout;
- Scheduling: combine continuous batching with chunked prefill to improve overall throughput under multiple concurrent requests;
- Deployment support: if the inference service runs on a mainstream cloud or inference platform, you can typically use container platforms for elastic scaling, object storage for model files, and general capabilities like logging and monitoring/alerting to continuously track metrics such as time-to-first-token, generation speed, memory utilization, and cache hit rate.
FAQ
- How do I choose between MQA and GQA? Choose MQA when memory is extremely tight and concurrency is very high; when balancing accuracy and memory, GQA is the safer default starting point, and a G of 4–8 is often a good trade-off.
- Does a sliding window lose long-range information? A single layer’s window indeed only sees locally, but this is mitigated through inter-layer propagation and a few global layers; pay attention to positional-encoding extrapolation and retaining the first-token sink.
- How do I estimate KV-cache memory? Use “2 × num_layers × num_kv_heads × head_dim × context_length × batch_size × bytes_per_element,” plugging in 2 bytes per element for fp16.
Conclusion
Attention variants may look numerous, but the design threads are clear: MQA and GQA compress the KV cache by reducing key/value projections in exchange for memory and throughput; sliding windows trade a smaller visibility scope for roughly linear cost; cross-attention supports cross-sequence and cross-modal modeling by separating the sources of query and key/value. When selecting, weigh the variant within the “quality–memory–throughput” coordinate system. For most general-purpose generation scenarios, grouped-query attention is a solid default starting point; when you need very long context or strict memory limits, sliding windows and their local-global hybrids are more worth evaluating first. Thinking in terms of categorizing by dimension, quantifying with formulas, and deciding by scenario is more valuable over the long term than memorizing individual variant names.
