Week 04 · Initialization and gradient flow

Measure how repeated multiplication suppresses or amplifies gradients.

← Week 3 · Subject contents · Week 5 →

Measure how repeated multiplication suppresses or amplifies gradients.

Work through the problem

For independent zero-mean inputs and weights, the second moment of a linear layer scales roughly with fan-in times weight variance. ReLU keeps about half the second moment under a symmetric input distribution. He initialization uses variance 2/fan-in to compensate in that approximation.

Even a simple chain exposes the mechanism. If hₗ = a hₗ₋₁ for L layers, ∂hₗ/∂h₀ = aᴸ. At L=20 and a=0.5 the gradient is roughly 10⁻⁶. At a=1.2 it is about 38.3. Real networks add changing directions and activation gates, so measure actual layer norms.

Gradients multiply across layers. Gradient magnitude by depth. Series: 0.5, 1.0, 1.2.

Gradients multiply across layers.

Run the Python lab

import numpy as np
import torch
depth = np.arange(1,21)
curves = {}
for a in [.5,1.,1.2]:
    x = torch.tensor(1.,dtype=torch.float64,requires_grad=True)
    y = x
    for _ in depth:
        y = y*a
    y.backward()
    print(a, f"{x.grad.item():.6g}")
    curves[str(a)] = a**depth
    assert np.isclose(x.grad.item(),a**20)

Output from the lab

0.5 9.53674e-07
1.0 1
1.2 38.3376

Practice

  1. Is initialization the only explanation for a small gradient?

Check your reasoning

  1. No. Saturating activations, a nearly solved task, and upstream masking can also make it small.

← Week 3 · Subject contents · Week 5 →

Further reading · Goodfellow, Bengio, and Courville · Deep Learning