Theory ofIntelligence
Index
Deep Learning FoundationsBook Index: Letter V

Vanishing & Exploding Gradients: From Audio Amplifiers to Xavier & He Initialization

Understand why deep neural networks suffer from vanishing and exploding activations and gradients: the audio amplifier analogy, repeated matrix multiplication, chain-rule calculus derivations, and the mathematical variance proofs behind Xavier and He weight initialization.

functionsMathematical Representation
∂L∂W[1]∝W[2]W[3]⋯W[L]\frac{\partial L}{\partial W^{[1]}} \propto W^{[2]} W^{[3]} \cdots W^{[L]}

Think of a deep neural network like a long chain of audio amplifiers connected one after another. If you speak into a microphone at the start, each amplifier multiplies the volume of your voice before passing it to the next one:

  • If each amplifier boosts the volume even slightly (1.5×1.5\times), within a few dozen stages the sound escalates into a deafening, distorted roar that blows out the speakers.
  • If each amplifier damps the volume slightly (0.5×0.5\times), within a few stages your voice fades into total silence.

In deep learning, this exact phenomenon governs both the forward pass (activations) and the backward pass (gradients). This guide breaks down the mathematics behind repeated multiplication, explores why early layers stop learning, and derives the "Goldilocks" variance rules behind Xavier and He weight initialization.


1. The Whiteboard Setup: Isolating the Core Math

A standard neural network layer performs three operations: it multiplies inputs by weights (WW), adds a bias (bb), and applies an activation function (gg):

a[l]=g(W[l]a[l−1]+b[l])a^{[l]} = g\left(W^{[l]} a^{[l-1]} + b^{[l]}\right)

SymbolMathematical Meaning
a[l−1]a^{[l-1]}Output vector from the previous layer (activations)
W[l]W^{[l]}Weight matrix of the current layer ll
b[l]b^{[l]}Bias vector of current layer ll
g(⋅)g(\cdot)Nonlinear activation function (e.g., Sigmoid, ReLU)
a[l]a^{[l]}Output vector of the current layer ll
TEXT
Forward Pass:
[ Input a^[0] ] ──► [ Layer 1: a^[1] ] ──► [ Layer 2: a^[2] ] ──► ⋯ ──► [ Output ŷ ]

To isolate the mathematical root of the instability without messy algebra, we make two simplifying assumptions:

  1. Set biases to zero: b[l]=0b^{[l]} = 0.
  2. Set activation to the identity function: g(z)=zg(z) = z (whatever enters comes straight out).

Now, each layer is pure linear multiplication: a[l]=W[l]a[l−1]a^{[l]} = W^{[l]} a^{[l-1]}

Expanding this across an LL-layer network:

  • Layer 1: a[1]=W[1]xa^{[1]} = W^{[1]} x
  • Layer 2: a[2]=W[2]W[1]xa^{[2]} = W^{[2]} W^{[1]} x
  • Layer 3: a[3]=W[3]W[2]W[1]xa^{[3]} = W^{[3]} W^{[2]} W^{[1]} x
  • Layer LL: y^=W[L]W[L−1]⋯W[2]W[1]x\boxed{\hat{y} = W^{[L]} W^{[L-1]} \cdots W^{[2]} W^{[1]} x}

Every single layer adds another matrix multiplication. When a network has 5050 or 100100 layers, we are chaining together dozens of matrix products.


2. The Core Problem: Multiplying Numbers Over and Over

Before analyzing matrices, consider a 1D scalar function applied repeatedly: f(x)=w⋅xf(x) = w \cdot x

Applying it LL times in a row yields: y=wLx\boxed{y = w^L x}

Depending on whether w>1w > 1 or w<1w < 1, two extreme behaviors emerge:

TEXT
Value
  ▲
  │                                     ● w = 1.5 (Explodes)
  │                                    /
  │                                   /
  │                                  /
1 ┼─────────────────────────────────●─── w = 1.0 (Stable)
  │                                  \
  │                                   \
0 ┼────────────────────────────────────● w = 0.5 (Vanishes to 0)
  └───────────────────────────────────────► Depth (Layers L)

Case A: Exploding Values (w=1.5>1w = 1.5 > 1)

Suppose w=1.5w = 1.5 and initial input x=1x = 1:

  • After Layer 1: 1×1.5=1.51 \times 1.5 = \mathbf{1.5}
  • After Layer 2: 1.5×1.5=2.251.5 \times 1.5 = \mathbf{2.25}
  • After Layer 10: 1.510≈57.671.5^{10} \approx \mathbf{57.67}
  • After Layer 39: 1.539≈7.37×1061.5^{39} \approx \mathbf{7.37 \times 10^6}
  • After Layer 100: 1.5100≈4.06×10171.5^{100} \approx \mathbf{4.06 \times 10^{17}}

