REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Clip one global gradient norm before updating
Clipping each layer independently defines a different update from clipping the norm of the entire gradient vector.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Clip one global gradient norm before updating →
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.
Starter
import torch
def clipped_update(values, gradients, lr, cap):
return NoneInspect the worked answer
import math
import torch
def clipped_update(values, gradients, lr, cap):
if len(values) != len(gradients) or not values:
raise ValueError('aligned parameter and gradient groups required')
if not math.isfinite(lr) or lr < 0 or not math.isfinite(cap) or cap <= 0:
raise ValueError('nonnegative learning rate and positive norm cap required')
if any(not row or any(not math.isfinite(v) for v in row) for row in values):
raise ValueError('nonempty finite parameter groups required')
for value, gradient in zip(values, gradients):
if gradient is not None and (len(value) != len(gradient) or any(not math.isfinite(g) for g in gradient)):
raise ValueError('finite shape-aligned gradients required')
parameters = [torch.nn.Parameter(torch.tensor(row, dtype=torch.float64)) for row in values]
for parameter, gradient in zip(parameters, gradients):
if gradient is not None:
parameter.grad = torch.tensor(gradient, dtype=torch.float64)
norm = torch.nn.utils.clip_grad_norm_(parameters, cap, error_if_nonfinite=True)
with torch.no_grad():
for parameter in parameters:
if parameter.grad is not None:
parameter.add_(parameter.grad, alpha=-lr)
return {'values': [p.detach().tolist() for p in parameters], 'norm': float(norm)}