Initialization and Normalization Layers: Measuring Activations and Gradients per Layer and Stabilizing Training with BN and LN

Sunhong··14 min read·0 views·Translated from Korean

Key points of this post

  • A neural network multiplies by weights at every layer, so the size of the activations is also multiplied by the same factor at every layer. If the factor is below 1 they vanish, and if above 1 they explode. In a 20-hidden-layer ReLU network started with weight standard deviation 0.01, the activation standard deviation at the last layer was 7×10−207 \times 10^{-20}, with Xavier 3.3×10−43.3 \times 10^{-4}, and with He (variance 2/n2/n) 0.34, almost unchanged across layers.
  • Normalization layers (BN, LN) fix this size directly at every layer. A 12-hidden-layer network started with small initialization had 11.3% accuracy after 3 epochs (training failed), but with batch normalization (BN) it reached 96.6%. Layer normalization (LN) got 11.3% in the same setting at learning rate 0.01 and 95.0% at 0.001.
  • BN depends on the other samples in the same batch. Evaluating the way it is used in training, 2 samples at a time, dropped accuracy to 25.6%, while eval mode with stored mean and variance gave 96.9%. LN gave the same 96.5% whether fed one sample or 1,000.

This is the fifth post in the AI Note series. In part 2 we introduced He initialization in one line, "keep the output variance of ReLU layers from changing much across layers", and part 4 covered optimizers. This post looks at the basis for that one line, in formulas and measurements: why signals vanish or explode as layers stack, the initializations that prevent it (Xavier, He), and normalization layers (batch normalization, layer normalization) that fix the size between layers altogether. We restate the needed formulas so you can follow without having read earlier parts.

1. Why a neural network is hard from the start

The forward pass of a network with several hidden layers is the same thing repeated: multiply the values by a matrix, pass through an activation function, multiply again. Simplify drastically and say the values are multiplied by a constant factor aa per layer. Starting from size 1, the size after 20 layers is a20a^{20}.

Factor per layer aa 0.5 0.9 1.0 1.1 1.5
Size after 20 layers a20a^{20} 9.5×10−79.5 \times 10^{-7} 0.12 1 6.7 3,325

A small departure from 1 changes the size a lot once the network is deep. Backpropagation is the same, because the gradient comes back through the same weight matrices in reverse. If the gradient in the early layers is near 0, learning hardly happens (vanishing), and if it is large, learning diverges (exploding). So "what size to draw the weights at first" decides success or failure.

2. Initialization that preserves variance

Say we draw the weights from a normal distribution with mean 0 and variance σ2\sigma^2. If a layer has nn inputs, each with mean 0 and size E[x2]E[x^2], then under independence the variance of one output y=∑i=1nwixiy = \sum_{i=1}^{n} w_i x_i is

Var(y)=n⋅σ2⋅E[x2]\mathrm{Var}(y) = n \cdot \sigma^2 \cdot E[x^2]

In words: the contributions of nn inputs add up, and larger weights give a larger size. Now pass through ReLU. ReLU turns negatives into 0, so the mean square of the output is half the variance of the symmetric yy. So the mean square gets multiplied by nσ2/2n\sigma^2/2 per layer. To make this factor 1, set

σ2=2n(He initialization)\sigma^2 = \frac{2}{n} \quad (\text{He initialization})

where nn is the number of inputs to the layer (fan-in). Xavier (Glorot) initialization is σ2=1/n\sigma^2 = 1/n, a value that assumes linear or origin-symmetric activations like tanh and ignores the half lost to ReLU. Used in a ReLU network, the factor per layer is 1/21/2, or 1/2≈0.711/\sqrt{2} \approx 0.71 in standard deviation.

Backpropagation follows the same logic. The gradient comes back multiplying by the transposes of the weight matrices, and the number of terms summed then is not the number of inputs but of outputs (fan-out). So as a compromise that satisfies both forward and backward passes, Xavier initialization uses the average of input and output counts, σ2=2/(nin+nout)\sigma^2 = 2/(n_{\text{in}} + n_{\text{out}}) (the same as 1/n1/n for layers of equal width). The He initialization in this post uses only the input count. Preserving the forward size was enough in this post's experiments, and for layers whose input and output counts differ greatly, you have to choose which side to match.

Let us compute the per-layer mean-square factor for a width-256 network with three initializations.

Initialization σ2\sigma^2 Factor per layer nσ2/2n\sigma^2/2 Std factor per layer
Small value σ=0.01\sigma = 0.01 10−410^{-4} 256×10−4/2=0.0128256 \times 10^{-4} / 2 = 0.0128 0.113
Xavier 1/2561/256 0.5 0.707
He 2/2562/256 1.0 1.0

With the small value 0.01, the standard deviation shrinks by 0.113 per layer. Over 20 layers that is 0.11319≈10−180.113^{19} \approx 10^{-18}. Let us verify in a figure.

