Weight Initialization: Xavier and He
Before training starts, every weight needs a value. Zero does not work, and random values of the wrong size make activations and gradients vanish or explode within a few layers. The fix is a short variance calculation: choose the weight variance so that each layer preserves the variance of its input. That calculation gives the Xavier (Glorot) and He (Kaiming) rules used by every framework.
Why not zeros?
If all weights of a layer start equal, every hidden unit computes the same function and receives the same gradient, so they stay identical forever: the layer behaves like a single unit. Random initialization breaks the symmetry. Biases, which do not cause symmetry, are usually set to zero.
The variance calculation
For a layer with independent, zero-mean weights and inputs,
To keep we need . The activation adjusts the picture:
- tanh or linear (Xavier/Glorot): is close to the identity near 0, giving ; averaging with the backward-pass condition gives the usual .
- ReLU (He/Kaiming): ReLU zeroes half its inputs, so ; compensating needs .
import numpy as np
rng = np.random.default_rng(0)
n, L = 512, 20
x0 = rng.normal(size=(1000, n))
def forward_std(std, act):
h = x0
for _ in range(L):
h = act(h @ rng.normal(0, std, (n, n)))
return h.std()
relu = lambda a: np.maximum(0, a)
print(f"ReLU, std 0.01 : activation std after {L} layers {forward_std(0.01, relu):.2e}")
print(f"ReLU, std 1 : {forward_std(1.0, relu):.2e}")
print(f"ReLU, He sqrt(2/n) : {forward_std(np.sqrt(2 / n), relu):.3f}")
print(f"tanh, Xavier sqrt(1/n): {forward_std(np.sqrt(1 / n), np.tanh):.3f}")ReLU, std 0.01 : activation std after 20 layers 8.79e-17
ReLU, std 1 : 7.67e+23
ReLU, He sqrt(2/n) : 0.969
tanh, Xavier sqrt(1/n): 0.160
Too small and the signal vanishes; too large and it explodes. He initialization keeps the ReLU network at a standard deviation near 1 after 20 layers. With tanh and Xavier the signal still shrinks slowly (to about 0.16 here), because tanh compresses large inputs, but there is no collapse to or explosion to .
The backward pass
Gradients flow through , so their variance is preserved when (times the activation factor). Xavier's compromises between the forward and backward conditions; He initialization picks one of them (fan_in mode by default).
import numpy as np
rng = np.random.default_rng(1)
n, L = 512, 20
Ws = [rng.normal(0, np.sqrt(2 / n), (n, n)) for _ in range(L)]
x = rng.normal(size=n); masks = []
for W in Ws:
a = W @ x; masks.append(a > 0); x = np.maximum(0, a)
g = rng.normal(size=n); g0 = np.linalg.norm(g)
for W, m in zip(reversed(Ws), reversed(masks)):
g = W.T @ (g * m)
print(f"He init: gradient norm ratio first/last layer after {L} layers = {np.linalg.norm(g) / g0:.3f}")He init: gradient norm ratio first/last layer after 20 layers = 1.300
Uniform or normal?
The variance is what matters, not the shape. A uniform distribution on has variance , so Xavier-uniform uses . Truncated normals avoid rare huge weights.
Transformers and residual scaling
With residual connections, every block adds to the residual stream, so its variance grows with depth. GPT-2 scales the output projection of each block by for layers; other schemes (T-Fixup, DeepNet, P) set initialization and learning rates as functions of width and depth so that hyperparameters transfer from small to large models.
In software
nn.init.kaiming_normal_(w, nonlinearity="relu"),nn.init.xavier_uniform_(w);nn.Lineardefaults to a Kaiming-uniform variant with .- Embedding tables are typically initialized in GPT-style models.
- A healthy initial loss for classes is about (Maximum Likelihood); zeroing the last layer's weights achieves it exactly.
Go further: Weight Initialisation in Practice compares five schemes on a thirty-layer network and shows what PyTorch does by default.
Exercises
Exercise 1: He standard deviation
What standard deviation does He initialization use for a ReLU layer with 1024 inputs?
Answer
About .
Solution
.
Exercise 2: Xavier-uniform bound
Find the Xavier-uniform bound for a layer.
Answer
.
Solution
.
Exercise 3: Symmetry stays (code)
Train a 2-unit hidden layer from identical initial weights for 100 steps and check that the two units remain identical.
Answer
They stay exactly equal.
Solution
import numpy as np
rng = np.random.default_rng(2)
X = rng.normal(size=(20, 3)); y = rng.normal(size=20)
W1 = np.full((2, 3), 0.1); w2 = np.full(2, 0.1)
for _ in range(100):
H = np.tanh(X @ W1.T); r = H @ w2 - y
gw2 = H.T @ r / 20; gW1 = ((np.outer(r, w2) * (1 - H**2)).T @ X) / 20
W1 -= 0.1 * gW1; w2 -= 0.1 * gw2
print(np.allclose(W1[0], W1[1]), np.isclose(w2[0], w2[1]))True True
Test yourself
Why can't all weights be initialized to the same value?
- It would overflow
- All units in a layer would compute and learn the same thing
- The loss would be zero
- Biases would explode
He initialization for ReLU layers uses weight variance…
What does variance-preserving initialization aim to keep roughly constant across layers?
- The number of parameters
- The scale of activations and gradients
- The learning rate
- The loss