21/23
Part 6 of 6 · One decode step, and long linesLearn and do

Read a long line from the inside out

Model code often packs several steps into one line. Read it from the inside out: find the innermost name, say its shape, then move out one call at a time and say the new shape.

q, k, v = (t.view(B, T, H, d).transpose(1, 2) for t in (q, k, v))
PieceWhat it doesShape
for t in (q, k, v)takes the three tensors one at a time(B, T, C)
t.view(B, T, H, d)cuts each token's numbers into heads(B, T, H, d)
.transpose(1, 2)puts the heads in front(B, H, T, d)
q, k, v = ...stores the three results under the same names(B, H, T, d) each

It's the head split from split_heads, done three times in one line. Here it is on numbers:

B, T, C, H = 1, 2, 6, 3
d = C // H
q = torch.arange(12.).view(B, T, C)
k, v = q + 100, q + 200
q, k, v = (t.view(B, T, H, d).transpose(1, 2) for t in (q, k, v))
for t in (q, k, v):
    print(t.shape)
print(k[0, 1])
torch.Size([1, 3, 2, 2])
torch.Size([1, 3, 2, 2])
torch.Size([1, 3, 2, 2])
tensor([[102., 103.],
        [108., 109.]])

Head 1 of the keys holds channels 2 and 3 of both tokens: 102 and 103 from token 0, 108 and 109 from token 1.

A chain of calls reads left to right instead, each call working on the result of the one before:

att = att.masked_fill(~mask, float("-inf")).softmax(dim=-1)

Flip the mask, write minus infinity where it's True, take the softmax over each row, store the result. The shape never changes.

The same habit finds bugs. Write the shape under each piece of a line. The piece whose shape surprises you is the bug.

In the editor, append_greedy(idx, logits) is the fourth function of the practice problem, written as one line, and it's wrong. Write the shape under each piece of that line, and fix it so it returns (B, T + 1).