Exercise: initialisation, normalisation and residual connections

Goal

By the end of this exercise you should be able to:

  • predict how the size of the signal and of the gradient changes through a deep stack, and choose initial weights that keep it,
  • compute batch and layer normalisation by hand, and explain the batch-statistics trap at test time,
  • explain the degradation problem and why residual connections y = x + F(x) let gradients through many blocks,
  • tell residual connections from U-Net skip connections,
  • (math) derive the variance rule for initial weights and the gradient of a residual stack.

The questions under By hand and Explore are for everyone. The Math questions (derive, prove) are for students who want the full treatment.

Background

Word Meaning
Size of a signal root mean square of the values of a layer, over a batch
Gain initial weights are normal with sd = gain / √fan-in; fan-in = number of inputs of a unit
Batch norm each unit: subtract its mean over the batch, divide by its sd; then a learned scale and shift; stored (running) statistics at test time
Layer norm each example: subtract the mean over its units, divide by their sd
Residual block y = x + F(x): the block learns a change of x
Degradation a deeper plain network trains worse than a shallower one

By hand

B1. Initial weights. (a) A dense ReLU layer with 100 inputs. Which standard deviation should its weights have? (b) A convolution with 3\times3 kernels on 64 input channels, followed by ReLU. What is its fan-in, and which standard deviation? (c) Why not set all weights to the same small value?

B2. A stack of linear layers (no bend), each multiplying the size of its input by the gain g. (a) Input size 1, g = 1.5: the size after 10 layers? (b) g = 0.5: after 10 layers? After 50? (c) What does this say about choosing g?

B3. A ReLU sets the negative half of its input to 0. (a) The input of a ReLU is symmetric about 0 with mean square 1. What is the mean square of its output? (b) Layers with gain 1 followed by ReLU: by which factor does the size (root mean square) change per layer? After 20 layers? (c) Which gain keeps the size?

B4. Normalisation by hand. A batch of three examples, two units: (1, 10), (3, 10), (5, 40) (one row per example). (a) Batch norm (\epsilon = 0, no scale and shift): the mean and variance of each unit, and the normalised batch. (b) Layer norm of the first example (1, 3, 5) of another layer. (c) Layer norm of (9, 13, 17). Compare with (b). What has been removed?

B5. The trap. (a) Batch norm in training mode on a batch of one example. What comes out, whatever the input? (b) Training images had grey values with mean 0.5 and sd 0.1 (stored statistics of the first layer, for simplicity on raw grey values). A new microscope gives 1.6v + 0.15 for the same sample. What are the mean and sd of the new images, and of the batch-norm outputs with the stored statistics? (c) Name two ways to fix (b) without new labels.

B6. Gradients through a chain of blocks; ignore the weights and keep one number per block. (a) Ten sigmoid layers: the slope is at most 0.25 per layer. By at most what factor does the gradient shrink? (b) Three plain blocks whose local derivatives are 0.1 each. The gradient at the top is 1: what reaches the bottom? (c) The same blocks with residual connections: each passes 1 + 0.1. What reaches the bottom now? (d) Plain blocks with derivative 1.5 each, 20 blocks: what happens?

B7. Residual or U-Net skip? For each, say which kind: (a) the encoder’s 64\times64 feature map is concatenated with the decoder’s upsampled map; (b) a block outputs x + \text{conv}(\text{ReLU}(\text{conv}(x))); (c) a transformer layer outputs x + \text{attention}(\text{LN}(x)).

B1. (a) \sqrt{2/100} = 0.141 (He). (b) Fan-in 3 \cdot 3 \cdot 64 = 576; \sqrt{2/576} = 0.059. (c) All units of a layer would compute the same and get the same gradient, so they would stay equal for ever: random weights break the symmetry.

B2. (a) 1.5^{10} = 57.7. (b) 0.5^{10} = 0.001, 0.5^{50} = 9 \times 10^{-16}. (c) Only g = 1 keeps the size; any other factor grows or shrinks geometrically with depth, so the deeper the network, the more exactly the initial scale must be right.

B3. (a) Half the values (the negative half) become 0, the others stay: mean square \tfrac12. (b) The mean square halves, so the size is multiplied by \sqrt{1/2} = 0.71 per layer; after 20 layers 0.71^{20} = 0.001. (c) Gain \sqrt2: the linear part doubles the mean square, the ReLU halves it.

