Deep learning in practice · lesson 9 of 13
Parts in this lesson
Areturn x + self.two(F.relu(self.one(x)))a residual block: the input, plus a change worked out by two layers
Bnn.ModuleList(Block(width, blocks) for _ in range(blocks))a list of layers that PyTorch registers as part of the model
Cfrom nets import Plain, Residualthe two networks live in nets.py, which both scripts import

Residual connections

Last updated

With good starting weights and normalisation, a 20-layer network trains. Make it 50 layers and it gets worse, even on its own training data. Residual connections fix this with one small change: each block adds its output to its input instead of replacing it. This lesson shows the problem, builds the fix, and follows the gradient along the shortcut that makes it work. Almost every deep network since 2015 has these shortcuts.

By the end of this lesson you can

  • Describe the degradation problem, and say why it isn't overfitting
  • Write a residual block, y = F(x) + x, as a PyTorch module
  • Explain why the shortcut keeps gradients flowing to the first layers

The degradation problem

A deeper network can do everything a shallower one can. Take a good 20-layer network, add 30 layers that each pass their input straight through unchanged, and you have a 50-layer network that's exactly as good. So training the 50-layer network should find something at least that good.

In 2015, He and colleagues found it doesn't. Their 56-layer plain network had a higher training error than their 20-layer one, even with batch norm and good initialisation. That rules out the usual suspects:

  • It isn't overfitting: an overfitting network does better on its training data, and worse only on new data. This one is worse at both.
  • It isn't vanishing gradients at the start: with He initialisation and batch norm, the gradients started a sensible size.

It's an optimisation problem. Copying the input through unchanged is a hard thing for a layer of Linear and ReLU to learn: it needs exactly the right weights, and gradient descent doesn't find them. They called it the degradation problem. Step 4 reproduces it on the digits.

y = F(x) + x

The fix: if passing the input through is hard to learn, build it in. A residual block adds its input to what its layers compute:

y=F(x)+x

In words: the block's layers work out F(x), a change, and the block outputs the input plus that change. The connection that carries x around the layers is a shortcut (or skip connection). Now "do nothing" is easy: F=0, which any block gets by making its last weights small. Each block only has to learn how its input should differ, which is often a small correction. F is called the residual, the part left over, which gives the networks their name: ResNets.

Here are both networks, each with depth Linear layers in all. A residual block here has two layers with a ReLU between, as in He's paper:

"""The two networks lesson 7.9 compares, both with `depth` Linear layers and He initialisation."""
import math

import torch
from torch import nn
from torch.nn import functional as F


def he(layer, scale=1.0):
    nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
    with torch.no_grad():
        layer.weight *= scale
    nn.init.zeros_(layer.bias)
    return layer


class Plain(nn.Module):
    """Linear, ReLU, Linear, ReLU, ...: each layer's output replaces its input."""

    def __init__(self, depth, width=64):
        super().__init__()
        self.layers = nn.ModuleList([he(nn.Linear(64, width))] + [he(nn.Linear(width, width)) for _ in range(depth - 2)])
        self.last = he(nn.Linear(width, 10))

    def forward(self, x):
        for layer in self.layers:
            x = F.relu(layer(x))
        return self.last(x)


class Block(nn.Module):
    """y = x + F(x), where F is two Linear layers with a ReLU between them."""

    def __init__(self, width, blocks):
        super().__init__()
        self.one = he(nn.Linear(width, width))
        self.two = he(nn.Linear(width, width), scale=1 / math.sqrt(blocks))  # each block starts by adding a small change

    def forward(self, x):
        return x + self.two(F.relu(self.one(x)))


class Residual(nn.Module):
    """A first layer, (depth - 2) / 2 blocks of two Linear layers each, and a last layer."""

    def __init__(self, depth, width=64):
        super().__init__()
        blocks = (depth - 2) // 2
        self.first = he(nn.Linear(64, width))
        self.blocks = nn.ModuleList(Block(width, blocks) for _ in range(blocks))
        self.last = he(nn.Linear(width, 10))

    def forward(self, x):
        x = F.relu(self.first(x))
        for block in self.blocks:
            x = block(x)
        return self.last(x)


def linears(model):
    """The model's Linear layers, from the input end to the output end."""
    return [m for m in model.modules() if isinstance(m, nn.Linear)]

Two details:

  • The shortcut needs x and F(x) to have the same shape, so every block keeps the width at 64.
  • Each block's second layer starts at 1/blocks of He's size. Without that, every block would add a change as big as its input, the signal's variance would roughly double with each of the 24 blocks, and lesson 7.6's explosion would be back. Smaller starting changes keep the total about the same size however many blocks there are. (Big ResNets get the same effect from batch norm inside each block.)

nn.ModuleList holds the blocks. A plain Python list would work for the forward pass, but PyTorch wouldn't see the layers inside it: model.parameters() would miss them and the optimiser would never train them.

Gradients through the shortcut

The chain rule through a residual block is where the shortcut earns its keep:

∂y∂x=∂F∂x+I

In words: the derivative of F(x)+x is the derivative of F plus the derivative of x itself, which is the identity matrix I (lesson 1.4: the matrix that changes nothing). So the gradient arriving at a block's output goes back two ways: through the layers, where it's multiplied by their weights and slopes, and through the shortcut, untouched. Lesson 7.5's long product of factors can't shrink it to nothing, because every block has a term that isn't multiplied by anything.

Unroll a few blocks and the output is the input plus a sum of changes, so the loss reaches layer 1 by a direct road as well as by every winding one. This script measures the gradient at all 50 layers of each network, before any training:

"""The gradient's size at every layer of a 50-layer network, plain and residual, after one backward pass."""
import torch
from sklearn.datasets import load_digits
from torch.nn import functional as F

