From Self-Attention to Multi-Head Attention: A Deep Dive into Transformer Core Mechanisms

    This article explains the core attention mechanisms behind the Transformer architecture, starting from the information bottleneck of RNN-based encoder-decoder models. It walks through how self-attention works with queries, keys, and values, why multi-head attention improves representational richness, and how variants like GQA, MQA, and sliding-window attention reduce KV cache overhead in modern large language models. Code examples in PyTorch illustrate the key computations.

    1. Why Attention Mechanisms Emerged

    To understand multi-head attention (MHA), we need to go back to its historical origins. Before the Transformer, the dominant approach to sequence modeling was the recurrent neural network (RNN) with an encoder-decoder structure, typically applied to machine translation.

    1.1 The Bottleneck of Early Architectures

    In the traditional encoder-decoder framework, the workflow looked roughly like this:

    1. The encoder RNN reads the source-language sentence token by token, progressively compressing information into a sequence of hidden states;
    2. In the simplest version, the semantics of the entire sentence are compressed into a single final fixed-length vector;
    3. The decoder RNN generates the target sentence step by step based on this limited “summary.”

    This design works reasonably well for short, simple sentences, but it has a fundamental flaw: the information bottleneck. A fixed-dimensional hidden state cannot store an unlimited amount of context. When the key information needed for a target word lies far away in the input sentence, the decoder can only “guess” from a highly compressed summary, and long-range dependencies are severely diluted during compression.

    1.2 The Core Idea of Attention

    The attention mechanism was proposed precisely to break this bottleneck: instead of forcing the model to squeeze all information into one vector, allow the decoder to look back directly at the entire input sequence when generating each word, assigning different weights to hidden states at different positions based on current needs. This idea of “dynamic weighted lookback” later became the cornerstone of the Transformer architecture.

    2. Self-Attention: Letting Every Token See Every Other Token

    2.1 Basic Principles

    Self-attention allows each token in a sequence to look at all other visible tokens, assign them weights, and use those weights to build a new context-aware representation. The computation breaks down into three steps:

    1. Projection: Multiply the input by three learnable projection matrices to obtain queries (Q), keys (K), and values (V);
    2. Scoring: Compute the dot product of queries and keys to measure relevance between tokens, usually scaled by the square root of the dimension to prevent gradient instability;
    3. Weighted aggregation: Apply softmax normalization to the scores to get attention weights, then take a weighted sum of the value vectors to produce the new contextual representation.

    A simplified implementation looks like this:

    1. import torch
    2. import torch.nn.functional as F
    3. def self_attention(x, W_q, W_k, W_v):
    4. # x: [batch, seq_len, d_model]
    5. Q, K, V = x @ W_q, x @ W_k, x @ W_v
    6. scores = Q @ K.transpose(-2, -1) / (K.size(-1) ** 0.5)
    7. # Causal mask: prevent attending to future tokens
    8. mask = torch.triu(torch.ones(scores.size(-2), scores.size(-1)), 1).bool()
    9. scores = scores.masked_fill(mask, float("-inf"))
    10. return F.softmax(scores, dim=-1) @ V

    In autoregressive language models, a causal mask is also applied to ensure each token can only attend to tokens at or before its own position—this is what “visible tokens” refers to.

    2.2 Advantages of Self-Attention

    Compared with the sequential passing of RNNs, self-attention has two significant advantages:

    • O(1) path length: There is a direct connection between any two tokens, so long-range dependencies no longer decay with distance;
    • High parallelism: The entire sentence can be computed in parallel at once, making it well suited for large-scale training on modern hardware.

    3. Multi-Head Attention: From a Single View to Multiple Views

    3.1 Why Multiple Heads Are Needed

    Single-head attention can only learn one pattern of relevance. But relationships in language are multidimensional: some heads attend to syntactic dependencies, some to coreference resolution, and some to local adjacent words. The solution of multi-head attention (MHA) is to run multiple self-attention heads with different learned projections in parallel. Each head independently models a different type of dependency in a lower-dimensional subspace, and the outputs of all heads are then concatenated and passed through a linear transformation to fuse them into a richer representation.

    3.2 Computation Flow

    1. class MultiHeadAttention(torch.nn.Module):
    2. def __init__(self, d_model, num_heads):
    3. super().__init__()
    4. self.h = num_heads
    5. self.d_head = d_model // num_heads
    6. self.W_q = torch.nn.Linear(d_model, d_model, bias=False)
    7. self.W_k = torch.nn.Linear(d_model, d_model, bias=False)
    8. self.W_v = torch.nn.Linear(d_model, d_model, bias=False)
    9. self.W_o = torch.nn.Linear(d_model, d_model, bias=False)
    10. def forward(self, x, mask=None):
    11. B, T, _ = x.shape
    12. q = self.W_q(x).view(B, T, self.h, self.d_head).transpose(1, 2)
    13. k = self.W_k(x).view(B, T, self.h, self.d_head).transpose(1, 2)
    14. v = self.W_v(x).view(B, T, self.h, self.d_head).transpose(1, 2)
    15. scores = q @ k.transpose(-2, -1) / self.d_head ** 0.5
    16. if mask is not None:
    17. scores = scores.masked_fill(mask, float("-inf"))
    18. out = (F.softmax(scores, dim=-1) @ v).transpose(1, 2).reshape(B, T, -1)
    19. return self.W_o(out)

    The key point is that multiple heads do not add much computation (each head has a smaller dimension), yet they significantly increase the diversity of the representation.

    4. The Evolution of Attention Mechanisms

    MHA is the standard form, but in the era of large models, the memory overhead of the KV cache during inference is enormous. The industry has therefore developed a series of variants:

    • Grouped-Query Attention (GQA): Multiple query heads share the same set of key-value heads, greatly compressing the KV cache. It is a common choice in today’s mainstream large models;
    • Sliding-window attention: Restricts each token to attending only to neighbors within a local window, reducing the cost of long-sequence attention from quadratic to linear;
    • Multi-Query Attention (MQA): An extreme form of GQA where all query heads share a single set of key-value heads, further saving memory but potentially sacrificing accuracy.

    The shared design philosophy of these variants is: reduce redundant key-value storage while preserving representational capacity. Once you understand the Q/K/V structure of standard MHA, these variants are simply different sharing strategies across heads—the underlying principles carry over directly.

    5. Summary

    The attention mechanism emerged from reflections on the RNN information bottleneck. Self-attention solves the long-range dependency problem through “dynamic weighted lookback,” and multi-head attention enriches representations through parallel multi-perspective modeling. From GPT-2 to recent open-source 7B-scale models, MHA and its variants such as GQA and sliding-window attention form the core components of large model architectures. For developers, a solid understanding of these mechanisms is essential for reading model structures and performing inference optimization and memory tuning. In practice, when using cloud-based large model services or GPU computing platforms to deploy self-trained models, the KV cache strategy of the attention module is often the first place to look for performance optimization.