Exploding Gradients & Clipping
Cliffs in the loss, relaxed smoothness and why clipping speeds training.
Every so often a training run's loss jumps, or its weights turn into NaNs after one bad step. The culprit is usually a gradient hundreds or thousands of times longer than normal, and the classic fix is almost embarrassingly simple: if the gradient is too long, shorten it. This lesson explains why that works, from the cliffs of recurrent networks to theorems showing that clipping can beat any fixed step size, and what clipping costs when gradients are noisy.
What you’ll learn
- Explain how exploding gradients create cliffs in the loss, and apply norm clipping, value clipping and adaptive unit-wise clipping, knowing which preserve the update's direction.
- State the -smoothness condition and the bounds showing that clipped gradient descent can be arbitrarily faster than gradient descent with any fixed step size on this class.
- Explain why clipping restores convergence under heavy-tailed gradient noise, with the optimal rates, and why clipped SGD is biased under ordinary noise.
- Use clipping in practice: global norms, thresholds, per-example clipping in differentially private SGD, and what clipping statistics reveal.
Cliffs in the loss
A gradient explodes when the Jacobians it passes through have norms above one, through many layers or, in a recurrent network, through many time steps. Pascanu, Mikolov and Bengio (2013) analyzed recurrent networks, deriving conditions on the recurrent weights and the activation's maximal slope under which long-range gradients must vanish or can explode, and gave a geometric picture: where gradients explode, the curvature in the same direction explodes too, so the loss surface has cliffs, steep walls beside otherwise gentle valleys. A gradient step that lands on a wall is enormous and throws the parameters far away, undoing many steps of progress. The direction of that gradient is still informative (it points away from the wall); only its length is useless.
Clipping by norm (Pascanu et al., 2013) rescales the whole gradient when it is too long, keeping its direction:
A gradient is clipped with threshold . What do norm clipping and value clipping return?
- Both return
- Norm clipping ; value clipping
- Norm clipping , same direction; value clipping , a different direction
- Both return
Show the answer
C. Norm clipping , same direction; value clipping , a different direction
, so norm clipping multiplies by : , still at . Value clipping caps each entry at : , at and of length . With many coordinates, value clipping can rotate the update far from the gradient.
Global or per-layer? PyTorch's clip_grad_norm_ treats all the parameters you pass it as one long vector, so the whole update keeps its direction. Clipping each layer separately changes the relative step sizes between layers. Adaptive gradient clipping (Brock, De, Smith & Simonyan, 2021) goes further and compares each unit's gradient with its own weights: for the gradient and weights of unit (a row of a weight matrix), if the gradient is rescaled to , where . It bounds the relative change of each unit's weights in one step. With at batch sizes of 1,024 to 4,096 (smaller for larger batches), and no clipping of the final linear layer, it let normalizer-free ResNets train stably at large batch sizes (Training Without Normalization).
Relaxed smoothness: why clipping speeds training up
Textbook gradient descent assumes -smoothness, everywhere, and uses the step . That assumption fails in exactly the way cliffs suggest. Zhang, He, Sra and Jadbabaie (2020) measured the local smoothness along training trajectories and found it strongly correlated with the gradient norm in LSTM language models (and in ResNets trained with clipping at large learning rates): the steep places are the curved places. They proposed a weaker condition that captures this.
The clipped bound does not depend on at all; the fixed-step bound grows almost linearly with it, and a matching upper bound for fixed-step GD with shows the dependence is real, up to the logarithm. Since can be astronomically large near a cliff, clipping can be faster by an arbitrary factor.
Under -smoothness, the curvature within a distance of order of is at most of order , so a step that stays in that ball decreases by at least
Choosing , which is what clipping does up to constants, makes the decrease of order : about where gradients are small and about where they are large. Summed until , this gives the two terms of the clipped bound.
A fixed step must be safe at the steepest point it may visit, so , and then in flat regions each step gains only about . The lower bound builds a function on which this is unavoidable. Clipping is, in effect, a step size that adapts to the local curvature through the gradient norm.
Which of these functions on is -smooth for some constants, but not -smooth for any ?
Show the answer
B.
is unbounded, so is not -smooth, but (check and separately), so it is -smooth. Its curvature grows with its gradient, like the cliffs of a network.
Noisy gradients: heavy tails and bias
Training uses stochastic gradients , and here clipping plays two opposite roles. Zhang, Karimireddy, Veit, Kim, Reddi, Kumar and Sra (2020) found the gradient noise of attention models such as BERT to be heavy-tailed, and modeled it by assuming only a bounded -th moment, with ; for the variance may be infinite. Then plain SGD can fail outright: even for and any step sizes fixed in advance, they show .
The exponents show how much heavy tails cost: at the nonconvex rate is instead of . The same paper proposed ACClip, which clips each coordinate adaptively, and used these results to argue that heavy-tailed noise is one reason adaptive methods beat SGD on attention models, an argument Why Adam Beats SGD on Transformers weighs against the competing explanations.
The other side: when the noise is ordinary (bounded variance ), clipping introduces a bias. Clipping shrinks large samples more than small ones, so the average clipped gradient is not the clipped average gradient. Koloskova, Hendrikx and Stich (2023) showed that clipped SGD with threshold only reaches a neighborhood of stationarity, , and that the first term cannot be removed: there are smooth functions with noise variance whose clipped-SGD fixed points have when , and at larger thresholds. Without noise, by contrast, the threshold affects only higher-order terms.
At some point the true gradient is , and the stochastic gradient is or with probability each. What is the expected clipped gradient with threshold ?
Show the answer
0.25
The samples and clip to and , averaging : half the true gradient. With they clip to and , averaging , so clipped SGD would stall at this point although . That is the bias of Koloskova et al. in miniature.
Clipping in practice
import torch
for x, y in loader:
loss = loss_fn(model(x), y)
optimizer.zero_grad(set_to_none=True)
loss.backward()
# one global norm over all parameters; returns the norm *before* clipping
total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
log(grad_norm=total_norm.item(), clipped=total_norm.item() > 1.0)clip_grad_value_(params, clip_value) clips entry by entry instead. Logging the pre-clipping norm costs nothing and is one of the most useful training diagnostics: spikes in it often accompany loss spikes, and a run that clips at every step is effectively using normalized gradient descent with a different learning rate.
A model's three layers have gradient norms , and . After clip_grad_norm_ with max_norm = 1.0, what is the norm of the first layer's gradient?
Show the answer
0.23
The global norm is , so every gradient is multiplied by : the first layer's becomes , and the update keeps its direction. Clipping each layer to norm separately would instead give all three layers norm , more than doubling the first layer's share of the update.
Thresholds. For large language models a global threshold of is a common choice; for example, LLaMA was trained with AdamW, weight decay and gradient clipping at (Touvron et al., 2023). Because the pre-clipping norm depends on the loss scale, model size and training phase, the right threshold is empirical. With Adam, clipping matters even though Adam normalizes each coordinate: a single enormous gradient would otherwise inflate the second-moment estimate for the next steps and shrink all of them.
Key takeaways
- Exploding gradients come with exploding curvature: cliffs in the loss where one step can throw the parameters far away. Norm clipping keeps the direction and bounds the step; value clipping changes the direction; adaptive clipping bounds each unit's relative update.
- Under -smoothness, , clipped GD needs iterations independently of the largest gradient norm , while fixed-step GD can need .
- Under heavy-tailed noise () plain SGD can fail and clipped SGD attains the optimal rates; under bounded-variance noise clipping adds a bias of order that no step size removes.
- In practice: clip the global norm (1.0 is a common choice for large language models), log the pre-clipping norm, and remember that per-example clipping in DP-SGD serves privacy, not stability.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why is clipping by the global norm usually preferred to clipping each gradient entry?
- It is cheaper to compute
- It makes the gradient unbiased
- It shortens the update while keeping its direction, so the step still points where the gradient does
- It guarantees that the loss decreases at every step
Show the answer
C. It shortens the update while keeping its direction, so the step still points where the gradient does
Norm clipping multiplies the whole vector by . Entry-wise clipping changes the direction, sometimes a lot when many coordinates are large.
On an -smooth function whose gradient can reach a huge norm on the sublevel set, how do clipped GD and fixed-step GD compare (Zhang et al., 2020)?
- Clipped GD's iteration bound does not depend on , while fixed-step GD needs a number of iterations growing almost linearly in on some such functions
- Both need a number of iterations proportional to
- Fixed-step GD is faster, because clipping throws away gradient information
- Neither converges, since the function is not -smooth
Show the answer
A. Clipped GD's iteration bound does not depend on , while fixed-step GD needs a number of iterations growing almost linearly in on some such functions
A fixed step must be safe at the steepest point, , which makes it crawl elsewhere; clipping shortens only the steps taken where the gradient is large.
Gradient noise has a finite -th moment for some but infinite variance. What is known (Zhang et al., 2020)?
- Plain SGD converges at the usual rate; clipping is unnecessary
- No first-order method can converge at all
- Clipped SGD converges only if the noise is symmetric
- Plain SGD with step sizes fixed in advance can fail even on , while clipped SGD converges at rates such as (nonconvex), which no algorithm can beat
Show the answer
D. Plain SGD with step sizes fixed in advance can fail even on , while clipped SGD converges at rates such as (nonconvex), which no algorithm can beat
Clipping tames the rare huge samples that make SGD's second moment infinite. The rates are tight: matching lower bounds hold for every algorithm. At they recover .
With ordinary bounded-variance noise , what does clipped SGD with a fixed threshold converge to (Koloskova, Hendrikx & Stich, 2023)?
- An exact stationary point, as long as the step size decays
- A neighborhood of stationarity of size about in gradient norm, which no choice of step size removes
- A point whose loss is at most above the minimum
- It diverges whenever
Show the answer
B. A neighborhood of stationarity of size about in gradient norm, which no choice of step size removes
Clipping changes the expected update: large samples are shrunk more than small ones, so fixed points of clipped SGD can have nonzero true gradient. The bias shrinks as grows relative to , and vanishes without noise.
Further reading
- R. Pascanu, T. Mikolov & Y. Bengio, "On the difficulty of training recurrent neural networks," ICML (2013).
- J. Zhang, T. He, S. Sra & A. Jadbabaie, "Why gradient clipping accelerates training: A theoretical justification for adaptivity," ICLR (2020).
- J. Zhang, S. P. Karimireddy, A. Veit, S. Kim, S. J. Reddi, S. Kumar & S. Sra, "Why are adaptive methods good for attention models?," NeurIPS (2020).
- A. Koloskova, H. Hendrikx & S. U. Stich, "Revisiting gradient clipping: Stochastic bias and tight convergence guarantees," ICML (2023).
- A. Brock, S. De, S. L. Smith & K. Simonyan, "High-performance large-scale image recognition without normalization," ICML (2021).