Skip to content

MLDay 35 of 50Deep Learning

Keep Deep Nets Trainable

You stack ten layers instead of two, expecting a better model.

9 min read

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 ff.

  • If ff 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 ff is above 1, the gradient grows at every layer. It explodes: the updates are huge and the loss blows up.
  • Only ff 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.

  1. He initialization draws the starting weights at the size that makes ff = 1 for ReLU.
  2. 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 ff:

Layers back f=0.5f = 0.5 f=1f = 1 f=2f = 2
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 LL layers, the gradient reaching layer 1 is about fL−1f^{L-1} times the one at the last layer:

g1≈f L−1 gL,f=a⋅σning_1 \approx f^{\,L-1}\, g_L, \qquad f = a \cdot \sigma \sqrt{n_{in}}
Symbol Meaning
gkg_k the size of the gradient arriving at layer kk (1 is next to the input)
LL the number of layers
aa the activation's factor: ReLU zeroes about half its units, which halves the gradient's squared size, so a≈1/2≈0.71a \approx \sqrt{1/2} \approx 0.71; sigmoid's slope is at most 0.25
σ\sigma the standard deviation (std) of the starting weights
ninn_{in} the inputs each unit adds up

Worked: with std 1 and 128 inputs, f=0.71×1×128=8.0f = 0.71 \times 1 \times \sqrt{128} = 8.0. Ten layers (L=10L = 10) give 8.09≈1.3×1088.0^9 \approx 1.3 \times 10^8: an exploding gradient.

He initialization picks the std that makes σnin=2\sigma \sqrt{n_{in}} = \sqrt{2}, which cancels ReLU's 0.71:

σ=2nin\sigma = \sqrt{\frac{2}{n_{in}}}
Symbol Meaning
σ\sigma the std of the normal distribution the layer's starting weights are drawn from
ninn_{in} the layer's inputs (its fan-in)

Worked: nin=128n_{in} = 128 gives σ=2/128=0.125\sigma = \sqrt{2 / 128} = 0.125, so f=0.71×0.125×128=1.0f = 0.71 \times 0.125 \times \sqrt{128} = 1.0. A first layer that reads 784 pixels gets the smaller σ=2/784≈0.051\sigma = \sqrt{2/784} \approx 0.051.

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.

Activation:
Initialization:
110⁵12345678910layer 1: gradient size 5.9 × 10⁶layer 2: gradient size 1 × 10⁶layer 3: gradient size 1.9 × 10⁵layer 4: gradient size 3.3 × 10⁴layer 5: gradient size 5.8 × 10³layer 6: gradient size 1 × 10³layer 7: gradient size 181.019layer 8: gradient size 32layer 9: gradient size 5.657layer 10: gradient size 1layer (1 = nearest the input)gradient size (log scale)

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 5.9×1065.9 \times 10^6, so it explodes. The widget assumes 64 inputs per unit, so its ff is 5.657. Click He (std √(2/n)): ff becomes 1, and so does every layer's gradient. Then switch to sigmoid: even with He, layer 1 gets only 8.6×10−58.6 \times 10^{-5}. 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 9.0×10−129.0 \times 10^{-12} by layer 1, and std 1 grows it to 1.3×1071.3 \times 10^7: a factor of 1.6×1081.6 \times 10^8, close to the formula's 1.3×1081.3 \times 10^8. 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)

Only He and BatchNorm keep the gradient in a narrow band

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.

Next · Day 36 · 8 minRegularize Networks: Dropout and Weight Decay← Previous: Day 34 · Optimizers and Learning-Rate Schedules
Not tapped yet