Clipping early stopping and mixed precision
Quick answer
Gradient clipping limits large update inputs, early stopping selects model weights using validation progress, and mixed precision uses lower precision selectively to reduce resource use. These techniques address different failure modes. Examples are static Python snippets tested locally on PyTorch CPU. ByteMind execution is unverified.
Global norm clipping
import torchw=torch.nn.Parameter(torch.zeros(2,dtype=torch.float64)); w.grad=torch.tensor([3.,4.],dtype=w.dtype)g=torch.nn.utils.clip_grad_norm_([w],2.,error_if_nonfinite=True)print(round(g.item(),4),[round(x,4) for x in w.grad.tolist()])Expected output (locally tested): 5.0 [1.2, 1.6]. The pre-clip norm is five; both components share approximately the same 0.4 scale.
How it works
Global norm clipping computes G=sqrt(sum of squared gradients) across parameters and multiplies by min(1,max_norm/(G+eps)); PyTorch clip_grad_norm_ modifies gradients in place and returns the pre-clip norm. Clip after backward and before optimizer.step(); error_if_nonfinite=True helps surface numerical failures. Early stopping tracks a validation metric, saves a copy of best weights and stops after a configured patience; restore best weights, not necessarily the optimizer state. Specify strict improvement, tie policy and epoch indexing. For equal-budget comparison, train all candidates for the same maximum epochs then select the best validation checkpoint (not actual early termination). Autocast selects precision per operation; CPU bfloat16 has a wide exponent range and often does not need loss scaling. CUDA float16 commonly uses torch.amp.GradScaler("cuda"): scale loss, backward, unscale optimizer gradients before clipping, scaler.step, scaler.update. Do not assume every op becomes low precision, that loss scaling fixes all overflow, or that CPU speed predicts GPU speed.
CPU autocast with a backward pass
import torchw=torch.nn.Parameter(torch.ones((2,2)))x=torch.ones((1,2))with torch.autocast("cpu",dtype=torch.bfloat16): y=x@w; loss=(y.float()**2).mean()loss.backward()print(str(y.dtype),str(w.grad.dtype),bool(torch.isfinite(w.grad).all()))Expected output (locally tested): torch.bfloat16 torch.float32 True. The matrix product uses bfloat16 while the parameter gradient is float32. No GPU behavior is inferred.
Common mistakes
Do not clip scaled gradients before unscaling, clip parameters instead of gradients, or select epochs from final test data. Save a deepcopy of state_dict rather than a live reference. Mixed precision must be tested for stability and hardware support.
Practice and next steps
Compute the scale for a gradient vector (3,4) with max norm 2. Compare selected checkpoint with final epoch. Test CPU autocast separately from CUDA, which is not available here.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Clipping early stopping and mixed precision — knowledge check
Apply clipping early stopping and mixed precision to small examples and debugging scenarios.
What does clip_grad_norm_ return?
When clip with GradScaler?
Which metric selects the best epoch?
What is autocast responsible for?
Why copy a best state_dict?