Weight Initialization, Gradient Flow & Global Norm Clipping
Why starting weights at zero breaks neural networks, how Xavier/Glorot and Kaiming/He preserve signal variance across 100 layers, and how Global L2 Norm Clipping rescues exploding gradients.
Bad initialization kills a 20-layer network on Step 0 before the optimizer even takes its first step!
Even with AdamW and LayerNorm, initializing residual projections or custom PyTorch modules with the wrong variance causes early NaN loss spikes or dead layers that stall training for days.
Understanding why Var(Wx) = n_in · Var(W) · Var(x) immediately explains why scaling by 1/√d shows up EVERYWHERE — from Kaiming init to Scaled Dot-Product Attention (QKᵀ / √d_k)!
Classic FAANG ML interview triple-combo: '1) What happens if I initialize all weights to 0? 2) Why does Kaiming He have a factor of 2 inside √(2/n_in)? 3) Why prefer Global L2 Norm Clipping over per-element value clipping?'
Suppose you initialize ALL weights of a 2-layer MLP to 0.0 (while biases start at 0.0) and train with SGD for 10,000 steps. What happens to the 128 hidden neurons?
- Prove why zero or constant weight initialization permanently destroys symmetry across hidden neurons
- Derive Xavier/Glorot (σ² = 1/n_in) for linear/Tanh layers and Kaiming/He (σ² = 2/n_in) for ReLU layers
- Diagnose vanishing vs. exploding activations and gradients across deep stacks
- Implement Global L2 Gradient Norm Clipping in PyTorch while preserving the exact gradient direction
Think of a 20-layer neural network as a 20-person game of telephone with volume knobs between each person. If every person whispers at 0.5× volume, by person 20 the message is 0.5²⁰ ≈ 0.000001 (pure silence — vanishing). If every person shouts at 1.5× volume, by person 20 the sound is 1.5²⁰ ≈ 3,325× (blown speakers — exploding). Kaiming / Xavier initialization sets every knob to exact 1.0× energy preservation so both the forward signal AND the backward gradient travel cleanly across dozens of layers!
1. Symmetry Breaking: Why Zero (or Constant) Weights Fail Permanently
Imagine hiring 100 detectives to solve a crime, but giving every single one the exact same clue, the exact same notebook, and the exact same instructions. All 100 detectives will write the exact same report forever! In a neural network, initializing all weights to 0 (or any constant c) forces every hidden neuron to behave as an identical twin.
Proof of Symmetry Collapse
For any two hidden neurons and in the same layer with identical weights and biases :
- Forward pass: , so .
- Backward pass: Because both feed identically into the next layer, .
- Update: .
By mathematical induction, all 128 neurons stay identical clones forever! Note: Initializing biases is completely fine because random weights already break symmetry.
2. Variance Preservation: Deriving Xavier (Tanh) & Kaiming He (ReLU)
Okay, weights must be random — but how big should the random numbers be? Slide the ratio below to watch how even a tiny 1.3× variance mismatch compounds exponentially across 16 ReLU layers!
Exact Variance Derivation
Consider a single linear pre-activation where and are independent with mean :
To keep across every layer, we need :
- Xavier / Glorot Init (Sigmoid / Tanh / Linear): Balances forward () and backward () variance:
- Kaiming / He Init (ReLU): ReLU zeroes out the entire negative half of a symmetric distribution, cutting variance in half ()! To compensate, we double the weight variance:
σ_He = √(2 / n_in)
Compensates for ReLU zeroing out ~50% of pre-activations, which cuts variance in half.
nn.Linear(512, 256) followed by ReLU, Kaiming Normal samples weights from N(0, (√(2/512))²) = N(0, 0.0625²), keeping Layer 20 activation std right near 1.0!16-Layer ReLU Signal Survival Simulator
Layer 16 activation std: 1.000 — Notice how even a tiny 1.3× mistake compounds to 1.3¹⁶ ≈ 66× across 16 layers!
3. Global L2 Gradient Norm Clipping (Direction-Preserving Safety Brake)
Even with perfect Kaiming init, a sudden sharp cliff in the loss surface (very common in RNNs and LLMs!) can launch a single batch's gradient to 10,000, catapulting weights into NaN territory. Global L2 Norm Clipping acts like an automatic speed governor that shrinks the step size without steering off course.
Global Norm Clipping vs. Per-Element Value Clipping
Given all parameter gradient tensors across the entire model:
- Compute the single global L2 norm:
- If (e.g., ), rescale every gradient tensor by the same scalar factor :
Why Global L2 beats per-element clip_grad_value_: Clamping individual coordinates to distorts the gradient vector's angle (it stops pointing in the steepest descent direction!). Scaling the whole vector uniformly by keeps the exact direction intact while guaranteeing .
Worked Example: Global L2 Gradient Clipping by Hand
A tiny 2-parameter model has gradients g₁ = [3.0, 4.0] and g₂ = [0.0, 12.0], and max_norm c = 6.5. Compute the global norm G and the clipped gradients.
Why does torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) preserve optimization geometry better than clip_grad_value_?
A nn.Linear(200, 100) layer is followed by ReLU. What exact weight standard deviation σ does Kaiming He Normal initialization use?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Yes! By default, PyTorch's nn.Linear and nn.Conv2d call kaiming_uniform_(weight, a=math.sqrt(5)). However, when writing custom residual blocks or Transformer projections (like GPT-2's 1/√(2N) residual scaling), engineers explicitly call nn.init.kaiming_normal_ or nn.init.xavier_uniform_.
Xavier vs. Kaiming Init & Global Gradient Norm Clipping Studio
Watch forward activations (cyan) and backward gradients (crimson) propagate across 12 ReLU layers — then rescue exploding gradients with Global L2 Norm Clipping.
σ = √(2/n_in)) breaks neuron symmetry and keeps ReLU variance ≈ 1.0 across deep stacks, while Global L2 Gradient Norm Clipping (g ← g·c/G) stops exploding gradients without distorting descent direction.LLM Pre-training (GPT / LLaMA)
Almost every frontier LLM uses clip_grad_norm_(params, 1.0) + 1/√(2L) residual-output scaling to prevent mid-training loss spikes.
Deep ResNets & ConvNets
Kaiming He init allowed training 30+ layer ConvNets from scratch for the first time in 2015 without auxiliary losses.
RNNs & LSTMs
Unrolling 100+ time steps causes W_hh^100 gradient spikes; Global L2 Norm Clipping is mandatory to prevent instant NaN weights.
LoRA & Residual Adapters
Initializing the output matrix B = 0 (while A is random Gaussian) makes adapters start as exact identity functions without symmetry collapse.
import math
import torch
import torch.nn as nn
# 1. From-Scratch Kaiming Normal Init + Global L2 Gradient Norm Clipping
def kaiming_normal_init(weight: torch.Tensor) -> None:
fan_in = weight.shape[1] # weight shape: (out_features, in_features)
std = math.sqrt(2.0 / fan_in)
with torch.no_grad():
weight.normal_(0.0, std)
def clip_grad_norm_scratch(params, max_norm: float = 1.0, eps: float = 1e-6) -> float:
grads = [p.grad for p in params if p.grad is not None]
total_norm = torch.sqrt(sum(g.detach().pow(2).sum() for g in grads))
clip_coef = max_norm / (total_norm + eps)
if clip_coef < 1.0:
for g in grads:
g.mul_(clip_coef) # uniform in-place scale -> preserves exact direction!
return float(total_norm)
# 2. Idiomatic Production PyTorch Training Step
layer = nn.Linear(512, 256) # weight: (256, 512)
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
x = torch.randn(32, 512) # (B=32, d_in=512)
loss = torch.relu(layer(x)).pow(2).mean()
loss.backward()
# Clip AFTER backward(), BEFORE optimizer.step()!
total_grad_norm = nn.utils.clip_grad_norm_(layer.parameters(), max_norm=1.0)
scaler.unscale_(optimizer) before clip_grad_norm_ under FP16 AMP.65536 × g to 1.0 shrinks real updates by 65,536×!√(2/n_in)) for ReLU-family activations to compensate for half-wave variance halving.model.parameters().model.parameters() together so relative layer gradient ratios stay intact.G = 10.0 and max_norm = 2.0, by what factor does clip_grad_norm_ multiply every gradient element?clip_grad_norm_ be called in a standard PyTorch training step?clip_grad_value_?