Practice in Lab: Clip one global gradient norm before updating →
Clip one global gradient norm before updating
Clipping each layer independently defines a different update from clipping the norm of the entire gradient vector. This Lab uses real parameter gradients and a single global clipping call. The returned diagnostic is the norm before clipping; the applied update must use the clipped values. Validate all incoming groups before applying an update so one nonfinite gradient cannot leave a partially changed model. A missing gradient is different from a zero gradient, especially when an optimizer also applies momentum or decay.
import torch
g = torch.tensor([3., 4.])
print(g.norm().item())Review the design
Explain the order of unscaling, nonfinite detection, global clipping and optimizer stepping. This CPU exercise does not execute automatic mixed precision or distributed collectives.
Your task
Implement one SGD update on lists of parameter vectors. A corresponding gradient is a same-length vector or None. Use real torch Parameters and clip_grad_norm_ over all groups together, then subtract lr times the clipped gradient under no_grad. Return values and the pre-clipping norm. Reject empty/misaligned/nonfinite groups, lr<0 and cap<=0. Do not mutate input lists. Parameters with None gradients stay unchanged.
The explanation opens here once every check passes.