Everything we've covered so far can be viewed as a single-head attention process.
First: Stacking Multiple Single-Head Attention Layers
One way to implement multi-head attention is to create several self-attention mechanisms, each with its own weights, and then combine their outputs.

multi-head attention made up of two single-head attention mechanisms
The example above is a simple multi-head attention module built by stacking two self-attention mechanisms.
The main idea behind multi-head attention is to run the self-attention mechanism multiple times in parallel using different learned linear projections—which are the result of multiplying the input data (such as the query, key, and value vectors in the attention mechanism) by weight matrices.
class MultiHeadAttentionWrapper(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
super().__init__()
self.heads = nn.ModuleList(
[CausalAttention( d_in, d_out, context_length, dropout, qkv_bias )
for _ in range(num_heads)]
)
def forward(self, x):
return torch.cat([head(x) for head in self.heads], dim=-1)

Output from two attention heads
torch.manual_seed(123)
context_length = batch.shape[1] # This is the number of tokens
d_in, d_out = 3, 2
mha = MultiHeadAttentionWrapper( d_in, d_out, context_length, 0.0, num_heads=2 )
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
## result
tensor([[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]],
[[-0.4519, 0.2216, 0.4772, 0.1063],
[-0.5874, 0.0058, 0.5891, 0.3257],
[-0.6300, -0.0632, 0.6202, 0.3860],
[-0.5675, -0.0843, 0.5478, 0.3589],
[-0.5526, -0.0981, 0.5321, 0.3428],
[-0.5299, -0.1081, 0.5077, 0.3493]]], grad_fn=<CatBackward0>) context_vecs.shape: torch.Size([2, 6, 4])
The first dimension of the resulting context_vecs tensor is 2 because we have two input texts (the input texts are duplicated, which is why these context vectors are identical). The second dimension refers to the 6 tokens in each input. The third dimension refers to the four-dimensional embedding for each token.
Second: Implementing Multi-Head Attention with Weight Splits
Now that we have MultiHeadAttentionWrapper and CausalAttention, we can combine them into MultiHeadAttention.
class MultiHeadAttention(nn.Module):
def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
super().__init__()
assert (d_out % num_heads == 0), "d_out must be divisible by num_heads"
self.d_out = d_out
self.num_heads = num_heads
self.head_dim = d_out // num_heads # 1
self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
self.out_proj = nn.Linear(d_out, d_out) # 2
self.dropout = nn.Dropout(dropout)
self.register_buffer(
"mask", torch.triu(torch.ones(context_length, context_length), diagonal=1)
)
def forward(self, x):
b, num_tokens, d_in = x.shape
keys = self.W_key(x) # 3
queries = self.W_query(x) # 3
values = self.W_value(x) # 3
keys = keys.view(b, num_tokens, self.num_heads, self.head_dim) # 4
values = values.view(b, num_tokens, self.num_heads, self.head_dim) # 4
queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
keys = keys.transpose(1, 2) # 5
queries = queries.transpose(1, 2) # 5
values = values.transpose(1, 2) # 5
attn_scores = queries @ keys.transpose(2, 3) # 6
mask_bool = self.mask.bool()[:num_tokens, :num_tokens] # 7
attn_scores.masked_fill_(mask_bool, -torch.inf) # 8
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
attn_weights = self.dropout(attn_weights)
context_vec = (attn_weights @ values).transpose(1, 2) # 9 # 10
context_vec = context_vec.contiguous().view(b, num_tokens, self.d_out)
context_vec = self.out_proj(context_vec) # 11
return context_vec
[!NOTE]
- Reduce the projection dimension to match the desired output dimension
- Use a linear layer to combine the outputs of the individual attention mechanisms
- Tensor shape: (b, numtokens, dout)
- We implicitly split the matrix by adding a numheads dimension. Then we unfold the last dimension: (b, numtokens, dout) -> (b, numtokens, numheads, headdim).
- Transpose from shape (b, numtokens, numheads, headdim) to (b, numheads, numtokens, headdim)
- Compute the dot product for each head
- Truncate the mask to the number of tokens
- Fill the attention scores using the mask
- Tensor shape: (b, numtokens, nheads, head_dim)
- Combine the heads, where self.dout = self.numheads * self.head_dim
- Add an optional linear projection

CleanShot 2024-11-13 at 11.54.08@2x.png
To illustrate this batched matrix multiplication, suppose we have the following tensor:
The shape of this tensor is (b, numheads, numtokens, head_dim) = (1, 2, 3, 4).
Now we perform batched matrix multiplication between the tensor itself and a view of the tensor. We transpose the last two dimensions, numtokens and headdim:
In this case, PyTorch's matrix multiplication implementation handles the four-dimensional input tensor so that it performs matrix multiplication between the last two dimensions (numtokens, headdim), then repeats this operation for each head.
For example, the approach above becomes a cleaner way to compute matrix multiplication for each head:
Continuing with multi-head attention: after computing the attention weights and context vectors, the context vectors from all heads are transposed back to shape (b, numtokens, numheads, headdim). These vectors are then reshaped (flattened) to shape (b, numtokens, d_out), effectively combining the outputs from all heads.
In addition, we added an output projection layer (self.out_proj) to MultiHeadAttention after combining the heads; this layer does not exist in the CausalAttention class. This output projection layer is not strictly necessary, but it is commonly used in many large language model architectures, so I added it here for completeness.
For comparison, the smallest GPT-2 model (117 million parameters) has 12 attention heads and a context vector embedding size of 768. The largest GPT-2 model (1.5 billion parameters) has 25 attention heads and a context vector embedding size of 1,600. In GPT models, the embedding size of the token inputs and the context embeddings is the same (din = dout).