Attention Mechanisms in Modern LLMs: MHA, MQA, GQA, and Sliding Window Explained
Much of the power of modern large language models comes from the attention mechanism, which lets a model weigh the importance of different positions in a sequence and build context-aware representations. As model sizes and context lengths grow, however, attention has become a major source of compute and memory overhead, leading to a range of variants that balance capability against cost. This article explains the origins and core principles of self-attention, then examines multi-head attention (MHA), multi-query attention (MQA), grouped-query attention (GQA), and sliding window attention, along with the trade-offs behind each.
Attention Mechanisms in Modern LLMs: MHA, MQA, GQA, and Sliding Window Explained
Much of the power of modern large language models rests on the attention mechanism. It allows a model to dynamically decide which positions in a sequence carry more important information, and from that to build context-aware representations. However, as both parameter counts and context lengths keep growing, attention itself has revealed a problem: compute cost and memory usage rise sharply. In response, the field has produced a range of attention variants that seek different balances among competing performance goals. This article takes a neutral, general-purpose view of these mainstream designs, focusing on their design rationale and engineering trade-offs.
1. Background: Why Attention Was Invented
It is worth noting that attention appeared before today’s mainstream Transformer architecture. Its immediate context was the encoder-decoder recurrent neural networks used for machine translation. In such systems, the encoder reads the source sentence token by token and tries to compress all the information into a single hidden state (or a sequence of hidden states). The decoder then generates the target sentence based on this limited summary.
This design works well enough when the source sentence is short and simple. But once key information is scattered across distant positions in the input, a single hidden state becomes an obvious information bottleneck. It cannot hold a nearly unlimited amount of information and context. Attention was introduced precisely so that the decoder could “look back” at the entire input sequence as needed, retrieving relevant parts directly instead of relying on a fixed-length summary. This motivation remains the starting point for understanding attention variants today.
2. How Self-Attention Works
Self-attention lets each token in a sequence “observe” the other visible tokens, assign different weights to them, and then aggregate a new, context-rich representation based on those weights. The core mechanism comes down to three projections:
- Map the input separately to a query (Q), keys (K), and values (V).
- Compute dot-product similarities between the query and all keys, then apply scaling and normalization to obtain the attention weights.
- Compute a weighted sum over the values.
In formula form:
Attention(Q, K, V) = softmax( Q · Kᵀ / √d_k ) · V
The division by √d_k keeps the dot products from growing too large, which could otherwise push softmax into a region of vanishing gradients. This query-key-value interaction paradigm is the common foundation for every attention variant that follows, so it is worth mastering first.
3. Multi-Head Attention (MHA)
Multi-head attention is the standard form of this idea in the Transformer. It runs multiple self-attention heads in parallel, each with its own learned projections, so that each head can focus on relationships in a different subspace, such as syntactic dependencies or coreference. The outputs of all heads are then concatenated and combined into a richer representation through a linear layer.
The original intent of the multi-head design is “division of labor”, allowing different heads to learn complementary representations. However, this parallelism also means that the key and value caches grow in proportion to the number of heads. During autoregressive generation, the key-value (KV) cache must store the keys and values of all past tokens. In long-context inference, this memory footprint often becomes the main bottleneck.
4. From MHA to MQA: Cutting Inference Memory
Multi-query attention (MQA) addresses this bottleneck with a bold simplification. All attention heads share the same set of keys and values, while only the query side keeps its multi-head structure. As a result, the KV cache shrinks substantially, memory bandwidth pressure during inference drops significantly, and decoding speed improves. The trade-off is a possible loss in representational capacity, since all heads must extract information from the same K and V.
5. Grouped-Query Attention (GQA): A Middle Ground
Grouped-query attention strikes a balance between MHA and MQA. It divides the query heads into several groups, and each group shares its own independent set of keys and values. When the number of groups equals the number of heads, GQA degenerates into standard MHA. When there is only one group, it is equivalent to MQA. By adjusting the number of groups, practitioners can flexibly trade off representational capacity against inference efficiency. Because of this tunability, grouped-query attention has become a common choice in many modern open-weight architectures. Its core logic can be illustrated with the following pseudocode:
n_heads = number of query headsn_kv_heads = number of key/value groups (n_kv_heads <= n_heads)group_size = n_heads // n_kv_headsQ = project_query(X) # shape: [sequence_length, n_heads, d]K = project_key(X) # shape: [sequence_length, n_kv_heads, d]V = project_value(X) # shape: [sequence_length, n_kv_heads, d]# each key/value group is shared by group_size query headsfor group in range(n_kv_heads):q_group = Q[:, group*group_size : (group+1)*group_size]k_head = K[:, group] # broadcast to the query heads in this groupv_head = V[:, group]out_group = attention(q_group, k_head, v_head)
6. Sliding Window and Local Attention
Beyond compressing the key-value structure, another family of variants addresses a different question: how far should each token look? Sliding window attention restricts each token to attending only to tokens within a fixed-length window before it. This reduces attention complexity from quadratic in the sequence length to linear. Models can therefore handle extremely long contexts while keeping compute overhead manageable. The trade-off is that long-range dependencies beyond the window must be conveyed indirectly by stacking multiple layers.
7. Engineering Trade-offs and Practical Guidance
These attention variants are essentially different solutions to the same tension: modeling sufficiently rich long-range dependencies while keeping compute and memory costs under control. In practice, the choice can be guided by the following considerations:
- Use standard multi-head attention when maximum representational capacity is the goal and memory is not a constraint.
- When inference throughput and memory are key constraints, grouped-query attention is usually a more balanced starting point.
- For extremely long contexts with limited compute, combine local attention strategies such as sliding windows.
- For extreme sensitivity to memory bandwidth, consider the more aggressive multi-query attention approach.
No single variant performs best in every scenario. A sound approach is to make targeted trade-offs and validate them with real benchmarks, taking into account the specific model size, target context length, hardware, and latency requirements of the application. Blindly chasing one “optimal” architecture is rarely the right choice.
