Attention Mechanism Variants in Modern LLMs: MHA, MQA, GQA, and Sliding Window Attention Explained
Self-attention is the core building block of modern large language models, but the way it is implemented varies widely across architectures. This article walks through the standard self-attention computation, explains why the KV cache becomes the dominant cost at inference time, and compares the main variants used to address it: multi-head attention (MHA), multi-query attention (MQA), grouped query attention (GQA), and sliding window attention. It also covers how each variant changes memory usage, throughput, and model quality, along with practical guidance on choosing between them.
Attention Mechanism Variants in Modern LLMs: A Complete Guide
1. Why Attention Is the Key to Understanding LLMs
Self-attention is the core building block of modern large language models. It lets every token in a sequence “see” the other visible tokens, assign them different weights, and use that weighting to build a new representation that blends in global context. This mechanism is what allows models to capture long-range dependencies and move past the inherent limits of early recurrent networks on long sequences.
Engineering optimizations around attention have multiplied in recent years. For developers working on inference deployment, memory optimization, and model selection, understanding how these variants differ is no longer optional nice-to-have knowledge — it is part of the basics.
2. A Brief History: From RNNs to Attention
To see why attention appeared, start in the era when recurrent neural networks (RNNs) dominated. Typical machine translation systems used an encoder–decoder structure:
- The encoder reads each token of the source sentence one by one, compressing the information into a sequence of hidden states, or in the simplest versions into a single final state vector.
- The decoder then generates the target sentence step by step from that limited summary.
This works reasonably well for short sentences with simple structure. But once the information needed for the next output word sits elsewhere in the input sequence, the problem surfaces: hidden state capacity is finite and cannot store unlimited information, so the model is forced to discard a large amount of detail during compression. The result is a clear information bottleneck.
Attention is a direct answer to that bottleneck. It lets the decoder look back over the entire source sequence each time it produces a word, dynamically deciding which positions matter, instead of relying on a fixed-length summary. That idea was later brought into the Transformer and combined with self-attention, establishing the paradigm LLMs are built on today.
3. How Self-Attention Works
Before optimizing anything, it helps to pin down the standard self-attention computation. For each input token, the model produces a query (Q), key (K), and value (V) through three linear projections:
Q = X · W_qK = X · W_kV = X · W_v
It then takes dot products between the query and all keys to get attention scores, and after scaling, masking, and softmax normalization, computes a weighted sum over the values:
scores = Q · Kᵀ / √d_k # d_k is the key dimension, used for scalingscores = scores + mask # causal mask, hides future tokensweights = softmax(scores) # normalized attention weightsoutput = weights · V # weighted aggregation of value vectors
Two points are worth emphasizing. First, the √d_k scaling factor prevents the dot products from growing too large as dimensionality increases, which would push softmax into a saturated region with tiny gradients. Second, the causal mask guarantees that each position can only attend to tokens before it (including itself) — essential for autoregressive generation.
4. Multi-Head Attention (MHA): Capturing Several Relationships in Parallel
Multi-head attention (MHA) is the standard approach in the Transformer. Instead of a single set of Q/K/V projections, it runs several attention heads in parallel, each with its own independent, learnable projection matrices:
# Each head is computed independently, then concatenated and projected backhead_i = Attention(X·W_q_i, X·W_k_i, X·W_v_i)output = Concat(head_1, ..., head_h) · W_o
Different heads can learn different attention patterns: some attend to adjacent tokens, some capture long-range syntactic relationships, and some specialize in particular semantic features. The output projection then merges the concatenated head results into a richer representation. The value of the multi-head design, in short, is observing the same sequence from multiple perspectives at once.
5. The Real Inference Challenge: The KV Cache
MHA works well, but it plants a problem for inference. During autoregressive generation, producing each new token requires the keys and values of all previous tokens. To avoid recomputing them, engineering practice uses a KV cache: computed K and V are stored and reused.
The catch is that every head in MHA keeps its full K and V, so the more heads, the larger the cache. As context length and batch size grow, the KV cache expands quickly and becomes the main bottleneck on memory capacity and memory bandwidth — often more demanding than the model weights themselves. This is precisely the background against which a series of attention variants emerged, all sharing one core goal: compress the KV cache with almost no loss in quality.
6. Multi-Query Attention (MQA): One Shared Set of Keys and Values
Multi-query attention (MQA) takes a straightforward approach: since each head’s K/V costs memory, let all query heads share a single set of K and V.
# All Q heads share one K, VK_shared, V_shared = project_shared_kv(X) # only one setfor i in range(h): # h query headshead_i = Attention(Q_i, K_shared, V_shared)
The payoff is significant: KV cache size drops to 1/h of the original, memory and bandwidth pressure at inference fall sharply, and decoding throughput improves noticeably. The cost is a potential loss in representational capacity — all heads are forced to share the same view, and the model may need more training or larger capacity to compensate. In practice, given sufficient training, MQA usually achieves a reasonable balance between efficiency and quality.
7. Grouped Query Attention (GQA): The Middle Path
Grouped query attention (GQA) is the compromise between MHA and MQA, and the default choice in many current mainstream open-weight models. It splits the query heads into groups, where multiple query heads within a group share one set of K/V:
num_groups = 4 # number of groups, between 1 (MQA) and num_heads (MHA)Q_reshaped = Q.reshape(num_groups, heads_per_group, seq, dim)K = K.reshape(num_groups, 1, seq, dim) # one shared K per groupV = V.reshape(num_groups, 1, seq, dim)
- When the number of groups equals the number of heads, this is equivalent to MHA.
- When the number of groups is 1, it reduces to MQA.
The significance of GQA is that it provides a tunable, continuous knob: developers can trade memory efficiency against model quality freely. Fewer groups means a smaller cache and faster inference; more groups moves closer to the original expressiveness of MHA. That flexibility is a large part of why it is so widely adopted.
8. Sliding Window Attention: Narrowing the Scope to Local Context
The variants above optimize the structure of the KV cache, while sliding window attention approaches from a different angle: how much context each token needs to attend to. It restricts each token to attend only to nearby tokens within a fixed-size local window:
# Attend only within the window; positions outside it are masked outfor pos in range(seq_len):mask[pos, max(0, pos - window + 1): pos + 1] = 0
This brings attention complexity down from quadratic in the sequence length to linear growth with the window size, which suits very long documents well. The cost is the loss of direct connections between arbitrary pairs of points — though by stacking layers, information still propagates step by step through network depth and eventually reaches distant positions. This combination of “local attention plus hierarchical propagation” is an important family of designs for long-context modeling.
9. How to Choose: Practical Guidance for Developers
Given these variants, engineering decisions should not be arbitrary. A few points are worth keeping in mind:
Identify the actual bottleneck. If memory and bandwidth are tight at inference with long contexts, look first at the KV-cache-related variants (MQA, GQA). If training compute is constrained by long sequences, consider complexity-reducing options such as sliding window attention.
Make use of GQA’s flexibility. When quality and efficiency are hard to balance, the group count in GQA is the first knob to tune, validated with small-scale ablations against your downstream task.
Treat cache optimization as part of the overall design. Attention variants need to work together with batching and scheduling, paged cache management, quantization, and other techniques; optimizing a single layer in isolation usually yields limited gains.
Pay attention to train–inference consistency. Inference-side acceleration techniques such as sharing K/V depend on the model having been trained with the corresponding structure in the first place; discussing deployment optimization in isolation from training tends to waste effort.
10. Conclusion
The evolution of the attention mechanism is, at its heart, a history of continuously searching for a balance point between representational capacity and compute/memory efficiency. From the information bottleneck of the RNN era, to the strong expressiveness of standard multi-head attention, to the efficiency gains brought by multi-query, grouped query, and sliding window attention, each improvement is a response to a real engineering constraint. For developers, understanding the principles and trade-offs behind these variants is more than memorizing a few terms — it is the ability to make sound technical decisions in real business scenarios, which is exactly what moves LLMs from “it runs” to “it runs well and runs cheap.”