3. Experiment 1: activations and gradients measured over 20 layers

20 hidden layers (width 256, ReLU), no normalization. The input is 512 MNIST images, the weights are drawn the three ways above, and we ran one forward pass and one backward pass, measuring the standard deviation of the activation (ReLU output) and the norm of the weight gradient at each layer.

Per-layer statistics of a 20-hidden-layer network. With small init the activation std vanishes from 0.054 at layer 1 to 7e-20 at layer 20, with Xavier it shrinks to 3.3e-4, and with He it stays at 0.28 to 0.34. The weight gradient norm is about 1e-19 for small init and about 1 for He

Layer 1 5 10 20
Small value σ=0.01 0.054 9.6×10−69.6 \times 10^{-6} 1.9×10−101.9 \times 10^{-10} 7.0×10−207.0 \times 10^{-20}
Xavier 0.19 0.053 0.010 3.3×10−43.3 \times 10^{-4}
He 0.28 0.30 0.32 0.34

The small value's standard deviation fell from 0.0540.054 to 7×10−207 \times 10^{-20} between layers 1 and 20, about 10−1810^{-18} times, matching the calculation. Xavier went from 0.190.19 to 3.3×10−43.3 \times 10^{-4}, about 1/600 (theory: 0.70719≈1/7200.707^{19} \approx 1/720). Only He stays constant across layers. The weight gradient norms tell the same story. The small value is around 10−1910^{-19} in every layer, so even after a step the weights barely move, while He is around 1, similar across layers.

4. Normalization layers: fix the size at every layer directly

Initialization sets the size only at the start. As learning proceeds the weights change and the size can go off again. So what if we insert, between layers, an operation that makes the activations mean 0 and variance 1 and fix it every time? That is a normalization layer. The formula is the same for both.

x^=x−μσ2+ϵ,y=γx^+β\hat{x} = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}}, \qquad y = \gamma \hat{x} + \beta

μ\mu and σ2\sigma^2 are the mean and variance, and ϵ\epsilon is a small number that prevents division by zero (PyTorch default 10−510^{-5}). γ\gamma and β\beta in the second formula are learned values: after fixing mean 0 and variance 1, they let the model change the scale and position again if it wants. The only difference between the two is along which direction the mean and variance are computed.

  • Batch Normalization (BN): gather the values of the same feature (a column) across all samples in the batch to get the mean and variance.
  • Layer Normalization (LN): gather all features of a single sample (a row) to get the mean and variance.

In a table of 3 samples and 3 features, BN gathers one column and normalizes it (1, 10, 0 with mean 3.67, std 4.50), and LN gathers one row (1, 2, 6 with mean 3.00, std 2.16)

Let us follow by hand. The table above (rows are samples, columns are features) is [[1,2,6],[10,20,30],[0,0,3]][[1, 2, 6], [10, 20, 30], [0, 0, 3]].

Operation Gathered values Mean Std Normalized result
BN (first column) 1, 10, 0 3.67 4.50 −0.59, 1.41, −0.82
LN (first row) 1, 2, 6 3.00 2.16 −0.93, −0.46, 1.39

(The standard deviation is the square root of the mean squared deviation; for the first column, (1−3.67)2+(10−3.67)2+(0−3.67)2=60.67(1-3.67)^2 + (10-3.67)^2 + (0-3.67)^2 = 60.67, divided by 3 is 20.22, whose square root is 4.50.) Whatever the size of the incoming values, the result has mean 0 and standard deviation 1.

Explanations of why BN works differ between studies. The original paper explained that it reduces the continual shift of the distribution of layer inputs during training (internal covariate shift), but later work argued that it instead smooths the loss surface, allowing larger learning rates (see references). This post's experiments point the same way as the latter: it let training work even with a large learning rate or bad initialization. Also, since the β\beta after BN plays the role of a bias, the bias of the linear layer before BN is not needed.

BN uses the current batch for the mean and variance during training, but at inference there may be only one sample, so it uses the moving averages accumulated during training (running mean, running var). LN computes only within a single sample, so training and inference are the same and it does not depend on batch size. That is why LN is used in sequence models (RNNs, transformers), where lengths vary and batches are small. In large language models RMSNorm, which does not subtract the mean and divides only by the magnitude (RMS), is common, but we did not measure it in this post.

Correctness check

We compared the formulas above written directly against PyTorch's BatchNorm1d and LayerNorm (batch 32, 6 features, 64-bit).

Comparison Max difference
BN train mode (batch statistics) 4.4×10−164.4 \times 10^{-16}
BN eval mode (running statistics) 2.2×10−162.2 \times 10^{-16}
LN 8.9×10−168.9 \times 10^{-16}

They agree within floating-point error.

5. Experiment 2: training a 12-hidden-layer network

