Self-Attention and Multiple Heads

Dive into Deep Learning · §10.3

Self-Attention, Multi-Head Attention, and Key–Value Sharing
self-attention · single-head mixture bottleneck · parallel subspace heads · FLOP & parameter counts · GQA & MQA

Why One Sequence Must Query Itself in Multiple Ways

Motivation

  • Multiple Syntactic Arguments: In “Alice gave Bob the book”, interpreting the verb gave requires identifying the giver (Alice), the recipient (Bob), and the object (book).
  • The Single-Head Bottleneck: A single attention head computes one probability distribution per query and returns a single blended vector (64 floats in GPT-2 small), averaging all attended arguments together.
  • Parallel Subspace Heads: Running H independent lookups in parallel lets a token retrieve multiple distinct arguments simultaneously.

Self-Attention: Three Learned Projections per Token

Self-Attention Formulation

  • Three Distinct Roles from One Input \mathbf{X} \in \mathbb{R}^{n \times d}: \textrm{SelfAttention}(\mathbf{X}) = \mathrm{softmax}\!\left(\frac{(\mathbf{X}\mathbf{W}_q)(\mathbf{X}\mathbf{W}_k)^\top}{\sqrt{d_h}}\right)\mathbf{X}\mathbf{W}_v
  • Query (\mathbf{q}_i = \mathbf{x}_i \mathbf{W}_q): What contextual features position i seeks.
  • Key (\mathbf{k}_j = \mathbf{x}_j \mathbf{W}_k) & Value (\mathbf{v}_j = \mathbf{x}_j \mathbf{W}_v): What position j advertises and what content vector it returns when selected.

Why Queries and Keys Require Separate Matrices

Asymmetry of Lookup

  • Symmetric PSD Trap (\mathbf{W}_q = \mathbf{W}_k = \mathbf{W}): Setting \mathbf{u}_i = \mathbf{x}_i \mathbf{W} makes the score matrix s_{ij} = \mathbf{u}_i^\top \mathbf{u}_j / \sqrt{d_h} symmetric and positive semidefinite.
  • Cauchy–Schwarz Self-Affinity Bound: s_{ij} \le \sqrt{s_{ii}\,s_{jj}}
  • Linguistic Failure Mode: Scores are symmetric (s_{ij} = s_{ji}), and since s_{ij} \le \max(s_{ii}, s_{jj}) a verb and a noun can never each prefer the other over itself. Separate \mathbf{W}_q \neq \mathbf{W}_k remove both limits.

Worked Example: One Head on a Five-Word Sentence

Tracing Self-Attention

Represent each word of “Alice gave Bob the book” by a 9\text{D} vector concatenating a 4\text{D} one-hot grammatical role and a 5\text{D} one-hot word indicator, with head width d_h = 2:

Token(s) Grammatical Role Query \mathbf{x}_i\mathbf{W}_q Key \mathbf{x}_i\mathbf{W}_k
Alice, Bob Person (1, -1) (1, 1)
gave Action (verb) (1, 1) (1, -1)
book Thing (1, -1) (1, 1)
the Function word (0, 0) (0, 0)
  • Scoring gave: Its query (1, 1) has dot product 2 with each noun’s key (1, 1) and 0 with gave and the.
  • Scaling & Softmax: Dividing by \sqrt{2} gives scores 1.41 on the three nouns and 0 elsewhere, yielding weights e^{1.41}/(3e^{1.41}+2) \approx \mathbf{0.29} per noun and \mathbf{0.07} on gave and the.

Visualizing One Head on ‘Alice gave Bob the book’

Geometry & Causal Masking

One head of self-attention scoring “gave” against all five words.

Computing One Head on ‘Alice gave Bob the book’

Geometry & Causal Masking

scores of gave:  [1.41 0.   1.41 0.   1.41]
weights of gave: [0.29 0.07 0.29 0.07 0.29]
weights of the:  [0.2 0.2 0.2 0.2 0.2]
output of gave:  [0.29 0.07 0.29 0.07 0.29]
causal weights of gave: [0.8 0.2 0.  0.  0. ]

