Overview
The gradient tells the optimizer which way to move and, through its length, how far. Usually that length is reasonable. Now and then, on a steep part of the loss surface or with an unlucky batch, it is hundreds of times larger, and one step throws the weights far away and undoes earlier progress. Clipping puts a ceiling on the step. Clipping by norm shortens the whole gradient like shortening an arrow: the direction stays and only the length changes. Clipping by value cuts off each number separately, which is simpler but bends the direction.
A short history
Recurrent networks were known since the early 1990s to suffer from gradients that grow without bound over long sequences. Tomas Mikolov clipped gradient values in his language model work around 2012. Razvan Pascanu, Tomas Mikolov and Yoshua Bengio analysed the problem in their 2013 paper "On the difficulty of training recurrent neural networks" and proposed rescaling the gradient when its norm exceeds a threshold. It is now routine for sequence models.
How it works
- Compute the gradients as usual, as a list or dictionary of arrays.
- Call clip. It first measures the global norm: the square root of the sum of squares of every entry of every array.
- If the norm is not a finite number, an error is raised, because clipping cannot repair NaN or infinite gradients.
- In norm mode, if the global norm is above max_norm, every array is multiplied by the same factor, max_norm divided by the norm. Otherwise nothing changes.
- In per_param_norm mode the same rule is applied to each array on its own, with its own norm.
- In value mode every entry is limited to the range from minus clip_value to clip_value.
- clip returns the new gradients and the norm before clipping. Log that norm, then pass the clipped gradients to the optimizer.
Watch out for
- If the gradient is clipped on nearly every step, the limit is acting as the real learning rate: every step has the same length. Watch the logged norm and raise the limit or lower the learning rate.
- Clipping by value changes the direction of the gradient, because large entries are cut and small ones are not. The step no longer points along the steepest descent.
- Clipping hides the symptom, not the cause. A norm that keeps exploding points to a learning rate that is too high, bad initialisation or bad data.
- Clipping each array separately changes the balance between layers, since a layer with a large gradient is cut while another is not. The combined direction is not preserved.
- A NaN gradient cannot be clipped. This template raises an error and does not pass it on, so the cause has to be found.
Use cases
When to use it
For recurrent networks, transformers, reinforcement learning and any training run where the loss sometimes spikes or turns into NaN. Clipping by global norm is the usual default.
In industry
- Language models
- Transformer language models are commonly trained with the global gradient norm clipped, often at 1.0, to survive occasional bad batches.
- Speech and sequence modelling
- LSTM and GRU models for speech and time series rely on clipping to prevent exploding gradients over long sequences.
- Reinforcement learning
- Algorithms such as PPO clip the gradient norm in common implementations, because reward scales and targets shift during training.
Choosing it: what must hold
- Training by gradient descent where occasional very large gradients cause loss spikes or NaN values.
- A threshold chosen from the observed gradient norms. Set too low, it slows learning on every step.
- For clipping by norm, the norm taken over all parameters together, so the gradient's direction is kept.
When to choose something else
| If | Use instead |
|---|---|
| Gradients are large on every step, not only now and then | A lower learning rate or a warmup schedule |
| The cause is poor initialisation or missing normalisation | Fix the initialisation or add normalisation layers |
| Gradients vanish instead of exploding | Gated units such as LSTM or GRU, or residual connections |
Math foundations
The global norm
All gradient arrays are treated as one long vector. Its length measures how large the whole update would be. This is what global_norm returns.
Clipping by norm
If the norm is at most the gradient is unchanged. Otherwise it is scaled down so its norm is exactly . Every entry is multiplied by the same factor, so the direction is kept.
What it guarantees
For plain gradient descent no single step can move the weights farther than the learning rate times the limit. That bound is what stops one bad batch from wrecking the run.
Clipping by value
Each entry is limited on its own to the range . Large entries shrink and small ones do not, so the direction generally changes.
Clipping each array
The norm rule applied to each parameter array separately. Each array keeps its own direction, but the arrays are rescaled by different factors.
Symbols
- all gradients taken together as one vector
- the gradient array of parameter p, and its i-th entry
- the global L2 norm of the gradients
- the clipped gradients
- max_norm, the limit on the norm
- clip_value, the limit on each entry
- the learning rate of the optimizer
Worked by hand
A model has two gradient arrays, and . Clip by global norm with , then separately by value with .
Norm clipping halves every entry, so the ratios 3 to 4 to 12 are kept and the norm is exactly 6.5. Value clipping changes only the 12, so the ratios become 3 to 4 to 5 and the direction has changed.
Visual example
Loading the example.
Try this
- Lower the limit: every gradient larger than it is cut to the same length.
Code sample
import numpy as np
from impl import GradClipper
from config import GradClipConfig
clipper = GradClipper(GradClipConfig(mode="norm", max_norm=1.0))
x = np.array([3.0]) # minimise f(x) = x^4, whose gradient explodes far from 0
for _ in range(200):
grads, norm_before = clipper.clip([4.0 * x**3])
x -= 0.1 * grads[0] # without the clip the first step would jump to -7.8
print(x, norm_before)Read the implementation (74 lines)
"""Gradient clipping on plain NumPy arrays: by global norm, by per-array norm and by value.
NumPy only. Gradients are a list of arrays or a dict of name -> array. `clip` returns new arrays in the same
structure together with the norm measured before clipping, which is worth logging: a norm that keeps hitting
the limit, or a sudden spike, says a lot about the health of a training run.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import GradClipConfig
except ImportError: # run from the template's own folder
from config import GradClipConfig
def _arrays(grads) -> list[np.ndarray]:
"""The gradient arrays of a list or dict, skipping None entries (parameters without a gradient)."""
values = grads.values() if isinstance(grads, dict) else grads
return [np.asarray(g, dtype=float) for g in values if g is not None]
def global_norm(grads) -> float:
"""L2 norm of all gradients taken together: sqrt(sum over every entry of every array of g^2)."""
return math.sqrt(sum(float(np.sum(g * g)) for g in _arrays(grads)))
class GradClipper:
"""Clips gradients. After each `clip`, `last_norm` is the global norm before clipping and `last_clipped`
says whether anything was changed."""
def __init__(self, config: GradClipConfig | None = None) -> None:
self.config = config or GradClipConfig()
self.last_norm = 0.0
self.last_clipped = False
def _clip_one(self, g: np.ndarray, scale: float) -> np.ndarray:
"""Clip one array. `scale` is the shared factor of "norm" mode (1.0 when no rescaling is needed)."""
cfg = self.config
if cfg.mode == "norm":
return g * scale
if cfg.mode == "value":
return np.clip(g, -cfg.clip_value, cfg.clip_value)
norm = float(np.linalg.norm(g))
return g * (cfg.max_norm / norm) if norm > cfg.max_norm else g.copy()
def clip(self, grads):
"""Return (clipped_grads, norm_before).
grads: list or dict of arrays (None entries are passed through). clipped_grads has the same structure
and holds new arrays; the input is not modified. norm_before: global L2 norm of the input.
"""
norm = global_norm(grads)
if not math.isfinite(norm):
raise FloatingPointError("gradients contain NaN or infinity; clipping cannot repair that")
scale = self.config.max_norm / norm if norm > self.config.max_norm else 1.0
if isinstance(grads, dict):
out = {k: None if g is None else self._clip_one(np.asarray(g, dtype=float), scale) for k, g in grads.items()}
else:
out = [None if g is None else self._clip_one(np.asarray(g, dtype=float), scale) for g in grads]
self.last_norm = norm
self.last_clipped = any(not np.array_equal(a, b) for a, b in zip(_arrays(grads), _arrays(out)))
return out, norm
def clip_(self, grads) -> float:
"""Clip in place (the arrays of `grads` are overwritten) and return the norm before clipping."""
clipped, norm = self.clip(grads)
keys = grads.keys() if isinstance(grads, dict) else range(len(grads))
for k in keys:
if grads[k] is not None:
grads[k][...] = clipped[k]
return norm- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create a dictionary of three random gradient arrays and scale one of them by 1000. Call GradClipper.clip in each of the three modes set through GradClipConfig. For each result print global_norm, last_clipped, and the cosine of the angle between the original and the clipped gradients (flattened into one vector). Explain which mode keeps the cosine at exactly 1 and why.
Check on learning
- During training you log the norm before clipping and see it is above max_norm on 95 percent of steps. What is the optimizer effectively doing, and what would you change?
A way to think about it
If every gradient is rescaled to the same length, only its direction is used. Compare that with what the learning rate is meant to control.
- Why does clipping by norm keep the direction while clipping by value does not? When might the changed direction not matter much?
A way to think about it
Multiply a vector by one number, and then cap its entries one by one, and compare the ratios between entries. Then think about optimizers such as Adam that already rescale each entry.
- A recurrent network multiplies by a similar matrix at every time step during backpropagation. Why does this make exploding gradients likely, and why is clipping a natural remedy?
A way to think about it
Raise a number slightly above 1 to the power of the sequence length. Clipping caps the result without touching the ordinary steps.
- Clipping makes the training curve smooth again, but the unclipped norm keeps growing over time. Is the problem solved?
A way to think about it
Ask what a steadily growing gradient norm says about the weights or the loss surface, and what clipping does and does not change about that.