Self-Attention and Multi-Head Attention: A Complete Guide
This article explains self-attention and multi-head attention (MHA) from their historical origins through to production engineering. It traces how attention emerged to solve the information bottleneck in RNN encoder-decoder models, breaks down the query-key-value mechanics of self-attention step by step, and shows why multi-head attention buys multiple independent "views" at nearly no extra cost. It then surveys the main variants derived from MHA—causal masking, grouped-query and multi-query attention, sliding-window attention, and cross-attention—and closes with practical guidance on cost structure, IO-aware attention, distributed setups, observability, a deployment checklist, and common misconceptions. Readers will come away with a clear mental model for judging what each attention variant saves, what it costs, and where it applies.
From Attention’s Origins to Multi-Head Self-Attention: A Complete Guide
1. Why revisit the attention mechanism?
Large-model discussions have dominated technical conversation for the past few years, but the old question that still deserves a fresh look is really just one: within a sequence, how should each position “see” every other position?
Self-attention offers an elegantly minimal answer: let every token in the sequence “query” all the other visible tokens, assign them different weights, and use those weights to build a new, context-aware representation. Multi-Head Attention (MHA) is the standard engineering version of this idea in the Transformer—it runs several self-attention heads in parallel, each with its own projection matrices, then fuses their outputs into a richer representation.
Understanding these two layers of the mechanism is the key to getting started, because almost every later efficiency improvement (grouped-query attention, sliding-window attention, sparse attention, linear attention, and so on) is a trade-off built on top of them. Once MHA clicks, you hold the key to understanding all of these variants.
This article unfolds in this order: historical motivation → how self-attention works → the multi-head transformation → typical architectural evolution → engineering practice and common pitfalls.
2. Where attention began: the “information bottleneck” in older systems
Many people assume attention was born together with the Transformer. The opposite is true—attention predates both the Transformer and multi-head attention. Its direct soil was the encoder-decoder RNN used for machine translation.
2.1 How the old paradigm worked
In those older architectures, the flow was usually:
- Encoding phase: the encoder RNN reads the source sentence token by token, compressing the information into a hidden-state sequence that evolves over time.
- Bridging: in the simplest implementations, only the final hidden state of the sequence is kept as a “condensed summary” of the sentence.
- Decoding phase: the decoder RNN starts from this fixed-length vector and generates the target sentence one step at a time.
This design worked well for short sentences, straightforward word order, and simple structure. Translating “我吃饭” into “eat,” for example, only needs a small “note card.”
2.2 Where the bottleneck appears
The problem is clear: the hidden state has fixed capacity, while the amount of information it must carry is variable.
When the correctness of the next word in the target sentence depends on information at the far end of the source sentence—long-range dependencies, inverted word order, swapped subject and object, proper nouns and numbers that must line up—the decoder’s little “note card” simply cannot hold it all. Translations then start to show omissions, mistranslations, and confused references. In more technical terms: a fixed-dimension vector serves as the sole channel between encoder and decoder, and the information-bandwidth ceiling of that channel becomes the ceiling on the entire model’s performance.
2.3 The liberation brought by attention
The core insight of attention is this: instead of compressing all information into one summary, look back at the original input at every decoding step.
Concretely, when the decoder generates step t, it uses a “query” to compute a similarity against every hidden state produced by the encoder, yielding a set of normalized weights. The decoder then takes a weighted sum over all encoder states to obtain a context vector tailored to the current generation step. This way, every time the decoder emits a word, it can re-focus on a different part of the source sentence.
This change delivered three benefits:
- It broke the information bottleneck: any decoding step can access the full input, not a fixed-size summary.
- It enabled automatic alignment: the distribution of attention weights often shows an interpretable alignment between the target word and its corresponding position in the source.
- It eased vanishing gradients: attention creates a “short path” between distant positions, so gradients no longer have to traverse the entire RNN time chain.
Note that these ideas were then generalized from “decoder looking at encoder” to “any two positions within a sequence looking at each other”—this is the prototype of self-attention. Once the design no longer relies on recurrence, the entire set of time steps can be computed in parallel, and training efficiency changes qualitatively.
3. Self-attention: turning “retrieval” into matrix operations
3.1 Four roles: Query, Key, Value
Self-attention can be broken down into a very plain three-step process, abstracted from the scenario of “retrieval”:
- Query (Q): what the current token is “looking for.”
- Key (K): the “here is what I have” label each token hangs out.
- Value (V): the actual content each token carries.
The flow is: compare Q against all K to get scores → scale and normalize the scores into weights → take a weighted sum over V. The output is a new vector that fuses information from the other tokens in the sequence.
3.2 Score, scale, normalize, weight: four steps
For the input sequence representation $X$, three sets of learnable projections produce:
Q = X · Wq , K = X · Wk , V = X · Wv
Then:
scores = Q · Kᵀ / √d_k # scaled dot-product scoresweights = softmax(scores, dim=-1) # normalize into a probability distributionoutput = weights · V # weighted aggregation
Why divide by $\sqrt{d_k}$? Because the dot product of two independent random vectors has a variance that grows linearly with the dimension. As the dimension gets large, the magnitude of the dot product blows up sharply, and softmax saturates into a “one-hot” distribution—almost only one position receives a gradient while the rest get gradients near zero, making training extremely unstable. Dividing by $\sqrt{d_k}$ pulls the variance of the dot product back into a manageable range. This is a numerical-stability issue, not a matter of mysticism.
Why scaled dot-product instead of the additive scoring common in earlier work? Because the dot-product form can be expressed entirely as matrix multiplication, which runs efficiently in parallel on modern hardware (GPUs and various AI accelerators); additive scoring with element-wise nonlinear accumulation requires each step to depend serially on the output of the previous one.
3.3 Example code
import torchimport torch.nn.functional as Fdef self_attention(x, Wq, Wk, Wv, mask=None):"""x : [B, T, D] batch, sequence length, model dimensionWq/Wk/Wv : [D, D] learnable projectionsmask : [B, 1, 1, T] or [B, 1, T, T], masked positions set to -inf"""Q = x @ Wq # [B, T, D]K = x @ Wk # [B, T, D]V = x @ Wv # [B, T, D]d_k = Q.size(-1)scores = (Q @ K.transpose(-1, -2)) / (d_k ** 0.5) # [B, T, T]if mask is not None:scores = scores.masked_fill(mask == 1, float('-inf'))weights = F.softmax(scores, dim=-1) # normalize per rowreturn weights @ V, weights # [B, T, D], [B, T, T]
Three engineering reminders:
- Masked positions must be filled with
-inf, not0. Filling with0still yields a non-zero probability after softmax, which effectively “leaks information that should not be seen.” - If an entire row for some query is masked (for example, a sequence that is all padding), the softmax denominator becomes 0 and produces
NaN, which requires extra fallback handling. - Self-attention is itself “indifferent” to order—shuffle the input order and the output is simply reordered accordingly. Positional information must be injected explicitly through positional encoding (sinusoidal, learnable, rotary, and so on).
4. Multi-head attention: replacing a single viewpoint with many
4.1 The problem with a single head
Having only one set of $W_q, W_k, W_v$ means the entire representation space has just one “focus.” It must simultaneously cover local collocations, long-range references, syntactic constraints, semantic similarity, and other patterns that differ fundamentally—and the optimal similarity measure for each of these is different. The result is that a single head learns an “averaged” way of attending, sharp for no specific pattern.
4.2 The core idea of multi-head attention
The MHA approach is not to “widen” but to “divide labor”:
- Split the $d{model}$-dimensional representation into $h$ parts, each with $d_k = d{model} / h$.
- Each part runs a complete self-attention computation independently, with its own $W_q^i, W_k^i, W_v^i$.
- Concatenate the outputs of the $h$ heads along the feature dimension.
- Apply one linear transformation through an output projection $WO$, fusing everything back to $d{model}$ dimensions.
The key point: the total compute and total parameter count are essentially on par with a single “full-width” attention head. Because each head’s width shrinks by a factor of $h$ while the number of heads grows by a factor of $h$, the two cancel out. In other words, multi-head attention is a nearly free lunch—you pay no extra compute, yet you gain $h$ independent similarity measures.
This is the fundamental reason MHA became the standard design, and it is also the most common baseline for evaluating other attention variants.
4.3 Example code
import torchimport torch.nn as nnclass MultiHeadAttention(nn.Module):def __init__(self, d_model, n_heads, dropout=0.1):super().__init__()assert d_model % n_heads == 0, "d_model must be divisible by n_heads"self.d_model = d_modelself.n_heads = n_headsself.d_k = d_model // n_headsself.Wq = nn.Linear(d_model, d_model)self.Wk = nn.Linear(d_model, d_model)self.Wv = nn.Linear(d_model, d_model)self.Wo = nn.Linear(d_model, d_model)self.dropout = nn.Dropout(dropout)def _split(self, x):B, T, _ = x.shape# [B, T, D] -> [B, H, T, d_k]; move the head dimension ahead of# the sequence dimension for easier parallel computationreturn x.view(B, T, self.n_heads, self.d_k).transpose(1, 2)def _merge(self, x):B, H, T, d_k = x.shapereturn x.transpose(1, 2).contiguous().view(B, T, H * d_k)def forward(self, x, mask=None):Q, K, V = self._split(self.Wq(x)), self._split(self.Wk(x)), self._split(self.Wv(x))scores = (Q @ K.transpose(-1, -2)) / (self.d_k ** 0.5) # [B, H, T, T]if mask is not None:scores = scores.masked_fill(mask, float('-inf'))attn = self.dropout(torch.softmax(scores, dim=-1))out = self.Wo(self._merge(attn @ V)) # [B, T, D]return out, attn
4.4 How it is organized in typical architectures
In typical mainstream large-model architectures, MHA is rarely an isolated module. It is usually wrapped in a “pre-normalization + residual” enclosure:
class AttentionBlock(nn.Module):def __init__(self, d_model, n_heads, norm_eps=1e-5):super().__init__()self.norm1 = nn.LayerNorm(d_model, eps=norm_eps) # pre-normalizationself.attn = MultiHeadAttention(d_model, n_heads)self.norm2 = nn.LayerNorm(d_model, eps=norm_eps)self.ffn = nn.Sequential( # position-wise feed-forward networknn.Linear(d_model, 4 * d_model),nn.GELU(),nn.Linear(4 * d_model, d_model),)def forward(self, x, mask=None):h, _ = self.attn(self.norm1(x), mask)x = x + h # residual connectionx = x + self.ffn(self.norm2(x))return x
The residual connection is not decorative. It guarantees an identity path for gradients, making deep stacking possible; normalization, meanwhile, pulls each layer’s input back into a numerically stable range. “Attention handles cross-position information mixing, and the feed-forward network handles per-position nonlinear transformation”—this division of labor is the key to understanding the Transformer’s overall design.
5. Evolution from MHA: what it spawned
MHA laid the basic framework, and nearly all later optimizations revolve around one question: what is necessary, and what can be dropped?
5.1 Causal attention (Causal Masking)
During autoregressive generation, position t can only see positions $\le t$. In practice, an upper-triangular mask is overlaid on the score matrix, filling future positions with -inf:
causal_mask = torch.triu(torch.ones(T, T), diagonal=1).bool()
This is a constraint at the visibility level, independent of the number of heads, but it makes the attention matrix inherently lower-triangular and sparse.
5.2 Grouped-query / Multi-query attention (GQA / MQA)
One of the heaviest costs during inference is the KV cache: to avoid recomputation, the K and V of historical tokens are cached, and its memory footprint scales with “number of heads × sequence length × depth.” When the context grows from a few thousand to hundreds of thousands of tokens, the KV cache can even exceed the model weights themselves.
This leads to a very pragmatic trade-off:
- MHA: every query head gets its own independent set of K/V heads.
- MQA: all query heads share a single set of K/V heads (maximum cache compression, but reduced expressiveness).
- GQA: query heads are split into several groups, each sharing one set of K/V heads, striking a balance between the two.
The key point here: the K/V heads become fewer, but the number of query heads stays the same, so “the shape of the attention matrix” is largely preserved while cache and memory-access pressure drops significantly.
5.3 Sliding-window attention
Standard self-attention’s computational complexity grows quadratically with sequence length, which is unacceptable in very-long-context scenarios (long-document understanding, repository-scale code retrieval). Sliding-window attention takes a simple approach: allow each token to attend only to a fixed window of its neighbors, and with layer-by-layer stacking, let the receptive field expand linearly with depth.
Its premise is that most truly important dependencies are local, while long-range information can be passed along gradually through depth. This has been shown effective on many language-modeling tasks, but it sacrifices the ability to jump directly between any two points, so it is often stacked alternately with global attention layers.
5.4 Cross-attention
When a “source-target” relationship exists between sequences (translation, summarization, aligning text and image tokens in multimodal settings), Q comes from one side and K/V from the other—this is cross-attention. It is essentially MHA with its module boundary cut along “sequence source,” a continuation in the Transformer era of the historical idea discussed in Section 2.
6. Engineering practice: a few key judgments from principle to production
6.1 First, get the cost structure straight
The cost composition of large-model training and inference is entirely different, and conflating them often leads to optimizing in the wrong direction:
- Training phase: closer to compute-bound; the core is the throughput and parallel efficiency of matrix multiplication.
- Inference prefill phase: also compute-intensive, since it must process the entire input at once.
- Inference decode phase: closer to memory-bandwidth-bound; every token must re-read all the weights and the KV cache, so the GPU’s arithmetic units spend much of their time waiting on data.
Therefore, “increasing FLOPS” is nearly useless for the decode phase. What actually helps is reducing memory traffic and improving cache reuse.
6.2 IO-aware attention implementations
Standard implementations fully materialize the $T \times T$ score matrix in memory, which is both a memory hog and a bandwidth hog for long sequences. The mainstream industry approach is block-wise computation + online normalization: load Q, K, and V in blocks into fast on-chip cache, maintaining the running softmax accumulation as you go, without ever writing back the full attention matrix. This avoids both the quadratic intermediate memory footprint and drastically reduces the number of memory round trips. Such implementations are mathematically equivalent to the standard version, with error coming only from floating-point accumulation order—an engineering optimization you can adopt with confidence.
6.3 Distribution and resource organization
When a single device cannot fit the model, common techniques include:
- Tensor parallelism: split attention heads by dimension across devices, each device handling a subset of heads—a natural fit for MHA’s “heads are independent” structure.
- Pipeline parallelism: split by layer.
- Sequence/context parallelism: split by sequence length, combined with ring communication to complete cross-segment attention.
- Data parallelism + gradient sharding: to raise overall throughput.
One hidden reason GQA is popular in practice is that it makes the sharding and communication of the KV cache under tensor parallelism simpler.
6.4 Observability and operations
After a large-model service goes live, the hard part is not the model but diagnosing “performance degradation.” At a minimum, cover the following observability items: per-request latency breakdown (queuing, prefill, decode), cache hit rate, memory and KV-cache usage, batch-aggregation efficiency, and drift in the output-length distribution. These metrics can be mapped directly onto general-purpose logging services and monitoring/alerting capabilities; training and inference clusters are scheduled through a container platform, combined with elastic GPU compute to scale up and down across peaks and troughs. General cloud-product capabilities—such as those available on Baidu AI Cloud—can cover these needs, so you do not have to build a low-level operations stack from scratch for every scenario.
6.5 A deployment checklist
- Is the maximum sequence length defined? When exceeded, is it truncation, sliding window, or segmented summarization?
- Is the KV-cache memory budget included in capacity planning? Have you considered quantization or paged management?
- Does the number of heads evenly divide the model dimension? Does the number of groups in grouped-query attention match the actual cache budget?
- Does the masking logic correctly handle padding and causality? Have you ever encountered
NaN? - Have you run an output-consistency comparison between baseline and optimized versions (same input, same parameters, token-by-token)?
- Are first-token latency and overall throughput each assigned their own SLO, rather than watching only a single average?
7. A few common misconceptions
- “More heads is always better.” Increasing the number of heads compresses each head’s width; when $d_k$ becomes too small, single-head expressiveness drops, and the benefit decays quickly or even turns negative. In practice, the number of heads must be tuned to match the model dimension, not cranked to the maximum blindly.
- Treating attention weights as the model’s explanation. Weights reflect similarity and normalization results; they are not equal to causal contribution. Only counterfactual methods such as perturbation or substitution get closer to a causal conclusion.
- Overlooking the role of positional information. Self-attention without positional encoding is nearly useless for language modeling, because it is completely insensitive to order.
- Mistaking a complexity problem for a compute problem. The core bottleneck in long-sequence scenarios is often memory and bandwidth, and piling on more compute tends to yield little.
- Confusing the “number of heads” in MHA versus GQA. The two have the same number of query heads but different numbers of K/V heads. When discussing performance and caching, you must be clear about which kind of head you mean.
8. Conclusion
The history of the attention mechanism’s evolution is essentially the history of how the information channel was continually widened while its cost was continually driven down:
- From the RNN’s fixed-vector summary to the decoder dynamically looking back at the input at every step;
- From single-head to multi-head, gaining multiple independent viewpoints at nearly zero extra cost;
- From full attention to variants such as grouped-query and sliding-window, each searching for its own optimum between expressiveness and resource efficiency.
The core conclusion is a single sentence: MHA provides a general and complete framework, and every later variant answers the same question—under your scenario’s constraints, which attention computations can be dropped, and does dropping them hurt quality?
Grasp this throughline, and when you read any new attention-improvement proposal, you can quickly judge what it saves, what it costs, and what kind of workload it suits. That is the real payoff of mastering this mechanism.
