Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 15 min · revision 2

Why Residual Networks Train Deeper

Build a residual block with batch normalisation and an identity or projection shortcut, count what the shortcut costs, measure first-layer gradients of deep plain and residual networks at initialisation, train a shallow plain, a deep plain and a deep residual CNN on the same data, and read the stage layout of torchvision's ResNet-18.

Contentsand lesson path

What you will learn

  • Explain convolution, padding, stride, pooling, receptive fields and residual connections, and compute a CNN's output shapes and parameter count.

Prerequisites: Deep Learning Fundamentals

01. Why it matters

Depth pays off in CNNs. Each layer widens the receptive field and can combine the patterns found by the layer before it, so deeper networks can build edges into textures, textures into parts and parts into objects. Around 2015, however, adding layers to a plain stack of convolutions stopped helping. He and colleagues showed that a 56-layer plain network had a higher training error than a 20-layer one on the same data. That is not overfitting, which would show as a gap between training and validation error. The deeper network was simply harder to optimise, even though it could in principle copy the shallow one and set its extra layers to the identity. They called this the degradation problem.

Their fix, the residual connection, is one addition per block, and it is in almost every deep vision model since, as well as in transformers. This lesson builds the block, counts what it costs, and measures its effect on gradients and on training. You need Python 3.12, PyTorch 2 and torchvision, and scikit-learn for the digits data; all scripts run on a CPU.

02. The residual block

A plain block computes y = F(x), where F is a few layers. A residual block computes y = F(x) + x: the input skips past the layers on a shortcut and is added back. F now only has to learn a correction to its input, the residual. If the best thing a block can do is nothing, its weights only need to drive F towards zero, which is much easier than making a stack of convolutions and ReLUs reproduce its input exactly.

In ResNet, F is two 3 × 3 convolutions, each followed by batch normalisation (BatchNorm). During training, BatchNorm normalises each channel to mean 0 and variance 1 over the current batch, then applies a learned scale γ and shift β. In evaluation mode it uses running averages collected during training instead of batch statistics, which is why model.eval() matters for these networks. Because BatchNorm subtracts the channel mean, a bias in the convolution before it would be cancelled; that is why the convolutions use bias=False, and β takes over the job.

The addition needs F(x) and x to have the same shape. When a block halves the resolution with stride 2 and doubles the channels, the identity shortcut no longer fits, and a projection shortcut is used instead: a 1 × 1 convolution with the same stride, followed by BatchNorm.

Python · blocks.py
import torch
from torch import nn


