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 autocast dtype choice and how GradScaler protects small gradients from underflow.
  • Log gradient norms, loss scale and skipped steps, and read overflow signals from the log.

Covers

Gradient clipping and numerical-event loggingMixed-precision vocabulary, scaling and overflow signals
1

Read

In this order, only the parts listed

0 of 3 done

  1. 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 eps 1e-6, applied in place after the backward pass

  2. PyTorch AMP recipe: autocast, GradScaler and clipping orderPyTorch Automatic Mixed Precision recipe

    Sections Adding torch.autocast (forward under autocast, never backward), Adding GradScaler (scale, backward, conditional step, update) and Inspecting/modifying gradients (unscale_ before clipping), plus Troubleshooting for inf and NaN loss

  3. 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)

2

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 float16 but reductions and the loss in float32, 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 backward under autocast. Backward ops must run in the dtype chosen for the forward ops, 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.
3

Try it yourself

Closed-book, before checking anything

Write the clip-then-step order for a plain loop and an AMP loop, including unscale_, the skip-on-inf rule and the per-step values to log.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 2.Why must scaler.unscale_ run before gradient clipping?Answer

    Backward 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. 3.The scaler finds inf gradients and skips optimizer.step. What must still run, and what happens to the batch?Answer

    scaler.update() still runs so the scale shrinks for the next step. The batch contributes no update; its gradients are discarded.

  4. 4.Under autocast, linear layers run in float16 but the loss stays in float32. Why?Answer

    Linears are compute-heavy and safe in half precision, while the loss is a reduction that needs float32 dynamic range. The recipe asserts output is float16 and loss is float32.

5

Practice

  • CS336 Assignment 1: gradient_clipping

    Problem (gradient_clipping) in Section 4.5; connect your function to run_gradient_clipping in tests/adapters.py and pass test_gradient_clipping in tests/test_nn_utils.py

    The test compares against clip_grad_norm_ with a frozen parameter and max_norm 1e-2. Implement it in your own repository.

  • PyTorch AMP recipe: add autocast and GradScaler to the default-precision loop

    Sections Adding torch.autocast through All together: run the default-precision loop, convert it, and keep the output-dtype and loss-dtype asserts green

    Run 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.