MHA, GQA, MQA, and Sliding Window Attention: How to Choose

    Compare the design, compute costs, KV cache requirements, and trade-offs of MHA, MQA, GQA, and sliding window attention. This guide explains how each approach works and provides a practical framework for choosing attention architectures based on inference efficiency, context length, and long-range retrieval requirements.

    Large language model architectures evolve rapidly, but attention remains one of their central components. As context windows grow, inference becomes increasingly expensive, driving the adoption of different attention designs.

    Starting with multi-head attention (MHA), this article explains the main variants, their computational and memory costs, and where they fit. The goal is a practical framework for choosing between them.

    1. The Foundation: Self-Attention

    Self-attention allows each token in a sequence to examine other visible tokens, assign weights to them, and build a new representation that incorporates context. The calculation has three steps:

    1. Project the input into query (Q), key (K), and value (V) vectors.
    2. Compute query–key dot products, scale the scores, and normalize them with softmax.
    3. Use the normalized weights to calculate a weighted sum of the value vectors.

    The example below includes tensor shapes, parameter initialization, and causal mask handling. It runs on the CPU using the default float32 precision. To run it on a GPU, move the tensors to the appropriate device.

    1. import torch
    2. import torch.nn.functional as F
    3. def causal_self_attention(x, W_q, W_k, W_v):
    4. """
    5. x: [batch, seq_len, d_model]
    6. W_q, W_k, W_v: [d_model, d_head]
    7. Returns: [batch, seq_len, d_head]
    8. """
    9. Q = x @ W_q # [B, L, d_head]
    10. K = x @ W_k
    11. V = x @ W_v
    12. d_head = Q.shape[-1]
    13. scores = Q @ K.transpose(-2, -1) / d_head ** 0.5 # [B, L, L]
    14. L = x.shape[1]
    15. # Causal mask: True above the diagonal blocks attention to future positions.
    16. # Shape [L, L] broadcasts to [B, L, L].
    17. mask = torch.triu(torch.ones(L, L, dtype=torch.bool, device=x.device), diagonal=1)
    18. scores = scores.masked_fill(mask, float("-inf"))
    19. weights = F.softmax(scores, dim=-1)
    20. return weights @ V
    21. if __name__ == "__main__":
    22. torch.manual_seed(0)
    23. B, L, d_model, d_head = 2, 5, 16, 8
    24. x = torch.randn(B, L, d_model)
    25. # Scale initialization by 1/sqrt(d_model) to avoid overly large initial scores.
    26. W_q, W_k, W_v = (torch.randn(d_model, d_head) * d_model ** -0.5 for _ in range(3))
    27. out = causal_self_attention(x, W_q, W_k, W_v)
    28. print(out.shape) # torch.Size([2, 5, 8])

    The mathematics is straightforward, but the implementation faces two engineering bottlenecks. First, the attention score matrix grows quadratically with sequence length, L. Second, inference requires caching the keys and values of previous tokens, so KV cache memory grows linearly with sequence length.

    Most of the variants discussed below target one or both of these bottlenecks.

    2. Multi-Head Attention: The Standard Design

    Multi-head attention runs several attention heads in parallel, each with its own Q, K, and V projections. Different heads can capture dependencies in different representation subspaces, such as syntactic relationships, semantic associations, or positional patterns. Their outputs are concatenated and projected again to produce a richer representation.

    MHA is expressive and structurally straightforward, making it a useful starting point for understanding and implementing language models. Many classic open-weight models use it.

    Its cost is especially apparent during inference. In MHA, the number of KV heads equals the number of query heads, so every head stores its own keys and values. KV cache storage per token can be estimated as:

    KV cache bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

    The factor of 2 accounts for storing both K and V.

    For a hypothetical model with 32 layers, 32 KV heads, a head dimension of 128, and fp16 storage at 2 bytes per element, the cache requires approximately 512 KiB per token. At tens of thousands of tokens, the cache can quickly exhaust GPU memory. In long-context workloads, this overhead often becomes a major constraint on throughput.

    3. Why Attention Variants Are Needed

    Current optimizations follow three main directions:

    • Compress the KV cache: Share key and value heads across multiple query heads. MQA and GQA are the main examples.
    • Restrict the attention range: Let each token attend only within a local window. Sliding window attention reduces attention computation from quadratic to linear in sequence length when the window size is fixed.
    • Use sparse or hybrid designs: Interleave sliding window layers with global attention layers to balance local efficiency and global information flow.

    All three address the same trade-off: how to balance limited memory and compute resources against the need to access the full context.

    Attention originally emerged to address a related information bottleneck. In early encoder–decoder RNNs for machine translation, the encoder compressed an entire sentence into a limited hidden-state representation, and the decoder generated a translation from that constrained summary. Translation quality could suffer when important information elsewhere in the input was not preserved. Attention allowed the decoder to revisit the input sequence, reducing this bottleneck.

    4. Grouped-Query Attention and Multi-Query Attention

    Multi-Query Attention: Maximum KV Sharing

    Multi-query attention (MQA) is the most direct KV cache compression approach. All query heads share a single key head and a single value head.

    With N query heads, the KV cache becomes 1/N of the MHA cache, assuming the other dimensions remain unchanged. More aggressive sharing saves more memory, but it can also increase the risk of quality degradation.

    Grouped-Query Attention: A Middle Ground

    Grouped-query attention (GQA) sits between MHA and MQA. It divides N query heads into G groups, with each group sharing one key head and one value head. The KV cache is therefore G/N of the MHA cache.

    The endpoints are:

    • G = N: GQA becomes MHA.
    • G = 1: GQA becomes MQA.

    The group count is a control knob for the quality–efficiency trade-off. Fewer groups reduce cache requirements but can increase quality risk. The best count depends on the model and task, so it must be validated on relevant evaluation data rather than copied directly from another configuration. Many newer models use GQA.

    5. Sliding Window Attention

    Sliding window attention restricts each token to a fixed-size window of preceding context. With window size W and sequence length L, attention computation per layer and per head is O(L × W), which is linear in sequence length for a fixed W.

    During inference, a rolling KV cache can retain only the most recent W positions in each layer. The cache then has a fixed upper bound rather than growing with the entire sequence.

    It is important to distinguish computation from storage:

    • Attention computation: O(L × W) per layer and per head.
    • Cached positions: O(W) per layer.
    • Total cache memory: Also depends on the number of layers, KV heads, head dimension, and batch size.

    During training, positions outside the window are also excluded from attention. Whether this produces meaningful speedups depends on the efficiency of the underlying kernels.

    Information outside the window must propagate through successive layers. At layer k, the effective receptive field is approximately k × W, so stacking layers expands the range of information that can influence a token.

    However, this propagation is lossy. Exact details outside the window—such as an identifier in a long document or the verbatim wording of a sentence—may not survive intact. Pure sliding window models therefore carry a significant risk of information loss on tasks requiring precise retrieval or copying from long contexts.

    In practice, sliding window layers are often combined with global attention layers. The appropriate ratio must be determined experimentally, with long-range retrieval treated as a priority evaluation task.

    6. Comparing the Four Approaches

    The table below summarizes relative costs for a single layer and a single sequence. Cache ratios compare storage per cached token; computation describes attention over a sequence of length L. The figures are not specific to any model and do not include training details.

    Approach Number of KV heads KV cache relative to MHA Attention computation Quality trade-off Typical use cases
    MHA N, equal to query heads 1 O(L²) Reference baseline; generally strong quality Learning, small models, workloads without tight cache constraints
    MQA 1 1/N O(L²) Potentially noticeable degradation Extremely memory-constrained inference where quality loss is acceptable
    GQA G, where 1 < G < N G/N O(L²) Often close to MHA Inference requiring a balance between quality and memory
    Sliding window Can be combined with MHA or GQA Bounded to W cached positions per layer O(L × W) Risk of losing long-range information; often combined with global layers Very long contexts dominated by local dependencies

    GQA and MQA reduce KV cache storage, but they do not by themselves remove the quadratic dependence of full-sequence attention on context length. Sliding window attention addresses the attention range and can be combined with either head-sharing design.

    7. Selection Guidelines and Practical Considerations

    1. For inference-focused workloads that need lower memory use, start with GQA. Choose the number of groups through quality evaluation.

    2. For very long contexts under tight memory limits, evaluate sliding window or hybrid architectures. KV cache quantization is another consideration, but it introduces additional error and also requires evaluation.

    3. For exact retrieval or verbatim copying from long documents, avoid relying solely on sliding window attention. Retain global attention layers.

    4. When learning or implementing attention from scratch, master MHA and causal masking first. Then examine precisely what each variant changes relative to MHA.

    5. Evaluate more than perplexity. Include long-text retrieval, code completion, and other tasks that depend on long-range information. Cache-sharing approaches can affect these tasks in ways that warrant separate testing.

    Conclusion

    Attention design is an ongoing trade-off between representational capacity and engineering efficiency. Early attention addressed the information bottleneck in RNNs. MHA established the standard multi-head design. GQA and sliding window attention target practical inference constraints through different mechanisms.

    Understanding each design’s motivation, cost, and limitations is more useful than memorizing its structure. When examining a new attention architecture, ask three questions:

    • Which part of the cache does it compress?
    • Which positions can no longer attend to one another?
    • Which tasks need additional quality validation?

    These questions provide a practical starting point for understanding most attention variants and deciding whether they fit a workload.