Gradient Clipping
Training is going well, then one batch produces a gradient a thousand times larger than usual, the update throws the weights far away and the loss jumps to inf or nan. This is an exploding gradient, common in recurrent networks, very deep networks and transformers early in training. Lowering the learning rate for the whole run would avoid it but slow everything down. Gradient clipping handles the rare huge gradient instead: if it is too long, shorten it before the update. It costs one norm per step and is a default in most training recipes for language models.
Where huge gradients come from
Backpropagation multiplies Jacobians layer by layer (or time step by time step in a recurrent network). If a layer multiplies its input by a factor around , the gradient after such layers scales like : , while . The first case is the exploding gradient, the second the vanishing one, which clipping does not help (Vanishing and Exploding Gradients, Backpropagation Through Time). In loss-landscape terms, these models have cliffs: regions where the loss rises very steeply, so a step of normal size computed on the cliff face lands somewhere absurd.
Two ways to clip
Let be the gradient of all parameters stacked into one vector and a threshold.
Clip by value: clamp every component separately,
Clip by (global) norm: if the whole vector is longer than , rescale it to length ,
Norm clipping keeps the direction of the gradient and only shortens the step; value clipping changes the direction, because large components are cut more than small ones. "Global" means one norm over all layers together (PyTorch's clip_grad_norm_), not a separate norm per layer, so the relative sizes of the layers' gradients are preserved too.
import numpy as np
def clip_by_value(grads, c):
return [np.clip(g, -c, c) for g in grads]
def clip_by_global_norm(grads, max_norm):
total = np.sqrt(sum(np.sum(g ** 2) for g in grads)) # one norm over all parameters
scale = min(1.0, max_norm / (total + 1e-6))
return [g * scale for g in grads], total
grads = [np.array([30.0, -4.0]), np.array([0.5, 2.0, -1.0])] # two layers' gradients
flat = lambda gs: np.concatenate(gs)
cos = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
v = clip_by_value(grads, 1.0)
n, total = clip_by_global_norm(grads, 1.0)
print("global norm before:", round(float(total), 3))
print("by value (c=1): ", flat(v), " norm", round(float(np.linalg.norm(flat(v))), 3),
" cosine to original", round(float(cos(flat(v), flat(grads))), 3))
print("by norm (max=1): ", flat(n).round(4), " norm", round(float(np.linalg.norm(flat(n))), 3),
" cosine to original", round(float(cos(flat(n), flat(grads))), 3))global norm before: 30.352
by value (c=1): [ 1. -1. 0.5 1. -1. ] norm 2.062 cosine to original 0.595
by norm (max=1): [ 0.9884 -0.1318 0.0165 0.0659 -0.0329] norm 1.0 cosine to original 1.0
The gradient points mostly along its first component (30). Value clipping turns it into a vector where four of five components are equal: the cosine with the original drops to 0.595, about 53 degrees off. Norm clipping keeps the cosine at 1.0 and only shortens the vector to length 1. That is why norm clipping is the usual choice; value clipping survives mainly in older reinforcement-learning code.
Clipping saves a run that explodes
A one-parameter caricature of a recurrent network: a value is multiplied by twenty times, and we want the result to be 2, so the loss is with gradient . The solution is . Below the gradient is small; above it, it explodes.
import numpy as np
T, target = 20, 2.0 # learn a so that a**T = 2 (a recurrence applied 20 times)
loss = lambda a: (a ** T - target) ** 2
grad = lambda a: 2 * (a ** T - target) * T * a ** (T - 1)
print("gradient at a = 0.9, 1.0, 1.1, 1.2:", [f"{grad(a):.3g}" for a in (0.9, 1.0, 1.1, 1.2)])
def run(clip, lr=0.0005, steps=500, a=1.2):
for step in range(steps):
g = grad(a)
if clip is not None and abs(g) > clip:
g = clip * np.sign(g) # norm clipping in one dimension
a -= lr * g
if not np.isfinite(a) or abs(a) > 1e6:
return f"diverged at step {step + 1} (a = {a:.3g})"
return f"a = {a:.5f}, a**T = {a ** T:.4f}, loss below 1e-12: {loss(a) < 1e-12}"
print("no clipping: ", run(None))
print("clip at norm 1.0: ", run(1.0))
print("solution: a =", round(2 ** (1 / T), 5))gradient at a = 0.9, 1.0, 1.1, 1.2: ['-10.1', '-40', '1.16e+03', '4.64e+04']
no clipping: diverged at step 2 (a = 4.67e+50)
clip at norm 1.0: a = 1.03526, a**T = 2.0000, loss below 1e-12: True
solution: a = 1.03526
From the gradient is 46 400. Even with the small learning rate 0.0005, the first step moves by about 23, to , and the next step overflows. With clipping, every step far from the solution has length , so walks down the cliff at a steady pace; near the solution the gradient falls below the threshold, clipping switches itself off and ordinary gradient descent finishes the job.
Note what clipping did not do: the learning rate still had to be small enough for the curvature at the solution (about 3000 here, so ; see the stability limit). Clipping protects against rare huge gradients; it does not replace a sensible learning rate.
In practice
- Where it goes: after
loss.backward()and beforeoptimizer.step():
loss.backward()
total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()The function returns the norm before clipping; log it. A healthy run has a fairly stable gradient norm; spikes point to bad batches, a too-high learning rate or numerical trouble.
- Choosing the threshold: 1.0 is the common default for transformers; 0.5 to 5 elsewhere. A data-driven choice: run a few hundred steps without clipping, look at the distribution of gradient norms, and clip somewhere above the typical values (for example the 90th to 99th percentile), so clipping only touches outliers.
- With mixed precision (loss scaling), unscale the gradients before clipping, otherwise the threshold applies to the scaled values (Mixed Precision).
- With gradient accumulation, clip once, after the last micro-batch, on the accumulated gradient.
- With Adam, clipping still matters: Adam normalises by a running average, so a single huge gradient also inflates that average and shrinks the following steps.
Pitfalls
- Clipping every step. If the norm is always above the threshold, the optimizer becomes "normalised gradient descent" with a fixed step length; the threshold is too low or the learning rate too high.
- Per-layer instead of global norm changes the relative step sizes of layers.
- Hiding a bug. Exploding gradients from a missing normalisation, a
log(0)or wrong initialisation should be fixed, not just clipped. - Expecting it to fix vanishing gradients. Clipping only shrinks; for vanishing gradients use better initialisation, normalisation, residual connections or gated units (LSTM, GRU).
Practice
- A gradient is . Clip it by norm with and by value with . Which keeps the direction?
Answer
Its norm is 5, so norm clipping gives : same direction, length 1. Value clipping gives : length , direction 45 degrees instead of about 53.1 degrees from the first axis. Norm clipping keeps the direction.
- In the one-parameter example, how many clipped steps does it take, roughly, to walk from to the solution?
Answer
The distance is and each clipped step is long, so about 330 steps. That is why the run uses 500.
Test yourself
What does clipping by global norm do to a gradient whose norm is larger than the threshold ?
- Sets it to zero
- Rescales the whole vector to length , keeping its direction
- Clamps each component to
- Adds noise to it
Why is clipping by value usually avoided?
- It is slower
- It changes the direction of the gradient, because large components are cut more than small ones
- It never changes anything
- It only works for biases
Where in the training step does gradient clipping go?
- Before the forward pass
- Between
loss.backward()andoptimizer.step() - After the optimizer step
- Only at the end of each epoch
Does gradient clipping help with vanishing gradients?
- Yes, it enlarges small gradients
- No, it only shortens gradients that are too long
- Yes, if the threshold is small
- Only with Adam