Initialization

Dive into Deep Learning · §5.3

Parameter Initialization
framework defaults · tree-wide initializers · truncated normals · residual variance (1 + g^2)^N · 1/\sqrt{N} & zero scaling

Why Per-Layer He Init Still Explodes in ResNets

The Residual Initialization Paradox

  • Additive skip connections: Every residual block computes \mathbf{x}_{k+1} = \mathbf{x}_k + f_k(\mathbf{x}_k).
  • Uncorrelated variances add: When both \mathbf{x}_k and f_k(\mathbf{x}_k) have unit mean square and are uncorrelated, their sum has double the mean square (2\times variance per block).
  • Exponential blow-up with depth: Across N = 32 residual blocks, activation standard deviation compounds by 2^{32/2} = 2^{16} = 65{,}536\times at step 0.

Default Initializers Do Not Use He Initialization

Why Defaults Collapse Deep ReLU Stacks

  • Default variance multiplier per ReLU layer (\frac{1}{2}n_{\text{in}}\sigma^2): nn.Linear draws U(\pm 1/\sqrt{n_{\text{in}}}), so \sigma^2 = \frac{1}{3n_{\text{in}}} and each layer multiplies the mean square by \frac{1}{6} (6^{-10} \approx 1.7 \times 10^{-8} after 10 layers).
  • He initialization (\sigma^2 = 2/n_{\text{in}}) keeps the multiplier at exactly 1.

Applying He Initialization Across a 10-Layer Module Tree

Tree-Wide Initialization

  • Walking the module tree to apply He initialization (\sigma = \sqrt{2 / n_{\text{in}}}) restores the output mean square of a 10-layer ReLU stack to order one.

Walking the Tree to Apply He Initialization

Tree-Wide Initialization

net = nn.Sequential(*[module for _ in range(10) for module in
                      (nn.Linear(256, 256, bias=False), nn.ReLU())])
X = torch.randn(1024, 256)
print(f'default: mean square of the output {net(X).pow(2).mean():.2g}')

def init_he(module):
    if isinstance(module, nn.Linear):
        nn.init.kaiming_normal_(module.weight, nonlinearity='relu')

net.apply(init_he)
print(f'He:      mean square of the output {net(X).pow(2).mean():.2g}')
default: mean square of the output 1.9e-08
He:      mean square of the output 1.1

Truncated Normals Eliminate Extreme Initial Outliers

Bounding Tail Draws at Scale

  • Across 10^8 weights, a Gaussian yields dozens of >5\sigma outliers. BERT and ViT use a truncated normal that redraws samples outside \pm 2\sigma (std \approx 0.88\times):
w = torch.empty(1000, 1000)
nn.init.normal_(w, std=0.02)
print(f'normal:    std {w.std():.4f}, max weight {w.abs().max():.4f}')
nn.init.trunc_normal_(w, std=0.02, a=-0.04, b=0.04)
print(f'truncated: std {w.std():.4f}, max weight {w.abs().max():.4f}')
normal:    std 0.0200, max weight 0.0998
truncated: std 0.0176, max weight 0.0400

Writing a Gain-Parameterized Custom Initializer

Custom Initializer Interface

  • We implement a reusable normal initializer with standard deviation \sigma = g / \sqrt{n_{\text{in}}} (weights are stored as (n_out, n_in)):
def scaled_normal_(weight, gain):
    nn.init.normal_(weight, std=gain / math.sqrt(weight.shape[1]))

Editing Parameter Tensors Directly in Place

Direct Weight Manipulation

We can also rescale or edit parameter tensors directly in place. Because ReLU is positively homogeneous, halving the final layer’s weights quarters the output mean square:

before = net(X).pow(2).mean()
with torch.no_grad():
    net[-2].weight *= 0.5
print(f'{before:.2g} before, {net(X).pow(2).mean():.2g} after')
1.1 before, 0.28 after

Deriving Variance Growth Across a Residual Block

Residual Block Variance Analysis

m_{k+1} = m_k + g^2 m_k = (1 + g^2)\, m_k

  1. Expansion + ReLU preserves input scale: The d \to 4d He layer (\text{Var} = 2/d) doubles mean square to 2m_k, and ReLU halves it back to m_k.
  2. Output projection scales by g^2: The 4d \to d projection (\text{Var} = g^2/(4d)) yields body mean square g^2 m_k.
  3. Uncorrelated skip and body add: \mathbb{E}[\mathbf{x}_k^\top f_k(\mathbf{x}_k)] = 0 \implies m_N = (1 + g^2)^N m_0.

Three Gain Schedules for Depth-N Residual Stacks

Controlling Compounding Across Depth

  • Unscaled (g = 1): Doubles variance per block (m_N = 2^N m_0), blowing up activation std by 2^{16} = 65{,}536\times at N = 32.
  • Depth-scaled (g = 1/\sqrt{N}, GPT-2): Multiplies variance by 1 + 1/N per block, bounding m_N \le e\,m_0 (\text{std} \le \sqrt{e} \approx 1.65\times).
  • Zero-initialized (g = 0, Fixup): Starts every residual block as an exact identity map (m_N = m_0, \text{std} = 1.00\times).

Why Scaling by 1/√N Caps Growth at √e for Any Depth

