Unit 1 of 7 · about 4 hours · derive, implement
The next-token objective: shifts, masks and perplexity
Every later number in this section, from optimizer steps to evaluation claims, reads off this loss. A shifted-by-one or unmasked loss trains the wrong objective while the curve still falls.
You'll be able to
- Derive token-weighted cross-entropy and perplexity with an explicit valid-token mask.
- Explain the input-target shift and predict the failure when labels are off by one.
- Explain which positions a packed or padded batch must exclude from the loss and why.
Covers
Read
In this order, only the parts listed
0 of 3 done
- CS336 Assignment 1 handout: cross-entropy and perplexityStanford CS336 Assignment 1 - training and decoding contract
Section 4.1, Cross-entropy loss (pp. 28 to 29): equations 16 to 18 for shifted likelihood, the numerically stable cross-entropy requirements and perplexity
- LLMs from Scratch ch05: generation loss and train/val lossLLMs from Scratch companion - training and generation
Sections 5.1.2 (shifted inputs and targets, flattening
logitsforcross_entropy, perplexity as the exponential of the loss) and 5.1.3 (train and validation loss withcalc_loss_batchandcalc_loss_loader) - Modern LLM Notebook 10-training-loss: shift, hand loss and valid tokensModern LLM Notebook - configuration, loss and generation
Sections 1 (input and label shift on
[1, 3, 4, 5, 6]), 3 (hand-computed cross-entropy fromlogits[2.0, 1.0, 0.1, -1.0]), 10 (perplexity table) and 11 (shift in the data versus shift in the model), plus Homework 3 (mean over valid tokens only)
Focus on
- Position predicts token from context to . Inputs and labels are the same sequence offset by one.
- The mean runs over valid tokens only. Padding and
-100label positions leave both the sum and the count. - Perplexity is exp of the mean cross-entropy, so it reads as the effective shortlist size at each step.
- One forward pass yields every position's distribution at once, which is why training parallelizes but generation does not.
Common mistakes · 3
- Averaging over all positions including padding. The denominator changes, so short and padded batches get different objectives.
- Shifting twice: slicing tokens in the data loader and again inside the model. Every target then predicts two steps ahead.
- Comparing perplexity across tokenizers. Different vocabularies split the same text into different token counts, so the means are over different units.
Try it yourself
Closed-book, before checking anything
F.cross_entropy on the flattened tensors.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does the Raschka code flatten
logitsto before callingcross_entropy?AnswerThe function expects a 2D input with one target index per row. Flattening keeps one row per position while targets flatten to , so each position is scored against its own shifted target.
2.Logits are
[2.0, 1.0, 0.1, -1.0]and the correct token is 0. What is the loss?AnswerAbout 0.45. Softmax gives the correct token probability , and .
3.Labels are not shifted, so position supervises with token . What breaks?Answer
The model is asked to output a token already in its context, so it learns copying. The loss still falls, but the trained objective is not next-token prediction and the perplexity is meaningless.
4.Six positions have losses
[0.2, 0.4, 1.0, 0.3, 0.8, 0.5]with labels[10, 11, -100, 3, -100, 12]. What is the training loss?Answer0.35. Only the four positions with real labels count: . Including the masked positions changes both the sum and the denominator.
Practice
- CS336 Assignment 1:
cross_entropyProblem (
cross_entropy) in Section 4.1; connect your function torun_cross_entropyintests/adapters.pyand passtest_cross_entropyintests/test_nn_utils.pyThe tests compare against
F.cross_entropyon a fixed batch and on a 1000x scaled copy, so subtract the row max and cancel log with exp. Implement it in your own repository.
You're done when
You hand-compute a masked loss and perplexity that match code, and your cross_entropy passes test_cross_entropy including the overflow case.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 3 more in the section
- LLMs from Scratch companion - training and generationSebastian Raschka · primary
Use the ch05 training and generation code for the small pretraining loop. Add full checkpoint state, explicit loss masks and resume-equivalence tests that the base example does not supply.
- Stanford CS336 Assignment 1 - training and decoding contractStanford University · required
Use cross_entropy, adamw, adamw_accounting, learning_rate_schedule, gradient_clipping, data_loading, checkpointing, training_together and decoding specifications plus public tests. Debug on CPU and implement independently in your own repository.
- Modern LLM Notebook - configuration, loss and generationWalking Labs · support
Use English notebooks 09-model-config, 10-training-loss and 20-generation to visualize configuration ownership, shifted loss and decoding policies. Change edge cases and cross-check probability calculations against your own implementation.
Also in this section
- PyTorch saving, loading and reproducibility referencesPyTorch · support
Use the state-dict and reproducibility notes to enumerate all state needed for the supported resume guarantee. Test model, optimizer, schedule, scaler, data order and RNG state across an interruption.
- Hugging Face LLM Course - library translationHugging Face · optional
Only after the blank-file loop passes, map tokenization, model configuration, data collation, generation configuration and stopping behavior into Transformers APIs. Keep the from-scratch tests as the authority.
- PyTorch Automatic Mixed Precision recipePyTorch · support
Use the
autocast,GradScaler, unscale-before-clip, scaler checkpointing and inf-NaN troubleshooting sections to add mixed precision to the blank-file loop. Keep the CS336 clipping contract as the authority for the clipping rule.