CNN Foundations: Why Images Need Convolutions, Kernels, Stride & Padding
Why flattening images into MLPs explodes parameter counts and breaks spatial geometry, how sliding 2D kernels detect edges everywhere via weight sharing, and exact stride/padding output-size math.
Convolutions cut Layer 1 parameters on a 224×224 image from 154 MILLION down to 1,728 — an 89,000× efficiency breakthrough!
Even in the Vision Transformer era, hybrid CNN stems (ConvNeXt, ResNet, Diffusion U-Nets, YOLO, audio Conv1d) remain the fastest, most data-efficient way to extract local spatial and temporal features.
Knowing the exact output-shape formula ⌊(H + 2P − K)/S⌋ + 1 lets you trace (B, C, H, W) shapes across an entire vision backbone in your head without shape-mismatch crashes.
Top Computer Vision interview question: 'Why can't we just flatten a 224×224 RGB image into an MLP? And compute the exact output shape and parameter count of Conv2d(3, 64, kernel_size=3, stride=2, padding=1)!'
You pass a 32 × 32 image through nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1). What is the exact output height and width?
- Explain the two inductive biases of CNNs: spatial locality and translation equivariance via weight sharing
- Compute exact 1D and 2D cross-correlation dot products by hand for edge, blur, and sharpen kernels
- Calculate exact output tensor dimensions using H_out = ⌊(H + 2P − K) / S⌋ + 1
- Implement 1D and 2D convolutions from scratch and with idiomatic PyTorch nn.Conv2d
Imagine looking for a red stop sign in a giant photo using a small magnifying glass (3×3 kernel). Instead of memorizing a separate stop-sign template for every single pixel coordinate on Earth (which is what a flattened MLP tries to do!), you slide the exact same magnifying glass left-to-right and top-to-bottom across the entire image. Wherever the pixels inside the glass match the pattern, the output map lights up brightly!
1. Why Flattening Images Breaks MLPs (Locality & Translation Equivariance)
Flattening a 224 × 224 × 3 photo into a 1D list of 150,528 numbers destroys 2D neighborhood structure (pixels directly above/below each other end up 224 indices apart!) and forces a massive weight matrix.
The Two Inductive Biases of Convolutions
- Spatial Locality: Nearby pixels form edges, corners, and textures — a neuron only needs a small local window, not all 150,528 pixels at once.
- Translation Equivariance (Weight Sharing): Applying the same kernel everywhere means if an object shifts 10 pixels right in the input, its activation simply shifts 10 pixels right in the feature map: .
2. The Sliding 2D Kernel: Cross-Correlation & Feature Maps
In Deep Learning, nn.Conv2d technically computes cross-correlation (sliding the kernel without flipping it 180° — since weights are learned, flipping doesn't matter!). Watch the 3×3 filter glide across the image in our Flagship Deep Lab below!
2D Convolution Formula (Single Channel)
- Vertical Edge Detector:
[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]outputs0on flat regions and a huge positive/negative spike right on vertical brightness jumps! - Learned Filters: Instead of hand-crafting Sobel filters, backpropagation learns all weights directly from data — Layer 1 discovers oriented edges & color blobs, deeper layers compose eyes, wheels, and faces!
3. Stride, Zero-Padding & Exact Output-Shape Arithmetic
Without padding, every 3×3 conv shaves 2 pixels off height and width — after 16 layers, a 32×32 image would vanish completely! Slide H, K, P, and S below to build instant muscle memory for the output-shape formula.
Master Output-Shape Equation
SamePadding (for odd and ): Set (so , ) to keep !- Dilated (Atrous) Convolution (): Inserts gaps of zeros between kernel taps, expanding effective kernel size to with zero extra parameters!
H_out = ⌊(H + 2P − K) / S⌋ + 1
Original height plus P zero-pixels added to BOTH top and bottom borders.
H = 224, K = 7, P = 3, S = 2 (ResNet's stem conv!), ⌊(224 + 6 − 7)/2⌋ + 1 = ⌊223/2⌋ + 1 = 111 + 1 = 112!Worked Example: Computing One 3×3 Edge-Detector Cell by Hand
Apply vertical-edge kernel W = [[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]] (bias b=0) to patch X = [[2, 2, 8], [2, 2, 8], [2, 2, 8]].
Left column: ; Middle column: ; Right column:
Conv2d Output-Shape Calculator
What padding P preserves exact spatial size (H_out = H) for a 5 × 5 convolution with stride = 1?
You apply nn.Conv1d(in_channels=16, out_channels=32, kernel_size=5, stride=2, padding=2) to an audio tensor of shape (8, 16, 100). What is the exact output tensor shape?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
An odd kernel has a true center pixel and allows symmetric integer padding P = (K−1)/2 on all four sides! Even kernels require asymmetric padding, which shifts feature maps by half a pixel.
Animated 2D Convolution & Edge-Detector Studio
Watch a 3×3 filter window glide pixel-by-pixel across a 5×5 input image, multiplying and summing each patch into the live 3×3 output feature map.
(C_out, C_in, K, K)) to achieve translation equivariance with thousands of times fewer parameters than MLPs, with output shape ⌊(H + 2P − K)/S⌋ + 1.Computer Vision Stems
ResNet, ConvNeXt, YOLO, and Diffusion U-Nets all open with Conv2d layers to extract local edge & texture maps.
Audio & Speech (Whisper / WaveNet)
OpenAI Whisper uses two Conv1d layers on Mel spectrograms before the Transformer encoder.
Time-Series & Sensor Analytics
Dilated Conv1d captures multi-scale temporal patterns in financial, IoT, and medical ECG signals.
Hybrid Vision-Language Encoders
Patch-embedding in ViT (Conv2d(3, D, kernel_size=16, stride=16)) is literally a single strided 2D convolution!
import torch
import torch.nn as nn
# 1. From-Scratch 1D Convolution (exact sliding dot product)
def conv1d_scratch(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, stride: int = 1, padding: int = 0):
# x: (B, C_in, L), weight: (C_out, C_in, K), bias: (C_out,)
if padding > 0:
x = torch.nn.functional.pad(x, (padding, padding))
B, C_in, L_pad = x.shape
C_out, _, K = weight.shape
L_out = (L_pad - K) // stride + 1
out = torch.zeros(B, C_out, L_out, device=x.device, dtype=x.dtype)
for t in range(L_out):
patch = x[:, :, t * stride : t * stride + K] # (B, C_in, K)
out[:, :, t] = torch.einsum("bck,ock->bo", patch, weight) + bias
return out
# 2. Idiomatic Production PyTorch Conv2d
conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=2, padding=1, bias=False)
x_img = torch.randn(8, 3, 224, 224) # (B=8, C=3, H=224, W=224)
y = conv(x_img) # (8, 64, 112, 112)
+ 1 at the end of ⌊(H + 2P − K)/S⌋ + 1.H=3, K=3, P=0, S=1: a 3×3 filter fits inside a 3×3 image 1 time, proving the +1!(B, H, W, C) like NumPy/TensorFlow.(B, C, H, W)!(C_out, C_in, K_h, K_w).(C_in, K, K) filter.28 × 28 image passed through Conv2d with K=3, P=1, S=2?nn.Conv2d(3, 64, 3) have far fewer parameters than a dense nn.Linear(224*224*3, 64)?P gives a 'same' convolution (H_out = H) when K = 3 and S = 1?16×16 non-overlapping patches) is mathematically identical to which PyTorch layer?