Simple Algorithm
Deep Learning · Emergence · 26 min

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 (L0,L1)(L_0, L_1)-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:

g ← g⋅min⁡(1, c∥g∥)\mathbf g\ \leftarrow\ \mathbf g\cdot\min\Big(1,\ \frac{c}{\norm{\mathbf g}}\Big)
Below the threshold cc nothing changes; above it the step has length exactly ηc\eta c. Pascanu et al. suggested setting cc from the typical gradient norm observed over many updates, and found training not very sensitive to it. Earlier, Mikolov (2012) had clipped the gradient's entries one by one (clipping by value), which also bounds the step but changes its direction.
Check your understanding

A gradient g=(3,4)\mathbf g = (3, 4) is clipped with threshold c=1c = 1. What do norm clipping and value clipping return?

  1. Both return (0.6,0.8)(0.6, 0.8)
  2. Norm clipping (1,1)(1, 1); value clipping (0.6,0.8)(0.6, 0.8)
  3. Norm clipping (0.6,0.8)(0.6, 0.8), same direction; value clipping (1,1)(1, 1), a different direction
  4. Both return (1,1)(1, 1)
Show the answer

C. Norm clipping (0.6,0.8)(0.6, 0.8), same direction; value clipping (1,1)(1, 1), a different direction

∥g∥=5\norm{\mathbf g} = 5, so norm clipping multiplies by 1/51/5: (0.6,0.8)(0.6, 0.8), still at 53.1∘53.1^\circ. Value clipping caps each entry at 11: (1,1)(1, 1), at 45∘45^\circ and of length 2\sqrt2. 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 GiG_i and weights WiW_i of unit ii (a row of a weight matrix), if ∥Gi∥F/∥Wi∥F⋆>λ\norm{G_i}_F/\norm{W_i}^\star_F > \lambda the gradient is rescaled to λ ∥Wi∥F⋆ Gi/∥Gi∥F\lambda\,\norm{W_i}^\star_F\,G_i/\norm{G_i}_F, where ∥Wi∥F⋆=max⁡(∥Wi∥F,10−3)\norm{W_i}^\star_F = \max(\norm{W_i}_F, 10^{-3}). It bounds the relative change of each unit's weights in one step. With λ=0.01\lambda = 0.01 at batch sizes of 1,024 to 4,096 (smaller λ\lambda 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 LL-smoothness, ∥∇2f∥≤L\norm{\nabla^2f}\le L everywhere, and uses the step 1/L1/L. 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 MM at all; the fixed-step bound grows almost linearly with it, and a matching upper bound for fixed-step GD with h=1/(2(ML1+L0))h = 1/(2(ML_1 + L_0)) shows the dependence is real, up to the logarithm. Since MM can be astronomically large near a cliff, clipping can be faster by an arbitrary factor.

DerivationWhy: the proof idea
  1. h∥∇f∥2−O(L0+L1∥∇f∥)2 h2∥∇f∥2h\norm{\nabla f}^2 - \frac{\order{L_0 + L_1\norm{\nabla f}}}{2}\,h^2\norm{\nabla f}^2

    Under (L0,L1)(L_0, L_1)-smoothness, the curvature within a distance of order 1/L11/L_1 of x\mathbf x is at most of order L0+L1∥∇f(x)∥L_0 + L_1\norm{\nabla f(\mathbf x)}, so a step x−h∇f(x)\mathbf x - h\nabla f(\mathbf x) that stays in that ball decreases ff by at least

  2. Δf ≳ min⁡{∥∇f∥2L0, ∥∇f∥L1}\Delta f\ \gtrsim\ \min\Big\{\frac{\norm{\nabla f}^2}{L_0},\ \frac{\norm{\nabla f}}{L_1}\Big\}

    Choosing h∝1/(L0+L1∥∇f∥)h\propto1/(L_0 + L_1\norm{\nabla f}), which is what clipping does up to constants, makes the decrease of order ∥∇f∥2/(L0+L1∥∇f∥)\norm{\nabla f}^2/(L_0 + L_1\norm{\nabla f}): about ∥∇f∥2/L0\norm{\nabla f}^2/L_0 where gradients are small and about ∥∇f∥/L1\norm{\nabla f}/L_1 where they are large. Summed until ∥∇f∥≤ϵ\norm{\nabla f}\le\epsilon, this gives the two terms of the clipped bound.

  3. A fixed step must be safe at the steepest point it may visit, so h≲1/(L1M)h\lesssim1/(L_1M), and then in flat regions each step gains only about hϵ2≈ϵ2/(L1M)h\epsilon^2\approx\epsilon^2/(L_1M). 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.

