Deep learning in practice · lesson 6 of 13
Parts in this lesson
Ann.init.kaiming_normal_(m.weight, nonlinearity="relu")He initialisation: standard deviation √(2 / n_in)
Bnn.init.xavier_normal_(m.weight)Xavier initialisation: standard deviation √(2 / (n_in + n_out))
Cnn.init.zeros_(m.bias)biases can start at 0; it's the weights that must differ

Initialisation

Last updated

Before the first step, every weight needs a starting value, and in a deep network the choice decides whether training can start at all. Too small and the signal fades layer by layer; too large and it grows until it overflows. This lesson works out the right size from one line of variance arithmetic, and checks it on a 20-layer network: Xavier initialisation for tanh and sigmoid, He initialisation for ReLU.

By the end of this lesson you can

  • Say how the size of the weights changes the size of the signal through each layer
  • Work out the He initialisation for ReLU from the variance of a sum
  • Choose Xavier or He initialisation, and set it in PyTorch

Too small, too large

Lesson 6.5 showed that the weights can't all start equal: identical units get identical gradients and stay identical forever. So they start random. But random how big?

Each unit adds up its inputs times its weights, z=∑i=1nwixi. If the weights and inputs are independent, with mean 0, the variance of a sum is the sum of the variances:

Var⁡(z)=nVar⁡(w)Var⁡(x)

In words: with n inputs, the output's spread is the input's spread times nVar⁡(w). If that factor is 2, each layer doubles the variance; after 20 layers it's a million times bigger. If it's 12, it's a million times smaller. Only a factor of exactly 1 keeps the signal the same size all the way up, and the same factor applies to the gradients on their way back down, which is lesson 7.5's problem seen from the other side.

This script sends 1,000 random inputs, each number about size 1, through 20 ReLU layers of 256 units, and prints the typical size of each layer's outputs for four ways to start the weights:

"""How big the activations are in each layer of a 20-layer ReLU network, for four ways to start the weights."""
import math

import torch
from torch import nn

torch.manual_seed(0)
x = torch.randn(1000, 256)                       # 1,000 inputs of 256 numbers, each about size 1
inits = {
    "PyTorch default": lambda w: None,           # what nn.Linear does on its own
    "N(0, 1)": lambda w: nn.init.normal_(w, 0, 1),
    "Xavier": lambda w: nn.init.xavier_normal_(w),
    "He": lambda w: nn.init.kaiming_normal_(w, nonlinearity="relu"),
}
for name, init in inits.items():
    torch.manual_seed(1)
    h, sizes = x, []
    for layer in range(20):
        lin = nn.Linear(256, 256, bias=False)
        init(lin.weight)
        h = torch.relu(lin(h))
        sizes.append(h.double().pow(2).mean().sqrt().item())  # typical size of an output (in float64, so the sum of squares fits)
    print(f"{name}: activation size in layers 1 to 20")
    print("  " + " ".join(f"{s:.1e}" for s in sizes))
print(f"He's standard deviation for 256 inputs: sqrt(2/256) = {math.sqrt(2 / 256):.4f}")
Terminal, in ml-local/7-6
(.venv) $ python activations.py
PyTorch default: activation size in layers 1 to 20
  4.1e-01 1.7e-01 6.9e-02 3.0e-02 1.2e-02 4.8e-03 2.0e-03 9.3e-04 4.0e-04 1.6e-04 6.4e-05 2.5e-05 9.3e-06 4.0e-06 1.5e-06 6.0e-07 2.4e-07 1.0e-07 3.6e-08 1.3e-08
N(0, 1): activation size in layers 1 to 20
  1.1e+01 1.3e+02 1.5e+03 1.6e+04 1.7e+05 2.1e+06 2.4e+07 2.6e+08 3.0e+09 3.3e+10 3.8e+11 4.1e+12 4.6e+13 4.5e+14 5.0e+15 5.0e+16 5.2e+17 6.3e+18 7.1e+19 8.0e+20
Xavier: activation size in layers 1 to 20
  7.1e-01 5.1e-01 3.6e-01 2.4e-01 1.6e-01 1.2e-01 8.9e-02 6.1e-02 4.3e-02 3.0e-02 2.2e-02 1.5e-02 1.0e-02 6.2e-03 4.4e-03 2.7e-03 1.8e-03 1.3e-03 9.4e-04 6.6e-04
He: activation size in layers 1 to 20
  1.0e+00 1.0e+00 1.0e+00 9.5e-01 9.3e-01 9.9e-01 1.0e+00 9.8e-01 9.8e-01 9.7e-01 9.8e-01 9.4e-01 9.2e-01 7.9e-01 7.9e-01 7.0e-01 6.4e-01 6.8e-01 6.8e-01 6.8e-01
He's standard deviation for 256 inputs: sqrt(2/256) = 0.0884
Signal through layersthe typical size of each layer's outputs, 20 ReLU layers, input size 1
10-910-610-31001031061091012101510181021the input's size15101520layerPyTorch defaultN(0, 1)XavierHe

Pick a starting method to follow its line. Only He keeps the signal near the input's size all the way up.

Two of them go badly wrong in opposite directions:

  • Weights from N(0,1), a standard normal, are far too big: 256 inputs each multiplied by about 1. The size grows about 11 times per layer, to 8×1020 by layer 20. In float32, which tops out near 3.4×1038, about 17 more layers would overflow to inf.
  • PyTorch's default for nn.Linear draws each weight uniformly between −1/n and 1/n. That's too small for ReLU: the size shrinks to about 0.41 times per layer, down to 1.3×10−8. This is why lesson 7.5's ReLU network still lost a factor of 500,000 in its gradients.

Xavier initialisation

To make the factor 1, choose Var⁡(w)=1/nin. The backward pass sends gradients through the same weights the other way, where nout counts instead, so Glorot and Bengio (2010) split the difference:

Var⁡(w)=2nin+nout

In words: average the number of inputs and outputs, and make the variance one over that. This is Xavier initialisation (or Glorot, after Xavier Glorot), nn.init.xavier_normal_. With 256 in and 256 out it's 1/256.

It's right for tanh, and fine for sigmoid, which both behave like a straight line near 0. With ReLU, look at the figure: the size drops to about 0.71 of itself per layer, to 6.6×10−4 by layer 20. Something about ReLU costs a factor of 2 every layer.

He initialisation for ReLU

The missing factor is the half of the units that ReLU switches off. If z is spread evenly around 0, ReLU zeroes the negative half and keeps the positive half, so the mean square of its output is half the variance of its input:

𝔼[ReLU⁡(z)2]=12Var⁡(z)

The next layer then multiplies by ninVar⁡(w), so the factor per layer is 12ninVar⁡(w). Setting it to 1 gives He initialisation (or Kaiming, after Kaiming He):

Var⁡(w)=2nin,standard deviation 2nin

For 256 inputs, the script's last line works it out: 2/256=0.0884. In PyTorch, nn.init.kaiming_normal_(w, nonlinearity="relu").

In the figure, He stays close to 1 all the way: still 0.98 at layer 11, and 0.68 at layer 20. The formula makes the factor exactly 1 on average; each real layer, with its 65,536 random weights, comes out a little above or below, and over 20 layers the wobbles add up to a drift of a third. That's harmless. The other methods are wrong by factors of a million or more.

The same arithmetic explains both failures in step 1: N(0,1) gives a factor of 12⋅256⋅1=128 in the mean square, which is 128≈11.3 in size; PyTorch's default has variance 1/(3n), giving 16, which is 0.41 in size. Both match the measured numbers.

To set it for a whole model, loop over its layers. Biases can start at zero: the weights already make the units different.

for m in model.modules():
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
        nn.init.zeros_(m.bias)

Wrong way: N(0, 1) in a deep ReLU network

"Random numbers from a standard normal" sounds like a sensible default, and it's what torch.randn gives you. Here it is in a 10-layer ReLU network on the digits, beside He:

"""The wrong way: a 10-layer ReLU network started with weights from N(0, 1)."""
import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

X, y = load_digits(return_X_y=True)
data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y))

for name in ("N(0, 1)", "He"):
    torch.manual_seed(0)
    layers = [nn.Linear(64, 64), nn.ReLU()]
    for _ in range(8):
        layers += [nn.Linear(64, 64), nn.ReLU()]
    model = nn.Sequential(*layers, nn.Linear(64, 10))
    for m in model:
        if isinstance(m, nn.Linear):
            if name == "N(0, 1)":
                nn.init.normal_(m.weight, 0, 1)
            else:
                nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
            nn.init.zeros_(m.bias)
    with torch.no_grad():                        # before any training: how big are the outputs?
        out = model(data.tensors[0][:32])
        first_loss = nn.functional.cross_entropy(out, data.tensors[1][:32]).item()
    print(f"{name:8} before training: outputs about {out.abs().mean().item():.1e}, loss {first_loss:.3g}")
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
    losses = []
    for epoch in range(5):
        total = 0.0
        for xb, yb in DataLoader(data, batch_size=32, shuffle=True):
            loss = nn.functional.cross_entropy(model(xb), yb)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            total += loss.item() * len(xb)
        losses.append(total / len(data))
    print(f"{name:8} loss in epochs 1 to 5: " + " ".join(f"{l:.3g}" for l in losses))
Terminal, in ml-local/7-6
(.venv) $ python normal_init.py
N(0, 1)  before training: outputs about 4.0e+07, loss 6.44e+07
N(0, 1)  loss in epochs 1 to 5: nan nan nan nan nan
He       before training: outputs about 1.2e+00, loss 3
He       loss in epochs 1 to 5: 1.54 0.609 0.608 0.2 0.277

With N(0,1), the outputs are about 40 million before training starts, and the first batch's loss is 64 million. (He's start gives outputs about 1.2 and a loss of 3, not far from the 2.3 of a uniform guess.) Softmax of numbers that size is all 0s and a single 1, the gradients are as huge as the loss, the first steps throw the weights out of float32's range, and once one nan appears every number computed from it is nan too: the average loss for epoch 1 is already nan. Nothing in the code is wrong, and nothing warns you; the loss simply never was a number.

The same network with He initialisation trains normally, from 1.54 to 0.2 in four epochs. The 0.277 in epoch 5 is the noise of mini-batches with momentum; it isn't a trend.

If the loss is nan in the very first epoch, check the starting weights (and the learning rate) before anything else. If you write weights by hand with torch.randn, scale them: torch.randn(n_out, n_in) * (2 / n_in) ** 0.5.

Check what you learned

A ReLU layer has 100 inputs. What standard deviation does He initialisation give its weights?
Why does Xavier initialisation shrink the signal in a ReLU network, when it keeps it steady with tanh?
A new deep ReLU network’s loss is nan in its first epoch. Its weights were made with torch.randn. What’s the likely cause?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning