TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Vanishing and Exploding Gradients

Vanishing and Exploding Gradients

Backpropagation computes the gradient of the first layer by multiplying together one factor per layer above it. Twenty factors of 0.25 give 10−1210^{-12}; twenty factors of 2 give a million. When the gradients of the early layers are many orders of magnitude smaller than those of the late layers, the early layers do not train (vanishing gradients); when they are many orders larger, one step throws the weights far away and the loss becomes nan (exploding gradients). The derivation, with the bound for sigmoid and the spectral-radius view, is in Vanishing and Exploding Gradients. Here you measure the effect in real networks, first in NumPy with a hand-written backward pass, then in PyTorch with p.grad.norm() and hooks, and you check which fixes actually work.

The product of Jacobians

For a stack hl=f(zl)h_l = f(z_l), zl=hl−1Wlz_l = h_{l-1} W_l, the gradient with respect to an early hidden state is

∂L∂hl−1=∂L∂hldiag⁡(f′(zl))Wl⊤⟹∂L∂h0=∂L∂hL∏l=L1diag⁡(f′(zl))Wl⊤\frac{\partial L}{\partial h_{l-1}} = \frac{\partial L}{\partial h_{l}} \operatorname{diag}\big(f'(z_l)\big) W_l^{\top} \quad\Longrightarrow\quad \frac{\partial L}{\partial h_{0}} = \frac{\partial L}{\partial h_{L}} \prod_{l=L}^{1} \operatorname{diag}\big(f'(z_l)\big) W_l^{\top}

and the weight gradient of layer ll is ∂L/∂Wl=hl−1⊤(∂L∂hl⊙f′(zl))\partial L / \partial W_l = h_{l-1}^{\top} \big(\frac{\partial L}{\partial h_l} \odot f'(z_l)\big). Each factor scales the gradient by roughly n σw⋅(typical f′)\sqrt{n} \, \sigma_w \cdot \text{(typical } f'\text{)}. Two things can make that factor different from 1:

  • The activation. The sigmoid's derivative is at most 1/41/4 (at z=0z = 0), and its output has mean about 1/21/2, not 0. tanh has slope 1 at 0 and ReLU has slope 1 on half of the units, which the He factor 2 compensates.
  • The weight scale. σw\sigma_w too small shrinks every factor, too large grows every factor, the subject of Weight Initialisation in Practice.

Measuring it in NumPy

A probe: one batch of 256 Digits images through 20 hidden layers of width 64, a softmax output and cross-entropy, then the backward pass layer by layer, recording ∥∂L/∂Wl∥\lVert \partial L / \partial W_l \rVert (the Frobenius norm). No training, just the gradients at initialisation, which is where trouble shows first.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits

X, y = load_digits(return_X_y=True)
X = X[:256] / 16.0                                  # one batch of 256 images is enough for a probe
Y = np.eye(10)[y[:256]]
depth, width = 20, 64

sigmoid = lambda z: 1 / (1 + np.exp(-z))
acts = {   # name: (f, f' written in terms of z and h = f(z))
    "sigmoid": (sigmoid, lambda z, h: h * (1 - h)),
    "tanh":    (np.tanh, lambda z, h: 1 - h ** 2),
    "relu":    (lambda z: np.maximum(z, 0), lambda z, h: (z > 0).astype(float)),
}