B4. (a) Unit 1: mean 3, variance (4 + 0 + 4)/3 = 2.67, sd 1.63: (-1.22, 0, 1.22). Unit 2: mean 20, variance (100 + 100 + 400)/3 = 200, sd 14.1: (-0.71, -0.71, 1.41). Normalised batch: (-1.22, -0.71), (0, -0.71), (1.22, 1.41). (b) Mean 3, sd 1.63: (-1.22, 0, 1.22). (c) Mean 13, sd 3.27: (-1.22, 0, 1.22), the same. (9, 13, 17) = 2 \cdot (1, 3, 5) + 7: layer norm removes an offset and a scale of the whole example (its brightness and contrast).

B5. (a) All zeros: each value minus the mean of a batch of one (itself) is 0. (b) New mean 1.6 \cdot 0.5 + 0.15 = 0.95, sd 1.6 \cdot 0.1 = 0.16. Normalised with the stored statistics: mean (0.95 - 0.5)/0.1 = 4.5, sd 0.16/0.1 = 1.6: far outside anything the next layers saw in training. (c) Re-estimate the stored statistics on unlabelled images of the new microscope; normalise the input images (e.g. to mean 0, sd 1 per image) before the network; train with intensity augmentation.

B6. (a) 0.25^{10} \approx 10^{-6}. (b) 0.1^3 = 0.001. (c) 1.1^3 = 1.33: the identity path alone passes 1. (d) 1.5^{20} = 3300: the gradient explodes.

B7. (a) U-Net skip (concatenation across the U). (b) Residual (a ResNet block). (c) Residual, with layer norm (a transformer block).

Math questions

