10/23
Part 3 of 6 · Split the headsLearn and do

Cut q, k and v apart

nn.Linear(C, 3 * C) makes the queries, the keys and the values in one go. They come out side by side on the last axis. split cuts them apart.

out = torch.arange(12).view(1, 2, 6)
q, k, v = out.split(2, dim=-1)
print(out)
print(q)
print(k)
print(v)
tensor([[[ 0,  1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10, 11]]])
tensor([[[0, 1],
         [6, 7]]])
tensor([[[2, 3],
         [8, 9]]])
tensor([[[ 4,  5],
         [10, 11]]])
out, cut into q, k and v
out[0] (2, 6)
qqkkvvtoken 0012345token 167891011

split(2, dim=-1) means: cut the last axis into pieces of size 2. Each token keeps its own row. Nothing is copied.

view(1, 2, 6) works like NumPy's reshape. Part 4 shows the one place where the two differ. chunk does the same as split with the other number: out.chunk(3, dim=-1) means three pieces. If you mix them up, out.split(3, dim=-1) gives two pieces of size 3, and q, k, v = ... fails because there are only two.

In the editor, out is a projection's output for 1 sentence of 3 tokens with C = 4, so each token has 3 * C = 12 numbers. Cut it into q, k and v with split, then into q2, k2 and v2 with chunk.