11/23
Part 3 of 6 · Split the headsLearn and do
Split the heads: view, then transpose
Multi-head attention cuts each token's numbers into H pieces, one per head, and then runs attention on each head separately. For that, each head must become its own grid: one row per token.
To see where every number goes, label them. The tens digit is the token, the ones digit is the channel.
x = torch.tensor([[[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15]]])
B, T, C = x.shape
H = 3
d = C // H
v = x.view(B, T, H, d)
h = v.transpose(1, 2)
print(v.shape, h.shape)
print(h)
torch.Size([1, 2, 3, 2]) torch.Size([1, 3, 2, 2])
tensor([[[[ 0, 1],
[10, 11]],
[[ 2, 3],
[12, 13]],
[[ 4, 5],
[14, 15]]]])
Step through it, and try the reshape too:
x (B, T, C) = (1, 2, 6)token 0012345token 1101112131415
Each number is 10 × token + channel, so its tens digit says which token it belongs to. Token 0 holds 0 to 5, token 1 holds 10 to 15.
Two steps, in this order:
view(B, T, H, d)cuts each token's row into H pieces. Each token's numbers stay together.transpose(1, 2)swaps the token axis and the head axis. Now each head is a small grid with one row per token.
Check it in the output: in every head, the first row only has tens digit 0, and the second row only tens digit 1. Each row is still one token. That's what attention needs.
Write split_heads(x, n_head): the view, then the transpose, for any x of shape (B, T, C). It's the first function of the practice problem, without its error check.