QuiddityML

By · 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.

Input token vectors go into multi-head self-attention and then the rest of the transformer block. Inside, the feature dimension is split across head 1 and head 2, each with its own W_Q, W_K and W_V slice, then the heads are concatenated, mixed by W_O and returned as one output stream.

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.

Q = XW_Q, K = XW_K and V = XW_V, with X of shape T × d_model, Q and K of shape T × d_k and V of shape T × d_v. One head is head = softmax(QK transpose over the square root of d_k) V, one learned way to weight the sequence.

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 tokens the, cute and axolotl map to ids 4, 7 and 9, and their vectors stack into X with 3 rows, one per token, and 6 columns, one per feature. In the packed multi-head setup q, k and v each have total feature dimension d_model = 6, which is split into heads later.

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.

d_model = 6 and H = 2 give D_h = 3. The 6 features are split into features 1 to 3 for head 1 and 4 to 6 for head 2, which together still cover the full width. An even split works for d_model = 6 with 2 heads, and d_model = 10 with 3 heads has no equal split.

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.

For 2 heads with d_model = 6 and head_dim = 3, W_Q, W_K and W_V each have shape H × d_model × D_h = 2 × 6 × 3, read as heads × input features × head features. Per head: Q = XW_Q, K = XW_K and V = XW_V, then S = QK transpose over the square root of D_h, then head output = softmax(S) V. Production code uses one larger Linear layer and reshapes instead.

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.

qkv_proj = nn.Linear(in_features=d_model, out_features=3 * d_model). With d_model = 6 the input x has 6 features per token and qkv has 18 features per token, split into Q, K and V. x is B × 3 × 6 and qkv is B × 3 × 18.

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.

qkv = self.qkv_proj(x), then q, k, v = qkv.chunk(3, dim=-1). qkv of shape B × T × 3d_model = B × 3 × 18 becomes q, k and v, each B × T × d_model = B × 3 × 6.

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.

q, k and v are viewed as (batch, seq_len, num_heads, head_dim). q goes from B × 3 × 6 to B × T × H × D_h = B × 3 × 2 × 3, and the 6 features of one token split into head 1 and head 2 with D_h = 3 each.

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.

q, k and v are transposed with transpose(1, 2), which turns the axis order B, T, H, D_h into B, H, T, D_h. Only the order of the two middle axes changes, the numbers inside are untouched, and the heads can run in parallel.

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.

q, k and v have shape B × H × T × D_h. scores = q @ k.transpose(-2, -1) has shape B × H × T × T = B × 2 × 3 × 3, one score grid per head over the, cute and axolotl. Each head then computes softmax(scores / sqrt(D_h)) @ v.

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.

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])

Query token the in both heads. Head 1 scores 8, -2 and 3 become 4.619, -1.155 and 1.732 after scaling and 0.944, 0.003 and 0.053 after softmax. Head 2 scores 2, 0 and -1 become 1.155, 0.000 and -0.577 and then 0.670, 0.211 and 0.119. Same sequence and same positions, but each head has its own learned projections.

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:

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.

What heads end up doing, patterns found after training rather than roles assigned before it: local heads weight next-door positions, syntactic heads link verb to subject, coreference heads link pronoun to noun, positional heads attend by fixed offset and semantic heads group related meaning. Every head has the same shape and formula, and only the weights differ.

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.

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})$.

Concat(head_1, ..., head_h) goes through W_O to give out, written in code as out = self.out_proj(out). MHA(X) = Concat(head_1, ..., head_h) W_O, and out has shape B × T × d_model. W_O lets information from different heads mix, and the final shape matches the input.

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:

Two heads with H = 2 and D_h = 3 run in parallel. Each takes its own q, k and v of shape B × 1 × T × D_h, one head's slice, runs scaled dot-product attention with a 3 × 3 grid over the, cute and axolotl, and returns a head output. The heads merge into B × 3 × 6, go through the output projection W_O of shape 6 × 6 and give the final output B × 3 × 6. The two example weight rows are the: 0.05, cute: 0.80, axolotl: 0.15 for a head that focuses on cute, and the: 0.25, cute: 0.35, axolotl: 0.40 for a head that uses a broader mix.

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 16640

All 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.

The full code path from B, T, C = x.shape through the fused projection, chunk, view and transpose for q, k and v, the scores, scaling, softmax and weighted sum, then transpose, contiguous, view(B, T, C) and out_proj. Notes: in equations the tensors are written Q, K and V and in code q, k and v, and contiguous() is needed because transpose can leave the tensor in a non-contiguous memory layout that view cannot read.

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:

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.