def grad_norms(act, std_of):
    rng = np.random.default_rng(0)
    f, df = acts[act]
    sizes = [64] + [width] * depth
    Ws = [rng.normal(0, std_of(n_in), (n_in, n_out)) for n_in, n_out in zip(sizes[:-1], sizes[1:])]
    Wout = rng.normal(0, np.sqrt(1 / width), (width, 10))
    hs, zs = [X], []
    for W in Ws:                                    # forward, keep what backward needs
        zs.append(hs[-1] @ W)
        hs.append(f(zs[-1]))
    logits = hs[-1] @ Wout
    p = np.exp(logits - logits.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    g = (p - Y) / len(Y) @ Wout.T                   # dL/dh of the last hidden layer (softmax + CE)
    norms = [0.0] * depth
    for l in range(depth - 1, -1, -1):              # backward
        gz = g * df(zs[l], hs[l + 1])
        norms[l] = float(np.linalg.norm(hs[l].T @ gz))   # ||dL/dW_l||
        g = gz @ Ws[l].T
    return norms, float(np.abs(logits).max())

configs = [
    ("sigmoid", "Xavier", lambda n: np.sqrt(1 / n)),
    ("tanh",    "Xavier", lambda n: np.sqrt(1 / n)),
    ("relu",    "He",     lambda n: np.sqrt(2 / n)),
    ("relu",    "2 x He", lambda n: 2 * np.sqrt(2 / n)),
]
print("||dL/dW|| for layer      1          5         10         15         20   ratio 1/20  max|logit|")
for act, init, std_of in configs:
    n, big = grad_norms(act, std_of)
    print(f"{act:7s} {init:7s}" + "".join(f"{n[i]:11.3g}" for i in (0, 4, 9, 14, 19)) + f"  {n[0] / n[19]:9.3g}  {big:10.3g}")
||dL/dW|| for layer      1          5         10         15         20   ratio 1/20  max|logit|
sigmoid Xavier       2e-13   7.73e-11   8.49e-08   0.000117      0.189   1.06e-12       0.803
tanh    Xavier       0.195      0.168      0.117      0.144      0.128       1.53       0.429
relu    He           0.227      0.285      0.178      0.113      0.126        1.8         1.1
relu    2 x He    3.14e+05   4.33e+05   3.12e+05   2.17e+05   2.95e+05       1.06    1.15e+06
  • Sigmoid with Xavier init: the last hidden layer gets a gradient of 0.189, the first 2×10−132 \times 10^{-13}. The ratio, 1.06×10−121.06 \times 10^{-12}, means that a learning rate large enough to move layer 20 leaves layer 1 where it started. The decay is steady, roughly a factor of 4 per layer, the sigmoid's 1/41/4 in action.
  • tanh with Xavier and ReLU with He keep every layer's gradient between 0.11 and 0.29: the factors are close to 1, and all layers learn at similar speeds.
  • ReLU with twice the He standard deviation explodes, but look at how: every layer's weight gradient is about 3×1053 \times 10^{5}, so the ratio is 1.06 and nothing looks unbalanced. The forward signal grows by 2 per layer and the backward signal by 2 per layer in the opposite direction, and in hl−1⊤δlh_{l-1}^{\top} \delta_l the two cancel. The tell-tale signs are elsewhere: the largest logit is 1.15×1061.15 \times 10^{6} (the softmax is saturated at 0 and 1), and the gradients are about 10410^4 times larger than the weights they would update (a 64×6464 \times 64 matrix with standard deviation 0.354 has a norm of about 23).

So the per-layer ratio detects vanishing; for exploding, also compare the gradient with the size of the weights and look at the loss and the logits.

Measuring it in PyTorch

In PyTorch you do not write the backward pass, but every parameter's gradient sits in p.grad after loss.backward(). This recorded experiment (CPU, PyTorch 2.14.1) builds five 20-layer networks for Digits, records the gradient norm of hidden layer 1 and hidden layer 20 on one batch at initialisation, then trains each with the same recipe (SGD, learning rate 0.01, momentum 0.9, batch 64, 20 epochs) on the course's training split and reports validation accuracy:

  • sigmoid and relu: nn.Linear with PyTorch's default init (uniform, variance 1/(3nin)1/(3 n_{\text{in}})),
  • relu He: He-normal weights, zero biases,
  • relu+BN: He init plus nn.BatchNorm1d after every linear layer (Batch Normalisation),
  • residual: 20 blocks h←h+Linear(ReLU(h))h \leftarrow h + \text{Linear}(\text{ReLU}(h)) with the default init (Residual Connections).
python · try it yourself
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))
DEPTH, W = 20, 64

class Residual(nn.Module):                       # h + Linear(ReLU(h))
    def __init__(self):
        super().__init__()
        self.lin = nn.Linear(W, W)
    def forward(self, h):
        return h + self.lin(torch.relu(h))