The Single-Head Bottleneck: The Copy-Both Task

Information-Theoretic Limit

In our sentence, gave received an equal blend 0.29\,\mathbf{v}_{\textrm{Alice}} + 0.29\,\mathbf{v}_{\textrm{Bob}} + 0.29\,\mathbf{v}_{\textrm{book}}. To quantify why one head cannot disentangle multiple arguments, define the copy-both task:

  • Setup: Two source positions hold independent Gaussian values \mathbf{v}_1, \mathbf{v}_2 \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_{d_v}) with fixed position-only keys; one query must output \mathbf{t} = [\mathbf{v}_1; \mathbf{v}_2] \in \mathbb{R}^{2d_v} via a linear readout.
  • One-Mixture Bottleneck: Because keys are fixed, a single head assigns fixed weights (\alpha_1, \alpha_2) and hands the readout only one d_v-dimensional vector \mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2.

One head produces a single blended mixture; two heads supply two independent mixtures.

Theorem: Any Single Head Loses Half the Variance

Lower Bound Proof

  • Optimal Bayes Estimator: Given \mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2, the minimum MSE estimator of \mathbf{v}_1 is \mathbb{E}[\mathbf{v}_1 \mid \mathbf{m}] = \frac{\alpha_1}{\alpha_1^2 + \alpha_2^2}\,\mathbf{m}, leaving residual variance \frac{\alpha_2^2}{\alpha_1^2 + \alpha_2^2}.
  • Conservation of Error: Estimating \mathbf{v}_2 leaves residual variance \frac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2}; their sum is 1 out of target variance 2, giving relative MSE 1/2 (RMS error \sqrt{1/2} \approx 0.707) for every (\alpha_1, \alpha_2).
  • Two Heads Invert Exactly: Two distinct weightings form an invertible 2 \times 2 mixing matrix.

Two Heads Invert the Mixture to Machine Precision

Empirical Verification

Two heads with distinct weightings (even soft ones like (0.88, 0.12) and (0.12, 0.88)) supply two linearly independent mixtures [\mathbf{m}_1; \mathbf{m}_2] \in \mathbb{R}^{2d_v} that a linear readout inverts to float32 precision:

one head, weights (0.70, 0.30): relative error 0.709; sqrt(1/2) = 0.707
two heads, weights (1.00, 0.00) and (0.00, 1.00): relative error 1.5e-06
two heads, weights (0.88, 0.12) and (0.12, 0.88): relative error 7.0e-07

Recovering k independent d_v-dimensional values requires two resources simultaneously: (1) at least k linearly independent attention weightings (\operatorname{rank}(\mathbf{A}) = k), and (2) at least k\,d_v total output coordinates (room).

Multi-Head Attention: Parallel Subspace Lookups

Multi-Head Architecture

  • Subspace Projections (i = 1, \ldots, H): Each head i projects \mathbf{X} \in \mathbb{R}^{n \times d} into width d_h = d/H via \mathbf{W}_i^{(q)}, \mathbf{W}_i^{(k)}, \mathbf{W}_i^{(v)} \in \mathbb{R}^{d \times d_h}: \mathbf{Z}_i = \mathrm{softmax}\!\left(\frac{(\mathbf{X}\mathbf{W}_i^{(q)})(\mathbf{X}\mathbf{W}_i^{(k)})^\top}{\sqrt{d_h}}\right)\mathbf{X}\mathbf{W}_i^{(v)}
  • Concatenation & Output Projection: Concatenate all H head outputs into n \times H d_h and mix across heads with \mathbf{W}_o \in \mathbb{R}^{H d_h \times d}: \textrm{MHA}(\mathbf{X}) = [\mathbf{Z}_1, \ldots, \mathbf{Z}_H]\,\mathbf{W}_o \in \mathbb{R}^{n \times d}

Multi-head attention runs H parallel subspace lookups and projects their concatenated outputs.

Parameter and FLOP Counts Are Independent of H

