Weight Initialisation in Practice
A 16-layer ReLU network on the Digits images, trained with plain SGD and momentum, sits at a training loss of 2.30 for 30 epochs, which is exactly : it predicts the uniform distribution and learns nothing. Change one line, the way the weights are drawn before training, and the same network reaches 95 % validation accuracy. Nothing else is different: same data, same optimiser, same learning rate, same seed.
The theory of why the scale of the initial weights matters (the variance of a sum of random products, the factor 2 for ReLU) is derived in Initialisation and applied to a 10-layer network in Parameters and Initialisation. This lesson is about practice: what goes wrong in a 30-layer stack with each common choice, what PyTorch actually does when you write nn.Linear(256, 128), how to override it, and the special cases (biases, output layers, residual branches) where the usual rule is not the best one.
The rule in one line
For a layer with inputs, the pre-activation variance is (plus the bias variance). To keep the signal at the same scale from layer to layer you choose
Xavier (Glorot) uses the average fan instead of , a compromise between keeping the forward signal and the backward gradient at scale; for square layers the two agree. The constant is the gain: the factor that undoes the shrinking of the activation function. A uniform distribution has variance , so the uniform version of any scheme uses the bound .
Thirty layers, five choices
The experiment: a batch of 256 standard-normal inputs goes through 30 square layers with 128 units, no biases, once with tanh and once with ReLU. For each initialisation it prints the standard deviation of the activations after layers 1, 10, 20 and 30, and for tanh the share of units that are saturated (, where the derivative of tanh is below 0.02).
import numpy as np
rng = np.random.default_rng(0)
n, depth = 128, 30
x0 = rng.normal(0, 1, (256, n)) # a batch of 256 inputs
schemes = {
"zeros": lambda: np.zeros((n, n)),
"N(0, 0.01)": lambda: rng.normal(0, 0.01, (n, n)),
"N(0, 1)": lambda: rng.normal(0, 1.0, (n, n)),
"Xavier": lambda: rng.normal(0, np.sqrt(2 / (n + n)), (n, n)),
"He": lambda: rng.normal(0, np.sqrt(2 / n), (n, n)),
}
acts = {"tanh": np.tanh, "relu": lambda z: np.maximum(z, 0)}
for act_name, f in acts.items():
head = f"{act_name}: std after layer 1, 10, 20, 30"
print(head + (" | share with |h| > 0.99 at 30" if act_name == "tanh" else ""))
for name, make in schemes.items():
h, stds = x0, []
for layer in range(1, depth + 1):
h = f(h @ make())
if layer in (1, 10, 20, 30):
stds.append(float(h.std()))
line = f" {name:11s}" + "".join(f"{s:10.3g}" for s in stds)
if act_name == "tanh":
line += f" | {float((np.abs(h) > 0.99).mean()):.2f}"
print(line)tanh: std after layer 1, 10, 20, 30 | share with |h| > 0.99 at 30
zeros 0 0 0 0 | 0.00
N(0, 0.01) 0.113 3.52e-10 1.18e-19 3.73e-29 | 0.00
N(0, 1) 0.965 0.964 0.962 0.963 | 0.81
Xavier 0.629 0.229 0.153 0.14 | 0.00
He 0.72 0.558 0.563 0.564 | 0.00
relu: std after layer 1, 10, 20, 30
zeros 0 0 0 0
N(0, 0.01) 0.0663 6.42e-12 6.29e-23 5.16e-34
N(0, 1) 6.68 7.9e+08 8.47e+17 9.4e+26
Xavier 0.584 0.0166 0.00049 9.53e-06
He 0.814 0.63 0.779 0.812
Read the table row by row:
- Zeros. Every activation is exactly 0, at every depth. In a tanh or ReLU network the gradient of every hidden weight is then 0 too, and even with a nonzero gradient all units of a layer would stay identical, the symmetry problem shown in Parameters and Initialisation. Zeros are fine for biases, never for the weights of hidden layers.
- Too small, . Each layer multiplies the variance by (half that for ReLU). After 30 layers the tanh signal is about and the ReLU one : numerically zero.
- Too large, . With ReLU the signal grows by a factor of about per layer and reaches ; in float32 (largest value about ) about a dozen more layers would overflow to
inf. With tanh the activations cannot grow, so the failure is quieter: the standard deviation is a healthy-looking 0.963, but 81 % of the units sit at , where the gradient is almost zero. - Xavier is right for tanh in the linear region, but tanh is slightly contracting, so the signal still decays slowly (0.629 to 0.14). With ReLU it loses half the variance per layer: after 30 layers.
- He () keeps ReLU activations between 0.63 and 0.81 for all 30 layers, and with tanh it settles at about 0.56 without saturation. The ReLU row wanders a little because the width is finite: each layer multiplies the norm by a random factor close to 1, and those factors do a small random walk.
Note: a stable standard deviation is necessary, not sufficient. The tanh row with shows that a constant scale can hide saturated units. When you probe a real network, look at the share of dead ReLUs or saturated units too.
What PyTorch does by default
nn.Linear(n_in, n_out) calls kaiming_uniform_(weight, a=math.sqrt(5)). The parameter a is the negative slope of a leaky ReLU, and with the gain becomes , so the bound is . In words: the weights are , variance , which is a third of LeCun's and a sixth of He's. The bias is drawn from the same interval. This is a historical choice inherited from Lua Torch, whose nn.Linear drew from the same interval; the comment in reset_parameters states the equivalence and points to the discussion in PyTorch issue #57109.
What does a variance of do in a deep stack without normalisation? The same NumPy probe, 20 layers:
import numpy as np
rng = np.random.default_rng(0)
n, depth = 128, 20
x0 = rng.normal(0, 1, (256, n))
bound = 1 / np.sqrt(n) # PyTorch's nn.Linear default: U(-1/sqrt(n), 1/sqrt(n))
W = rng.uniform(-bound, bound, (n, n))
print(f"default weight std {W.std():.5f} 1/sqrt(3n) = {1 / np.sqrt(3 * n):.5f} He std = {np.sqrt(2 / n):.5f}")
for act_name, f, gain in (("tanh", np.tanh, 5 / 3), ("relu", lambda z: np.maximum(z, 0), np.sqrt(2))):
for name, std in (("default", 1 / np.sqrt(3 * n)), ("gain-corrected", gain / np.sqrt(n))):
h = x0
for _ in range(depth):
h = f(h @ rng.normal(0, std, (n, n)))
print(f"{act_name:4s} {name:15s} std after {depth} layers: {h.std():.3g}")default weight std 0.05110 1/sqrt(3n) = 0.05103 He std = 0.12500
tanh default std after 20 layers: 1.21e-05
tanh gain-corrected std after 20 layers: 0.656
relu default std after 20 layers: 1.19e-08
relu gain-corrected std after 20 layers: 0.429
The default weights have standard deviation 0.0511, matching , while He would be 0.125. Per layer the ReLU variance is multiplied by , so after 20 layers the signal is ; tanh ends at . Multiply the standard deviation by the right gain and both stay at order 1 (0.656 and 0.429).
In shallow networks, and in networks with normalisation layers and residual connections (almost every modern architecture), the default is harmless, because the normalisation rescales whatever the weights produce. For a deep plain MLP, set the initialisation yourself.
Initialising a PyTorch model
torch.nn.init has one function per scheme. They work in place (the trailing underscore) and take the tensor to fill:
| Function | Distribution |
|---|---|
xavier_uniform_(w, gain=1) |
, |
xavier_normal_(w, gain=1) |
, |
kaiming_uniform_(w, nonlinearity="relu") |
, (mode="fan_out" uses ) |
kaiming_normal_(w, nonlinearity="relu") |
, |
orthogonal_(w, gain=1) |
a random orthogonal matrix times |
zeros_, ones_, constant_(w, c), normal_(w, 0, s), trunc_normal_(w, std=s) |
the obvious ones |
calculate_gain(name) returns . The usual pattern is a function applied to every submodule with model.apply, which visits modules recursively:
import math
import torch
from torch import nn
torch.manual_seed(0)
lin = nn.Linear(256, 128)
w, b = lin.weight.detach(), lin.bias.detach()
print("weight shape", tuple(w.shape), " fan_in", lin.in_features)
print(f"max |w| {w.abs().max().item():.4f} 1/sqrt(fan_in) {1 / math.sqrt(256):.4f}")
print(f"std(w) {w.std().item():.4f} 1/sqrt(3 fan_in) {1 / math.sqrt(3 * 256):.4f}")
print(f"max |b| {b.abs().max().item():.4f} (bias also U(-1/sqrt(fan_in), 1/sqrt(fan_in)))")
print("gains:", {a: round(nn.init.calculate_gain(a), 4) for a in ("linear", "tanh", "relu", "selu")})
w2 = torch.empty(128, 256)
nn.init.kaiming_normal_(w2, nonlinearity="relu") # std = sqrt(2 / fan_in), fan_in = 256
print(f"kaiming_normal_ std {w2.std().item():.4f} sqrt(2/256) {math.sqrt(2 / 256):.4f}")
nn.init.xavier_uniform_(w2) # bound = sqrt(6 / (fan_in + fan_out))
print(f"xavier_uniform_ max {w2.abs().max().item():.4f} sqrt(6/384) {math.sqrt(6 / 384):.4f}")
def make(depth=20, width=256):
layers = []
for _ in range(depth):
layers += [nn.Linear(width, width), nn.ReLU()]
return nn.Sequential(*layers)
def he_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
nn.init.zeros_(m.bias)
x = torch.randn(512, 256)
for name in ("default", "kaiming"):
torch.manual_seed(0)
net = make()
if name == "kaiming":
net.apply(he_init) # visits every submodule
with torch.no_grad():
h, stds = x, []
for i, layer in enumerate(net):
h = layer(h)
if isinstance(layer, nn.ReLU) and (i + 1) // 2 in (1, 10, 20):
stds.append(f"{h.std().item():.3g}")
print(f"{name:8s} ReLU std after layer 1, 10, 20: {stds}")weight shape (128, 256) fan_in 256
max |w| 0.0625 1/sqrt(fan_in) 0.0625
std(w) 0.0360 1/sqrt(3 fan_in) 0.0361
max |b| 0.0615 (bias also U(-1/sqrt(fan_in), 1/sqrt(fan_in)))
gains: {'linear': 1, 'tanh': 1.6667, 'relu': 1.4142, 'selu': 0.75}
kaiming_normal_ std 0.0880 sqrt(2/256) 0.0884
xavier_uniform_ max 0.1250 sqrt(6/384) 0.1250
default ReLU std after layer 1, 10, 20: ['0.336', '0.0227', '0.0219']
kaiming ReLU std after layer 1, 10, 20: ['0.824', '0.682', '0.615']
The recording (PyTorch 2.14.1 on CPU) confirms the arithmetic: the largest default weight is 0.0625 , the standard deviation 0.0360 against , and the bias is bounded by the same 0.0625. Note the weight's shape: PyTorch stores (out_features, in_features), and the fan-in is the second dimension, so nn.init computes it correctly from the tensor. Gains are 5/3 for tanh, for ReLU and 3/4 for SELU.
In the 20-layer probe the default network behaves differently from the NumPy one: its ReLU activations drop from 0.336 to 0.0227 at layer 10 and then stop shrinking (0.0219 at layer 20). That floor is the bias. With weights this small the input's contribution dies out, and what remains after a few layers is mostly the random biases, pushed through the network. The output no longer depends much on the input, which is just as bad for learning. He initialisation with zero biases keeps 0.824, 0.682, 0.615.
The training experiment
Now the experiment from the first paragraph. The Digits split of this course (1077 training, 360 validation images, 64 pixels scaled to ), a 16-layer ReLU MLP of width 64, SGD with learning rate 0.01, momentum 0.9 and batch size 64, 30 epochs, evaluated on the validation set (the test set stays untouched):
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
X_tr, X_va = (torch.tensor(a, dtype=torch.float32) for a in (X_tr, X_va))
y_tr, y_va = (torch.tensor(a) for a in (y_tr, y_va))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("device:", device)
def make(depth=16, width=64):
layers, d = [], 64
for _ in range(depth):
layers += [nn.Linear(d, width), nn.ReLU()]
d = width
return nn.Sequential(*layers, nn.Linear(width, 10))
def he_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
nn.init.zeros_(m.bias)
for name in ("default", "kaiming"):
torch.manual_seed(0)
model = make()
if name == "kaiming":
model.apply(he_init)
model.to(device)
opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
loss_fn = nn.CrossEntropyLoss()
g = torch.Generator().manual_seed(0)
for epoch in range(1, 31):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(64):
loss = loss_fn(model(X_tr[idx].to(device)), y_tr[idx].to(device))
opt.zero_grad(); loss.backward(); opt.step()
if epoch in (1, 5, 10, 30):
model.eval()
with torch.no_grad():
tr_loss = loss_fn(model(X_tr.to(device)), y_tr.to(device)).item()
acc = (model(X_va.to(device)).argmax(1).cpu() == y_va).float().mean().item()
print(f"{name:8s} epoch {epoch:2d} train loss {tr_loss:.3f} val acc {acc:.3f}")device: cpu
default epoch 1 train loss 2.305 val acc 0.097
default epoch 5 train loss 2.303 val acc 0.097
default epoch 10 train loss 2.303 val acc 0.100
default epoch 30 train loss 2.302 val acc 0.103
kaiming epoch 1 train loss 1.993 val acc 0.253
kaiming epoch 5 train loss 0.833 val acc 0.628
kaiming epoch 10 train loss 0.493 val acc 0.808
kaiming epoch 30 train loss 0.020 val acc 0.953
With the default initialisation the training loss stays at 2.302 to 2.305, , and the validation accuracy at chance (0.097 to 0.103) for all 30 epochs: the logits are almost constant, so the gradients reaching the first layers are tiny. With He initialisation the same network is at 0.808 after 10 epochs and 0.953 after 30, with a training loss of 0.020. Adding a normalisation layer or residual connections would also rescue the default, which is the subject of the next lessons.
Special cases
- Biases. Zero is the standard choice; the random weights already break the symmetry. PyTorch's uniform bias is not harmful in shallow nets, but in deep plain stacks it can dominate the signal, as the probe showed.
- The output layer. Initialise its bias to the answer of a model that knows nothing. For a classifier with a rare positive class of frequency , set the logit bias to , so the first losses are not dominated by confidently wrong predictions (the trick used with focal loss). For regression, set it to the mean of the training targets.
- Small output weights. Scaling the last layer's weights down (or zeroing them) makes the initial logits near 0, so the first loss is close to for classes: a useful sanity check, see Debugging a network.
- Residual branches. In a block , initialise the last layer of (or the scale of its last normalisation layer) to zero. Then every block starts as the identity, and a 100-block network starts as a shallow one; torchvision's ResNet offers this as
zero_init_residual=True. Transformers do a softer version: GPT-2 scales the initial weights of the residual output projections by for residual layers. More in Residual Connections. - Recurrent layers. Orthogonal recurrent matrices keep the norm of the hidden state over many steps, and LSTM forget-gate biases are often set to 1 so the cell remembers by default (LSTM and GRU).
- Embeddings.
nn.Embeddingdraws , which is large next to the other layers; transformer code often re-initialises it with standard deviation 0.02.
Pitfalls
- Calling
initon a module instead of its tensor.nn.init.kaiming_normal_(model)fails; passlayer.weight. - Initialising inside
forward. It runs every step and wipes training. Initialise once, after constructing the model and before creating the optimiser (the optimiser keeps references, so in-place init after it is fine, but replacinglayer.weightwith a new tensor is not). - Forgetting
torch.no_grad()in hand-written init.layer.weight *= 0.1on a parameter raises an error;nn.initfunctions do the no-grad part for you. - Using
fan_outby accident. Fornn.Linear,mode="fan_in"(the default) preserves the forward signal;fan_outpreserves the backward gradient. For square layers they agree, for a 784-to-64 layer they differ by a factor of 12 in variance. - Blaming the optimiser. A loss stuck at exactly from the first epoch is the signature of a dead or collapsed network, usually initialisation or a bug, not a learning rate that is a little off.
Practice
- In the first table, why does tanh with show a standard deviation near 0.96 even though the network is useless?
Answer
The pre-activations have a variance of about 128, so tanh maps almost every unit to or . A variable that is with equal probability has standard deviation 1, so the statistic looks fine, but 81 % of the units are saturated and their derivative is close to 0: almost no gradient flows back.
- Compute the bound of PyTorch's default uniform weights for
nn.Linear(64, 10)and the bound He-uniform would use.
Answer
Default: . He-uniform: . The variances are and , a factor of 6 apart.
- Write an init function for a model with
nn.Linearandnn.Embeddinglayers: He-normal for linear weights, zero biases, for embeddings.
Answer
def init_weights(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
model.apply(init_weights)- A binary classifier has 2 % positives. What should the initial output bias be, and what is the initial loss with it?
Answer
, so every prediction starts at . The initial binary cross-entropy is the entropy of the labels, , instead of with .
Test yourself
What distribution does PyTorch's nn.Linear(n_in, n_out) use for its weights by default?
- (He normal)
- All zeros
In the 30-layer probe, which initialisation kept ReLU activations at order 1 through all layers?
- Xavier
- He,
A tanh network's activations have standard deviation 0.96 at layer 30. What else should you check before concluding the initialisation is fine?
- Nothing, 0.96 is ideal
- The share of saturated units, where tanh's derivative is near zero
- The bias of the output layer
- The learning rate
Why initialise the last layer of a residual branch to zero?
- To save memory
- So every block starts as the identity and the deep network starts as a shallow one
- To make the gradients exactly zero
- Because ReLU requires it
A 16-layer ReLU MLP with the default init has a training loss of 2.302 for 30 epochs on a 10-class problem. What does that number tell you?
- It is overfitting
- It predicts the uniform distribution: , so it has learned nothing
- The learning rate is slightly too low
- The labels are noisy