Flatten before the loss
The loss is the average, over every guess, of how unlikely the model found the right answer: minus the log of the probability it gave to the right next word. F.cross_entropy computes it. It wants one row of V scores per guess, so flatten the batch and the positions together first: (B, T, V) becomes (B * T, V), and (B, T) becomes (B * T,).
Here are five rows of random scores, the logits in the code further down, one row per guess. Each row is labeled with the word its position has just read. The marked cell is the right next word, and it's the only score in its row the loss looks at:
logits.reshape(-1, V) (5, 5)Pass (B, T, V) straight in, and PyTorch reads the second axis, T, as the vocabulary. This sentence has 5 guesses and 5 words, so T and V are both 5:
# cat sat on the mat
targets = torch.tensor([[1, 2, 3, 0, 4]])
torch.manual_seed(0)
# (B, T, V): 5 guesses, 5 words
logits = torch.randn(1, 5, 5)
right = F.cross_entropy(logits.reshape(-1, 5), targets.reshape(-1))
# reads T as the vocabulary
wrong = F.cross_entropy(logits, targets)
print(round(right.item(), 4), round(wrong.item(), 4))
One loss flattens the logits to (5, 5). The other passes (1, 5, 5) as it is. What happens?