TExcelTAD
Home › Math for Deep Learning & LLMs › Vanishing and Exploding Gradients

Vanishing and Exploding Gradients

Backpropagation multiplies one Jacobian per layer. In a deep network that is a long product of matrices, and long products tend to shrink to zero or blow up exponentially. When gradients vanish, the early layers stop learning; when they explode, training diverges. This lesson shows the mechanism and previews the fixes that made deep learning work.

A product of Jacobians

For h(l)=ϕ(W(l)h(l−1))\mathbf{h}^{(l)} = \phi(W^{(l)}\mathbf{h}^{(l-1)}), the gradient reaching layer 1 is

∂L∂h(1)=(∏l=2LW(l)TD(l))∂L∂h(L),D(l)=diag⁡(ϕ′(a(l)))\frac{\partial\mathcal{L}}{\partial\mathbf{h}^{(1)}} = \left(\prod_{l=2}^{L} W^{(l)T}D^{(l)}\right)\frac{\partial\mathcal{L}}{\partial\mathbf{h}^{(L)}}, \qquad D^{(l)} = \operatorname{diag}(\phi'(\mathbf{a}^{(l)}))

Each factor scales a vector by roughly its typical gain γ\gamma. After LL layers the gradient is scaled by about γL\gamma^{L}: with γ=0.9\gamma = 0.9 and L=50L = 50 that is 0.0050.005; with γ=1.1\gamma = 1.1 it is 117117. Only γ≈1\gamma \approx 1 is safe.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n, L = 256, 50
for scale in (0.8, 1.0, 1.2):
    g = rng.normal(size=n); g /= np.linalg.norm(g)
    for _ in range(L):
        W = rng.normal(0, scale / np.sqrt(n), (n, n))    # gain about `scale` per layer
        g = W.T @ g
    print(f"weight scale {scale}: gradient norm after {L} linear layers = {np.linalg.norm(g):.2e}")
weight scale 0.8: gradient norm after 50 linear layers = 1.10e-05
weight scale 1.0: gradient norm after 50 linear layers = 7.75e-01
weight scale 1.2: gradient norm after 50 linear layers = 6.81e+03

The activation's share

Saturating activations add a factor below 1 at every layer: the sigmoid's derivative is at most 0.250.25 (Activations). ReLU contributes 0 or 1, and with He initialization (variance 2/n2/n) the factor 2 exactly compensates for the half of units that are off.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
n, L = 256, 30
def grad_norms(act, dact, std):
    x = rng.normal(size=n); Ws, As = [], []
    for _ in range(L):
        W = rng.normal(0, std, (n, n)); a = W @ x; x = act(a); Ws.append(W); As.append(a)
    g = np.ones(n) / np.sqrt(n); norms = []
    for W, a in zip(reversed(Ws), reversed(As)):
        g = W.T @ (g * dact(a)); norms.append(np.linalg.norm(g))
    return norms[0], norms[-1]
sig = lambda a: 1 / (1 + np.exp(-a))
for name, act, dact, std in [
    ("sigmoid, std 1/sqrt(n)", sig, lambda a: sig(a) * (1 - sig(a)), 1 / np.sqrt(n)),
    ("tanh, std 1/sqrt(n)   ", np.tanh, lambda a: 1 - np.tanh(a)**2, 1 / np.sqrt(n)),
    ("relu, std sqrt(2/n)   ", lambda a: np.maximum(0, a), lambda a: (a > 0) * 1.0, np.sqrt(2 / n))]:
    top, bottom = grad_norms(act, dact, std)
    print(f"{name}: gradient norm at last layer {top:.2e}, at first layer {bottom:.2e}")
sigmoid, std 1/sqrt(n): gradient norm at last layer 2.52e-01, at first layer 1.80e-19
tanh, std 1/sqrt(n)   : gradient norm at last layer 9.36e-01, at first layer 9.76e-02
relu, std sqrt(2/n)   : gradient norm at last layer 1.17e+00, at first layer 5.44e+00

Recurrent networks: the extreme case

An RNN applies the same matrix WW at every time step, so the product is WTW^T raised to the sequence length. Its behavior is governed by the largest eigenvalue magnitude (spectral radius) ρ(W)\rho(W): below 1 the gradient vanishes exponentially in the time gap, above 1 it explodes. This is why plain RNNs struggle to learn dependencies longer than about 10 to 20 steps (Backpropagation Through Time).

The toolbox of fixes

Problem Fix Lesson
gain ≠1\ne 1 at initialization variance-preserving initialization (Xavier, He) Initialization
saturation ReLU-family activations Activations
drift of activation scale during training batch and layer normalization Batch Normalization
long products residual connections (h+F(h)\mathbf{h} + F(\mathbf{h}), Jacobian I+JFI + J_F) Residual Connections
long products in time gated recurrent units (LSTM, GRU), attention LSTM and GRU
occasional explosions gradient clipping Schedules and Clipping

In software

  • Monitor per-layer gradient norms (p.grad.norm() per parameter) during training; a layer whose gradients are orders of magnitude smaller than others is not learning.
  • A loss that suddenly becomes nan usually means an explosion; clipping and a lower learning rate are the first remedies.
  • torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) is standard in transformer training.

