Step 3 of 6

CNNs, RNNs & sequence models

Convolutional nets for spatial patterns, recurrent nets for sequences, LSTMs for long-range memory - the architectures that dominated before transformers, and why transformers replaced them.

16 min read

Images have spatial structure - nearby pixels are related. Text has sequential structure - word order matters. Generic MLPs ignore both, treating every input dimension independently. Convolutional neural networks (CNNs) exploit spatial locality; recurrent neural networks (RNNs) exploit sequential dependencies. Both were the dominant architectures before transformers, and their ideas live on in modern models.

Convolutions - local pattern detectors#

A convolution slides a small filter (kernel) across the input, computing a dot product at each position. The filter detects a local pattern - an edge, a texture, a color gradient - regardless of where it appears:

output(i,j)=∑m∑ninput(i+m, j+n)⋅filter(m,n)+bias\text{output}(i, j) = \sum_m \sum_n \text{input}(i{+}m,\, j{+}n) \cdot \text{filter}(m, n) + \text{bias}

2D convolution: slide a k×k filter across the input, computing the dot product at each position. The same filter weights are shared across all positions.

Two key properties make convolutions powerful:

  • Weight sharing: the same filter is applied everywhere, so the network learns what to detect, not where. This dramatically reduces parameters compared to a fully connected layer.
  • Translation equivariance: if the input shifts, the output shifts by the same amount. A cat detector works whether the cat is in the top-left or bottom-right.

CNN architecture#

A CNN stacks three types of layers:

  1. 01Convolutional layers: detect local patterns (edges → textures → parts → objects)
  2. 02Pooling layers: downsample, increasing the receptive field
  3. 03Fully connected layers: combine features for final prediction
ComponentPurposeCommon choices
Conv layerExtract local features3×3 filters, stride 1, padding "same"
ActivationAdd nonlinearityReLU (or GELU in modern nets)
PoolingDownsample spatial dimensions2×2 max pooling, stride 2
Batch normStabilize trainingAfter conv, before activation
Global avg poolCollapse spatial dims to one vectorBefore the final classifier

As you go deeper, the receptive field - the region of the input that influences each neuron - grows. Early layers see edges and textures; deep layers see entire objects. This hierarchical feature extraction is why CNNs work.

Landmark CNN architectures#

ArchitectureYearKey idea
LeNet-51998First practical CNN (handwritten digits)
AlexNet2012Deep CNN + GPU training; won ImageNet by a huge margin
VGGNet2014Very deep (16-19 layers), only 3×3 filters
GoogLeNet2014Inception modules - parallel filters of different sizes
ResNet2015Residual connections; trained 152 layers
EfficientNet2019Compound scaling of depth, width, and resolution

Sequences and the limits of feedforward networks#

Text, audio, and time series are sequences - the order matters, and the length varies. A feedforward network can't handle this: it needs a fixed input size and treats each position independently.

Recurrent neural networks process sequences one step at a time, maintaining a hidden state that carries information forward:

ht=σ(Whht−1+Wxxt+b)\mathbf{h}_t = \sigma(\mathbf{W}_h \mathbf{h}_{t-1} + \mathbf{W}_x \mathbf{x}_t + \mathbf{b})

RNN: at each time step, the hidden state is updated using the current input and the previous hidden state. The same weights are shared across all time steps.

The hidden state hₜ is the network's "memory" - it summarizes everything it's seen so far. But vanilla RNNs have a fatal flaw: vanishing gradients. Gradients flowing backward through many time steps shrink exponentially, so the network can't learn long-range dependencies.

LSTM - learning what to remember#

Long Short-Term Memory (LSTM) networks solve the vanishing gradient problem with a gated architecture. Instead of a single hidden state, LSTMs maintain a cell state - a highway that carries information across many time steps, controlled by three gates:

GateFunctionWhat it learns
Forget gateWhat to erase from cell state"The subject changed; forget the old one"
Input gateWhat new information to store"This word is the subject; remember it"
Output gateWhat to expose from cell state"Verb coming; output the subject's number"
ft=σ(Wf⋅[ht−1, xt]+bf)it=σ(Wi⋅[ht−1, xt]+bi)ot=σ(Wo⋅[ht−1, xt]+bo)\begin{aligned} f_t &= \sigma\bigl(\mathbf{W}_f \cdot [\mathbf{h}_{t-1},\, \mathbf{x}_t] + \mathbf{b}_f\bigr) \\ i_t &= \sigma\bigl(\mathbf{W}_i \cdot [\mathbf{h}_{t-1},\, \mathbf{x}_t] + \mathbf{b}_i\bigr) \\ o_t &= \sigma\bigl(\mathbf{W}_o \cdot [\mathbf{h}_{t-1},\, \mathbf{x}_t] + \mathbf{b}_o\bigr) \end{aligned}

LSTM gates: each gate is a sigmoid layer that outputs values in (0,1), controlling how much information flows through.

The GRU (Gated Recurrent Unit) simplifies the LSTM to two gates (reset and update), with similar performance and fewer parameters.

Cell state
The LSTM's long-term memory highway - carries information across many time steps with minimal modification, solving the vanishing gradient problem.
Gated architecture
A design where learnable gates (sigmoid layers outputting 0-1) control how much information flows through - used in LSTMs, GRUs, and SwiGLU.
GRU
Gated Recurrent Unit - a simpler alternative to LSTM with two gates instead of three, offering similar performance with fewer parameters.

Sequence-to-sequence and the encoder-decoder pattern#

For tasks where both input and output are sequences (translation, summarization), the encoder-decoder architecture processes the input into a fixed representation, then generates the output:

  1. 01Encoder: read input sequence, produce a context vector
  2. 02Context vector: fixed-size summary of the entire input
  3. 03Decoder: generate output sequence one token at a time, conditioned on the context

The bottleneck is obvious: the entire input must be compressed into a single vector. For long sequences, information is lost. This limitation directly motivated the invention of attention - letting the decoder look back at all encoder states, not just the final one.

Where it shows up in ML#

CNNs power efficient vision

MobileNet, EfficientNet, and ConvNeXt use convolutional backbones optimized for mobile and edge deployment - where transformers are too expensive.

1D convolutions process sequences

WaveNet (audio), temporal CNNs for time series, and causal convolutions in some language models use 1D convolutions instead of recurrence.

LSTMs persist in production

Many deployed systems still use LSTMs for time series forecasting, speech recognition, and text classification where transformer overhead isn't justified.

Encoder-decoder inspired transformers

The original transformer (2017) is an encoder-decoder. BERT is the encoder; GPT is the decoder. The architecture pattern outlived RNNs.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.