The GPT-2 Residual Scaling Rule

m_N = \left(1 + \frac{1}{N}\right)^N m_0 \le e \, m_0 \approx 2.718 \, m_0

  • Depth-independent bound: Since (1 + 1/N)^N \nearrow e, the activation standard deviation never exceeds \sqrt{e} \approx 1.65\times the input scale—whether the model has 8, 32, or 1,000 blocks.
  • Used in practice: GPT-2 shrinks the initial standard deviation of every residual branch’s output projection by 1/\sqrt{N}.

Why Zeroing Output Projections Avoids the Symmetry Trap

Zero Output Projections (g = 0)

  • Step 0 (Identity network): Zeroing only the output projection (\mathbf{W}_{\text{out}} = \mathbf{0}) sets f_k(\mathbf{x}_k) = \mathbf{0} so \mathbf{x}_{k+1} = \mathbf{x}_k with unit variance.
  • Step 1 backward pass (Breaking zero): Because the expansion layer (d \to 4d) has random He weights, its post-ReLU activations \mathbf{h}_k are nonzero and distinct.
  • Immediate wake-up: \nabla_{\mathbf{W}_{\text{out}}} L = (\nabla_{\mathbf{x}_{k+1}} L)\mathbf{h}_k^\top \neq \mathbf{0} updates \mathbf{W}_{\text{out}} on step 1 so gradients flow into the body from step 2 onward.

WideResidualBlock With Configurable Output Gain

Experimental Setup

We test all three schedules on a d \to 4d \to d residual block (WideResidualBlock, width d = 64) using He initialization (g = \sqrt{2}) on the expansion layer and out_gain on the output projection:

class WideResidualBlock(nn.Module):
    def __init__(self, d, out_gain):
        super().__init__()
        self.body = nn.Sequential(nn.Linear(d, 4 * d), nn.ReLU(),
                                  nn.Linear(4 * d, d))
        for layer, gain in ((self.body[0], math.sqrt(2)),
                            (self.body[2], out_gain)):
            scaled_normal_(layer.weight, gain)
            nn.init.zeros_(layer.bias)

    def forward(self, X):
        return X + self.body(X)

Measuring Activation Standard Deviation Across Depth

Forward-Pass Diagnostic

std_across_depth stacks num_blocks blocks of width d = 64, feeds in a minibatch of 256 \mathcal{N}(0, 1) vectors, and records the empirical standard deviation after every block:

def std_across_depth(num_blocks, out_gain):
    net = nn.Sequential(*[WideResidualBlock(64, out_gain)
                          for _ in range(num_blocks)])
    X = torch.randn(256, 64)
    stds = [X.std().item()]
    with torch.no_grad():
        for block in net:
            X = block(X)
            stds.append(X.std().item())
    return stds

Empirical Verification Across 32 Residual Blocks

Theory Meets Measurement

Measuring g = 1, 1/\sqrt{N} and 0 over N \in \{2, 8, 32\} blocks confirms (1+g^2)^N:

  N  unscaled    scaled      zero
  2      2.04      1.49     0.996
  8      13.8      1.55     0.988
 32  5.24e+04      1.57      1.01
  • Always run a step-0 forward check: one unit-variance batch through a new architecture catches variance explosion in milliseconds.

Concept Check: Initialization & Residual Scaling

Concept Check

Work out the variance multipliers for these three initialization scenarios:

  1. A 10-layer ReLU MLP (256 \to 256, no biases) uses a \mathcal{U}(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}}) initializer. By what factor does each layer multiply the activation mean square, and what happens after 10 layers?
  2. An initializer draws from \mathcal{N}(0, \sigma^2), truncates at \pm 2\sigma (which shrinks std by 0.88), and rescales so the final std is \sigma = 0.02. What is the maximum possible magnitude |w| after rescaling?
  3. What is the largest output-projection gain g that keeps the mean square after N = 100 residual blocks within 3\times the input mean square?

Answers:

  1. \frac{1}{6} per layer (6^{-10} \approx 1.7 \times 10^{-8} after 10 layers): \text{Var}(w) = \frac{1}{3 n_{\text{in}}} scales variance by \frac{1}{3}, and ReLU halves it to \frac{1}{6}.
  2. |w|_{\max} = \frac{2\sigma}{0.88} \approx 2.27\sigma = 0.0455: Rescaling divides the \pm 0.04 cutoff by 0.88.
  3. g \le \sqrt{3^{1/100} - 1} \approx \sqrt{\ln(3)/100} \approx 0.105 (close to 1/\sqrt{100} = 0.10, which gives 1.01^{100} \approx 2.70).

Summary: Parameter Initialization

Key Takeaways

  • Single-layer & tree-wide init: \sigma = g/\sqrt{n_{\text{in}}} (g = \sqrt{2} for ReLU) applied across the module tree prevents deep signal decay; truncated normals clip >2\sigma outliers.
  • Residual variance compounding: m_{k+1} = (1 + g^2)m_k \implies m_N = (1 + g^2)^N m_0 explodes as 2^N when g = 1.
  • Residual branch scaling: Setting output-projection gain to g = 1/\sqrt{N} caps std growth at \sqrt{e} \approx 1.65\times, while g = 0 starts as an exact identity map.