13.4 Variance propagation and initialization
Module system and basic layers in AI Engineering builds layers, and a layer needs starting weights. The obvious choices fail. All zeros makes every unit in a layer compute the same thing and receive the same gradient forever. Standard normal weights make a layer with 512 inputs multiply the size of its input by about , so after a few layers the activations overflow float32 or saturate every tanh, and the gradients are 0 or NaN. Weights a little too small do the opposite: the signal shrinks geometrically and the deep layers learn nothing.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Standard normal: the distribution with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Random variable: a number assigned to each outcome of a random experiment; a discrete one is a table of values and probabilities. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives
- Second moment (,
exp_avg_sq): the EMA of the elementwise squared gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay - PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- C-contiguous: row-major layout, with the last axis packed and each earlier stride equal to the next stride times the next size. Read more: 1.1 Python and numpy: arrays, dtypes, broadcasting, views vs copies, uv projects in Programming and Algorithms
The first MLP in that book trains on digits from the initialization built here, and the TinyStories capstone trains a 10M-parameter Transformer the same way. This section derives the one number that decides which of these outcomes happens, the variance of the weights, from the expectation and variance of Random variables, expectation, variance, and normal draws, and builds the initializers every later model calls.
That section’s normal(rng, n) (rv.py) draws every normal weight here. For background you will also want the activations of Activation Functions and Their Derivatives, the generator of Modular arithmetic, hashing, and PCG32, and the Gaussian integrals worked in the Calculus 2 and Calculus 3 problem sets. The reference implementation is course/solutions/python/tinyllm/nn/init.py, with its contract in init.pyi and the draw order in spec/pcg32.md.
Learning objectives
- Derive for a layer’s pre-activation.
- Derive the Xavier and Kaiming variances and explain which activations each suits.
- Compute fans and gains for Linear and convolution weights the way torch does.
- Draw weights reproducibly in row-major order from a passed-in generator.
- Scale residual output projections so a Transformer’s stream variance is independent of depth.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| , | expectation and variance of a random variable, | scalars |
| a Linear weight, one row per output (torch’s layout) | float32[out, in] | |
| the layer’s input; its pre-activation | vectors | |
| fan-in and fan-out: inputs feeding one output, outputs fed by one input | int | |
| the variance every weight is drawn with | float | |
| the activation, | function | |
| the gain of : the factor that corrects the variance for it | float | |
| , | uniform on ; normal with mean 0 and standard deviation | distributions |
| the number of Transformer blocks | int |
Expectation and variance of sums and products
Section titled “Expectation and variance of sums and products”Two rules from the previous sections do all the work. Expectation is linear: for any random variables. Variance adds for independent ones: , because the cross term is a product of two zero means. For a product of independent and with :
Note , not : the input’s mean counts too (after a ReLU, has a positive mean).
Choosing the weight variance
Section titled “Choosing the weight variance”With those rules, a whole layer is one line of algebra. One output of a layer is , a sum of independent products, each with mean 0, so
To keep the signal the same size from layer to layer, set this equal to the previous layer’s value. For linear activations (, zero mean), and the condition is . The backward pass multiplies gradients by , whose rows have entries, so it wants . Xavier initialization (Glorot and Bengio) splits the difference:
ReLU, , keeps the positive half of a symmetric and zeroes the rest, so . The next layer then sees , and preserving the variance needs twice as much weight variance. That is Kaiming initialization (He et al.):
Getting the factor wrong compounds: a variance too small by 2 per layer is after 20 layers, and too large by 2 is . With Kaiming the signal survives 20 ReLU layers; with Xavier it shrinks by about .
Fans and gains
Section titled “Fans and gains”The two formulas above differ only in a constant that depends on the activation and in which fan they use. Libraries factor both out. A gain writes the activation’s correction as a factor on the standard deviation: Kaiming is with for ReLU, and Xavier takes an optional gain, .
The solution matches torch’s gain table: for linear, convolutions, and sigmoid; for ReLU; for leaky ReLU with negative slope (default ), because it keeps of the negative half’s second moment; for SELU; and for tanh. The tanh value is empirical: tanh has slope 1 at 0 but shrinks larger inputs, and with the mean square of a deep tanh stack settles near 0.42 instead of draining toward 0 (about 0.02 after 20 layers with ).
Fans come from the weight’s shape (out, in, *kernel): , , with the product of the kernel dimensions (1 for a Linear weight). A convolution with 4 input channels and a kernel has . Fewer than 2 dimensions have no fan-in and are an error.
Drawing the weights
Section titled “Drawing the weights”Two distributions with the same variance work equally well at the start. A uniform has variance , so Xavier-uniform uses ; element is with the -th rng.uniform(). A normal is times a standard normal from normal(rng, n).
Either way the array is filled in row-major (C) order, one draw per element, and nothing else is drawn. A model initialized layer after layer from one generator is therefore reproducible, and the Rust port can rebuild the same weights from the same seed. Results are float32, the dtype of every parameter.
Residual streams
Section titled “Residual streams”Deep Transformers add one more consideration. A Transformer block adds its outputs to a running residual stream: , two additions per block, in all. If each addition is independent with variance , the stream’s variance grows to . GPT-2 scales the standard deviation of the two output projections in every block to
whatever the depth. This is scaled_residual_std, with in GPT-2 and in the Llama-family model.
Working it by hand
Section titled “Working it by hand”A Linear layer with 3 inputs and 4 outputs stores as shape : , . The four scales come out as follows.
| Initializer | Formula | Value |
|---|---|---|
| Xavier-uniform bound | ||
| Xavier-normal std | ||
| Kaiming-normal std (ReLU, fan_in) | ||
| GPT-2 residual std, |
The variance carries through. Feed the Kaiming layer an input with : . ReLU keeps half the second moment: , exactly what the next layer received. With Xavier () the same input gives and : the signal loses more than half per layer.
The draws. With PCG32(0) the first uniform is , so Xavier-uniform’s first weight is . Kaiming’s first weight uses the first pair : , , so the standard normal is and the weight . These values form the first test case a correct implementation must reproduce.
Designing the interface
Section titled “Designing the interface”Seven functions cover fans, gains, the three families of initializer, and the residual scale:
def fans(shape: tuple[int, ...]) -> tuple[int, int] # (fan_in, fan_out)def calculate_gain(nonlinearity: str, param: float | None = None) -> floatdef xavier_uniform(shape, gain: float, rng) -> NDArray # float32, U(-a, a)def xavier_normal(shape, gain: float, rng) -> NDArray # float32, N(0, s^2)def kaiming_normal(shape, fan_mode: Literal["fan_in", "fan_out"], nonlinearity: str, rng) -> NDArraydef normal_init(shape, std: float, rng) -> NDArray # any shape, including 1-Ddef scaled_residual_std(base_std: float, n_layers: int) -> float # base / sqrt(2 L)rng is a PCG32 (rng.py). Uniforms come from rng.uniform(), normals from tinyllm.prob.rv.normal(rng, n). Every function raises ValueError for a shape without a fan (fewer than 2 dimensions, or a 0 fan), a negative gain or standard deviation, an unknown nonlinearity or fan mode, and n_layers < 1.
Building it step by step
Section titled “Building it step by step”Six observations produce the implementation.
- Everything is set by the fans. The variance a layer needs depends only on and . For a weight of shape
(out, in, *kernel)those arein * randout * r, with the product of the kernel dimensions (math.prod(())is 1, so a Linear weight needs no special case). Fewer than 2 dimensions, or a fan of 0, leaves the variance undefined: raise. - The activation enters as one gain on the standard deviation. A lookup table returns (not ), so every initializer is “some over the square root of some fan”.
- Xavier-uniform needs the uniform’s own variance. , so matching forces . Each element is the affine map of one uniform.
- Every normal initializer is “std times spec normals”. Xavier-normal, Kaiming-normal, and
normal_initdiffer only in the standard deviation; one helper drawsprod(shape)normals withnormal, scales, reshapes in C order, and casts to float32. - The generator is passed in, never created. One
rngthreads through every layer, so the seed fixes the whole model and layers initialized in sequence get different, reproducible weights. - The residual scale counts two additions per block. , so for any depth.
Fans and gains come first:
def fans(shape: tuple[int, ...]) -> tuple[int, int]: s = _shape(shape) # ints, none negative if len(s) < 2: raise ValueError(f"fan_in and fan_out need at least 2 dimensions, got shape {s}") receptive = math.prod(s[2:]) # kernel size; 1 for a Linear weight # torch's layout is (out, in, *kernel): dim 1 feeds each output, dim 0 is fed by each input. fan_in, fan_out = s[1] * receptive, s[0] * receptive if fan_in == 0 or fan_out == 0: raise ValueError(f"shape {s} has a fan of 0") # sqrt(2 / 0) is no scale at all return fan_in, fan_out
def calculate_gain(nonlinearity: str, param: float | None = None) -> float: if nonlinearity in _GAIN_ONE: # linear, the conv variants, sigmoid return 1.0 if nonlinearity == "tanh": return 5.0 / 3.0 # empirical: keeps a deep tanh stack's mean square stable if nonlinearity == "relu": return math.sqrt(2.0) # a standard deviation: ReLU halves the second moment if nonlinearity == "leaky_relu": if param is None: slope = 0.01 elif isinstance(param, Real) and not isinstance(param, bool): slope = float(param) else: raise ValueError(f"leaky_relu slope must be a number, got {param!r}") return math.sqrt(2.0 / (1.0 + slope**2)) # the negative half keeps slope^2 of its moment if nonlinearity == "selu": return 3.0 / 4.0 raise ValueError(f"unsupported nonlinearity {nonlinearity!r}") # no silent default of 1For the weight of the hand example, receptive = 1, fan_in = 3, fan_out = 4. A conv weight gets receptive = 9 and fans .
The initializers then reduce to choosing a scale and calling one of two drawing routines:
def _normal(shape: tuple[int, ...], std: float, rng: Any) -> NDArray: """std * standard normals in C order, as float32.""" n = math.prod(shape) # Draw in float64 (the spec's normals), scale, then fill row-major and cast once. return (std * normal(rng, n)).reshape(shape).astype(np.float32)
def xavier_uniform(shape: tuple[int, ...], gain: float, rng: Any) -> NDArray: if not gain >= 0.0: # also rejects NaN raise ValueError(f"gain must be >= 0, got {gain}") s = _shape(shape) fan_in, fan_out = fans(s) a = gain * math.sqrt(6.0 / (fan_in + fan_out)) # Var U(-a, a) = a^2 / 3 = 2 g^2 / (in + out) u = np.array([rng.uniform() for _ in range(math.prod(s))], dtype=np.float64) # one draw per element return (-a + 2.0 * a * u).reshape(s).astype(np.float32)
def xavier_normal(shape: tuple[int, ...], gain: float, rng: Any) -> NDArray: # (gain check as above) s = _shape(shape) fan_in, fan_out = fans(s) return _normal(s, gain * math.sqrt(2.0 / (fan_in + fan_out)), rng)
def kaiming_normal(shape, fan_mode, nonlinearity, rng) -> NDArray: if fan_mode not in ("fan_in", "fan_out"): raise ValueError(f"fan_mode must be 'fan_in' or 'fan_out', got {fan_mode!r}") s = _shape(shape) fan_in, fan_out = fans(s) fan = fan_in if fan_mode == "fan_in" else fan_out # forward or backward variance preserved return _normal(s, calculate_gain(nonlinearity) / math.sqrt(fan), rng)
def normal_init(shape: tuple[int, ...], std: float, rng: Any) -> NDArray: if not std >= 0.0: raise ValueError(f"std must be >= 0, got {std}") return _normal(_shape(shape), std, rng) # no fans: any shape, including 1-D biases
def scaled_residual_std(base_std: float, n_layers: int) -> float: # (argument checks elided) return base_std / math.sqrt(2.0 * n_layers) # two residual additions per blockOn the hand example, Xavier-uniform’s first element is , and Kaiming’s is , where is the first spec normal of PCG32(0). Because reshape is C order, element of the flat draw becomes row , column , the same layout the Rust port reads. The full solution is init.py.
Why this design
Section titled “Why this design”Each initializer costs draws and arithmetic; the uniform version makes exactly one rng.uniform() per element and the normal versions . Memory is one float64 temporary plus the float32 result.
Drawing in float64 and casting once matters for reproducibility. Scaling float64 normals and casting at the end gives the correctly rounded float32 of the exact value, which every port can reproduce; drawing or scaling in float32 would add a port-dependent rounding.
Passing one generator in is the only arrangement that makes the seed meaningful. A global or per-call generator makes the seed meaningless or gives every layer the same weights. Threading rng through keeps the whole model a function of one seed.
There are alternatives. Orthogonal initialization preserves norms exactly rather than in expectation and helps very deep linear stacks, at the cost of a QR per layer. Truncated normals avoid rare large weights. LSUV and data-dependent schemes measure variance on a batch. The analytic Xavier and Kaiming scales need no data and are what torch uses, which the layers in AI Engineering compare against.
The tradeoff accepted is that the derivation assumes independent zero-mean weights and inputs, so it is exact only at initialization. Training breaks independence, and normalization layers such as Pre-LN and RMSNorm then keep the scale.
What can go wrong
Section titled “What can go wrong”A correct solution reproduces the hand values, matches torch, and passes measured-variance and deep-stack checks. The full list, with why each matters downstream:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the layer by hand | unit | fans, gains, the residual std, and the first weights of PCG32(0) | everyone agrees on every formula |
| torch’s fans and gains | golden | torch’s gain table and fan rule for Linear and conv shapes | the layers are compared with torch |
| spec normals in C order | unit | each normal initializer is std times the spec normals, row-major, odd sizes too | reproducible weights across languages |
| one uniform per element | unit | exact values, and the generator advanced by exactly one uniform per element | layers initialized in sequence stay aligned |
| same seed, same weights | property | equal seeds give equal bytes, different seeds differ | replayable runs |
| measured variance | statistical | mean 0 and variance within 4 standard errors for all four variants | the variance formulas, measured |
| 20 ReLU layers | property | Kaiming keeps the mean square within a factor 16; Xavier collapses it below | deep MLPs and Transformers train at all |
| 20 tanh layers | property | gain keeps the mean square in ; gain 1 ends at less than half that | tanh and gated recurrent layers (LSTM) |
| the residual stream | property | for several depths | GPT-2 style output projections |
| shapes and dtype | unit | float32, C-contiguous, exact shapes, 1-D for normal_init | parameters are float32 |
| bad arguments | boundary | 1-D fans, unknown names, negative std or depth raise ValueError | no silent wrong-scale default |
Most bugs here are a wrong constant or a wrong axis, and none of them crash: they just train badly. Reading a (out, in) weight as (in, out) swaps fan-in and fan-out, so non-square layers get the wrong scale; the solution uses fan_in = s[1] * receptive. Ignoring the kernel dimensions initializes a convolution 9 times too large in variance; receptive = math.prod(s[2:]) prevents that.
Warning: Confusing variances and standard deviations is the classic initialization bug. Using as the uniform bound is 3 times too small in variance, because the uniform’s variance is . A ReLU gain of 2 (a variance) instead of (a standard deviation) doubles the activations’ mean square per layer: after 20.
A GPT-2 residual scale of instead of forgets that each block adds two outputs, so the stream ends twice as large; the solution uses math.sqrt(2.0 * n_layers).
Two mistakes break reproducibility rather than scale. Filling in column-major order gives the same distribution but different weights, so Python and the Rust port disagree for the same seed; numpy’s default C-order reshape avoids it. Making a new generator inside the initializer gives every layer the same weights and makes the seed do nothing; rng is a parameter for that reason.
Where this leads
Section titled “Where this leads”These functions initialize nearly every model in AI Engineering. Linear and Embedding in Module system and basic layers initialize their parameters with them, as do the LSTM gate weights. Further layers use the same functions: the GRU, the RNN language model, positional encodings, the encoder-decoder Transformer, GPT, BERT, and ELECTRA. The Llama-family model and the TinyStories capstone use normal_init(0.02) plus scaled_residual_std for the output projections of a Llama-style decoder. In vision, conv layers use normal_init scaled by fan-in, and the vision transformer uses it for patch and position embeddings.
Further reading
Section titled “Further reading”- Glorot and Bengio, “Understanding the difficulty of training deep feedforward neural networks” (2010), section 4.2.
- He et al., “Delving Deep into Rectifiers” (2015), section 2.2.
- Radford et al., “Language Models are Unsupervised Multitask Learners” (GPT-2, 2019), section 2.3.
torch.nn.init(torch/nn/init.py): in-place initializers,trunc_normal_,orthogonal_, andkaiming_uniform_witha = sqrt(5)(torch’sLineardefault).- GPT-NeoX and Megatron’s
scaled_init_method_normal(megatron/core/utils.py): the same rule, applied by parameter name. - Yang et al., “Tensor Programs V” (2022), muP: width-dependent init and learning rates so hyperparameters transfer from small to large models, replacing a fixed base std.
- Schoenholz et al., “Deep Information Propagation” (2017): mean-field analysis of depth and the edge of chaos; Fixup and T-Fixup train without normalization.
Key terms
Section titled “Key terms”- Fan-in / fan-out: the number of inputs feeding one output, and the number of outputs fed by one input.
- Variance propagation: tracking how carries a signal’s size from layer to layer.
- Xavier (Glorot) initialization: weight variance , for activations that are linear near 0.
- Kaiming (He) initialization: weight variance (or ), compensating for ReLU zeroing half its inputs.
- Gain: a factor on the standard deviation that corrects the initialization for a particular activation.
- Residual stream: the running sum a Transformer block adds its attention and MLP outputs to.
Summary
Section titled “Summary”- For with independent zero-mean weights, : the variance of a layer’s output is set by its fan-in and the weights’ variance.
- Xavier picks for layers that are linear near 0; Kaiming picks for ReLU, which zeroes half its inputs. With Kaiming the signal survives 20 ReLU layers; with Xavier it shrinks by about .
- A gain folds the activation’s effect into one factor; fans of a convolution or a Linear weight follow torch’s
(out, in, *kernel)rule. - GPT-2 scales residual output projections by so the stream’s added variance is independent of depth.
- Weights are drawn in row-major order, one draw per element, from the PCG32, so a seed fixes the model in every language.
Review questions
Section titled “Review questions”-
Why is ReLU’s gain and not 2?
Answer
The gain multiplies the standard deviation: Kaiming is . ReLU halves the second moment, so the variance must double: , which means . A gain of 2 would quadruple the variance and grow the mean square by per layer, after 20.
-
Why is the Xavier-uniform bound and not ?
Answer
The target is a variance, , and a uniform on has variance , not . Solving gives the factor 6. Using 2 would make the variance three times too small.
-
Why does
fansreadshape[1]as the fan-in?Answer
torch stores a Linear weight as
(out, in): row holds the weights that feed output , so the number of inputs summed into one output is the length of a row,shape[1]. Swapping the two only matters for non-square layers, which is why the example has different fans. -
What breaks if an initializer creates its own
PCG32(seed)instead of takingrng?Answer
Every layer of the same shape gets identical weights (two attention heads would compute the same thing and receive the same gradient), and changing the model’s seed does nothing. Passing one generator advances it by a known number of draws per layer, so the model is reproducible and different layers differ.
-
Why and not for the residual projections?
Answer
Each block adds two outputs to the stream, attention and MLP, so there are independent additions. Their variances add to ; setting makes the total at any depth. With the stream’s added variance would be twice the target.