Attention Mechanism Variants in LLMs: MHA vs. MQA vs. GQA, FlashAttention, Sliding Window, and Sparse Attention — Selection and Tuning

    This article walks through the attention variants used in modern large language models, from plain multi-head attention to grouped-query and multi-query attention, FlashAttention, sliding-window attention, and sparse attention. It explains how self-attention and MHA work, why attention emerged from encoder–decoder RNN translation models, and why the KV cache — not parameter count — is usually the real inference-time memory bottleneck. You will find a comparison of KV cache size, time complexity, quality risk, and typical use cases for each variant, annotated PyTorch code for MHA and GQA/MQA, guidance on how position encoding and RoPE interact with attention structure for long context, a practical selection and tuning order for production workloads, and the mistakes most often made when implementing these variants.

    1. How Self-Attention and Multi-Head Attention Work

    Self-attention is, at its core, a way to let every token in a sequence “see” the other visible tokens according to how relevant they are, and to produce a new representation that carries context. Mechanically, each token projects three vectors — a Query, a Key, and a Value. The Query is compared against all Keys for similarity, the resulting scores are normalized into attention weights, and the Values are summed with those weights.

    Multi-head attention (MHA) is the standard engineering form of this mechanism. Rather than keeping a single attention distribution, it runs several attention heads in parallel, each with its own independently learned projection matrices, so token relationships can be observed from different subspaces. The outputs of all heads are concatenated and fused into a richer representation. A useful analogy is several readers going through the same text simultaneously: some heads track syntax, some semantics, some coreference or local collocations.

    Below is a corrected MHA sketch. The key point is that autoregressive generation must apply a causal mask; otherwise the model would “see” future tokens and violate the autoregressive constraint.

    1. import torch
    2. from torch import nn
    3. class MultiHeadAttention(nn.Module):
    4. def __init__(self, d_model, n_heads):
    5. super().__init__()
    6. self.n_heads = n_heads
    7. self.d_head = d_model // n_heads
    8. self.q_proj = nn.Linear(d_model, d_model)
    9. self.k_proj = nn.Linear(d_model, d_model)
    10. self.v_proj = nn.Linear(d_model, d_model)
    11. self.o_proj = nn.Linear(d_model, d_model)
    12. def forward(self, x):
    13. B, T, D = x.shape
    14. q = self.q_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2)
    15. k = self.k_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2)
    16. v = self.v_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2)
    17. # Scaled dot-product attention
    18. attn = (q @ k.transpose(-2, -1)) / (self.d_head ** 0.5)
    19. # Causal mask: prevent a position from attending to future positions
    20. causal_mask = torch.tril(
    21. torch.ones(T, T, device=x.device, dtype=attn.dtype)
    22. ).view(1, 1, T, T)
    23. attn = attn.masked_fill(causal_mask == 0, float("-inf"))
    24. attn = attn.softmax(dim=-1)
    25. out = (attn @ v).transpose(1, 2).reshape(B, T, D)
    26. return self.o_proj(out)

    This snippet illustrates an engineering detail that is easy to overlook: attention does not stop at a matrix multiplication plus a softmax. For autoregressive language models, the causal mask is a baseline condition for correct generation.

    2. Where the Attention Mechanism Came From

    Before comparing variants, it helps to know why attention existed in the first place. It did not arrive together with the Transformer. Its more direct ancestor is the encoder–decoder RNN architecture used in early machine translation.

    In those early systems, the encoder RNN read the source sentence token by token and compressed the entire sentence into a single fixed-size hidden state. The decoder RNN then generated the target sentence from that hidden state. This works when the source sentence is short and structurally simple, but as the source gets longer and the key information is spread across several positions, the fixed-length hidden state becomes an information bottleneck.

    Attention was introduced precisely to break that bottleneck. Instead of relying on one fixed summary, the decoder looks back at multiple positions of the source sequence at every step and retrieves information on demand. The idea was later transferred in full and scaled up inside the Transformer architecture, where it became one of the foundational components of large language models.

    3. Why Inference Memory Gets Tight

    During autoregressive generation, producing each new token requires the Keys and Values of the current token and all previous tokens. To avoid recomputation, engineering practice relies on the KV cache, which stores the Keys and Values of historical tokens. This clearly improves decoding throughput, but it creates a new problem: KV cache memory grows with sequence length, batch size, and the number of layers.

    With MHA, every attention head maintains its own Keys and Values. The more heads, the larger the KV cache. In long-context, high-concurrency online serving, the KV cache often becomes the memory bottleneck before the model parameters do.

    KV cache size can be estimated roughly as:

    1. KV Cache ≈ 2 × batch × seq_len × layers × kv_heads × head_dim × dtype_bytes

    Here, the factor of 2 accounts for caching both Keys and Values; kv_heads is the number of key/value heads that participate in caching; head_dim is the dimension of each head; and dtype_bytes depends on precision — bf16 or fp16 typically means 2 bytes.

    For example, a model with 32 query heads, 8 KV heads, and a per-layer head_dim of 128, with batch=1, seq_len=8192, layers=32, and bf16 precision, ends up with a KV cache on the order of roughly 1 GiB across all 32 layers. Switch to MHA with 32 KV heads and the footprint grows to about 4×; switch to MQA with a single KV head and it shrinks to roughly 1/32. In large-scale inference serving, that difference is decisive.

    One of the core goals of modern attention variants, therefore, is to compress the KV cache without significantly damaging generation quality.

    4. Compressing Memory: MHA, MQA, GQA, Sliding Window, and Sparse Attention

    Two main families of ideas address KV cache optimization. The first is to reduce the number of key/value heads, which is what MQA and GQA do. The second is to limit how much each token attends to, which is what sliding-window and more general sparse attention do.

    Approach KV cache size Time complexity Quality risk Typical use case
    MHA Largest; every query head has its own K/V Usually O(T²) Lowest Plenty of memory, quality ceiling matters most
    GQA Moderate; several query heads share one K/V set Usually O(T²) Low High concurrency, long context, general online serving
    MQA Smallest; all query heads share one K/V set Usually O(T²) May drop slightly; must be measured Extremely memory- and latency-sensitive
    Sliding window Keeps only nearby history Near-linear within the local window Long-range information must be covered by global tokens or by propagation through depth Very long documents, near-linear complexity requirements
    Sparse attention Depends on the sparse pattern Usually below full attention A poorly designed pattern can lose key information Very long sequences, task-specific tuning

    1. MQA: One K/V Set Serving All Query Heads

    Multi-query attention (MQA) takes an aggressive approach: all query heads share the same Keys and Values. No matter how many query heads the model has, only one K/V set is stored.

    This compresses the KV cache to a fraction of its original size. With 32 query heads, for instance, MQA can in theory reduce the cache to 1/32. The benefits are significant: lower memory-bandwidth pressure during decoding, higher throughput, and easier long-context deployment.

    MQA also has a cost. All query heads are forced to share one set of context key/value information, which compresses the expressive space. Whether that causes a noticeable quality drop depends on the task, the model scale, and how well the model was adapted during training, so it cannot be generalized. For tasks such as code completion and short-text generation, MQA often still performs well; for complex reasoning and long-document question answering, thorough evaluation is recommended.

    2. GQA: Tuning the Sharing Granularity Between MHA and MQA

    Grouped-query attention (GQA) is the more common compromise. It divides the query heads into several groups, with one K/V set shared inside each group.

    If the number of groups equals the number of query heads, GQA degenerates into MHA; if the number of groups is 1, it is equivalent to MQA. GQA therefore provides a tunable knob: engineers can pick a point between “smaller cache” and “more stable quality.”

    For example, some mainstream open-source models pair 32 query heads with 8 KV heads, reducing the theoretical KV cache size to 1/4 of the original; others use 64 query heads with 8 KV heads, a theoretical reduction to 1/8. Compared with MHA, GQA keeps strong representational ability while substantially lowering inference-cache pressure, which is why it is very common in today’s mainstream open-weight models.

    The simplified GQA/MQA sketch below shows the core change: the output head count of the K and V projections goes from n_heads to n_kv_heads. When n_kv_heads=1, it is MQA.

    1. class GroupedQueryAttention(nn.Module):
    2. def __init__(self, d_model, n_heads, n_kv_heads):
    3. super().__init__()
    4. assert n_heads % n_kv_heads == 0
    5. self.n_heads = n_heads
    6. self.n_kv_heads = n_kv_heads
    7. self.n_rep = n_heads // n_kv_heads
    8. self.d_head = d_model // n_heads
    9. self.q_proj = nn.Linear(d_model, d_model)
    10. self.k_proj = nn.Linear(d_model, n_kv_heads * self.d_head)
    11. self.v_proj = nn.Linear(d_model, n_kv_heads * self.d_head)
    12. self.o_proj = nn.Linear(d_model, d_model)
    13. def forward(self, x):
    14. B, T, D = x.shape
    15. q = self.q_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2)
    16. k = self.k_proj(x).view(B, T, self.n_kv_heads, self.d_head).transpose(1, 2)
    17. v = self.v_proj(x).view(B, T, self.n_kv_heads, self.d_head).transpose(1, 2)
    18. # Expand the shared K/V to the corresponding query head groups
    19. k = k.repeat_interleave(self.n_rep, dim=1)
    20. v = v.repeat_interleave(self.n_rep, dim=1)
    21. attn = (q @ k.transpose(-2, -1)) / (self.d_head ** 0.5)
    22. causal_mask = torch.tril(
    23. torch.ones(T, T, device=x.device, dtype=attn.dtype)
    24. ).view(1, 1, T, T)
    25. attn = attn.masked_fill(causal_mask == 0, float("-inf"))
    26. attn = attn.softmax(dim=-1)
    27. out = (attn @ v).transpose(1, 2).reshape(B, T, D)
    28. return self.o_proj(out)

    In practice, GQA tuning comes down to choosing a sensible number of KV heads. Fewer is not automatically better: too few KV heads may cause quality regressions, while too many makes the cache savings marginal. A common approach is to start evaluating with 8 KV heads, then try 4, 2, and 1 step by step while watching downstream task metrics, perplexity, long-text retrieval ability, and inference throughput.

    3. FlashAttention: Same Cache Structure, Better Memory Access and Compute Utilization

    FlashAttention is a family of IO-aware exact attention implementations. Its core is neither reducing the number of KV heads nor changing the mathematics of attention; it uses tiled computation and reduces how often intermediate matrices are read from and written to memory, lowering the memory and bandwidth cost of attention on long sequences.

    In a conventional implementation, computing attention scores typically materializes an attention matrix of size T×T and writes it to memory. When the sequence is long, that intermediate result consumes a great deal of memory bandwidth. FlashAttention uses tiling and online softmax updates to avoid explicitly spilling large intermediate matrices, which makes it very useful for long-context training and inference.

    It is worth stressing that FlashAttention and MQA/GQA are not substitutes; they can be combined. MQA and GQA mainly reduce the number of heads in the KV cache, while FlashAttention mainly improves the memory-access efficiency of the attention computation itself. A model that uses GQA and also relies on a FlashAttention implementation can gain both cache compression and compute efficiency.

    4. Sliding Window Attention: Trading a Local Receptive Field for Near-Linear Scaling

    Sliding window attention does not reduce the number of KV heads; it limits what each token can attend to. Every token attends only to neighboring tokens within a fixed window instead of the entire history.

    There are two benefits. First, the per-layer computational complexity can drop from the quadratic cost of global attention to something near-linear within the local window. Second, the KV cache only needs to retain the history near the window, which lowers cache usage.

    Sliding window also has a clear limitation: with only a local window, distant information cannot be seen directly by the current token. In engineering practice this is usually addressed by stacking many layers so information propagates hop by hop across layers, and by adding a small number of global tokens that can see the full sequence across window boundaries. It should be stated plainly that sliding window attention is itself a form of local sparse attention. It is a basic instance of sparse attention, not a fully independent alternative sitting alongside it.

    5. Sparse Attention: Combining Local, Global, and Random Patterns

    Sparse attention covers a broader space. It does not require the full attention matrix to be computed; instead, it designs sparse patterns so that only a small number of key positions are attended to.

    Common ideas include:

    • Block sparsity: split the sequence into blocks and compute attention between only some of the blocks.
    • Local plus global: keep a local window while designating a few global tokens, so key information can propagate across the whole sequence.
    • Random plus window: add random connections on top of a local window to improve graph-like expressiveness.

    Longformer and BigBird are representative examples of this line of work. Longformer generally combines a local sliding window with a small number of global tokens, while BigBird additionally introduces random sparse connections to approach the theoretical properties of full attention with better graph-like expressiveness. Such methods suit very long sequence scenarios — long-document question answering, codebase understanding, very long context retrieval, and so on. However, sparse attention usually requires customized training or inference support, making its engineering complexity higher than that of GQA and sliding window.

    5. How Position Encoding Works With Long Context

    Attention itself is insensitive to order, so position encoding is required to inject order information. Common choices include sinusoidal position encoding, learned position embeddings, and rotary position embeddings (RoPE). For long context, the extrapolation ability of the position encoding is critical. Many models use position interpolation, length-extension training, or dynamic RoPE scaling to keep behavior stable at longer context lengths.

    Two dimensions need to be kept separate:

    • Attention structure variants decide how much information each token sees and how large the KV cache is.
    • Position encoding schemes decide how long-distance positional relationships are expressed.

    These are orthogonal optimization dimensions and must be designed together. For example, GQA can reduce the KV cache, but long-context quality will still degrade if the position encoding cannot extrapolate to the target length; sliding window can lower complexity, but long-range dependencies may be lost if global tokens are missing or the position encoding is unstable.

    6. Engineering Selection and Tuning: Choosing Groups, Windows, and Fallbacks

    The following order works well in practice.

    First, if memory is plentiful and the quality ceiling matters most, prefer MHA. MHA offers a complete expressive space at the cost of the largest KV cache, which suits offline training, quality-first scenarios, and private deployments with ample memory.

    Second, for high-concurrency online serving, long-context generation, or memory-constrained deployments, GQA is usually the robust choice that balances quality and efficiency. Start by testing 8 KV heads, then adjust down to 4, 2, or 1 based on memory usage, throughput, latency, and quality metrics.

    Third, if inference latency and memory are extremely sensitive and the task does not demand much contextual expressiveness, MQA is worth considering — for example short-text continuation, simple dialogue, or code completion. MQA must still go through task-level evaluation before launch; it should not be adopted on cache-compression benefits alone.

    Fourth, if you are handling very long documents or very long conversations, or need close to linear complexity, consider sliding window. Window sizes commonly start at 512, 1024, 2048, or 4096 for testing. A larger window preserves more complete local information but raises cache and compute cost; a smaller window scales better but makes long-range information depend more on global tokens or propagation through depth.

    Fifth, if the task needs million-token or extreme long context, consider sparse attention. Here the focus is not simply tuning the window size, but designing a combination of global tokens, local windows, random blocks, or hierarchical memory, and validating it on tasks such as long-document retrieval, summarization, and question answering.

    During tuning, it is worth setting up a fallback evaluation framework:

    • Quality metrics: perplexity, downstream task accuracy, long-text retrieval hit rate, summarization consistency.
    • Efficiency metrics: time to first token, decoding throughput, peak memory, KV cache occupancy.
    • Stability metrics: whether long context gets truncated, whether window boundaries cause jitter, whether different concurrency levels trigger out-of-memory errors.

    If replacing MHA with GQA hurts quality, increase kv_heads somewhat; if sliding window loses long-range information, add global tokens, widen the window, or move to a hybrid “sliding window + global memory” scheme.

    7. Common Mistakes and Things to Watch Out For

    A few mistakes come up repeatedly when implementing attention variants.

    First, forgetting the causal mask. MHA, MQA, and GQA must all prevent the current token from attending to future tokens during autoregressive generation. If the code only computes a softmax without applying the causal mask, model behavior diverges from the training objective.

    Second, assuming sliding window and sparse attention are unrelated. In fact, sliding window is itself a typical form of local sparse attention. The only difference is whether the sparse pattern is a fixed local window or a combination of local, global, and random connections.

    Third, focusing only on parameter count and ignoring the KV cache. The inference bottleneck of large models often lies not in the parameter weights themselves but in the key/value cache over long sequences. When evaluating a model, look at the number of layers, KV head count, head_dim, sequence length, and batch size together.

    Fourth, setting up GQA groups unreasonably. Fewer KV heads is not better by default. With too few kv_heads, the model may regress on complex reasoning, long-range dependency, and knowledge-association tasks. The optimal group count must be determined empirically.

    Fifth, conflating FlashAttention with MQA/GQA. FlashAttention mainly optimizes the memory-access efficiency of the attention computation, while MQA/GQA mainly optimize the KV cache structure. The two can be stacked, but neither replaces the other.

    Conclusion

    From MHA to GQA and MQA, and on to sliding window and sparse attention, the evolution of attention is essentially a continuing balance between expressiveness, compute, and memory. MHA provides the most complete expressive space, GQA has become the mainstream choice that balances quality and efficiency, MQA still has value under extreme memory constraints, and sliding window and sparse attention target very long sequences and near-linear complexity. Meanwhile, IO-aware implementations such as FlashAttention provide important system-level optimization for long-context training and inference.

    Understanding the motivation and the cost behind each variant matters more than chasing whichever structure is currently called “strongest.” In real engineering, the choice should be made against sequence length, concurrency, latency requirements, memory budget, and quality goals, then continuously tuned through task-level evaluation. Mastering this set of trade-offs is what makes it possible to build large-model applications that are efficient, stable, and scalable.