liveBook · Manning

Cross entropy loss

As explained in Build a Reasoning Model (From Scratch)

A loss function that measures the average negative log probability assigned to the correct target tokens.

Cross-entropy loss measures how confidently a language model predicts each correct next token. It averages the negative log probabilities over target answer tokens, making sequence losses comparable across lengths. section 8.6

Compute the answer-only loss in four implementation steps:

  • Shift the token sequence into model inputs and next-token targets. section 8.6
  • Run the model and retain logits beginning at the answer boundary, excluding prompt predictions. section 8.6
  • Apply cross_entropy to answer logits and reference answer tokens; values closer to zero indicate greater confidence. section 8.6
  • Average losses across examples for training and validation monitoring, restoring training mode after evaluation. section 8.6

Direct answer-token calculation

For “The capital of Germany is Berlin,” five target predictions produce a summed log probability of −16.6250; negating and averaging gives cross-entropy 3.325. A PyTorch implementation slices answer logits and targets, then calls torch.nn.functional.cross_entropy. section 8.6 section 8.6

Figure 8.12 Illustration of token and sequence log probabilities. The log probabilities of the correct next tokens are summed to obtain the sequence log probability, which is the basis for the cross-entropy loss used later in this chapter.

Trace how token log probabilities combine into a sequence log probability and then become the cross-entropy training signal. section 8.6

How Build a Reasoning Model (From Scratch) covers it

How deep it goes
Explains token alignment, answer masking, length normalization, direct computation, and multi-example evaluation without covering optimizer internals.
Examples
Demonstrates the Germany–Berlin sequence, answer-token slicing, single-example loss, and averaged train-versus-validation results.
What it assumes
Assumes tokenized prompt–answer examples and basic log-probability concepts while grounding classification-style cross-entropy in next-token prediction.
What you can do after
Build it from scratch with shifted token tensors, answer-boundary slicing, PyTorch cross_entropy, and aggregate train or validation evaluation.
How it connects
Connects cross-entropy to log probability, next-token prediction, supervised learning, knowledge distillation, and validation loss.

Also explained in

Compare how 19 books explain cross entropy loss →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Reasoning Model (From Scratch). The section links point to the parts of the book it draws on.