def he(m):
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight, nonlinearity="relu"); nn.init.zeros_(m.bias)

def build(kind):
    if kind == "residual":
        blocks = [Residual() for _ in range(DEPTH)]
    else:
        act = nn.Sigmoid if kind == "sigmoid" else nn.ReLU
        blocks = []
        for _ in range(DEPTH):
            blocks += [nn.Linear(W, W)] + ([nn.BatchNorm1d(W)] if kind == "relu+BN" else []) + [act()]
    model = nn.Sequential(nn.Linear(64, W), *blocks, nn.Linear(W, 10))
    if kind in ("relu He", "relu+BN"):
        model.apply(he)
    return model

loss_fn = nn.CrossEntropyLoss()
for kind in ("sigmoid", "relu", "relu He", "relu+BN", "residual"):
    torch.manual_seed(0)
    model = build(kind)
    linears = [m for m in model.modules() if isinstance(m, nn.Linear)]
    loss_fn(model(X_tr[:256]), y_tr[:256]).backward()          # one probe batch at init
    g_first, g_last = linears[1].weight.grad.norm().item(), linears[-2].weight.grad.norm().item()
    model.zero_grad()
    opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
    gen = torch.Generator().manual_seed(0)
    for epoch in range(20):
        model.train()
        for idx in torch.randperm(len(y_tr), generator=gen).split(64):
            loss = loss_fn(model(X_tr[idx]), y_tr[idx])
            opt.zero_grad(); loss.backward(); opt.step()
    model.eval()
    with torch.no_grad():
        acc = (model(X_va).argmax(1) == y_va).float().mean().item()
    print(f"{kind:9s} grad norm hidden layer 1: {g_first:9.2e}  layer {DEPTH}: {g_last:9.2e}"
          f"  ratio {g_first / g_last:8.2e}   val acc after 20 epochs {acc:.3f}")
sigmoid   grad norm hidden layer 1:  3.36e-18  layer 20:  6.28e-02  ratio 5.36e-17   val acc after 20 epochs 0.103
relu      grad norm hidden layer 1:  4.75e-09  layer 20:  8.23e-03  ratio 5.77e-07   val acc after 20 epochs 0.103
relu He   grad norm hidden layer 1:  3.09e-01  layer 20:  3.27e-01  ratio 9.43e-01   val acc after 20 epochs 0.472
relu+BN   grad norm hidden layer 1:  1.57e+01  layer 20:  4.59e-01  ratio 3.42e+01   val acc after 20 epochs 0.925
residual  grad norm hidden layer 1:  5.19e-01  layer 20:  3.35e-01  ratio 1.55e+00   val acc after 20 epochs 0.967

The gradient ratios predict the training results:

Network ratio layer 1 / layer 20 at init val acc after 20 epochs
sigmoid, default init 5.36×10−175.36 \times 10^{-17} 0.103 (chance)
ReLU, default init 5.77×10−75.77 \times 10^{-7} 0.103 (chance)
ReLU, He 0.943 0.472
ReLU, He + BatchNorm 34.2 0.925
residual, default init 1.55 0.967

Two networks never leave chance level: their first layers receive gradients of 3×10−183 \times 10^{-18} and 5×10−95 \times 10^{-9}. He initialisation fixes the balance (0.943) but a 20-layer plain stack is still slow to train with this learning rate: 0.472 after 20 epochs. Batch normalisation and the residual connection both reach above 0.92. The BN network's first layer has the larger gradient (15.7 against 0.459); that is harmless, because batch norm makes each layer invariant to the scale of the weights feeding it, so only the gradient relative to the weight norm matters.

Note: Adam does not rescue the sigmoid network. Its update is m/(v+ϵ)m / (\sqrt{v} + \epsilon) with ϵ=10−8\epsilon = 10^{-8}, and when the gradient is 10−1810^{-18} the denominator is dominated by ϵ\epsilon, so the update is about 10−1010^{-10} times the learning rate. Per-parameter scaling helps with gradients that are small, not with gradients that have vanished.

Hooks: gradients of activations, not just weights

