By Sagi Shaier · 10 November 2026 · 11 min read
Multi-head attention explained
Why transformers split attention into several heads and how the code reshapes queries, keys and values into heads and joins them back, with small worked numbers and a full PyTorch module.
Multi-head attention runs several smaller self-attention computations side by side on the same sequence and then joins their outputs into one. In a transformer layer, the attention block is usually multi-head self-attention. Each smaller computation is called a head. The heads' outputs are placed side by side and mixed by one more learned matrix, so the result has the same size as the input. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens.

One head gives one weighting pattern
A single head is ordinary self-attention. It takes the token vectors $X$ of the sequence, with one row per token. It makes queries, keys and values from them with three learned matrices:
$$Q = XW_Q \qquad K = XW_K \qquad V = XW_V$$
It then scores every query against every key, turns each row of scores into weights with softmax and blends the value vectors with those weights:
$$\text{head} = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$
Here $d_k$ is the number of features in each query and key vector. One head gives each position one learned way to score, weight and combine the value vectors of the sequence. Self-attention explained step by step works through every piece of this formula with numbers.

Why use more than one head
A token can need several kinds of information at the same time. Take the sentence the cute axolotl and the output position for axolotl. One head might put most of its weight on the adjective:
$$[\text{the}: 0.05,\quad \text{cute}: 0.80,\quad \text{axolotl}: 0.15]$$
Another head might use a broader mix of the phrase:
$$[\text{the}: 0.25,\quad \text{cute}: 0.35,\quad \text{axolotl}: 0.40]$$
One head produces one set of weights per position, so it cannot do both. Multi-head attention gives each head its own learned query, key and value projections. Each head can then learn a different way to weight and combine the value vectors.
Splitting the features into heads
The running example is the same three-token sentence with 6 features per token:
$$X = \begin{bmatrix} 1 & -1 & 2 & 0 & 1 & -2 \\ 0 & 2 & -1 & 1 & -3 & 1 \\ 2 & 1 & 0 & -1 & 1 & 3 \end{bmatrix}$$
$X$ has shape $T \times d_{model} = 3 \times 6$. $T$ is the number of tokens and $d_{model}$ is the number of features per token, called the model width. Real models use widths in the hundreds or thousands, and 6 keeps the arithmetic small.

The common setup keeps the total width the same and splits it between the heads. With $H$ heads, each head works with $D_h$ features, also written head_dim:
$$D_h = \frac{d_{model}}{H} = \frac{6}{2} = 3$$
Two heads of 3 features cover all 6, since $H \times D_h = d_{model}$. Multi-head attention does not make the output twice as wide. It splits the width into smaller heads and joins them back at the end. The split has to be even, so a width of 10 cannot be shared equally by 3 heads.

Each head has its own projections
The clearest way to picture it is one set of matrices per head. Head 1 has $W_{Q1}$, $W_{K1}$ and $W_{V1}$. Head 2 has $W_{Q2}$, $W_{K2}$ and $W_{V2}$. Each maps the 6 input features down to 3:
$$W_{Q1} \in \mathbb{R}^{6 \times 3} \qquad Q_{\text{head 1}} = XW_{Q1} \in \mathbb{R}^{3 \times 3}$$
The same goes for the keys and values, and again for head 2. Stacked together, the query matrices of all heads form one block of shape heads by input features by head features:
$$W_Q \in \mathbb{R}^{H \times d_{model} \times D_h} = \mathbb{R}^{2 \times 6 \times 3}$$
Each head then runs scaled dot-product attention on its own queries, keys and values. The scaling uses $\sqrt{D_h}$, the size of the head's own queries and keys.

The code path: one projection, then reshape
Code usually builds all heads and all three projections as one nn.Linear layer. Its output has 3 times the model width:
1self.qkv_proj = nn.Linear(
2 in_features=d_model,
3 out_features=3 * d_model,
4)For the running example that is $3 \times 6 = 18$ features per token. With a batch of $B$ sequences, $x$ of shape $(B, 3, 6)$ becomes qkv of shape $(B, 3, 18)$. Those 18 features hold the queries, keys and values for both heads.

