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 None
Inspect 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)}

About this algorithm

How Clip one global gradient norm before updating works

The idea

Gradient clipping limits how far one update can move the weights. Clipping by global norm treats the gradients of every parameter as a single long vector, measures its length (the L2 norm) and, if that length is above cap, multiplies every gradient by the same factor, about cap / norm.

The shared factor is the point. It shortens the step but keeps its direction, so the layers stay in proportion to each other. Clipping each layer on its own would give each a different factor and bend the update away from the true gradient. A gradient already shorter than cap is left alone, never scaled up.

How it works

  1. Reject misaligned or empty groups, non-finite numbers, lr < 0 and cap <= 0 before touching anything.
  2. Copy each list in values into a new torch.nn.Parameter, so the caller's lists are never changed.
  3. Attach each gradient as .grad, and leave .grad unset where the gradient is None.
  4. Call clip_grad_norm_ once over all parameters: it measures the combined norm and scales every gradient by one factor if the norm exceeds cap.
  5. Under torch.no_grad(), subtract lr times the clipped gradient from each parameter that has one.
  6. Return the new values and norm, the length measured before clipping.

What it costs

Per step
O(P)
Memory
O(1) extra
Scales with
parameter count P

Measuring the norm reads every gradient entry once and rescaling writes each one once, so clipping adds two cheap passes over the P parameters to a training step.

Where it is used

  • Hugging Face Transformers' Trainer clips the global gradient norm to max_grad_norm, 1.0 by default, before every optimizer step.
  • Pascanu, Mikolov and Bengio proposed norm clipping in 2013 to stop exploding gradients when training recurrent networks.
  • Stable-Baselines3's PPO clips the global gradient norm at 0.5 by default through its max_grad_norm setting.

Watch out for

  • Clipping each layer or tensor separately: every layer gets its own factor, so the update no longer points along the true gradient.
  • Rescaling every gradient to exactly cap: clipping only shrinks, and a small gradient must pass through unchanged.
  • Reading the value returned by clip_grad_norm_ as the clipped norm: it is the norm from before clipping.