from nets import Plain, Residual, linears

X, y = load_digits(return_X_y=True)
X, y = torch.tensor(X[:256] / 16, dtype=torch.float32), torch.tensor(y[:256])

for Net in (Plain, Residual):
    torch.manual_seed(0)
    model = Net(50)
    F.cross_entropy(model(X), y).backward()
    norms = [m.weight.grad.norm().item() for m in linears(model)]
    print(f"{Net.__name__.lower()}: gradient size of the weights in layers 1 to 50")
    for start in range(0, 50, 10):
        print("  " + " ".join(f"{n:.1e}" for n in norms[start:start + 10]))
Terminal, in ml-local/7-9
(.venv) $ python grad_flow.py
plain: gradient size of the weights in layers 1 to 50
  8.4e-02 9.0e-02 8.6e-02 8.9e-02 7.9e-02 7.4e-02 8.0e-02 5.9e-02 5.8e-02 7.3e-02
  5.0e-02 5.5e-02 4.7e-02 5.8e-02 6.1e-02 7.0e-02 7.9e-02 9.0e-02 9.2e-02 5.9e-02
  6.0e-02 5.5e-02 6.4e-02 6.4e-02 5.9e-02 5.1e-02 4.3e-02 4.7e-02 6.1e-02 5.6e-02
  4.6e-02 3.9e-02 4.3e-02 4.9e-02 6.2e-02 6.0e-02 5.5e-02 6.3e-02 6.8e-02 8.1e-02
  7.9e-02 6.4e-02 5.9e-02 5.3e-02 5.5e-02 3.8e-02 2.6e-02 2.6e-02 3.0e-02 2.5e-02
residual: gradient size of the weights in layers 1 to 50
  2.2e+00 6.3e-01 3.5e+00 7.4e-01 3.7e+00 9.4e-01 4.2e+00 7.8e-01 3.1e+00 7.2e-01
  3.4e+00 6.3e-01 3.4e+00 6.1e-01 3.3e+00 6.3e-01 3.5e+00 7.2e-01 3.8e+00 6.9e-01
  4.1e+00 6.8e-01 3.3e+00 6.5e-01 3.7e+00 7.2e-01 2.9e+00 6.8e-01 3.0e+00 7.2e-01
  3.0e+00 7.8e-01 4.1e+00 6.5e-01 3.5e+00 6.5e-01 2.8e+00 5.3e-01 3.5e+00 6.4e-01
  3.9e+00 5.6e-01 2.8e+00 5.9e-01 2.7e+00 6.0e-01 3.5e+00 6.4e-01 3.2e+00 2.5e+00
Two highwaysthe way back from the loss, with and without shortcuts; and the gradient measured at each of 50 layers
++++layerlayerlayerlayerlayerlayerlayerlayerlossinput end← gradients flow this way10-210-1100101layer 1layer 50

Residual, 50 layers, before any training: between 0.53 and 4.2 at every layer. Every shortcut is a second road: the gradient arriving at a block passes straight through the +, as well as through the block's two layers. The bars alternate: each block's first layer gets its gradient through the block's second layer, which starts scaled down, so it gets less.

Both are healthy at the start: the plain network's gradients are 0.025 to 0.092 at every layer, thanks to He initialisation, and the residual network's 0.53 to 4.2. Neither vanishes. The difference shows during training, when the weights move away from their careful start: the plain network has only the one road, and step 4 shows where that leads.

Wrong way: a 50-layer plain network

If 20 layers are good, 50 should be better. Here are both networks at 6, 20 and 50 layers, each trained for 15 epochs with Adam:

"""Plain networks against residual networks with 6, 20 and 50 layers, trained the same way on the digits."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch.nn import functional as F

from nets import Plain, Residual, linears

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=500, stratify=y, random_state=0)
X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_train, y_val = torch.tensor(y_train), torch.tensor(y_val)

print("layers   plain: train   val    residual: train   val")
for depth in (6, 20, 50):
    scores = []
    for Net in (Plain, Residual):
        torch.manual_seed(0)
        model = Net(depth)
        assert len(linears(model)) == depth
        optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
        for epoch in range(15):
            model.train()
            for idx in torch.randperm(len(X_train)).split(32):
                loss = F.cross_entropy(model(X_train[idx]), y_train[idx])
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
        model.eval()
        with torch.no_grad():
            scores += [(model(X_train).argmax(1) == y_train).float().mean().item(),
                       (model(X_val).argmax(1) == y_val).float().mean().item()]
    print(f"{depth:6}   {scores[0]:12.3f} {scores[1]:6.3f}   {scores[2]:15.3f} {scores[3]:6.3f}")
Terminal, in ml-local/7-9
(.venv) $ python residual.py
layers   plain: train   val    residual: train   val
     6          1.000  0.962             1.000  0.974
    20          0.966  0.902             0.977  0.940
    50          0.530  0.524             1.000  0.972

The plain network gets worse with every step up in depth: validation 96.2%, then 90.2%, then 52.4%. Look at its training accuracy too: 100%, 96.6%, 53.0%. At 50 layers it can't even fit the 1,297 digits it's trained on, which is the degradation problem exactly as He described it.

The residual network, with the same number of layers, the same width, data, optimiser and epochs: 97.4%, 94.0%, then 97.2% at 50 layers, with 100% on its training digits. Depth stopped hurting.

Stacking more plain layers is the wrong way to get a better network. If deeper does worse on the training data itself, the network isn't too big; it's too hard to train. Add shortcuts. Every convolutional network in Stage 8 from ResNet onward, and every transformer in Stage 10, is built from residual blocks.

Check what you learned

A 50-layer plain network has lower training accuracy than a 20-layer one. Is it overfitting?
What does a residual block output?
Why does the shortcut help gradients reach the first layers?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning