Simple Algorithm
· 8 min read

CNN vs RNN vs Transformer: Three Answers to One Question

A neural network knows nothing about images, sentences or time unless that knowledge is built into its wiring. CNNs, RNNs and transformers are three ways of building it in, and each choice has a price.

Give a plain neural network a photograph and it sees a long list of numbers. It has no idea that the pixel at position 5,000 sits next to the pixel at position 5,001, or that a cat in the top left corner is the same thing as a cat in the bottom right. It can learn those facts from data, but it needs an enormous amount of data to do so, because it starts from nothing.

The three famous architectures are three answers to one question: what do we already know about this kind of data, and how do we wire that knowledge in? A convolutional network (CNN) assumes that nearby things belong together. A recurrent network (RNN) assumes that order matters and reads one step at a time. A transformer assumes almost nothing and lets every part of the input look at every other part. What each is good at, and what it costs, follows from that assumption.

The comparison at a glance

What it assumesWhere it fits best
CNNNearby inputs are related, and a pattern means the same thing wherever it appearsImages, audio, anything laid out on a grid. Works with modest datasets.
RNNInputs come in order, and what came before shapes what comes nextShort sequences, streaming data, small devices. Works with modest datasets.
TransformerVery little: any input may matter to any otherLanguage, and most things at large scale. At its best with very large datasets.
How distant parts connectCost as the input length nn grows
CNNGradually, through many stacked layersIn step with nn, with every position computed at once
RNNThrough every step in betweenIn step with nn, but strictly one step after another
TransformerDirectly, in a single layerWith n2n^2 for standard attention, with every position computed at once

CNNs: nearby things belong together

A convolutional layer slides a small filter, often 3 by 3 pixels, across the image and applies the same weights at every position. Two assumptions are packed into that one move. The first is locality: to decide whether there is an edge here, you only need to look here. The second is weight sharing: an edge detector that is useful in one corner is useful everywhere, so there is no reason to learn it more than once.

The saving is enormous. A fully connected layer that maps a 224 by 224 grayscale image to an output of the same size needs about 2.5 billion weights. A 3 by 3 filter needs nine.

Stack the layers and each one sees a wider area of the original image than the one before, so the network builds up from edges to textures to parts to whole objects. This is the design that made deep learning work on images. LeNet read handwritten digits in the 1990s, AlexNet won the ImageNet competition by a wide margin in 2012, and ResNet in 2015 showed how to train networks more than a hundred layers deep. The whole story is in CNN Architectures: LeNet to ConvNeXt.

The weakness is the mirror image of the strength. Relating two things on opposite sides of an image takes many layers, because information travels only a few pixels per layer.

RNNs: one step at a time, with a memory

A recurrent network reads a sequence in order. At each step it combines the new input with a hidden state, a vector that summarizes everything it has read so far, and produces an updated hidden state. The same weights are used at every step, so one network can handle a sequence of any length.

This suits language and time series naturally, and it is cheap to run: the memory it needs while reading does not grow with the length of the sequence, which is why recurrent models are still used where data arrives as a stream.

Two problems held it back. The first is long-range memory. Everything the network knows about the past has to squeeze through that one hidden state, and the training signal has to travel backward through every step, shrinking or blowing up as it goes. In practice a plain RNN has trouble learning connections across long gaps. The LSTM, introduced by Sepp Hochreiter and Jürgen Schmidhuber in 1997, added gates that let information pass through many steps untouched, and for years it was the standard tool for speech recognition and translation.

The second problem is speed, and it had no real fix. An RNN is sequential by construction: step 50 can’t be computed before step 49. Graphics processors are fast because they do many things at once, and an RNN gives them very little to do at once.

Transformers: let everything look at everything

The transformer, introduced in the 2017 paper “Attention Is All You Need”, drops both the sliding filter and the step-by-step loop. Its core operation is self-attention: for every position in the input, the model works out how relevant every other position is, and builds a new representation as a weighted mix of all of them. The weights are not fixed by distance. They are computed from the content, so the word “it” can pull information from the noun it refers to whether that noun is two words back or two hundred.

Two things follow. Any two positions are connected in a single layer, so long-range relationships are as easy to learn as short-range ones. And every position is processed at the same time, which is exactly the kind of work graphics processors are built for. That made it practical to train sequence models on far more data than before.