Computational Complexity

  • Leading Complexity (with d_h = d / H): \textrm{Params} = 4d^2, \qquad \textrm{FLOPs} = 8nd^2 + 4n^2 d
  • GPT-2 Small Layer (d = 768, n = 1{,}024): 2.36\text{M} parameters, 4.83\text{ GFLOPs} for projections, and 3.22\text{ GFLOPs} for scores and value mixing—identical whether H = 1 or H = 12.
  • Why Not H = d (d_h = 1)? At d_h = 1, scalar scores q_i k_j are monotone in k_j, so queries can only sharpen onto extremal keys.

Comparing Convolution, Recurrence, and Attention

Sequence Layer Taxonomy

Layer Type FLOP Complexity Sequential Steps Max Path Length
1D Conv (kernel k) O(knd^2) O(1) O(n/k)
Recurrence (RNN) O(nd^2) O(n) O(n)
Self-Attention O(nd^2 + n^2d) O(1) O(1)
  • Self-attention achieves both O(1) parallel training depth and O(1) direct token-to-token path length; its 4n^2d term overtakes 8nd^2 only when n > 2d.

Connectivity, path length, and parallelism of convolution, recurrence, and self-attention.

Vectorizing Heads via Tensor Reshape and Transpose

Batched Head Axis

  • Instead of launching H separate matrix multiplications in a Python loop, we project all heads at once into (batch, n, H * d_h).
  • split_heads: Reshapes the feature axis into (batch, n, H, d_h) and transposes axes 1 and 2 to (batch, H, n, d_h) so H acts as a batch dimension.
  • merge_heads: Swaps axes 1 and 2 back and flattens (H, d_h) to H * d_h before \mathbf{W}_o.

Splitting a projected (n, d) tensor into H heads of width d_h = d/H.

Implementing MultiHeadAttention

Module Implementation

One module covers multi-head (num_kv_heads = num_heads) and grouped-query attention (num_kv_heads < num_heads). The constructor sizes the key and value projections for num_kv_heads:

class MultiHeadAttention(nn.Module):
    """Multi-head attention with heads as an explicit axis; num_kv_heads <
    num_heads shares each key-value head across a group of query heads."""
    def __init__(self, num_hiddens, num_heads, dropout=0.0, bias=False,
                 num_kv_heads=None):
        super().__init__()
        assert num_hiddens % num_heads == 0, 'heads must divide num_hiddens'
        self.num_heads = num_heads
        self.num_kv_heads = num_kv_heads or num_heads
        assert num_heads % self.num_kv_heads == 0
        kv_hiddens = self.num_kv_heads * (num_hiddens // num_heads)
        self.attention = d2l.DotProductAttention(dropout)
        self.W_q = nn.Linear(num_hiddens, num_hiddens, bias=bias)
        self.W_k = nn.Linear(num_hiddens, kv_hiddens, bias=bias)
        self.W_v = nn.Linear(num_hiddens, kv_hiddens, bias=bias)
        self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)

Implementing MultiHeadAttention (cont.)

Module Implementation

The forward pass splits heads, repeats each key–value head across its query group, and attends:

    def forward(self, queries, keys, values, mask=None):
        # queries: (batch, no. of queries, num_hiddens); keys and values:
        # (batch, no. of key-value pairs, num_hiddens). mask: boolean,
        # broadcastable to (batch, no. of queries, no. of keys), shared by
        # all heads, or to (batch, num_heads, no. of queries, no. of keys)
        q = self.split_heads(self.W_q(queries), self.num_heads)
        k = self.split_heads(self.W_k(keys), self.num_kv_heads)
        v = self.split_heads(self.W_v(values), self.num_kv_heads)
        group = self.num_heads // self.num_kv_heads
        k, v = k.repeat_interleave(group, 1), v.repeat_interleave(group, 1)
        if mask is not None and mask.dim() == 3:
            mask = mask[:, None]           # The same mask for every head
        # Shape of Y: (batch, num_heads, no. of queries, head width)
        Y = self.attention(q, k, v, mask)
        return self.W_o(self.merge_heads(Y))

    @property
    def attention_weights(self):
        """Weights of the last call: (batch, num_heads, queries, keys)."""
        return self.attention.attention_weights

