TExcelTAD
Home › Math for Deep Learning & LLMs › Weight Initialization

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 ai=∑j=1ninWijxja_i = \sum_{j=1}^{n_{\text{in}}} W_{ij}x_j with independent, zero-mean weights and inputs,

Var⁡(ai)=ninVar⁡(W) E[xj2]\operatorname{Var}(a_i) = n_{\text{in}}\operatorname{Var}(W)\,\mathbb{E}[x_j^2]

To keep Var⁡(a)=E[x2]\operatorname{Var}(a) = \mathbb{E}[x^2] we need Var⁡(W)=1/nin\operatorname{Var}(W) = 1/n_{\text{in}}. The activation adjusts the picture:

  • tanh or linear (Xavier/Glorot): tanh⁡\tanh is close to the identity near 0, giving Var⁡(W)=1nin\operatorname{Var}(W) = \frac{1}{n_{\text{in}}}; averaging with the backward-pass condition gives the usual 2nin+nout\frac{2}{n_{\text{in}} + n_{\text{out}}}.
  • ReLU (He/Kaiming): ReLU zeroes half its inputs, so E[ReLU⁡(a)2]=12Var⁡(a)\mathbb{E}[\operatorname{ReLU}(a)^2] = \frac{1}{2}\operatorname{Var}(a); compensating needs Var⁡(W)=2nin\operatorname{Var}(W) = \frac{2}{n_{\text{in}}}.
python · try it yourself
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 10−1710^{-17} or explosion to 102310^{23}.

The backward pass

Gradients flow through WTW^T, so their variance is preserved when Var⁡(W)=1/nout\operatorname{Var}(W) = 1/n_{\text{out}} (times the activation factor). Xavier's 2nin+nout\frac{2}{n_{\text{in}} + n_{\text{out}}} compromises between the forward and backward conditions; He initialization picks one of them (fan_in mode by default).

python · try it yourself
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 [−r,r][-r, r] has variance r2/3r^2/3, so Xavier-uniform uses r=6/(nin+nout)r = \sqrt{6/(n_{\text{in}} + n_{\text{out}})}. 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 1/2L1/\sqrt{2L} for LL layers; other schemes (T-Fixup, DeepNet, μ\muP) 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.Linear defaults to a Kaiming-uniform variant with Var⁡(W)=13nin\operatorname{Var}(W) = \frac{1}{3n_{\text{in}}}.
  • Embedding tables are typically initialized N(0,0.022)\mathcal{N}(0, 0.02^2) in GPT-style models.
  • A healthy initial loss for KK classes is about ln⁡K\ln K (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 0.04420.0442.

Solution

2/1024=1/512≈0.0442\sqrt{2/1024} = \sqrt{1/512} \approx 0.0442.

Exercise 2: Xavier-uniform bound

Find the Xavier-uniform bound rr for a 256→128256 \to 128 layer.

Answer

r=0.125r = 0.125.

Solution

6/(256+128)=6/384=0.015625=0.125\sqrt{6/(256 + 128)} = \sqrt{6/384} = \sqrt{0.015625} = 0.125.

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
python · try it yourself
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?

  1. It would overflow
  2. All units in a layer would compute and learn the same thing
  3. The loss would be zero
  4. Biases would explode

He initialization for ReLU layers uses weight variance…

  1. 1/nin1/n_{\text{in}}
  2. 2/nin2/n_{\text{in}}
  3. 11
  4. 0.010.01

What does variance-preserving initialization aim to keep roughly constant across layers?

  1. The number of parameters
  2. The scale of activations and gradients
  3. The learning rate
  4. The loss