TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Weight Initialisation in Practice

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 ln⁡10\ln 10: 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 nn 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 h=f(Wx+b)h = f(Wx + b) with ninn_{\text{in}} inputs, the pre-activation variance is ninVar⁡(w)Var⁡(x)n_{\text{in}} \operatorname{Var}(w) \operatorname{Var}(x) (plus the bias variance). To keep the signal at the same scale from layer to layer you choose

Var⁡(w)=g2nin,g={1linear, sigmoid-like (Xavier/LeCun)2ReLU (He/Kaiming)5/3tanh (PyTorch’s gain)\operatorname{Var}(w) = \frac{g^2}{n_{\text{in}}}, \qquad g = \begin{cases} 1 & \text{linear, sigmoid-like (Xavier/LeCun)} \\ \sqrt{2} & \text{ReLU (He/Kaiming)} \\ 5/3 & \text{tanh (PyTorch's gain)} \end{cases}

Xavier (Glorot) uses the average fan 12(nin+nout)\tfrac{1}{2}(n_{\text{in}} + n_{\text{out}}) instead of ninn_{\text{in}}, a compromise between keeping the forward signal and the backward gradient at scale; for square layers the two agree. The constant gg is the gain: the factor that undoes the shrinking of the activation function. A uniform distribution U(−a,a)U(-a, a) has variance a2/3a^2/3, so the uniform version of any scheme uses the bound a=g3/nina = g\sqrt{3 / n_{\text{in}}}.

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 (∣h∣>0.99\lvert h \rvert > 0.99, where the derivative of tanh is below 0.02).

python · try it yourself
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, N(0,0.012)N(0, 0.01^2). Each layer multiplies the variance by 128⋅10−4=0.0128128 \cdot 10^{-4} = 0.0128 (half that for ReLU). After 30 layers the tanh signal is about 4×10−294 \times 10^{-29} and the ReLU one 5×10−345 \times 10^{-34}: numerically zero.
  • Too large, N(0,1)N(0, 1). With ReLU the signal grows by a factor of about 64=8\sqrt{64} = 8 per layer and reaches 9.4×10269.4 \times 10^{26}; in float32 (largest value about 3.4×10383.4 \times 10^{38}) 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 ±1\pm 1, 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: 9.53×10−69.53 \times 10^{-6} after 30 layers.
  • He (Var⁡(w)=2/nin\operatorname{Var}(w) = 2/n_{\text{in}}) 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 N(0,1)N(0, 1) 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 a=5a = \sqrt{5} the gain becomes 2/(1+5)=1/3\sqrt{2/(1 + 5)} = \sqrt{1/3}, so the bound is 1/3⋅3/nin=1/nin\sqrt{1/3} \cdot \sqrt{3/n_{\text{in}}} = 1/\sqrt{n_{\text{in}}}. In words: the weights are U(−1/nin,1/nin)U(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}}), variance 1/(3nin)1/(3 n_{\text{in}}), 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 1/(3nin)1/(3 n_{\text{in}}) do in a deep stack without normalisation? The same NumPy probe, 20 layers:

python · try it yourself
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 1/3n=0.05101/\sqrt{3n} = 0.0510, while He would be 0.125. Per layer the ReLU variance is multiplied by n⋅13n⋅12=16n \cdot \frac{1}{3n} \cdot \frac{1}{2} = \frac{1}{6}, so after 20 layers the signal is 1.19×10−81.19 \times 10^{-8}; tanh ends at 1.21×10−51.21 \times 10^{-5}. 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) U(−a,a)U(-a, a), a=g6/(nin+nout)a = g\sqrt{6/(n_{\text{in}} + n_{\text{out}})}
xavier_normal_(w, gain=1) N(0,σ2)N(0, \sigma^2), σ=g2/(nin+nout)\sigma = g\sqrt{2/(n_{\text{in}} + n_{\text{out}})}
kaiming_uniform_(w, nonlinearity="relu") U(−a,a)U(-a, a), a=g3/nina = g\sqrt{3/n_{\text{in}}} (mode="fan_out" uses noutn_{\text{out}})
kaiming_normal_(w, nonlinearity="relu") N(0,σ2)N(0, \sigma^2), σ=g/nin\sigma = g/\sqrt{n_{\text{in}}}
orthogonal_(w, gain=1) a random orthogonal matrix times gg
zeros_, ones_, constant_(w, c), normal_(w, 0, s), trunc_normal_(w, std=s) the obvious ones

calculate_gain(name) returns gg. The usual pattern is a function applied to every submodule with model.apply, which visits modules recursively:

python · try it yourself
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 =1/256= 1/\sqrt{256}, the standard deviation 0.0360 against 1/768=0.03611/\sqrt{768} = 0.0361, 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, 2\sqrt{2} 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 [0,1][0, 1]), 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):

python · try it yourself
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, ln⁡10≈2.303\ln 10 \approx 2.303, 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 π\pi, set the logit bias to ln⁡(π/(1−π))\ln(\pi / (1 - \pi)), 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 ln⁡K\ln K for KK classes: a useful sanity check, see Debugging a network.
  • Residual branches. In a block y=x+F(x)y = x + F(x), initialise the last layer of FF (or the scale γ\gamma 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 1/N1/\sqrt{N} for NN 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.Embedding draws N(0,1)N(0, 1), which is large next to the other layers; transformer code often re-initialises it with standard deviation 0.02.

Pitfalls

  • Calling init on a module instead of its tensor. nn.init.kaiming_normal_(model) fails; pass layer.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 replacing layer.weight with a new tensor is not).
  • Forgetting torch.no_grad() in hand-written init. layer.weight *= 0.1 on a parameter raises an error; nn.init functions do the no-grad part for you.
  • Using fan_out by accident. For nn.Linear, mode="fan_in" (the default) preserves the forward signal; fan_out preserves 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 ln⁡K\ln K 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

  1. In the first table, why does tanh with N(0,1)N(0, 1) 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 −1-1 or +1+1. A variable that is ±1\pm 1 with equal probability has standard deviation 1, so the statistic looks fine, but 81 % of the units are saturated and their derivative 1−tanh⁡21 - \tanh^2 is close to 0: almost no gradient flows back.

  1. Compute the bound of PyTorch's default uniform weights for nn.Linear(64, 10) and the bound He-uniform would use.
Answer

Default: 1/64=0.1251/\sqrt{64} = 0.125. He-uniform: 2⋅3/64=6/64≈0.306\sqrt{2} \cdot \sqrt{3/64} = \sqrt{6/64} \approx 0.306. The variances are 0.1252/3≈0.00520.125^2/3 \approx 0.0052 and 2/64≈0.0312/64 \approx 0.031, a factor of 6 apart.

  1. Write an init function for a model with nn.Linear and nn.Embedding layers: He-normal for linear weights, zero biases, N(0,0.022)N(0, 0.02^2) for embeddings.
Answer
python
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)
  1. A binary classifier has 2 % positives. What should the initial output bias be, and what is the initial loss with it?
Answer

b=ln⁡(0.02/0.98)≈−3.89b = \ln(0.02 / 0.98) \approx -3.89, so every prediction starts at p=0.02p = 0.02. The initial binary cross-entropy is the entropy of the labels, −0.02ln⁡0.02−0.98ln⁡0.98≈0.098-0.02 \ln 0.02 - 0.98 \ln 0.98 \approx 0.098, instead of ln⁡2≈0.693\ln 2 \approx 0.693 with b=0b = 0.

Test yourself

What distribution does PyTorch's nn.Linear(n_in, n_out) use for its weights by default?

  1. N(0,2/nin)N(0, 2/n_{\text{in}}) (He normal)
  2. U(−1/nin,1/nin)U(-1/\sqrt{n_{\text{in}}}, 1/\sqrt{n_{\text{in}}})
  3. All zeros
  4. N(0,1)N(0, 1)

In the 30-layer probe, which initialisation kept ReLU activations at order 1 through all layers?

  1. Xavier
  2. N(0,1)N(0, 1)
  3. He, Var⁡(w)=2/nin\operatorname{Var}(w) = 2/n_{\text{in}}
  4. N(0,0.012)N(0, 0.01^2)

A tanh network's activations have standard deviation 0.96 at layer 30. What else should you check before concluding the initialisation is fine?

  1. Nothing, 0.96 is ideal
  2. The share of saturated units, where tanh's derivative is near zero
  3. The bias of the output layer
  4. The learning rate

Why initialise the last layer of a residual branch FF to zero?

  1. To save memory
  2. So every block starts as the identity y=xy = x and the deep network starts as a shallow one
  3. To make the gradients exactly zero
  4. 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?

  1. It is overfitting
  2. It predicts the uniform distribution: ln⁡10≈2.303\ln 10 \approx 2.303, so it has learned nothing
  3. The learning rate is slightly too low
  4. The labels are noisy