AI Logic

Attention Mechanisms

Multi-Head Attention

Updated:

Structure of multi-head attention. Left: the overall flow (Q, K, V are projected by per-head linear layers, scaled dot-product attention is computed h times, the results are concatenated and passed through a linear layer). Right: each head's N × N attention matrix, showing that every query-key pair is computed

What is multi-head attention

Multi-head attention is a mechanism that replaces one large attention with hh small attentions (heads) computed on short vectors, and concatenates their results. It was proposed by Vaswani et al. in 2017 in the Transformer paper "Attention Is All You Need", and nearly every Transformer-based model, including BERT, GPT, and ViT, uses this form.

The formula is as follows (Section 3.2.2 of the paper).

MultiHead(Q,K,V)=Concat(head1,…,headh) WO\mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^O headi=Attention(QWiQ, KWiK, VWiV)\mathrm{head}_i = \mathrm{Attention}(Q W_i^Q,\ K W_i^K,\ V W_i^V)
  • Attention\mathrm{Attention}: scaled dot-product attention, softmax(QK⊤/dk) V\mathrm{softmax}(QK^\top / \sqrt{d_k})\,V.
  • WiQ,WiKW_i^Q, W_i^K: the linear-layer weights of head ii (dmodel×dkd_{\text{model}} \times d_k). WiVW_i^V is dmodel×dvd_{\text{model}} \times d_v.
  • WOW^O: the weights of the linear layer that maps the concatenated result back to the original size (hdv×dmodelh d_v \times d_{\text{model}}).

Think of it this way: rather than one judge evaluating every aspect (grammar, meaning, word order) at once, hh judges each responsible for one aspect evaluate separately and then combine their opinions, which picks up finer differences. Each head projects the input into "its own aspect's space" with its own linear layers before computing attention.

In the figure at the top of the article, the left side shows the overall flow and the right side shows the attention matrix. Multi-head attention computes the N×NN \times N matrix for all pairs in every head.

Computation steps

Let NN be the sequence length and dmodeld_{\text{model}} the vector size. The paper uses dmodel=512d_{\text{model}} = 512, h=8h = 8 heads, and a per-head vector size of dk=dv=dmodel/h=64d_k = d_v = d_{\text{model}} / h = 64. The computation proceeds bottom-up as follows (in the same order as the right side of Figure 2 in the paper).

  1. Per-head linear projection: multiply the inputs Q,K,VQ, K, V (each N×dmodelN \times d_{\text{model}}) by head ii's weights WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V to get N×64N \times 64 matrices.
  2. Per-head attention: compute scaled dot-product attention on the projected Q,K,VQ, K, V.
    • Each head produces an N×NN \times N weight matrix, and its output is N×dvN \times d_v.
    • The hh heads are independent of each other, so they can be computed in parallel.
  3. Concatenation: place the hh outputs side by side into an N×hdvN \times h d_v matrix (N×512N \times 512 in the paper).
  4. Linear projection: multiply by WOW^O to return to N×dmodelN \times d_{\text{model}}.

Because the input and output of steps 1 to 4 have the same shape (N×dmodelN \times d_{\text{model}}), the Transformer can add the input directly to the output as a residual connection.

Depending on where Q,K,VQ, K, V come from, the Transformer uses it in three ways (Section 3.2.3 of the paper).

Where it is usedQQK,VK, VRange attended
Encoder self-attentionPrevious layer's outputPrevious layer's output (same as QQ)All positions of the input sentence
Decoder self-attentionPrevious layer's outputPrevious layer's output (same as QQ)Only earlier positions (hidden by a mask)
Encoder-decoder attentionDecoder sideEncoder outputAll positions of the input sentence

Why split into heads

The reason for splitting into heads is that a single attention takes a weighted average, so different kinds of relationships get mixed and become hard to tell apart. The paper states that with a single head, "averaging inhibits" jointly attending to information from different representation subspaces at different positions.

The output of attention is a weighted average of the values. If a single head tries to attend to both "the subject's position" and "the previous word", its weights are split between two places and the output is a blend of the two values. With separate heads, head 1 can concentrate its weights on the subject and head 2 on the previous word, and the linear layer WOW^O after concatenation can combine both pieces of information. The figures in the paper's appendix also show heads learning different behaviors, such as relationships between distant words or the word a pronoun refers to.