chunk splits the last axis into three equal pieces, one each for q, k and v:
1qkv = self.qkv_proj(x)
2q, k, v = qkv.chunk(3, dim=-1)Each piece has shape $(B, 3, 6)$, the full model width.

view then reads the last axis of 6 features as 2 groups of 3, one group per head. Features 1 to 3 belong to head 1 and features 4 to 6 to head 2:
1q = q.view(batch, seq_len, num_heads, head_dim)
2k = k.view(batch, seq_len, num_heads, head_dim)
3v = v.view(batch, seq_len, num_heads, head_dim)The shape goes from $(B, 3, 6)$ to $(B, T, H, D_h) = (B, 3, 2, 3)$: batch, sequence positions, heads and features per head.

Attention compares positions within one head, so the code moves the head axis in front of the token axis:
1q = q.transpose(1, 2)
2k = k.transpose(1, 2)
3v = v.transpose(1, 2)The shape changes from $(B, T, H, D_h)$ to $(B, H, T, D_h)$. Each head now holds its own small sequence of query, key and value vectors. The numbers themselves do not change, and PyTorch can run the attention of every head in one batched operation.

Attention inside each head
With q, k and v of shape $(B, H, T, D_h)$, the score line is the same as in single-head attention:
1scores = q @ k.transpose(-2, -1)The matrix product works on the last two axes and treats the batch and head axes as separate copies. The scores have shape $(B, H, T, T)$, which is $(B, 2, 3, 3)$ here. Each head gets its own 3 by 3 grid of scores over the sequence.

To see one head at work, look at head 1 for the token the. Suppose head 1 gives the the query $[1, -1, 2]$ and gives the three tokens these keys, one per row:
$$K = \begin{bmatrix} 1 & 1 & 4 \\ 0 & -2 & -2 \\ 2 & -1 & 0 \end{bmatrix}$$
The scores are the dot products of the query with each key:
$$\begin{aligned} [1, -1, 2] \cdot [1, 1, 4] &= 8 \\ [1, -1, 2] \cdot [0, -2, -2] &= -2 \\ [1, -1, 2] \cdot [2, -1, 0] &= 3 \end{aligned}$$
Dividing $[8, -2, 3]$ by $\sqrt{D_h} = \sqrt{3} \approx 1.732$ gives $[4.619, -1.155, 1.732]$. Softmax then gives the weights $[0.944, 0.003, 0.053]$. The head's output for the is $0.944\,v_1 + 0.003\,v_2 + 0.053\,v_3$, where $v_1$, $v_2$ and $v_3$ are head 1's value vectors.
![Head 1, query token the: q_the = [1, -1, 2] dotted with the rows of K gives the raw scores [8, -2, 3]. Scaling by the square root of 3, about 1.732, gives [4.619, -1.155, 1.732], softmax gives [0.944, 0.003, 0.053], and the output is 0.944 V1 + 0.003 V2 + 0.053 V3.](images/mha_head0_tiny_scores.png)
Head 2 has different learned projections, so the same token can get different scores. If head 2 scores the as $[2, 0, -1]$, the scaled scores are $[1.155, 0.000, -0.577]$ and the weights are $[0.670, 0.211, 0.119]$. Head 1 puts almost all its weight on the first position. Head 2 spreads it over all three. Both numbers check out in PyTorch:
1import torch
2
3head1 = torch.tensor([8., -2., 3.])
4head2 = torch.tensor([2., 0., -1.])
5for scores in (head1, head2):
6 scaled = scores / 3 ** 0.5
7 print(scaled.round(decimals=3), torch.softmax(scaled, dim=-1).round(decimals=3))1tensor([ 4.6190, -1.1550, 1.7320]) tensor([0.9440, 0.0030, 0.0530])
2tensor([ 1.1550, 0.0000, -0.5770]) tensor([0.6700, 0.2110, 0.1190])
Multi-head attention adds no positions and no new tokens. It gives the same sequence several learned ways to weight and combine its value vectors.
What heads end up doing
Nothing in the formula tells a head what to specialize in. Every head has the same shape and the same formula, and only its learned projections differ. When people inspect the attention weights of trained models, some heads show recognizable patterns:
- Local heads put most of their weight on the one or two positions next to the query.
- Syntactic heads link a word to the word it depends on grammatically, such as a verb to its subject.
- Coreference heads link a pronoun to the noun it refers to.
- Positional heads attend by offset, for example two positions back, and largely ignore which words are there.
- Semantic heads group words with related meaning rather than related position.
These are patterns found after training, not roles assigned before it. The labels are rough, and plenty of heads do not fit any of them cleanly.

