PythiloLesson 1 of 9 · progress kept in this browser

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())
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.