Because 1.5>11.5 > 1, repeated multiplication causes exponential growth. In computer arithmetic, 32-bit floating-point numbers quickly overflow, producing NaN (Not a Number) or Infinity. This is Exploding Activation / Gradient.

Case B: Vanishing Values (w=0.5<1w = 0.5 < 1)

Now suppose w=0.5w = 0.5 and initial input x=1x = 1:

  • After Layer 1: 0.5\mathbf{0.5}
  • After Layer 2: 0.25\mathbf{0.25}
  • After Layer 10: 0.510≈0.000976(9.77×10−4)0.5^{10} \approx \mathbf{0.000976} \quad (9.77 \times 10^{-4})
  • After Layer 100: 0.5100≈7.89×10−310.5^{100} \approx \mathbf{7.89 \times 10^{-31}}

Because 0<0.5<10 < 0.5 < 1, repeated multiplication causes exponential decay: lim⁡L→∞(0.5)L=0\lim_{L \to \infty} (0.5)^L = 0

The signal rapidly underflows to absolute zero. The output carries zero information about the input.


3. What This Has to Do with Matrices

In real networks, each layer contains multiple neurons (e.g., x1x_1 and x2x_2). Our input is a vector: x=(x1x2)\mathbf{x} = \begin{pmatrix} x_1 \\ x_2 \end{pmatrix}

If we want both neurons to multiply their values by 1.51.5 without cross-mixing information, we write a diagonal weight matrix: W=(1.5001.5)W = \begin{pmatrix} 1.5 & 0 \\ 0 & 1.5 \end{pmatrix}

Multiplying by an input vector x=(24)\mathbf{x} = \begin{pmatrix} 2 \\ 4 \end{pmatrix}: Wx=(1.5001.5)(24)=(1.5(2)+0(4)0(2)+1.5(4))=(36)W \mathbf{x} = \begin{pmatrix} 1.5 & 0 \\ 0 & 1.5 \end{pmatrix} \begin{pmatrix} 2 \\ 4 \end{pmatrix} = \begin{pmatrix} 1.5(2) + 0(4) \\ 0(2) + 1.5(4) \end{pmatrix} = \begin{pmatrix} 3 \\ 6 \end{pmatrix}

Both neurons have been amplified by 1.51.5. Multiplying this matrix across LL layers: WL=(1.5L001.5L)\boxed{W^L = \begin{pmatrix} 1.5^L & 0 \\ 0 & 1.5^L \end{pmatrix}}

In general matrices with non-zero off-diagonals, the role of ww is played by the matrix's eigenvalues (or singular values). If the dominant eigenvalue ∣λmax⁡∣>1|\lambda_{\max}| > 1, the matrix product explodes; if ∣λmax⁡∣<1|\lambda_{\max}| < 1, it vanishes to zero.


4. The Backward Pass: Why Gradients Vanish

Instability in the forward pass is problematic, but the death blow to training occurs during the backward pass (backpropagation).

Consider a 3-layer linear toy network: a[1]=w1x,a[2]=w2a[1],y^=a[3]=w3a[2]a^{[1]} = w_1 x, \quad a^{[2]} = w_2 a^{[1]}, \quad \hat{y} = a^{[3]} = w_3 a^{[2]}

Substituting: y^=w3w2w1x\hat{y} = w_3 w_2 w_1 x

Let the squared-error loss be: L=12(y^−y)2L = \frac{1}{2}(\hat{y} - y)^2

To update the earliest weight w1w_1 using gradient descent, we need ∂L∂w1\frac{\partial L}{\partial w_1}. Applying the multivariable chain rule along the backward dependency path:

∂L∂w1=∂L∂y^⋅∂y^∂a[2]⋅∂a[2]∂a[1]⋅∂a[1]∂w1\frac{\partial L}{\partial w_1} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial a^{[2]}} \cdot \frac{\partial a^{[2]}}{\partial a^{[1]}} \cdot \frac{\partial a^{[1]}}{\partial w_1}

Calculating each local derivative:

  • ∂L∂y^=y^−y\frac{\partial L}{\partial \hat{y}} = \hat{y} - y
  • ∂y^∂a[2]=w3\frac{\partial \hat{y}}{\partial a^{[2]}} = w_3
  • ∂a[2]∂a[1]=w2\frac{\partial a^{[2]}}{\partial a^{[1]}} = w_2
  • ∂a[1]∂w1=x\frac{\partial a^{[1]}}{\partial w_1} = x

Multiplying these terms together: ∂L∂w1=(y^−y)⋅w3⋅w2⋅x\boxed{\frac{\partial L}{\partial w_1} = (\hat{y} - y) \cdot w_3 \cdot w_2 \cdot x}

