Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Weight initialization

P4.1240 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A network starts from random weights, and their size decides whether the signal and the gradient stay a usable size through many layers or shrink to nothing or blow up before training has even begun.

  • Vanishing and exploding gradients are repeated multiplications by too small or too large factors, and the starting scale of the weights sets those factors. (P4.16: Vanishing and exploding gradients)
  • Normalization layers re-scale the activations inside the network, which makes training much less sensitive to the starting scale. (P4.19: Normalization layers)
  • Residual connections add a path that carries the signal unchanged, which also helps very deep networks start well. (P4.20: Residual connections)
  • Every PyTorch training script starts from some initialization, so you need to know what the default layers do and when to change it. (P2.7: The PyTorch training loop)

Before this: Activation functions, The forward pass in matrix form, Expectation and variance, Common distributions

After this lesson you can

  • Explain why all-zero (or all-equal) starting weights fail, using the symmetry argument, and why zero biases are fine
  • Derive Var(z)=nin Var(w) E[x2]\mathrm{Var}(z)=n_{\text{in}}\,\mathrm{Var}(w)\,\mathbb{E}[x^2] from the rules for the variance of a sum, and use it to see why weights that are too small or too large make signals vanish or explode
  • State and derive the LeCun, Xavier (Glorot) and He (Kaiming) variances, in normal and uniform form, and choose the right one for tanh and ReLU layers
  • Explain what orthogonal initialization preserves, and what PyTorch's default layers and initialization functions do

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 0.010.01, and the standard deviation of the last layer’s output is 2.5×10−132.5\times10^{-13}: nothing is left. With standard deviation 11 it is 2.5×1072.5\times10^{7}: the numbers have exploded. With standard deviation 2/64=0.177\sqrt{2/64}=0.177 it is 0.740.74, 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 x=(1,2)\mathbf{x}=(1,2) and the target is y=1y=1. The loss is 12(y^−y)2\tfrac12(\hat y-y)^2 and every hidden unit has bias 0. Give every weight the same value 0.50.5:

  • Both hidden units see z=0.5⋅1+0.5⋅2=1.5z=0.5\cdot1+0.5\cdot2=1.5, so both output tanh⁡(1.5)=0.9051\tanh(1.5)=0.9051.
  • The output is y^=0.5⋅0.9051+0.5⋅0.9051=0.9051\hat y=0.5\cdot0.9051+0.5\cdot0.9051=0.9051, and the error is y^−y=−0.0949\hat y-y=-0.0949.
  • The gradient of the loss with respect to each output weight is −0.0949×0.9051=−0.0859-0.0949\times0.9051=-0.0859: the same for both units.
  • The gradient with respect to the incoming weights is (−0.0086, −0.0171)(-0.0086,\,-0.0171) for both units.

With a learning rate of 0.10.1, both units move by the same amount: each incoming weight vector becomes (0.5009, 0.5017)(0.5009,\,0.5017) and each output weight 0.50860.5086. 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 0.10.1 and then 0.190.19, 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 (0.5,0.5)(0.5,0.5) and (0.3,−0.2)(0.3,-0.2), their gradients differ: (−0.054,−0.108)(-0.054,-0.108) and (−0.296,−0.591)(-0.296,-0.591), 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 0.010.01 for the weights of a layer with nin=64n_{\text{in}}=64 inputs. A sum of 64 terms, each about 0.010.01 times an input of size 1, has a typical size of about 64×0.01=0.08\sqrt{64}\times0.01=0.08 (the terms partly cancel, so it grows like the square root, not like 64; P1.D8). Each layer shrinks the signal by about 0.080.08, and ten layers shrink it by 0.0810≈10−110.08^{10}\approx10^{-11}. With standard deviation 11 the factor per layer is about 88, and 810≈1098^{10}\approx10^{9}. ReLU also zeroes the negative half, which lowers the factor, so the measured figures in the opening paragraph are a little different (10−1310^{-13} and 10710^{7}), but the exponential pattern is the same.

The backward pass is the same story. The gradient travelling back through a layer is multiplied by W⊤\mathbf{W}^\top (P4.8), so it also shrinks or grows by a factor per layer. A signal of size 10−1310^{-13} gives gradients too small to change anything, and a signal of size 10710^{7} 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

