When backward overshoots, clip it
Some training setups produce gradients with huge norms — RNNs over long sequences, very deep networks without proper normalization, GANs, transformer training without warmup. Huge gradients × any learning rate produce huge updates that destabilize training (NaN losses, sudden divergence).
Gradient clipping bounds the magnitude of gradients before the optimizer step. Two common variants:
- Clip by global norm — compute the L2 norm of all gradients combined, scale them down if it exceeds a threshold. Most common in modern training (Transformers, LLM fine-tuning, etc.).
- Clip by value — clamp each gradient element to
[-c, c]. Cruder, but useful when you have outlier elements rather than overall large norms.
Where it goes in the loop
Always between backward() and optimizer.step(). Clipping before backward doesn't make sense (no gradients yet); clipping after step is too late.
A typical max_norm value is 1.0 for transformer training, sometimes 5.0 for RNNs. The right value is empirical — log the actual gradient norm during training and you'll see whether you're hitting the cap often.