The Chain Product for an LL-Layer Network

For a network with LL layers, the gradient of the loss with respect to the first-layer weights contains a product of all downstream weights:

∂L∂W[1]∝W[L]⋅W[L−1]⋯W[3]⋅W[2]\boxed{\frac{\partial L}{\partial W^{[1]}} \propto W^{[L]} \cdot W^{[L-1]} \cdots W^{[3]} \cdot W^{[2]}}

TEXT
Forward Pass:   x ──► [ W^[1] ] ──► [ W^[2] ] ──► ⋯ ──► [ W^[L] ] ──► ŷ ──► Loss L
                        │
Backward Pass:  ◄───────┴─────────────── (W^[L] · W^[L-1] ⋯ W^[2]) ◄────── dL/dŷ
                The learning signal must survive L-1 matrix multiplications!

The Devastating Consequence for Early Layers

  1. Vanishing Gradient: If downstream weights are <1< 1 (or activation functions like Sigmoid compress slopes to ≤0.25\le 0.25), multiplying dozens of fractions shrinks the gradient to 10−15≈010^{-15} \approx 0. The update step: W[1]←W[1]−η∂L∂W[1]W^{[1]} \leftarrow W^{[1]} - \eta \frac{\partial L}{\partial W^{[1]}} adds virtually nothing. The earliest layers freeze at their random initial values and never learn. Because early layers are responsible for basic feature extraction (edges, contours, phonemes), the rest of the network is starved of useful representations.
  2. Exploding Gradient: If downstream weights are >1> 1, the gradient blows up exponentially. The parameter update takes massive, erratic leaps across the loss surface, destabilizing the entire network and crashing with NaN.

5. Forward vs. Backward Comparison

FeatureForward Pass (a[l]a^{[l]})Backward Pass (∂L∂W[l]\frac{\partial L}{\partial W^{[l]}})
DirectionLeft to right (Input →\to Output)Right to left (Output →\to Earliest Layers)
Transmitted EntityData features & activationsError signals & gradients
Mathematical EngineRepeated matrix multiplicationRepeated Jacobian multiplication (Chain Rule)
Exploding EffectActivations overflow to Inf / NaNWeights jump wildly, optimizer destabilizes
Vanishing EffectOutput loses all input varianceEarly layers freeze and fail to learn

6. The "Goldilocks" Solution: Weight Initialization Variance

If weights >1> 1 explode and weights <1< 1 vanish, what is the ideal initial weight size? We need a Goldilocks condition: the variance of the signal should neither grow nor shrink as it passes through each layer.

Consider a single neuron computing a weighted sum of ninn_{\text{in}} inputs: z=∑j=1ninwjxjz = \sum_{j=1}^{n_{\text{in}}} w_j x_j

Assume:

  • Inputs xjx_j and weights wjw_j are independent with mean zero: E[xj]=0,E[wj]=0\mathbb{E}[x_j] = 0, \mathbb{E}[w_j] = 0.
  • All inputs have variance Var⁡(x)\operatorname{Var}(x).
  • All weights have variance σw2\sigma_w^2.

Using the variance formula for the product of two independent zero-mean random variables: Var⁡(wjxj)=Var⁡(wj)Var⁡(xj)=σw2Var⁡(x)\operatorname{Var}(w_j x_j) = \operatorname{Var}(w_j) \operatorname{Var}(x_j) = \sigma_w^2 \operatorname{Var}(x)

Summing across all ninn_{\text{in}} independent inputs: Var⁡(z)=∑j=1ninVar⁡(wjxj)=ninσw2Var⁡(x)\operatorname{Var}(z) = \sum_{j=1}^{n_{\text{in}}} \operatorname{Var}(w_j x_j) = n_{\text{in}} \sigma_w^2 \operatorname{Var}(x)

Var⁡(z)=ninσw2Var⁡(x)\boxed{\operatorname{Var}(z) = n_{\text{in}} \sigma_w^2 \operatorname{Var}(x)}

The Goldilocks Condition

To keep signal variance constant from input to output: Var⁡(z)≈Var⁡(x)  ⟺  ninσw2=1\operatorname{Var}(z) \approx \operatorname{Var}(x) \iff n_{\text{in}} \sigma_w^2 = 1

Solving for weight variance: σw2=1nin\boxed{\sigma_w^2 = \frac{1}{n_{\text{in}}}}

1. Xavier (Glorot) Initialization (for Tanh / Sigmoid)

Taking both the forward pass (ninn_{\text{in}}) and backward pass (noutn_{\text{out}}) into account: σw2=2nin+nout\boxed{\sigma_w^2 = \frac{2}{n_{\text{in}} + n_{\text{out}}}}

