LLM Attention Variants Explained: MHA, MQA, GQA, Sliding Window, Gated Attention, and Low-Rank KV Compression
This article walks through the attention variants that dominate modern open-weight LLM architectures, using the same mental map for all of them: self-attention and multi-head attention as the baseline, then grouped-query attention (GQA), multi-query attention (MQA), sliding window attention (SWA), gated attention, cross-layer KV sharing, low-rank latent compression, linear and hybrid designs, and attention sinks. It explains why the KV cache is the real bottleneck in autoregressive decoding, how to estimate KV cache size with a simple formula, what each variant costs and buys, and how to choose between them. It also covers practical engineering notes — converting an existing MHA model to GQA, paged cache management, continuous batching, prefix reuse, cache quantization, length-extrapolation testing — plus a task-oriented evaluation matrix and four common misconceptions about attention.
1. Introduction: Why Attention Variants Deserve Their Own Article
Not long ago, a visual collection called the “LLM Architecture Gallery” took off in the AI community. It drew architecture diagrams for dozens of well-known open-weight models in a consistent style, paired each one with a model card, and made side-by-side comparison easy. A prominent AI educator known for a “build a large model from scratch” course called it a “treasure gallery.” The authors then turned the collection into physical posters, using everyday objects such as coins and keys as size references — and the posters sold very well.
That collection also spawned a companion piece: a visual guide to attention variants in modern LLMs. Its author reviewed the attention variants proposed in recent years and widely adopted in open-weight architectures, hoping the diagrams would work both as a reference and as lightweight learning material.
The reason these two resources caught on is not hard to understand:
- A shared frame of reference. Diagrams in different papers use different styles and different terminology. One consistently drawn architecture diagram dramatically lowers the barrier to comparison.
- A view of the evolution. You can understand a single model’s structure by reading its code, but to understand why it was designed that way and what changed relative to the previous generation, you need several models side by side.
- Attention is where the differences concentrate. Differences in positional encoding, activation functions, and normalization mostly show up as local tweaks. The shape of attention, by contrast, directly determines memory footprint, decode speed, and the ceiling on context length — it is where architectural generations differ most.
A lot of people’s knowledge of attention still stops at what is taught in class: “scaled dot product” and “concatenate the heads.” From here, this article follows a single thread — self-attention → multi-head → grouped-query/multi-query → sparse windows → gating and compression — puts the mainstream variants on one map, and offers practical guidance you can use directly when making design or deployment choices.
2. The Baseline: What Self-Attention and Multi-Head Attention Actually Compute
2.1 Self-attention in three steps
Self-attention lets every token in a sequence “see” the other visible tokens and decide how much attention to give each one. You can break it into three steps:
- Score: take the dot product between the current token’s “query” and other tokens’ “keys” to get relevance scores.
- Normalize: divide by the square root of the dimension to keep the numbers stable, then apply softmax to get an attention distribution whose weights sum to 1.
- Weighted sum: use those weights to sum the “values” of all tokens, producing a new representation that has absorbed the context.
For an autoregressive language model, scoring also requires a causal mask: position t may only attend to tokens at positions ≤ t. This prevents the model from “peeking” at the answer during training, and it guarantees that at inference time you can cache the keys and values of past tokens and generate text step by step.
2.2 Illustrative code: from single-head to multi-head
The following pseudocode shows the core computation (the batch dimension is omitted for readability):
def self_attention(X, Wq, Wk, Wv, Wo, causal=True):Q = X @ Wq # (L, D) queriesK = X @ Wk # (L, D) keysV = X @ Wv # (L, D) values# Scaled dot-product scores; dividing by sqrt(D) controls the variance# growth of the dot product as the dimension increasesscores = Q @ K.T / sqrt(D) # (L, L)if causal:# Set the upper triangle (future positions) to -inf so softmax yields 0scores = scores + causal_mask(L) # (L, L)A = softmax(scores, dim=-1) # each row sums to 1return (A @ V) @ Wo # (L, D) output projectiondef multi_head_attention(X, Wq, Wk, Wv, Wo, h):"""Project the input, split it into h heads computed in parallel,then concatenate back into a single representation."""D = X.shape[-1] # model dimensiondq = D // h # dimension per head# A single projection followed by a reshape is equivalent to h# independent smaller projection matricesQ = (X @ Wq).view(L, h, dq).transpose(0, 1) # (h, L, dq)K = (X @ Wk).view(L, h, dq).transpose(0, 1)V = (X @ Wv).view(L, h, dq).transpose(0, 1)Y = softmax(Q @ K.transpose(-1, -2) / sqrt(dq), dim=-1) @ V # (h, L, dq)return Y.transpose(0, 1).reshape(L, D) @ Wo
The reason for using multiple heads is that a single softmax distribution can only express one kind of “attention pattern.” Different heads can learn different relational patterns: some attend to adjacent words, some to syntactic dependencies, some are responsible for reaching back across sentences. That is the original motivation of multi-head attention (MHA). It is the default configuration in a standard Transformer decoder, and the architecture gallery mentioned above uses it as the baseline for comparing model generations.
One intuitive way to think about it: each head is like asking the input a question. All heads ask in parallel and answer independently, and the output projection finally integrates the answers into one unified representation.
2.3 Two costs that often get overlooked
For a sequence of length L, the full attention matrix is L × L. This means:
- Compute grows quadratically with sequence length.
- Memory also grows quadratically during training, because backpropagation needs to store the attention weights.
More importantly, during autoregressive inference, generating each new token requires the keys and values of all historical tokens. To avoid recomputing them, engineering practice maintains a KV cache. You can think of it as filing: the “dossier” computed at every past step (the K and V of each token) is stored away, and a new token only has to prepare its own dossier and then compare it against the archive.
The total KV cache that must be held within the context window is:
KV cache = num_layers × 2 (K and V) × num_kv_heads × head_dim × seq_len × batch × bytes_per_element
Take 32 layers, hidden dimension 4096, 32 heads, FP16 precision, and a single request with a 32K context:
- Standard multi-head attention: the number of KV heads equals the number of query heads — 32 × 2 × 32 × 128 × 32768 × 2 ≈ 16 GiB of memory.
- Grouped-query attention with 8 groups: down to 4 GiB.
- Multi-query attention: down further to 0.5 GiB.
None of this includes the model weights themselves. This is the root motivation behind most of the variants discussed below: compress the KV cache without noticeably hurting quality.
3. Four Lines of Evolution: A Map of Attention Variants
To make things easier to remember, the mainstream variants can be grouped into four lines:
- Compress the KV cache: let multiple query heads share the same keys and values — multi-query attention (MQA), grouped-query attention (GQA), cross-layer KV sharing, low-rank compression in a latent space.
- Sparse windows: stop letting every token see the whole sequence and attend only to a local window — sliding window attention (SWA), and hybrid designs that alternate local and global layers.
- Restructure attention: change the computational form or the output path — gated attention, linear attention, and hybrid architectures combining SSMs with linear attention.
- Cross-sequence: the decoder reads the encoder’s output through cross-attention — typical of encoder-decoder designs for translation and summarization, and of early multimodal fusion.
The table below is a quick reference for the mainstream variants; each one is covered in detail later.
| Variant | Core idea | Primary goal | Typical cost |
|---|---|---|---|
| Multi-head attention (MHA) | Each query head gets its own K/V | Expressiveness baseline | Largest KV cache |
| Multi-query attention (MQA) | All query heads share one set of K/V | Drastically compress the KV cache | Lower expressiveness, potentially unstable training |
| Grouped-query attention (GQA) | K/V split into g groups, shared within a group | Balance quality and cost | Quality degrades when g is too small |
| Sliding window attention (SWA) | Attend only to the most recent W tokens | Less compute, naturally supports long streams | Requires global layers to compensate |
| Gated attention | Elementwise gating on head outputs | Training stability, better extrapolation | Small amount of extra parameters and compute |
| Cross-layer KV sharing | Adjacent layers reuse the same K/V | Compress KV, reduce memory bandwidth | Less representational independence across layers |
| Low-rank latent compression | Cache K/V as a low-dimensional latent vector | More aggressive KV compression | Extra decompression projection at decode time |
| Cross-attention | Queries from the decoder, K/V from the encoder | Cross-sequence / cross-modal alignment | Two sets of sequence representations to maintain |
4. Historical Context: Why Attention Was Invented at All
To understand these variants, it helps to go back to the era when attention first appeared. Its immediate backdrop was the encoder-decoder recurrent neural network (RNN) used for machine translation. In such a system:
- The encoder reads the source-language sentence token by token, continuously writing information into a hidden state. In the simplest version, only the last hidden state is kept, as a summary of the whole sentence.
- The decoder conditions on that “summary” and generates the translation word by word.
When sentences are short and structurally simple, this mechanism is sufficient. The problem is that the hidden state has limited capacity. Once the information needed to translate a given word sits far away in the input sentence, or once several fragments must be consulted at the same time, the fixed summary becomes an obvious information bottleneck. The decoder is forced to compress the entire sentence into a fixed-length vector, details are lost in the compression, and translation quality on long sentences drops accordingly.
Attention was invented precisely to break that bottleneck: it lets the decoder, at every generation step, look directly back at the encoder’s hidden states at each input position and dynamically allocate attention weights according to what it currently needs. The information path changed from “compress first, then transmit” to “read on demand,” and translation quality improved markedly. The idea was later transferred to sequence labeling, speech recognition, image captioning, and eventually became the core component of the Transformer.
This history also explains what every variant that follows is trading off: attention fundamentally exchanges direct read access for expressiveness, and the price is expensive compute and storage. Most later variants are simply rebalancing that account along a different axis.
5. A Closer Look at the Mainstream Attention Variants
5.1 Grouped-query attention (GQA): the best engineering trade-off
Structural sketch (MHA → MQA → GQA):
MHA: Q Q Q Q | Q Q Q Q | Q Q Q Q | Q Q Q QK K K K | K K K K | K K K K | K K K K <- 8 query heads, 8 sets of K/VV V V V | V V V V | V V V V | V V V VMQA: Q Q Q Q | Q Q Q Q | Q Q Q Q | Q Q Q QK K K K <- 8 query heads share 1 set of K/VV V V VGQA: Q Q | Q Q | Q Q | Q QK K | K K | K K | K K <- 8 query heads share 4 sets of K/VV V | V V | V V | V V
Variant definition: multi-query attention and grouped-query attention are direct relaxations of the assumption that “every head must have its own K/V.” MQA goes to the extreme with a single set of K/V; GQA splits the difference with g groups, where 1 < g < h. Query head i reads the K/V of group ⌊i·g/h⌋ (simplified for presentation; real implementations partition into contiguous groups).
Illustrative code for the grouped version:
def grouped_query_attention(X, Wq, Wk, Wv, Wo, h, g):"""h query heads share g sets of keys/values; h must be divisible by g"""L, D = X.shapedq = D // h # query head dimensiondkv = D // g # key/value head dimensionQ = (X @ Wq).view(L, h, dq).transpose(0, 1) # (h, L, dq)K = (X @ Wk).view(L, g, dkv).transpose(0, 1) # (g, L, dkv)V = (X @ Wv).view(L, g, dkv).transpose(0, 1)K = K.repeat_interleave(h // g, dim=0) # replicate each group h/g times to align with query headsV = V.repeat_interleave(h // g, dim=0)Y = softmax(Q @ K.transpose(-1, -2) / sqrt(dq), dim=-1) @ Vreturn Y.transpose(0, 1).reshape(L, D) @ Wo
Real inference kernels do not actually replicate the K/V tensors; they use an index mapping so that multiple query heads read the same cache.
Benefits and costs:
- Benefit: the main bottleneck during decoding is usually memory bandwidth, not compute. Every generated token requires reading all weights and the entire historical KV cache out of memory. If the KV cache shrinks by a factor of N, that portion of the reads shrinks by roughly the same factor, which typically yields a noticeable throughput improvement; memory footprint drops as well.
- Typical settings: the number of groups is commonly between 2 and 8, which is equivalent to reducing each query head’s K/V dimension to 1/2 to 1/8 of the original — a common middle ground between “preserve quality” and “compress the cache.”
- Cost: with too few groups, the model’s ability to distinguish fine-grained relationships degrades, with the exact impact depending on the task and the training recipe.
GQA has become one of the mainstream choices in open-source models in recent years, mainly because it balances quality and cost well.
5.2 Sliding window attention (SWA): trading locality for length
Structural sketch (window size 4, with causal masking):
t0 t1 t2 t3 t4 t5 t6 t7t0 Xt1 X Xt2 X X Xt3 X X X Xt4 X X X Xt5 X X X Xt6 X X X Xt7 X X X X
Variant definition: each token attends only to the W tokens before it. The attention matrix goes from dense to banded and sparse, and a single layer’s compute and cache cost grows linearly with sequence length instead of quadratically.
Why it works: language is strongly local, and dependencies between adjacent words are the densest. At the same time, attention during autoregressive decoding tends to concentrate on recent content. Models also often run in streaming mode — speech recognition that outputs sentence by sentence, live captions, ongoing conversations — where input keeps being appended and the sequence can in principle grow without bound.
How to avoid losing global information: if every layer only looks locally, distant information gets diluted layer by layer. The theoretical receptive field can extend to L layers × W tokens, but transmission efficiency decays with distance. Two common approaches:
- Global tokens: introduce a small number of special tokens that every position can always attend to, acting as information “relay stations.”
- Layer mixing: most layers use local windows, while a few layers use full attention or a significantly larger window and take on the job of long-range aggregation.
Trade-offs to watch: the smaller the window, the cheaper the compute, but cross-window dependencies become harder to model. Window size usually has to be chosen jointly with the number of layers and the target context length, and validated with long-distance dependency evaluations (such as paragraph-level coreference and cross-document question answering).
5.3 Gated attention: a switch on the output side
Structural sketch:
+-- Query --> score / mask / softmax --> weighted V --+Input X ---------+-- Key / Value ---------------------------------------++-- Gate projection --> sigmoid --> elementwise mult ---+--> Output projection
Variant definition: in a conventional multi-head attention block, the output is a plain concatenation of the heads’ weighted values, and regardless of whether a given step actually needs context, the information enters the residual stream at full strength. Gated attention inserts an elementwise gate value (usually a sigmoid mapped to 0–1) before the head output or before the output projection, letting the model “decide for itself” at each step how much of the attended information to let through.
def gated_head_output(Y, X, Wg):"""Y: (L, D) attention output; the gate is derived from the current layer'sinput and controls the information flow element by element."""return Y * sigmoid(X @ Wg)
Benefits:
- Tokens that should not attract attention no longer indiscriminately pollute the residual stream, which eases some of the early-training instability.
- The model can handle “very long context” — a situation rarely seen during training — more smoothly. For example, when critical information appears extremely far outside the window, the attention distribution struggles to form an effective peak, and elementwise gating can suppress the injection of noisy output.
- The cost is only a small number of parameters and one elementwise multiplication.
5.4 Cross-layer KV sharing: compression along the depth dimension
Variant definition: the previous variants compress K/V across “different heads within the same layer.” Cross-layer KV sharing extends the scope to relationships between layers. A common approach: some layers compute their own K/V, while the remaining layers directly reuse the K/V of an earlier layer and keep only their own query projection.
Benefits:
- The KV cache shrinks in proportion to the number of layers that compute K/V independently.
- Memory reads during decoding drop accordingly.
Costs and caveats:
- Layers were originally responsible for processing features at different levels of abstraction; sharing K/V means those layers must work on the same key/value representation, so representational independence across layers decreases.
- The sharing granularity (how many layers share once, which layers keep independent K/V) has to be settled experimentally as a function of model size; the usual preference is to keep the bottom layers or otherwise critical layers independent.
5.5 Low-rank latent compression: storing K/V as a “zip file”
Structural sketch:
Standard: X --> K (d_k) --+X --> V (d_v) --+--> cache stores the full K and VLow-rank: X --↓ down-project--> c (d_c << d_k) --> only c is cached+->↑ up-project --> K+->↑ up-project --> V
Variant definition: when the key and value dimensions are large and the number of attention heads is also high, you can first compress each token’s representation into a latent vector c whose dimension d_c is clearly smaller, and cache only c. During the actual attention computation, up-projection then reconstructs K and V separately. Some designs apply similar treatment to the query as well, forming a “low-rank query + latent key/value” combination.
Benefits:
- The cached dimension drops from “num_heads × head_dim” to d_c, and when d_c is much smaller than the former, the compression ratio can even beat grouped-query attention.
- The reconstruction projections are small per-token matrix multiplications, so the extra compute overhead is limited.
- Because the compression is jointly optimized with the backbone during training, the reconstructed K/V retain task-relevant information better.
Costs:
- At decode time every historical token needs a reconstruction projection, which adds compute and depends on how well it fuses with the attention kernel.
- Combining it with positional encoding requires careful design; otherwise length extrapolation can suffer.
5.6 Other variants worth watching
- Multimodal cross-attention:
- Vision-language models often let text tokens act as queries and the visual tokens produced by an image encoder act as keys and values, using cross-attention for cross-modal alignment. Early approaches mostly inserted cross-attention at every layer.
- The later trend is to encode visual information into a small number of “visual prompt” tokens that are concatenated into the text sequence, so both modalities go through the same self-attention machinery.
- Comparing the two: the former gives finer-grained alignment and richer cross-modal interaction; the latter is simpler to implement and compatible with a text-only inference pipeline.
- Linear attention and hybrid architectures:
- Linear attention uses the associativity of matrix multiplication to change “score all tokens first, then weight” into “aggregate into a state first, then interact with the query,” reducing complexity to linear and maintaining a fixed-size recurrent state at inference time that does not grow with context length.
- It has developed into a class of linear sequence modeling alongside state space models. The common practical form is a few full-attention layers alternating with mostly linear layers: the former handle precise recall, the latter handle low-cost long-range information compression.
- Attention sinks:
- Autoregressive models exhibit a stable phenomenon: regardless of whether the content is relevant, the first few tokens (such as the sequence start token) always receive a great deal of attention, absorbing excess attention like a “trash can.”
- Truncating early context directly degrades perplexity noticeably. Streaming inference systems need to deliberately retain the first several tokens, or reserve dedicated “sink slots.”
- Refinements of gated and pooled attention:
- Beyond elementwise output gating, there are also approaches such as adding a learnable bias before the softmax and introducing inter-head gating. What they have in common is strengthening control over “whether to attend” and “how much to attend” without changing the basic form of attention.
6. Side-by-Side Comparison and Selection Guidance
6.1 Comparison dimensions
KV cache and memory: you can estimate quickly with the formula above. For 32 layers, hidden dimension 4096, and FP16, a single 32K-context request needs roughly the following KV cache (with slight variation depending on the number of query heads):
- MHA (32 K/V heads): ~16 GiB
- GQA (8 groups): ~4 GiB
- GQA (4 groups): ~2 GiB
- GQA (2 groups): ~1 GiB
- MQA (1 group): ~0.5 GiB
Extrapolating from this, if a single device has to hold both the model weights and dozens of concurrent long-context requests, optimizing the KV cache is close to mandatory.
- Long-context capability: determined jointly by window size, the proportion of global layers, positional encoding, and training length.
- Implementation complexity: grouped-query and sliding-window attention are well supported in mainstream inference frameworks; low-rank compression and cross-layer sharing may require custom kernels.
- Hardware friendliness: sharing K/V reduces memory bandwidth pressure, with a particularly clear throughput benefit in the decoding phase. Low-rank compression can more easily achieve high arithmetic intensity on some hardware.
6.2 Selection decision path
- Short context (≤ 4K), low concurrency: standard multi-head attention is enough — simple and stable.
- Long context, high concurrency: prefer grouped-query attention; 4 to 8 groups is a common starting point.
- Extreme compression needs (tight memory, very long context): consider cross-layer sharing, low-rank compression, or a linear hybrid architecture.
- Streaming scenarios: sliding window attention combined with a few global layers, while keeping an eye on the attention sink issue.
- Multimodal scenarios: decide explicitly between a “cross-attention” design and a “unified sequence” design, and assess the impact on the inference pipeline.
7. Engineering Implementation Notes
Architecture changes don’t have to start from scratch. “Upgrading” an existing standard multi-head model to grouped-query attention is a well-trodden path:
- Average the K/V projection weights of the heads inside each group to be shared, and use that as the initialization for the group’s K/V projections;
- Run a short period of continued training on a small amount of data to help the model adapt to the new sharing structure.
This gets you the KV cache compression benefit at relatively low cost, and suits cases where an existing model needs to reduce cost.
Co-optimize the cache and the kernels. Whether the benefits of cache compression actually materialize depends heavily on the implementation:
- Paged management: split the KV cache into fixed-size blocks allocated on demand, reducing memory fragmentation and improving concurrency;
- Continuous batching: new requests can join at any time and finished requests leave immediately, letting requests of different lengths share compute;
- Prefix reuse: the KV of common prefixes such as system prompts and document templates is computed once and reused many times;
- Numerical precision: quantizing the KV cache can further reduce bandwidth pressure, but the accuracy loss needs to be evaluated.
In cloud deployments, these capabilities are typically provided by a model inference service or a containerized service, and general-purpose cloud capabilities such as monitoring, alerting, and logging are used to observe throughput, latency, and memory utilization as a basis for capacity planning.
- Validate length extrapolation early. The context length used in training is not the model’s actual usable length. Before launch, evaluate the effective context with “long-document retrieval” style tests — plant target information inside a long document and check whether it can be recovered accurately — rather than looking only at the nominal window size.
- Build an evaluation matrix per task. Cover at least three categories of metrics:
- Quality: perplexity, long-document question answering, retrieval recall;
- Efficiency: time to first token, per-token generation speed, maximum concurrency per unit of memory;
- Stability: whether the training loss curve is smooth, whether there is any divergence.
8. Common Misconceptions
- Treating attention weights as an explanation. Attention weights reflect relevance, not causal contribution, and should not be used on their own as an interpretability conclusion.
- Looking at parameter count and ignoring the cache. Two models with similar parameter counts can have KV caches that differ by several times or even tens of times, and the cost gap for long-context serving widens accordingly.
- Assuming sliding windows necessarily hurt quality. As long as global layers or global tokens are configured well, local attention can still handle global understanding.
- Confusing window size with cache size. Sliding windows mean each layer only needs to cache the K/V within the window, which mainly affects memory usage during training and for short requests; in causal decoding, combined with a cache eviction policy, the cache cost of long generations can also stay bounded.
9. Conclusion
From the “summary bottleneck” of recurrent networks, to the parallel expressiveness of multi-head attention, to variants like grouped-query, sliding window, gated attention, and low-rank compression, the roughly decade-plus evolution of attention has revolved around the same tension: how much compute and storage to spend in exchange for how much context modeling ability. Understanding that through-line is more valuable than memorizing the details of any one model: when you get hold of a new architecture, you can start by asking four questions — are K/V shared, how large is the window, are there global layers, and is the output gated? The answers will roughly sketch where it sits in the “quality, cost, length” triangle.
Cloud model platforms — Baidu AI Cloud’s Qianfan model platform among them — let developers call a range of built-in mainstream model services to quickly test how different attention designs behave on real tasks, and also host their own models on the platform’s training and inference toolchain, using a unified evaluation and monitoring setup for quantitative comparison before deciding how to deploy in production.
