Gradient Clipping and Mixed Precision

The optimizer and schedule from the previous lesson assume gradients are sane. They usually are not. A single bad batch can spike the gradient norm by three orders of magnitude. Mixed-precision training amplifies this by introducing FP16 overflow on the loss side. This lesson builds the two safety belts that production training cannot ship without: gradient clipping to a configured global L2 norm, and a mixed-precision loop with autocast and GradScaler that detects NaN and Inf, skips the step cleanly, and logs the scaling factor for forensics.

Build 1.5 hr Python

Prerequisites: Phase 19 lessons 30-37

#Learning Objectives

  • Compute the global L2 norm over all parameter gradients and clip in place when it exceeds a configured threshold.
  • Wrap a training step in autocast plus a GradScaler so FP16 forward and backward passes survive overflow.
  • Detect NaN and Inf in the loss or gradient, skip the optimizer step, and log the skip.
  • Report the GradScaler's scaling factor every step so a long sequence of skips is visible immediately.
Full Access lesson

Keep going. The rest of this lesson is one step away.

Unlock all 503 lessons, video, code, quizzes and every future update. Pay in your own currency with Paystack.

The text and code of this lesson are based on AI Engineering from Scratch by Rohit Ghumare, MIT licensed.