Pitfall: Reshaping Directly to (B, H, n, d_h)

Silent Tensor Bug

  • Correct (reshape, then swap axes 1 and 2): Splits each token’s d-vector into H blocks of width d_h.
  • Buggy (X.reshape(B, H, n, d_h)): Because memory is row-major along the sequence axis n, reshaping directly packs the first n/H tokens into “head 0”.
  • Insidious Shape Match: Both return (B, H, n, d_h), so no shape check catches the bug.
def split_heads(self, X, num_heads):
    """(batch, length, num_heads * width) -> (batch, num_heads, length,
    width)."""
    return X.reshape(X.shape[0], X.shape[1], num_heads, -1).transpose(1, 2)

def merge_heads(self, X):
    """Reverse split_heads: (batch, num_heads, length, width) -> (batch,
    length, num_heads * width)."""
    return X.transpose(1, 2).reshape(X.shape[0], X.shape[2], -1)

Trained Multi-Head Layers on the Copy-Both Task

Empirical Verification

We train MultiHeadAttention (d = 16, values d_v = 8 padded to 16, all models having 4 \times 16^2 = 1{,}024 parameters) for 2{,}000 Adam steps on the copy-both task:

H  run  parameters  error    weight on v_1, per head
1    1        1024  0.71     0.51
1    2        1024  0.71     0.52
2    1        1024  1.1e-07  0.98 0.12
2    2        1024  1.1e-07  0.93 0.03
4    1        1024  1.1e-07  0.96 0.94 0.16 0.12
4    2        1024  1.2e-07  0.04 0.26 0.88 0.95
  • H = 1 Head: Stalls at relative error 0.71 \approx \sqrt{1/2} with attention weights near (0.50, 0.50), matching our theorem.
  • H \in \{2, 4\} Heads: Specialize automatically (one head places > 0.80 weight on \mathbf{v}_1 while another places < 0.20 on \mathbf{v}_1), driving relative error down to float32 rounding (\sim 10^{-7}).

Grouped-Query (GQA) and Multi-Query Attention (MQA)

Key–Value Head Sharing

  • The Generation Bottleneck: Autoregressive decoding caches past keys and values in GPU memory (2 \cdot H \cdot d_h floats per token per layer).
  • GQA (H_{\textrm{kv}} < H) and MQA (H_{\textrm{kv}} = 1): Share each key–value head across a group of H / H_{\textrm{kv}} query heads, cutting the KV cache by H / H_{\textrm{kv}} (e.g., 36\text{ KiB} \to 12\text{ KiB}/token in 16-bit GPT-2 small when 12 \to 4).
  • Subspace Capacity Condition: Shared value heads span H_{\textrm{kv}} d_h coordinates per token, so copying d_v-dimensional values requires H_{\textrm{kv}} d_h \ge d_v:

MHA, GQA, and MQA key–value head sharing topologies.

Testing Key–Value Head Sharing on Copy-Both

GQA & MQA Experiments

Evaluating (H, H_{\textrm{kv}}) \in \{(2, 1), (4, 2), (4, 1)\} with d = 16 and d_v = 8 verifies the subspace capacity threshold H_{\textrm{kv}} d_h \ge d_v:

H  H_kv  run  parameters  error    weight on v_1, per head
2     1    1         768  1.1e-07  0.93 0.03
2     1    2         768  1.1e-07  0.03 0.96
4     2    1         768  1.1e-07  0.08 0.95 0.98 0.08
4     2    2         768  1.1e-07  0.03 0.88 0.02 0.88
4     1    1         640  0.71     0.97 0.04 0.13 0.89
4     1    2         640  0.71     0.03 0.04 0.72 0.98
  • Sufficient Value Width ((2, 1) and (4, 2)): Both have H_{\textrm{kv}} d_h = 8 = d_v and solve the copy-both task to machine precision (\sim 10^{-7}) using only 768 parameters instead of 1{,}024.
  • Value Bottleneck ((4, 1)): Has four query heads (four distinct weightings) but only H_{\textrm{kv}} d_h = 1 \times 4 = 4 < 8 shared value coordinates, returning to the 0.71 error bound.