Go further: Vanishing and Exploding Gradients in the Deep Learning course measures the effect in NumPy and PyTorch and ranks the fixes by how often you need them.

Exercises

Exercise 1: Exponential scaling

A 100-layer network has a per-layer gradient gain of 0.950.95. By what factor is the gradient at layer 1 smaller than at layer 100?

Answer

About 0.0060.006 (a factor of about 170 smaller).

Solution

0.9599≈e−5.08≈0.00620.95^{99} \approx e^{-5.08} \approx 0.0062.

Exercise 2: Sigmoid depth bound

Ignoring the weights, what is the largest possible factor a gradient can be multiplied by passing through 20 sigmoid activations?

Answer

0.2520≈9.1×10−130.25^{20} \approx 9.1 \times 10^{-13}.

Solution

Each sigmoid derivative is at most 0.250.25, so the product is at most 0.25200.25^{20}.

Exercise 3: Spectral radius (code)

For W=(0.5400.5)W = \begin{pmatrix} 0.5 & 4 \\ 0 & 0.5 \end{pmatrix}, compute ∥(WT)tg∥\lVert (W^T)^t\mathbf{g} \rVert for t=1,2,5,20,50t = 1, 2, 5, 20, 50 with g=(1,0)\mathbf{g} = (1, 0). The spectral radius is 0.50.5; what happens at first?

Answer

The norm first grows to about 4, then decays to zero.

Solution

Non-normal matrices can amplify transiently even when ρ<1\rho < 1: (WT)tg=(0.5t,4t⋅0.5t−1)(W^T)^t\mathbf{g} = (0.5^t, 4t \cdot 0.5^{t-1}), and eventually ρt\rho^t wins.

python · try it yourself
import numpy as np
W = np.array([[0.5, 4.0], [0.0, 0.5]])
for t in (1, 2, 5, 20, 50):
    print(t, f"{np.linalg.norm(np.linalg.matrix_power(W.T, t) @ np.array([1.0, 0.0])):.3e}")
1 4.031e+00
2 4.008e+00
5 1.250e+00
20 1.526e-04
50 3.553e-13

Test yourself

Why do gradients vanish or explode in deep networks?

  1. Because of the loss function
  2. Backprop multiplies one Jacobian per layer, and long products shrink or grow exponentially
  3. Because of the batch size
  4. Because weights are random

In a plain RNN, gradients over long time gaps are governed mainly by…

  1. the vocabulary size
  2. the spectral radius of the recurrent weight matrix
  3. the output layer
  4. the learning rate schedule

Which of these does NOT address vanishing gradients?

  1. Residual connections
  2. ReLU activations
  3. He initialization
  4. Increasing the number of sigmoid layers