Joining the heads back together
Each head returns vectors with $D_h = 3$ features. Suppose the two heads give the these outputs:
$$\text{head 1: } [1.5, -0.7, 0.4] \qquad \text{head 2: } [-0.2, 2.1, 1.0]$$
Placing them side by side, called concatenation, gives one vector with 6 features again:
$$[1.5, -0.7, 0.4, -0.2, 2.1, 1.0]$$
![Head 1 output for the, [1.5, -0.7, 0.4], and head 2 output for the, [-0.2, 2.1, 1.0], are concatenated into [1.5, -0.7, 0.4, -0.2, 2.1, 1.0], with the first three features from head 1 and the last three from head 2, back to d_model = 6.](images/mha_concat_tiny_outputs.png)
In code, the head outputs have shape $(B, H, T, D_h)$. Two lines put the heads side by side for each token:
1out = out.transpose(1, 2).contiguous()
2out = out.view(B, T, C)transpose(1, 2) moves the heads back after the tokens, giving $(B, T, H, D_h)$. view(B, T, C) then joins the $H$ pieces of size $D_h$ into $C = d_{model}$ features per token.
The contiguous() call is there because of how tensors sit in memory. transpose swaps axes by changing how PyTorch steps through the stored numbers, and it leaves them where they were. view needs the numbers stored in order, so contiguous() first copies them into one ordered block. Leaving it out raises an error:
1import torch
2
3out = torch.randn(2, 2, 3, 3) # (B, H, T, D_h) as it comes out of weights @ v
4merged = out.transpose(1, 2) # (B, T, H, D_h)
5print(merged.is_contiguous())
6try:
7 merged.view(2, 3, 6)
8except RuntimeError as err:
9 print("RuntimeError:", str(err).split(".")[0])
10print(merged.contiguous().view(2, 3, 6).shape)1False
2RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)
3torch.Size([2, 3, 6])The output projection
After concatenation, the model applies one more learned matrix, the output projection $W_O$:
$$\text{MHA}(X) = \operatorname{Concat}(\text{head}_1, \ldots, \text{head}_H)\,W_O$$
$W_O$ has shape $(H \cdot D_h) \times d_{model}$, which is $d_{model} \times d_{model}$ since $H \cdot D_h = d_{model}$. Concatenation only places the heads side by side. $W_O$ is where the information from different heads gets mixed into each output feature, before the result goes back into the transformer layer. The final shape matches the input, $(B, T, d_{model})$.

Counting the weights shows how the head count affects the size of the block. The fused projection is $d_{model} \times 3d_{model}$ and the output projection is $d_{model} \times d_{model}$, so one attention block holds about
$$4\,d_{model}^2 \text{ weights}$$
plus a small bias vector in each layer. That number does not depend on $H$. More heads split the same budget into more, smaller weighting patterns instead of adding parameters.
Put together, the whole path for two heads in the running example looks like this:

