The Evolution of Transformer Attention: Dense Multi-Head, Sparse, and Linear Designs

    This article reviews the main technical paths that have shaped Transformer attention over the past decade. It explains why dense multi-head attention became the default, how shared key-value heads, low-rank compression, sliding windows, hardware-aware kernels, native sparsity, and linear or state-space alternatives address different bottlenecks, and how prefill and decoding should be optimized separately. It also provides a practical selection order based on measured bottlenecks rather than model names.

    Self-attention is responsible for mixing information within a sequence, and it is also the part of the Transformer most likely to become difficult to control as context length grows. Many changes have appeared over the past decade, but from an engineering perspective they mostly address two problems.

    During the prefill stage, the cost of computing attention scores and the weighted sum grows roughly quadratically with sequence length. During autoregressive decoding, every new token must read the historical key-value cache, so memory usage and memory-bandwidth pressure grow linearly with context length. As sequences become longer, compute bottlenecks and memory-access bottlenecks appear one after another. Simply making the model larger does not automatically solve either problem.

    The key-value cache of standard softmax attention can be described as the storage size for one layer over one sequence. It is approximately:

    batch size × number of layers × number of key-value heads × sequence length × head dimension × bytes per element

    Keys and values are usually stored separately, so the total is roughly doubled. In standard multi-head attention, the number of query heads equals the number of key-value heads. As a result, the cache for long sequences grows almost linearly with:

    number of heads × head dimension × sequence length

    Most mainstream improvements since 2017 can be viewed as progress along three largely orthogonal directions:

    1. Reduce the number of heads, head dimension, or effective length inside the softmax framework.
    2. Replace part of self-attention with linear-complexity sequence mixing outside the softmax framework.
    3. Reorder computation at the operator level according to the memory hierarchy, reducing round trips to high-bandwidth memory.

    Why Dense Multi-Head Attention Became the Default

    The original multi-head attention design splits the representation into multiple subspaces. Each head performs its own query, key, and value projections, followed by softmax weighting.

    Its advantages are clear: the design is intuitive, training is stable, parallelism is high, and computation is acceptable for short sequences. The cost is written directly into the cache formula: every token, at every layer, must retain the keys and values of all heads.

    When context grows from thousands to tens of thousands or hundreds of thousands of tokens, decoding is no longer limited mainly by whether matrix multiplication is fast enough. Instead, every new token must move a very large historical cache from off-chip memory. At that point, tuning the optimizer, using activation checkpointing, or simply increasing batch size does not address the real hotspot.

    Reducing the Workload Inside Softmax

    The first direction does not change the semantics of “score first, normalize, then take a weighted sum.” It only reduces the amount of data that must be stored and read.

    Sharing Key-Value Heads

    Sharing key-value heads was one of the first reduction methods to be deployed at scale.

    Multi-query attention allows all query heads to share one set of keys and values. Grouped-query attention is a compromise: it uses several groups, with sharing inside each group while preserving some diversity across groups. In the cache formula, the number of key-value heads drops from being equal to the number of query heads to being much smaller than the number of query heads.

    There is some loss in parameter count and expressive power, but decoding bandwidth often drops by a constant factor of less than an order of magnitude, which matters for serving cost. In practice, grouped sharing is more common than extreme single-group sharing. If there are too few groups, long-range retrieval and disambiguation become worse. If there are too many groups, the cache returns to the scale of dense multi-head attention.

    Low-Rank Latent Compression

    Low-rank latent compression takes a different dimension. Instead of projecting keys and values to the full head dimension before caching, it stores history in a lower-dimensional latent representation and reconstructs it on demand during decoding, or computes it jointly with the query.

    This approach targets the product of:

    head dimension × sequence length

    rather than only reducing the number of heads. The latent dimension, reconstruction method, and whether differential or gating mechanisms are applied to the latent representation all affect numerical stability and forgetting under long contexts.

    The engineering purpose of gating or differential designs is to suppress slowly accumulating noise in the latent space and prevent the attention distribution from becoming too flat after compression. These methods still belong to the softmax family, so the quadratic term in prefill does not disappear in theory. Only the constants and memory-access patterns change.

    Reducing Effective Length

    Reduction in effective length includes sliding windows, local blocks, global tokens, and retrieval-style memory. The model still applies softmax over visible positions, but each query only attends to a subset.

    Correctness depends on whether the positions that should be attended to are still inside that subset. If the task is local encoding, a window is often sufficient. If the task requires precise backtracking across the full text, merely shrinking the window can show up in evaluations as incorrect citations or inconsistent references.

    Hardware-Aware Operators: Same Math, Different Data Movement

    The second direction is often misunderstood as a “new attention” mechanism. In most cases, the mathematical form has not changed. What changes is the blocking order.

    Standard implementations materialize a very large score matrix. The score matrix also grows quadratically with sequence length, and for long sequences it can consume more memory than the model parameters themselves.

    Hardware-aware methods tile the computation according to on-chip storage capacity. Within each tile, they compute scores, normalization statistics, and incremental updates to the output. Tile results are written back, avoiding the need to place the full score matrix in off-chip memory.

    This approach mainly removes the prefill memory wall and a large amount of unnecessary data movement. It does not reduce the number of multiply-add operations in the algorithmic sense. Therefore, it can be combined with grouped-query attention and low-rank compression: the former improves how computation is performed, while the latter reduces what must be computed and stored.

    Three constraints must be considered together in practice.

    First, tile size must match on-chip cache capacity. If tiles are too small, kernel launch and boundary overhead become too large. If tiles are too large, intermediate results inside the tile cannot fit.

    Second, masks, variable-length sequences, and prefix caching can break regular tiling. Effective ranges must be compressed into contiguous segments before computation.

    Third, incremental softmax depends on running maximum values and normalization factors. Under low precision, overflow is more likely, and tail probabilities can be rounded to zero. Tile-based algorithms must preserve a stable rescaling step rather than relying only on naive low-precision matrix multiplication.

    Native Sparsity: Making the Computation Graph Sparse

    As context continues to grow, blocking alone still requires paying for nearly all-to-all computation. Native sparsity writes “which positions participate in attention” into the structure itself, rather than patching it afterward.

    Common patterns include:

    • Selecting a small number of historical blocks per block.
    • Assigning different spans to different heads.
    • Using a cheap scoring step to filter candidates before exact attention.
    • Hierarchical compression, where coarse-grained summaries handle long-range information and fine-grained tokens handle the current window.

    Sparsity works only if the selector is cheap and either differentiable or at least stable during training. If the selection itself is another dense attention operation, the quadratic cost has merely been renamed.

    The sparse pattern used during training must also match the pattern used during inference. Otherwise, a distribution shift can occur in which information is visible during training but masked during inference.

    Sparsity also changes the cache layout. The cache is no longer a single contiguous key-value sequence. It becomes a collection of block tables, indices, and optional summary caches. On the serving side, logical positions must be mapped to physical pages. Prefix reuse, eviction, and batch scheduling all become more complex.

    Experience with very long contexts in industry shows that attention-related data movement often dominates decoding latency. The first value of sparsity is reading less cache; reducing multiply-add operations is secondary.

    Beyond Softmax: Linear Attention and State-Space Mixing

    The third direction accepts that softmax normalization couples all historical positions, making it difficult to become linear at the root.

    Linear attention uses kernel functions or feature maps to factorize the query-key inner product, so history can be folded into a state whose size is independent of sequence length. During decoding, only the state is updated; there is no need to read back all keys and values.

    State-space modules maintain a hidden state through linear recurrence. For long sequences, both computation and caching are closer to constant or linear scanning.

    Their weaknesses are also clear. Exact “name a specific token from a huge history” behavior is less reliable than with softmax, and training can be less stable in the early stages.

    Therefore, hybrid architectures are more common in recent years than full replacement. For example, lower layers may use linear or recurrent modules for cheap local mixing, while higher layers retain a small number of softmax heads for retrieval. Alternatively, most channels in the same layer may follow a linear path, while a few channels retain full attention.

    The mixing ratio should be adjusted according to the task rather than copied from default values in papers. Code completion, conversational summarization, and multi-document question answering have different requirements for precise recall. If too few softmax heads are retained, performance can suddenly drop on subtasks that require exact copying.

    Prefill and Decoding Should Be Designed Separately

    An easily overlooked fact is that the two walls have different optimal solutions.

    Prefill consumes compute and on-chip cache. It is suited to fused kernels, large matrix multiplications, and operator-level tiling.

    Decoding consumes bandwidth. It is suited to reducing key-value heads, compressing head dimension, paged caching, and ensuring that each new token touches only sparse blocks or a constant-size state.

    Using the same set of kernels for both stages usually means neither stage is optimal.

    For serving systems, it is recommended to separate them explicitly:

    • Prefill: variable-length packing, prefix-cache hits, and block-fused softmax or sparse selection.
    • Decoding: continuous batching, page-based cache management, and page sizes aligned with memory alignment and kernel access granularity.
    • Eviction: discard entries by prefix popularity rather than request arrival order, avoiding repeated recomputation of high-reuse system prompts.
    • Precision: the cache can be stored at lower precision than compute, but rescaling and rotary position embedding accumulation must retain enough precision. Otherwise, positional information in the later part of long sequences will drift.

    Illustratively, the number of cache bytes read in one decoding step can be written as:

    1. bytes ≈ batch × layers × kv_heads × page_tokens_touched × head_dim × elem_bytes × 2

    Here, page_tokens_touched is close to the full context under dense full attention, close to the window or selected blocks under window or block sparsity, and close to the width of a constant state under pure linear recurrence.

    To judge whether an optimization is effective, first check whether this quantity decreases, then check whether quality evaluations remain acceptable.

    Selection Order

    Do not start from terminology. Start from bottleneck measurement.

    If memory is first exhausted by the key-value cache while compute-unit utilization remains low, prioritize grouped key-value sharing, lower cache precision, paging, and prefix reuse.

    If the score matrix or intermediate activations exhaust memory during prefill, prioritize hardware-aware tiling and avoid materializing the full attention matrix.

    If the context is extremely long and decoding bandwidth still dominates, then introduce controlled sparsity or linear hybrids, while retaining a softmax path for heads that must perform precise backtracking.

    Low-rank compression is suitable when the cache dimension can no longer be reduced effectively but global softmax semantics are still required. It needs a separate long-sequence numerical regression test; short-context loss alone is not enough.

    Evaluation should separate at least four items:

    • Short-context quality.
    • Long-context retrieval and multi-hop consistency.
    • Time to first token.
    • Steady-state per-token latency and single-card concurrency.

    Reporting only an average score can hide sparse-selection failures. Reporting only throughput can hide quality regressions. Position encoding, batch scheduling, and cache layout must be changed together with the attention design. Otherwise, gains from lower algorithmic complexity can be consumed by fragmented memory access.

    The common point of the past decade is not that one fixed structure won. Instead, attention has been transformed from an indivisible dense operator into a system that can be budgeted separately by head count, dimension, length, state, and data movement.

    Softmax remains the anchor for exact mixing. Linear and sparse methods try to remove length from the cost formula as much as possible. Hardware-aware operators make the remaining computation fit the chip’s memory hierarchy.

    When making a selection, state clearly which dimension is being reduced, then decide how much full attention to retain. That is more reliable than chasing a single structure name.