Causal Training, Checkpointing & Generation
A correct forward pass is only the beginning. This section fixes target alignment, valid-token weighting, full training state and sampling semantics so that a tiny model can train, resume and generate reproducibly.
Section 3 of 5 · 7 units · about 25 hours
By the end you can Overfit one tiny batch, prove target and mask alignment, train and resume a compact decoder with a stated equivalence level, then reproduce fixed-seed greedy, temperature, top-k and top-p outputs while explaining each distributional change.
Units
- The next-token objective: shifts, masks and perplexity4h
- Feeding the model: batches, initialization and first steps3h
- AdamW, schedules and the global token batch4h
- Keeping training numerically healthy3h
- Checkpoints that really resume4h
- Decoding policies: from greedy to nucleus sampling4h
- Stopping rules and reproducible generation3h
Build it
Mini project · about 10 to 14 hours
Train, resume and sample the tiny decoder
Turn the decoder into a trained model you can trust: a loss you can derive by hand, a loop that resumes exactly, and decoding policies whose distributions you can check. Train on the packed split from section 1 on a CPU or a free GPU notebook.
- 1Implement cross-entropy, gradient clipping,
AdamW, the warmup-cosine schedule,get_batchand checkpointing, and pass the CS336 tests intest_nn_utils.py,test_optimizer.py,test_data.pyandtest_serialization.py. - 2Run two controls before any real run: drive one tiny batch to near-zero loss, and confirm that a run on shuffled targets leaves validation loss near the unigram baseline.
- 3Train on your section 1 split with a fixed seed, logging loss, gradient norm, learning rate and tokens seen, with a validation curve from the held-out split.
- 4Save complete state, including model, optimizer, step, RNG and data cursor, and show that an interrupted run matches an uninterrupted one to a stated level.
- 5Implement greedy, temperature, top- and top- sampling with
EOSand length stops, and reproduce fixed-seed outputs exactly. - 6Train on a synthetic Markov chain with a known entropy rate: validation loss should approach that rate, and a loss clearly below it means the labels leak. On CPU, a resumed run should match an uninterrupted one exactly.
What you hand in
- The training script and config, with the checkpoint format documented.
- The training log and validation curve for your run, plus the two control runs.
- A resume-equivalence result: the steps compared, the tolerance and why it is the right one.
- Sample outputs for each decoding policy from one prompt and seed, with the config that reproduces them.
How to check it
- CS336 tests for cross-entropy, clipping, `AdamW`, the schedule, data loading and checkpointing
uv run pytest tests/test_nn_utils.py tests/test_optimizer.py tests/test_data.py tests/test_serialization.py - Self-grade with the rubric below
How it's graded
Objective
Pass: Your cross-entropy passes the public test, including the overflow case.
Great: You derive one masked loss by hand and match your code, and the shuffled-target control behaves as you predicted.
Training
Pass: Validation loss falls on your split, and on the Markov chain it approaches the entropy rate without going clearly below it.
Great: The log shows learning rate, gradient norm and tokens seen, and you explain one anomaly from it.
Resume
Pass: An interrupted run continues without a loss jump.
Great: Losses after resume match the uninterrupted run exactly on CPU, and your stated GPU tolerance is justified.
Decoding
Pass: Each policy runs and stops on EOS or the length cap.
Great: Fixed-seed outputs reproduce exactly, and you show by hand how temperature followed by top- changes the kept set at one step.
Resources
- LLMs from Scratch companion - training and generationSebastian Raschka
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
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
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.
- PyTorch saving, loading and reproducibility referencesPyTorch
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.
- PyTorch Automatic Mixed Precision recipePyTorch
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. - Hugging Face LLM Course - library translationHugging Face
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.