v9.1.1
Menu

Chapter 10: CNNs & Sequence Models

Week 19-20

Master specialized neural network architectures for structured data. Learn convolutional networks that exploit spatial patterns in images, recurrent networks that process sequences with memory, and attention mechanisms that power modern transformers.

Topics
4
Demo
1
Videos
3
Min read
35

Chapter Overview

Different data types have different structures that specialized architectures can exploit. Images have spatial locality—nearby pixels are related. Sequences like text and time series have temporal dependencies—earlier elements influence later ones.

Convolutional Neural Networks (CNNs) revolutionized computer vision by using learnable filters that detect local patterns regardless of their position in the image. The same edge detector works whether the edge appears in the top-left or bottom-right. This translation equivariance, combined with parameter sharing, makes CNNs incredibly efficient for visual data.

Recurrent Neural Networks (RNNs) process sequences by maintaining a hidden state that acts as memory, carrying information from earlier time steps. However, vanilla RNNs struggle with long-range dependencies due to vanishing gradients. LSTMs and GRUs solve this with gating mechanisms that control information flow.

The Transformer architecture replaced recurrence with self-attention, allowing direct connections between any positions in a sequence. This parallel processing is faster and handles long-range dependencies better. Transformers now dominate both NLP (BERT, GPT) and increasingly vision (ViT).

This chapter covers:

  • Convolutions: Learnable filters that extract local features through sliding-window operations
  • Pooling: Downsampling operations that provide translation invariance and reduce computation
  • RNNs/LSTMs: Recurrent architectures that maintain memory across sequence elements
  • Attention: Self-attention mechanisms that enable transformers to model complex dependencies

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Convolutions & CNNs

Learnable filters that exploit spatial locality — parameter sharing, translation equivariance, and feature hierarchies.

Convolution OperationStride & PaddingFeature MapsCNN Architecture
2
Pooling

Spatial downsampling for translation invariance — max pooling, average pooling, and global average pooling.

Max PoolingAverage PoolingGlobal Average PoolingStride in Conv vs Pooling
From spatial to sequential processing
3
RNNs & LSTMs

Recurrent architectures with memory — hidden states, gating mechanisms, and long-range sequence dependencies.

RNN CellLSTM CellGRU (Gated Recurrent Unit)Bidirectional RNNs
Replacing recurrence with direct connections
4
Attention & Transformers

Self-attention and multi-head attention — parallel sequence processing that replaced recurrence in modern NLP and vision.

Attention MechanismMulti-Head AttentionTransformer ArchitecturePre-trained Transformers

Topics

4 topics in this chapter

The previous chapter, Neural Networks, built fully connected MLPs and trained them with backpropagation and Adam. They reached about 98 percent on MNIST, but the design breaks down on real images. A 224 by 224 color photo has 150,528 inputs, so a single fully connected layer of 1,000 units already needs 150 million weights. Worse, an MLP treats a cat in the top-left corner and a cat in the bottom-right as unrelated patterns, to be learned twice. Images have structure: nearby pixels belong together, and the same edge or texture can appear anywhere. Can a layer exploit that?

This chapter, CNNs and Sequence Models, builds architectures around the structure of their data. This topic starts with the convolution, a small filter slid across the image and shared by every position. We then cover stride and padding, which set the output size, and feature maps, the stack of channels each layer produces. The topic closes with how convolutions, activations, and pooling assemble into CNN architectures from LeNet to VGG and ResNet.

Definition

A convolutional layer slides a small learnable kernel over its input and, at each position, computes the sum of elementwise products between the kernel and the input patch beneath it. Each kernel produces one feature map; a layer with CoutC_{out} kernels over CinC_{in} input channels has Cout(CinK2+1)C_{out}(C_{in}K^2 + 1) parameters, shared across every spatial position.

In this topic

  1. 1Convolution Operation
  2. 2Stride & Padding
  3. 3Feature Maps
  4. 4CNN Architecture
1 of 4
Convolution Operation

(I∗K)[i,j]=∑m∑nI[i+m,j+n]⋅K[m,n](I * K)[i,j] = \sum_m \sum_n I[i+m, j+n] \cdot K[m,n]

In the formula above, the input II is an image or feature map, the kernel KK is a small grid of weights, often 3 by 3, and (I∗K)[i,j](I * K)[i,j] is one output value: lay the kernel over the patch starting at row ii, column jj, multiply overlapping entries, and sum. Sliding over every position gives the output map. Deep learning libraries compute this cross-correlation without flipping the kernel; since the weights are learned, the distinction does not matter. Two properties make it powerful: local connectivity, since each output sees only a small patch, and weight sharing, since one kernel is reused everywhere. Shifting the input shifts the output, which is translation equivariance.

Mathematical Intuition

The 2D convolution (I∗K)[i,j]=∑m∑nI[i+m,j+n]K[m,n](I * K)[i,j] = \sum_m \sum_n I[i+m, j+n] K[m,n] slides a kernel KK of size k×kk \times k over an input II of size H×WH \times W, producing an output of size (H−k+1)×(W−k+1)(H - k + 1) \times (W - k + 1). In the frequency domain, convolution becomes pointwise multiplication: F(I∗K)=F(I)⋅F(K)\mathcal{F}(I * K) = \mathcal{F}(I) \cdot \mathcal{F}(K), which is why FFT-based convolution is O(nlog⁡n)O(n \log n) versus O(n⋅k2)O(n \cdot k^2) for direct computation — but GPU hardware makes direct convolution faster for typical kernel sizes.

