TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › CNN Architectures: LeNet to ResNet

CNN Architectures: LeNet to ResNet

You can now build any CNN from convolutions, pooling and a head. The hard part is the arrangement: how many layers, how wide, where to downsample, how to keep the cost down and how to make a deep stack train at all. Twenty-five years of image classification produced a handful of designs that answer those questions, and each one introduced an idea still in use. This lesson goes through them with the arithmetic that explains each step (computed in NumPy), then opens torchvision's ResNet-18 and checks every number.

Using these networks for real image tasks (fine-tuning, detection, segmentation) is the subject of transfer learning with ResNet and the computer vision course. Here the focus is the architecture itself.

The cost of a convolution layer

Two numbers describe a layer's cost: its parameters (memory, and what must be learned) and its multiply-adds (MACs, roughly the compute; 1 MAC = 2 FLOPs). For a convolution with kernel kk, CinC_\text{in} input and CoutC_\text{out} output channels, producing an H×WH \times W map:

params=Cout Cin k2 (+Cout),MACs=Cout Cin k2⋅HW\text{params} = C_\text{out}\, C_\text{in}\, k^2 \ (+ C_\text{out}), \qquad \text{MACs} = C_\text{out}\, C_\text{in}\, k^2 \cdot H W

Parameters do not depend on the map size; compute does. That is why early layers (large maps, few channels) dominate the compute and late layers (small maps, many channels) dominate the parameters. The Mathematics lesson parameter and FLOP counting has the general rules.

LeNet, AlexNet, VGG: deeper, and the fully connected trap

  • LeNet-5 (1998): two 5 ×\times 5 convolutions with subsampling, then three fully connected layers, for 32 ×\times 32 digits. The template of conv-pool blocks followed by a classifier.
  • AlexNet (2012): the same template, scaled to 224 ×\times 224 ImageNet photos with five convolutions (the first one 11 ×\times 11 with stride 4), ReLU instead of tanh, dropout, data augmentation, and training on GPUs. It won ImageNet by a wide margin and started the deep-learning era in vision.
  • VGG (2014): only 3 ×\times 3 convolutions, stacked two or three at a time between 2 ×\times 2 max pools, channels doubling after each pool (64, 128, 256, 512, 512). Simple and uniform, 16 or 19 weight layers.

Their parameter counts, from the layer shapes (the convolution and linear layers as in torchvision's versions):

python · try it yourself
def conv(c_in, c_out, k):
    return c_out * (c_in * k * k + 1)          # weights + biases

def linear(n_in, n_out):
    return n_out * (n_in + 1)

lenet5 = [conv(1, 6, 5), conv(6, 16, 5), linear(16 * 5 * 5, 120), linear(120, 84), linear(84, 10)]
alexnet = [conv(3, 64, 11), conv(64, 192, 5), conv(192, 384, 3), conv(384, 256, 3), conv(256, 256, 3),
           linear(256 * 6 * 6, 4096), linear(4096, 4096), linear(4096, 1000)]
vgg_cfg = [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"]
vgg16, c = [], 3
for v in vgg_cfg:
    if v != "M":
        vgg16.append(conv(c, v, 3)); c = v
n_conv = len(vgg16)
vgg16 += [linear(512 * 7 * 7, 4096), linear(4096, 4096), linear(4096, 1000)]

for name, layers, n_c in [("LeNet-5", lenet5, 2), ("AlexNet", alexnet, 5), ("VGG-16", vgg16, n_conv)]:
    total = sum(layers)
    print(f"{name:8s} {total:12,d} parameters, {len(layers)} weight layers, "
          f"{sum(layers[n_c:]) / total:.1%} in the fully connected layers")
LeNet-5        61,706 parameters, 5 weight layers, 95.8% in the fully connected layers
AlexNet    61,100,840 parameters, 8 weight layers, 96.0% in the fully connected layers
VGG-16    138,357,544 parameters, 16 weight layers, 89.4% in the fully connected layers

LeNet-5 has 61,706 parameters, AlexNet 61,100,840 and VGG-16 138,357,544, and in all three about 90 % or more sit in the fully connected layers: VGG-16's first linear layer alone takes 512⋅7⋅7=25,088512 \cdot 7 \cdot 7 = 25{,}088 inputs to 4096 outputs, 102.8 million weights. Later designs removed that head and replaced it with global average pooling and a single linear layer.

Cheaper convolutions: 3 ×\times 3 stacks, 1 ×\times 1 bottlenecks, depthwise separable

Three ideas reduce the cost of a layer without shrinking what it can see.

Stacks of 3 ×\times 3 (VGG). Two 3 ×\times 3 convolutions have the same 5 ×\times 5 receptive field as one 5 ×\times 5 convolution, with 2⋅9=182 \cdot 9 = 18 weights per channel pair instead of 25 and an extra nonlinearity in between. Three 3 ×\times 3 replace a 7 ×\times 7 (27 vs 49).

1 ×\times 1 bottlenecks (Inception / GoogLeNet, 2014). A 1 ×\times 1 convolution mixes channels at each pixel; placed before an expensive 5 ×\times 5 it first reduces the channel count, so the 5 ×\times 5 runs on fewer channels. Inception modules run 1 ×\times 1, 3 ×\times 3 and 5 ×\times 5 branches (each with a bottleneck) and a pooling branch in parallel and concatenate their outputs, letting the network mix receptive-field sizes in every block.

Depthwise separable convolutions (MobileNet, 2017). Split a k×kk \times k convolution into a depthwise step (one k×kk \times k filter per input channel, no mixing between channels) and a pointwise 1 ×\times 1 step that mixes channels. The cost ratio to a standard convolution is

Cink2HW+CinCoutHWCinCoutk2HW=1Cout+1k2\frac{C_\text{in} k^2 HW + C_\text{in} C_\text{out} HW}{C_\text{in} C_\text{out} k^2 HW} = \frac{1}{C_\text{out}} + \frac{1}{k^2}

about 1/91/9 for 3 ×\times 3 kernels and many channels. The three ideas side by side, with realistic layer sizes:

python · try it yourself
def conv_cost(h, w, c_in, c_out, k, groups=1):
    """Parameters (no bias) and multiply-adds of a stride-1 'same' convolution on an h x w map."""
    params = c_out * (c_in // groups) * k * k
    return params, params * h * w

def show(name, parts):
    p = sum(x[0] for x in parts); m = sum(x[1] for x in parts)
    print(f"{name:38s} params {p:9,d}   MACs {m / 1e6:8.1f} M")
    return p, m

print("Receptive field 5 x 5 on a 56 x 56 map, 64 -> 64 channels")
show("one 5x5", [conv_cost(56, 56, 64, 64, 5)])
show("two 3x3 (VGG)", [conv_cost(56, 56, 64, 64, 3)] * 2)

print("\nInception-style branch: 256 -> 32 channels with a 5x5, 28 x 28 map")
a = show("direct 5x5", [conv_cost(28, 28, 256, 32, 5)])
b = show("1x1 to 32, then 5x5", [conv_cost(28, 28, 256, 32, 1), conv_cost(28, 28, 32, 32, 5)])
print(f"saving: {a[1] / b[1]:.1f}x fewer MACs")

print("\nMobileNet: 3x3 conv, 256 -> 256 channels, 14 x 14 map")
s = show("standard 3x3", [conv_cost(14, 14, 256, 256, 3)])
d = show("depthwise 3x3 + pointwise 1x1", [conv_cost(14, 14, 256, 256, 3, groups=256), conv_cost(14, 14, 256, 256, 1)])
print(f"ratio {d[1] / s[1]:.4f}  vs 1/C_out + 1/k^2 = {1 / 256 + 1 / 9:.4f}")
Receptive field 5 x 5 on a 56 x 56 map, 64 -> 64 channels
one 5x5                                params   102,400   MACs    321.1 M
two 3x3 (VGG)                          params    73,728   MACs    231.2 M

Inception-style branch: 256 -> 32 channels with a 5x5, 28 x 28 map
direct 5x5                             params   204,800   MACs    160.6 M
1x1 to 32, then 5x5                    params    33,792   MACs     26.5 M
saving: 6.1x fewer MACs

MobileNet: 3x3 conv, 256 -> 256 channels, 14 x 14 map
standard 3x3                           params   589,824   MACs    115.6 M
depthwise 3x3 + pointwise 1x1          params    67,840   MACs     13.3 M
ratio 0.1150  vs 1/C_out + 1/k^2 = 0.1150

Two 3 ×\times 3 layers cost 73,728 parameters against 102,400 for one 5 ×\times 5 layer. The Inception-style bottleneck cuts the 5 ×\times 5 branch from 160.6 M to 26.5 M multiply-adds, 6.1 times fewer. The depthwise separable layer needs 67,840 parameters and 13.3 M MACs instead of 589,824 and 115.6 M: a ratio of 0.1150, exactly 1/256+1/91/256 + 1/9.

What does a separable layer give up? It is an ordinary convolution whose kernel is forced to be a product: wo,c,a,b=po,c dc,a,bw_{o,c,a,b} = p_{o,c}\, d_{c,a,b}, where pp is the pointwise and dd the depthwise weight. The NumPy check below builds both and confirms it, then tests whether a random full kernel has that form.

python · try it yourself
import numpy as np

def conv_same(x, w):
    """x: (C_in, H, W), w: (C_out, C_in, 3, 3), zero padding 1, stride 1."""
    xp = np.pad(x, ((0, 0), (1, 1), (1, 1)))
    H, W = x.shape[1:]
    out = np.zeros((w.shape[0], H, W))
    for a in range(3):
        for c in range(3):
            out += np.einsum("oc,chw->ohw", w[:, :, a, c], xp[:, a:a + H, c:c + W])
    return out

def depthwise(x, w_dw):
    """Each channel gets its own 3x3 filter: w_dw (C, 3, 3). No mixing between channels."""
    xp = np.pad(x, ((0, 0), (1, 1), (1, 1)))
    H, W = x.shape[1:]
    out = np.zeros_like(x)
    for a in range(3):
        for c in range(3):
            out += w_dw[:, a, c, None, None] * xp[:, a:a + H, c:c + W]
    return out

rng = np.random.default_rng(0)
C_in, C_out = 4, 6
x = rng.normal(size=(C_in, 5, 5))
w_dw = rng.normal(size=(C_in, 3, 3))          # depthwise: C_in * 9 weights
w_pw = rng.normal(size=(C_out, C_in))         # pointwise 1x1: C_out * C_in weights
y_sep = np.einsum("oc,chw->ohw", w_pw, depthwise(x, w_dw))

# The same map as ONE ordinary convolution whose kernel is a product of the two
w_full = w_pw[:, :, None, None] * w_dw[None]  # (C_out, C_in, 3, 3), rank-limited
y_full = conv_same(x, w_full)
print("separable == full conv with w[o,c] = pw[o,c] * dw[c]:", np.allclose(y_sep, y_full))
print("weights: separable", w_dw.size + w_pw.size, " full", w_full.size)
w_any = rng.normal(size=(C_out, C_in, 3, 3))  # a general full kernel is not of that form
ratios = w_any[:, :, 1, 1, None, None] / w_any
print("a random full kernel factorises:", bool(np.allclose(ratios, ratios[:1])))
separable == full conv with w[o,c] = pw[o,c] * dw[c]: True
weights: separable 60  full 216
a random full kernel factorises: False

The separable layer with 60 weights computes exactly what a 216-weight full convolution computes when its kernel is rank-limited in this way, and a general kernel is not. In practice the network makes up for the restriction with more layers and channels at the same budget, which is why MobileNet reaches good ImageNet accuracy with a few million parameters.

ResNet: making depth trainable

Simply stacking more VGG-style layers stopped helping around 20 layers: deeper plain networks had higher training error, an optimisation problem rather than overfitting. ResNet (2015) added a shortcut around every pair of convolutions, so a block computes y=F(x)+xy = F(x) + x. A block that does not help can learn F≈0F \approx 0 and pass its input through, and gradients reach early layers through the identity paths. With it, networks of 50, 101 and 152 layers trained well. The full story, with experiments, is in residual connections.

x64 x 56 x 56 conv 3x3 s=2BN, ReLU conv 3x3BN shortcutconv 1x1 s=2, BN + ReLU128 x 28 x 28 F(x)x (projected)

ResNet-18 has a 7 ×\times 7 stride-2 stem convolution and a max pool (224 to 56), then four stages of two such blocks each, with 64, 128, 256 and 512 channels; the first block of stages 2 to 4 halves the map with stride 2 and needs a 1 ×\times 1 projection on the shortcut so the shapes match for the addition. Global average pooling and one linear layer to 1000 classes finish it. Deeper ResNets (50 and up) use a bottleneck block: 1 ×\times 1 down, 3 ×\times 3, 1 ×\times 1 up, the Inception trick inside a residual block.

Inside torchvision's resnet18

The recorded run (CPU) loads the ImageNet weights cached in the image (ResNet18_Weights.IMAGENET1K_V1; weights=None gives the same shapes with random weights), pushes one random 224 ×\times 224 image through the stages and prints each output shape and parameter count.

python · try it yourself
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights

torch.manual_seed(0)
model = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).eval()   # cached in the image, no download
count = lambda m: sum(p.numel() for p in m.parameters())
print(f"resnet18: {count(model):,} parameters")

x = torch.randn(1, 3, 224, 224)
print(f"{'stage':8s} {'output shape':20s} {'params':>10s}")
for name in ["conv1", "bn1", "relu", "maxpool", "layer1", "layer2", "layer3", "layer4", "avgpool"]:
    m = getattr(model, name)
    x = m(x)
    print(f"{name:8s} {str(tuple(x.shape)):20s} {count(m):10,d}")
x = model.fc(torch.flatten(x, 1))
print(f"{'fc':8s} {str(tuple(x.shape)):20s} {count(model.fc):10,d}")

block = model.layer2[0]                     # the first block of a stage: stride 2 and 64 -> 128 channels
print("layer2[0]:", [n for n, _ in block.named_children()])
print("  conv1", tuple(block.conv1.weight.shape), "stride", block.conv1.stride,
      "| shortcut", tuple(block.downsample[0].weight.shape), "stride", block.downsample[0].stride)
print("  conv bias:", block.conv1.bias)     # BatchNorm follows, so no bias
resnet18: 11,689,512 parameters
stage    output shape             params
conv1    (1, 64, 112, 112)         9,408
bn1      (1, 64, 112, 112)           128
relu     (1, 64, 112, 112)             0
maxpool  (1, 64, 56, 56)               0
layer1   (1, 64, 56, 56)         147,968
layer2   (1, 128, 28, 28)        525,568
layer3   (1, 256, 14, 14)      2,099,712
layer4   (1, 512, 7, 7)        8,393,728
avgpool  (1, 512, 1, 1)                0
fc       (1, 1000)               513,000
layer2[0]: ['conv1', 'bn1', 'relu', 'conv2', 'bn2', 'downsample']
  conv1 (128, 64, 3, 3) stride (2, 2) | shortcut (128, 64, 1, 1) stride (2, 2)
  conv bias: None

The total is 11,689,512 parameters. The shapes follow the figure: the stem gives 64 ×\times 112 ×\times 112, the max pool 56 ×\times 56, and each stage halves the map and doubles the channels, down to 512 ×\times 7 ×\times 7, then 512 after the average pool and 1000 logits. The parameters behave the opposite way: layer4 alone holds 8,393,728 (72 % of the network) on the smallest map, while the stem has 9,408. The fc head has 513,000, less than 5 %, a far cry from VGG. Inside layer2[0] the first convolution has stride 2 and weight shape (128, 64, 3, 3), the shortcut is a (128, 64, 1, 1) convolution with stride 2, and the convolutions have no bias because a batch normalisation follows each one.

After ResNet: EfficientNet and ConvNeXt

EfficientNet (2019) asked how to scale a good small network. Instead of growing only depth, only width or only resolution, it grows all three together with one coefficient ϕ\phi: depth by αϕ\alpha^\phi, width by βϕ\beta^\phi, resolution by γϕ\gamma^\phi, with αβ2γ2≈2\alpha \beta^2 \gamma^2 \approx 2 so each step roughly doubles the FLOPs. Its base network, B0, is built from MobileNet-style inverted bottleneck blocks with depthwise convolutions and squeeze-and-excitation (a small channel-attention branch).

ConvNeXt (2022) took a plain ResNet and changed it step by step toward the design of vision transformers: larger 7 ×\times 7 depthwise kernels, a "patchify" stem (4 ×\times 4 stride 4), fewer activations and normalisations, layer norm, GELU, inverted bottlenecks. The result matched transformers of the same size on ImageNet, showing that much of their advantage came from the training recipe and design details, not from attention itself.

The sizes of the networks in this lesson, built from torchvision's architecture code with random weights (nothing is downloaded):

python · try it yourself
import torch
from torchvision import models

torch.manual_seed(0)
for name in ["alexnet", "vgg16", "resnet18", "resnet50", "mobilenet_v2", "efficientnet_b0", "convnext_tiny"]:
    m = getattr(models, name)(weights=None)          # architecture only, random weights
    print(f"{name:16s} {sum(p.numel() for p in m.parameters()):12,d}")
alexnet            61,100,840
vgg16             138,357,544
resnet18           11,689,512
resnet50           25,557,032
mobilenet_v2        3,504,872
efficientnet_b0     5,288,548
convnext_tiny      28,589,128

AlexNet and VGG-16 reproduce the counts computed by hand above. ResNet-50 has 25,557,032 parameters with 50 layers, less than a fifth of VGG-16; MobileNetV2 3,504,872 and EfficientNet-B0 5,288,548 are the small, mobile-friendly end; ConvNeXt-Tiny has 28,589,128.

Choosing one

For a new image task the default today is a pretrained ResNet-50, EfficientNet or ConvNeXt fine-tuned on your data (transfer learning); MobileNet or EfficientNet-B0 when the model must run on a phone; a small custom CNN like the one from the previous lesson for tiny images or when you cannot use pretrained weights. Count parameters and MACs before training: they tell you whether the model fits the device long before accuracy does.

Pitfalls

  • Parameters are not compute. A layer with few parameters on a large map can dominate the run time (the ResNet stem: 9,408 parameters, but on a 112 ×\times 112 map). Measure both.
  • Depthwise convolutions are not free on every device. They have few MACs but low arithmetic intensity; on some GPUs a depthwise-separable network runs slower than its MAC count suggests.
  • Wrong input size or normalisation for pretrained weights. ImageNet models expect 3-channel images normalised with the ImageNet mean and standard deviation (weights.transforms() gives the exact preprocessing).
  • Forgetting model.eval(). ResNets contain batch normalisation; in training mode a single image is normalised with its own statistics and the outputs change.
  • Flatten heads lock the resolution. VGG's linear head requires 7 ×\times 7 maps; ResNet's global pooling accepts any size above the minimum.

Practice

  1. How many parameters does one ResNet basic block with 256 channels (no downsampling) have, counting the batch-norm weights and biases? Check against the layer3 count above (two blocks, the first with a projection from 128 channels).
  2. A 3 ×\times 3 convolution from 512 to 512 channels runs on a 7 ×\times 7 map. Compute its MACs, and those of a depthwise separable replacement.
  3. Why does replacing VGG-16's fully connected head by global average pooling and one linear layer to 1000 classes remove almost 90 % of the parameters? Compute the new head's size.
Answer
  1. Two convolutions 2⋅256⋅256⋅9=1,179,6482 \cdot 256 \cdot 256 \cdot 9 = 1{,}179{,}648 plus two batch norms 2⋅2⋅256=10242 \cdot 2 \cdot 256 = 1024: 1,180,672. For layer3: the first block has 256⋅128⋅9+256⋅256⋅9=884,736256 \cdot 128 \cdot 9 + 256 \cdot 256 \cdot 9 = 884{,}736 conv weights, 2⋅512=10242 \cdot 512 = 1024 BN parameters, a projection 256⋅128=32,768256 \cdot 128 = 32{,}768 with its BN (512): 919,040; plus the second block 1,180,672 gives 2,099,712, the printed number.
  2. Standard: 512⋅512⋅9⋅49=115,605,504512 \cdot 512 \cdot 9 \cdot 49 = 115{,}605{,}504, about 115.6 M. Separable: 512⋅9⋅49+512⋅512⋅49=225,792+12,845,056=13,070,848512 \cdot 9 \cdot 49 + 512 \cdot 512 \cdot 49 = 225{,}792 + 12{,}845{,}056 = 13{,}070{,}848, about 13.1 M (ratio 1/512+1/9≈0.1131/512 + 1/9 \approx 0.113).
  3. The three linear layers hold 89.4 % of VGG-16's parameters, 123.6 million. A GAP head is one linear layer from 512 to 1000: 512⋅1000+1000=513,000512 \cdot 1000 + 1000 = 513{,}000, the same as ResNet-18's fc.

Test yourself

Where are most of VGG-16's 138 million parameters?

  1. In the first convolution
  2. In the 3 ×\times 3 convolutions of the last stage
  3. In the fully connected layers (about 89 %)
  4. In the batch normalisation layers

A depthwise separable 3 ×\times 3 convolution with many channels costs roughly what fraction of a standard one?

  1. 1/21/2
  2. 1/91/9 (more exactly 1/Cout+1/k21/C_\text{out} + 1/k^2)
  3. 1/Cin1/C_\text{in}
  4. the same

Why does the first block of ResNet-18's layer2 have a 1 ×\times 1 convolution on its shortcut?

  1. To add more parameters
  2. Because the block changes the shape (stride 2, 64 to 128 channels), so the identity cannot be added directly
  3. To replace batch normalisation
  4. It is a bottleneck that reduces compute

How many parameters does torchvision's resnet18 have, and which part holds the most?

  1. About 11.7 million; layer4
  2. About 138 million; the fc head
  3. About 25.6 million; layer1
  4. About 3.5 million; the stem