Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Vanishing and exploding gradients

P4.1640 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

In a deep network the gradient that reaches an early layer is a long product of per-layer factors, so it can shrink to nothing or blow up, and then the early layers stop learning or training breaks.

  • Residual connections add an identity term to every layer's Jacobian, so the product cannot fade. (P4.20: Residual connections)
  • Normalization layers keep the scale of every layer near one in both directions. (P4.19: Normalization layers)
  • LSTMs and GRUs reuse one matrix over many time steps, and their gates keep the gradient alive. (P6.7: LSTM, coming soon)
  • Gradient clipping is part of the standard recipe for training large models and recurrent networks. (P10.B7: Training stability, coming soon)

Before this: Backpropagation: step by step with numbers, Activation functions, Weight initialization, Vector functions and the Jacobian

After this lesson you can

  • Write the backward pass as a product of per-layer Jacobians, and explain why a factor slightly below or above 1 makes the gradient vanish or explode exponentially with depth
  • Read the cause of a bad gradient from the gradient lengths layer by layer, for sigmoid, tanh and ReLU stacks
  • Name the remedies (activation, initialization, normalization, skip connections, gating, clipping) and say what each one changes
  • Clip a gradient by global norm and by value by hand, say which keeps its direction, and use clip_grad_norm_ correctly

Take a network with 20 sigmoid layers of 32 units and the LeCun starting weights (P4.12). Run one example forward, then send a gradient of length 1 backward from the output. At the layer nearest the output the gradient has length 0.240.24. At layer 1 it has length 1.7×10−131.7\times10^{-13}, about 1.4 trillion times smaller (a factor of about 101210^{12}). Layer 1 receives a gradient so small that no sensible learning rate can turn it into a useful step.

Nothing in the code is wrong. Backpropagation (P4.8) computed every number correctly. The size shrank because the gradient is multiplied by one factor per layer, and a factor below 1, repeated 20 times, is small. This lesson shows where the factors come from, what the problem looks like in a training run, and the tools that tame it.

The backward pass is a product

P4.8 sent a gradient back through a network one layer at a time. Here is that step with vectors. Layer ℓ\ell computes

zℓ=Wℓhℓ−1+bℓ,hℓ=ϕ(zℓ),\mathbf{z}_\ell=\mathbf{W}_\ell\mathbf{h}_{\ell-1}+\mathbf{b}_\ell,\qquad \mathbf{h}_\ell=\phi(\mathbf{z}_\ell),

where ϕ\phi is the activation function (P4.4). Write gℓ=∇hℓL\mathbf{g}_\ell=\nabla_{\mathbf{h}_\ell}L for the gradient of the loss with respect to the output of layer ℓ\ell. The Jacobian of the layer (P1.C7) is the matrix of all the rates of change of hℓ\mathbf{h}_\ell with respect to hℓ−1\mathbf{h}_{\ell-1}:

Jℓ=DℓWℓ,Dℓ=diag(ϕ′(zℓ)).\mathbf{J}_\ell=\mathbf{D}_\ell\mathbf{W}_\ell,\qquad \mathbf{D}_\ell=\mathrm{diag}\bigl(\phi'(\mathbf{z}_\ell)\bigr).

The matrix Dℓ\mathbf{D}_\ell holds the activation slopes on its diagonal, one per unit. The chain rule then gives the backward step

gℓ−1=Jℓ⊤gℓ=Wℓ⊤Dℓ gℓ.\mathbf{g}_{\ell-1}=\mathbf{J}_\ell^\top\mathbf{g}_\ell=\mathbf{W}_\ell^\top\mathbf{D}_\ell\,\mathbf{g}_\ell .

Apply it from the last layer to the first and the gradient at the input is a product, J1⊤J2⊤⋯JLlayers⊤gLlayers\mathbf{J}_1^\top\mathbf{J}_2^\top\cdots\mathbf{J}_{L_{\text{layers}}}^\top\mathbf{g}_{L_{\text{layers}}}. The gradient that the parameters of layer ℓ\ell use comes from the same chain. The gradient of the bias is δℓ=Dℓgℓ\boldsymbol{\delta}_\ell=\mathbf{D}_\ell\mathbf{g}_\ell (the ∂L/∂zℓ\partial L/\partial\mathbf{z}_\ell of P4.8), and the gradient of the weights is δℓhℓ−1⊤\boldsymbol{\delta}_\ell\mathbf{h}_{\ell-1}^\top.

Each factor can shrink a vector or stretch it (P1.C7). A product of many factors does this many times over, and that is the whole story. The rest of the lesson is about how big the factors are and what to do when they are not near 1.

One number per layer

Start with the simplest case: every layer multiplies the gradient by the same number aa. After kk layers the gradient is aka^k times its starting size.

  • 0.950≈0.0050.9^{50}\approx0.005: fifty layers that each keep 90 percent leave half of one percent.
  • 1.150≈1171.1^{50}\approx117: fifty layers that each add 10 percent give a factor of 117.
  • 0.97100≈0.0480.97^{100}\approx0.048 and 1.03100≈191.03^{100}\approx19: a 3 percent error per layer is already a factor of 20 over 100 layers.
  • It takes 132 layers of 0.90.9 to fall below 10−610^{-6}.

The pattern is exponential in depth. A factor that is a little off 1 is harmless in 3 layers and a disaster in 100. P1.C3 gave the sigmoid example, where a stack of 10 sigmoid layers with weight 1 multiplies the gradient by about 4×10−74\times10^{-7} and the same stack with weight 8 multiplies it by 210=10242^{10}=1024. A unit pushed into the flat tail does worse than 14\frac14: at z=6z=6 the slope is 0.00250.0025 (P1.C2), so three such layers give 1.6×10−81.6\times10^{-8}.

One matrix per layer

A real factor is a matrix, not a number, so it acts differently on different directions. The singular values of a matrix (P1.B13) are its stretch factors: the largest is the most it can lengthen a vector, the smallest is the most it can shorten one. Take the matrix diag(2,12)\mathrm{diag}(2,\tfrac12), which stretches the first direction by 2 and squeezes the second by 12\frac12, and apply it to the vector (1,1)(1,1):

  • after 1 layer: (2, 0.5)(2,\,0.5), length 2.062.06;
  • after 5 layers: (32, 0.031)(32,\,0.031), length 3232;
  • after 10 layers: (1024, 0.00098)(1024,\,0.00098), length 10241024.

The stretched direction takes over and the squeezed direction disappears. A gradient that lies along a stretched direction grows. To guarantee vanishing for every gradient, every direction must be squeezed. The bound goes one way only: ∥Mx∥≤σmax⁡∥x∥\lVert\mathbf{M}\mathbf{x}\rVert\le\sigma_{\max}\lVert\mathbf{x}\rVert, so a product of factors whose largest singular values are all below 1 must shrink every gradient. For one matrix applied again and again (the case of a recurrent network, P6.5) the same story is told by the eigenvalues, as P1.B12 showed with its powers λk\lambda^k.

A random matrix with the right scale is a middle case (P4.12): it keeps the length on average but stretches some directions and shrinks others, and over many layers the length drifts. Orthogonal matrices have all singular values equal to 1, and keep the length exactly, in a linear chain.

Add the activation

The factor of layer ℓ\ell is DℓWℓ\mathbf{D}_\ell\mathbf{W}_\ell, so the slopes in Dℓ\mathbf{D}_\ell multiply in:

  • Sigmoid: the slope is at most 14\frac14, and smaller away from z=0z=0.
  • tanh: the slope is at most 1, reached at z=0z=0, and falls towards 0 when the unit saturates.
  • ReLU: the slope is exactly 1 where the unit is on and exactly 0 where it is off.

With LeCun weights the weights alone keep the length about the same (P4.12), so the slopes decide. In the hook, a sigmoid slope averages about 0.230.23, and 20 layers multiply 0.230.23 nineteen times, which gives the 10−1210^{-12} above. A ReLU stack with the He scale (P4.12) keeps a factor of about 1 on average, because doubling the weight variance makes up for the half of the units that are off. P4.4 showed the same direction with bars for a 6-layer stack. See it in the widget:

See it: the gradient at every layer

The widget builds a stack of 5 to 30 layers with 32 units each, runs one made-up example forward, then sends a made-up starting gradient of length 1 from the output (right) back to layer 1 (left). Each bar is the length of the gradient of that layer, on a log scale (so the first bar is below 1: the gradient has already passed through the last layer’s slopes). Press Play the backward pass to watch it travel, or Step to move one layer at a time.

Weight scale: every weight is drawn with standard deviation scale÷√32 (×1 is the LeCun rule of P4.12; ×1.4 is close to He's 1.41). 32 units per layer.

seed 1 of 5
5101520−30−20−10010

Bar height: the length of that layer's gradient as a power of 10 (the scale reads 0 for length 1, the dotted line where the backward pass starts, and −20 for 10−20). Layer 1 is next to the input, the output is on the right, so the pass travels from right to left. A small triangle at the foot or the top of a bar means the value is off the scale; an outlined triangle marks a dashed bar.

  • Layer 20 (first reached)0.237
  • Layer 1 (last reached)1.72e−13
  • Layer 1 ÷ layer 207.24e−13
  • Typical factor per layer×0.23

The gradient fades: layer 1 gets almost nothing.

Show the length at every layer
LayerLength
11.72e−13
21.08e−12
34.29e−12
41.54e−11
57.07e−11
63.70e−10
71.44e−9
88.06e−9
93.77e−8
101.59e−7
115.93e−7
122.63e−6
131.48e−5
145.56e−5
152.10e−4
169.73e−4
170.00455
180.0184
190.071
200.237

A made-up input and a made-up starting gradient (length 1). Plain layers use h = activation(Wh); skip connections use h = h + activation(Wh). The length of a layer's gradient is the length of ∂L/∂z, which is also the gradient of that layer's bias. In Lite Mode, Play shows the final bars at once.

The backward pass through a deep stack. The gradient starts with length 1 at the output on the right and travels left. Each orange bar is the length of one layer's gradient (the gradient of its bias), on a log scale; the dotted line is length 1. Choose Sigmoid, tanh or ReLU, change the depth and the weight scale (×1 is the LeCun rule, ×1.4 is close to He), switch skip connections on, or clip by global norm and watch the dashed outlines, which show the bars before clipping. In Lite Mode, Play shows the final bars at once.

What the widget shows with its default random weights (seed 1; running the same algorithm in NumPy reproduces every number):

  1. Sigmoid, 20 layers, scale ×1. Layer 20 has length 0.2370.237 and layer 1 has 1.7×10−131.7\times10^{-13}, a ratio of 7.2×10−137.2\times10^{-13}, or about ×0.23\times0.23 per layer. Over the five seeds the ratio stays between 3×10−133\times10^{-13} and 1.5×10−121.5\times10^{-12}. Raise the depth to 30 and the ratio falls to 1.7×10−191.7\times10^{-19}.
  2. ReLU, 30 layers. At scale ×1.4 (close to He’s 2=1.41\sqrt2=1.41) the ratio is 0.390.39: the gradient keeps a usable size. Lower the scale to ×1 and it falls to 2.3×10−52.3\times10^{-5}, to ×0.5 and it falls to 4.2×10−144.2\times10^{-14}. Raise it to ×2 and it grows to 1.2×1041.2\times10^{4}, to ×3 and it reaches 1.6×1091.6\times10^{9}. A small change of scale turns “fine” into vanishing or exploding, as in the one-number picture.
  3. tanh, 30 layers, scale ×1. The ratio is 0.0530.053: a mild fade, because the slope of tanh is near 1 for small zz. At scale ×3 the weights win and the gradient grows by a factor of about 5×1035\times10^{3}.
  4. Skip connections. Switch them on with sigmoid at ×1 and 30 layers: the ratio goes from 1.7×10−191.7\times10^{-19} to 1010. The fading is gone. With ReLU the picture is different: at ×1.4 the skip makes the ratio 3.7×1053.7\times10^{5}, and only at a small scale such as ×0.2 does it come back to 1.51.5. P4.20 explains why a skip path helps and how real residual networks keep the sum under control.
  5. Clipping. Choose ReLU, depth 30, scale ×3, and switch on Clip by global norm with c=1c=1. The total length of all the bars is 1.06×1091.06\times10^{9}, so every bar is multiplied by 9.4×10−109.4\times10^{-10}. The bar at layer 1 becomes 0.900.90, but the bar at layer 30 becomes 5.8×10−105.8\times10^{-10}. The total is under control and the ratio between layers is exactly as before. Clipping does not repair the shape of the problem. Switch back to the default sigmoid stack with clipping on: the total length is 0.250.25, below c=1c=1, so nothing changes and layer 1 is still tiny.

The widget measures the gradient of the bias, which is δℓ=∂L/∂zℓ\boldsymbol{\delta}_\ell=\partial L/\partial\mathbf{z}_\ell. The gradient of the weights is δℓ\boldsymbol{\delta}_\ell times the layer’s input, and that input also shrinks or grows in the forward pass, which can cancel the trend in a plain stack and hide it. For a chain with factor aa per layer, the backward part is aLlayers−ℓa^{L_{\text{layers}}-\ell} and the forward part is aℓ−1a^{\ell-1}, so their product has almost no trend. The bias gradient shows the backward product alone.

What it looks like in training

Vanishing. The layers near the output learn, and the layers near the input barely move, because their gradients are tiny. Typical signs: the loss drops a little and then plateaus, the first layers’ weights are almost the same after thousands of steps, and the per-layer gradient norms fall steadily towards the input. The network behaves like a shallow one stacked on top of nearly random early layers.

Exploding. One step can be enormous: the loss spikes up, the weights jump, and soon a value overflows to infinity (P1.G1), after which operations such as ∞−∞\infty-\infty give NaN (P1.G2). Once a NaN enters the weights it stays, so the loss prints nan from then on.

Not every blow-up is exploding gradients

A loss that explodes does not prove the gradients exploded through depth. A learning rate that is too large does it with a network of one weight. Minimise L(w)=w2L(w)=w^2 by gradient descent from w=1w=1. The gradient is 2w2w, so one step gives w←w−2ηw=(1−2η)ww\leftarrow w-2\eta w=(1-2\eta)w. With η=1.1\eta=1.1 the factor is −1.2-1.2, and after 20 steps w=38.3w=38.3 and the gradient is 76.776.7. With η=0.9\eta=0.9 the factor is −0.8-0.8 and ww shrinks to 0.01150.0115. With η=0.4\eta=0.4 it shrinks to 10−1410^{-14}. The gradient grows here because each step lands farther from the minimum, as in P1.F3, not because of depth. The cure is a smaller learning rate or a schedule (P4.13, P4.14), and gradient clipping only softens the damage.

So the first question is where the gradient is large. If the per-layer norms grow towards the input, it is the product. If they are all moderate and the loss still jumps, look at the step size and the data (P4.22).

Remedies

The causes are all ways for the factors to drift from 1: saturating activations (P4.4), a bad starting scale (P4.12), depth, which amplifies any drift, and one matrix used many times, as in a recurrent network (P6.5), where backpropagation through time (P6.6) multiplies by W⊤\mathbf{W}^\top again and again. Each remedy changes the factors in a different way:

  • Activations that do not saturate (ReLU and relatives, P4.4): the slope is 1 where the unit is on, so the 14\frac14 of the sigmoid disappears. Units that are off pass nothing back, and a unit that is off for every input stops learning.
  • A good starting scale (P4.12): He for ReLU, Xavier for tanh, orthogonal matrices. This puts the factors near 1 at step 0, but training can move them.
  • Normalization layers (P4.19) keep each layer’s scale near a fixed size during training, forward and backward.
  • Skip connections (P4.20) change the layer to hℓ=hℓ−1+ϕ(Wℓhℓ−1)\mathbf{h}_\ell=\mathbf{h}_{\ell-1}+\phi(\mathbf{W}_\ell\mathbf{h}_{\ell-1}). Its Jacobian is I+Jℓ\mathbf{I}+\mathbf{J}_\ell, and the product (I+J3)(I+J2)(I+J1)(\mathbf{I}+\mathbf{J}_3)(\mathbf{I}+\mathbf{J}_2)(\mathbf{I}+\mathbf{J}_1) expands into I+J3+J2+J1+J3J2+⋯\mathbf{I}+\mathbf{J}_3+\mathbf{J}_2+\mathbf{J}_1+\mathbf{J}_3\mathbf{J}_2+\cdots. The first term is a path with no factors at all, so the gradient has a route to layer 1 that cannot fade. The other terms can still be large, which is the ReLU case of the widget.
  • Gated recurrent cells (LSTM and GRU, P6.7, P6.8) add a path through time that is mostly copied, for the same reason as a skip.
  • Gradient clipping (next section) limits an explosion. It does not fix the shape of a vanishing gradient.
  • A shallower network, or a smaller learning rate, when the cause is the step size and not the product.
Go deeper A bound for sigmoid layers

The factor of a sigmoid layer is DℓWℓ\mathbf{D}_\ell\mathbf{W}_\ell, and the size of a product of matrices is at most the product of their sizes. The largest singular value of Dℓ\mathbf{D}_\ell is at most 14\frac14 (the largest sigmoid slope), so σmax⁡(Jℓ)≤14σmax⁡(Wℓ)\sigma_{\max}(\mathbf{J}_\ell)\le\frac14\sigma_{\max}(\mathbf{W}_\ell). If every Wℓ\mathbf{W}_\ell has σmax⁡<4\sigma_{\max}<4, each backward step shrinks every vector by a fixed factor below 1, and the gradient must vanish exponentially with depth, for every direction. Pascanu, Mikolov and Bengio (2013) used this kind of argument for recurrent networks. The converse does not hold: σmax⁡(W)>4\sigma_{\max}(\mathbf{W})>4 allows growth but does not force it, because the slopes are usually far below 14\frac14 and the stretched direction may not line up with the gradient.

Go deeper Adaptive optimizers, tiny gradients and number formats

Adam (P4.13) divides each step by the typical size of that parameter’s gradient. With a steady gradient gg the update is about η g/(∣g∣+ε)\eta\,g/(|g|+\varepsilon), with ε=10−8\varepsilon=10^{-8}. For g=10−3g=10^{-3} that is about η\eta, so a small gradient still gets a full-size step: the scale problem is partly hidden. For g=10−13g=10^{-13} it is 10−5η10^{-5}\eta, because ε\varepsilon dominates, so a very small gradient is still ignored. A step of full size is also a step along a direction made of noise if the gradient was tiny because the signal faded, so a better-scaled gradient is still better.

Number formats add a limit of their own. The smallest positive normal number in float16 is 6.1×10−56.1\times10^{-5} and the smallest subnormal one is 6×10−86\times10^{-8}, so values between 6×10−86\times10^{-8} and 6.1×10−56.1\times10^{-5} keep fewer and fewer digits, and values below about 3×10−83\times10^{-8} round to 0 in float16. Mixed-precision training multiplies the loss by a constant (loss scaling) before the backward pass to avoid it (P10.B5). The gradient of layer 1 in the hook, 10−1310^{-13}, would be lost in float16 even before the question of learning.

Gradient clipping

Clipping handles the other end: a gradient that is suddenly very large, from a rare input or an unlucky step. Instead of taking an enormous step, shrink the gradient to a maximum length cc and take a step of that size. The common form is clipping by global norm. Treat all the parameter gradients of the whole network as one long vector g\mathbf{g}, and compute its length ∥g∥\lVert\mathbf{g}\rVert, the square root of the sum of all squared entries (P1.B4). Then:

g  ←  g⋅min⁡ ⁣(1,  c∥g∥).\mathbf{g}\;\leftarrow\;\mathbf{g}\cdot\min\!\Bigl(1,\;\frac{c}{\lVert\mathbf{g}\rVert}\Bigr).

If ∥g∥≤c\lVert\mathbf{g}\rVert\le c the factor is 1 and nothing changes. If ∥g∥>c\lVert\mathbf{g}\rVert>c every entry is multiplied by the same number below 1, so the new length is exactly cc.

A worked example. A tiny network has two gradient tensors, (3,4)(3,4) and (12,0)(12,0). The global norm is 9+16+144=13\sqrt{9+16+144}=13. With c=5c=5 the factor is 5/13=0.38465/13=0.3846, and the clipped tensors are (1.154, 1.538)(1.154,\,1.538) and (4.615, 0)(4.615,\,0). The new global norm is 5. The cosine between the old and the new gradient is 1.0 (the angle is 0), so the direction is exactly the same.

Clipping by value instead limits each entry to [−v,v][-v,v]. With v=4v=4 the tensors become (3,4)(3,4) and (4,0)(4,0). The cosine with the original is 0.8770.877 (an angle of about 29∘29^\circ): the large entry was cut and the others were not, so the direction changed. The clipped gradient never points against the original (every entry keeps its sign, so their dot product is positive), so it is still a descent direction, but the step no longer follows the gradient exactly, and clipping by norm is usually the better default. A third form clips every tensor to its own norm. It also changes the relative sizes of the layers’ gradients, so it changes the direction of the whole gradient.

What clipping does and does not do. It caps the size of one step, which protects against a single huge gradient. It cannot lift a gradient that is too small: when ∥g∥<c\lVert\mathbf{g}\rVert<c nothing happens, and the widget’s default sigmoid stack with clipping on is unchanged. It also does not fix a cause. A network that explodes at every step will be clipped at every step and move at the speed of cc. The value of cc comes from watching the norm in an ordinary run: a limit a little above the typical norm clips only the spikes. Many published recipes use a limit of 1. The GPT-3 paper, for example, says it clips the global norm of the gradient at 1.0.

In PyTorch

The call goes between backward() and the optimizer step. clip_grad_norm_ rescales the gradients in place and returns the total norm from before clipping, which makes it also a monitoring tool:

loss.backward()
total = torch.nn.utils.clip_grad_norm_(
    model.parameters(), max_norm=1.0)   # returns the norm BEFORE clipping
optimizer.step()

Internally PyTorch multiplies by min⁡(1, c/(∥g∥+10−6))\min\bigl(1,\,c/(\lVert\mathbf{g}\rVert+10^{-6})\bigr), a hair below the formula so that a zero norm does not divide by zero. clip_grad_value_(params, clip_value) is the clip-by-value version. If you use mixed precision with a gradient scaler, unscale the gradients before clipping (P10.B5).

Monitoring: look at the gradient norms

The loss alone cannot tell you which problem you have. Also log the total gradient norm (which clip_grad_norm_ returns for free) and the gradient norm of each layer. Per-layer norms that fall steadily towards the input mean vanishing, a total that sometimes jumps 100 times above its typical value is the spike that clipping cuts, and any nan needs attention at once. P4.22 uses these logs in a full debugging routine. The Value engine of P4.9 would show the same numbers if you printed .grad on each node of a deep chain.

On the history: Hochreiter’s 1991 diploma thesis at the Technical University of Munich analysed why gradient-based learning struggles with long chains, and Bengio, Simard and Frasconi’s 1994 paper, “Learning long-term dependencies with gradient descent is difficult”, made the problem widely known for recurrent networks. Mikolov’s 2012 PhD thesis had already clipped gradient entries one by one in language models. Pascanu, Mikolov and Bengio (ICML 2013), “On the difficulty of training recurrent neural networks”, analysed the problem and argued for clipping the gradient norm.

Depth: three ways to see it

Intuition

Think of a message passed along a line of people, each of whom repeats only 80 percent of the loudness they heard. After 10 people the message is a tenth as loud, and after 40 it can hardly be heard. If each person repeats it 20 percent louder, the last one shouts. The people at the front of the line, the early layers, are the ones who hear the faded message and cannot tell the right way to adjust. Where the picture breaks: the layers are not equal, a gradient is a vector, and a stretched direction can stay loud while others fade.

Math

The backward pass is gℓ−1=Jℓ⊤gℓ\mathbf{g}_{\ell-1}=\mathbf{J}_\ell^\top\mathbf{g}_\ell with Jℓ=DℓWℓ\mathbf{J}_\ell=\mathbf{D}_\ell\mathbf{W}_\ell, so

g0=J1⊤J2⊤⋯JLlayers⊤ gLlayers,∥g0∥≤∏ℓσmax⁡(Jℓ)  ∥gLlayers∥.\begin{aligned} \mathbf{g}_0&=\mathbf{J}_1^\top\mathbf{J}_2^\top\cdots\mathbf{J}_{L_{\text{layers}}}^\top\,\mathbf{g}_{L_{\text{layers}}},\\ \lVert\mathbf{g}_0\rVert&\le\prod_\ell\sigma_{\max}(\mathbf{J}_\ell)\;\lVert\mathbf{g}_{L_{\text{layers}}}\rVert . \end{aligned}

A typical factor aa gives ∥g0∥≈aLlayers\lVert\mathbf{g}_0\rVert\approx a^{L_{\text{layers}}}. With skip connections Jℓ→I+Jℓ\mathbf{J}_\ell\to\mathbf{I}+\mathbf{J}_\ell. Clipping by global norm: g←gmin⁡(1,c/∥g∥)\mathbf{g}\leftarrow\mathbf{g}\min(1,c/\lVert\mathbf{g}\rVert), where ∥g∥2\lVert\mathbf{g}\rVert^2 is the sum of the squared entries over all parameters. The direction g/∥g∥\mathbf{g}/\lVert\mathbf{g}\rVert does not change. Clipping by value uses gi←clip(gi,−v,v)g_i\leftarrow\mathrm{clip}(g_i,-v,v) for each entry.

Code

A 20-layer sigmoid network in PyTorch, with the gradient norm of each layer’s weights printed, then one call of clip_grad_norm_ with a small limit:

import torch
import torch.nn as nn

torch.manual_seed(0)
layers = []
for _ in range(20):
    layers += [nn.Linear(32, 32), nn.Sigmoid()]
model = nn.Sequential(*layers, nn.Linear(32, 1))

x, y = torch.randn(64, 32), torch.randn(64, 1)
loss = ((model(x) - y) ** 2).mean()
loss.backward()

linears = [m for m in model if isinstance(m, nn.Linear)]
for i in (1, 10, 21):
    g = linears[i - 1].weight.grad.norm().item()
    print(f"layer {i:2d}  grad norm {g:.2e}")

total = nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.01)
after = torch.sqrt(sum(p.grad.pow(2).sum()
                       for p in model.parameters()))
print("total before clip:", f"{total.item():.3e}")
print("total after clip :", f"{after.item():.3e}")

Output from a local run with PyTorch 2.9.1:

layer  1  grad norm 9.83e-18
layer 10  grad norm 6.87e-10
layer 21  grad norm 1.79e+00
total before clip: 1.909e+00
total after clip : 1.000e-02

The gradient norm falls by 18 powers of ten from the last layer to the first. (PyTorch’s default starting weights are a bit smaller than the LeCun scale of the widget, and these are weight gradients, so the numbers differ from the widget’s.) The total norm is dominated by the last layer, so clipping scales everything by about 0.00520.0052 and the first layer’s gradient gets smaller still. The value returned by the call, 1.9091.909, is the norm before clipping.

Try it in Python

The first cell builds a 30-layer network (64 units per layer, 16 made-up examples) and prints the gradient norm of the weights of four layers for sigmoid and for ReLU with He initialization (P4.12).

Per-layer gradient norms, 30 layers

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints, for sigmoid, 2.65×10−182.65\times10^{-18} at layer 1, 1.37×10−121.37\times10^{-12} at layer 10, 2.72×10−62.72\times10^{-6} at layer 20 and 4.484.48 at layer 30. For ReLU with He it prints 33.233.2, 45.545.5, 49.749.7 and 12.412.4: no trend of ten orders of magnitude, only the ordinary differences between layers. These are the gradients of the weights, which include the size of each layer’s input, and with sigmoid the inputs of layers 2 to 30 stay between 0 and 1, so the weight gradients show the same trend as the widget’s bias gradients.

The second cell checks the numbers of this lesson: the powers, the matrix diag(2,12)\mathrm{diag}(2,\frac12), and the clipping example.

Powers, a stretching matrix and two kinds of clipping

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The cell prints 0.950=0.005150.9^{50}=0.00515, 1.150=1171.1^{50}=117, 0.2510=9.54×10−70.25^{10}=9.54\times10^{-7}, 0.97100=0.04760.97^{100}=0.0476 and 1.03100=19.21.03^{100}=19.2, then 132 layers. The matrix part gives lengths 2.062.06, 3232 and 10241024. The clipping part gives the global norm 13, the scale 0.38460.3846, cosine 1.01.0 for clipping by norm and 0.8770.877 for clipping by value.

Common mistakes

Quiz

Check your understanding

  1. Every layer of a 40-layer network multiplies the size of the backward gradient by 0.8. About how large is the gradient at layer 1, compared with its size at the output?

  2. A gradient has a global norm of 20, and the clipping limit is c=5c=5. What does clipping by global norm do?

  3. In a 40-layer ReLU network the logged gradient norms are 0.30.3 at the last layer and 10−1210^{-12} at layer 1, and the loss has stopped improving. Which change goes after the cause?

  4. Why is clipping by global norm usually preferred to clipping each entry by value?

  5. A skip connection changes a layer's Jacobian from J\mathbf{J} to I+J\mathbf{I}+\mathbf{J}. Why does that stop the gradient from fading?

Exercises

  1. Compute 0.9500.9^{50} and 1.1501.1^{50}, and the number of layers of factor 0.90.9 needed to go below 10−610^{-6}.
    Show answer0.950=0.005150.9^{50}=0.00515 and 1.150=1171.1^{50}=117. Since 0.9k<10−60.9^k<10^{-6} needs k>ln⁡(10−6)/ln⁡0.9=131.1k>\ln(10^{-6})/\ln0.9=131.1, it takes 132 layers.
  2. Two gradient tensors are (1,2,2)(1,2,2) and (4,0,3)(4,0,3), and the clipping limit is c=2c=2. Find the global norm and the clipped tensors.
    Show answerThe global norm is 1+4+4+16+0+9=34=5.831\sqrt{1+4+4+16+0+9}=\sqrt{34}=5.831. The factor is 2/5.831=0.3432/5.831=0.343, so the tensors become (0.343, 0.686, 0.686)(0.343,\,0.686,\,0.686) and (1.372, 0, 1.029)(1.372,\,0,\,1.029). Their global norm is 2.
  3. Clip the gradient (0.5,−3,2)(0.5,-3,2) by value with v=1v=1. Does its direction change?
    Show answerThe result is (0.5,−1,1)(0.5,-1,1). The cosine with the original is 0.9620.962, so the direction changes (the angle is about 16∘16^\circ). Clipping by norm to the same length (1.5) would keep the direction.
  4. Gradient descent on L(w)=w2L(w)=w^2 starts at w=1w=1 with η=1.1\eta=1.1. Find the first five values of ww and say whether depth is involved.
    Show answerEach step multiplies ww by 1−2η=−1.21-2\eta=-1.2: −1.2-1.2, 1.441.44, −1.728-1.728, 2.0742.074, −2.488-2.488. The distance from the minimum grows by 1.2 per step. There is no depth: the cause is a learning rate that is too large.
  5. Three layers each have a scalar Jacobian J=0.5J=0.5. Find the product without and with skip connections. Repeat for J=0.1J=0.1.
    Show answerWithout: 0.53=0.1250.5^3=0.125. With: (1+0.5)3=3.375(1+0.5)^3=3.375. For J=0.1J=0.1: 0.13=0.0010.1^3=0.001 without and 1.13=1.3311.1^3=1.331 with. The skip version stays near 1 when JJ is small, and it grows when JJ is large, as 1+3J+3J2+J31+3J+3J^2+J^3.

Next: P4.17 returns to regularization with weight decay, dropout and early stopping, and P4.19 and P4.20 show how normalization layers and residual connections keep the gradient healthy in very deep networks. P6.6 follows the same product through time in recurrent networks.

Key takeaways

  • The backward pass multiplies the gradient by one Jacobian per layer, gℓ−1=Jℓ⊤gℓ\mathbf{g}_{\ell-1}=\mathbf{J}_\ell^\top\mathbf{g}_\ell with Jℓ=DℓWℓ\mathbf{J}_\ell=\mathbf{D}_\ell\mathbf{W}_\ell. If a typical factor is aa, the gradient after kk layers is about aka^k: 0.950≈0.0050.9^{50}\approx0.005 and 1.150≈1171.1^{50}\approx117. Backpropagation computes this product exactly. The product itself is the problem.
  • With matrices, the factor is a stretch that depends on direction (its largest and smallest values are the singular values). A direction stretched by 2 grows like 2k2^k and a direction squeezed by 12\frac12 shrinks like 2−k2^{-k}. A sigmoid slope is at most 14\frac14, so sigmoid stacks tend to vanish. A ReLU slope is 0 or 1, so ReLU stacks keep the scale only if the weight scale is right (P4.12).
  • Vanishing looks like early layers that barely move and a loss that plateaus. Exploding looks like loss spikes, huge weights, then inf or NaN. A learning rate that is too large can also blow up a loss, with no depth involved, so look at the gradient lengths before choosing a cure.
  • Remedies attack the factor: ReLU-like activations (P4.4), a good starting scale (P4.12), normalization layers (P4.19), skip connections that turn each factor into I+J\mathbf{I}+\mathbf{J} (P4.20) and gated recurrent cells (P6.7). Skip connections stop the fading, but the sum can still grow.
  • Clipping by global norm rescales the whole gradient, g←gmin⁡(1,c/∥g∥)\mathbf{g}\leftarrow\mathbf{g}\min(1,c/\lVert\mathbf{g}\rVert), so its direction is kept. Clipping by value changes the direction. Clipping limits explosions and does nothing for vanishing, and logging per-layer gradient norms shows which problem you have.
Found a mistake? Tell us