B8. (math) z = \sum_{i=1}^n W_i a_i with W_i independent, mean 0, variance \sigma^2, independent of the a_i. Show \operatorname{Var}(z) = n\sigma^2\,\mathbb E[a^2] (all a_i alike). If a = \text{ReLU}(z') for z' symmetric about 0, show \mathbb E[a^2] = \tfrac12\mathbb E[z'^2], and conclude that \sigma^2 = 2/n keeps \operatorname{Var}(z) from layer to layer.

B9. (math) Show that the output of batch normalisation (without \epsilon, before scale and shift) has mean 0 and variance 1 over the batch for every unit, and that it does not change when the weights of the layer below are multiplied by c > 0.

B10. (math) For \mathbf x_{l+1} = \mathbf x_l + F_l(\mathbf x_l), show \mathbf x_L = \mathbf x_l + \sum_{k=l}^{L-1}F_k(\mathbf x_k) and \partial\mathcal L/\partial\mathbf x_l = \partial\mathcal L/\partial\mathbf x_L\,\prod_{k=l}^{L-1}(I + J_k), with J_k the Jacobian of F_k. For scalars with J_k = j, compare (1 + j)^L with the plain j^L for j = 0.1 and L = 20.

B11. (math) Batch norm is followed by y = \gamma\hat z + \beta with learned \gamma, \beta. Show that the layer can still represent the identity on its batch, i.e. that normalisation does not restrict what the layer can output.

B8. (math) \mathbb E[z] = 0, and the cross terms vanish because the W_i are independent with mean 0: \operatorname{Var}(z) = \sum_i\mathbb E[W_i^2]\mathbb E[a_i^2] = n\sigma^2\mathbb E[a^2]. For a = \max(0, z') with z' symmetric: \mathbb E[a^2] = \mathbb E[z'^2\,\mathbb 1(z' > 0)] = \tfrac12\mathbb E[z'^2]. So \operatorname{Var}(z) = \tfrac12 n\sigma^2\operatorname{Var}(z'), which equals \operatorname{Var}(z') if \sigma^2 = 2/n.

B9. (math) \hat z_n = (z_n - \mu)/\sigma: the mean of z_n - \mu is 0, and the mean of (z_n - \mu)^2/\sigma^2 is \sigma^2/\sigma^2 = 1. With weights cW every z_n becomes cz_n, so \mu \to c\mu, \sigma \to c\sigma, and \hat z_n = (cz_n - c\mu)/(c\sigma) is unchanged.

B10. (math) Summing \mathbf x_{k+1} - \mathbf x_k = F_k(\mathbf x_k) from k = l to L - 1 gives the first formula (a telescoping sum). The chain rule through each block: \partial\mathbf x_{k+1}/\partial\mathbf x_k = I + J_k, and the product of these from l to L - 1. Scalars: (1.1)^{20} = 6.7, 0.1^{20} = 10^{-20}: the residual stack passes the gradient (here even a bit amplified), the plain stack loses it completely. With j near 0, (1 + j)^L \approx 1.

B11. (math) Choose \gamma = \sigma and \beta = \mu (of the batch): y_n = \sigma(z_n - \mu)/\sigma + \mu = z_n. So any output the layer could give without normalisation is still reachable; normalisation changes how the weights are parametrised (and makes training easier), not what can be represented.

Explore

A deep stack: a batch of 64 random inputs goes up through dense layers of 64 units, and a random gradient comes back down from the top. Top plot: the size of the activations (blue) and of the gradients (red) after each layer, on a log scale; the dashed line is 1. Below: histograms of the activations at five depths; values beyond ±3 pile up in the red end bins. Choose the bend, the gain of the initial weights, a normalisation, residual connections and the depth. Nothing is trained: this is what the first training step sees.

E1. Presets ReLU, gain 1: fades, gain √2: steady and gain 2: explodes (30 layers). Read the activation size at layer 30 and the gradient size at layer 1 for each. Compare with B3.

E2. Choose no bend and move the gain from 0.9 to 1.1. How sensitive is the size at layer 30? Then set 50 layers.

E3. Presets tanh, gain 0.5 and tanh, gain 3: saturates. What do the histograms look like? What happens to the gradient at layer 1 in each case?

E4. Preset sigmoid, gain 1. The activations look fine. What about the gradient? Why?

E5. Preset gain 2 + batch norm. Read the activation sizes. Now move the gain anywhere between 0.5 and 4: what changes? Look at the gradient at layer 1, too.

E6. Preset gain 1 + layer norm. Compare with E1 (gain 1 without normalisation).

E7. Preset sigmoid: plain vs residual. Read the gradient at layer 1 with the residual box ticked and unticked. Compare with B6.

E8. Presets plain, gain √2, 50 layers and residual, gain √2, 50 layers. Compare the gradient curves and the activation sizes. What grows in the residual stack, and why might real residual networks put a normalisation into every block?

E1. Gain 1: activations 1.6 \times 10^{-5} at layer 30, gradient at layer 1 2.6 \times 10^{-5} (of about 1 at the top). Gain \sqrt2: activations 0.52, gradient 0.60. Gain 2: activations 17,000, gradient 14,000. A factor \sqrt{1/2} = 0.71 per layer for gain 1 gives 0.71^{30} = 3 \times 10^{-5}, as B3 predicts; gain 2 gives \sqrt2 per layer, 1.41^{30} = 33{,}000.

E2. Without a bend, gain 1 keeps the size near 1 (1.5 at layer 30); 0.9 and 1.1 give about 0.9^{30} = 0.04 and 1.1^{30} = 17. At 50 layers the same 10 % error gives factors 0.005 and 117: the deeper the stack, the more exactly the scale must be right.

E3. Gain 0.5: the histograms shrink to a spike at 0 (size 10^{-9} at layer 30), and the gradient vanishes (3 \times 10^{-9} at layer 1). Gain 3: the values pile up at ±1 (tanh saturates; a quarter of the values have slope below 0.01), the size stays 0.84, but the gradient at layer 1 is 6000 times the top: large weights multiply it on the way back more than the saturated slopes shrink it.

E4. The activations stay near 0.5, but the gradient at layer 1 is 10^{-18}: the sigmoid’s slope is at most 0.25, so each layer shrinks the gradient by about 4 (B6). A forward pass that looks healthy can hide vanishing gradients.

E5. Every layer has size 0.71: each sum is normalised to mean 0 and sd 1, and the ReLU then gives \sqrt{1/2}. Changing the gain changes nothing in the forward pass (scale invariance, B9). The gradient at layer 1, however, is about 260 times the top: batch norm does not make the backward pass perfect.

E6. With layer norm, gain 1 no longer fades: the size stays near 0.7 at every layer (0.65 at layer 30), and the gradient at layer 1 is 0.46 instead of 2.6 \times 10^{-5}.

E7. Residual: gradient at layer 1 is 1.0 (of 0.98 at the top). Plain: 10^{-18}. The identity path passes the gradient unchanged; through the sigmoid layers alone it shrinks by about 4 per layer.

E8. Both keep a usable gradient at initialisation (plain: about 1.1 at layer 1; residual: about 7). But the residual stack’s activations grow, to about 41 at layer 50: every ReLU block adds a positive change to the signal. Normalisation inside each block (as in ResNet and transformers) keeps the blocks’ inputs at a fixed size while the identity path carries the signal and the gradient. The plain stack keeps its size only for this one carefully chosen gain, and loses it again as training changes the weights; in the course code (below) the 50-block plain network stays at the guessing loss for 12 epochs.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in training/src/normalisation/exercise.rs.

C1. init_weights(fan_in, fan_out, gain, rng): normal weights with sd gain / sqrt(fan_in). The check is B1.

C2. batch_norm(z, eps): normalise each unit over the examples of the batch; return the means and variances.

for every unit j:
    mean = average over n of z[n][j]
    var  = average over n of (z[n][j] − mean)²
    for every example n:  z[n][j] = (z[n][j] − mean) / sqrt(var + eps)

The checks are B4(a) and B5(a).

C3. layer_norm(z, eps): the same over the units of one example. The check is B4(b, c).

C4. signal_sizes(depth, width, gain, act, norm, batch, seed): push a batch of random inputs through depth layers (init_weights, then the normalisation, then the bend) and record the size of every layer’s output. The checks are B2 and B3.

Then cargo run -p training -- normalisation. The program prints the signal sizes after layers 1, 2, 5, 10, 20 and 50 (64 units, batches of 128) for linear, ReLU and tanh stacks with several gains, with and without batch and layer norm; the gradient sizes on the way back; the batch-statistics trap with 8\times8 patches of the course micrograph; and finally it trains narrow networks (16 units per layer) with 2, 20 and 50 plain or residual blocks on a three-class spiral for 60 epochs (provided code in training/src/normalisation/resnet.rs). Plots in out/normalisation/.

C5. The signal table. Which settings keep the size within a factor 2 of 1 over 50 layers? Compare “ReLU, gain 1” with “ReLU, gain 1, batch norm”.

C6. The gradient table: tanh with gain 3 keeps the activations at size 0.83. What happens to its gradient, and why is that a problem too?

C7. The trap: what are the output mean and sd for new patches, for a batch of one, for the “other microscope”, and after re-estimating the statistics? Compare with B5.

C8. Plain vs residual: compare the training losses after 5, 20 and 60 epochs and the gradient sizes at the first block. Which network shows the degradation problem?

The model solution is training/src/normalisation/solution.rs in the download.

C5. Linear with gain 1 (1.0 to 1.95), ReLU with gain \sqrt2 (0.37 to 1.03), and every stack with batch or layer norm (0.67 to 0.74); tanh with gain 3 also stays at 0.83, by saturating. ReLU with gain 1 falls to 1.1 \times 10^{-8} at layer 50; with batch norm it stays at 0.71 at every layer.

C6. Its gradient explodes: 3.5 \times 10^6 at layer 1, from about 1 at the top. The weights are large, and the saturated units pass little but the unsaturated ones multiply by the large weights. Steps of plain gradient descent would throw the first layers’ weights anywhere; a healthy forward pass does not guarantee a healthy backward pass.

C7. Training patches after batch norm: mean 0.000, sd 1.000. New patches with the stored statistics: mean 0.029, sd 0.976. A batch of one: every output 0. The other microscope: mean 1.145, sd 0.613 (the bright parts are clipped at 1, so the sd grows less than ×1.6). Re-estimated on 50 patches: mean 0.077, sd 1.031. As in B5: the shift is large, and re-estimating the statistics on unlabelled images repairs it.

C8. Training loss at epochs 5, 20, 60: 2 plain blocks 0.581, 0.172, 0.037; 20 plain 0.615, 0.155, 0.131; 50 plain 1.099, 1.013, 0.101 (it sits at \ln 3, guessing, for 12 epochs); 20 residual 0.125, 0.034, 0.022; 50 residual 0.221, 0.114, 0.029. The deeper plain networks train worse than the 2-block network on the training data itself: the degradation problem. Gradient at the first block (first batch): 0.068 (2 plain), 0.0066 (20 plain), 9.8 \times 10^{-5} (50 plain), 0.089 (20 residual), 0.14 (50 residual).

Where this leads

Residual blocks with normalisation are the building blocks of the U-Nets and encoders of the cell networks, of the transformers of the attention unit (layer norm, never batch norm) and of diffusion models. The batch-statistics trap returns as domain shift: a model trained on one microscope that fails on another (the evaluation day). The next unit turns to the data: overfitting on small data sets, and augmentation.