MLDay 35 of 50Deep Learning
Keep Deep Nets Trainable
You stack ten layers instead of two, expecting a better model.
You stack ten layers instead of two, expecting a better model. Instead the accuracy sits at 10%, a blind guess among ten classes, or the loss reads 40 million. The network isn't too weak: its gradients are the wrong size.
The idea
Backpropagation multiplies local slopes on its way back from the loss (D30). In a deep network, every layer multiplies the gradient by roughly the same factor. Call it .
- If is below 1, the gradient shrinks at every layer. By the first layers it has vanished: their weights barely move, so they never learn.
- If is above 1, the gradient grows at every layer. It explodes: the updates are huge and the loss blows up.
- Only close to 1 keeps every layer learning.
The factor comes from two things: how much the activation lets through, and how big the weights are. Two fixes follow.
- He initialization draws the starting weights at the size that makes = 1 for ReLU.
- Batch normalization (BatchNorm) rescales each layer's outputs during training, so their size can't drift. For each unit, it subtracts the batch's mean and divides by the batch's standard deviation. Two learned numbers then set a new scale and shift.
A tiny example
Send a gradient of size 1 back through a chain of layers that each multiply it by the same :
| Layers back | |||
|---|---|---|---|
| 1 | 0.5 | 1 | 2 |
| 2 | 0.25 | 1 | 4 |
| 5 | 0.031 | 1 | 32 |
| 10 | 0.001 | 1 | 1,024 |
A factor of 0.5 per layer looks harmless, but after 10 layers it leaves a thousandth. A factor of 2 turns the same gradient into a thousand.
The formula
Through layers, the gradient reaching layer 1 is about times the one at the last layer:
| Symbol | Meaning |
|---|---|
| the size of the gradient arriving at layer (1 is next to the input) | |
| the number of layers | |
| the activation's factor: ReLU zeroes about half its units, which halves the gradient's squared size, so ; sigmoid's slope is at most 0.25 | |
| the standard deviation (std) of the starting weights | |
| the inputs each unit adds up |
Worked: with std 1 and 128 inputs, . Ten layers () give : an exploding gradient.
He initialization picks the std that makes , which cancels ReLU's 0.71:
| Symbol | Meaning |
|---|---|
| the std of the normal distribution the layer's starting weights are drawn from | |
| the layer's inputs (its fan-in) |
Worked: gives , so . A first layer that reads 784 pixels gets the smaller .
Try it
Find the setting that keeps every layer learning
Model: going back one layer multiplies the gradient by f = (activation factor) × (weight gain). Sigmoid's slope is at most 0.25, so take 0.25. ReLU's slope is 1 on the units that are on and 0 on the rest; about half are on, so take √½ ≈ 0.71. Weight gain = weight std × √n, with n = 64 inputs per unit: naive std 1 gives 8; He std √(2/64) ≈ 0.177 gives 1.41.
Dashed lines: 10⁻³ (below it the gradient has vanished) and 10³ (above it, exploded). Red bars are past a line.
f = 0.71 × 8 = 5.657 per layerlayer 1 gets f9 = 5.9 × 10⁶exploding: the updates blow up
It starts with ReLU, naive (std 1) and 10 layers: layer 1 gets , so it explodes. The widget assumes 64 inputs per unit, so its is 5.657. Click He (std √(2/n)): becomes 1, and so does every layer's gradient. Then switch to sigmoid: even with He, layer 1 gets only . Drag the layers slider to find the depth where it starts to vanish (past 7).
In code
A 10-layer MLP on the Fashion-MNIST slice: 784 pixels into nine hidden layers of 128 ReLU units, then 10 classes. The split, batches, Adam optimizer and seeds follow the D33 baseline. The script builds four versions: two naive inits that use one std for every layer (0.01 and 1), He, and BatchNorm on the std-0.01 init. It measures the gradient arriving at each layer, on one batch of 256 images, before any training:
# script_id: day_035_trainable_deep_nets/depth
import os
from pathlib import Path
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X_tr, X_val, y_tr, y_val = map(torch.tensor, train_test_split(
d["X_train"].astype("float32") / 255, d["y_train"], test_size=1000, stratify=d["y_train"], random_state=42))
def deep_mlp(init: str, batchnorm: bool = False) -> nn.Sequential:
torch.manual_seed(42)
layers = [nn.Flatten()]
for n_in in [784] + [128] * 8: # nine hidden layers
layers += [nn.Linear(n_in, 128)] + ([nn.BatchNorm1d(128)] if batchnorm else []) + [nn.ReLU()]
model = nn.Sequential(*layers, nn.Linear(128, 10)) # 10 Linear layers in all
for layer in model:
if isinstance(layer, nn.Linear):
if init == "he":
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu") # std sqrt(2 / n_in)
else:
nn.init.normal_(layer.weight, std=float(init)) # one std for every layer
nn.init.zeros_(layer.bias)
return model
def gradient_sizes(model: nn.Sequential, xb: torch.Tensor, yb: torch.Tensor) -> list[float]:
"""The size (norm) of the gradient arriving at each Linear layer's output, layer 1 first."""
outputs, h = [], xb
for layer in model:
h = layer(h)
if isinstance(layer, nn.Linear):
h.retain_grad() # keep this in-between tensor's gradient
outputs.append(h)
nn.CrossEntropyLoss()(h, yb).backward()
return [out.grad.norm().item() for out in outputs]
setups = {"std 0.01": ("0.01", False), "std 1": ("1", False), "He": ("he", False),
"std 0.01 + BatchNorm": ("0.01", True)}
sizes = {name: gradient_sizes(deep_mlp(*s), X_tr[:256], y_tr[:256]) for name, s in setups.items()}
for name, g in sizes.items():
print(f"{name:21s} layer 1: {g[0]:.1e} layer 10: {g[-1]:.1e}")
std 0.01 layer 1: 9.0e-12 layer 10: 5.9e-02
std 1 layer 1: 1.3e+07 layer 10: 8.4e-02
He layer 1: 6.8e-02 layer 10: 6.0e-02
std 0.01 + BatchNorm layer 1: 3.1e-01 layer 10: 5.9e-02
Every version gets 0.06–0.08 at layer 10, next to the loss. Going back, std 0.01 shrinks it to by layer 1, and std 1 grows it to : a factor of , close to the formula's . He holds it near 0.06 at every layer. BatchNorm, on the same std 0.01, keeps it between 0.06 and 0.31, about a factor of 5. This one-batch check costs a single backward pass, so run it on any new deep net before a long training run. Now train each for 10 epochs:
# script_id: day_035_trainable_deep_nets/depth
def train(model: nn.Sequential, epochs: int = 10) -> tuple[float, float]:
loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True,
generator=torch.Generator().manual_seed(42))
opt, loss_fn = torch.optim.Adam(model.parameters(), lr=1e-3), nn.CrossEntropyLoss()
model.train() # BatchNorm uses each batch's own mean and std
for _ in range(epochs):
for xb, yb in loader:
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
model.eval() # BatchNorm now uses the mean and std it averaged over training
with torch.no_grad():
logits = model(X_val)
return loss_fn(logits, y_val).item(), (logits.argmax(1) == y_val).float().mean().item()
for name, s in setups.items():
loss, acc = train(deep_mlp(*s))
print(f"{name:21s} validation loss {loss:9.3g} accuracy {acc:.3f}")
std 0.01 validation loss 2.3 accuracy 0.100
std 1 validation loss 3.95e+07 accuracy 0.654
He validation loss 0.447 accuracy 0.835
std 0.01 + BatchNorm validation loss 0.532 accuracy 0.809
With std 0.01 the net never beats a blind guess (0.100), and with std 1 the loss is 40 million. He reaches 0.835, level with D33's one-hidden-layer baseline (0.840). BatchNorm takes the std-0.01 net from 0.100 to 0.809 without touching its init. The chart shows the gradient sizes from the first run:
# script_id: day_035_trainable_deep_nets/depth
import matplotlib.pyplot as plt
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
layer_ids = range(1, 11)
for (name, g), color, marker in zip(sizes.items(), ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"], "os^D"):
ax.plot(layer_ids, g, color=color, marker=marker, lw=2, ms=6, label=name)
ax.set(yscale="log", xlabel="layer (1 = nearest the input)", ylabel="gradient size (log scale)",
xticks=list(layer_ids), title="Only He and BatchNorm keep the gradient in a narrow band")
ax.title.set_fontsize(10)
ax.grid(alpha=0.3)
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()
fig.savefig(FIG_DIR / "gradient_sizes.png", dpi=120)
plt.close(fig)

Quick check
Quick check
1. Each layer multiplies the gradient by f = 0.5. What reaches a layer 10 layers back from a gradient of 1?
2. A ReLU layer has 512 inputs. Which starting std does He initialization use?
3. A 10-layer net's validation accuracy is stuck at 0.10 on 10 classes. Layer 1's gradient is 10⁻¹¹; layer 10's is 0.06. What is wrong?
Next
D36: Regularize Networks: Dropout and Weight Decay takes a network that trains well and stops it memorizing the training set.
Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.