Multi-head attention is a mechanism that replaces one large attention with h 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).
WiQ,WiK: the linear-layer weights of head i (dmodel×dk). WiV is dmodel×dv.
WO: the weights of the linear layer that maps the concatenated result back to the original size (hdv×dmodel).
Think of it this way: rather than one judge evaluating every aspect (grammar, meaning, word order) at once, h 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×N matrix for all pairs in every head.
Computation steps
Let N be the sequence length and dmodel the vector size. The paper uses dmodel=512, h=8 heads, and a per-head vector size of dk=dv=dmodel/h=64. The computation proceeds bottom-up as follows (in the same order as the right side of Figure 2 in the paper).
Per-head linear projection: multiply the inputs Q,K,V (each N×dmodel) by head i's weights WiQ,WiK,WiV to get N×64 matrices.
Per-head attention: compute scaled dot-product attention on the projected Q,K,V.
Each head produces an N×N weight matrix, and its output is N×dv.
The h heads are independent of each other, so they can be computed in parallel.
Concatenation: place the h outputs side by side into an N×hdv matrix (N×512 in the paper).
Linear projection: multiply by WO to return to N×dmodel.
Because the input and output of steps 1 to 4 have the same shape (N×dmodel), the Transformer can add the input directly to the output as a residual connection.
Depending on where Q,K,V come from, the Transformer uses it in three ways (Section 3.2.3 of the paper).
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 WO 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 h grows, each head's vector size shrinks to dk=dmodel/h.
Parameters: the WQ part consists of h matrices of size dmodel×dk, totaling dmodel×dmodel. The same holds for K,V,O, so the total is 4dmodel2 (about 1.05 million for dmodel=512, excluding biases), independent of the number of heads.
Compute: computing QK⊤ costs N2dk per head, or N2dmodel for all h heads — the same as computing one attention with vector size dmodel.
In practice, implementations do not hold h separate linear layers; they apply one dmodel×dmodel linear layer and then split the result into h 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 h and per-head sizes dk,dv while keeping compute constant (English-to-German translation, development set newstest2013, rows (A) of Table 3). Lower perplexity and higher BLEU are better.
Heads h
dk=dv
Perplexity
BLEU
1
512
5.29
24.9
4
128
5.00
25.5
8 (base)
64
4.92
25.8
16
32
4.91
25.8
32
16
5.01
25.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=32, each head's dk shrinks to 16 and BLEU drops.
Rows (B) of the same table also show that reducing only dk 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×N weight matrix, it becomes heavy for long sequences.
The weight matrix is N×N per head. With batch size B, one layer holds B×h×N×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.
dmodel 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). Specify batch_first=True when passing (B,N,d).
The meaning of boolean masks is reversed between functions: in nn.MultiheadAttention, attn_maskhides positions that are True. In F.scaled_dot_product_attention, attn_maskallows 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×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
Heads are split into groups, shared within each group
Speed 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 N2 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=8 (with dk=64 per head) for dmodel=512, which gave the best result, nearly the same as h=16. With h=1, BLEU dropped by 0.9, and it also dropped with h=32 (dk=16). A good rule of thumb is to choose h so that each head's dk 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/h as heads are added, the linear layers still total 4dmodel2 parameters, and the compute for QK⊤ remains N2dmodel. However, there is one weight matrix per head, so the memory to store the N×N matrices is proportional to h.
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×N). Displaying them as matrices reveals the differences in where each head attends. Methods that trace weights across layers include Attention Rollout.