3.1.11Neural Network Fundamentals

Vanishing and exploding gradients

1,936 words9 min readdifficulty · medium6 backlinks

What is actually happening

WHAT is multiplied? In a plain feed-forward net, each layer computes a(l)=σ ⁣(z(l)),z(l)=W(l)a(l1)+b(l).a^{(l)} = \sigma\!\big(z^{(l)}\big), \qquad z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}. Backprop pushes the error δ(l)=L/z(l)\delta^{(l)} = \partial L/\partial z^{(l)} backward using the chain rule.


Derivation from first principles

Let the "error at layer ll" be δ(l)=Lz(l)\delta^{(l)} = \dfrac{\partial L}{\partial z^{(l)}}.

Step 1 — link consecutive layers. Since z(l+1)=W(l+1)σ(z(l))+b(l+1)z^{(l+1)} = W^{(l+1)} \sigma(z^{(l)}) + b^{(l+1)}, the chain rule gives δ(l)=(W(l+1)) ⁣δ(l+1)    σ ⁣(z(l)).\delta^{(l)} = \Big(W^{(l+1)}\Big)^{\!\top}\,\delta^{(l+1)} \;\odot\; \sigma'\!\big(z^{(l)}\big). Why this step? Error at layer ll only reaches the loss through layer l+1l+1, so we take l+1l+1's error, pull it back through the weights (W(l+1))(W^{(l+1)})^\top, and scale by how much this neuron's output changes with its input, σ(z(l))\sigma'(z^{(l)}).