The cost comes from the same idea. Comparing every position with every other means the work grows with the square of the length: double the input and attention costs four times as much. And attention has no built-in sense of order. Shuffle the words and each word gets the same result as before. So the order has to be supplied separately, as positional information added to the input.

Why transformers took over

Weak assumptions are a handicap when data is scarce and an advantage when it is plentiful. A CNN’s belief in locality is a head start on a small dataset. On a huge one it stops helping, and it can get in the way of patterns that don’t fit it. A transformer starts further back and keeps improving.

The clearest evidence came from vision, the CNN’s home ground. The Vision Transformer of 2020 cut an image into patches and fed them to a standard transformer, with no convolutions after that first cut. Trained on ImageNet alone, with the training recipe of the day, it lost to comparable CNNs. Pretrained on a dataset of about 300 million images, it beat them. Same architecture, different amount of data, opposite verdict.

The researcher Rich Sutton called the general pattern “the bitter lesson”: methods that lean on built-in human knowledge keep getting overtaken by general methods that can use more computation. Given enough data and compute, the architecture that assumes least tends to win.

Why the others are still here

None of this made convolutions or recurrence obsolete.

Convolutions remain the efficient choice for images at ordinary scale. In 2022 a research team took a standard ResNet, gave it the training recipe and design details that transformers had been enjoying, called the result ConvNeXt, and matched the vision transformers of the day. A good part of the transformers’ lead had come from how they were trained. Many strong vision models now mix the two, with convolutions in the early layers and attention later.

Recurrence came back in a new form. The quadratic cost of attention hurts on very long inputs. A family called state space models, of which Mamba (2023) is the best known, handles sequences in time proportional to their length while still training in parallel. They are recurrent networks rebuilt so that training can run in parallel.

And for small jobs the old tools are simply enough. A sensor reading that arrives a hundred times a second on a battery-powered microcontroller is a job for a tiny recurrent or convolutional network, not a transformer.

Which one should you use?

For most real projects the honest answer is: whichever one comes pretrained on data like yours. Fine-tuning a pretrained model beats training any architecture from scratch on a small dataset, and it makes most of the architecture question go away. Beyond that:

  • Images, with a small or medium dataset. A pretrained CNN, or a pretrained vision transformer if there is one at a size you can afford to run.
  • Text. A pretrained transformer. At scale, nothing else has matched it so far.
  • Audio. Often both: convolutions to compress the raw signal, then a transformer on top.
  • Long sequences or streaming data, under tight limits on memory or delay. A recurrent model, a state space model, or a one-dimensional CNN.
  • A table of numbers and categories. Usually none of them. Gradient-boosted trees are still the baseline to beat on tabular data, though on small tables a transformer pretrained for the purpose, such as TabPFN, can now match or beat them.

Common questions

What is the difference between a CNN and an RNN?

A CNN applies the same small filter at every position of a grid, so it suits data where neighbors are related, such as images. An RNN applies the same update at every step of a sequence while carrying a memory forward, so it suits data that arrives in order, such as text or sensor readings.

Is a transformer always better than an RNN?

No. With plenty of data and compute it usually is. On small datasets, very long sequences, or hardware with little memory, a recurrent model can match it at a fraction of the cost.

Are CNNs obsolete?

No. They are still widely used in vision, especially on phones, cameras and other devices where efficiency matters, and convolutional layers sit inside many models that are described as transformers.

Which architecture do large language models use?

Transformers. Models in the GPT family use the decoder half of the original design, which predicts the next token from the ones before it. See Transformer Language Models.

Do I need to learn CNNs and RNNs before transformers?

You can read about attention on its own, but the older architectures make it much easier to see what problem it solves. Attention was first added to recurrent translation models to relieve their memory bottleneck, three years before the transformer removed the recurrence altogether. Our deep learning course goes in that order: convolutional networks, then recurrent networks, then transformers.

Is deep learning a different thing from machine learning?

It is a part of it. Deep learning is machine learning with many-layered neural networks as the model, and all three architectures here can be trained with labels, without them, or from rewards. We untangle those terms in Supervised vs Unsupervised vs Reinforcement Learning.

Keep reading