Five letters
Open any transformer codebase and you'll find the same five letters everywhere: B, T, C, H and d. Once you can read them, a line like x.view(B, T, H, d) stops looking like noise. From here on the data is text: one pair of sentences, the cat sat on the mat, and the same words in another order.
# the cat sat on the mat
idx = torch.tensor([[0, 1, 2, 3, 0, 4],
# the mat sat on the cat
[0, 4, 2, 3, 0, 1]])
torch.manual_seed(0)
# 12 numbers for each token
x = torch.randn(2, 6, 12)
B, T, C = x.shape
H = 4
d = C // H
print(B, T, C, H, d)
2 6 12 4 3
Tap each letter to see its axis:
x.shape = (2, 6, 12)- B, batch: how many sentences go through together.
- T, time: how many tokens are in each sentence.
- C, channels: how many numbers describe each token.
Attention adds two more:
- H, heads: how many pieces each token's numbers get cut into.
- d, the size of one piece,
d = C // H.
Notice that every size here is different: 2, 6, 12, 4 and 3. That's on purpose, and it's a habit worth stealing for your own tests. Say you swap two axes by mistake. With all sizes different, you get a shape nothing else expects, and the very next line fails and points at the bug. Now imagine B and T were both 4. The swap would keep the shape, nothing would fail, and the numbers would be quietly wrong. Different sizes turn silent bugs into loud ones.
In the editor, x is the same (2, 6, 12) tensor. Read B, T and C from x.shape, then set d, the size of one head when H = 4.