z=∑i=1ninwixi,z=\sum_{i=1}^{n_{\text{in}}} w_i x_i ,

where ninn_{\text{in}} is the number of inputs to the unit, called its fan-in (it is the dd of P1.D4). Suppose the weights are drawn independently of each other and of the inputs, all with mean 00 and the same variance Var(w)\mathrm{Var}(w). Then:

  1. Each term has mean E[wixi]=E[wi] E[xi]=0\mathbb{E}[w_i x_i]=\mathbb{E}[w_i]\,\mathbb{E}[x_i]=0.
  2. Each term has variance Var(wixi)=E[wi2xi2]=E[wi2] E[xi2]=Var(w) E[x2]\mathrm{Var}(w_i x_i)=\mathbb{E}[w_i^2 x_i^2]=\mathbb{E}[w_i^2]\,\mathbb{E}[x_i^2]=\mathrm{Var}(w)\,\mathbb{E}[x^2], using E[wi2]=Var(w)\mathbb{E}[w_i^2]=\mathrm{Var}(w) because the mean is 0.
  3. The variance of a sum of independent terms is the sum of the variances, so
Var(z)=nin  Var(w)  E[x2].\mathrm{Var}(z)=n_{\text{in}}\;\mathrm{Var}(w)\;\mathbb{E}[x^2].

