Residual networks

The skip connection that lets networks grow to a hundred layers — and a careful audit of the ResNet-18, -50 and -110 scripts.

What you'll learn
  • Explain why adding the input back makes very deep networks trainable
  • Know when a skip connection needs a 1×1 projection
  • Count where a ResNet's parameters live, and audit an architecture by running it

Before 2015, adding layers to a deep network eventually made it worse — not from overfitting, but because the optimiser could no longer train it. The residual block fixed that with one addition. Instead of asking a block to compute the output \(H(x)\) directly, it computes a correction \(F(x)\) and adds the input back:

\[\text{out} = \mathrm{ReLU}\big(F(x) + x\big)\]

If a block has nothing useful to add, it only needs to push \(F\) towards zero, which is easy. And on the backward pass the identity gives the gradient a direct route:

\[\frac{\partial\,\text{out}}{\partial x} = \frac{\partial F}{\partial x} + I\]
Signals travel through the convolution path and across the skip, and are added. Switch to the backward pass to watch gradients take the same two routes in reverse; the readout compares a plain stack of the chosen depth.

In a plain stack, the gradient reaching the first layer is a product of one factor per layer; if those factors are typically below 1 it shrinks exponentially — fifty factors of 0.5 leave \(10^{-15}\). The identity term in each residual block keeps a path along which nothing is multiplied away.

The block in resnet_18.py

ResidualBlock is the classic “basic block”: two 3×3 convolutions, each followed by BatchNorm, with a ReLU between and after the addition. The interesting part is the skip:

self.skip_connection = nn.Sequential()
if stride != 1 or in_dim != out_dim:
    self.skip_connection = nn.Sequential(
        nn.Conv2d(in_dim, out_dim, kernel_size=1, stride=stride),
        nn.BatchNorm2d(out_dim))
Two residual blocks side by side. Left: x of shape 64 by 56 by 56 passes through conv 3x3, BatchNorm, ReLU, conv 3x3, BatchNorm, which together form F(x); an identity skip adds x back before a final ReLU, giving the same shape. Right: at a stage boundary the first conv has stride 2 and the skip passes through a 1x1 conv with stride 2 plus BatchNorm, so both paths produce 128 by 28 by 28. Two residual blocks side by side. Left: x of shape 64 by 56 by 56 passes through conv 3x3, BatchNorm, ReLU, conv 3x3, BatchNorm, which together form F(x); an identity skip adds x back before a final ReLU, giving the same shape. Right: at a stage boundary the first conv has stride 2 and the skip passes through a 1x1 conv with stride 2 plus BatchNorm, so both paths produce 128 by 28 by 28.
Inside a stage the skip is the identity. At the start of a stage the main path halves the resolution and doubles the channels, so the skip needs a strided 1×1 convolution to match before the two can be added.

An empty nn.Sequential() is the identity, so inside a stage \(x\) is added unchanged. At the start of a new stage the shapes disagree, and the 1×1 strided convolution is the cheapest way to make them match.

Where the parameters are

Counting the model as written gives 11,694,312 parameters. torchvision’s resnet18 has 11,689,512; the difference, 4,800, is exactly the biases of the 20 convolutions here, which keep PyTorch’s default bias=True. Those biases are redundant — each convolution is followed by BatchNorm, whose mean subtraction cancels any constant — which is why reference implementations pass bias=False.

Parameters per part of ResNet-18. Each stage doubles the channels, and a 3×3 convolution's weight grows with the square of the width, so the last stage alone holds 72% of the model.

Auditing the deeper variants

The ResNet-50 and ResNet-110 scripts print their models but never run them. Pushing a (1, 3, 224, 224) tensor through each tells a different story.

ResNet-50 uses bottleneck blocks (1×1 reduce, 3×3, 1×1 expand by 4). The script passes the expanded width as the block width:

self.layer1 = self._make_layer(64, 256, 3, stride=1)

so every bottleneck expands again by 4: stage 1 outputs 1,024 channels instead of 256. _make_layer then builds the first block of stage 2 with the argument in_dim=256, while the tensor arriving has self.in_dim = 1024 channels — and the forward pass stops at layer2 with a channel-mismatch error. The fix is to pass the bottleneck width, _make_layer(64, 3), _make_layer(128, 4, stride=2) and so on, and to use self.in_dim for the first block too. The classifier nn.Linear(2048 * 4, ...) then becomes nn.Linear(2048, ...).

ResNet-110 runs, but is not ResNet-110. The name comes from the CIFAR family in the original paper: three stages of 16, 32 and 64 channels with \(n = 18\) basic blocks each, \(6n + 2 = 110\) weight layers and about 1.7 million parameters. The script instead stacks 18 blocks in each of the four ImageNet stages of 64 to 512 channels: 146 weight layers and 112 million parameters — about 65 times the intended size, and almost ten times ResNet-18.

Neither problem is visible in print(model). Both appear in one line:

print(model(torch.randn(1, 3, 224, 224)).shape)

Try it yourself. Count parameters with sum(p.numel() for p in model.parameters()) for the ResNet-18 script, then add bias=False to its convolutions and confirm you get 11,689,512. Next, apply the _make_layer fix to resnet_50.py, run a forward pass, and — with bias=False on its convolutions as well — check you land on torchvision’s 25,557,032.

View source on GitHub →