Multi-head attention in PyTorch
The full module, with the reshape steps from above. The constructor checks that the width splits evenly, works out the head size and builds the two projection layers. d_model % num_heads is the remainder of the division, and d_model // num_heads divides and drops the remainder:
1import torch
2import torch.nn as nn
3
4
5class MultiHeadAttention(nn.Module):
6 def __init__(self, d_model, num_heads):
7 super().__init__()
8 assert d_model % num_heads == 0
9 self.num_heads = num_heads
10 self.head_dim = d_model // num_heads
11 self.qkv_proj = nn.Linear(d_model, 3 * d_model)
12 self.out_proj = nn.Linear(d_model, d_model)
13
14 def forward(self, x):
15 B, T, C = x.shape
16 qkv = self.qkv_proj(x)
17 q, k, v = qkv.chunk(3, dim=-1)
18 q = q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
19 k = k.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
20 v = v.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
21 scores = q @ k.transpose(-2, -1)
22 scores = scores / (self.head_dim ** 0.5)
23 weights = torch.softmax(scores, dim=-1)
24 out = weights @ v
25 out = out.transpose(1, 2).contiguous()
26 out = out.view(B, T, C)
27 return self.out_proj(out), weights
28
29
30torch.manual_seed(0)
31mha = MultiHeadAttention(d_model=6, num_heads=2)
32x = torch.randn(1, 3, 6) # 1 sequence, 3 tokens, 6 features per token
33out, weights = mha(x)
34print(out.shape)
35print(weights.shape)
36print(weights[0].detach().round(decimals=2))1torch.Size([1, 3, 6])
2torch.Size([1, 2, 3, 3])
3tensor([[[0.2900, 0.4200, 0.3000],
4 [0.3500, 0.2600, 0.4000],
5 [0.2500, 0.4500, 0.3000]],
6
7 [[0.3300, 0.2700, 0.4000],
8 [0.2700, 0.3300, 0.4000],
9 [0.3100, 0.3800, 0.3000]]])The output has the input's shape, and there is one $3 \times 3$ weight grid per head. These weights come from random, untrained projections, so they are close to even. Training is what pulls each head toward its own pattern.
The parameter count with a width of 64 and different numbers of heads, using the class above:
1for num_heads in (1, 2, 4, 8):
2 layer = MultiHeadAttention(d_model=64, num_heads=num_heads)
3 print(num_heads, sum(p.numel() for p in layer.parameters()))11 16640
22 16640
34 16640
48 16640All four print 16,640, which is $4 \times 64^2 = 16{,}384$ weights plus 256 biases. If view raises an error about size and stride in a module like this, the usual cause is a missing contiguous() after the transpose.

Common mistakes
The head count is a setting chosen together with the model width, and it has to divide the width evenly. Mistakes that come up often:
- A width that does not split evenly. With
d_model = 10andnum_heads = 3there is no whole-numberhead_dim, which is what theassertin the constructor catches. - Skipping the transpose before the scores. With
qandkstill shaped(B, T, H, D_h), the product compares heads with heads and gives scores of shape(B, T, H, H). - Scaling by the wrong size. Each head's scores are divided by $\sqrt{D_h}$, the head's own query and key size, not by $\sqrt{d_{model}}$.
- Merging without moving the heads back. Calling
view(B, T, C)on a(B, H, T, D_h)tensor mixes features from different tokens into one row. - Expecting more heads to add parameters. The total stays near $4\,d_{model}^2$ for any head count.
Related concepts
Self-attention is the single-head computation that each head runs. Positional encoding adds order information to the token vectors, since more heads give more ways to compare tokens but no sense of where they sit. How transformers work shows where the multi-head attention block sits inside a transformer layer, next to the feed-forward network.
QuiddityML teaches multi-head attention as its own concept in the Intro to NLP track. The exercises on it include reshaping q, k and v into heads, merging the heads back through the output projection and typing a complete MultiHeadAttention module from scratch.