TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Vision Backbones: ResNet, MobileNet, EfficientNet and ViT

Vision Backbones: ResNet, MobileNet, EfficientNet and ViT

Almost no vision model is designed from scratch any more. A classifier, a detector, a segmenter and a re-identification model all start from a backbone: a network that turns an image into feature maps, designed once, trained once on a large dataset (usually ImageNet), and reused with a small task-specific head on top. Choosing a backbone is therefore one of the first decisions of every vision project, and it is mostly a trade-off between accuracy, latency and memory. This lesson explains the four families you will meet most, computes their key numbers from scratch, and measures parameter counts, compute and output shapes of the real torchvision models. The building blocks themselves (convolution, residual connections, attention) are taught in Deep Learning: CNN architectures, residual connections, vision transformers.

Stages and output stride

image224 stem/4 stage 156 x 56 stage 228 x 28 stage 314 x 14 stage 47 x 7 pool + fc stride 4stride 8stride 16stride 32 resolution halves and channels grow from stage to stage detectors and segmenters read several stages (a feature pyramid) classification

Every CNN backbone in this lesson has the same skeleton. A stem (a strided convolution, often followed by pooling) reduces the image by 4; then four or five stages each start by halving the height and width (a stride-2 convolution or pooling) and widen the channels; the stages are stacks of the family's block. The factor between the input size and a feature map's size is its stride (or output stride): the last stage of a standard backbone has stride 32, so a 224×224224 \times 224 image becomes a 7×77 \times 7 map and a 640×640640 \times 640 image a 20×2020 \times 20 map. Each cell of that map "sees" a large region of the image (its receptive field, pooling and receptive fields) and describes it with hundreds of channels.

For classification the head is simple: global average pooling and one linear layer. Detectors and segmenters need positions, so they read several stages at once (stride 8, 16 and 32 in YOLO and Faster R-CNN's feature pyramid), and segmenters upsample back to stride 4 or 1. That is why "the backbone" is a separate, swappable part: the same ResNet-50 sits inside a classifier, Faster R-CNN and Mask R-CNN.

The four families

ResNet (2015). Stacks of residual blocks y=x+F(x)\mathbf{y} = \mathbf{x} + F(\mathbf{x}), where FF is two 3×33 \times 3 convolutions (the basic block, ResNet-18 and -34) or a 1×11 \times 1, 3×33 \times 3, 1×11 \times 1 bottleneck that first reduces the channels by 4 (ResNet-50 and deeper). The identity path lets gradients reach early layers, which made networks of 50 to 152 layers trainable (the paper's deepest ImageNet model has 152). Still the default reference backbone: simple, well understood, supported everywhere.

MobileNet (v1 2017, v2 2018, v3 2019). Built for phones: it replaces a standard convolution with a depthwise separable one. A standard k×kk \times k convolution from CinC_\text{in} to CoutC_\text{out} channels on an H×WH \times W map costs

MACsstd=H W Cin Cout k2\text{MACs}_\text{std} = H\, W\, C_\text{in}\, C_\text{out}\, k^2

multiply-accumulates. The separable version first filters every channel on its own (depthwise, one k×kk \times k kernel per channel), then mixes channels with a 1×11 \times 1 convolution (pointwise):

MACssep=H W Cin k2+H W Cin Cout,MACssepMACsstd=1Cout+1k2\text{MACs}_\text{sep} = H\, W\, C_\text{in}\, k^2 + H\, W\, C_\text{in}\, C_\text{out}, \qquad \frac{\text{MACs}_\text{sep}}{\text{MACs}_\text{std}} = \frac{1}{C_\text{out}} + \frac{1}{k^2}

With k=3k = 3 and a few hundred channels that is about 8 to 9 times less compute and as many fewer parameters. MobileNetV2 wraps it in an inverted residual block (expand the channels with 1×11 \times 1, depthwise 3×33 \times 3, project back down, residual connection on the narrow ends), and V3 adds squeeze-and-excitation (a learned per-channel weighting) and the hard-swish activation, with the architecture partly found by automated search.

EfficientNet (2019). The same kind of block as MobileNetV2/V3, plus a rule for making the network bigger: compound scaling. Instead of making a network only deeper, only wider or only fed larger images, scale all three together with one coefficient ϕ\phi:

depth∝αϕ,width∝βϕ,resolution∝γϕ,α β2γ2≈2\text{depth} \propto \alpha^\phi,\quad \text{width} \propto \beta^\phi,\quad \text{resolution} \propto \gamma^\phi, \qquad \alpha\, \beta^2 \gamma^2 \approx 2

so each step of ϕ\phi roughly doubles the compute (compute grows linearly with depth and quadratically with width and resolution). The paper found α=1.2\alpha = 1.2, β=1.1\beta = 1.1, γ=1.15\gamma = 1.15 by a small grid search on the base network B0, and B1 to B7 are the scaled versions.

Vision Transformer (ViT) (2020). No convolutions after the first step: the image is cut into 16×1616 \times 16 patches, each patch is flattened and linearly projected to a token, a class token and position embeddings are added, and a standard transformer encoder processes the sequence (vision transformers builds one). A 224×224224 \times 224 image gives (224/16)2=196(224 / 16)^2 = 196 tokens. Attention compares every token with every other, so cost grows with the square of the number of tokens. ViTs need much more training data (or strong augmentation and distillation) than CNNs to reach the same accuracy, but scale better with data and dominate large pretrained models. ConvNeXt (2022) went the other way: a ResNet modernised with transformer-era choices (large 7×77 \times 7 depthwise kernels, layer norm, fewer activations, a patchify stem), matching ViTs with a pure CNN.

Depthwise separable convolutions and compound scaling in numbers

python · try it yourself
import numpy as np

def conv_cost(H, W, cin, cout, k):
    std_mac = H * W * cin * cout * k * k
    sep_mac = H * W * cin * k * k + H * W * cin * cout
    std_par = cin * cout * k * k
    sep_par = cin * k * k + cin * cout
    return std_mac, sep_mac, std_par, sep_par

print(f"{'layer (H x W, Cin -> Cout)':30s} {'std MACs':>12s} {'separable':>12s} {'ratio':>7s} {'1/Cout + 1/k^2':>15s}")
for H, cin, cout in [(112, 32, 64), (56, 128, 128), (14, 512, 512), (7, 1024, 1024)]:
    s, d, sp, dp = conv_cost(H, H, cin, cout, 3)
    print(f"{f'{H} x {H}, {cin} -> {cout}':30s} {s:12,d} {d:12,d} {d / s:7.3f} {1 / cout + 1 / 9:15.3f}")
s, d, sp, dp = conv_cost(14, 14, 512, 512, 3)
print(f"parameters of the 512 -> 512 layer: standard {sp:,}, separable {dp:,}")

alpha, beta, gamma = 1.2, 1.1, 1.15          # EfficientNet's grid-searched constants
print(f"\nalpha * beta^2 * gamma^2 = {alpha * beta**2 * gamma**2:.3f}")
print(f"{'phi':>3s} {'depth x':>8s} {'width x':>8s} {'resolution':>11s} {'compute x':>10s}")
for phi in range(0, 8):
    d, w, r = alpha ** phi, beta ** phi, gamma ** phi
    print(f"{phi:3d} {d:8.2f} {w:8.2f} {round(224 * r):11d} {d * w**2 * r**2:10.2f}")
layer (H x W, Cin -> Cout)         std MACs    separable   ratio  1/Cout + 1/k^2
112 x 112, 32 -> 64             231,211,008   29,302,784   0.127           0.127
56 x 56, 128 -> 128             462,422,016   54,992,896   0.119           0.119
14 x 14, 512 -> 512             462,422,016   52,283,392   0.113           0.113
7 x 7, 1024 -> 1024             462,422,016   51,831,808   0.112           0.112
parameters of the 512 -> 512 layer: standard 2,359,296, separable 266,752

alpha * beta^2 * gamma^2 = 1.920
phi  depth x  width x  resolution  compute x
  0     1.00     1.00         224       1.00
  1     1.20     1.10         258       1.92
  2     1.44     1.21         296       3.69
  3     1.73     1.33         341       7.08
  4     2.07     1.46         392      13.60
  5     2.49     1.61         451      26.11
  6     2.99     1.77         518      50.14
  7     3.58     1.95         596      96.28

The ratio printed by brute force matches the formula 1/Cout+1/k21/C_\text{out} + 1/k^2 in every row: 0.127 for 64 output channels, falling towards 1/9≈0.1111/9 \approx 0.111 as the channels grow. The 512-channel layer needs 266,752 parameters instead of 2,359,296. For compound scaling, the paper's constants give αβ2γ2=1.92\alpha \beta^2 \gamma^2 = 1.92, so each step of ϕ\phi multiplies the compute by 1.92 and ϕ=7\phi = 7 by about 96. The released B1 to B7 do not follow the formula exactly (B7 uses 600×600600 \times 600 images where the formula gives 596, and the intermediate sizes were rounded to convenient values), but the idea is the same.

The real models: parameters, compute and output shapes

torchvision ships all of these architectures. Pretrained weights are a download (only ResNet-18's are cached in this course's image), but the architectures can be built with weights=None: random weights, real structure. That is enough to measure what a backbone costs, which depends only on its structure. The recorded example builds seven models, counts parameters, counts multiply-accumulates for one 224×224224 \times 224 image with PyTorch's FlopCounterMode (which reports FLOPs, 2 per multiply-accumulate; divided by 2 here), and runs the feature part to get the shape of the last feature map.

python · try it yourself
import torch
from torch import nn
from torch.utils.flop_counter import FlopCounterMode
from torchvision import models

x = torch.zeros(1, 3, 224, 224)
def features(name, m):
    """The backbone part without the classification head."""
    if name.startswith("resnet"):
        return nn.Sequential(*list(m.children())[:-2])
    if name.startswith("vit"):
        return lambda t: m.encoder(torch.cat([m.class_token.expand(len(t), -1, -1), m._process_input(t)], 1))
    return m.features

print(f"{'model':20s} {'params (M)':>10s} {'GMACs':>7s}  feature output for 224 x 224")
for name in ["resnet18", "resnet50", "mobilenet_v3_small", "mobilenet_v3_large", "efficientnet_b0",
             "convnext_tiny", "vit_b_16"]:
    torch.manual_seed(0)
    m = getattr(models, name)(weights=None).eval()
    params = sum(p.numel() for p in m.parameters()) / 1e6
    with FlopCounterMode(display=False) as counter:      # grad mode on: no fused attention kernel
        out = m(x)
    macs = counter.get_total_flops() / 2 / 1e9
    with torch.no_grad():
        f = features(name, m)(x)
    print(f"{name:20s} {params:10.2f} {macs:7.2f}  {tuple(f.shape)}  -> logits {tuple(out.shape)}")
model                params (M)   GMACs  feature output for 224 x 224
resnet18                  11.69    1.81  (1, 512, 7, 7)  -> logits (1, 1000)
resnet50                  25.56    4.09  (1, 2048, 7, 7)  -> logits (1, 1000)
mobilenet_v3_small         2.54    0.06  (1, 576, 7, 7)  -> logits (1, 1000)
mobilenet_v3_large         5.48    0.22  (1, 960, 7, 7)  -> logits (1, 1000)
efficientnet_b0            5.29    0.39  (1, 1280, 7, 7)  -> logits (1, 1000)
convnext_tiny             28.59    4.46  (1, 768, 7, 7)  -> logits (1, 1000)
vit_b_16                  86.57   16.85  (1, 197, 768)  -> logits (1, 1000)

The spread is large. MobileNetV3-Small has 2.54 million parameters and needs 0.06 billion multiply-accumulates per image; ViT-B/16 has 86.57 million and needs 16.85 billion, about 280 times more compute. ResNet-18 (11.69 M, 1.81 GMACs) and ResNet-50 (25.56 M, 4.09) reproduce the numbers in torchvision's model table, where "GFLOPS" means billions of multiply-accumulates (for ViT-B/16 that table lists 17.56, because its counter includes a few operations this one does not). EfficientNet-B0 needs less compute than ResNet-18 (0.39 against 1.81 GMACs) with fewer than half the parameters. Every CNN ends with a 7×77 \times 7 map (stride 32) and a channel count between 512 and 2,048; the ViT ends with 197 tokens of 768 numbers (196 patches and the class token), and its classifier reads only the class token.

Strides, measured

The output stride is a property of the architecture, so a backbone accepts any input size that is a multiple of 32 (most accept any size at all, thanks to the global pooling at the end; ViT is the exception, its position embeddings are learned for one grid of patches). The example sends a 224×224224 \times 224 and a 320×480320 \times 480 image through ResNet-18 and prints every stage:

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

m = resnet18(weights=None).eval()
stages = [("stem (conv1 + maxpool)", lambda t: m.maxpool(m.relu(m.bn1(m.conv1(t))))),
          ("layer1", m.layer1), ("layer2", m.layer2), ("layer3", m.layer3), ("layer4", m.layer4)]
for H, W in [(224, 224), (320, 480)]:
    t = torch.zeros(1, 3, H, W)
    print(f"input {H} x {W}")
    with torch.no_grad():
        for name, f in stages:
            t = f(t)
            print(f"  {name:24s} {tuple(t.shape)}  stride {H // t.shape[2]}")
        print(f"  {'avgpool + fc':24s} {tuple(m.fc(torch.flatten(m.avgpool(t), 1)).shape)}")
input 224 x 224
  stem (conv1 + maxpool)   (1, 64, 56, 56)  stride 4
  layer1                   (1, 64, 56, 56)  stride 4
  layer2                   (1, 128, 28, 28)  stride 8
  layer3                   (1, 256, 14, 14)  stride 16
  layer4                   (1, 512, 7, 7)  stride 32
  avgpool + fc             (1, 1000)
input 320 x 480
  stem (conv1 + maxpool)   (1, 64, 80, 120)  stride 4
  layer1                   (1, 64, 80, 120)  stride 4
  layer2                   (1, 128, 40, 60)  stride 8
  layer3                   (1, 256, 20, 30)  stride 16
  layer4                   (1, 512, 10, 15)  stride 32
  avgpool + fc             (1, 1000)

The stem divides by 4, layer1 keeps the resolution, and each later stage halves it, so the last map has stride 32 for both inputs: 7×77 \times 7 for 224×224224 \times 224, 10×1510 \times 15 for 320×480320 \times 480. The global average pooling turns either into the same 512 numbers, which is why the classifier works for both sizes. A detector reading layer2, layer3 and layer4 gets maps with strides 8, 16 and 32.

Choosing a backbone

Parameter counts and multiply-accumulates are measured above; accuracy needs trained weights. The ImageNet top-1 accuracies below are the values reported by torchvision's documentation for its IMAGENET1K_V1 weights (single 224×224224 \times 224 centre crop; the acc@1 values in each weights enum's meta, rounded to one decimal). They are a rough guide only: ImageNet accuracy predicts transfer to other tasks imperfectly, and latency depends on the hardware and runtime far more than MACs suggest (depthwise convolutions use the hardware less efficiently than dense ones, so MobileNets are less fast on GPUs than their MACs promise).

Backbone ImageNet top-1 (torchvision, reported) Good for
ResNet-18 about 69.8% baselines, small datasets, teaching, anything that must be simple
ResNet-50 about 76.1% (80.9% with the newer V2 weights) the standard reference; detection and segmentation backbones
MobileNetV3-Small about 67.7% phones and microcontrollers, very low latency
MobileNetV3-Large about 74.0% mobile and edge devices
EfficientNet-B0 about 77.7% good accuracy per MAC; scale up with B1 to B7
ConvNeXt-Tiny about 82.5% a modern CNN with transformer-level accuracy
ViT-B/16 about 81.1% large datasets, strong pretraining; image-text models

A practical order of questions: where does it run (a GPU server, a phone, a camera with a small accelerator: this sets the budget in milliseconds and megabytes); how much labelled data you have (little data favours a well-pretrained CNN; ViTs shine with large pretraining); what the task needs (dense prediction needs a backbone with a feature pyramid your detector or segmenter supports); what the deployment runtime supports (ONNX, TensorRT, Core ML, TFLite: every exotic layer is a risk). Then measure: latency on the target device with the real input size, and accuracy on your validation set after fine-tuning (pretrained models and transfer).

Pitfalls

  • Comparing MACs as if they were milliseconds. Measure latency on the target hardware with the batch size you will use.
  • Feeding a ViT a different image size without interpolating its position embeddings: it fails or silently degrades.
  • Assuming a "bigger" backbone helps on a small dataset: more parameters fine-tuned on a few thousand images overfit; a smaller pretrained network often wins.
  • Ignoring the input size. Compute grows with H⋅WH \cdot W: doubling the side of the input quadruples the MACs of every CNN in the table (and grows a ViT's attention cost by 16 times, with 4 times the tokens).
  • Mixing up weights versions. IMAGENET1K_V1 and V2 of the same architecture differ in accuracy and in the preprocessing they expect (weights.transforms() tells you).

Practice

  1. A 3×33 \times 3 convolution maps 256 to 256 channels on a 28×2828 \times 28 map. Compute the MACs of the standard and of the depthwise separable version, and their ratio.
  2. What is the size of ResNet-18's last feature map for a 640×640640 \times 640 input, and how many tokens does ViT-B/16 make from a 384×384384 \times 384 image?
  3. Why does EfficientNet scale width and resolution by smaller factors than depth?
Answer
  1. Standard: 28⋅28⋅256⋅256⋅9=462,422,01628 \cdot 28 \cdot 256 \cdot 256 \cdot 9 = 462{,}422{,}016. Separable: 28⋅28⋅256⋅9+28⋅28⋅256⋅256=1,806,336+51,380,224=53,186,56028 \cdot 28 \cdot 256 \cdot 9 + 28 \cdot 28 \cdot 256 \cdot 256 = 1{,}806{,}336 + 51{,}380{,}224 = 53{,}186{,}560. Ratio ≈0.115=1/256+1/9\approx 0.115 = 1/256 + 1/9.
  2. Stride 32: 20×2020 \times 20 (with 512 channels). (384/16)2=576(384 / 16)^2 = 576 patch tokens, plus the class token.
  3. Compute grows linearly with depth but with the square of width and of resolution, so equal factors would make width and resolution dominate the cost; the constraint αβ2γ2≈2\alpha \beta^2 \gamma^2 \approx 2 balances the three so each step doubles the compute.

Test yourself

What does an output stride of 32 mean for a backbone fed a 640 x 640 image?

  1. The model has 32 layers
  2. The last feature map is 20 x 20: each cell covers a 32 x 32 pixel step of the input
  3. The batch size is 32
  4. The image is cut into 32 patches

Why is a depthwise separable 3 x 3 convolution with many channels about 8 to 9 times cheaper than a standard one?

  1. It uses smaller images
  2. Its cost ratio is 1/C_out + 1/9, because spatial filtering is done per channel and channel mixing by a 1 x 1 convolution
  3. It skips half the pixels
  4. It has no weights

How many patch tokens does ViT-B/16 make from a 224 x 224 image (without the class token)?

  1. 16
  2. 49
  3. 196
  4. 224

Why can the same ResNet-50 be used in a classifier, Faster R-CNN and Mask R-CNN?

  1. Because all three tasks use the same labels
  2. Because the backbone only turns images into feature maps; each task adds its own head (pooling + fc, a detection head, a mask head) on top
  3. Because ResNet-50 has no classification layer
  4. It cannot