Attention Mechanism Variants: From Multi-Head Attention to Efficient Inference
This article introduces the fundamentals of attention mechanisms, starting from why fixed-length encoder states fall short for long sequences. It walks through the scaled dot-product self-attention computation step by step, explains multi-head attention and why splitting dimensions across heads costs no extra FLOPs, and then examines the real inference bottleneck: the KV cache, including how to estimate its size.
1. Why Attention Is Needed
Early sequence-to-sequence models typically used an encoder–decoder architecture. The encoder reads the source sequence in order and compresses all its information into a fixed-length hidden state, and the decoder then generates the target sequence token by token based on this summary. This works when the input is short. As the input grows longer, information from distant positions decays as it propagates step by step, and the fixed-capacity final state cannot retain the details of every position.
Attention abandons the assumption that “one summary is enough.” At each decoding step, the model re-scores all input positions and aggregates them with weights proportional to their relevance. Information no longer has to be squeezed into a single vector; the model can look back directly at any position in the source sequence whenever needed.
This idea was later generalized to positions within the same sequence, giving rise to self-attention, which became the core component of the Transformer architecture.
2. How Self-Attention Is Computed
Self-attention allows every token in a sequence to attend to every other token and produce a new, context-aware representation. The computation has three steps.
Step 1: linear projection. Each input vector is multiplied by three sets of learnable matrices to produce the Query, Key, and Value vectors. The query represents “what I am looking for,” the key represents “what label I can offer,” and the value represents “the actual content to be passed along.”
Step 2: compute similarities and normalize. Take the dot product of the query with all keys, divide by the square root of the dimension to stabilize the numerics, and apply softmax to obtain the weights. The reason for dividing by √d is that with large dimensions, the variance of the dot products grows with the dimension; unscaled scores would push softmax into its saturated region, where gradients become very small.
Step 3: weighted sum. Multiply the value vectors by the weights and sum them to get the output for that position.
The formula is:
Attention(Q, K, V) = softmax(QKᵀ / √d_k) V
Pseudocode:
function attention(Q, K, V, mask):scores = Q × transpose(K) / sqrt(d_k)if mask is not None:scores = scores + mask # masked positions set to negative infinityweights = softmax(scores, axis=-1)return weights × V
In the decoder, a causal mask is also required to prevent position i from attending to tokens after position i. Otherwise, the model could simply read the answer during training. The mask works by setting the corresponding scores to negative infinity, so their weights become zero after softmax.
In terms of complexity, for a sequence of length n the attention matrix is n×n, and both the time and the intermediate memory scale with n². Many attention variants start from exactly this point, aiming to reduce the cost of long sequences.
3. Multi-Head Attention
A single set of attention can only capture one similarity pattern. Multi-Head Attention (MHA) splits the hidden dimension d_model into h subspaces. Each head has its own projection matrices and computes attention independently; the results are then concatenated and passed through one final output projection.
Different heads often attend to different kinds of relationships—for example, local syntactic dependencies, long-range coreference, or the positions of specific symbols. This division of labor is an empirical observation of trained models, not something enforced by the architecture.
The projection parameters of an MHA layer total roughly 4·d_model² (excluding biases), corresponding to the Q, K, V, and O projection matrices. Each head has dimension d_model / h, and the total computation of attention scores is n²·d_model, independent of the number of heads h. Therefore, splitting the hidden dimension into multiple heads adds no extra floating-point operations, yet lets the model learn multiple types of relationships simultaneously.
4. The Real Bottleneck at Inference Time
During training, the entire sequence can be computed in parallel, so the bottleneck is usually raw compute. At inference time, the model generates tokens one by one, and each step must access the keys and values of all previous positions. To avoid recomputation, the system stores the K and V tensors already computed at each layer—this is the KV cache.
The size of the KV cache can be estimated with the following formula:
Bytes per token = 2 × number of layers × number of key/value heads × head dimension × bytes per element
An example makes this concrete. Consider a model with 32 layers and a head dimension of 128, using 16-bit floating-point numbers