Check your understanding

Which of these functions on R\R is (L0,L1)(L_0, L_1)-smooth for some constants, but not LL-smooth for any LL?

  1. f(x)=x2f(x) = x^2
  2. f(x)=x4f(x) = x^4
  3. f(x)=∣x∣3/2f(x) = \abs{x}^{3/2}
  4. f(x)=sin⁡xf(x) = \sin x
Show the answer

B. f(x)=x4f(x) = x^4

f′′=12x2f'' = 12x^2 is unbounded, so x4x^4 is not LL-smooth, but 12x2≤12+3∣4x3∣12x^2\le12 + 3\abs{4x^3} (check ∣x∣≤1\abs x\le1 and ∣x∣>1\abs x > 1 separately), so it is (12,3)(12, 3)-smooth. Its curvature grows with its gradient, like the cliffs of a network.

Noisy gradients: heavy tails and bias

Training uses stochastic gradients g=∇f+noise\mathbf g = \nabla f + \text{noise}, 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 α\alpha-th moment, E∥g−∇f∥α≤σα\E\norm{\mathbf g - \nabla f}^\alpha\le\sigma^\alpha with α∈(1,2]\alpha\in(1, 2]; for α<2\alpha < 2 the variance may be infinite. Then plain SGD can fail outright: even for f(x)=x2/2f(x) = x^2/2 and any step sizes fixed in advance, they show E∥∇f(xk)∥2=∞\E\norm{\nabla f(x_k)}^2 = \infty.

The exponents show how much heavy tails cost: at α=1.5\alpha = 1.5 the nonconvex rate is K−1/5K^{-1/5} instead of K−1/4K^{-1/4}. 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 σ2\sigma^2), 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 cc only reaches a neighborhood of stationarity, min⁡tE∥∇f(xt)∥≤O(min⁡{σ,σ2/c})+(terms that vanish with small steps and long training)\min_t\E\norm{\nabla f(\mathbf x_t)}\le\order{\min\{\sigma,\sigma^2/c\}} + (\text{terms that vanish with small steps and long training}), and that the first term cannot be removed: there are smooth functions with noise variance σ2\sigma^2 whose clipped-SGD fixed points have ∥∇f∥≥σ/12\norm{\nabla f}\ge\sigma/12 when c≤2σc\le2\sigma, and ∥∇f∥≥σ2/(6c)\norm{\nabla f}\ge\sigma^2/(6c) at larger thresholds. Without noise, by contrast, the threshold affects only higher-order terms.

Predict before you look

At some point the true gradient is 0.50.5, and the stochastic gradient is 0.5+20.5 + 2 or 0.5−20.5 - 2 with probability 12\tfrac12 each. What is the expected clipped gradient with threshold c=2c = 2?

Show the answer

0.25

The samples 2.52.5 and −1.5-1.5 clip to 22 and −1.5-1.5, averaging 0.250.25: half the true gradient. With c=1c = 1 they clip to 11 and −1-1, averaging 00, so clipped SGD would stall at this point although f′(x)=0.5f'(x) = 0.5. That is the bias of Koloskova et al. in miniature.

Clipping in practice

python
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.

Predict before you look

A model's three layers have gradient norms 33, 44 and 1212. 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 32+42+122=13\sqrt{3^2 + 4^2 + 12^2} = 13, so every gradient is multiplied by 1/131/13: the first layer's becomes 3/13≈0.233/13\approx0.23, and the update keeps its direction. Clipping each layer to norm 11 separately would instead give all three layers norm 11, more than doubling the first layer's share of the update.