If the inputs also have mean 0, then E[x2]=Var(x)\mathbb{E}[x^2]=\mathrm{Var}(x) and this is the Var(z)=nin Var(w) Var(x)\mathrm{Var}(z)=n_{\text{in}}\,\mathrm{Var}(w)\,\mathrm{Var}(x) of P1.D4. The version with E[x2]\mathbb{E}[x^2] 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 nin=1000n_{\text{in}}=1000 inputs of variance 1 and weights of variance 1, the output variance is 10001000. With Var(w)=1/1000\mathrm{Var}(w)=1/1000 it is 11. A simulation of 20,000 such units gives 995.4995.4 and 0.9920.992 (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 zz itself, so E[x2]=Var(zprevious)\mathbb{E}[x^2]=\mathrm{Var}(z_{\text{previous}}). Keeping the variance equal from layer to layer means ninVar(w)=1n_{\text{in}}\mathrm{Var}(w)=1:

Var(w)=1nin.\mathrm{Var}(w)=\frac{1}{n_{\text{in}}}.

This choice is often called LeCun initialization, after advice in LeCun and colleagues’ Efficient BackProp chapter (1998). For nin=64n_{\text{in}}=64 it is a standard deviation of 0.1250.125.

He (Kaiming): ReLU removes half

ReLU sets every negative zz to 0. If zz is centred on 0 and symmetric, half of its values are negative, so half of the squared values vanish:

E[ReLU(z)2]=12 E[z2]=12 Var(z).\mathbb{E}\bigl[\mathrm{ReLU}(z)^2\bigr]=\tfrac12\,\mathbb{E}[z^2]=\tfrac12\,\mathrm{Var}(z).

The simulation agrees: for zz with variance 1, E[z2]≈1.002\mathbb{E}[z^2]\approx1.002 and E[ReLU(z)2]≈0.501\mathbb{E}[\mathrm{ReLU}(z)^2]\approx0.501. Put this in the rule: Var(znext)=ninVar(w)⋅12Var(z)\mathrm{Var}(z_{\text{next}})=n_{\text{in}}\mathrm{Var}(w)\cdot\tfrac12\mathrm{Var}(z). For the variance to stay steady, 12ninVar(w)=1\tfrac12 n_{\text{in}}\mathrm{Var}(w)=1, which gives

Var(w)=2nin.\mathrm{Var}(w)=\frac{2}{n_{\text{in}}}.

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 2−30≈10−92^{-30}\approx10^{-9} of the input’s in theory, and the first code cell below prints an rms of 4.5×10−54.5\times10^{-5} for LeCun, whose square is 2×10−92\times10^{-9}.

Xavier (Glorot): balance forward and backward

The forward pass wants ninVar(w)=1n_{\text{in}}\mathrm{Var}(w)=1. The backward pass has its own condition. The gradient at a layer’s input is W⊤δ\mathbf{W}^\top\boldsymbol{\delta}, and each of its entries sums over the noutn_{\text{out}} units that the input feeds (the layer’s fan-out). If the activation has slope near 1, the same argument gives Var(δprevious)=noutVar(w) Var(δ)\mathrm{Var}(\delta_{\text{previous}})=n_{\text{out}}\mathrm{Var}(w)\,\mathrm{Var}(\delta), which wants Var(w)=1/nout\mathrm{Var}(w)=1/n_{\text{out}}. When nin≠noutn_{\text{in}}\ne n_{\text{out}} both cannot hold. Glorot and Bengio (Understanding the difficulty of training deep feedforward neural networks, AISTATS 2010) proposed a compromise:

Var(w)=2nin+nout.\mathrm{Var}(w)=\frac{2}{n_{\text{in}}+n_{\text{out}}}.

This is Xavier or Glorot initialization (it is 1/n1/n with nn the average of fan-in and fan-out). It assumes the activation is roughly linear with slope 1 near 0, as tanh is. When nin=nout=nn_{\text{in}}=n_{\text{out}}=n it reduces to 1/n1/n, 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 [−a,a][-a,a] has variance (2a)212=a23\frac{(2a)^2}{12}=\frac{a^2}{3} (P1.D3). To get a target variance vv you need a=3va=\sqrt{3v}. For Xavier, v=2/(nin+nout)v=2/(n_{\text{in}}+n_{\text{out}}), so

a=6nin+nout,a=\sqrt{\frac{6}{n_{\text{in}}+n_{\text{out}}}},

which is the limit Glorot and Bengio wrote down. For He with the uniform form, a=6/nina=\sqrt{6/n_{\text{in}}}.

Fan-in or fan-out?

Which count to use for a layer with nin=256n_{\text{in}}=256 inputs and nout=64n_{\text{out}}=64 outputs? Here are the numbers for that layer:

  • LeCun: variance 1/256=0.00391/256=0.0039, standard deviation 0.06250.0625.
  • Xavier: variance 2/320=0.006252/320=0.00625, standard deviation 0.07910.0791, uniform limit a=0.1369a=0.1369.
  • He, fan-in mode: variance 2/256=0.00782/256=0.0078, standard deviation 0.08840.0884.
  • He, fan-out mode: variance 2/64=0.03132/64=0.0313, standard deviation 0.17680.1768.

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 N(0,1)N(0,1) 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 0.830.83 in theory (the 64-unit stacks fluctuate around that), not at 1, even though the second moment stays 1.

seed 1 of 5

Large: normal, standard deviation 1.

Activations of layers 1 to 10 (128 made-up inputs, 64 units per layer). Each small histogram spans 0 to 4; the last bar collects every value above 4. Under each: the layer and the standard deviation of its activations. Each is scaled to its own tallest bar.

L1
4.72
L2
29.3
L3
159
L4
961
L5
5.6e3
L6
3.1e4
L7
1.8e5
L8
1.1e6
L9
5.5e6
L10
2.5e7
12345678910−10−505layerlog₁₀ of std
  • activations (forward), solid line and circles
  • gradient at each layer (backward), dashed line and squares

The dotted line is a standard deviation of 1 (the ideal). A point on the bottom edge means 10−14 or smaller, or exactly 0. The gradient starts as N(0, 1) numbers arriving at layer 10 and travels back to layer 1, so read the orange line from right to left.

LayerActivationsGradient
14.724.5e6
229.37.9e5
31591.3e5
49612.4e4
55.6e34.2e3
63.1e4735
71.8e5137
81.1e622.2
95.5e63.82
102.5e70.68
A 10-layer network with 64 units per layer, run forward and backward. Choose an activation (tanh, ReLU, sigmoid) and a way to draw the starting weights. The small histograms show the activations of each layer, and the plot shows the standard deviation of the activations (blue) and of the gradient (orange) per layer on a log scale. Try ReLU with LeCun and then He, tanh with Large and then Xavier, and Orthogonal with gain 1 and then gain √2.

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 0.0470.047 in layer 1 to 2.5×10−132.5\times10^{-13} in layer 10. The histograms are a single bar at 0 and the gradient at layer 1 is 4.5×10−124.5\times10^{-12}. With tanh the activations fall from 0.080.08 in layer 1 to 10−1110^{-11}.
  • Large (standard deviation 1). With ReLU the activations rise to 2.5×1072.5\times10^{7} and the gradient has standard deviation 0.680.68 at layer 10 but 4.5×1064.5\times10^{6} at layer 1. With tanh the values cannot explode, so they saturate instead: about 7373 percent of the layer-10 activations are beyond ±0.99\pm0.99, where the slope of tanh is almost 0, and the gradient is large and uneven (std 0.260.26 at layer 10, growing to 211211 at layer 1).
  • ReLU with LeCun versus He. LeCun leaves the activations at 0.0230.023 in layer 10, because half the variance is lost at every layer. He keeps them at 0.740.74, and the gradient at layer 1 is 0.750.75 against 0.680.68 at layer 10.
  • tanh with Xavier. The activations settle near 0.240.24 and the gradient at layer 1 is 0.270.27 (against 0.940.94 at layer 10). They shrink somewhat, because tanh is only linear for small zz, but they do not collapse. The Xavier (uniform) and LeCun (normal) variances are equal here, because nin=nout=64n_{\text{in}}=n_{\text{out}}=64, so the two behave alike.
  • tanh with He. For these 64-unit layers He keeps the scale steadier than Xavier: the activations settle near 0.550.55 (from 0.720.72 in layer 1) and the gradient is 0.720.72 at layer 1 against 0.740.74 at layer 10. Tanh is only linear for small zz and flattens larger ones, so a slightly larger variance compensates (PyTorch’s recommended gain for tanh is 5/35/3, a variance 25/9≈2.825/9\approx2.8 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 0.20.2 to 0.330.33 per layer (for LeCun, 5.0×10−75.0\times10^{-7} at layer 1 against 0.230.23 at layer 10). Small weights are far worse (about 0.020.02 per layer), and the PyTorch default shrinks it by about 0.140.14 per layer. Large weights shrink it least, only about 7×7\times over the stack, because the sigmoids saturate. A sigmoid’s slope is at most 14\tfrac14, and its output is centred on 0.50.5, 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 10−410^{-4} in layer 10, a factor of about 0.40.4 per layer. See the section on defaults below.
  • Orthogonal. With gain 1 and ReLU the scale matches LeCun’s (0.0230.023); with gain 2\sqrt2 it gives 0.750.75, close to He’s 0.740.74. 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 Q\mathbf{Q} satisfies Q⊤Q=I\mathbf{Q}^\top\mathbf{Q}=\mathbf{I} and keeps the length of every vector: ∥Qx∥=∥x∥\lVert\mathbf{Q}\mathbf{x}\rVert=\lVert\mathbf{x}\rVert (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 1/n1/n. 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 0.760.76 after the Gaussian chain, and exactly 11 after the orthogonal chain. Over 1000 random starting vectors the mean of the squared length is 1.011.01, but the lengths themselves range widely: the middle 80 percent lie between 0.290.29 and 1.581.58. 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 gg multiplies the matrix to compensate. PyTorch’s calculate_gain gives 2\sqrt2 for ReLU (the factor that undoes the loss of half the variance), 5/35/3 for tanh and 11 for sigmoid and for no activation. In the widget the two orthogonal choices use gain 1 and gain 2\sqrt2.

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 [−1/nin, 1/nin][-1/\sqrt{n_{\text{in}}},\,1/\sqrt{n_{\text{in}}}]. The source code calls kaiming_uniform_ with the argument a=5a=\sqrt5, which works out to exactly this range. The variance is a2/3=1/(3nin)a^2/3=1/(3n_{\text{in}}), 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 0.40.4 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_ and xavier_normal_ for tanh-like layers.
  • kaiming_uniform_ and kaiming_normal_ for ReLU-like layers (pass nonlinearity="relu"; they use fan-in mode by default).
  • orthogonal_ for an orthogonal matrix, with gain= from calculate_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 0.020.02 and the biases start at 0. For a layer with 768 inputs, 1/768≈0.0361/\sqrt{768}\approx0.036 would be the LeCun value, so 0.020.02 is smaller. The GPT-2 paper also mentions scaling the weights of residual layers by 1/N1/\sqrt{N} for NN 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 ninn_{\text{in}} independent zero-mean weights,

Var(z)=nin Var(w) E[x2].\mathrm{Var}(z)=n_{\text{in}}\,\mathrm{Var}(w)\,\mathbb{E}[x^2].

Requiring the variance of zz to stay constant from layer to layer gives:

  • LeCun (linear activation): Var(w)=1nin\mathrm{Var}(w)=\dfrac{1}{n_{\text{in}}}.
  • He (ReLU): Var(w)=2nin\mathrm{Var}(w)=\dfrac{2}{n_{\text{in}}}.
  • Xavier (tanh-like): Var(w)=2nin+nout\mathrm{Var}(w)=\dfrac{2}{n_{\text{in}}+n_{\text{out}}}.

Uniform form: Uniform(−a,a)\mathrm{Uniform}(-a,a) has variance a2/3a^2/3, so a=3 Var(w)a=\sqrt{3\,\mathrm{Var}(w)}. For Xavier, a=6/(nin+nout)a=\sqrt{6/(n_{\text{in}}+n_{\text{out}})}. Per layer, the signal’s standard deviation is multiplied by about ninVar(w)\sqrt{n_{\text{in}}\mathrm{Var}(w)} for a linear unit and ninVar(w)/2\sqrt{n_{\text{in}}\mathrm{Var}(w)/2} for ReLU; over LL layers this is raised to the power LL.

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.4142

The default maximum 0.06250.0625 is 1/2561/\sqrt{256}, as the source code says, and the He standard deviation is close to 2/256=0.0884\sqrt{2/256}=0.0884. 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 0.630.63 to 0.240.24 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 0.740.74 and 1.071.07 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 1/n1/n 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 0.290.29 to 1.581.58 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 12\tfrac12 of ReLU. The third compares Gaussian and orthogonal chains.

Signal size after 30 ReLU layers

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives about 6.7×10−296.7\times10^{-29} for standard deviation 0.010.01, 2.4×10312.4\times10^{31} for standard deviation 11, 4.5×10−54.5\times10^{-5} for LeCun and 1.41.4 for He. Only the He rule keeps the signal near the size of the input.

The variance rule and the half of ReLU

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Gaussian versus orthogonal, 50 layers

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The second cell prints 995.4995.4 against the theory value 10001000, 0.9920.992 against 11, and 1.0021.002 and 0.5010.501 for the ReLU check. The third prints the Gaussian length 0.760.76 and the orthogonal length 11, then the mean squared length 1.011.01 and the middle 80 percent range 0.290.29 to 1.581.58.

Common mistakes

Quiz

Check your understanding

  1. 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?

  2. A unit has 100 inputs with E[x2]=1\mathbb{E}[x^2]=1, and its weights are independent with mean 0 and variance 0.010.01. What is Var(z)\mathrm{Var}(z) for z=∑iwixiz=\sum_i w_ix_i?

  3. He initialization uses Var(w)=2/nin\mathrm{Var}(w)=2/n_{\text{in}}, twice the LeCun value. Why the factor 2 for ReLU layers?

  4. A tanh layer has 256 inputs and 64 outputs. What variance does Xavier (Glorot) initialization give its weights?

  5. What does an orthogonal matrix Q\mathbf{Q} preserve, and why does that help as a starting weight matrix for a deep linear chain?

Exercises

  1. A weight is drawn uniformly from [−0.5,0.5][-0.5,0.5]. What is its variance? What limit aa gives a variance of 0.010.01?
    Show answera2/3=0.25/3=0.0833a^2/3=0.25/3=0.0833. For variance 0.010.01, a=3×0.01=0.03=0.173a=\sqrt{3\times0.01}=\sqrt{0.03}=0.173.
  2. 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 answerHe: 2/512=0.0039=0.0625\sqrt{2/512}=\sqrt{0.0039}=0.0625. Xavier uniform: a=6/(512+128)=0.009375=0.0968a=\sqrt{6/(512+128)}=\sqrt{0.009375}=0.0968. (For a ReLU layer the He rule is the matching one; Xavier is computed here only to practise the formula.)
  3. A linear stack has 100 units per layer and weights with standard deviation 0.050.05. 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 answerThe factor is ninVar(w)=100×0.0025=0.5\sqrt{n_{\text{in}}\mathrm{Var}(w)}=\sqrt{100\times0.0025}=0.5, and 0.510≈0.000980.5^{10}\approx0.00098, so the signal falls to about a thousandth. A factor of 1 needs Var(w)=1/100\mathrm{Var}(w)=1/100, a standard deviation of 0.10.1.
  4. The inputs to a ReLU layer with nin=64n_{\text{in}}=64 have E[x2]=0.5\mathbb{E}[x^2]=0.5. The weights have variance 2/642/64. Compute Var(z)\mathrm{Var}(z), then E[ReLU(z)2]\mathbb{E}[\mathrm{ReLU}(z)^2].
    Show answerVar(z)=64×264×0.5=1\mathrm{Var}(z)=64\times\frac{2}{64}\times0.5=1. Then E[ReLU(z)2]=12×1=0.5\mathbb{E}[\mathrm{ReLU}(z)^2]=\frac12\times1=0.5, the same as the input’s E[x2]\mathbb{E}[x^2], so the scale is preserved from layer to layer.
  5. Take Q=(0−110)\mathbf{Q}=\begin{pmatrix}0&-1\\1&0\end{pmatrix} (a quarter turn) and x=(3,4)\mathbf{x}=(3,4). Find Qx\mathbf{Q}\mathbf{x} and its length. What are Q50x\mathbf{Q}^{50}\mathbf{x} and its length?
    Show answerQx=(−4,3)\mathbf{Q}\mathbf{x}=(-4,3), with length 16+9=5\sqrt{16+9}=5, the same as ∥x∥=5\lVert\mathbf{x}\rVert=5. Four quarter turns give the identity, so Q50=Q2=−I\mathbf{Q}^{50}=\mathbf{Q}^{2}=-\mathbf{I} and Q50x=(−3,−4)\mathbf{Q}^{50}\mathbf{x}=(-3,-4), 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.

Key takeaways

  • If all the weights of a layer start equal, every hidden unit computes the same value and receives the same gradient, so the units stay identical for the whole of training. Random starting weights break the tie. Biases can start at 0, because each unit's incoming weights already differ.
  • A unit that sums ninn_{\text{in}} independent terms with zero-mean weights has Var(z)=nin Var(w) E[x2]\mathrm{Var}(z)=n_{\text{in}}\,\mathrm{Var}(w)\,\mathbb{E}[x^2]. Each layer therefore multiplies the typical size of the signal by about ninVar(w)\sqrt{n_{\text{in}}\mathrm{Var}(w)}, so a factor even slightly away from 1 shrinks or grows exponentially with depth. The gradient travelling back behaves the same way.
  • Keeping the variance steady gives Var(w)=1/nin\mathrm{Var}(w)=1/n_{\text{in}} (LeCun). ReLU zeroes half of zz, so E[ReLU(z)2]=12Var(z)\mathbb{E}[\mathrm{ReLU}(z)^2]=\tfrac12\mathrm{Var}(z) and the rule becomes 2/nin2/n_{\text{in}} (He/Kaiming). Xavier/Glorot balances the forward and backward passes with 2/(nin+nout)2/(n_{\text{in}}+n_{\text{out}}) and suits tanh-like activations.
  • A uniform distribution on [−a,a][-a,a] has variance a2/3a^2/3, so a target variance vv needs a=3va=\sqrt{3v}; for Xavier this is a=6/(nin+nout)a=\sqrt{6/(n_{\text{in}}+n_{\text{out}})}. Orthogonal matrices keep lengths exactly, so orthogonal initialization (with a gain for ReLU) keeps the scale of a linear chain.
  • PyTorch's nn.Linear draws weights uniformly from [−1/nin, 1/nin][-1/\sqrt{n_{\text{in}}},\,1/\sqrt{n_{\text{in}}}], which has variance 1/(3nin)1/(3n_{\text{in}}), and its biases are not zero. Normalization layers and residual connections make a network less sensitive to the initialization, not immune to it.
Found a mistake? Tell us