20/29
Part 4 of 5 · The loss and the length limitLearn and do

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:

One row per guess, one column per word
logits.reshape(-1, V) (5, 5)
thecatsatonmatthe-1.1-1.2-0.3-0.40.8cat0.7-0.3-2.10.3-0.2sat1.40.30.20.9-0.1on-0.1-0.61.32.00.1the0.6-0.4-0.8-2.3-0.1

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))
Predict

One loss flattens the logits to (5, 5). The other passes (1, 5, 5) as it is. What happens?

Pick one to see what it prints.
Pick an answer above to see the rest