Thresholds. For large language models a global threshold of 1.01.0 is a common choice; for example, LLaMA was trained with AdamW, weight decay 0.10.1 and gradient clipping at 1.01.0 (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 ∼1/(1−β2)\sim1/(1 - \beta_2) 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 g←gmin⁡(1,c/∥g∥)\mathbf g\leftarrow\mathbf g\min(1, c/\norm{\mathbf g}) keeps the direction and bounds the step; value clipping changes the direction; adaptive clipping bounds each unit's relative update.
  • Under (L0,L1)(L_0, L_1)-smoothness, ∥∇2f∥≤L0+L1∥∇f∥\norm{\nabla^2f}\le L_0 + L_1\norm{\nabla f}, clipped GD needs O(L0F0/ϵ2)\order{L_0F_0/\epsilon^2} iterations independently of the largest gradient norm MM, while fixed-step GD can need Ω(L1MF0/(ϵ2log⁡M))\Omega(L_1MF_0/(\epsilon^2\log M)).
  • Under heavy-tailed noise (α<2\alpha < 2) plain SGD can fail and clipped SGD attains the optimal rates; under bounded-variance noise clipping adds a bias of order min⁡{σ,σ2/c}\min\{\sigma,\sigma^2/c\} 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.

Question 1

Why is clipping by the global norm usually preferred to clipping each gradient entry?

  1. It is cheaper to compute
  2. It makes the gradient unbiased
  3. It shortens the update while keeping its direction, so the step still points where the gradient does
  4. 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 min⁡(1,c/∥g∥)\min(1, c/\norm{\mathbf g}). Entry-wise clipping changes the direction, sometimes a lot when many coordinates are large.

Question 2

On an (L0,L1)(L_0, L_1)-smooth function whose gradient can reach a huge norm MM on the sublevel set, how do clipped GD and fixed-step GD compare (Zhang et al., 2020)?

  1. Clipped GD's iteration bound does not depend on MM, while fixed-step GD needs a number of iterations growing almost linearly in MM on some such functions
  2. Both need a number of iterations proportional to MM
  3. Fixed-step GD is faster, because clipping throws away gradient information
  4. Neither converges, since the function is not LL-smooth
Show the answer

A. Clipped GD's iteration bound does not depend on MM, while fixed-step GD needs a number of iterations growing almost linearly in MM on some such functions

A fixed step must be safe at the steepest point, h≲1/(L1M)h\lesssim1/(L_1M), which makes it crawl elsewhere; clipping shortens only the steps taken where the gradient is large.

Question 3

Gradient noise has a finite α\alpha-th moment for some α∈(1,2)\alpha\in(1, 2) but infinite variance. What is known (Zhang et al., 2020)?

  1. Plain SGD converges at the usual rate; clipping is unnecessary
  2. No first-order method can converge at all
  3. Clipped SGD converges only if the noise is symmetric
  4. Plain SGD with step sizes fixed in advance can fail even on x2/2x^2/2, while clipped SGD converges at rates such as K−(α−1)/(3α−2)K^{-(\alpha-1)/(3\alpha-2)} (nonconvex), which no algorithm can beat
Show the answer

D. Plain SGD with step sizes fixed in advance can fail even on x2/2x^2/2, while clipped SGD converges at rates such as K−(α−1)/(3α−2)K^{-(\alpha-1)/(3\alpha-2)} (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 α=2\alpha = 2 they recover K−1/4K^{-1/4}.

Question 4

With ordinary bounded-variance noise σ2\sigma^2, what does clipped SGD with a fixed threshold cc converge to (Koloskova, Hendrikx & Stich, 2023)?

  1. An exact stationary point, as long as the step size decays
  2. A neighborhood of stationarity of size about min⁡{σ,σ2/c}\min\{\sigma,\sigma^2/c\} in gradient norm, which no choice of step size removes
  3. A point whose loss is at most cc above the minimum
  4. It diverges whenever c<σc < \sigma
Show the answer

B. A neighborhood of stationarity of size about min⁡{σ,σ2/c}\min\{\sigma,\sigma^2/c\} 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 cc grows relative to σ\sigma, 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).