Trace activation spread through deep ReLU layers for Xavier and He init

Why it matters Choosing the wrong init is a classic reason a deep CNN or MLP refuses to train from step one.

The point of an init scheme is what happens to the signal 10 layers deep. Measuring it beats memorising formulas.

Write init_std_trace(n_layers, width, scheme, seed, n=256). Make rng = np.random.default_rng(seed). Draw the input X = rng.standard_normal((n, width)). Then for each layer draw W = rng.standard_normal((width, width)) * scale and set X = relu(X @ W), with no bias. scale is sqrt(2 / (fan_in + fan_out)) for "xavier" and sqrt(2 / fan_in) for "he" (fan_in = fan_out = width here). Return a float array of length n_layers with the standard deviation of X (over all entries) after each layer. Draw in exactly this order so results are reproducible.

Signaturedef init_std_trace(n_layers, width, scheme, seed, n=256)

Example

init_std_trace(3, 64, "he", 0) is about [0.8153, 0.8371, 0.8399]: He keeps the spread flat, while "xavier" shrinks it by about 0.7 per layer.

Understand the idea

Every layer multiplies the signal by a random matrix. If each multiplication makes it a little smaller, after 20 layers there is almost nothing left; a little bigger and it blows up. Like a rumour passed along a line, a tiny change per person adds up.

Tiny example: with width 64, each output is a sum of 64 terms x_i * w_i. Its variance is 64 * var(x) * var(w). To keep variance the same we need var(w) = 1 / 64. ReLU then throws away the negative half, cutting the second moment in half, so He doubles it: var(w) = 2 / 64.

Rules: Xavier std = sqrt(2 / (fan_in + fan_out)), He std = sqrt(2 / fan_in).

PyTorch's kaiming_normal_ and xavier_uniform_ apply exactly these scales, and ResNets use He init by default.

Shapes and data flow

X (n, width) -> X @ W (n, width) -> relu -> next layer
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleinit_std_trace(3, 64, 'he', 0)
  • Sample 2: xavier shrinksinit_std_trace(6, 32, 'xavier', 1)
  • Test 3: he deepinit_std_trace(6, 32, 'he', 1)