Self-Attention vs. Cross-Attention

Input Routing

  • Self-Attention (attention(X, X, X)): Queries, keys, and values all come from the same sequence \mathbf{X} \in \mathbb{R}^{n \times d}, producing an n \times n score matrix.
  • Cross-Attention (attention(A, B, B)): Queries come from target \mathbf{A} \in \mathbb{R}^{n \times d} while keys and values come from source \mathbf{B} \in \mathbb{R}^{m \times d}, producing an n \times m score matrix.
  • Source Permutation Invariance: In unmasked cross-attention, permuting rows of \mathbf{B} \mapsto \boldsymbol{\Pi}\mathbf{B} leaves the output at every query of \mathbf{A} unchanged.

Concept Check: Heads, FLOPs, and GQA Capacity

Check Your Understanding

Test your understanding of multi-head scaling and capacity bounds:

  1. FLOP Crossover: For a layer with hidden width d = 4{,}096 and H = 32 heads (d_h = 128), at what sequence length n does the quadratic score-and-mix FLOP count (4n^2 d) equal the linear QKVO projection FLOP count (8nd^2)? Does changing H to 64 alter this crossover?
  2. General k-Value Copy Bound: If a single query uses H heads with fixed attention weight matrix \mathbf{A} \in \mathbb{R}^{H \times k} to retrieve k independent Gaussian values [\mathbf{v}_1; \ldots; \mathbf{v}_k], what is the minimum relative squared error?
  3. Word-Order Invariance: If we swap Alice and Bob to form “Bob gave Alice the book”, does the unmasked self-attention output at gave change with H = 12 heads?

Answers:

  1. n = 2d = 8{,}192 tokens (4n^2d = 8nd^2 \iff n = 2d). Changing H to 64 leaves both leading FLOP counts and the crossover unchanged.
  2. 1 - \operatorname{rank}(\mathbf{A}) / k (provided the output has room H d_h \ge k d_v); for H = 1 and k = 2, \operatorname{rank}(\mathbf{A}) = 1 gives 1 - 1/2 = 1/2.
  3. No. Swapping two tokens permutes their keys and values together across every head, so the weighted sum at gave is identical—motivating positional encodings (§10.4).

Summary: Self-Attention and Multiple Heads

Key Takeaways

Concept / Variant Mathematical Form / Dimension Parameters & FLOPs Key Capability / Bottleneck
Single Head (H=1) \mathrm{softmax}\!\left(\frac{\mathbf{X}\mathbf{W}_q(\mathbf{X}\mathbf{W}_k)^\top}{\sqrt{d_h}}\right)\mathbf{X}\mathbf{W}_v 3d d_h params; O(nd d_h + n^2 d_h) Forms 1 mixture per query; \ge 1/2 MSE on 2-value copy
Separate \mathbf{W}_q \neq \mathbf{W}_k Asymmetric score matrix \mathbf{Q}\mathbf{K}^\top Decouples query and key subspaces Escapes the PSD bound s_{ij} \le \sqrt{s_{ii}s_{jj}} of shared maps
Multi-Head (MHA) [\mathbf{Z}_1, \ldots, \mathbf{Z}_H]\mathbf{W}_o, d_h = d/H 4d^2 params; 8nd^2 + 4n^2d FLOPs H distinct mixtures per query at H-independent cost
Grouped-Query (GQA) H query heads share H_{\textrm{kv}} KV heads (2 + 2 H_{\textrm{kv}}/H)d^2 params Cuts generation KV cache by H/H_{\textrm{kv}}; needs H_{\textrm{kv}}d_h \ge d_v
Multi-Query (MQA) All H query heads share H_{\textrm{kv}} = 1 KV head (2 + 2/H)d^2 params Maximum H\times KV-cache reduction
Cross-Attention attention(A, B, B) (n queries, m keys) O((n+m)d^2 + nmd) FLOPs Routes information from source \mathbf{B} to target \mathbf{A}