Example:

3×3 kernel K=[[1,0,-1],[1,0,-1],[1,0,-1]] applied to image patch [[10,20,30],[10,20,30],[10,20,30]]. Output?

2 of 4
Stride & Padding

Stride SS is how far the kernel moves between positions; padding PP adds a border of zeros around the input. For input width WW and kernel size KK, the output width is ⌊(W−K+2P)/S⌋+1\lfloor (W - K + 2P)/S \rfloor + 1. Without padding, every layer trims the border, and edge pixels are covered by fewer positions than central ones. 'Same' padding, P=⌊K/2⌋P = \lfloor K/2 \rfloor for odd KK at stride 1, keeps the size unchanged. Stride 2 roughly halves each spatial dimension, quartering the computation of later layers, and is a common way to downsample. When the formula does not divide evenly, the last partial window is dropped.

Mathematical Intuition

The output size formula ⌊(W−K+2P)/S⌋+1\lfloor(W - K + 2P) / S\rfloor + 1 encodes the interplay of input width WW, kernel size KK, padding PP, and stride SS. 'Same' padding sets P=⌊K/2⌋P = \lfloor K/2 \rfloor to preserve spatial dimensions when S=1S = 1. A stride-2 convolution halves spatial dimensions, performing downsampling with learnable parameters — unlike pooling which uses fixed operations. The total FLOPs for a conv layer is 2⋅Cin⋅Cout⋅K2⋅Hout⋅Wout2 \cdot C_{\text{in}} \cdot C_{\text{out}} \cdot K^2 \cdot H_{\text{out}} \cdot W_{\text{out}}.

Example:

Input 32×32, kernel 5×5, stride 2, no padding. Output size?

3 of 4
Feature Maps

Each kernel produces one feature map, a 2D grid showing where its pattern appears. A layer stacks many kernels, so its output has one channel per kernel. Each kernel spans all input channels: a 3 by 3 kernel on a 64-channel input has 64 times 9 weights plus a bias, mixing every channel's evidence at each location. Early layers detect edges and color blobs; deeper layers combine those maps into textures, parts, and objects. Networks typically increase the number of channels as they downsample, trading spatial resolution for richer features. Weight sharing keeps the parameter count independent of image size, unlike a fully connected layer.

Mathematical Intuition

Each of CoutC_{\text{out}} output filters convolves across all CinC_{\text{in}} input channels and sums the results: the kernel tensor has shape (Cout,Cin,K,K)(C_{\text{out}}, C_{\text{in}}, K, K), giving CoutCinK2+CoutC_{\text{out}} C_{\text{in}} K^2 + C_{\text{out}} parameters. A fully connected layer mapping the same Cin×H×WC_{\text{in}} \times H \times W input to a Cout×H×WC_{\text{out}} \times H \times W output would need CinCout(HW)2C_{\text{in}} C_{\text{out}} (HW)^2 weights, a factor of (HW)2/K2(HW)^2/K^2 more: about 10610^6 for a 56×5656 \times 56 map with 3×33 \times 3 kernels. This weight sharing is the key insight: the same edge detector is reused at every position.

Example:

Conv layer: 64 input channels, 128 kernels (output channels), 3×3 kernels. How many parameters?

4 of 4
CNN Architecture

A classic CNN alternates convolution, activation, and downsampling stages: spatial size shrinks while channel count grows. A classifier head, flattening plus dense layers or global average pooling, then produces class scores. LeNet (1998) read digits with two conv layers; AlexNet (2012) scaled this up on GPUs and won ImageNet. VGG (2014) stacked only 3 by 3 convolutions: two of them cover a 5 by 5 region and three cover 7 by 7, with fewer parameters and more nonlinearities than one large kernel. ResNet (2015) added skip connections, y=F(x)+xy = F(x) + x, so networks with over 100 layers train. Layer counts include only layers with weights.

Mathematical Intuition

A typical CNN repeats conv-ReLU-downsample stages. If each stage halves spatial dimensions, after LL stages the spatial size is H/2L×W/2LH / 2^L \times W / 2^L, while channels grow from C0C_0 to roughly C0⋅2LC_0 \cdot 2^L. ResNets add skip connections y=F(x)+x\mathbf{y} = F(\mathbf{x}) + \mathbf{x}, so each block only learns a residual and gradients flow directly through the identity path. He et al. (2015) found that without them, a 34-layer plain network had higher training error than an 18-layer one, a degradation problem that residual connections removed, allowing networks of 152 layers and more.

Example:

VGG16 has 13 conv layers and 3 dense layers. Why is it called VGG-16?

Theory Exercise

Problem:

A convolutional layer with a 3×3 kernel connecting 64 input channels to 64 output channels is applied to a 56×56 feature map. Compare its parameter count and per-position connectivity to a fully connected layer mapping the same flattened input to the same flattened output. Why is parameter sharing the key win?

Hints:
  • Conv params depend on kernel size and channels, not spatial size
  • An FC layer connects every input element to every output element
  • Translation equivariance means the same filter is reused at every position

Coding Exercise

Problem:

Build a small CNN in PyTorch (two conv-ReLU-pool stages followed by a linear head) for 28×28 grayscale images, run one forward pass on a random batch, and print the output shape plus the total trainable parameter count.

Hints:
  • nn.Conv2d(in_channels, out_channels, kernel_size, padding=1) keeps spatial size with a 3×3 kernel
  • nn.MaxPool2d(2) halves height and width each time
  • Sum p.numel() for p in model.parameters() if p.requires_grad to count parameters