Let's start with the smallest picture that still has something in it. It's a grayscale image, 5 pixels wide and 5 tall, stored as a grid of brightness numbers where 0 is dark and 9 is bright. Every row reads 0, 0, 9, 9, 9, so there's a dark strip on the left, a bright block on the right, and one vertical edge between them. You see that edge at once. A program only gets 25 numbers, and it has to find the edge in them. A real photo is the same thing on a bigger scale: a 224×224 colour image holds 224 × 224 × 3 = 150,528 numbers, one for each pixel in each of three colour layers (red, green and blue). This chapter builds a network that can take such a grid of numbers and say what's in it.
Chapter 04 gives us a first attempt, a stack of fully-connected layers in which every unit has its own weight for every input number. On a photo that gets out of hand quickly. A single layer of 1,000 units would need over 150 million weights, and every one of them is tied to one particular pixel position, so a cat learned in the top-left corner tells the network nothing about a cat in the bottom-right. Images have a structure that this design ignores. Nearby pixels belong together, and a pattern that's useful in one place is useful in another.
A convolution builds both facts in. We take a small grid of weights, a filter, and slide it across the image, reusing the same weights at every position. That one change cuts the weight count dramatically and lets a detector learned in one place work everywhere. Before 2012, vision systems mostly fed hand-designed features into a classical classifier. Then AlexNet showed that a deep stack of learned convolutions beat that approach by a wide margin, and convolutional networks (CNNs) became the default for images for the next decade.
We'll follow our 5×5 image through the chapter. First we slide a filter over it and see what comes out. Then we count what that costs in output size and weights, stack layers into a network, and ask why very deep stacks stopped training until residual connections arrived. After a short history of the architectures that followed, we put new heads on the same backbone to find objects and label pixels, and finish with what each of those choices costs you.
01A small filter, slid across the image
Let's take the fully-connected approach seriously for a moment, using our tiny image. If each of 9 output units gets its own weight for each of the 25 pixels, that's 9 × 25 = 225 weights for one layer, and each weight only knows about one pixel position. Scale the image up to 224×224×3 and a layer with 1,000 units needs over 150 million weights. There aren't enough labeled images in existence to learn that many independent numbers without overfitting, which means memorising the quirks of the training set instead of the pattern behind it. And since the weights are tied to positions, the network would have to see an object at every possible position during training to recognise it anywhere.
The convolution avoids both problems. Take a 3×3 filter, which is just nine numbers. Lay it over the top-left 3×3 patch of the image, multiply each filter number by the pixel underneath it, and add up the nine products. That's the dot product from chapter 01, and it gives a single number that's large when the patch looks like whatever the filter is built to detect. Now slide the filter one pixel to the right and do it again, and carry on across the row, then down to the next row. The numbers we collect form a new grid called a feature map, and the whole sliding procedure is a convolution. The filter also has one extra number, a bias, added to each result, so the filter has 9 weights plus a bias in total.
For our image, let's use a filter whose three rows are all [-1, 0, 1]. At each position it subtracts the pixel on the left from the pixel on the right, so it gives a big positive number wherever dark turns into bright. On the top-left patch the pixels in each row are 0, 0, 9, so each row contributes −0 + 0 + 9 = 9, and the three rows add up to 27. On the last patch every pixel is 9, so each row gives −9 + 0 + 9 = 0.
The code below does exactly this. It builds the image and the filter, then loops over the 3×3 grid of positions where the filter fits inside the 5×5 image. The slice img[i:i+3, j:j+3] is the patch under the filter, and multiplying it by k and calling .sum() is the dot product.
Try it Slide an edge-detecting filter over a tiny image
import numpy as np
img = np.array([[0, 0, 9, 9, 9]] * 5, dtype=float) # dark | bright
k = np.array([[-1, 0, 1]] * 3, dtype=float) # dark-to-bright
out = np.zeros((3, 3))
for i in range(3):
for j in range(3):
out[i, j] = (img[i:i+3, j:j+3] * k).sum()
print(out.astype(int))
27 in the two left columns of the output and 0 in the right one. Every row is the same because every row of the image is the same. The first two patches contain the jump from 0 to 9, and the last patch sees only bright pixels. The same nine filter weights were used at all nine positions.Look at the three columns of the output. The first two patches each include the dark-to-bright jump, so they both score 27, and the last patch sits entirely inside the bright block, so it scores 0. Nobody told the code where the edge was. The filter found it by being slid everywhere. In a real network the nine numbers aren't chosen by hand like this. They start random and get adjusted by gradient descent, so that the filter ends up detecting whatever pattern helps the task.
Why can one small filter do the work of so many weights?
Think of the filter as a stencil. A stencil has a fixed shape, and you don't cut a new one for every spot you want to stamp it. In the same way, the filter's size follows the pattern it looks for and has nothing to do with the size of the picture. Nine numbers describe a vertical edge, and that description doesn't get longer when the image does. Our filter has 9 weights and a bias on a 5×5 image, and it would have the same 9 weights and a bias on a 4096×4096 one. We call the reuse of the same weights at every position weight sharing.
Weight sharing bakes in two assumptions about images. Nearby pixels are related, which we call locality, so a filter only needs to look at a small window at a time. And a useful pattern stays useful wherever it appears, which gives us translation invariance: an edge detector that works in the top-left corner works in the bottom-right corner too, so the network never has to learn "edge at (5,5)" and "edge at (200,200)" as two unrelated facts. Both assumptions hold for almost every natural image, so a CNN doesn't spend parameters or training data rediscovering them. A fully-connected layer gets neither, because each output unit has an independent weight for every input pixel.
Parameter counts staying flat as the image grows, a detector transferring from one corner to every other, and layers that stay affordable as we add more of them all follow from this one property. A few settings control how the sliding happens. Stride is how far the filter moves between positions. Stride 1 checks every position, and stride 2 skips every other one, which halves the output resolution. Padding is a border of zeros added around the image before sliding, most often so the output stays the same size as the input. Dilation spreads the filter's nine sample points further apart, with gaps between them, so one filter sees a wider area without gaining a single weight.
The last setting is channels, the depth of the data. A colour image has three channels, one each for red, green and blue. A real convolutional layer doesn't run one filter. It runs dozens or hundreds of independent filters over the same input, and each one produces its own feature map: edges, corners, colour blobs, whatever gradient descent finds useful. Stacked together, those maps are the channels the next layer sees. So how big is the output, and how many weights does a layer have once channels come into it? Let's count.
02Counting output sizes and weights
In our example the 3×3 filter fitted into the 5-pixel row at 3 positions, so the output was 3×3. The general rule uses the input's width W, the filter size K, the padding P and the stride S:
- W the input's spatial width (or height, computed identically and usually equal for square feature maps) — e.g. 224 for a 224×224 input image, or whatever spatial size the previous layer output.
- K kernel size — the width/height of the learned filter, most commonly 3, sometimes 5 or 7 for an early "stem" layer.
- P padding — rows/columns of zeros added to each side of the input before sliding the kernel, most often chosen so the output stays the same spatial size as the input ("same" padding).
- S stride — how many pixels the kernel moves between applications.
S=1checks every position;S=2skips every other position and roughly halves the output size — this is exactly what a strided convolution uses to downsample instead of pooling. - ⌊⌋ + 1 the floor accounts for the kernel needing to fit fully inside the padded input (a fractional position isn't a valid convolution step); the
+1counts the starting position itself.
Try it on our image first. With W=5, K=3, P=0 and S=1 we get (5 − 3)/1 + 1 = 3, which matches the 3×3 output we computed. Add one ring of zero padding, P=1, and it becomes (5 − 3 + 2)/1 + 1 = 5, the same size as the input. Keep P=0 and use stride 2, and it becomes ⌊2/2⌋ + 1 = 2. For a bigger check, take ResNet's first layer, which puts a 224×224 input through a 7×7 kernel with stride 2 and padding 3. (224 − 7 + 2·3)/2 + 1 = (223)/2 + 1 = 111 + 1 = 112, a 112×112 output, exactly matching the published architecture.
Parameter count
Channels change the weight count too. A 3×3 convolution with C_in input channels and C_out output channels has exactly parameters. Each (input channel, output channel) pair contributes 9 weights, and each output channel adds one bias. Notice what the formula leaves out: the image's width and height. Run the same filters on a 32×32 image or a 4096×4096 image and the parameter count doesn't move. Only the compute does, because the same small filters get evaluated at more positions.
Compare that with a fully-connected layer mapping a 224×224×3 image (150,528 input values) to a modest 1,000-unit hidden layer, which has over 150 million weights in that one layer. With 9 · C_in · C_out weights reused at every position, learning from a realistic number of labeled images becomes a tractable problem. So one convolutional layer is cheap, but it only detects small local patterns like our edge. How do we get from edges to cats?
03Stacking layers into a network
A second convolutional layer, applied to the feature maps of the first, looks for patterns in a map of edges, so it finds patterns of edges: corners, curves, textures. A third layer finds patterns of those, such as parts of objects, and further up we get whole objects. This is a feature hierarchy, and it builds itself during training, because gradient descent adjusts every layer's filters to whatever helps the final answer. Each output unit in a deeper layer depends on a wider patch of the original image, called its receptive field, even though every individual filter only ever looks at a small window.
To widen the receptive field quickly, networks shrink the feature maps as they go. After halving the map, a 3×3 filter covers twice as much of the original image. Since shrinking throws away spatial positions, the network compensates by adding channels, so it can keep track of more kinds of patterns in less space. The result is a pipeline you can see in the diagram below: alternate convolution layers (each followed by a ReLU, the activation from chapter 04 that sets negative values to zero) with downsampling, shrinking space while channels grow. When the map is small enough, we average each channel's whole map down to one number (global pooling), flatten the result into a single vector, and hand it to a plain fully-connected layer whose softmax turns the class scores into probabilities.
Follow the sizes left to right. A colour image goes in, and the first block turns it into 112×112 with 64 channels. Each "pool /2" halves the width and height, giving 56×56 with 128 channels and then 28×28 with 256 channels. Global pooling collapses each of the 256 maps into one number, so the flattened vector has 256 entries, and the classifier head maps it to class scores. The three dashed amber squares over the input show how the area a single output unit can see grows at each stage.
Pooling versus strided convolution: two ways to downsample
Both operations shrink the feature map, and they differ in who decides how. Pooling applies a fixed rule with no learned parameters: max pooling keeps the largest value in each small window, and average pooling keeps the mean. It's cheap, and it gives a small amount of translation invariance almost for free, since a small shift in the input often doesn't change which value was the largest. A strided convolution downsamples by moving a learned filter more than one pixel at a time (stride 2 instead of 1), so the network gets to learn how to summarise each region.
Most modern backbones lean toward strided convolutions, or a mix of both, because letting gradient descent decide how to downsample beat the fixed rule often enough that max-pooling-everywhere fell out of fashion in the highest-performing designs. Pooling is still cheap, simple and common. With the pipeline in place, the obvious next move is to make it deeper, since deeper means more levels of the hierarchy. That turns out to be harder than it sounds, and you might already suspect why.
04Going deeper: why residual connections
By the mid-2010s, people were stacking convolutional layers deeper and deeper. Plain networks past roughly 20 layers, though, got harder to train. He et al. (2015) saw something that looks backwards: a plain, non-residual 56-layer CNN had higher training error than an 18-layer one. Training error is the error on the very data the network learns from. Overfitting would show up as low training error and high error on new data, so it can't explain a deeper network doing worse on its own training set.
Why couldn't the deep network just copy the shallow one?
In principle it can. A deeper plain network can always represent the shallower one exactly, by setting the extra layers to compute the identity and pass their input through unchanged. Capacity was never the issue, so the cause had to be an optimization failure: plain stochastic gradient descent, working through dozens of stacked non-linear layers, couldn't reliably find that identity mapping.
The fix, which chapter 04 introduced, is to make identity the starting point. A residual block computes instead of , where is the block's input and is the usual stack of convolutions. Whenever the learned branch contributes little, the block just passes the input through, so the network begins at "do nothing" and only has to learn a useful deviation, instead of learning identity the hard way through stacked layers. That single change took ImageNet-winning networks (ImageNet is a large benchmark collection of labeled photos) from roughly 19 layers (VGG) to 152 in the same year, and they were still improving, perhaps surprisingly, as depth grew. The figure below shows the smallest member of the family, ResNet-18, drawn out in full.
Reading it from top to bottom, you can pick out a convolutional stem at the start, four stages of residual blocks in which the channels grow and the spatial size shrinks (the same pattern as our diagram), then global pooling and a classifier head. With depth no longer the bottleneck, a lot of different ideas became worth trying, and the field produced a whole family of architectures. Let's see how they line up.
05How the architectures got here
Before 2012, vision pipelines fed hand-engineered features such as SIFT and HOG into a classical classifier like an SVM (a support vector machine). Those systems plateaued below what tasks needed and broke under changes in lighting, rotation or camera angle. AlexNet (Krizhevsky, Sutskever and Hinton, 2012) trained a deep convolutional network end to end on GPUs with ReLU and ImageNet, and beat the hand-engineered pipelines by a large margin, because the features were learned from pixels. VGG, Inception, ResNet and EfficientNet then refined the design, task-specific heads added detection, segmentation and pose estimation, and CNNs stayed the default until Vision Transformers (06) began taking over at the largest scales after 2020.
From LeNet to ResNet, one question at a time
Each architecture in this lineage answered a question the previous one left open, and interviewers tend to ask "why did X matter" more often than "when was X", so the reasons are the part worth keeping. LeNet (LeCun, late 1980s and 1990s) set the template on small images such as handwritten digits: convolution layers, pooling, and a small classifier head. The compute and data of its era couldn't scale it further.
AlexNet (2012) proved the template scales. Enough labeled data (ImageNet), enough compute (GPUs) and ReLU in place of saturating activations carried it past the hand-engineered features. ReLU mattered because it avoided the vanishing-gradient problem that sigmoid and tanh networks suffered at depth. VGG (2014) then made a simplicity argument: stop hand-tuning filter sizes per layer, stack small 3×3 convolutions repeatedly, and go deeper. Three stacked 3×3 convolutions see as much of the input as one 7×7, with more non-linearity and roughly 45% fewer parameters, 27·C² against 49·C² at equal channel count C.
Inception/GoogLeNet (2014) argued that a second axis mattered too. Instead of picking one filter size per layer, it runs several (1×1, 3×3 and 5×5) in parallel inside the same layer, and lets the network combine multi-scale information itself instead of betting on one receptive field size being right everywhere. Then ResNet (He et al., 2015) fixed the structural problem we saw in the last section, which is the same residual-connection idea introduced in chapter 04.
After ResNet: the efficiency lineage
Once depth stopped being the bottleneck, the next generation optimised for parameter and compute efficiency as well as raw accuracy. DenseNet connects each layer to every previous layer's output, not just the one before it. That encourages feature reuse and eases gradient flow through a different mechanism than ResNet's: concatenation instead of summation. EfficientNet scales depth, width and input resolution together in a fixed ratio (compound scaling) instead of growing one dimension alone, which gives a better accuracy per FLOP (a floating-point operation, the unit we count compute in) than scaling any single dimension.
MobileNet targets on-device inference and is built from depthwise separable convolutions. These split a standard convolution into a per-channel spatial filter followed by a 1×1 filter that mixes channels, doing almost the same job for a fraction of the parameters and compute. The cost ratio against a standard k×k convolution with N output channels is 1/N + 1/k², which for 3×3 kernels at typical channel counts is roughly 8–9× cheaper. And ConvNeXt (2022) is a more recent data point in the CNN-versus-ViT story. It took a standard ResNet, modernised the training recipe, and borrowed a handful of transformer design choices. A "pure" CNN can still match ViT-era accuracy when trained with modern tricks, which suggests that some of the ViT-era gains came from training recipes and not from attention alone.
All of these are classification backbones, designed to answer "what's in this image?" with a single label. Many real tasks need more than that, and they reuse the same backbones with different final layers.
06Finding objects and labelling pixels
The convolutional layers that produce feature maps are called the backbone, and the layers on top that turn those maps into an answer are called the head. Swap the head and the same backbone can answer a different question. Detection and segmentation both need two things from the backbone at once. Early layers have fine spatial detail, and late layers have strong semantic content but coarse resolution. Feature pyramids combine feature maps from several depths of the same backbone, which is the standard way detection and segmentation heads get both properties and avoid picking one depth and losing the other.
Object detection
Object detection asks "what objects are here, and where?". The answer is a class label plus a bounding box, a rectangle drawn around each object. Two families approach it differently. Two-stage detectors (R-CNN, then Fast R-CNN, then Faster R-CNN) first propose candidate regions that might contain an object, then run a second network to classify and refine each region individually. One-stage detectors (YOLO, SSD) skip the proposal stage and predict every box and class directly, everywhere on the image, in a single forward pass.
Most detectors in both families historically relied on anchor boxes, a fixed set of predefined box shapes tiled across the image, with the network predicting offsets from the nearest anchor and not raw coordinates. Anchor-free detectors predict box boundaries straight from each spatial location instead. That removes a category of shape hyperparameters, at the cost of a different and often simpler matching problem during training. How the two families compare on speed and accuracy comes up in the next section.
Segmentation
Segmentation asks a finer question than detection: where detection gives a box, segmentation gives a label for every pixel. It comes in three variants. Semantic segmentation answers "what class is this pixel?", so every pixel gets one of a fixed set of labels, and two adjacent cats come out as "cat, cat", indistinguishable as separate objects. Instance segmentation answers "which individual object does this pixel belong to?", and separates those two cats into two distinct instances. Panoptic segmentation combines both: every pixel gets a class label, and every pixel belonging to a countable "thing" (an object, as opposed to a background region like sky or road) also gets an instance id, so one unified output replaces two separate tasks.
Two architectures cover most of this ground. Mask R-CNN extends a two-stage detector into instance segmentation, doing everything Faster R-CNN does plus a small branch that predicts a pixel mask for each detected region. U-Net (Ronneberger et al., 2015) is the classic semantic segmentation architecture. It has an encoder that downsamples like a normal CNN, a decoder that upsamples back to the original resolution, and skip connections that carry fine spatial detail from encoder to decoder at matching resolutions. Why those skips are needed is the subject of the next section.
Other tasks built the same way
Several other vision tasks reuse the backbone-plus-head pattern. Pose estimation predicts pixel locations for a fixed set of keypoints, such as the joints of a human body, instead of a box or a mask. OCR and document understanding combine detection (where is the text?) with sequence recognition (what does it say?), and structured documents add layout analysis, which asks what role each block plays, whether a title, a table cell or a caption. Optical flow estimates, for every pixel, how it moved between two consecutive video frames, giving a dense motion field and not a single global camera motion.
Depth estimation predicts per-pixel distance from the camera. From a single image it's monocular, inherently ambiguous, and relies on learned priors, while a stereo pair lets you triangulate directly. Visual tracking follows a specific object's identity across video frames. It builds on detection and adds the constraint that the same physical object should keep the same identity over time. Finally, face recognition and metric learning train a network to produce embeddings where one identity's images land close together and different identities land far apart, in place of a fixed closed-set classifier. The same idea reappears constantly in retrieval and recommendation systems (16). Each of these choices of head and backbone comes with costs, so let's go through what they are.
07What each choice costs
Start with the two detector families. The table lays out how they differ, and the short version is that one is slower and more careful, and the other is faster and more direct.
| Two-stage (R-CNN family) | One-stage (YOLO / SSD) | |
|---|---|---|
| Core idea | Propose candidate regions first, then classify and refine each one individually | Predict every box and class directly, everywhere, in one forward pass |
| Speed | Slower — two networks run in sequence | Faster — a single pass, real-time capable |
| Accuracy (historically) | Higher, especially on small or overlapping objects, from the dedicated per-region refinement step | Historically lower, though better losses (e.g. focal loss, addressing the huge foreground/background imbalance one-stage detectors face) and feature pyramids have closed most of that gap |
| Typical use case | Offline or high-accuracy pipelines where latency matters less — e.g. medical image review | Real-time systems — video, robotics, mobile/edge deployment |
The "historically" in the accuracy row matters. The gap was real and large around 2015–2017, when Faster R-CNN clearly beat early YOLO and SSD on accuracy. Better losses and multi-scale features closed most of it over the following years, so for most production systems today a well-tuned one-stage detector is the default, and it's probably no longer a compromise made only when speed is forced on you. The idea that two-stage detectors are always meaningfully more accurate describes the 2015 situation.
Failure modes
Pooling (or a strided convolution) makes a network cheaper and more translation-invariant, and it destroys exact spatial detail on the way. After five rounds of halving, a 224×224 input is down to 7×7, and the network no longer knows which original pixel any given feature came from. That suits classification, since "is there a cat in this image?" doesn't need pixel-exact detail. Segmentation does need it, because it has to label every original pixel, and that detail is gone from the bottleneck.
Why do U-Net's skip connections fix this?
At each resolution level, the encoder's feature map from before it was downsampled is copied straight across to the matching level in the decoder and concatenated with the upsampled features. Without the skip, the decoder has to reconstruct a precise object boundary from a heavily compressed, low-resolution bottleneck. That information was thrown away several pooling steps ago and isn't recoverable. The skip connection hands the decoder back exactly the spatial detail the encoder saw before pooling, at exactly the resolution needed to draw a sharp edge.
Built-in assumptions: a head start and a ceiling
Remember the two assumptions from section 01, locality and translation invariance. They're a genuine strength when data is scarce. The network doesn't have to spend training examples learning that images have local structure, because that's wired into the architecture before training starts, so a CNN reaches good accuracy from comparatively little labeled data. But a baked-in assumption is also a ceiling. At very large scale, an architecture with fewer built-in assumptions and more freedom to learn spatial structure directly from data has empirically scaled further. That architecture is the Vision Transformer (08 covers the attention mechanism, and 06 covers ViT specifically), and its freedom becomes an advantage once dataset size and compute are large enough.
So where does that leave CNNs in 2026? Their backbones remain the default wherever inference budget or labeled data is limited: mobile and edge deployment, and transfer-learning pipelines fine-tuned on a modest labeled dataset. The reasons are the low-data inductive bias described above and a decade of mature tooling built around it. At the frontier end, ViT-based and hybrid conv-transformer backbones (06) are now the default for large-scale pretrained vision foundation models. "CNNs are obsolete" is an overclaim. It's a scale- and data-dependent tradeoff and not a strict replacement, and exactly where the line falls is what 06 covers next.
08Summary
- A convolution is a small filter slid across the image. At each position it takes a dot product with the patch underneath, and the grid of results is a feature map.
- Weight sharing is what makes it cheap. A 3×3 filter has 9 weights and a bias whatever the image size, while a fully-connected layer on a 224×224×3 photo needs over 150 million.
- It builds in two assumptions about images, locality and translation invariance, so a detector learned in one place works everywhere.
- Output size follows one formula,
⌊(W − K + 2P)/S⌋ + 1, and a layer's weight count,9·C_in·C_out + C_outfor 3×3 filters, never depends on image size. - Stacking layers builds a feature hierarchy from edges to textures to parts to objects, and each deeper unit has a wider receptive field.
- A classification CNN shrinks space while growing channels, then pools globally and hands a vector to a classifier head. Pooling uses a fixed rule, while strided convolution learns how to downsample.
- Plain networks got worse when made deeper, even on training data, because of an optimization failure. Residual blocks compute
f(x) + xso identity is the default, and that took networks from about 19 layers to 152. - Each architecture answered one question: AlexNet showed the template scales, VGG showed stacked 3×3 filters suffice, Inception ran several filter sizes in parallel, ResNet fixed depth, and MobileNet and EfficientNet cut cost.
- Heads turn a backbone into other tasks. Detection produces boxes (two-stage or one-stage, with or without anchors), and segmentation labels pixels (semantic, instance or panoptic).
- Downsampling destroys spatial detail, which is fine for classification and fatal for segmentation. U-Net's skip connections copy that detail back to the decoder.
- CNNs win when data or compute is limited, and ViT-style backbones pull ahead at large scale. Neither has replaced the other.
09Build this
Nobody tells a convolution to look for edges. It finds them anyway, and the fastest way to believe that is to plot the filters yourself.
Train a small CNN on CIFAR-10, then render its first convolutional layer's filters as images. The classification task is ordinary on purpose. The reveal is the filter grid. It starts as random noise and ends up looking like a page from a signal-processing textbook nobody handed the network.
- Write the convolution yourself first. Loop over output positions, dot the kernel with the patch underneath, and check the answer matches
nn.Conv2don a random input. Use the library version afterwards so training finishes. - Build a small CNN: a 7×7 first conv with 32 filters, then three 3×3 blocks with stride-2 downsampling, global pool, one linear head. The first kernel is large on purpose, so the filters are legible when plotted. Size each layer with the formula from §02.
- Before any training, render those 32 filters as tiny RGB images on a grid and save that picture.
- Train for a few epochs. Re-render the same grid after every epoch. Then push one test image through and plot the 32 activation maps the first layer produces.
- Now break it: replace the whole conv stack with an MLP of matching parameter count and train it identically.
- Shift every test image two pixels to the right. Re-evaluate both models on the shifted set.
Where this runs in production
Say the constraint is a phone-class NPU running object detection at 30 fps — roughly a 33ms budget per frame. Every choice covered above becomes a concrete lever and stops being abstract:
- Backbone: a MobileNet-style stack built from depthwise separable convolutions rather than standard convolutions. Illustrative at
C_in = C_out = 256: a standard 3×3 convolution costs9·256·256 ≈ 590,000parameters (and proportional FLOPs); splitting it into a depthwise 3×3 (one filter per channel,9·256 ≈ 2,300parameters) followed by a pointwise 1×1 that mixes channels (256·256 ≈ 65,500parameters) does nearly the same job for roughly 8–9× fewer parameters and FLOPs — the difference between fitting the latency budget and not. - Detector head: one-stage (YOLO/SSD-style) rather than two-stage — a single forward pass fits inside the budget; a two-stage detector's second region-by-region pass does not.
- Downsampling: strided convolutions folded into the backbone rather than separate pooling layers, so downsampling doesn't cost an extra pass over the data.
- Anchors: a small anchor set tuned to the object scales that occur in the target use case, rather than the broad, expensive anchor sets tuned for general-purpose benchmarks — fewer anchors means fewer candidate boxes to score every frame.
None of this is an exotic trick list — every item is a direct, mechanical consequence of an idea already covered above: fewer parameters per layer, one forward pass instead of two, and letting the network fold downsampling into a convolution it's already computing rather than paying for a separate operation.
10Vision is not one task
"Computer vision" names a dozen different problems that happen to share an input type. The backbone is often identical. What changes is the head, the shape of the label, and what counts as a failure.
Section §06 introduced detection and segmentation as families of task head, and this is the practical version. For each problem: what goes in, what comes out, what makes it hard, and what you would reach for now.
- Image classification. In: one image. Out: one label. It is the easiest member of the family, and the one where architecture choice matters least. The decision that matters is which pretrained weights you start from.
- Object detection. Out: a variable-length list of boxes with labels. The variable length is the hard part: a network with a fixed-size output has to be coerced into emitting a set, and that coercion is the entire design problem.
- Semantic segmentation. Out: a class label for every pixel. Hard because you need pixel-exact boundaries from a backbone that threw spatial detail away while downsampling. Skip connections (§07) exist for exactly this.
- Instance segmentation. Out: one mask per object, plus a class. Two adjacent cats become two masks. Masks are allowed to overlap, and nothing requires you to label the background at all.
- Panoptic segmentation. Out: exactly one class and one instance id for every pixel, background included. It is not a union of the two above, for reasons that deserve a subsection of their own.
- Keypoint and pose estimation. Out: pixel coordinates for a fixed skeleton of joints. Joints get occluded constantly, and you still have to work out which person a detected elbow belongs to.
- Depth estimation. Out: distance from the camera, per pixel. A stereo pair lets you triangulate geometrically. A single image does not: absolute scale is unrecoverable, so a monocular model leans on learned priors about how big things usually are.
- Tracking. Out: detections plus a consistent identity across frames. Detection quality is rarely the bottleneck here; identity is, and the signature failure is the ID switch, where two objects cross paths and swap labels.
Why detection needed anchors, and then stopped
A convolutional head emits a fixed grid of predictions. Objects arrive as a variable-length set. Something has to decide which output slot is responsible for which real object. That assignment problem is the thing every generation of detector has been attacking.
Anchors were the first answer: tile a set of predefined box shapes across every location, then assign each ground-truth object to whichever anchor overlaps it most. The network predicts an offset from that anchor rather than raw coordinates, and regressing a small correction is far easier than regressing an absolute box from nothing.
Anchors bought tractability and charged for it:
- Hyperparameters. How many shapes, which aspect ratios, which scales. All tuned per dataset, none of them learned.
- Class imbalance. Most anchors match nothing, so easy background examples swamp the gradient. Focal loss was designed specifically to stop that drowning effect.
- Duplicate predictions. Several anchors fire on the same object, so you need non-maximum suppression afterwards to clean up.
Anchor-free detectors predict box edges straight from each spatial location, deleting the shape hyperparameters outright. DETR went further still, reframing detection as direct set prediction: it matches predictions to ground truth with the Hungarian algorithm during training, and so removes NMS by construction rather than by post-processing.
Anchors, anchor-free heads and set prediction look like three unrelated architectures. They are three answers to one question: which prediction should be held responsible for which object?
Anchors answer it with a hand-designed geometric prior. Anchor-free heads answer it with spatial position. DETR answers it by solving an explicit matching problem during training.
If an interviewer asks why detection is harder than classification, this is the answer. Classification has one output and one label. Detection has to invent a correspondence.
Why panoptic is not semantic plus instance
Kirillov et al. (2019) defined panoptic segmentation with a hard constraint: every pixel gets exactly one class label and one instance id, with no overlaps and no gaps.
You cannot reach that by running two models and merging their output:
- Instance masks may overlap. Two predicted masks claiming the same pixel is legal in instance segmentation and illegal in panoptic, so something has to arbitrate.
- Instance segmentation ignores the background. Sky, road and grass have no countable instances, so an instance model has nothing to say about them.
- Semantic segmentation cannot split objects. It covers every pixel, but two touching cars come back as one undifferentiated "car" region.
The vocabulary is the part worth keeping. Things are countable: cars, people, bottles. Stuff is not: road, sky, vegetation. Panoptic gives things an instance id and leaves stuff without one.
Mask2Former resolved the split architecturally. Predict a set of binary masks, each carrying one class label. Semantic, instance and panoptic then become the same model output, read three different ways.
11Where you meet this in the wild
Almost none of these deployments look like ImageNet. The label format is usually the thing that changes, and the interesting engineering happens around the model.
- Local texture or shape decides the answer. Defects, tissue boundaries, edges. Locality is a correct assumption here, and you get it for free.
- You have modest labelled data and a pretrained backbone. The inductive bias substitutes for examples you do not have.
- Compute or latency is tight. Edge devices, real-time video, embedded hardware. The tooling is mature and the models are small.
- Your input is not three-channel RGB: multispectral, depth or stacked medical slices all drop straight in.
- The answer depends on relating distant parts of the image. Attention models that assumption instead of fighting it. See 06.
- You have large-scale pretraining available: past a certain data budget, fewer built-in assumptions scale further, which is the tradeoff §07 lays out.
- The problem is geometric with known mathematics. Calibration, homographies, and stereo rectification are solved analytically, and learning them gives a worse answer.
- Labels are the bottleneck. Promptable models like SAM can cut annotation cost far more than a better backbone would.
12Interview questions
BeginnerWhat does a convolution actually compute, and why does weight sharing matter?
A convolution slides a small learned filter over every position of the input, computing a dot product between the filter and the patch underneath at each position. Reusing the same filter (weight sharing) at every position gives two things: far fewer parameters than a fully-connected layer, since the filter's size doesn't depend on the image's size, and translation invariance, since a pattern learned in one position is automatically recognized in every other position.
BeginnerPooling vs. a strided convolution — what's the actual difference?
Both downsample the spatial size of a feature map. Pooling (max or average) applies a fixed, hard-coded rule with zero learned parameters — cheap, and gives a bit of translation invariance for free. A strided convolution downsamples using its learned weights, moving the filter more than one pixel per step, which lets the network learn how to summarize each region instead of following a fixed rule. Most high-performing modern backbones lean toward strided convolutions or a mix, rather than pure pooling everywhere.
IntermediateDerive the output spatial size of a convolutional layer.
W_out = ⌊(W − K + 2P) / S⌋ + 1, where W is input width, K is kernel size, P is padding on each side, and S is stride. The kernel needs K input positions to produce one output; padding effectively extends the usable width to W + 2P; dividing by stride and flooring counts how many valid starting positions fit; the +1 counts the first position. Concrete check: ResNet's stem uses a 224 input, K=7, P=3, S=2: (224 − 7 + 6)/2 + 1 = 111 + 1 = 112.
IntermediateWhy did ResNet's residual connections specifically fix the degradation problem — why wasn't it just an overfitting issue?
He et al. showed that a plain (non-residual) deeper network could have higher training error than a shallower one — not a generalization gap, worse error on the training set itself. Since a deeper plain network can always represent the shallower function exactly (set extra layers to identity), this had to be an optimization failure: plain SGD struggled to find the identity mapping through many stacked non-linear layers. A residual block computes instead of , making identity the default whenever the learned branch contributes little, so the network only has to learn a useful deviation from "do nothing" rather than learning identity the hard way.
IntermediateWhen would you actually choose a two-stage detector over a one-stage one today?
When the latency budget genuinely allows for it and the task rewards the extra accuracy a dedicated per-region refinement step gives — small or heavily overlapping objects, or offline/high-stakes review pipelines like medical imaging — rather than real-time constraints. For most real-time or edge deployments, a well-tuned one-stage detector has closed most of the historical accuracy gap and is the default choice, not a fallback.
DeepWhy do skip connections matter specifically for segmentation?
An encoder built from repeated pooling/stride-2 convolutions destroys exact spatial detail as it downsamples — after several halvings, the network no longer knows precisely which original pixel a feature came from. That's harmless for classification but fatal for segmentation, which needs a label for every original pixel. U-Net's skip connections copy the encoder's feature map at each resolution directly across to the matching resolution in the decoder, concatenating it with the upsampled features. Without that connection, the decoder would have to reconstruct sharp object boundaries purely from a heavily compressed low-resolution bottleneck — detail that was already thrown away and isn't recoverable from the bottleneck alone.
DeepYou're choosing a backbone — CNN or ViT — for a new vision product with a modest labeled dataset, tens of thousands of images. Which do you pick, and why?
The deciding factor isn't "CNN vs. ViT" in the abstract, it's how much data and pretraining you actually have access to. A CNN's built-in locality and translation-invariance assumptions give it a strong head start on modest data, so a CNN — or better, a CNN pretrained on a large dataset and fine-tuned on yours (transfer learning) — is the safer default when data is limited. A ViT can still win, but only by leaning on large-scale pretraining (06) to learn spatial structure it doesn't get for free architecturally; training a ViT from scratch on tens of thousands of images, with no pretraining, typically underperforms a comparable CNN.
13Go deeper
●Now write it yourself
Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.
Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.