liveBook · Manning

Gradient clipping

As explained in Inside Deep Learning: Math, Algorithms, Models

A training stabilization method that caps gradient values to a chosen threshold to prevent excessively large updates.

Gradient clipping stabilizes training by limiting excessively large gradient values before they produce unreasonable parameter updates. For a threshold z, each gradient value is restricted to the interval [-z, z], while smaller values remain unchanged. It works with SGD, Adam, and learning-rate schedules, and directly addresses exploding gradients. section 5.3.3

Elementwise clipping

With z = 5, g = [1, -2, 1000, 3, -7] becomes clip₅(g) = [1, -2, 5, 3, -5]. In PyTorch, register a hook on every model parameter and clamp each gradient: for p in model.parameters(): p.register_hook(lambda grad: torch.clamp(grad, -5, 5)). This implementation clips values independently rather than rescaling the whole gradient. section 5.3.3

Use clipping when exploding gradients prevent learning, and treat its effect as empirical: it can improve or worsen results when the model is otherwise stable. Recurrent neural networks are a common case for including it because recurrent connections tend to produce exploding gradients. An autoregressive character model uses a tighter [-2, 2] bound. section 5.3.3 section 7.5.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Defines elementwise thresholding and demonstrates PyTorch hooks and clamp, but does not develop alternative clipping algorithms.
Examples
Uses a vector threshold example, parameter hooks, FashionMNIST comparisons, and an autoregressive character GRU.
What it assumes
Assumes model parameters, gradients, optimizers, and recurrent networks, while introducing the clipping rule directly.
What you can do after
Apply it via PyTorch parameter hooks and torch.clamp, then compare training results empirically.
How it connects
Connects exploding gradients with SGD, Adam, learning-rate schedules, and recurrent neural networks.

Also explained in

Compare how 2 books explain gradient clipping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.