Step 2 — unroll across LL layers. Applying Step 1 repeatedly from the last layer down to layer 1: δ(1)=(l=2L(W(l)) ⁣diag ⁣(σ(z(l1))))δ(L).\delta^{(1)} = \left(\prod_{l=2}^{L} \Big(W^{(l)}\Big)^{\!\top} \operatorname{diag}\!\big(\sigma'(z^{(l-1)})\big)\right)\delta^{(L)}. Why this step? Every layer inserts one more multiplicative factor. Going from layer LL down to layer 11 crosses L1L-1 links, so there are L1L-1 factors in the product.

Step 3 — bound the magnitude (the key insight). Take norms. If every factor satisfies (W(l))diag(σ)γ\big\|(W^{(l)})^\top \operatorname{diag}(\sigma')\big\| \le \gamma, then δ(1)    γL1δ(L).\big\|\delta^{(1)}\big\| \;\le\; \gamma^{\,L-1}\,\big\|\delta^{(L)}\big\|. Why this step? Norm of a product \le product of norms, and there are L1L-1 factors. Now the behaviour is obvious:

  • γ<1γL10\gamma < 1 \Rightarrow \gamma^{L-1}\to 0vanish.
  • γ>1γL1\gamma > 1 \Rightarrow \gamma^{L-1}\to \inftyexplode.
  • γ1\gamma \approx 1 \Rightarrow signal preserved. This is the whole design goal.

Why activation choice matters

σsigmoid(z)=σ(z)(1σ(z))14,tanh(z)=1tanh2(z)1.\sigma_{\text{sigmoid}}'(z) = \sigma(z)\big(1-\sigma(z)\big) \le \tfrac14,\qquad \tanh'(z) = 1 - \tanh^2(z) \le 1.

Why sigmoid vanishes: its derivative never exceeds 0.250.25. So even with perfectly scaled weights, γ0.25W\gamma \le 0.25 \cdot \|W\|; through many layers the 0.250.25 factors compound to near zero. ReLU has derivative 11 for positive inputs, so it does not shrink the signal (its factor is exactly 11), which is why it dominates deep nets.

Figure — Vanishing and exploding gradients

Fixes (the 80/20 that solves most cases)

  1. Weight initialization — scale WW so that variance is preserved.
    • Xavier/Glorot (for tanh/sigmoid): Var(W)=2nin+nout\operatorname{Var}(W)=\dfrac{2}{n_{in}+n_{out}}.
    • He (for ReLU): Var(W)=2nin\operatorname{Var}(W)=\dfrac{2}{n_{in}} (extra ×2\times 2 because ReLU zeroes half the inputs). Why: keeps Wmaxσ1\|W\|\cdot\max\sigma' \approx 1 at the start.
  2. Non-saturating activations — ReLU / LeakyReLU (slope 11).
  3. Batch/Layer Normalization — re-centers/scales z(l)z^{(l)} each layer so σ\sigma' stays in a healthy range.
  4. Residual (skip) connectionsa(l)=a(l1)+f(a(l1))a^{(l)} = a^{(l-1)} + f(a^{(l-1)}) gives the Jacobian an I+()I + (\dots) term, so the gradient always has a "11" path (factor 1\approx 1).
  5. Gradient clipping (for exploding) — rescale ggthresholdgg \leftarrow g\cdot \dfrac{\text{threshold}}{\|g\|} if g>\|g\|> threshold.
  6. LSTM/GRU gates (for RNNs) — additive cell state gives a near-11 recurrence.

Worked examples


Common mistakes


Active recall

What operation in backprop causes gradients to vanish or explode?
Repeated multiplication of Jacobians (weights × activation derivatives) across layers — a product of many factors.
How many multiplicative factors are in the gradient for an LL-layer net?
L1L-1, one per layer-to-layer link, so the bound scales like γL1\gamma^{L-1}.
What single quantity determines stability?
The per-layer gain γWmaxσ\gamma \approx \|W\|\cdot\max\sigma'; need γ1\gamma\approx 1.
Why does sigmoid promote vanishing gradients?
Its derivative σ(1σ)0.25\sigma(1-\sigma)\le 0.25, so factors always shrink the signal.
What is the max value of the sigmoid derivative and where?
0.250.25, at z=0z=0 (where σ=0.5\sigma=0.5).
He vs Xavier init — when and why the factor of 2?
He for ReLU (Var=2/nin\operatorname{Var}=2/n_{in}); the ×2\times2 compensates for ReLU zeroing ~half the activations. Xavier for tanh/sigmoid (2/(nin+nout)2/(n_{in}+n_{out})).
Which fix targets exploding gradients specifically?
Gradient clipping (rescale gradient if its norm exceeds a threshold).
Why do residual connections help?
The layer Jacobian becomes I+()I + (\dots), giving a guaranteed gain-1\approx1 identity path for the gradient.
For γ=0.25\gamma=0.25, L=10L=10, estimate the shrink factor.
0.2593.8×1060.25^{9}\approx 3.8\times10^{-6} (using L1=9L-1=9 factors); order 10610^{-6} either way.
Can loss be high while gradients vanish?
Yes — early layers frozen while later layers still learn.
Recall Feynman: explain to a 12-year-old

Imagine whispering a message down a line of 20 friends. If each friend whispers a bit softer, by the end there's no sound — that's a vanishing gradient (the first friends never hear the correction). If each whispers a bit louder, by the end everyone is screaming — that's exploding. We fix it by teaching everyone to repeat the message at the same volume (gain 1\approx 1) using good starting rules (He/Xavier) and shortcuts (skip connections) so the message survives the whole line.

Connections

  • Backpropagation — the chain-rule product that creates the problem.
  • Activation Functions — sigmoid/tanh/ReLU and their derivatives.
  • Weight Initialization — Xavier & He as γ\gamma-control.
  • Batch Normalization — keeps pre-activations well-scaled.
  • Residual Networks (ResNet) — identity paths for gradient flow.
  • LSTM and GRU — additive cell state fixing the recurrent version.
  • Gradient Descent — how these gradients get used to update weights.

Concept Map

enables

uses

multiplies

each factor

bounded by

raised to power

gamma < 1

gamma > 1

gamma approx 1

effect

effect

goal

Deep network depth

Backprop passes error backward

Chain rule per layer

Product of many Jacobians

W transpose times diag sigma prime

Norm factor gamma

gamma^L-1 scaling

Vanishing gradient

Exploding gradient

Signal preserved

Early layers stop learning

Weights blow up, loss NaN

Stable deep training

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, deep network ko train karna matlab error signal ko peeche ki taraf (backpropagation) har layer se guzarna. Har layer par yeh signal ek weight aur activation ke derivative se multiply hota hai. Ab agar aap bahut saare numbers ko baar-baar multiply karo — aur woh saare 11 se chhote hain — toh answer 00 ki taraf gir jaata hai. Yeh hi vanishing gradient hai: shuruaat wali layers ko koi correction milta hi nahi, woh seekhna band kar deti hain. Agar numbers 11 se bade hain, toh product phat jaata hai (infinity), isko exploding gradient bolte hain — loss NaN ho jaata hai.

Poori kahani ek number par tiki hai: per-layer gain γW×maxσ\gamma \approx \|W\| \times \max\sigma'. Layer LL se layer 11 tak jaate hue L1L-1 links cross hote hain, toh bound γL1\gamma^{L-1} ki tarah scale karta hai. Agar γ1\gamma \approx 1 ho toh signal preserve rehta hai; agar <1<1 toh vanish, >1>1 toh explode. Isiliye sigmoid kharab hai — uska derivative maximum sirf 0.250.25 hota hai, toh gain hamesha girta rehta hai. ReLU ka slope 11 hota hai, isliye woh signal ko shrink nahi karta — yahi reason hai ki modern deep nets ReLU use karte hain.

Fixes bhi sab ek hi cheez karte hain: γ\gamma ko 11 ke paas laana. He/Xavier initialization weights ko sahi scale par set karta hai. Batch Normalization pre-activations ko healthy range mein rakhta hai. Residual (skip) connections gradient ko ek identity path deti hain (Jacobian =I+= I + \dots), jisse gain hamesha 1\approx 1. Aur exploding ke liye gradient clipping — agar gradient bada ho jaaye toh usko cut kar do. Yeh 80/20 concept hai: yeh samajh lo, toh deep learning training ka aadha struggle solve ho jaata hai.

Go deeper — visual, from zero

Test yourself — Neural Network Fundamentals

Connections