p.grad holds gradients of parameters only. To see ∂L/∂hl\partial L / \partial h_l, the gradient flowing between layers, attach a hook. A forward hook on each nn.Linear registers a tensor hook on that layer's output; autograd calls the tensor hook with the gradient during backward. The network is the exploding one (10 ReLU layers, twice the He standard deviation), and the gradient is then clipped with clip_grad_norm_, which returns the global norm before clipping:

python · try it yourself
import torch
from torch import nn
from sklearn.datasets import load_digits

X, y = load_digits(return_X_y=True)
xb = torch.tensor(X[:256] / 16.0, dtype=torch.float32)
yb = torch.tensor(y[:256])

torch.manual_seed(0)
model = nn.Sequential(*[m for _ in range(10) for m in (nn.Linear(64, 64), nn.ReLU())], nn.Linear(64, 10))
linears = [m for m in model if isinstance(m, nn.Linear)]
for m in linears:
    nn.init.normal_(m.weight, 0, 2 * (2 / m.in_features) ** 0.5)   # 2 x He: too large
    nn.init.zeros_(m.bias)

seen = {}
def watch(i):
    def forward_hook(module, inputs, out):           # runs in the forward pass ...
        out.register_hook(lambda g: seen.__setitem__(i, g.norm().item()))  # ... and this in backward
    return forward_hook
handles = [m.register_forward_hook(watch(i)) for i, m in enumerate(linears)]

loss = nn.functional.cross_entropy(model(xb), yb)
loss.backward()
for h in handles:
    h.remove()                                       # hooks stay until removed
print(f"loss {loss.item():.4g}")
print("||dL/d output|| of Linear 1, 3, 5, 7, 9, 11:", [f"{seen[i]:.2g}" for i in range(0, 11, 2)])
print("||dL/dW||      of Linear 1, 3, 5, 7, 9, 11:", [f"{linears[i].weight.grad.norm().item():.2g}" for i in range(0, 11, 2)])
total = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)  # returns the norm BEFORE clipping
after = torch.linalg.vector_norm(torch.stack([p.grad.norm() for p in model.parameters()]))
print(f"global grad norm before clipping {total.item():.3g}, after {after.item():.3f}")
loss 1360
||dL/d output|| of Linear 1, 3, 5, 7, 9, 11: ['76', '18', '5.1', '1.2', '0.3', '0.083']
||dL/dW||      of Linear 1, 3, 5, 7, 9, 11: ['1.8e+03', '2.3e+03', '2.8e+03', '2.7e+03', '1.6e+03', '1.8e+03']
global grad norm before clipping 7.91e+03, after 1.000

The loss is 1360, far above ln⁡10\ln 10: the logits are enormous and confidently wrong. The gradient arriving at the outputs of the linear layers grows going backwards, from 0.083 at the last one to 76 at the first, a factor of about 4 every two layers, as the factor 2 per layer predicts. The weight gradients are uniform at a few thousand, the same cancellation as in NumPy. The global gradient norm is 7910, and clipping rescales all gradients together so the norm is 1.000. Clipping stops one bad step from destroying the model, the topic of Gradient Clipping, but it does not fix this network: the logits are still saturated, and the right fix is the initialisation.

Remove hooks when you are done (handle.remove()); a forgotten hook keeps running, and one that stores tensors keeps them in memory.

The fixes, ranked by how often you need them

  1. Activation. Use ReLU, GELU or SiLU in hidden layers. Keep sigmoid and tanh for gates and outputs (Activation Functions).
  2. Initialisation matched to the activation: He for ReLU-like units, Xavier for tanh.
  3. Normalisation layers (batch norm, layer norm and RMSNorm) rescale activations at every layer, so the scale cannot drift over depth.
  4. Residual connections add an identity path whose Jacobian is II, so the product of Jacobians becomes a product of I+JlI + J_l terms that does not shrink to zero.
  5. Gradient clipping as a safety net against rare spikes, especially in RNNs and transformers (Gradient Clipping).
  6. A lower learning rate or warm-up if the gradients are fine at the start but explode later in training.

Modern architectures combine 2, 3 and 4 by default, which is why a 100-layer transformer trains while the 20-layer sigmoid stack above does not.

