Multi-Head Attention in Transformers: A Deep Dive

    Multi-head attention (MHA) is the core mechanism behind modern large language models. This article explains self-attention fundamentals, walks through the complete MHA computation pipeline with implementation code, covers key engineering details like masking and KV caching, and introduces mainstream optimization variants such as GQA and sliding window attention. Understanding MHA is essential for model selection, performance tuning, and cost optimization in LLM workloads.

    Deep Dive into Multi-Head Attention in Transformers

    The attention mechanism is the foundation of modern large language models. Whether it’s architecture design, inference performance optimization, or the evolution of long-context handling, almost all work in this space revolves around understanding and modifying attention. This article starts with the basics of self-attention, progressively builds up to the complete mechanics of Multi-Head Attention (MHA), and lays the groundwork for understanding various attention variants.

    1. Self-Attention: Giving Tokens Context Awareness

    The core idea of self-attention is simple: every token in a sequence can “look at” other visible tokens, assign them different weights based on relevance, and use those weights to produce a weighted aggregation of information—resulting in a new, context-aware representation.

    Concretely, for each token in the input sequence, the model applies three learnable linear projection matrices to map it into three different vectors:

    • Query (Q): what the current token is “looking for”;
    • Key (K): how the current token “can be retrieved”;
    • Value (V): the actual information content the current token carries.

    The attention weights are computed using the classic scaled dot-product formula:

    1. Attention(Q, K, V) = softmax(QK^T / √d_k) · V

    Here, QK^T computes the similarity between queries and all keys. Dividing by √d_k scales the values down, preventing large dot products from pushing softmax into its gradient saturation region. Softmax then normalizes the similarity scores into a weight distribution, and finally the weights are used to compute a weighted sum of the value vectors, producing an output enriched with contextual information.

    In causal language models, a causal mask is also introduced to preserve autoregressive behavior: each position can only attend to itself and earlier positions, while information from future tokens is blocked. This design is the prerequisite for decoder-style architectures to generate text token by token.

    2. From Single Head to Multiple Heads: Why Parallel Attention?

    A single attention head can only learn token dependencies within one representation subspace. But dependency patterns in language are diverse—some positions relate to syntactic structure, others to coreference resolution, and others to long-range semantic connections. Multi-head attention is designed precisely to capture this diversity.

    MHA runs multiple attention heads in parallel. Each head has its own independently learned Q, K, and V projection matrices and performs attention in a different subspace. The outputs of all heads are then concatenated and passed through an output projection matrix (W_O) to produce the final representation. The computation can be summarized as:

    1. head_i = Attention(Q·W_i^Q, K·W_i^K, V·W_i^V)
    2. MHA(Q, K, V) = Concat(head_1, ..., head_h) · W_O

    A reference implementation looks like this:

    1. import torch
    2. import torch.nn as nn
    3. class MultiHeadAttention(nn.Module):
    4. def __init__(self, d_model, num_heads):
    5. super().__init__()
    6. assert d_model % num_heads == 0
    7. self.num_heads = num_heads
    8. self.head_dim = d_model // num_heads
    9. self.q_proj = nn.Linear(d_model, d_model)
    10. self.k_proj = nn.Linear(d_model, d_model)
    11. self.v_proj = nn.Linear(d_model, d_model)
    12. self.out_proj = nn.Linear(d_model, d_model)
    13. def forward(self, x, mask=None):
    14. B, T, C = x.shape
    15. # Linear projection and head split: (B, T, C) -> (B, h, T, d)
    16. q = self.q_proj(x).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
    17. k = self.k_proj(x).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
    18. v = self.v_proj(x).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
    19. # Scaled dot-product attention
    20. scores = q @ k.transpose(-2, -1) / (self.head_dim ** 0.5)
    21. if mask is not None:
    22. scores = scores.masked_fill(mask == 0, float("-inf"))
    23. attn = torch.softmax(scores, dim=-1)
    24. out = attn @ v
    25. # Merge heads and apply output projection
    26. out = out.transpose(1, 2).contiguous().view(B, T, C)
    27. return self.out_proj(out)

    It’s worth emphasizing that multi-head attention does not increase the total computation: each head’s dimension is reduced to d_model / num_heads, so the total cost of h parallel heads is roughly on par with a single full-dimensional head—while expressive power improves significantly.

    3. Key Engineering Details

    In real-world development, several details deserve special attention:

    1. Mask correctness: The shapes and broadcasting behavior of causal masks and padding masks must align exactly with the attention score matrix. This is one of the most common sources of bugs.
    2. Numerical stability: The scaling factor √d_k must not be omitted. Under mixed-precision training, softmax typically needs to be computed in higher precision to avoid overflow.
    3. KV caching: During inference, the K and V vectors of past tokens can be cached and reused, avoiding recomputation over the entire sequence for every generated token. This is the fundamental technique for inference acceleration—and also the primary target of optimization in subsequent attention variants, since cache size scales directly with the number of heads and head dimension.

    4. Limitations of MHA and Improvement Directions

    The main bottleneck of standard MHA is that as sequence length and the number of heads grow, KV cache memory usage and attention computation complexity (O(n²)) expand rapidly. Several improvement approaches have been proposed to address this:

    • Grouped Query Attention (GQA): multiple query heads share the same set of K and V heads, significantly shrinking the KV cache and reducing inference cost with almost no loss in model quality;
    • Multi-Query Attention (MQA): the extreme form of GQA, where all query heads share a single set of K and V;
    • Sliding Window Attention (SWA): restricts each token to attending only within a fixed-size local window, reducing complexity to linear; often stacked alternately with global attention layers;
    • Sparse and approximate attention: approximates the full attention matrix through various sparsity patterns to support very long contexts.

    All of these variants re-explore the trade-off between “expressive power” and “compute/memory cost” that MHA embodies. Understanding MHA’s complete computation pipeline is a prerequisite for mastering these optimization techniques.

    5. Conclusion

    Through its structure of “parallel multi-subspace attention + output fusion,” multi-head attention dramatically improves a model’s ability to capture diverse dependency patterns while keeping computational overhead manageable. From Q/K/V projections and scaled dot products to causal masking and multi-head concatenation, every step has a clear design rationale. In engineering practice—whether building your own training framework or deploying models using compute and inference services from general-purpose cloud platforms—a deep understanding of MHA helps developers make better decisions on model selection, performance tuning, and cost control. Mastering MHA is also the key to understanding cutting-edge architectural optimizations like GQA and sliding window attention.