Cross-entropy loss scores how well predicted token probabilities match target token IDs. Lower loss means the model assigns higher probability to the required next tokens. section 5.1.2
For causal language modeling, inputs and targets have matching shapes, with targets shifted one position forward. A GPT model produces logits shaped [batch, tokens, vocabulary], softmax converts them to probabilities, and the target probability is selected at each position. section 5.1.2
The manual calculation follows a short sequence:
- Select the probability assigned to each target token from the model's output distribution. section 5.1.2
- Take logarithms of those probabilities, average the log probabilities, and multiply by negative one. section 5.1.2
- Flatten logits from [batch, tokens, vocabulary] to [batch × tokens, vocabulary] and targets to [batch × tokens] before calling PyTorch cross_entropy. section 5.1.2 section 5.1.3
Worked language-model example
With two sequences of three input tokens and a vocabulary of 50,257 tokens, the probability tensor has shape [2, 3, 50257], while targets have shape [2, 3]. Flattening produces [6, 50257] logits and six target IDs. PyTorch returns a loss of 10.7940, matching the manual negative average log probability. section 5.1.2
Training and validation evaluation applies the same batch loss across data loaders, averages the batch values, and uses no-grad evaluation. A small tokenized dataset can produce separate training and validation losses before pretraining. section 5.1.3
For classification fine-tuning, cross-entropy remains the optimization target because accuracy is not differentiable. The loss uses only the final-token logits, shaped [batch, classes], against one class label per input. section 6.6
Figure 5.4 For each of the three input tokens, shown on the left, we compute a vector containing probability scores corresponding to each token in the vocabulary. The index position of the highest probability score in each vector represents the most likely next token ID. These token IDs associated with the highest probability scores are selected and mapped back into a text that represents the text generated by the model.
Trace the flow from each input token through vocabulary probabilities to the selected next-token prediction. section 5.1.2


















