Attention Variants in Large Language Models: From MHA to Sparse Attention

    This article offers a comprehensive tour of attention variants used in modern large language models. It starts from the baseline of multi-head self-attention, breaks down why its KV cache becomes the dominant cost in long-context and high-concurrency inference, and then walks through the main families of variants across six design dimensions: KV sharing (MQA, GQA), latent compression (MLA), cross-layer reuse (CLA), field-of-view control (sliding window, attention sinks, native sparse attention), and vertical mixing of attention with recurrent or linear layers. It also covers orthogonal inference-time optimizations such as paged KV management, prefix reuse, and KV quantization, plus practical guidance on positional encoding, training stability, variant selection, and evaluation. By the end, readers will have a unified framework for choosing and combining attention designs rather than chasing a single new structure.

    1. Introduction: Why Attention Keeps Getting Rebuilt

    Since the Transformer first appeared, multi-head self-attention has remained the most central module in language models. But as demands for long context, high concurrency, and low-cost inference have grown, the costs of this module have started to concentrate. There are four main pressures.

    First, memory. Autoregressive decoding must cache historical keys and values, and as sequence length and concurrency increase, this cache rapidly consumes most of the available GPU memory. Second, memory bandwidth. Generating each token requires moving all the weights and historical cache from memory, which makes the decoding stage a classic memory-bandwidth-bound workload. Third, computation. The attention score matrix grows quadratically with sequence length, making long-sequence pre-training expensive. Fourth, extrapolation. Once the context exceeds the training length, model performance often drops sharply.

    The industry has gradually converged on a shared understanding: attention is not a fixed structure but a design space with trade-offs along six dimensions.

    • How query heads share keys and values: multi-head, multi-query, grouped-query.
    • What form keys and values are stored in: the original dimension, or a latent vector after low-rank compression.
    • Whether each layer maintains its own keys and values: independent within a layer, or shared across layers.
    • How far each query can see: global, within a window, or into selectively chosen blocks.
    • How positional information is injected and extrapolated: rotary position embeddings, linear biases, explicit encoding, or none.
    • How attention output is stabilized: whether to apply query-key normalization or score truncation.

    Around these six dimensions, a large number of attention variants have emerged over the past few years. This article first establishes a unified analysis framework, then breaks down the major variants one category at a time, and finally discusses engineering implementation, selection, and evaluation.

    2. Foundations: The Computation Flow and Cost of Self-Attention

    2.1 Computation flow

    Given an input X (shape seq × d_model), self-attention first uses three sets of learnable matrices to map each token to a query Q, a key K, and a value V. It then measures relevance with the dot product of queries and keys, normalizes with scaling and softmax to obtain attention weights, and finally computes a weighted sum over the values:

    1. Q = X · W_Q # shape seq × d_k
    2. K = X · W_K # shape seq × d_k
    3. V = X · W_V # shape seq × d_v
    4. Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k + M) · V

    Here M is the mask matrix. In decoding-style models it is a causal mask that lets position t attend only to positions 0 through t. Masked positions are filled with negative infinity, so after softmax their weights are exactly 0; this neither leaks future information nor produces gradients.

    The scaling factor √d_k suppresses the variance blow-up that appears in dot products as the dimension grows, avoiding softmax saturation and gradients that approach zero. Some models also apply L2 normalization to queries and keys before normalization, or apply soft truncation to attention scores afterward, aiming to preserve training stability across longer contexts and deeper networks.

    2.2 The multi-head structure

    A single attention head has limited expressive power; it can output only one weighted combination. Splitting d_model evenly into h parts, letting each part learn its own projections and compute attention independently, and then concatenating and applying an output projection, yields multi-head attention (MHA). Different heads can attend to different relationships, such as syntactic dependencies, coreference resolution, local adjacency, or long-range correspondence.

    This structure has one key property: queries and keys always correspond one-to-one, and each query head owns its complete set of key and value projections. This is the foundation of MHA’s expressive power, and also the root of its memory overhead. Most subsequent variants essentially break this one-to-one correspondence.

    2.3 The KV cache: the main memory burden for long context

    In autoregressive decoding, the K and V of the first t positions do not change when new tokens arrive, so they can be cached and reused to avoid recomputation at every step. The cache size is approximately:

    1. KV memory ≈ batch_size × seq_len × 2 × n_layers × n_kv_heads × d_head × bytes

    Here the factor 2 accounts for keys and values each occupying one copy, n_kv_heads is the number of key-value heads (equal to the number of query heads under MHA), and bytes is the number of bytes per element (2 for BF16/FP16).

    Consider a typical configuration: 32 layers, 64 query heads, head dimension 128, BF16 precision.

    • With 8 concurrent requests, each with a 4K context, MHA needs roughly 34 GB.
    • With the same configuration extended to a 128K context, MHA alone needs about 1 TB, far exceeding the memory of a single accelerator.

    In addition, the complexity of full attention is O(n²). Doubling the sequence length makes the compute and memory cost roughly four times larger.

    These numbers explain why competition in long-context scenarios often shows up first in how the KV cache is managed. It is worth emphasizing that the KV cache problem is not unique to autoregressive models. Some encoder-style multimodal models that use a full-attention mask, when generating video or high-resolution images, also compute very long sequences in one pass and cache keys and values, so the analysis above applies equally well.

    3. KV Sharing: Multi-Query and Grouped-Query Attention

    3.1 Multi-Query Attention (MQA)

    The simplest idea is to let all query heads share the same K and V. This is multi-query attention (MQA): the query heads still number h, but there is only one key-value head, so the KV cache shrinks directly to 1/h of the original.

    The benefits are direct: at decoding time each token needs to read only one copy of keys and values, which sharply reduces memory-bandwidth demand and correspondingly reduces memory usage. The cost is equally clear: all heads are forced to compete over the same set of keys and values, so expressive power declines. Many models that switched to MQA had to continue training on large amounts of data to recover quality.

    A common engineering transition is to start from MHA weights, average the multiple key-value projections within the same layer to obtain an initial shared projection, and then fine-tune briefly. This converges faster than random initialization.

    3.2 Grouped-Query Attention (GQA)

    Grouped-query attention (GQA) is a compromise between MQA and MHA: it splits the h query heads into g groups, with each group sharing one set of K/V. When g = 1 it degenerates into MQA, and when g = h it degenerates into MHA. As long as g divides h, each group has an equal number of query heads.

    For example, with 64 query heads and 8 key-value heads, every 8 query heads share one set of keys and values. The KV cache shrinks to 1/8, and the quality loss is usually clearly smaller than with MQA. In effect, GQA recovers most of the expressive power that MQA sacrifices at very little extra cost, which is why it has become one of the most common and safest choices among current mainstream open-weight models.

    3.3 A shared constraint

    It is worth noting that neither MQA nor GQA changes the mathematical form of attention; they change only the number of keys and values. What they save is memory capacity and memory bandwidth, while the attention computation itself is unchanged. As a result, their gains show up mainly in decoding throughput, concurrency scale, and long-context capacity, and they offer limited help for the compute pressure of long-sequence pre-training.

    4. Compression Form: Low-Rank Latent Attention

    MQA and GQA reduce the number of key-value “heads,” but the per-head dimension d_head is unchanged. Another approach does not reduce the number of heads; instead, it compresses the key-value representation of each token itself.

    Low-rank latent attention (represented by MLA) works as follows: each token caches only a low-dimensional compressed vector. Both queries and keys are derived from this vector, and values are obtained by up-projecting it as well. In addition, a small segment of position-transformed keys is cached separately to carry positional information.

    Its memory advantage comes from the fact that the cache dimension is no longer tied to “number of key-value heads × head dimension” but is instead determined by the compression dimension. Therefore, even with many query heads, the KV cache can remain small. Its effect is often summarized as: under the same KV budget, retaining richer information than simply “reducing heads.” The cost is a significant increase in implementation complexity: it requires a specialized attention operator that fuses compression and up-projection, or else memory is saved but compute may increase; parallel partitioning is also more constrained, since the key-value cache is no longer split along the head dimension.

    There is an even more aggressive idea: letting keys and values share the same low-rank projection. This is closer to the “kernel feature map” view in linear attention. Such methods can be implemented with standard matrix-multiply operators, but their expressive power and training stability both need careful evaluation.

    5. Layer Reuse: Cross-Layer Sharing

    The previous categories of variants all operate within a layer. Cross-layer sharing (represented by CLA) moves the view up one level: a group of adjacent layers (for example, every two layers) computes keys and values only once and passes them downward, while each layer computes only its own queries.

    The theoretical basis is that attention patterns in adjacent layers are often highly similar, and not every layer needs its own independent key-value storage. The intuitive benefit is that within a sharing group each layer’s KV cost is 1/k of the original, and the size of cross-request prefix caching shrinks as well. The cost is that the layers’ expressive power is coupled together, and the diversity gained from depth declines. Usually the sharing structure must be decided early in pre-training; later changes are hard to make up for through fine-tuning.

    6. Field of View: Sliding Window, Attention Sinks, and Sparse Attention

    6.1 Sliding Window Attention (SWA)

    Each token attends only to the most recent w positions, including itself. Complexity drops from O(n²) to O(n·w), and the KV cache can also keep only the portion within the window.

    One common misconception needs clarification: stacking many layers does not extend the window indefinitely. It can be shown that stacking L layers of attention with window w gives a receptive field of at most roughly L × w. That is, when L × w is smaller than the context length, the most distant tokens never interact directly with the very first tokens; information can only pass layer by layer, and it decays at each layer. This is an inherent boundary of window attention.

    6.2 Attention Sinks

    Empirical observation shows that after softmax, a model tends to assign a large share of its attention to the first few tokens of the sequence, even when they are not semantically important. This “attention sink” acts like a pressure-relief valve for attention, because softmax must normalize the weights to sum to 1, so the model needs somewhere it can freely dump attention.

    Once a sliding window pushes the opening tokens out of the visible range, the model may have “nowhere to put” its excess attention, and output quality collapses. A common fix is to keep the first k tokens always visible (together with the recent window), i.e., a sink + sliding window combination. When using such a structure, you need to be clear about where the system prompt should go. If it is placed at the beginning, it will slide out of the visible range with the window; if it is placed immediately adjacent to the query, it can be reused across requests via prefix caching, which is more robust.

    6.3 Native Sparse Attention

    The goal of sparse attention is to balance global coverage with near-linear complexity. A recent class of representative native sparse attention schemes typically consists of three components:

    • Compression: aggregate the keys and values of several consecutive tokens into a block-level summary.
    • Selection: score the query lightly against the block summaries and select the top few most relevant blocks.
    • Sliding window: also retain a local window to fill in the details.

    The final attention is computed only over “selected blocks + local window + a few global tokens.” Training and inference use the same sparse path, which avoids the problem of train-inference inconsistency.

    Implementation has many error-prone details, such as: indices must be sorted before gathering to preserve causality; positions within blocks and within windows must be masked correctly; and the normalization denominator of the attention weights must match the actual visible range.

    6.4 Other attention forms

    Beyond the schemes above, two more forms are worth attention.

    The first is static sparsity during training, which fixes part of the connections based on sentence length, relative positional distance, or manually specified head-level patterns. It is simple to implement but still degrades on long sequences.

    The second is linear/recurrent attention, which uses a recursively updatable compressed state instead of an explicit key-value history, giving complexity linear in length. It performs a lossy compression of history and remains weak on exact retrieval tasks, so it is often mixed with a few global attention layers.

    7. Vertical Trade-offs: Mixing Layer Patterns and Linear Structures

    The variants above mainly change the “horizontal” KV sharing and visible range. Another class of approaches works from the “vertical” dimension, mixing at the level of layer types. Two common forms exist.

    The first is mixing by layer type. Most layers use window attention while a few use global attention; or some layers use recurrent/linear structures, with a standard attention layer inserted every few layers to form a hybrid model. Global layers provide long-range routing capability, local layers handle details, and linear layers take on sequence compression. The overall effect is close to sparse attention, but the kernel implementation is simpler.

    The second is mixing attention with recurrent/linear modules. Some layers are standard attention, while others are recurrent-style modules with a compressed state. The KV cache of attention shrinks in proportion to the number of attention layers, rather than being eliminated entirely.

    The key to vertical design is not “whether to use attention” but “whether global information can be efficiently propagated across every distance segment.” Even with only a few global layers, you must ensure that critical content can travel from any position to wherever it is needed.

    8. Inference-Time Optimization: Saving KV Without Restructuring

    Even when the structure stays unchanged, the inference-system level offers several orthogonal optimizations. They do not alter model weights, so they can be stacked on top of any attention variant.

    • Paged KV management: divide the KV cache into fixed-size blocks allocated on demand, which reduces memory fragmentation and lets different requests share cache blocks for the same prefix.
    • Prefix reuse: cache the identical parts of the system prompt, fixed instructions, or RAG retrieval results. In multi-turn dialogue and fixed-prompt scenarios, time-to-first-token often improves significantly.
    • Continuous batching: insert an arriving request into a running batch immediately, without waiting for the whole batch to finish, which improves the utilization of both memory and compute.
    • KV quantization: store keys and values in lower precision such as INT8 or FP8. On most tasks the accuracy loss is limited, and memory usage can drop by half or more, but it must be validated separately for different tasks.
    • KV eviction and compression: during decoding, drop unimportant historical tokens based on cumulative attention scores, positional distance, or summary scores. These methods are lossy compression and also require accuracy evaluation.
    • Prefix cache offloading: migrate inactive KV blocks to memory or local storage and swap them back into GPU memory when needed.

    9. Positional Encoding and Training Stability

    After changing the key-value structure, positional information often becomes the most easily overlooked part.

    Positional encoding needs to be recalibrated. Take rotary position embedding as an example: it encodes positional information as a rotation applied to queries and keys. Common long-context extrapolation techniques include position interpolation (compressing position indices), frequency scaling (adjusting the rotary base frequency for the target length), and hybrid approaches. The key point is that when attention shifts from “global” to “window + sparse,” the distance range the model can actually perceive changes, so the original frequency calibration must be recomputed.

    There is a risk of positional collapse. If the positional encoding does not match the attention range, then during long-range extrapolation the model dumps almost all of its attention onto a few tokens at the beginning of the sequence, forming an “attention collapse” that shows up as repeated output and failed instructions. Such problems are hard to expose on benchmark tests but are common in real long-document scenarios.

    Training stability needs reinforcement. In extremely long contexts, attention scores can become extreme. Some schemes normalize queries and keys before attention, or apply soft truncation to the output, to control the magnitude of the logits. These practices usually appear in conjunction with a specific attention structure and should be considered together during selection.

    The source of positional information can be combined flexibly. In practice, positional information can be carried by the keys, by the queries, or placed only on the keys. In theory, as long as at least one of queries and keys carries positional information, attention can distinguish order. The differences among many variants essentially come down to whether positional information is placed in the “keys and values that every head has” or in the “shared compressed representation.” The latter concentrates positional information more, and also depends more strongly on the shared structure.

    10. Variant Comparison and Selection Guidance

    Variant KV cache cost Main benefit Main cost Implementation note
    MHA Baseline Strong expressive power, mature implementation Largest memory and bandwidth cost Standard attention kernel
    MQA ~1/h Lowest memory-bandwidth demand Noticeable quality drop Needs projection-initialization transition
    GQA ~1/g Good quality/cost balance Gains limited to memory and bandwidth Kernel must support group mapping
    Low-rank latent compression Depends on compression dimension Richer information under the same budget Needs a specialized fused operator Parallel partitioning is constrained
    Cross-layer sharing ~1/k Cache and prefix reuse shrink together Reduced cross-layer diversity Must be designed early
    Sliding window Within window Near-linear complexity Limited long-range coverage Combine with global layers or sink
    Sparse attention Selected blocks + window Global coverage, near-linear Complex, needs training support Unify training and inference paths
    Hybrid structure Depends on layer type Balances global coverage and efficiency More complex scheduling and partitioning Global layers must ensure routing

    When selecting, you can first answer three questions:

    1. Where is the bottleneck? If the bottleneck is memory capacity and memory bandwidth (typically long context and high-concurrency decoding), prioritize KV-sharing variants (GQA, low-rank compression, cross-layer sharing) along with inference-time paged caching, prefix reuse, and KV quantization. If the bottleneck is the attention computation of long sequences, prioritize window, sparse, or hybrid structures.
    2. What is the context length and task type? Short context and multi-turn dialogue are least sensitive to structural changes, so a mature scheme plus inference-time optimization is enough. Extremely long context requires a combination of “sparse or window + global layers + adapted positional encoding.”
    3. Can you control pre-training? If training from scratch, you have the greatest freedom of choice. If you can only adapt an existing model, prioritize schemes that can be realized through short fine-tuning or purely inference-time methods.

    11. Evaluation Methods and Engineering Notes

    Evaluation cannot rely on perplexity alone. Perplexity mainly reflects local language-modeling quality and is not sensitive enough to subtle differences in attention structure. It is recommended to also use:

    • Synthetic retrieval tasks: for example, single-needle “needle in a haystack” retrieval, multi-needle retrieval, variable tracking, and multi-hop question answering.
    • Real business evaluation sets: long-document summarization, long-context code understanding, contract and report review, and so on.

    Watch how metrics change with length. Fix a few length tiers and observe the trends in perplexity growth, retrieval accuracy, time-to-first-token, and single-card throughput, rather than looking only at single-point numbers at the maximum length.

    Watch out for implementation-level degradation. Whether a variant takes effect depends on whether the kernel supports it. If the framework falls back to a generic implementation, the theoretically more memory-efficient approach may actually deliver worse throughput. Before going live, compare the actual latency, throughput, and memory usage with the variant on versus off to confirm that the kernel path is indeed in effect.

    Confirm prefix consistency before cross-request reuse. When using prefix caching, always confirm that the cached prefix is token-for-token identical across different requests, including the system prompt and retrieved content. Even a slight difference causes a cache miss and can even assemble an incorrect context.

    On a cloud platform, you can treat the attention structure as one of the capacity parameters of the inference service. The model inference solutions of cloud providers such as Baidu AI Cloud typically take memory utilization, concurrency, and time-to-first-token as their core metrics. In this setting, combining GQA, paged caching, prefix reuse, and KV quantization is easier to turn into stable gains than pursuing a single novel structure. It is worth noting that regardless of how the structure changes, techniques such as quantization, distillation, and service scheduling are orthogonal to attention design and can be stacked on top.

    12. Summary

    Looking back across the whole spectrum of attention variants, three main threads can be distilled.

    • KV sharing (MQA/GQA): the most direct and mature means of reducing memory and memory-bandwidth demand.
    • Form compression (low-rank latent, cross-layer sharing): attempts to retain more information under the same budget, at the cost of greater implementation complexity.
    • Field-of-view control (window, attention sink, sparse, hybrid structures): a balance between the compute complexity and coverage of long context.

    The three can be stacked, but the complexity growth from stacking them is often nonlinear. What truly determines the outcome is not how many “advanced” variants are adopted, but whether the variants, positional encoding, inference kernels, and evaluation system can work together as a whole.

    For engineering teams, a pragmatic path is: first use GQA and inference-time optimization to solve cost and throughput, then gradually introduce window, sparse, and hybrid structures for long-context scenarios; validate each step with both synthetic retrieval and real business evaluation, and watch the degradation curve along the length dimension. When building large-model services in the cloud, this “structure selection + system optimization + length-stratified evaluation” approach is more controllable, and easier to evolve continuously, than chasing a single new structure.