Recurrent networks: depth in time

A recurrent network applies the same weight matrix at every time step, so the gradient through TT steps contains WTW^{T}: the same matrix multiplied TT times. If its largest singular value is below 1 (and the activation's slope is at most 1, as for tanh) the gradient vanishes exponentially in TT; a largest singular value above 1 is necessary for it to explode, though not sufficient (Pascanu, Mikolov and Bengio, 2013). Unlike a feed-forward net, the factors cannot differ from layer to layer, which makes RNNs the worst case; Recurrent Neural Networks measures it, and LSTM and GRU cells (LSTM and GRU in Practice) were designed to give the gradient an additive path, the same idea as a residual connection.

Pitfalls

  • Looking only at the loss. A loss that does not move can mean a learning rate that is too low or gradients that vanished. Print the per-layer gradient norms once; the difference is obvious.
  • One global norm. clip_grad_norm_'s return value is useful to log, but a healthy global norm can hide a first layer with 10−1210^{-12}. Log per-layer norms (or their ratio) too.
  • Measuring with model.eval(). Dropout and batch norm behave differently in eval mode; measure gradients in train mode, on a real batch.
  • Reading p.grad after zero_grad(). Read gradients between backward() and optimizer.step()/zero_grad(). Since PyTorch 2.0 zero_grad() sets them to None.
  • Hooks that accumulate. Registering hooks inside the training loop adds a new one every step. Register once, keep the handles, remove them.

Practice

  1. With the sigmoid's maximal slope of 1/41/4 and weights that keep nσw=1\sqrt{n} \sigma_w = 1, what is the best case gradient ratio between layer 1 and layer 20?
Answer

About (1/4)19≈3.6×10−12(1/4)^{19} \approx 3.6 \times 10^{-12} for 19 factors between the two layers, the same order as the measured 1.06×10−121.06 \times 10^{-12}. In practice f′f' is below 1/41/4 for most units, so the real ratio is usually worse.

  1. In the "2 x He" network all weight gradients have about the same norm. Why is the network still broken?
Answer

The forward activations grow by about 2 per layer and the backward gradients by about 2 per layer the other way, so the products hl−1⊤δlh_{l-1}^{\top} \delta_l are equal; but they are about 10410^4 times larger than the weights, the logits are around 10610^6 and the softmax is saturated. One SGD step would move the weights by far more than their size.

  1. Write a function that returns {name: grad_norm} for every parameter of a model, and a condition that flags vanishing gradients.
Answer
python
def grad_norms(model):
    return {n: p.grad.norm().item() for n, p in model.named_parameters() if p.grad is not None}

norms = grad_norms(model)
weights = [v for n, v in norms.items() if n.endswith("weight")]
if weights[0] < 1e-4 * weights[-1]:
    print("first layer gradient is 10^4 times smaller than the last one: vanishing")

Call it after loss.backward() and before optimizer.step().

Test yourself

In the 20-layer sigmoid network, the first layer's gradient was about 10−1210^{-12} times the last layer's. What happens during training?

  1. All layers learn at the same rate
  2. The last layers learn while the first layers barely change
  3. The network diverges
  4. Only the first layer learns

Which measurement best reveals exploding gradients in the '2 x He' ReLU network?

  1. The ratio of first to last layer gradient norms
  2. Gradient norms compared with weight norms, the logits and the loss
  3. The number of parameters
  4. The validation accuracy at epoch 0

What does torch.nn.utils.clip_grad_norm_(params, max_norm=1.0) return?

  1. The norm after clipping, always 1
  2. The global gradient norm before clipping
  3. The clipped gradients
  4. Nothing

Why do residual connections help the gradient reach early layers?

  1. They remove the activation functions
  2. The block's Jacobian is I+JFI + J_F, so the product of Jacobians keeps an identity path
  3. They make the network shallower
  4. They clip the gradients

Why are plain RNNs especially prone to vanishing and exploding gradients?

  1. They have no activation function
  2. The same weight matrix is multiplied at every time step, so the gradient contains WTW^T for TT steps
  3. They use too many parameters
  4. They cannot use backpropagation