Numerical Stability and Initialization

Dive into Deep Learning · §4.4

Numerical Stability & Variance-Preserving Initialization
vanishing & exploding products · per-layer variance scaling · Xavier & He initialization · symmetry breaking

Why a 10-Layer MLP Fails with N(0, 0.01²) or N(0, 1)

The Depth Bottleneck

  • Too small (\mathcal{N}(0, 0.01^2)): Across 9 hidden hops of width h = 256, gradient mean squares shrink by 10^{-17}, leaving the loss frozen at \log 10 \approx 2.30 (10\% random guessing).
  • Too large (\mathcal{N}(0, 1)): Across 9 hops, gradient mean squares explode by 10^{19}; deeper stacks overflow float32 past 3.4 \times 10^{38} to inf/NaN on step 1.
  • Variance-preservation principle: Both forward activations and backward gradients must maintain O(1) variance across every layer from step 0.

The Backward Gradient Is a Product of Layer Matrices

Vanishing & Exploding Products

\frac{\partial L}{\partial \mathbf{H}^{(k-1)}} = \Bigl(\frac{\partial L}{\partial \mathbf{H}^{(k)}} \odot \phi'\bigl(\mathbf{Z}^{(k)}\bigr)\Bigr)\, \mathbf{W}^{(k)\top}

  • Matrix product across depth: Unrolling from layer K-1 down to layer k multiplies t = K - 1 - k matrix-slope operators \odot\,\phi'(\mathbf{Z}^{(l)})\mathbf{W}^{(l)\top}.
  • Exponential sensitivity: Even a 10\% per-layer drift compounds across 50 layers to 0.9^{50} \approx 0.005 (vanishing) or 1.1^{50} \approx 117 (exploding).

Per-Layer Gradient Variance Multiplier: hτ²𝔼[φ′(z)²]

Analytical Variance Scaling

\mathbb{E}[g_i^2] = \underbrace{h\, \tau^2\, \mathbb{E}\bigl[\phi'(z)^2\bigr]}_{\textrm{per-layer multiplier}}\, \mathbb{E}[(g'_j)^2]

  • ReLU (\mathbb{E}[\phi'(z)^2] = 1/2): At h = 256, \tau = 0.01 multiplies variance by 0.0128\times per layer (10^{-17} after 9 hops), while \tau = 1 multiplies by 128\times (10^{19} after 9 hops).
  • Sigmoid (\mathbb{E}[\sigma'(z)^2] \le 1/16): Even with h\tau^2 = 1, variance shrinks by at least 16\times per layer (\le 1.5 \times 10^{-11} after 9 hops).

Empirical Verification across 10 Layers

Measuring Vanishing & Exploding Gradients

  • Setup: Activation and gradient mean squares of a 10-layer, width-256 network at initialization, for our three regimes.
  • Exact exponential lines on a log axis: Every layer multiplies the mean square by a constant factor, producing straight lines on a semilog plot.
  • Predicted vs. measured at Layer 1:
    • ReLU, \tau = 0.01: \sim 10^{-17} (vanished)
    • ReLU, \tau = 1: \sim 10^{19} (exploded)
    • Sigmoid, \tau = 1/16: \sim 5 \times 10^{-12}

ReLU, N(0, 0.01²): gradient mean square at layer 1: 8.5e-18
ReLU, N(0, 1): gradient mean square at layer 1: 8.2e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.5e-12

Why Sigmoid Vanishes Even with Scaled Weights

Vanishing & Exploding Mechanisms

  • The sigmoid catch-22: Since \sigma'(z) \le 1/4, setting h\tau^2 = 1 divides gradient variance by \ge 16 per layer, and inflating weights (h\tau^2 \ge 16) pushes pre-activations z into the saturated tails (|z| \gg 3) where \sigma'(z) \to 0 even faster.
  • Exploding gradients ruin step-size conditioning: When layer-1 gradients are 10^9\times larger than layer-10 gradients, no single learning rate \eta can train both layers simultaneously.

Forward & Backward Variance Balance: Xavier Init

Xavier (Glorot) Initialization

\begin{aligned}\mathrm{Var}[o_j] &= \bigl(n_{\textrm{in}}\,\tau^2\bigr)\,\gamma^2, \\ \mathrm{Var}[g_i] &= \bigl(n_{\textrm{out}}\,\tau^2\bigr)\,\mathrm{Var}[g'_j]\end{aligned}

  • Dual preservation criteria: Forward variance preservation requires n_{\textrm{in}}\tau^2 = 1; backward gradient preservation requires n_{\textrm{out}}\tau^2 = 1.
  • Xavier compromise (Glorot & Bengio, 2010): Average the two fan counts \frac{1}{2}(n_{\textrm{in}} + n_{\textrm{out}})\tau^2 = 1 \implies \tau^2 = \frac{2}{n_{\textrm{in}} + n_{\textrm{out}}}.

He (Kaiming) Initialization for ReLU Networks

He Initialization

v^{(k)} = \frac{1}{2}\, n_{\textrm{in}}\, \tau^2\, v^{(k-1)} \quad \Longrightarrow \quad \tau^2 = \frac{2}{n_{\textrm{in}}}

  • ReLU halves the second moment: Zeroing out the negative half of a symmetric zero-mean pre-activation z gives \mathbb{E}[\mathrm{ReLU}(z)^2] = \frac{1}{2}\mathbb{E}[z^2].
  • He / Kaiming rule (He et al., 2015): Double the weight variance to \tau^2 = 2 / n_{\textrm{in}} so \frac{1}{2}n_{\textrm{in}}\tau^2 = 1 holds across arbitrarily deep ReLU stacks.

Measured Activation Variance Across 10 ReLU Layers

Xavier vs. He in Depth

  • Setup: 10 ReLU layers of width h = 256 under three initializations; Xavier and He differ by a factor of 2 per layer.
  • \mathcal{N}(0, 0.01^2): Collapses to \sim 10^{-19} by layer 10.
  • Xavier (\tau^2 = 1/h): Loses a factor of 1/2 at every ReLU layer, decaying by 2^{-10} \approx 10^{-3} across 10 layers.
  • He (\tau^2 = 2/h): Holds both activation mean squares and backward gradient mean squares near 1, within a factor of about 2, across all 10 layers.

N(0, 0.01²): activations at layer 10: 1.2e-19, gradient at layer 1: 1.2e-17
Xavier: activations at layer 10: 7.4e-04, gradient at layer 1: 1.9e-03
He: activations at layer 10: 5.7e-01, gradient at layer 1: 8.3e-01

Building a 10-Layer Parameterized DeepMLP

Deep Network Construction

To test how initial weight scale determines trainability, DeepMLP(std, lr, depth=10, width=256) stacks 10 hidden ReLU layers (784 \to 256 \times 10 \to 10) and initializes each layer’s weights with standard deviation std(n_in, n_out):

class DeepMLP(d2l.Classifier):
    """A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
    def __init__(self, std, lr, depth=10, width=256):
        super().__init__()
        self.save_hyperparameters(ignore=['std'])
        sizes = [784] + [width] * depth + [10]
        layers = [nn.Flatten()]
        for n_in, n_out in zip(sizes[:-1], sizes[1:]):
            layer = nn.Linear(n_in, n_out)
            nn.init.normal_(layer.weight, std=std(n_in, n_out))
            nn.init.zeros_(layer.bias)
            layers += [layer, nn.ReLU()]
        self.net = nn.Sequential(*layers[:-1])  # No ReLU after the logits

Training a 10-Layer MLP on Fashion-MNIST

Impact on Real Training

  • Setup: A 10-hidden-layer ReLU DeepMLP (784 \to 256 \times 10 \to 10), 10 epochs on Fashion-MNIST at \eta = 0.05.
  • \mathcal{N}(0, 0.01^2): Completely untrainable—loss stays flat at \log 10 \approx 2.30 (10\% accuracy).
  • Xavier: Starts slowly on epoch 1 (due to the 2^{-10} signal attenuation) before recovering to above 80\% accuracy.
  • He initialization: Drops the training loss steeply from epoch 1 and reaches 85–87\% validation accuracy cleanly.

N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.84
He: validation accuracy 0.87

Beware: Framework Default Initializers Are Rarely He

Framework Defaults Pitfall

Standard framework linear layers do not default to He initialization—leaving defaults untouched in a deep plain ReLU stack causes progressive signal decay:

Framework Layer Built-In Default Distribution Weight Variance \tau^2 ReLU Multiplier \frac{1}{2}h\tau^2 (h = 256)
PyTorch nn.Linear U(-1/\sqrt{n_{\textrm{in}}}, 1/\sqrt{n_{\textrm{in}}}) \frac{1}{3 n_{\textrm{in}}} \frac{1}{6} \approx 0.167 per layer
Explicit He Normal \mathcal{N}(0, 2/n_{\textrm{in}}) \frac{2}{n_{\textrm{in}}} 1.000 per layer

Symmetry Breaking: Why Weights Cannot Be Constant

Permutation Symmetry

Why not initialize every entry of \mathbf{W}^{(1)} deterministically to the constant c = \sqrt{2/n_{\textrm{in}}}, which has the exact He mean square c^2 = 2/n_{\textrm{in}}?

constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.16
  • Permutation invariance: An MLP’s output is unchanged if we permute the columns of \mathbf{W}^{(1)} and the corresponding rows of \mathbf{W}^{(2)}.
  • Deterministic fixed point of SGD: If all columns of \mathbf{W}^{(1)} start identical (c) and all rows of \mathbf{W}^{(2)} start identical (c_{\textrm{out}}), every hidden unit receives the same gradient (0.00 difference above) and remains identical forever, reducing width h to 1 effective unit.

What Initialization Alone Cannot Fix During Training

Limits of Initialization

  • Post-step-1 correlation drift: \mathrm{Var}[o_j] = n_{\textrm{in}}\tau^2\gamma^2 assumes independent weights and inputs at step 0; once SGD updates \mathbf{W}^{(k)}, layer gains can drift away from 1.
  • ReLU rescaling symmetry: Because \mathrm{ReLU}(\alpha z) = \alpha\,\mathrm{ReLU}(z) for \alpha > 0, multiplying incoming weights by \alpha and outgoing weights by 1/\alpha preserves the function while distorting gradient norms.
  • Deep architectural stabilizers (K \ge 50): Combine He/Xavier init with BatchNorm / LayerNorm and residual skip connections.

Concept Check: Initialization Scales & Symmetry

Check

Test your understanding of variance propagation and symmetry breaking:

  1. He scale calculation: For the first layer of our Fashion-MNIST ReLU MLP (n_{\textrm{in}} = 784 \to n_{\textrm{out}} = 256), what weight standard deviation \tau do Xavier and He prescribe?
  2. Leaky ReLU initialization: Suppose a hidden layer uses Leaky ReLU \phi(z) = \max(z, \alpha z) with \alpha = 0.1. For symmetric zero-mean z, what is \mathbb{E}[\phi'(z)^2], and what weight variance \tau^2 preserves the mean square?
  3. Bias symmetry breaking: If all weights start at zero (\mathbf{W}^{(1)} = \mathbf{0}, \mathbf{W}^{(2)} = \mathbf{0}), does initializing \mathbf{b}^{(1)} to distinct random numbers break hidden-unit symmetry on step 1?

Answers:

  1. First-layer \tau: Xavier gives \tau = \sqrt{2/(784 + 256)} = \sqrt{2/1040} \approx 0.0439; He gives \tau = \sqrt{2/784} = 1/19.8 \approx 0.0505 (5\times larger than 0.01).
  2. Leaky ReLU: \phi'(z)^2 = 1 for z > 0 (prob 1/2) and \alpha^2 for z < 0 (prob 1/2), so \mathbb{E}[\phi'(z)^2] = \frac{1 + \alpha^2}{2} and \tau^2 = \frac{2}{(1 + \alpha^2)n_{\textrm{in}}}.
  3. Zero weights: If \mathbf{W}^{(2)} = \mathbf{0}, then \partial L / \partial \mathbf{H} = (\partial L / \partial \mathbf{O})\mathbf{W}^{(2)\top} = \mathbf{0}, so \partial L / \partial \mathbf{W}^{(1)} = \mathbf{0} for all hidden units on step 1 regardless of \mathbf{b}^{(1)}. Random weights are essential.

Summary: Numerical Stability and Initialization

Key Takeaways

Initialization / Regime Weight Variance \tau^2 Per-Layer Multiplier (\text{ReLU}) 10-Layer Signal Scaling Deep Learning Role & Behavior
Small Fixed \mathcal{N}(0, 0.01^2) 10^{-4} \frac{1}{2}h(10^{-4}) = 0.0128 \sim 10^{-17} (vanishes) Freezes early layers; 10-layer MLP stays stuck at \log 10
Large Fixed \mathcal{N}(0, 1) 1 \frac{1}{2}h(1) = 128 \sim 10^{19} (explodes) Overflows float32 to inf/NaN or destabilizes SGD
Sigmoid (\sigma(z)) 1/n_{\textrm{in}} \mathbb{E}[\sigma'(z)^2] \le 1/16 \le 16^{-9} \approx 10^{-11} Slope \le 1/4 plus tail saturation causes vanishing gradients
Xavier / Glorot \frac{2}{n_{\textrm{in}} + n_{\textrm{out}}} \frac{1}{2} (on ReLU); 1 (on \tanh) 2^{-10} \approx 10^{-3} (on ReLU) Standard for linear, \tanh, and attention projection layers
He / Kaiming \frac{2}{n_{\textrm{in}}} \frac{1}{2}n_{\textrm{in}}\bigl(\frac{2}{n_{\textrm{in}}}\bigr) = 1 \approx 1.0 across all layers Standard for ReLU/GELU networks; trains immediately at depth
Constant Weights (w_{ij} = c) c^2 = 2/n_{\textrm{in}} Preserves norm, rank 1 All columns identical Fails to break permutation symmetry; h units act as 1