class BasicBlock(nn.Module):
    """Two 3x3 conv-BN layers plus a shortcut: out = relu(F(x) + shortcut(x))."""
    def __init__(self, c_in, c_out, stride=1):
        super().__init__()
        self.f = nn.Sequential(
            nn.Conv2d(c_in, c_out, 3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(c_out), nn.ReLU(),
            nn.Conv2d(c_out, c_out, 3, padding=1, bias=False),
            nn.BatchNorm2d(c_out),
        )
        if stride == 1 and c_in == c_out:
            self.shortcut = nn.Identity()     # nothing to learn
        else:                                 # projection: match channels and size
            self.shortcut = nn.Sequential(
                nn.Conv2d(c_in, c_out, 1, stride=stride, bias=False),
                nn.BatchNorm2d(c_out))

    def forward(self, x):
        return torch.relu(self.f(x) + self.shortcut(x))


def count(m):
    return sum(p.numel() for p in m.parameters())


if __name__ == "__main__":
    x = torch.randn(2, 32, 16, 16)
    for c_in, c_out, stride in [(32, 32, 1), (32, 64, 2)]:
        b = BasicBlock(c_in, c_out, stride)
        print(f"block {c_in}->{c_out} stride {stride}: out {tuple(b(x).shape)}, "
              f"F(x) params {count(b.f):,}, shortcut params {count(b.shortcut):,}")

    # the identity default: with the last BN scale at zero, F(x) is zero
    b = BasicBlock(32, 32).eval()
    nn.init.zeros_(b.f[4].weight)             # BN gamma of the second conv
    h = torch.relu(torch.randn(2, 32, 16, 16))    # a post-ReLU input
    print("zero-initialised block returns its input:", torch.allclose(b(h), h))
Terminal
python blocks.py
Expected output
block 32->32 stride 1: out (2, 32, 16, 16), F(x) params 18,560, shortcut params 0
block 32->64 stride 2: out (2, 64, 8, 8), F(x) params 55,552, shortcut params 2,176
zero-initialised block returns its input: True

The identity shortcut adds no parameters at all. The projection shortcut has 32 × 64 = 2,048 weights for the 1 × 1 convolution plus 2 × 64 = 128 for the BatchNorm scale and shift: 2,176, small next to the 55,552 of the two convolutions. The last line shows the identity default: with the scale γ of the last BatchNorm set to zero, F(x) is zero and the block passes its input through unchanged. torchvision offers this start as resnet18(zero_init_residual=True), so a freshly built deep network behaves like a much shallower one until training gives the blocks something to add.

03. What the shortcut does to gradients

Backpropagation multiplies the gradient by the derivative of every layer it passes through, from the loss back to the first layer (see backpropagation step by step). If those factors are mostly below 1, the product shrinks with depth: the vanishing gradient problem. In a residual block, ignoring the ReLU after the addition, the derivative of y = F(x) + x with respect to x is (derivative of F) + 1. The "+ 1" gives the gradient a path through the addition that is not multiplied by any weight, so a signal from the loss reaches early layers even when the branches are weak.

The script builds three kinds of network on the 8 × 8 digits, with 4 to 32 convolutions of 16 channels between a first convolution and a classifier: a plain stack without normalisation, a plain stack with BatchNorm, and residual blocks with BatchNorm. It runs one backward pass at initialisation and prints the size of the gradient that reaches the first layer.

Python · nets.py
import torch
from torch import nn

from blocks import BasicBlock


def plain_layer(c, bn):
    layers = [nn.Conv2d(c, c, 3, padding=1, bias=not bn)]
    return nn.Sequential(*layers, *([nn.BatchNorm2d(c)] if bn else []), nn.ReLU())


def make_net(kind, depth, c=16, n_classes=10):
    """depth = number of 3x3 conv layers between the stem and the head."""
    stem = nn.Sequential(nn.Conv2d(1, c, 3, padding=1), nn.ReLU())
    if kind == "plain":
        body = [plain_layer(c, bn=False) for _ in range(depth)]
    elif kind == "plain+bn":
        body = [plain_layer(c, bn=True) for _ in range(depth)]
    else:                                     # "residual": two convs per block
        body = [BasicBlock(c, c) for _ in range(depth // 2)]
    head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(c, n_classes))
    return nn.Sequential(stem, *body, head)
Python · gradnorm.py
import torch
from sklearn.datasets import load_digits
from torch import nn

from nets import make_net

torch.set_num_threads(1)                      # identical numbers on any thread count
X, y = load_digits(return_X_y=True)
x = torch.tensor(X[:256] / 16.0, dtype=torch.float32).view(-1, 1, 8, 8)
y = torch.tensor(y[:256])

print("gradient norm of the first conv layer at initialisation")
print(f"{'depth':>5s} {'plain':>10s} {'plain+bn':>10s} {'residual':>10s}")
for depth in (4, 8, 16, 32):
    norms = []
    for kind in ("plain", "plain+bn", "residual"):
        torch.manual_seed(0)
        net = make_net(kind, depth)
        nn.functional.cross_entropy(net(x), y).backward()
        norms.append(net[0][0].weight.grad.norm().item())
    print(f"{depth:5d} " + " ".join(f"{n:10.2e}" for n in norms))
Terminal
python gradnorm.py
Expected output
gradient norm of the first conv layer at initialisation
depth      plain   plain+bn   residual
    4   2.08e-04   1.11e-01   1.39e-01
    8   6.93e-06   8.81e-02   1.92e-01
   16   4.65e-09   3.22e-01   4.97e-01
   32   2.00e-15   3.18e+00   1.17e+00

Without normalisation the first-layer gradient falls from 2e-4 at depth 4 to 7e-6 at depth 8 and 5e-9 at depth 16; at depth 32 it is 2e-15, so the first layer would not learn at all. PyTorch's default initialisation shrinks the signal a little at every layer, and 32 layers multiply that up. BatchNorm rescales the activations at every layer and removes most of the problem at initialisation; with 32 layers the gradient even grows. So BatchNorm alone already gives healthy-looking gradients. The question is whether the deep plain network then also trains well.

04. Training deep plain and residual networks

The next script trains three networks for 300 steps with the same optimiser, learning rate and batches: a plain network with 8 convolutions, a plain network with 24, and a residual network with 24 (12 blocks). All use BatchNorm. It prints the mean training loss of recent batches, which is what you would watch in a training log, and the validation accuracy at the end. It runs in about a minute on one CPU thread.

Python · compare.py
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn

from nets import make_net

torch.set_num_threads(1)
X, y = load_digits(return_X_y=True)
X = torch.tensor(X / 16.0, dtype=torch.float32).view(-1, 1, 8, 8)
X_tr, X_va, y_tr, y_va = train_test_split(X, torch.tensor(y), test_size=0.25,
                                          stratify=y, random_state=0)


def train(kind, depth, steps=300, seed=0):
    torch.manual_seed(seed)
    net = make_net(kind, depth)
    opt = torch.optim.SGD(net.parameters(), lr=0.02, momentum=0.9)
    g = torch.Generator().manual_seed(seed)
    recent, log = [], []
    net.train()
    for step in range(1, steps + 1):
        idx = torch.randint(0, len(X_tr), (32,), generator=g)
        loss = nn.functional.cross_entropy(net(X_tr[idx]), y_tr[idx])
        opt.zero_grad()
        loss.backward()
        opt.step()
        recent = (recent + [loss.item()])[-50:]  # mean of the last 50 batch losses
        if step % 100 == 0:
            log.append(sum(recent) / len(recent))
    net.eval()
    with torch.no_grad():
        acc = (net(X_va).argmax(1) == y_va).float().mean().item()
    return log, acc


print("mean training loss over the last 50 steps, and final val accuracy")
print("model         step 100  step 200  step 300  val acc")
for kind, depth in [("plain+bn", 8), ("plain+bn", 24), ("residual", 24)]:
    log, acc = train(kind, depth)
    print(f"{kind + ' ' + str(depth):12s} " + " ".join(f"{v:9.3f}" for v in log)
          + f" {acc:8.3f}")
Terminal
python compare.py
Expected output
mean training loss over the last 50 steps, and final val accuracy
model         step 100  step 200  step 300  val acc
plain+bn 8       0.760     0.163     0.075    0.973
plain+bn 24      1.632     1.296     0.997    0.511
residual 24      0.386     0.086     0.103    0.949

This is the degradation problem at small scale. Tripling the depth of the plain network makes its training loss worse, 0.997 against 0.075 after 300 steps, and its validation accuracy drops from 0.973 to 0.511, even though its first-layer gradients looked fine. Adding shortcuts to the same 24 layers brings the training loss down to 0.103 and validation accuracy to 0.949, close to the shallow network. Training is chaotic enough that the exact numbers move if you change the seed or the number of CPU threads (the script fixes both), but the order of the three rows is the result to look for. On a task this small the deep residual network is not better than the shallow one; the point is that depth no longer makes training worse, which is what lets ResNets grow to 50, 101 or 152 layers on large datasets.

05. ResNet-18 in torchvision

torchvision's ResNet-18 is built from exactly these blocks. A 7 × 7 stride-2 convolution and a max-pool shrink the image by 4, then four stages (layer1 to layer4) of two blocks each follow. Every stage after the first halves the resolution and doubles the channels in its first block, which therefore needs a projection shortcut. The script builds the architecture with random weights, so nothing is downloaded.

Python · resnet.py
from torchvision.models import resnet18

model = resnet18(weights=None)               # architecture only: nothing is downloaded
print("children:", ", ".join(name for name, _ in model.named_children()))
for name in ("layer1", "layer2", "layer3", "layer4"):
    stage = getattr(model, name)
    first = stage[0]
    n_short = sum(p.numel() for p in first.downsample.parameters()) \
        if first.downsample is not None else 0
    print(f"{name}: {len(stage)} blocks, {first.conv1.in_channels:3d} -> "
          f"{first.conv2.out_channels:3d} channels, stride {first.conv1.stride[0]}, "
          f"shortcut params {n_short:,}")
conv, bn = model.layer2[0].downsample
print("layer2 shortcut:", conv)
print("  followed by", type(bn).__name__, "with", bn.num_features, "channels")
print(f"total parameters: {sum(p.numel() for p in model.parameters()):,}")
Terminal
python resnet.py
Expected output
children: conv1, bn1, relu, maxpool, layer1, layer2, layer3, layer4, avgpool, fc
layer1: 2 blocks,  64 ->  64 channels, stride 1, shortcut params 0
layer2: 2 blocks,  64 -> 128 channels, stride 2, shortcut params 8,448
layer3: 2 blocks, 128 -> 256 channels, stride 2, shortcut params 33,280
layer4: 2 blocks, 256 -> 512 channels, stride 2, shortcut params 132,096
layer2 shortcut: Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False)
  followed by BatchNorm2d with 128 channels
total parameters: 11,689,512

The three projection shortcuts together hold 173,824 parameters, about 1.5% of the 11.7 million in the network. Deeper ResNets (50 layers and more) replace the two 3 × 3 convolutions with a bottleneck block: a 1 × 1 convolution that reduces the channels, a 3 × 3 convolution, and a 1 × 1 convolution that expands them again, which keeps the cost per block down. In the transfer-learning lab you will reuse these stages, freezing some and fine-tuning layer4.

06. Check your understanding

Practice check · 3 questions

Blocks and training curves

Use the scripts and outputs of this lesson.

Q1. Every convolution in `blocks.py` is created with `bias=False`. Why is the bias left out?
Q2. In `compare.py`, the 24-layer plain network ends with a mean training loss of 0.997, against 0.075 for the 8-layer one. What does that show?
Q3. `blocks.py` reports 0 shortcut parameters for the 32 → 32 block and 2,176 for the 32 → 64 block with stride 2. Where do the 2,176 come from?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the from-scratch model of the practice project, decide whether you need residual blocks.

  1. Take the network you planned with trace.py in the convolutions lesson and write a version that is twice as deep, once plain and once with BasicBlock from this lesson.
  2. Train both for the same number of steps and compare the training loss, not only the validation accuracy, to see whether depth makes optimisation harder on your data.
  3. Record the parameters spent on projection shortcuts and keep the version that trains better.

08. Review prompt

Without looking back, describe the degradation problem and how it differs from overfitting; write the output of a residual block and explain why a block can easily act as the identity; explain the "+ 1" in the gradient of a residual block; say what BatchNorm computes in training and in evaluation mode and why the convolution before it has no bias; and explain when a projection shortcut is needed and what it costs.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check