13/23
Part 4 of 6 · Merge the headsLearn and do
Merge the heads: transpose back, then reshape
After attention you have one output per head, (B, H, T, d). To get back to (B, T, C), undo the two steps in reverse order: tokens back in front, then join each token's pieces.
y = h.contiguous()
z = y.transpose(1, 2)
print(z.reshape(B, T, C))
tensor([[[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15]]])
The rows come back exactly as they were.
Here h.contiguous() stands in for the output of attention: it copies h into a fresh tensor, laid out in memory in its current order. You only need to know one thing about why that matters. A transpose doesn't move any numbers. It changes the order in which PyTorch reads the same memory. After it, one token's numbers are no longer next to each other in memory. That has one consequence:
viewnever copies, so it can't join numbers that aren't next to each other. It raises an error.reshapecopies when it has to. It always works.
So after a transpose, join axes with reshape.
The quiet failure: you skip the transpose and write y.reshape(B, T, C) on the heads. What happens?
Pick an answer above to see the rest