Now we actually train. 12 hidden layers (width 128, ReLU), momentum SGD (learning rate 0.01, momentum 0.9), batch 128, 3 epochs, 60,000 MNIST training images, 10,000 test images. We varied the initialization, and also put BN or LN between the linear layer and ReLU with small or He initialization. One seed.

Test accuracy of the 12-hidden-layer network after 3 epochs. Small init 11.3%, large init diverged, Xavier 94.4%, He 96.0%. Adding BN to small init gives 96.6%, LN gives 11.3% and with learning rate 0.001 gives 95.0%. He+BN 96.9%, He+LN 96.5%

Setting Test accuracy
Small init σ=0.01 11.3% (no learning, loss stuck at 2.30)
Large init σ=0.5 diverged (first loss 9.2×1079.2 \times 10^7, NaN)
Xavier 94.4%
He 96.0%
Small init + BN 96.6%
Small init + LN 11.3%
Small init + LN, learning rate 0.001 95.0%
He + BN 96.9%
He + LN 96.5%

What we can read:

  • If initialization is wrong, learning cannot even start. The small value did not move from loss 2.30 (=ln⁡10= \ln 10, the value for guessing among 10 classes), and the large value diverged with a first loss of 10710^7.
  • With ReLU, He is better than Xavier. 96.0% vs 94.4% on the same 12 layers. The gap is likely to widen with depth (estimate; we measured only up to 12 layers).
  • BN makes initialization matter less. Adding BN to small initialization gave 96.6%, higher than He initialization (96.0%), because BN re-fixes the size at every layer.
  • LN was sensitive to the learning rate with small initialization. At learning rate 0.01 it got 11.3%, and lowering to 0.001 gave 95.0%. Weights before a normalization are scale-invariant (changing their scale leaves the output the same), so the gradient is inversely proportional to the weight size. With small weights the same learning rate is effectively a much bigger step, and it seems to have broken down in the first few steps (estimate; we did not run an experiment to confirm this cause). BN trained in the same condition.

With one seed, rankings of 1 to 2 point differences such as 94.4 vs 96.0 are hard to settle, and only large differences like training failure vs success can be trusted.

6. The weakness of BN: it depends on the batch

With BN, the output for one sample changes depending on the other samples in the same batch. We checked what problem this causes in practice with the He + BN and He + LN networks from the experiment above, evaluating the 10,000 test images with varying batch sizes. BN's "train mode" uses the current batch's mean and variance exactly as in training.

Evaluation method Accuracy
BN, eval mode (running statistics) 96.9%
BN, train mode, batch 1,000 96.5%
BN, train mode, batch 8 72.5%
BN, train mode, batch 2 25.6%
LN, batch 1 96.5%
LN, batch 1,000 96.5%

As the batch gets smaller, the batch's mean and variance become unstable, BN's output wobbles, and at batch 2 accuracy dropped to 25.6%. This is why BN uses stored statistics at inference. A problem remains, though: if the batch is too small during training, or the data distribution differs between training and inference, these moving averages do not fit. LN looks at only one sample, so the result is the same at batch 1 or 1,000.

The setup is the CPU of a MacBook Pro M1 Max (4 threads), PyTorch 2.15.0, NumPy 2.5.4, Python 3.12.13. The 20-layer statistics and the correctness check took a few seconds, the 9 training runs (3 epochs each) 44 seconds, 54 seconds in all. These times were measured while the Mac was shared with other jobs. We made the networks small (width 128 to 256, 12 to 20 hidden layers), cut epochs to 3, and trained with one seed. The original BN and LN papers dealt with large-scale image classification and recurrent networks, and we did not reproduce results at that scale.

7. Summary

  • The activation size gets multiplied by a constant factor at every layer, so if the factor departs from 1 it vanishes or explodes exponentially with depth. In ReLU, He initialization (σ2=2/n\sigma^2 = 2/n) makes the factor 1, while Xavier (1/n1/n) shrinks the standard deviation by 0.71 per layer.
  • Measured over 20 layers, small initialization made activations vanish from 0.0540.054 to 7×10−207 \times 10^{-20}, Xavier reached 3.3×10−43.3 \times 10^{-4}, and He held at 0.34, matching the calculations.
  • BN makes mean 0 and variance 1 along columns (the batch direction), LN along rows (the features of one sample). A 12-layer network started with small initialization went from 11.3% to 96.6% with BN.
  • BN depends on batch size, so evaluating 2 samples at a time the way it is trained gave 25.6%. LN is independent of the batch.

Next post: Now we have the tools to train deep networks stably. But high training accuracy does not mean it will fit new data. In part 6 we measure generalization and overfitting with training and test error, and run experiments on how weight decay, dropout, data augmentation and early stopping narrow the gap, and on double descent, where the error comes down again as the model gets bigger.

References

Similar posts