Adding heads barely increases compute or parameters, because as the number of heads hh grows, each head's vector size shrinks to dk=dmodel/hd_k = d_{\text{model}} / h.

  • Parameters: the WQW^Q part consists of hh matrices of size dmodel×dkd_{\text{model}} \times d_k, totaling dmodel×dmodeld_{\text{model}} \times d_{\text{model}}. The same holds for K,V,OK, V, O, so the total is 4dmodel24 d_{\text{model}}^2 (about 1.05 million for dmodel=512d_{\text{model}} = 512, excluding biases), independent of the number of heads.
  • Compute: computing QK⊤QK^\top costs N2dkN^2 d_k per head, or N2dmodelN^2 d_{\text{model}} for all hh heads — the same as computing one attention with vector size dmodeld_{\text{model}}.

In practice, implementations do not hold hh separate linear layers; they apply one dmodel×dmodeld_{\text{model}} \times d_{\text{model}} linear layer and then split the result into hh pieces. This is mathematically the same computation, and it is faster because the GPU can do it as one large matrix multiplication. PyTorch's nn.MultiheadAttention also takes this form.

Experimental results

The paper compares different numbers of heads hh and per-head sizes dk,dvd_k, d_v while keeping compute constant (English-to-German translation, development set newstest2013, rows (A) of Table 3). Lower perplexity and higher BLEU are better.

Heads hhdk=dvd_k = d_vPerplexityBLEU
15125.2924.9
41285.0025.5
8 (base)644.9225.8
16324.9125.8
32165.0125.4

The results show the following.

  • A single head is clearly worse: BLEU is 0.9 lower than the best setting.
  • Too many heads also hurts: with h=32h = 32, each head's dkd_k shrinks to 16 and BLEU drops.

Rows (B) of the same table also show that reducing only dkd_k to 16 or 32 lowers performance. The paper suggests that determining compatibility between keys and queries is not easy, and that making each head's vectors too short leaves them unable to represent it.

Practical considerations

Because each head of multi-head attention builds an N×NN \times N weight matrix, it becomes heavy for long sequences.

The weight matrix is N×NN \times N per head. With batch size BB, one layer holds B×h×N×NB \times h \times N \times N values. Doubling the sequence length quadruples the memory, so for long documents or high-resolution images, this is the first thing to run out.

Watch for the following in implementations.

  • dmodeld_{\text{model}} must be divisible by the number of heads: in PyTorch's nn.MultiheadAttention(embed_dim, num_heads), an error is raised if embed_dim is not divisible by num_heads.
  • The default input layout is "sequence first": batch_first defaults to False, and inputs are interpreted in the order (Nseq,B,d)(N_{\text{seq}}, B, d). Specify batch_first=True when passing (B,N,d)(B, N, d).
  • The meaning of boolean masks is reversed between functions: in nn.MultiheadAttention, attn_mask hides positions that are True. In F.scaled_dot_product_attention, attn_mask allows positions that are True.
  • Returning weights makes fast implementations less likely to be used: need_weights defaults to True, which also returns the weights (averaged over heads by default). When the weights are not needed, setting need_weights=False lets PyTorch use the optimized scaled_dot_product_attention.

When passing a boolean attn_mask to nn.MultiheadAttention, True means "do not attend". If you pass the same mask unchanged when switching to F.scaled_dot_product_attention, the allowed and hidden positions are swapped, and only the results change without any error.

Ways to reduce the N×NN \times N cost for long sequences are compared in the next section.

Comparison with other methods

Improvements to multi-head attention fall broadly into those that change "which part of the attention matrix is computed" and those that change "how heads hold keys and values".

Methods that change how the attention matrix is computed

MethodWhich part of the N×NN \times N matrix is computedResultCost (in sequence length NN)
Multi-head attention (Vaswani et al., 2017)All pairsExactO(N2)O(N^2)
Sparse attention (Child et al., 2019)Only a predefined subset of pairsSome pairs skippedO(NN)O(N\sqrt{N})
Linear attention (Katharopoulos et al., 2020)No matrix is built (the order of computation is changed)Softmax is replaced by another functionO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs, but split into small tiles without storing the full matrix in memoryExact (same values)O(N2)O(N^2) compute, O(N)O(N) extra memory

Methods that change how keys and values are held

MethodLinear layers for keys and valuesGoal
Multi-head attentionSeparate for each headExpressiveness
Multi-query attention (MQA) (Shazeer, 2019)One set shared by all headsFaster token-by-token generation by loading fewer keys and values
Grouped-query attention (GQA) (Ainslie et al., 2023)Heads are split into groups, shared within each groupSpeed close to MQA with quality close to multi-head attention

