Chapter 23 of 42 · ~28 min read & lab+80 XP
Chapter 23 · Deep Learning

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.

Why ML Engineers & Data Scientists Actually Need This

Convolutions cut Layer 1 parameters on a 224×224 image from 154 MILLION down to 1,728 — an 89,000× efficiency breakthrough!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

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)!'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
(B, C, H, W)Say aloud:“Batch, Channels, Height, Width”
Plain-English Meaning
PyTorch's standard 4D image tensor layout (NCHW)
Everyday Example
(32, 3, 224, 224) = 32 RGB images
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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)

Everyday Story First (Zero Math Yet!)

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.

Why Images Need Convolutions: Locality + Translation Weight SharingFlattened MLP on 224×224×3 Image150,528 inputs × 1,024 hidden154,140,672 params!Shift a cat 2 pixels right → completelydifferent weights fire (zero spatial sharing!)3×3 Conv2d (64 Shared Filters)3 × 3 × 3 × 64 filters1,728 params (89,000× smaller!)Same 3×3 edge detector slides everywhere→ Translation Equivariance built-in ✓
Flattening a 224×224 RGB image into a 1,024-unit MLP needs 154 MILLION weights in Layer 1 alone and breaks translation equivariance; a 3×3 Conv shares just 27 weights per filter across the entire image!

The Two Inductive Biases of Convolutions

  1. Spatial Locality: Nearby pixels form edges, corners, and textures — a neuron only needs a small local 3×33 \times 3 window, not all 150,528 pixels at once.
  2. Translation Equivariance (Weight Sharing): Applying the same 3×33 \times 3 kernel everywhere means if an object shifts 10 pixels right in the input, its activation simply shifts 10 pixels right in the feature map: f(shift(x))=shift(f(x))f(\text{shift}(x)) = \text{shift}(f(x)).

2. The Sliding 2D Kernel: Cross-Correlation & Feature Maps

Everyday Story First (Zero Math Yet!)

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: Sliding a 3×3 Kernel Over a 5×5 Input → 3×3 Feature MapInput (5×5)∗Kernel (3×3)-101-101-101Output Map (3×3)Output[i, j] = Σ_{u,v} Input[i·S + u, j·S + v] · Kernel[u, v] + bias
A 3×3 convolution slides across the 5×5 input image computing dot products at every spatial location — producing a 3×3 feature map that lights up wherever the pattern appears.

2D Convolution Formula (Single Channel)

Y[i,j]=b+∑u=0K−1∑v=0K−1X[i⋅S+u,  j⋅S+v]⋅W[u,v]Y[i, j] = b + \sum_{u=0}^{K-1} \sum_{v=0}^{K-1} X[i \cdot S + u, \; j \cdot S + v] \cdot W[u, v]

  • Vertical Edge Detector: [[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]] outputs 0 on flat regions and a huge positive/negative spike right on vertical brightness jumps!
  • Learned Filters: Instead of hand-crafting Sobel filters, backpropagation learns all 3×33 \times 3 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

Everyday Story First (Zero Math Yet!)

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.

Output Size Formula: H_out = ⌊(H + 2P − K) / S⌋ + 1Valid Conv (P=0, S=1)5×5 → 3×3 (Shrinks)⌊(5 + 0 − 3)/1⌋ + 1 = 3Same Conv (P=1, S=1)5×5 → 5×5 (Preserves!)⌊(5 + 2 − 3)/1⌋ + 1 = 5Strided Downsample (P=1, S=2)5×5 → 3×3 (Halves!)⌊(5 + 2 − 3)/2⌋ + 1 = 3
Zero-padding P = 1 preserves exact spatial size for a 3×3 kernel ('same' conv), while stride S = 2 cleanly halves height and width (⌊(H + 2P − K)/S⌋ + 1).

Master Output-Shape Equation

