Unit 4 of 7 · about 3 hours · explain, measure
Keeping training numerically healthy
One bad batch can end a run, and mixed precision makes bad batches likelier. Clipping, scaling and logging turn a crash into a diagnosed event with a known remedy.
You'll be able to
- Explain the clipping rule, where it sits in the step order, and how it changes with a gradient scaler.
- Explain
autocastdtype choice and howGradScalerprotects small gradients from underflow. - Log gradient norms, loss scale and skipped steps, and read overflow signals from the log.
Covers
Read
In this order, only the parts listed
0 of 3 done
- CS336 Assignment 1 handout: gradient clippingStanford CS336 Assignment 1 - training and decoding contract
Section 4.5, Gradient clipping (p. 34): the global norm rule with max and
eps1e-6, applied in place after the backward pass - PyTorch AMP recipe:
autocast,GradScalerand clipping orderPyTorch Automatic Mixed Precision recipeSections Adding
torch.autocast(forward underautocast, never backward), AddingGradScaler(scale, backward, conditional step, update) and Inspecting/modifying gradients (unscale_before clipping), plus Troubleshooting forinfandNaNloss - LLMs from Scratch Appendix D: worked clipping exampleLLMs from Scratch companion - training and generation
Section D.3 (L2 norm worked example on the gradient matrix , before-and-after clipping comparison) and Section D.4 (clipping inside the modified training function)
Focus on
- Clipping rescales the whole gradient vector when its global norm passes . Direction is preserved; only the step length is capped.
- Under a scaler, gradients are scaled by , so
unscale_must run before the norm check or the threshold tests the wrong numbers. - Autocast keeps compute-heavy ops in
float16but reductions and the loss infloat32, because they need the dynamic range. - A skipped optimizer step is protection working, not a bug. The log should show the skip, the shrunken scale and the recovery.
Common mistakes · 3
- Clipping the scaled gradients. The norm test then uses a threshold meant for unscaled values and either never fires or always fires.
- Running
backwardunderautocast. Backward ops must run in the dtype chosen for theforwardops, outside the context. - Retrying a diverged run with the same seed and settings. The overflow recurs; lower the scale policy, the clip threshold or the learning rate first.
Try it yourself
Closed-book, before checking anything
unscale_, the skip-on-inf rule and the per-step values to log.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.The global gradient norm is 5 and is 1. What does clipping do?Answer
It multiplies every gradient by about , the factor . The resulting norm sits just under 1 and the update direction is unchanged.
2.Why must
scaler.unscale_run before gradient clipping?AnswerBackward under a scaler leaves gradients multiplied by the scale . Clipping tests the norm against , so on scaled values the comparison is wrong by a factor of and corrupts the step.
3.The scaler finds
infgradients and skipsoptimizer.step. What must still run, and what happens to the batch?Answerscaler.update()still runs so the scale shrinks for the next step. The batch contributes no update; its gradients are discarded.4.Under
autocast, linear layers run infloat16but the loss stays infloat32. Why?AnswerLinears are compute-heavy and safe in half precision, while the loss is a reduction that needs
float32dynamic range. The recipe asserts output isfloat16and loss isfloat32.
Practice
- CS336 Assignment 1:
gradient_clippingProblem (
gradient_clipping) in Section 4.5; connect your function torun_gradient_clippingintests/adapters.pyand passtest_gradient_clippingintests/test_nn_utils.pyThe test compares against
clip_grad_norm_with a frozen parameter andmax_norm1e-2. Implement it in your own repository. - PyTorch AMP recipe: add
autocastandGradScalerto the default-precision loopSections Adding
torch.autocastthrough All together: run the default-precision loop, convert it, and keep the output-dtype and loss-dtype asserts greenRun on any CUDA machine you can access; on CPU, read the scale and skip logic and wire the same order into your own loop without claiming speedups.
You're done when
Your clipping matches the reference in test_gradient_clipping, and your AMP loop holds the recipe dtype asserts while you explain each skip from your own log.
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.
- 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.
Also in this section
- 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.
- 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.