Rough guidelines for choosing:

  • Sequences up to a few thousand tokens, with exact computation: use multi-head attention as is, and leave the computation to a fast implementation such as FlashAttention. PyTorch's F.scaled_dot_product_attention automatically selects a fast implementation when conditions allow.
  • Very long sequences where the N2N^2 compute itself is the bottleneck: consider methods that reduce the pairs computed, such as sparse attention or linear attention. Note that the results will not match the original attention.
  • Faster inference for text generation: reduce the amount of keys and values with MQA or GQA.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


class MultiHeadAttention(nn.Module):
    """Multi-head attention following the paper's formula (h linear layers merged into one large linear layer)"""

    def __init__(self, d_model=512, num_heads=8, dropout=0.1):
        super().__init__()
        assert d_model % num_heads == 0, "d_model must be divisible by the number of heads"
        self.h = num_heads
        self.d_k = d_model // num_heads
        self.w_q = nn.Linear(d_model, d_model)  # W_1^Q, ..., W_h^Q combined
        self.w_k = nn.Linear(d_model, d_model)
        self.w_v = nn.Linear(d_model, d_model)
        self.w_o = nn.Linear(d_model, d_model)  # W^O
        self.dropout = dropout

    def split(self, x):
        # [B, N, d_model] -> [B, h, N, d_k] (split into heads)
        B, N, _ = x.shape
        return x.view(B, N, self.h, self.d_k).transpose(1, 2)

    def forward(self, q, k, v, is_causal=False):
        q, k, v = self.split(self.w_q(q)), self.split(self.w_k(k)), self.split(self.w_v(v))
        # Per-head scaled dot-product attention. Apply dropout only during training
        # (F.scaled_dot_product_attention ignores model.eval(), so set it to 0 yourself)
        out = F.scaled_dot_product_attention(
            q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal
        )
        B, _, N, _ = out.shape
        out = out.transpose(1, 2).reshape(B, N, self.h * self.d_k)  # concatenate [B, N, h*d_k]
        return self.w_o(out)


x = torch.randn(2, 10, 512)  # [batch, sequence length, d_model]
mha = MultiHeadAttention()
mha.eval()
print(mha(x, x, x, is_causal=True).shape)  # torch.Size([2, 10, 512])

# PyTorch built-in: nn.MultiheadAttention
attn = nn.MultiheadAttention(embed_dim=512, num_heads=8, dropout=0.1, batch_first=True)
# batch_first defaults to False ([sequence, batch, d] order). Set True to pass [batch, sequence, d]
attn.eval()

# In attn_mask, True means "do not attend" (the opposite of F.scaled_dot_product_attention)
causal = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1)
# In key_padding_mask, True marks keys that are padding and hidden [batch, sequence]
pad = torch.zeros(2, 10, dtype=torch.bool)
pad[1, 8:] = True

out, w = attn(x, x, x, attn_mask=causal, key_padding_mask=pad)
print(out.shape, w.shape)  # [2, 10, 512] and [2, 10, 10] (weights are averaged over heads by default)

out, w = attn(x, x, x, attn_mask=causal, need_weights=True, average_attn_weights=False)
print(w.shape)  # [2, 8, 10, 10]: per-head weights

# When weights are not needed, use need_weights=False (allows the fast implementation)
out, w = attn(x, x, x, attn_mask=causal, need_weights=False)
print(w)  # None

FAQ

Q. How many heads should be used?
A.

The paper uses h=8h = 8 (with dk=64d_k = 64 per head) for dmodel=512d_{\text{model}} = 512, which gave the best result, nearly the same as h=16h = 16. With h=1h = 1, BLEU dropped by 0.9, and it also dropped with h=32h = 32 (dk=16d_k = 16). A good rule of thumb is to choose hh so that each head's dkd_k does not become too short (around 64 is common).

Q. Does adding heads increase compute or parameters?
A.

Barely. Since each head's vectors shrink to dmodel/hd_{\text{model}} / h as heads are added, the linear layers still total 4dmodel24 d_{\text{model}}^2 parameters, and the compute for QK⊤QK^\top remains N2dmodelN^2 d_{\text{model}}. However, there is one weight matrix per head, so the memory to store the N×NN \times N matrices is proportional to hh.

Q. How can I see what each head is attending to?
A.

Passing need_weights=True, average_attn_weights=False to PyTorch's nn.MultiheadAttention returns per-head weights (B×h×N×NB \times h \times N \times N). Displaying them as matrices reveals the differences in where each head attends. Methods that trace weights across layers include Attention Rollout.

References

  1. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  2. N. Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need," arXiv:1911.02150, 2019.
  3. J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón, and S. Sanghai, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints," EMNLP, 2023.
  4. PyTorch Documentation, "torch.nn.MultiheadAttention."
  5. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."