Hout=⌊H+2P−KS⌋+1,Wout=⌊W+2P−KS⌋+1H_{\text{out}} = \left\lfloor \frac{H + 2P - K}{S} \right\rfloor + 1, \qquad W_{\text{out}} = \left\lfloor \frac{W + 2P - K}{S} \right\rfloor + 1

  • Same Padding (for odd KK and S=1S = 1): Set P=(K−1)/2P = (K - 1) / 2 (so K=3  ⟹  P=1K=3 \implies P=1, K=5  ⟹  P=2K=5 \implies P=2) to keep Hout=HH_{\text{out}} = H!
  • Dilated (Atrous) Convolution (d>1d > 1): Inserts gaps of (d−1)(d-1) zeros between kernel taps, expanding effective kernel size to Keff=d(K−1)+1K_{\text{eff}} = d(K-1) + 1 with zero extra parameters!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of the Conv2d Output-Size Formula

H_out = ⌊(H + 2P − K) / S⌋ + 1

Padded Image Size

Original height plus P zero-pixels added to BOTH top and bottom borders.

In our example: H=32, P=1 → 34
Put it together with real numbers: For H = 224, K = 7, P = 3, S = 2 (ResNet's stem conv!), ⌊(224 + 6 − 7)/2⌋ + 1 = ⌊223/2⌋ + 1 = 111 + 1 = 112!
Walk Through With Me · Interactive Worked Example

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]].

11. Multiply element-by-elementStep 1 / 2

Left column: 3×(−1⋅2)=−63 \times (-1 \cdot 2) = -6; Middle column: 3×(0⋅2)=03 \times (0 \cdot 2) = 0; Right column: 3×(1⋅8)=+243 \times (1 \cdot 8) = +24

Teacher's Note: The filter subtracts the left side from the right side.
Animated Mini-Lab • Ch 13

Conv2d Output-Shape Calculator

Output: 7 × 7 ('Same' Conv ✓)
H_out = ⌊(7 + 2·1 − 3) / 1⌋ + 1 = ⌊6 / 1⌋ + 1 = 7
Pause & Check · Quick Intuition Pulse

What padding P preserves exact spatial size (H_out = H) for a 5 × 5 convolution with stride = 1?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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.

Interactive Visual Lab
Lab Challenge: Switch between Vertical Edge, Horizontal Edge, Blur, and Sharpen in the 2D Conv Scanner Studio below and watch the sliding window compute the feature map!
Interactive Animation • Ch 13 Deep Lab

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.

5×5 Input Image1199911999119991122211222Vertical Edge-101-101-1013×3 Feature Map24
0%
Patch (0, 0) → Output = 24
Intuition Takeaway: Convolutions exploit spatial locality and weight sharing ((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.
Where This Powers Real ML, Deep Learning & Generative AI

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!

Production NumPy & PyTorch Code Patterns
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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting the + 1 at the end of ⌊(H + 2P − K)/S⌋ + 1.
Best Practice: Always test H=3, K=3, P=0, S=1: a 3×3 filter fits inside a 3×3 image 1 time, proving the +1!
Trap #2: Confusing Translation Equivariance with Translation Invariance.
Best Practice: Conv2d is equivariant (output shifts with input); Pooling/GAP creates invariance.
Trap #3: Thinking PyTorch uses (B, H, W, C) like NumPy/TensorFlow.
Best Practice: PyTorch defaults to channels-first (B, C, H, W)!
Trap #4: Forgetting that a single Conv2d weight tensor has 4 dimensions (C_out, C_in, K_h, K_w).
Best Practice: Every output channel has its own 3D (C_in, K, K) filter.
Chapter Mastery Check (+80 XP)
Score: 0 / 5
1What is the output height of a 28 × 28 image passed through Conv2d with K=3, P=1, S=2?
2Why does nn.Conv2d(3, 64, 3) have far fewer parameters than a dense nn.Linear(224*224*3, 64)?
3What is PyTorch's default 4D tensor shape convention for image batches?
4What zero-padding P gives a 'same' convolution (H_out = H) when K = 3 and S = 1?
5A Vision Transformer patch embedding (16×16 non-overlapping patches) is mathematically identical to which PyTorch layer?

Apply What You Learned — Solve Matching Coding Problems