Weights are sampled from a normal distribution N(0,2nin+nout)\mathcal{N}\left(0, \sqrt{\frac{2}{n_{\text{in}} + n_{\text{out}}}}\right) or uniform distribution U(−6nin+nout,+6nin+nout)\mathcal{U}\left(-\sqrt{\frac{6}{n_{\text{in}} + n_{\text{out}}}}, +\sqrt{\frac{6}{n_{\text{in}} + n_{\text{out}}}}\right).

2. He (Kaiming) Initialization (for ReLU)

The ReLU activation function (max⁡(0,z)\max(0, z)) sets all negative values to zero, effectively cutting the signal's variance in half (12\frac{1}{2}). To compensate, He initialization doubles the variance:

σw2=2nin\boxed{\sigma_w^2 = \frac{2}{n_{\text{in}}}}

Sampling weights with variance 2nin\frac{2}{n_{\text{in}}} guarantees that signals passing through ReLU layers remain stable across hundreds of layers.


7. Python Simulation: Experiencing the Exponential Curve

The script below demonstrates how rapidly scalar and matrix signals vanish or explode over 50 layers:

PYTHON
import numpy as np

def simulate_propagation(weight_scalar, num_layers=50):
    val = 1.0
    history = [val]
    for _ in range(num_layers):
        val *= weight_scalar
        history.append(val)
    return history

layers = 50
exploding = simulate_propagation(1.5, layers)
vanishing = simulate_propagation(0.5, layers)
balanced  = simulate_propagation(1.0, layers)

print(f"Initial Value: 1.0")
print(f"After {layers} layers with w=1.5: {exploding[-1]:.4e} (EXPLODED)")
print(f"After {layers} layers with w=0.5: {vanishing[-1]:.4e} (VANISHED)")
print(f"After {layers} layers with w=1.0: {balanced[-1]:.4f} (STABLE)")

# Multi-layer network simulation with independent Xavier weights per layer
np.random.seed(42)
x = np.random.randn(100, 1)

signal = x
for _ in range(50):
    W_layer = np.random.randn(100, 100) * np.sqrt(1.0 / 100)  # Variance 1/n_in
    signal = W_layer @ signal

print(f"\nInitial input variance: {np.var(x):.4f}")
print(f"50-layer Xavier signal variance: {np.var(signal):.4f} (STABLE)")

Output:

TEXT
Initial Value: 1.0
After 50 layers with w=1.5: 6.3762e+08 (EXPLODED)
After 50 layers with w=0.5: 8.8818e-16 (VANISHED)
After 50 layers with w=1.0: 1.0000 (STABLE)

Initial input variance: 0.8165
50-layer Xavier signal variance: 0.5654 (STABLE)

8. Test Your Understanding

schoolQuestion 1: If every layer multiplies its input by 2, what happens after 20 layers?
expand_more

Answer: The value grows exponentially: 220=1,048,5762^{20} = 1{,}048{,}576 (over 1 million times larger). In deep networks, this leads to arithmetic overflow (Infinity/NaN).

schoolQuestion 2: If every layer multiplies its input by 0.1, what happens as layers increase?
expand_more

Answer: The value approaches zero exponentially (0.1L→00.1^L \to 0). By layer 16, 0.116=10−160.1^{16} = 10^{-16}, hitting the floating-point precision limit and underflowing to zero.

schoolQuestion 3: Why do the earliest layers stop learning in a deep network with vanishing gradients?
expand_more

Answer: By the chain rule, ∂L∂W[1]∝W[2]W[3]⋯W[L]\frac{\partial L}{\partial W^{[1]}} \propto W^{[2]} W^{[3]} \cdots W^{[L]}. When downstream weights or activation derivatives are <1< 1, multiplying them together creates a near-zero factor. The gradient reaching Layer 1 is virtually 0, so gradient descent makes no parameter updates.

schoolQuestion 4: What is the primary mathematical purpose of Xavier and He initialization?
expand_more

Answer: To set the initial weight variance (σw2=1nin\sigma_w^2 = \frac{1}{n_{\text{in}}} or 2nin\frac{2}{n_{\text{in}}}) such that the output variance of each layer equals the input variance (Var⁡(z)≈Var⁡(x)\operatorname{Var}(z) \approx \operatorname{Var}(x)), preventing exponential growth or decay across depth.


  1. Activation Functions — Why switching from Sigmoid (σ′≤0.25\sigma' \le 0.25) to ReLU (σ′=1\sigma' = 1) solved the vanishing gradient problem in practice.
  2. The Complete Guide to Backpropagation — Tracing dependency trees and matrix calculus through deep layers.
  3. Batch & Layer Normalization — How normalization layers dynamically rescale activations between layers throughout training.
  4. Deep Learning: Unstable Gradients — Full textbook chapter on gradient clipping, residual connections, and diagnostics.