Attention Mechanism Variants: From Multi-Head Attention to Efficient Inference
This article explains the main attention variants, from the motivation for attention and the self-attention computation to multi-head attention and the KV cache bottleneck during inference. It then covers multi-query, grouped-query, sliding window, sparse, and linear attention, along with causal and cross attention, and offers a practical approach for choosing a variant based on training throughput, latency, batch throughput, and memory limits.
1. Why Attention Is Needed
Before attention, sequence-to-sequence tasks commonly used an encoder-decoder structure. The encoder read the source sequence in order and compressed all of its information into a single fixed-length hidden state. The decoder could only generate output based on this summary.
This design worked reasonably well for short sentences, but it had an obvious bottleneck. The capacity of the hidden state is limited. When a position in the target sequence depends on information far away in the source sequence, a limited summary struggles to preserve all the details.
The core idea of attention is this: when generating each output, the model looks back directly at all positions in the input sequence and assigns weights according to their relevance. Instead of relying on a single compressed state, the model reads the original information as needed.
2. How Self-Attention Works
Self-attention applies this idea within a single sequence. Each token in the sequence plays three roles:
- Query (Q): what the current token is looking for.
- Key (K): what kind of information each token can offer, used to match against queries.
- Value (V): the content each token actually carries, which is aggregated with weights once a match is found.
The computation proceeds as follows.
- Multiply the input matrix by three learnable projection matrices to obtain Q, K, and V.
- Compute the dot product of Q and K to measure the relevance between each pair of tokens.
- Divide by a scaling factor to keep large dot-product values from making softmax gradients too small.
- Apply softmax to each row to obtain the attention weights.
- Compute a weighted sum of V using these weights to get a new representation for each position.
The formula is:
Attention(Q, K, V) = softmax(Q K^T / √d_k) V
Here, d_k is the dimension of the key vectors. The pseudocode is:
# X: input matrix with shape [n, d_model], where n is the sequence lengthQ = X @ W_Q # [n, d_k]K = X @ W_K # [n, d_k]V = X @ W_V # [n, d_v]scores = Q @ K.T / sqrt(d_k) # [n, n], pairwise relevance scoresscores = scores + mask # In causal settings, future positions are set to -infweights = softmax(scores, axis=-1)out = weights @ V # [n, d_v]
The time and memory complexity of this computation both scale with the square of the sequence length n. The longer the sequence, the faster the attention matrix grows. This is one of the core problems that the variants below try to solve.
3. Multi-Head Attention (MHA)
A single attention head can learn only one pattern of association. For example, one head might focus on grammatical structure, while another focuses on coreference. Multi-head attention runs h independent sets of projections and attention computations in parallel, then concatenates the results.
The process is as follows.
- Project the d_model-dimensional input into h subspaces, where each head has dimension d_head = d_model / h.
- Each head computes its attention output independently.
- Concatenate the h outputs into a d_model-dimensional vector.
- Use an output projection matrix to combine the information from all heads.
Multi-head attention is highly expressive and stable to train, so it became the standard configuration in the Transformer architecture. Its cost shows up during inference, especially in the key-value cache (KV Cache).
4. The Inference Bottleneck and the KV Cache
When generating text, the model outputs one token at a time. To avoid recomputing the K and V for all previous tokens at every step, the system caches them. This is the KV cache.
The memory used by the cache can be estimated with this formula:
KV cache bytes per sequence = 2 × number of layers × number of KV heads × dimension per head × sequence length × bytes per value
Consider a hypothetical configuration with 32 layers, 32 KV heads, 128 dimensions per head, a sequence length of 4096, and 2 bytes per value (for example, half-precision floating point). Substituting these values gives:
2 × 32 × 32 × 128 × 4096 × 2 bytes = 2 GiB
A single long sequence uses about 2 GiB of memory, and the memory pressure multiplies in batched inference. Therefore, most of the variants below aim to reduce the number of KV heads or the size of the cache, rather than change the basic way attention is computed.
5. Multi-Query Attention (MQA)
Multi-query attention keeps multiple query heads, but all query heads share a single set of keys and values.
- Query projections: still h sets.
- Key and value projections: only 1 set.
As a result, the KV cache shrinks to 1/h of its original size. In the hypothetical configuration above, the cache drops from 2 GiB to about 64 MiB.
The cost is that different heads no longer have their own independent key-value representations, which reduces the model’s ability to express some association patterns. In practice, a validation set is needed to determine whether the quality loss is acceptable.
6. Grouped-Query Attention (GQA)
Grouped-query attention sits between MHA and MQA. It divides the h query heads into g groups, with each group sharing one pair of keys and values.
- When g = h, it reduces to MHA.
- When g = 1, it reduces to MQA.
- When 1 < g < h, it is grouped-query attention.
The KV cache size is proportional to g. With g = 8 in the configuration above, the cache falls to 1/4 of its original size, about 512 MiB. This method strikes a good balance between memory savings and model quality, which is why it is widely used in inference optimization for large language models.
In implementation, you only need to copy or broadcast the smaller set of K and V heads to the corresponding query heads before computing attention. The rest of the model architecture stays the same.
7. Sliding Window Attention
Global attention requires each token to compute relevance with all previous tokens. Sliding window attention limits the visible range to the most recent w tokens.
Mask illustration (window size w = 3, where “●” means visible and “○” means masked):
t1 t2 t3 t4 t5 t6t4 ○ ● ● ● ○ ○t5 ○ ○ ● ● ● ○t6 ○ ○ ○ ● ● ●
This design brings two direct benefits.
- Computation drops from O(n²) to O(n·w), a clear advantage for long sequences.
- The KV cache only needs to keep the most recent w positions. It can be implemented as a ring buffer, so the cache size no longer grows with the sequence.
Information outside the window is not completely lost. After stacking multiple layers, information can propagate from layer to layer, so the effective receptive field grows with the number of layers, roughly the number of layers multiplied by the window size. However, tasks that directly depend on information from very distant positions may still be affected. For this reason, sliding window layers are usually alternated with global attention layers.
8. Sparse Attention and Linear Attention
These two approaches reduce complexity from a different angle.
Sparse attention predefines a sparse set of connection patterns, such as a local window plus a few global positions, or selecting parts of the history by blocks. It computes attention only between the selected token pairs, so complexity decreases as the selection gets smaller. The key difficulty is pattern design: if the pattern is too fixed, important dependencies may be missed.
Linear attention uses a kernel function to replace softmax with a decomposable form, so the order of computation can change. The core transformation is:
softmax(QK^T)V ≈ φ(Q)(φ(K)^T V)
By computing the small d × d matrix φ(K)^T V first, the complexity can be reduced to linear in n. The cost is that the approximation introduces error, and performance may drop on tasks that require exact retrieval.
In engineering practice, these two approaches are usually supplementary methods, mixed with standard attention or sliding window attention.
9. Causal Attention and Cross Attention
These concepts are orthogonal to the variants above, and they often appear together in real models.
Causal attention is used for autoregressive generation. The mask prevents each position from seeing the t
