7 routes42 sections324 units

Unit 3.4 · about 3 h

307 / 324

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.

  • explain
  • measure

You can now

  • 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 logging
  • Mixed-precision vocabulary, scaling and overflow signals

Study, in this order

3 steps

  1. CS336 Assignment 1 handout: gradient clipping
    Stanford CS336 Assignment 1 - training and decoding contract

    Section 4.5, Gradient clipping (p. 34): the global norm rule with max \(M\) and eps 1e-6, applied in place after the backward pass

  2. PyTorch AMP recipe: `autocast`, `GradScaler` and clipping order
    PyTorch 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 example
    LLMs from Scratch companion - training and generation

    Section D.3 (L2 norm worked example on the gradient matrix \(G\), 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 \(M\). Direction is preserved; only the step length is capped.
  • Under a scaler, gradients are scaled by \(s\), 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.

Reproduce closed-book

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.

Traps

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

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.

Self-test

  1. The global gradient norm is 5 and \(M\) is 1. What does clipping do?

  2. Why must scaler.unscale_ run before gradient clipping?

  3. The scaler finds inf gradients and skips optimizer.step. What must still run, and what happens to the batch?

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

Completion criterion

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

Mark passed, then open 3.5 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • LLMs from Scratch companion - training and generation
    Sebastian Raschkaprimaryimplementation
    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 contract
    Stanford Universityrequiredassessment
    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 recipe
    PyTorchsupportreference
    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 generation
    Walking Labssupportimplementation
    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 references
    PyTorchsupportreference
    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 translation
    Hugging Faceoptionalapplication
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels