Before training starts, every weight needs a value. Does the choice matter? Take a network with 10 layers of 64 ReLU units and feed it the same 128 made-up inputs. Draw the weights from a normal distribution with standard deviation , and the standard deviation of the last layer’s output is : nothing is left. With standard deviation it is : the numbers have exploded. With standard deviation it is , close to the size of the input. Same network, same data, and only the size of the starting weights changed.
This lesson explains why, and gives the rules (named after LeCun, Glorot and Bengio, He and others) that choose a good size from the shape of each layer.
First idea: start everything at zero?
The loss is smallest when the weights are good, and zero looks like a neutral place to begin. It fails, and the reason is a symmetry.
Take a tiny network: two inputs, two tanh hidden units, one linear output unit that has a bias, also 0. The input is and the target is . The loss is and every hidden unit has bias 0. Give every weight the same value :
- Both hidden units see , so both output .
- The output is , and the error is .
- The gradient of the loss with respect to each output weight is : the same for both units.
- The gradient with respect to the incoming weights is for both units.
With a learning rate of , both units move by the same amount: each incoming weight vector becomes and each output weight . They are still equal, so the next gradients are equal again. By induction, the two units stay identical at every step. Two hidden units behave as one: the layer’s width is wasted.
All zeros is the extreme case, and it is worse. With every weight 0, the hidden outputs are 0, so the gradient for each output weight (which is the error times the hidden output) is 0. The output weights are 0, so the gradient for each incoming weight (which passes through them) is also 0. In this example only the output bias moves, from 0 to and then , while the hidden layer receives no gradient at any step. With tanh or ReLU, a hidden layer that starts at zero does not learn (with sigmoid the hidden outputs start at 0.5, but equal weights still keep the units identical). If instead the two units start with different incoming weights, such as and , their gradients differ: and , and they can specialise.
Running the code in NumPy gives each of these numbers.
Small random, large random: scale matters
So draw the weights from a random distribution with mean 0. Now the question is how wide. Two guesses come to mind: small, so the first steps are gentle, or large, so the units are different from each other. Both fail in a deep network, and the numbers in the opening paragraph show how.
A layer multiplies the size of the signal by a factor. Pick a standard deviation of for the weights of a layer with inputs. A sum of 64 terms, each about times an input of size 1, has a typical size of about (the terms partly cancel, so it grows like the square root, not like 64; P1.D8). Each layer shrinks the signal by about , and ten layers shrink it by . With standard deviation the factor per layer is about , and . ReLU also zeroes the negative half, which lowers the factor, so the measured figures in the opening paragraph are a little different ( and ), but the exponential pattern is the same.
The backward pass is the same story. The gradient travelling back through a layer is multiplied by (P4.8), so it also shrinks or grows by a factor per layer. A signal of size gives gradients too small to change anything, and a signal of size gives enormous updates. This is the problem of vanishing and exploding gradients (P4.16), and a bad starting scale causes it from the first step.
This is also the picture of repeated multiplication from P1.B12: applying a matrix over and over scales a vector by powers of its eigenvalues. A deep network does not reuse one matrix, but the lesson is the same: a factor a little below 1 vanishes, a factor a little above 1 explodes, and the factor has to be close to 1.
The variance rule
How close to 1 and how to get there? The key fact is the rule for the variance of a sum (P1.D4). A single unit computes
where is the number of inputs to the unit, called its fan-in (it is the of P1.D4). Suppose the weights are drawn independently of each other and of the inputs, all with mean and the same variance . Then:
- Each term has mean .
- Each term has variance , using because the mean is 0.
- The variance of a sum of independent terms is the sum of the variances, so
If the inputs also have mean 0, then and this is the of P1.D4. The version with is the one we need, because ReLU outputs are not centred on 0.
The example from P1.D4 shows the size of the effect. With inputs of variance 1 and weights of variance 1, the output variance is . With it is . A simulation of 20,000 such units gives and (the second code cell below).
LeCun: keep the variance steady
For a layer whose activation leaves the value alone, such as the identity, the next layer’s input is itself, so . Keeping the variance equal from layer to layer means :
This choice is often called LeCun initialization, after advice in LeCun and colleagues’ Efficient BackProp chapter (1998). For it is a standard deviation of .
He (Kaiming): ReLU removes half
ReLU sets every negative to 0. If is centred on 0 and symmetric, half of its values are negative, so half of the squared values vanish:
The simulation agrees: for with variance 1, and . Put this in the rule: . For the variance to stay steady, , which gives
This is He initialization, also called Kaiming initialization, from He, Zhang, Ren and Sun’s 2015 paper Delving Deep into Rectifiers (ICCV 2015), which treats ReLU-like activations. The LeCun rule is too small by a factor of 2 in variance for ReLU, and the error compounds: every layer loses half the variance, so after 30 ReLU layers of 256 units the second moment of the signal falls to about of the input’s in theory, and the first code cell below prints an rms of for LeCun, whose square is .
Xavier (Glorot): balance forward and backward
The forward pass wants . The backward pass has its own condition. The gradient at a layer’s input is , and each of its entries sums over the units that the input feeds (the layer’s fan-out). If the activation has slope near 1, the same argument gives , which wants . When both cannot hold. Glorot and Bengio (Understanding the difficulty of training deep feedforward neural networks, AISTATS 2010) proposed a compromise:
This is Xavier or Glorot initialization (it is with the average of fan-in and fan-out). It assumes the activation is roughly linear with slope 1 near 0, as tanh is. When it reduces to , the same as LeCun’s.
Normal or uniform?
All these rules fix a variance. Any distribution with mean 0 and that variance has the same effect on the first-order argument, so each rule comes in a normal and a uniform form. A uniform distribution on has variance (P1.D3). To get a target variance you need . For Xavier, , so
which is the limit Glorot and Bengio wrote down. For He with the uniform form, .
Fan-in or fan-out?
Which count to use for a layer with inputs and outputs? Here are the numbers for that layer:
- LeCun: variance , standard deviation .
- Xavier: variance , standard deviation , uniform limit .
- He, fan-in mode: variance , standard deviation .
- He, fan-out mode: variance , standard deviation .
Fan-in mode keeps the forward signal steady, and fan-out mode keeps the backward gradient steady. PyTorch’s kaiming_normal_ uses fan-in mode unless you pass mode="fan_out". For a layer that is not square the two modes differ, but for the equal widths of the widget below they coincide. In a convolution layer (Part 5) the fan-in also counts the kernel’s positions.
See it: every layer, every rule
The widget runs a stack of 10 layers of 64 units, forward and backward, on 128 made-up Gaussian inputs, with the starting weights drawn from a seeded random generator in your browser. The small histograms show the activations of each layer. The plot shows the standard deviation of the activations (blue) and of the gradient (orange) layer by layer, on a log scale. The backward gradient starts as random numbers at the last layer, a stand-in for the loss, and goes back to layer 1. The widget shows the standard deviation, and after a ReLU the mean is above 0, so the standard deviation of a steady ReLU stack settles near in theory (the 64-unit stacks fluctuate around that), not at 1, even though the second moment stays 1.
What the default seed shows (running the same algorithm in NumPy reproduces every number):
- All zero. The activations have no spread: they are 0 in every layer (0.5 for sigmoid, so the standard deviation shown is 0). With tanh or sigmoid the gradient is 0 in all layers but the last, and with ReLU it is 0 everywhere (the ReLU slope at 0 is taken as 0, as in P4.4). The hidden layers do not move.
- Small (standard deviation 0.01). With ReLU, the activations fall from in layer 1 to in layer 10. The histograms are a single bar at 0 and the gradient at layer 1 is . With tanh the activations fall from in layer 1 to .
- Large (standard deviation 1). With ReLU the activations rise to and the gradient has standard deviation at layer 10 but at layer 1. With tanh the values cannot explode, so they saturate instead: about percent of the layer-10 activations are beyond , where the slope of tanh is almost 0, and the gradient is large and uneven (std at layer 10, growing to at layer 1).
- ReLU with LeCun versus He. LeCun leaves the activations at in layer 10, because half the variance is lost at every layer. He keeps them at , and the gradient at layer 1 is against at layer 10.
- tanh with Xavier. The activations settle near and the gradient at layer 1 is (against at layer 10). They shrink somewhat, because tanh is only linear for small , but they do not collapse. The Xavier (uniform) and LeCun (normal) variances are equal here, because , so the two behave alike.
- tanh with He. For these 64-unit layers He keeps the scale steadier than Xavier: the activations settle near (from in layer 1) and the gradient is at layer 1 against at layer 10. Tanh is only linear for small and flattens larger ones, so a slightly larger variance compensates (PyTorch’s recommended gain for tanh is , a variance times the linear case). Xavier is derived for an activation that is linear near zero, which is why it is the standard first choice, not a guarantee of the best scale.
- Sigmoid. With the variance-based rules (LeCun, Xavier, He, orthogonal) the gradient shrinks by a factor of about to per layer (for LeCun, at layer 1 against at layer 10). Small weights are far worse (about per layer), and the PyTorch default shrinks it by about per layer. Large weights shrink it least, only about over the stack, because the sigmoids saturate. A sigmoid’s slope is at most , and its output is centred on , not on 0, so the zero-mean assumption of the rule does not hold. No choice of weight variance in this list rescues a deep stack of sigmoids; this is part of why other activations replaced them in hidden layers (P4.4).
- PyTorch default. With ReLU the activations fall to about in layer 10, a factor of about per layer. See the section on defaults below.
- Orthogonal. With gain 1 and ReLU the scale matches LeCun’s (); with gain it gives , close to He’s . With tanh the results are close to those of LeCun and He at the same variance.
These numbers belong to one seed; draw new random weights to see that the pattern stays while the numbers move (the He stack ends between 0.74 and 1.5 over five seeds).
Orthogonal initialization
The rules above keep the scale correct on average. There is a sharper idea. An orthogonal matrix satisfies and keeps the length of every vector: (P1.B10). A chain of orthogonal layers therefore keeps the length of the signal exactly, forward, and its transpose keeps the length of the gradient backward.
Compare it with a Gaussian matrix of variance . Its squared length is preserved only on average. The second code cell uses 64 units and 50 layers: one starting vector ends up with length after the Gaussian chain, and exactly after the orthogonal chain. Over 1000 random starting vectors the mean of the squared length is , but the lengths themselves range widely: the middle 80 percent lie between and . The scale is correct on average and unreliable in a single run.
To draw a random orthogonal matrix, generate a Gaussian matrix and take its QR decomposition (an orthogonalisation, as in P1.B11); the Q factor is orthogonal. For a layer that is not square, the rows (or columns) are made orthonormal. Orthogonal initialization for deep networks was analysed by Saxe, McClelland and Ganguli (arXiv, December 2013; ICLR 2014), who studied deep linear networks and found that random orthogonal starting weights let learning time stop depending on depth.
An orthogonal matrix keeps length for a linear map. A nonlinear activation changes the scale, so a gain multiplies the matrix to compensate. PyTorch’s calculate_gain gives for ReLU (the factor that undoes the loss of half the variance), for tanh and for sigmoid and for no activation. In the widget the two orthogonal choices use gain 1 and gain .
Biases, defaults and the PyTorch functions
Biases are usually started at 0. Symmetry is not a problem for biases, because each unit’s incoming weights already differ (see the box below).
PyTorch’s nn.Linear draws its weights uniformly from . The source code calls kaiming_uniform_ with the argument , which works out to exactly this range. The variance is , which is one third of the LeCun value. Its biases are drawn from the same range, so they are not zero. With ReLU this default shrinks the signal at every layer (about per layer in the widget); in a shallow network that does no harm, and normalization layers (P4.19) can compensate, but a deep plain ReLU stack is better served by a deliberate choice.
The functions live in torch.nn.init. You pick the rule that matches the activation:
xavier_uniform_andxavier_normal_for tanh-like layers.kaiming_uniform_andkaiming_normal_for ReLU-like layers (passnonlinearity="relu"; they use fan-in mode by default).orthogonal_for an orthogonal matrix, withgain=fromcalculate_gain.zeros_for biases.
Transformers. Large language models often use a fixed small standard deviation for all the weight matrices, not a fan-in formula. In OpenAI’s released GPT-2 code, the attention and feed-forward weight matrices are drawn from a normal distribution with standard deviation and the biases start at 0. For a layer with 768 inputs, would be the LeCun value, so is smaller. The GPT-2 paper also mentions scaling the weights of residual layers by for residual layers at initialization (P4.20). Networks with normalization layers are less sensitive to the exact scale (P4.19), which is part of why a single constant is workable.
What normalization and residual connections change
A normalization layer re-scales the activations to a fixed size at each layer, so the scale of the forward signal no longer depends on the product of all the earlier factors; P4.19 shows how. A residual connection adds the layer’s input to its output, so the signal and the gradient also have a direct path that does not pass through the weights (P4.20). Both make very deep networks much less sensitive to the initial scale. Neither makes initialization irrelevant: the scale still affects the first steps and how large a learning rate is safe.
Random, seeded and different every run
The starting weights come from a pseudo-random generator. A fixed seed gives the same starting weights and, on the same software and hardware, the same run (P1.G3). A different seed gives a different start and, because the loss of a neural network is not convex (P1.F2), possibly a different final model (the New start button of P4.3 showed this). The button in the widget does the same: it draws new weights, and the pattern stays but the numbers change.
Depth: three ways to see it
Intuition
Think of copying a photograph ten times, each time on a photocopier whose contrast is set a little off. If the contrast is a little low, each copy is washed out, and after ten copies the page is blank. If it is a little high, each copy is darker and the page ends up black. Only a setting very close to correct keeps the picture. A layer’s weight scale is the photocopier’s contrast, and the variance rule is the correct setting. The analogy breaks in one way: a layer has to keep the signal informative (different units doing different things), not just the same size. That is the other job of random values, and the symmetry argument shows what happens without it.
Math
For a unit with independent zero-mean weights,
Requiring the variance of to stay constant from layer to layer gives:
- LeCun (linear activation): .
- He (ReLU): .
- Xavier (tanh-like): .
Uniform form: has variance , so . For Xavier, . Per layer, the signal’s standard deviation is multiplied by about for a linear unit and for ReLU; over layers this is raised to the power .
Code
import torch
import torch.nn as nn
torch.manual_seed(0)
layer = nn.Linear(256, 64) # weight shape (64, 256)
print("default std", round(layer.weight.std().item(), 4),
" max", round(layer.weight.abs().max().item(), 4))
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
print("He std", round(layer.weight.std().item(), 4))
nn.init.xavier_uniform_(layer.weight)
print("Xavier max", round(layer.weight.abs().max().item(), 4))
nn.init.orthogonal_(layer.weight) # rows orthonormal
print("orth W W^T = I:",
torch.allclose(layer.weight @ layer.weight.T,
torch.eye(64), atol=1e-5))
nn.init.zeros_(layer.bias)
print("gain tanh", round(nn.init.calculate_gain("tanh"), 4),
" relu", round(nn.init.calculate_gain("relu"), 4))Output from a local run with PyTorch 2.9.1:
default std 0.0361 max 0.0625
He std 0.0883
Xavier max 0.1369
orth W W^T = I: True
gain tanh 1.6667 relu 1.4142The default maximum is , as the source code says, and the He standard deviation is close to . To apply a rule to a whole model, write a function and use model.apply(fn).
Go deeper Where the variance argument is only approximate
The rule rests on assumptions: the terms of a sum are independent, the weights have mean 0, and the activation is close to linear or to ReLU. In a real network the inputs to a layer are not exactly independent, because they come from the same earlier layers, and the activations of tanh and sigmoid are only roughly linear near 0. The widget shows the effects: with Xavier and tanh the activation scale still drifts down from to across 10 layers, and for sigmoid no rule keeps the gradient steady. A width of 64 is also small, so the measured std fluctuates from layer to layer around its target (the He stack has values between and across its 10 layers). The rules give the right order of magnitude and remove the exponential trend; they are not a guarantee, and training can adapt afterwards.
Go deeper Why a Gaussian matrix is less reliable than an orthogonal one
A random Gaussian matrix with variance has singular values spread between 0 and about 2 (P1.B13). It stretches some directions and shrinks others. A single vector passed through many such matrices has a squared length that is right on average but wanders, as the 50-layer simulation showed: lengths from to for the middle 80 percent of starts. An orthogonal matrix has every singular value equal to 1, so no direction is stretched or shrunk and a chain of them keeps lengths exactly. The advantage is clearest for very deep, nearly linear chains.
Try it in Python
The first cell passes 200 inputs through 30 ReLU layers of 256 units for four weight scales and prints the root-mean-square size of the last layer. The second checks the variance rule and the factor of ReLU. The third compares Gaussian and orthogonal chains.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives about for standard deviation , for standard deviation , for LeCun and for He. Only the He rule keeps the signal near the size of the input.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The second cell prints against the theory value , against , and and for the ReLU check. The third prints the Gaussian length and the orthogonal length , then the mean squared length and the middle 80 percent range to .
Common mistakes
Quiz
Check your understanding
Every weight of a two-unit hidden layer, including the output weights from it, is set to the same nonzero value, and the biases are 0. What happens in training?
Both units compute the same value and the loss depends on them only through equal contributions, so they receive equal gradients and are updated by equal amounts; by induction they stay identical, and the layer behaves as one unit. Rounding does not separate them in exact arithmetic, the hidden weights do get gradients (they are just equal), and the examples are the same for both units, so they cannot make the two differ.
A unit has 100 inputs with , and its weights are independent with mean 0 and variance . What is for ?
The variance of a sum of independent terms is the sum of the variances, so . The value 0.01 is the variance of one weight, and 100 would need . The square-root growth applies to the standard deviation of a sum whose terms have variance 1, which is the case , and here the terms are smaller.
He initialization uses , twice the LeCun value. Why the factor 2 for ReLU layers?
Half of the squared values vanish, so the next layer sees half the variance, and doubling restores it. The ReLU slope is 1, not 2, for positive inputs. Symmetry is broken by any random draw, whatever its size. Positive outputs are the reason is used instead of , but the factor is not a centring correction.
A tanh layer has 256 inputs and 64 outputs. What variance does Xavier (Glorot) initialization give its weights?
Xavier uses both counts: . The value is the He rule for ReLU, which uses only the fan-in. The value uses the fan-out only, which would keep the backward pass steady but not the forward one. A fixed standard deviation of 0.01 ignores the layer size, which is exactly what the rules are meant to avoid.
What does an orthogonal matrix preserve, and why does that help as a starting weight matrix for a deep linear chain?
For orthogonal , , so a product of orthogonal matrices keeps the length of the signal exactly, forward and backward. Its entries are not equal (equal entries would give the symmetry problem), it does not zero any outputs, and it is lengths, not means, that it preserves.
Exercises
- A weight is drawn uniformly from . What is its variance? What limit gives a variance of ?
Show answer
. For variance , . - A ReLU layer has 512 inputs and 128 outputs. Give the standard deviation for He (fan-in, normal) initialization and the limit for Xavier (uniform) initialization.
Show answer
He: . Xavier uniform: . (For a ReLU layer the He rule is the matching one; Xavier is computed here only to practise the formula.) - A linear stack has 100 units per layer and weights with standard deviation . By what factor does each layer scale the signal’s standard deviation, and what happens after 10 layers? What standard deviation keeps the factor at 1?
Show answer
The factor is , and , so the signal falls to about a thousandth. A factor of 1 needs , a standard deviation of . - The inputs to a ReLU layer with have . The weights have variance . Compute , then .
Show answer
. Then , the same as the input’s , so the scale is preserved from layer to layer. - Take (a quarter turn) and . Find and its length. What are and its length?
Show answer
, with length , the same as . Four quarter turns give the identity, so and , again of length 5.
Next: P4.13 covers the optimizers that take the steps from this starting point, P4.16 treats vanishing and exploding gradients in depth, and P4.19 and P4.20 show how normalization layers and residual connections make a deep network easier to start.