Convolution and Convolutional Neural Networks
A convolutional layer applies a shared set of small filters across spatial positions, producing translation-equivariant feature maps with far fewer parameters than a fully connected layer. The 2D cross-correlation operation, its stride/padding/dilation geometry, channel mixing, and im2col/GEMM implementation are the primitives behind every CNN.
1. Concept overview
A 2D convolutional layer slides a small kernel (filter) over an image and computes a dot product at every position. For a single-channel image and kernel ,
where is the stride. Deep learning libraries actually implement cross-correlation (no kernel flip); because is learned, the distinction is absorbed into the weights.
With input channels and filters, the kernel tensor has shape and the output has shape :
Three properties make CNNs work: sparse connectivity (each output depends on only inputs), parameter sharing (the same kernel is used at every position), and equivariance (shift the input and the output shifts with it). A fully connected layer from to 1000 units would need ~150M weights; a 64-filter conv needs only 1,792.
2. Why this concept exists
Flattening an image into a vector and using dense layers destroys spatial structure and is catastrophically parameter-hungry: a image has 150,528 inputs, so even 1000 hidden units require 150 million weights, with no invariance to translation.
Earlier approaches: hand-crafted features (SIFT, HOG) plus shallow classifiers; fully connected networks on small images; early "neocognitron" models with local receptive fields. The breakthrough was combining local connectivity, weight sharing, and backpropagation end-to-end (LeCun's LeNet for digit recognition, later AlexNet at ImageNet scale).
Convolution exploits stationarity of statistics in natural images: an edge detector useful in the top-left is useful everywhere. Sharing the detector across positions reduces parameters by a factor of roughly (e.g. 5,000× for a 224×224 map) and gives built-in translation equivariance. Pooling adds a degree of local translation invariance. These inductive biases are why CNNs need far less data than MLPs for vision and dominate when compute or data is limited.
3. Historical background
Hubel & Wiesel (1962, 1968) discovered simple and complex cells in the visual cortex, with local receptive fields and hierarchical feature selectivity — the biological inspiration.
Kunihiko Fukushima's Neocognitron (1980) introduced a hierarchical locally connected architecture with shared weights. Yann LeCun implemented backpropagation for convolutional networks at Bell Labs; his 1989 paper applied it to handwritten digits, and LeNet-5 (LeCun et al. 1998) was deployed in ATM cheque readers.
AlexNet (Krizhevsky, Sutskever & Hinton, 2012) won ImageNet with a deep CNN using ReLU, dropout, GPU training, and data augmentation, cutting top-5 error from ~16% to ~15% (vs ~26% for the best non-CNN) and triggering the deep-learning boom. Zeiler & Fergus (2013) visualized conv filters with deconvolution. VGG (2014) showed depth with uniform filters; GoogLeNet/Inception (2015) used multi-scale and bottlenecks; ResNet (He et al. 2015/2016) used skip connections to train 100+ layers. MobileNet (2017) popularized depthwise separable convolutions for mobile inference; Vision Transformers (2020) later challenged conv dominance by replacing local sharing with global attention.
4. Fundamental problem
Given an image (or feature map) with spatial structure, build a linear map that (a) detects local patterns at all positions, (b) uses a manageable number of parameters, (c) composes into a hierarchy from edges to object parts, and (d) supports efficient gradient-based training on GPUs.
Formally, we want a family of maps that are translation-equivariant: for integer shifts (up to boundary effects). A dense matrix multiplication cannot satisfy this; a shared local kernel does, exactly, for full convolutions with suitable padding. The remaining design questions — kernel size, stride, padding, dilation, number of channels, grouping — are the architecture hyperparameters explored in later modules.
5. First-principles explanation
Fact 1 — local receptive field. A neuron in a conv layer depends on a patch of the input (times all input channels). Natural images have strong local correlations, so local patterns (edges, corners, textures) are informative.
Fact 2 — stationarity and weight sharing. If a pattern detector is useful at one location, it is useful elsewhere. Using the same at every position reduces free parameters from to just per output channel, and makes the operation equivariant to translations.
Fact 3 — linearity plus nonlinearity. Each output is a dot product (a linear filter), so a stack of conv layers without nonlinearity would collapse to a single conv. Inserting ReLU (or GELU/SiLU) between layers lets the network compose filters into increasingly complex, nonlinear features.
Fact 4 — small kernels are enough. Two stacked convs have a receptive field of 5 with weights per channel pair, versus one with 25, and the stack has an extra nonlinearity — the design principle behind VGG.
Fact 5 — computation as matrix multiplication. Rearranging image patches into columns (im2col) turns convolution into a GEMM, which GPUs execute at high throughput. This is why conv layers are fast despite their apparent loop structure.
6. Prerequisite concepts
You need: (a) vectors, matrices, dot products, and matrix multiplication — a convolution output is a dot product between a flattened kernel and a flattened patch; (b) basic signal-processing intuition about filters, kernels, and cross-correlation; (c) backpropagation and the chain rule, to derive weight/input gradients; (d) feedforward networks, to understand why weight sharing is a regularizer; (e) NumPy array shape/broadcasting and PyTorch tensors, nn.Conv2d, and autograd for the implementations. Familiarity with image formats (channels × height × width, uint8 vs. normalized floats) is assumed; see the linked concepts for each prerequisite.
7. Complete mathematical formulation
Single-channel, full definition. With zero padding and stride ,
with out-of-range indices treated as zero. Output size: .
Multi-channel. For input , kernels and bias :
Parameter count: .
Dilation : sampling is , expanding the receptive field without extra parameters.
Groups : channels are split into disjoint groups; each filter connects only to one group, reducing parameters by . Depthwise convolution is .
1×1 convolution: ; it mixes channels with parameters and no spatial mixing — a learned per-pixel MLP, used for bottleneck dimensionality reduction.
Transposed convolution (deconv) is the transpose of the im2col linear map, used for upsampling; it is not a true inverse convolution.
8. Notation dictionary
| Symbol | Meaning | Type / shape | |---|---|---| | | input feature map | | | | output feature map | | | | kernel / filter tensor | | | | bias | | | | input/output channels | integers | | | kernel spatial size | integers, usually 1, 3, or 5 | | | stride | integers | | | zero padding | integers | | | dilation | integer | | | number of groups | integer | | | batch size | integer | | | spatial output index | pair of integers | | | upstream gradient | same shape as | | | unfolded patches | | | MAC | multiply–accumulate operation | one multiply + one add |
9. Step-by-step derivation
Step 1 — write the linear map. For a fixed output channel , the operation is where is the patch extracted from at position . This is a dot product between a flattened kernel and a flattened patch.
Step 2 — output size. The largest input index touched in the vertical direction is . Requiring it to be yields ; take the floor.
Step 3 — parameter sharing. A dense layer from patch to one output would use a different weight matrix per position. Sharing across positions gives the equivariance identity up to padded borders — prove it by reindexing the sum.
Step 4 — im2col. Stack all values of each patch as a column: the matrix has shape . Flatten kernels into . Then
This is an ordinary GEMM, the basis of efficient CPU/GPU implementations.
Step 5 — gradients. Let . Then (a GEMM) and , which is then "col2im"-folded back into ; equivalently, is a full convolution of with the spatially flipped kernel. Bias gradient: .
Step 6 — dilation/receptive field. A dilated kernel samples every -th pixel; the receptive field of layer is . This formula quantifies how depth, stride and dilation grow context.
10. Proofs and proof intuition
Proposition 1 (translation equivariance). For infinite zero-free signals (or ignoring boundaries), where shifts by pixels. Proof. for stride dividing ; for stride 1 the identity is exact. With padding, equivariance holds for positions away from the borders.
Proposition 2 (two vs one ). Two convs (stride 1) have receptive field , with weights per input–output channel pair vs. for one , and an extra ReLU. Proof. Apply the receptive-field formula with , , twice.
Proposition 3 (im2col equivalence). The GEMM computes exactly the convolution sums. Proof. Column of contains in a fixed order; row of contains in the matching order. Their dot product is the definition of .
Proposition 4 (depthwise-separable parameter count). Standard conv: . Depthwise + pointwise: , a reduction factor . Proof. Depthwise has one filter per input channel; pointwise is a conv. Add the counts. For , , : vs , a reduction.
11. Geometric interpretation
A convolution filter is a template matcher: its weights form a small pattern, and the output at a position is the cosine-similarity-like overlap (dot product) between that pattern and the image patch. A horizontal-edge filter responds strongly where intensity changes vertically; stacking layers composes simple templates into complex ones — the feature hierarchy from edges → textures → object parts → classes.
Think of the kernel as a sliding window over the image plane. The stride determines the lattice of window positions; padding controls how the window treats the border; dilation spreads the kernel's taps apart, like looking through a coarse stencil. The output feature map is a new image whose channels encode "how much of pattern is present here".
In parameter space, weight sharing constrains the linear map to a convolutional (block-Toeplitz) matrix: a huge dense matrix with most entries zero and many equal entries. The diagonal-ish band structure is what makes both storage and computation cheap, and the equalities encode the inductive bias of translation equivariance.
12. Visual explanation
Picture a transparent square with nine numbers in it sliding across a grid of pixel numbers. At each stop, multiply overlapping numbers pairwise and add: that single number becomes one pixel of the output map. An animation with the kernel highlighted and the running sum displayed makes the operation immediately concrete.
For multiple channels, imagine the same window over each of the red/green/blue planes, with a separate set of nine weights per plane; the three products are summed to one output pixel. Multiple filters produce a stack of output planes.
Use the Interactive Convolution Visualizer in Practical Labs: choose the kernel (edge, blur, sharpen), adjust stride/padding/dilation, and watch the output map change. Overlay the receptive-field box on the original image to see how depth grows context: after three layers the unit sees a patch, after four, .`,
Classic filter examples: (Laplacian edge detector), (box blur).
13. Numerical worked example
Single-channel valid convolution (no padding, stride 1). Let
The output is ; compute each position:
- .
- .
- .
- .
So .
Shape and parameter example. Input , 16 filters of size , padding 1, stride 1: , output . Parameters . Multiply–accumulates per sample .
Channel mixing. With two input channels and one filter, set ; the output at a position is simply the sum of the per-channel dot products. A conv with kernel tensor maps 3 channels to 4 using parameters at every spatial position.
14. Real-world analogy
Imagine scanning a page with a small magnifying glass that has a stencil cut out in the shape of the letter "e". You slide the stencil over the page, count how much ink lines up with the cutout at each position, and mark a dot whenever the count is high. That is a convolution filter acting as a feature detector. Using the same stencil everywhere is weight sharing; moving it a fixed number of millimetres each time is the stride; adding a blank margin around the page is padding. Stacking stages — first stencils for short strokes, then for curves, then for whole letters — mirrors a CNN's hierarchy.
15. Algorithm pseudocode
algorithm Conv2D_Naive(X, K, stride s, padding p):
# X: (C_in, H, W), K: (C_out, C_in, k_h, k_w)
pad X with p zeros on each spatial side -> X_pad: (C_in, H+2p, W+2p)
H_out <- floor((H+2p-k_h)/s)+1 ; W_out <- floor((W+2p-k_w)/s)+1
Y <- zeros(C_out, H_out, W_out)
for c_out = 0 .. C_out-1:
for i = 0 .. H_out-1:
for j = 0 .. W_out-1:
acc <- bias[c_out]
for c_in = 0 .. C_in-1:
for m = 0 .. k_h-1:
for n = 0 .. k_w-1:
acc <- acc + X_pad[c_in, i*s+m, j*s+n] * K[c_out,c_in,m,n]
Y[c_out,i,j] <- acc
return Y
algorithm Conv2D_im2col(X, K):
Xcols <- im2col(X) # (C_in*k_h*k_w, H_out*W_out)
Kflat <- reshape(K, (C_out, C_in*k_h*k_w))
Yflat <- Kflat @ Xcols # GEMM
return reshape(Yflat, (C_out, H_out, W_out))
16. Implementation from scratch
import numpy as np
def conv2d_naive(X, K, bias=None, stride=1, padding=0):
"""X: (C_in,H,W); K: (C_out,C_in,k_h,k_w) -> Y: (C_out,H_out,W_out)."""
C_in, H, W = X.shape
C_out, _, k_h, k_w = K.shape
Xp = np.pad(X, ((0,0),(padding,padding),(padding,padding)))
H_out = (H + 2*padding - k_h)//stride + 1
W_out = (W + 2*padding - k_w)//stride + 1
Y = np.zeros((C_out, H_out, W_out))
for c in range(C_out):
for i in range(H_out):
for j in range(W_out):
patch = Xp[:, i*stride:i*stride+k_h, j*stride:j*stride+k_w]
Y[c,i,j] = np.sum(patch * K[c]) + (bias[c] if bias is not None else 0.0)
return Y
# Worked example from section 13: single channel, valid convolution.
X = np.array([[1,2,0],[3,1,4],[2,0,5]], dtype=float)[None]
K = np.array([[1,0],[-1,2]], dtype=float)[None,None]
Y = conv2d_naive(X, K, stride=1, padding=0)
np.testing.assert_array_equal(Y[0], [[0,9],[1,11]])
# Shape check: 3 channels, 32x32, 16 filters 3x3, pad 1.
X2 = np.random.randn(3, 32, 32)
K2 = np.random.randn(16, 3, 3, 3)
Y2 = conv2d_naive(X2, K2, padding=1)
assert Y2.shape == (16, 32, 32)
print(Y2.shape, K2.size + 16)
For speed, replace the loops by im2col + GEMM: unfold X into Xcols of shape (C_in*k_h*k_w, H_out*W_out), then (K.reshape(C_out, -1) @ Xcols).reshape(C_out, H_out, W_out).
17. Professional library implementation
import torch
import torch.nn as nn
# nn.Conv2d expects (N, C_in, H, W) and kernels (C_out, C_in, k_h, k_w).
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3,
stride=1, padding=1, bias=True)
x = torch.randn(8, 3, 32, 32) # batch of 8 RGB images
y = conv(x) # (8, 16, 32, 32)
print(y.shape, sum(p.numel() for p in conv.parameters())) # 448
# Dilation: 3x3 kernel sees a 5x5 region when dilation=2.
dil = nn.Conv2d(3, 16, 3, padding=2, dilation=2)
print(dil(x).shape) # (8, 16, 32, 32)
# 1x1 bottleneck: 64 -> 32 channels at every position.
bottleneck = nn.Conv2d(64, 32, 1)
print(bottleneck(torch.randn(8,64,28,28)).shape) # (8, 32, 28, 28)
# Depthwise separable: depthwise (groups=C_in) then pointwise.
depthwise = nn.Conv2d(32, 32, 3, padding=1, groups=32) # 32*9 = 288 weights
pointwise = nn.Conv2d(32, 64, 1) # 32*64 = 2048 weights
print(sum(p.numel() for p in depthwise.parameters()),
sum(p.numel() for p in pointwise.parameters())) # 320, 2080 incl. bias
# Backprop works automatically through every layer.
loss = y.square().mean()
loss.backward()
print(conv.weight.grad.shape) # (16, 3, 3, 3)
Use torch.backends.cudnn.benchmark = True for fixed input sizes; in mixed precision torch.cuda.amp.autocast computes convs in fp16/tf32 with fp32 accumulation.
18. Code walkthrough
Naive implementation. np.pad with a triple ((0,0),(p,p),(p,p)) pads only spatial axes, leaving channels untouched. The output loops order c_out, i, j; for each location, patch has shape $(C_{\text{in}},k_h,k_w)$, which broadcasts against K[c] of the same shape, and the sum yields one scalar. This is Python-level operations — correct but slow; use it as a reference implementation in tests.
Shape assertions. The test assert Y2.shape == (16,32,32) catches the common off-by-one from padding/stride arithmetic; the parameter count K2.size + 16 includes one bias per output channel.
PyTorch version. nn.Conv2d stores weights in out_channels, in_channels/groups, k_h, k_w order; its forward is the optimized im2col/Winograd/cuDNN path. The groups=32 depthwise example connects each output channel to exactly one input channel, so the weight tensor has shape (32,1,3,3). The subsequent 1\times1 conv mixes channels. Gradients flow through all of them via autograd: conv.weight.grad has exactly the kernel shape.
Numerical equivalence. For small tensors, assert torch.allclose(nn.Conv2d(...)(x), torch.as_tensor(conv2d_naive(...))) with identical weights — an essential test when writing custom CUDA kernels.
19. Tensor and memory analysis
For a batch of images with shape in fp32 (4 bytes/element):
- input: bytes. For , : MB.
- a conv layer with , , pad 1, stride 1: output = 205,520,896 elements ≈ 822 MB in fp32 (411 MB in fp16). This is why activation memory, not weights, dominates CNN training.
- weights: plus 64 biases = 1792 elements ≈ 7 KB — negligible.
- im2col expansion: the input patch matrix has rows per spatial position vs. 3 in the original: a 9× memory blowup for kernels. cuDNN avoids materializing it via implicit GEMM or Winograd.
Backpropagation needs stored activations for each layer (roughly the sum of all layer outputs) plus gradient buffers of the same size; a ResNet-50 training batch of 256 at 224² can exceed 10 GB. Mitigations: mixed precision, activation checkpointing, smaller batches, and inference-only torch.no_grad().
20. Time complexity
For one sample, a conv layer costs multiply–accumulates (MACs); multiply by for a batch. Example: , 3→64 channels, : MACs ≈ 0.88 MFLOP per image (counting multiply+add as two operations). At that's 5.5G MACs ≈ 11 GFLOPs.
Computational savings:
- conv: MACs — used as a cheap bottleneck.
- depthwise separable: vs. standard ; for the numbers above, 7.9× fewer operations.
- stride reduces by .
The GEMM formulation reaches near-peak GPU throughput for large layers; small kernels may be memory-bound. Winograd transforms reduce multiplications by up to ~2.25× at the cost of more additions. Training adds a backward pass (≈2× forward compute for input and weight gradients), so a full step is ~3× the forward cost.
21. Space complexity
Model weights: per layer; e.g. 1,792 parameters for a 3→64 conv. Activations: per layer, which dominates training memory; gradient buffers of equal size are needed for backprop.
im2col temporarily needs — a factor over the input; implicit-GEMM implementations avoid this. Grouped/depthwise convolutions reduce both weight and activation-channel counts by in the depthwise stage.
Inference can discard intermediate activations as soon as they are consumed (or fuse conv+BN+ReLU), reducing memory to roughly the largest two feature maps; training with checkpointing recomputes activations in chunks, trading extra compute for instead of activation memory over layers.
22. Experimental demonstration
- Verify the worked example against
conv2d_naiveand againstnn.Conv2dwith identical weights (make a single filter withweight[0,0]=K), confirming the no-flip cross-correlation convention. - Time the naive loop vs. im2col/GEMM vs. cuDNN for : expect orders of magnitude difference; report GFLOPs achieved.
- Sweep stride/padding/dilation and record output shapes; verify the formula for at least 10 combinations, including cases where it is non-integer.
- Visualize learned first-layer filters after training a small CNN on CIFAR-10: expect Gabor-like edge detectors; compare with hand-coded Laplacian/blur kernels.
- Replace a standard 32→64 conv by depthwise-separable and measure both parameter count and ImageNet-scale latency; discuss accuracy vs. speed tradeoff (MobileNet results).
- Receptive-field check: build a stack of 3 stride-1 convs and use zero-one input probing to verify that an output pixel changes only when inputs within a window change.
23. Benchmark results
Reference ImageNet top-1/top-5 error trajectories (single-crop, validation set; approximate published figures): AlexNet (2012) ~15.3% top-5 error with ensembles; VGG-16 (2014) ~8.1% top-5; GoogLeNet (2015) ~6.7%; ResNet-50 (2015) ~5.25% top-5; ResNet-152 ~4.5%. These improvements came with 60M (AlexNet), 138M (VGG-16), 4M (GoogLeNet, using bottlenecks), and 25M (ResNet-50) parameters respectively — convolution design, not just scale, drove efficiency.
On mobile hardware, MobileNetV1 (Howard et al. 2017) reported ~4.2M parameters and ~569M MACs at 224×224, versus ~29M parameters and ~4.1B MACs for VGG-16, at a modest accuracy cost — a ~7× reduction in compute from depthwise separable convolutions.
Compute benchmarks are hardware- and library-specific: a 3×3 conv at 224² may run at hundreds of GFLOPs/s on a modern GPU but be memory-bound on CPU. Always report batch size, precision, library version, and whether batch-normalization/ReLU were fused into the timing.
24. Limitations
- Translation equivariance, not full invariance: object recognition usually needs pooling or attention to achieve invariance to position.
- Local receptive fields miss long-range dependencies; stacking many layers or using dilation is needed for global context (one reason transformers excel with large data).
- Fixed kernel geometry is a strong inductive bias: non-grid data (point clouds, graphs) require different operators.
- Parameter sharing can hurt when different image regions have genuinely different statistics (e.g. face alignment tasks).
- Small kernels plus pooling can discard precise spatial information needed for localization/segmentation.
- Depthwise separable convs reduce parameters but can be memory-bound and less hardware-friendly than dense GEMMs.
- Convolution is sensitive to input resolution and scale; multi-scale processing (feature pyramids, FPNs) is often required.
25. Failure scenarios
- Wrong output shape: mismatched padding/stride arithmetic; assert
H_out=(H+2p-k)//s+1before debugging further. - Channel mismatch:
nn.Conv2d(in_channels=3)fed a 4-channel tensor — usually a preprocessing mistake (RGBA vs RGB). - Kernel flipped unexpectedly: frameworks implement cross-correlation; if you port a MATLAB 'valid convolution' implementation, results differ unless you flip the kernel.
- Zero gradients: all inputs are zero in the receptive field (e.g. after ReLU dying), or the learning rate is too small; inspect activation histograms.
- Huge activation memory: storing all intermediate feature maps for a deep stack at large resolution; use checkpointing or mixed precision.
- Depthwise conv not learning: using
groups=C_inwith an output channel count that is not a multiple of groups; PyTorch requiresC_out % groups == 0. - Boundary artefacts: 'valid' padding shrinks the map each layer; use 'same' padding (p=(k-1)/2 for odd k, stride 1) when spatial size must be preserved.
26. Common misconceptions
- "CNN convolution flips the kernel, like mathematical convolution." Most libraries implement cross-correlation; the flip is unnecessary because weights are learned.
- "A stride of 2 makes the filter see more." It subsamples positions and reduces output resolution; dilation, not stride, expands the sampling pattern.
- "More channels always mean more parameters per output position, so bigger is worse." Channels also reduce the need for spatial width and enable rich feature compositions; parameter counts grow but so does representational capacity.
- "1×1 convolutions do nothing spatially." They mix channels at each pixel and are the workhorse of bottlenecks (Inception, ResNet).
- "Pooling is required after every conv." Modern architectures often use strided convs and global average pooling instead.
- "im2col is the convolution." It is an implementation trick; the mathematical operation is a dot product per position, and implicit GEMM avoids materializing the unfolded matrix.
- "Convolutions are invariant to translation." They are equivariant; invariance requires pooling or a global aggregation step.
27. Alternative approaches
- Fully connected (dense) layers: no inductive bias, many more parameters; useful only for small flattened inputs or final heads.
- Transformer / self-attention: global receptive field from layer 1, less inductive bias, needs more data; hybrids (ConvNeXt, Swin) blend both.
- Depthwise separable / grouped convolutions: parameter- and compute-efficient variants (MobileNet, ResNeXt).
- Dilated / atrous convolution: enlarges receptive field without pooling, used in semantic segmentation (DeepLab).
- Transposed convolution / interpolation + conv: learned upsampling for segmentation and generators.
- Winograd / FFT convolution: algorithmic acceleration for specific kernel sizes.
- Dynamic / deformable convolution: kernels or sampling offsets predicted per input, for geometric variation.
29. Research applications
- Image classification / detection / segmentation: the standard backbone family — ResNet, EfficientNet, YOLO, Mask R-CNN, U-Net.
- Medical imaging: CT/MRI segmentation with dilated convs and U-Net-style skip connections.
- Video: 3D convolutions (spatiotemporal kernels) and two-stream networks for action recognition.
- Generative models: DCGAN, diffusion-model U-Nets with residual conv blocks, and super-resolution (ESRGAN).
- Efficient inference: quantization, pruning, and separable convs for mobile/edge deployment.
- Interpretability: visualizing filters/feature maps, deconvolution, Grad-CAM, and studying the edge-detector hierarchy.
30. Important research papers
- Hubel D. H., Wiesel T. N. (1962), Receptive Fields, Binocular Interaction and Functional Architecture in the Cat's Visual Cortex, J. Physiology 160:106–154.
- Fukushima K. (1980), Neocognitron: A self-organizing neural network model for a mechanism of pattern recognition unaffected by shift in position, Biological Cybernetics 36:193–202.
- LeCun Y. et al. (1989), Backpropagation Applied to Handwritten Zip Code Recognition, Neural Computation 1:541–551.
- LeCun Y., Bottou L., Bengio Y., Haffner P. (1998), Gradient-Based Learning Applied to Document Recognition, Proc. IEEE 86(11):2278–2324 — LeNet-5.
- Krizhevsky A., Sutskever I., Hinton G. (2012), ImageNet Classification with Deep Convolutional Neural Networks, NIPS — AlexNet.
- Zeiler M. D., Fergus R. (2013), Visualizing and Understanding Convolutional Networks, ECCV.
- Simonyan K., Zisserman A. (2014), Very Deep Convolutional Networks for Large-Scale Image Recognition, arXiv:1409.1556 — VGG.
- Szegedy C. et al. (2015), Going Deeper with Convolutions, CVPR — Inception and 1×1 bottlenecks.
- He K. et al. (2016), Deep Residual Learning for Image Recognition, CVPR.
- Howard A. G. et al. (2017), MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications, arXiv:1704.04861.
31. Further reading
- Goodfellow, Bengio & Courville, Deep Learning (2016), chapter 9 — convolution networks and their inductive biases.
- Stanford CS231n notes on convolution/pooling layers and im2col: cs231n.github.io/convolutional-networks/.
- LeCun et al. (1998) for the original end-to-end CNN training pipeline.
- Zeiler & Fergus (2013) for filter visualization intuition.
- PyTorch documentation: torch.nn.Conv2d and torch.nn.functional.conv2d.
- NVIDIA cuDNN documentation for Winograd/implicit-GEMM implementation notes.
32. Practical exercises
- Implement
conv2d_naivefrom memory and verify the worked example exactly. - Implement im2col and col2im; assert that the GEMM result matches the naive convolution on random tensors for 10 shape configurations.
- Derive the output-size formula and verify it for .
- Implement the backward pass for conv manually (using
np.flipfor the input gradient and a GEMM for the weight gradient) and check againsttorch.autograd.gradcheck. - Build a depthwise-separable block in PyTorch; count parameters and compare with the standard conv for 32→64 channels, .
- Train a 2-conv-layer CNN on MNIST to >98% test accuracy; visualize the first-layer kernels and confirm Gabor-like structure.
33. Debugging challenges
- Output has the wrong spatial size: recheck
floor((H+2p-k)/s)+1; PyTorch uses floor division too, so mismatches indicate wrong padding or kernel size. - Batch norm after conv expects the wrong channel count:
nn.BatchNorm2d(C_out), not the flattened size. - Depthwise conv throws a shape error:
out_channelsmust be divisible bygroups. - Custom conv is 100× slower than PyTorch: you forgot im2col/GEMM; Python loops over every patch are not acceptable in production.
- Gradients are all zero: check that inputs are not detached, that ReLU units are not all dead, and that padding doesn't zero out the entire patch.
- ONNX export fails on a custom op: replace loops with standard
nn.Conv2dor register a symbolic. - Training OOMs: activation memory dominates; reduce batch, use fp16, or enable checkpointing.
34. Advanced exercises
- Prove translation equivariance formally including the padding boundary conditions; identify where it breaks.
- Derive the backward pass via im2col: show and that .
- Implement Winograd F(2×2,3×3) convolution and verify numerical equivalence and arithmetic-count reduction.
- Derive the receptive-field formula with mixed strides/dilations and verify byactivation probing on a 6-layer network.
- Implement grouped convolution with arbitrary and show parameter reduction ; compare training speed to standard conv at fixed FLOPs.
- Analyze when a conv is equivalent to a per-pixel MLP and prove that stacking layers is a deep MLP shared across positions.
35. Interview questions
- Write the multi-channel 2D convolution formula and the output-size formula; state the parameter count.
- Why is convolution equivariant rather than invariant? How do you get invariance?
- Explain im2col and why it makes convolution fast on GPUs. What is its memory cost?
- Why do two 3×3 convolutions beat one 5×5? Compare parameters and receptive fields.
- What does a 1×1 convolution do, and why is it used in Inception/ResNet bottlenecks?
- Derive the gradient with respect to the kernel in the im2col formulation.
- When would you use dilated or grouped convolution?
- How do depthwise separable convolutions reduce parameters and compute? Give the formula and an example.
36. Research questions
- How much translation equivariance is actually preserved by finite padding and strided pooling, and does it predict generalization to shifted test data?
- Can learned dynamic/deformable kernels beat fixed convolutions when data are limited, and under what regularization?
- What is the optimal tradeoff between locality (conv) and global mixing (attention) as a function of dataset size?
- How do hardware-aware design (Winograd, sparsity, quantization) and accuracy interact for edge inference?
- Do first-layer Gabor-like filters emerge universally, or are they an artefact of training data and optimization?
37. Mastery assessment
To pass: (1) derive the convolution formula, output size, and parameter count without notes; (2) compute a small convolution by hand and match code; (3) implement naive conv, im2col conv, and a PyTorch conv with matching outputs; (4) explain equivariance, receptive fields, and the 3×3 stacking argument; (5) derive the backward pass; (6) diagnose shape and memory failures; (7) answer the interview questions. Complete the linked assessment; reading alone is not mastery.
38. Implementation submission
Push a repository containing conv.py (naive, im2col, and depthwise implementations plus manual backward), experiments.ipynb (the worked example, shape sweep, naive-vs-cuDNN timing, filter visualizations, receptive-field probe), a README.md with derivations and measured FLOPs, and tests asserting equivalence with nn.Conv2d and the parameter counts (448 and 2,336/2,368). Submit the repository URL and exact reproduction command.
39. Completion criteria
All of: every section read; formulas derived on paper; three implementations passing equivalence tests; at least three experiments with recorded numbers and plots; assessment score ; one failure case (shape or memory) reproduced and explained; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`