AI State of the Art
Fundamentals/The Transformer: The Architecture That Changed Everything/26 min
Section 36

Why the Transformer Replaced RNNs

Listen as a podcast →

The story: the sudden death of RNNs (2017-2020)

Between 2017 and 2020, something spectacular happened in NLP (Natural Language Processing, the automatic handling of human language): RNNs (Recurrent Neural Networks, the family that includes LSTMs, or Long Short-Term Memory, and GRUs, or Gated Recurrent Units, two variants fitted with internal valves) disappeared overnight. From total dominance across all language processing tasks to near-extinction in 3 years. It's one of the fastest transitions in the history of computer science.

This wasn't a fad. It was a brutal technical necessity: the Transformer solves fundamental problems that RNNs cannot solve, whatever stopgaps you bolt onto them. Let's go through these problems one by one.

Problem 1: the RNN is sequential, not parallel

This is reason #1, and maybe the only one you really need to understand the Transformer's victory.

An RNN processes words one by one, in order. Word 2 can't be processed before word 1 is finished, because word 2 needs the hidden state produced by word 1. It's like an assembly line with a single worker: even if you have 100 workers available, only one works at a time.

Diagram comparing two ways of encoding the sentence I am Italian. On the left, the RNN: three chained cells, each receiving one word and passing its state to the next through a horizontal arrow. On the right, the Transformer: a single round block linked by three downward arrows to the three words, all processed at the same time.
It all comes down to the direction of the arrows. On the left, the horizontal chain forces an order: you cannot compute am before finishing I. On the right, three arrows leave the same block toward the three words simultaneously, which is exactly what a GPU does fastest.Source : Towards NLP

RNN: Word 1 (wait), Word 2 (wait), Word 3 (wait)...

  • Steps are strictly sequential
  • A GPU has several thousand compute cores: nearly all of them sit idle
  • Impossible to parallelize training along the time dimension

Transformer: Word 1, Word 2, Word 3... all at the same time

  • All positions are processed simultaneously
  • The GPU's thousands of cores all work in parallel
  • Training takes a number of non-parallel steps that no longer depends on the length of the text

The right way to state the gain, rather than an invented number: for a sequence of nn tokens the RNN chains nn steps that cannot be done at the same time, while the Transformer does one, whatever nn is. The actual speedup therefore depends on text length and hardware, not on some universal constant. The one solid figure on the subject is the original paper's, quoted in the overview lesson: three and a half days on eight GPUs to beat the state of the art in translation.

It's as simple as that. Modern GPUs are massively parallel machines: they excel when given thousands of independent computations to do at once. The Transformer gives them exactly that. The RNN gives them exactly the opposite: one computation at a time, with a rigid sequential dependency.

Parallelism isn't a nice bonus. It's what made training models with hundreds of billions of parameters possible. Without parallelism, GPT-3 would have taken years to train instead of weeks.

Problem 2: the memory bottleneck

An RNN has a critical design problem: it must compress the entire history into a single vector, a hidden state, typically 256 to 1,024 dimensions.

Take the sentence: "The black cat that was peacefully sleeping on the blue carpet suddenly woke up"

The RNN must condense all this information into a single vector of a few hundred dimensions. It's like summarizing an entire paragraph on a Post-it note. Inevitably, details get lost: word by word, the hidden state gradually "forgets" the beginning of the sequence, the first words being overwritten by the last ones. At exactly what rate? That depends on the model and the task, and it is precisely what no recurrent architecture ever managed to guarantee.

The Transformer works radically differently: it maintains a separate representation for each token in the sequence. Each word keeps its own vector, and the attention mechanism can directly access any past word without going through a bottleneck.

Nothing gets compressed. Nothing gets forgotten. Everything remains accessible at all times. It's a decisive advantage as soon as you work with sequences longer than a few dozen words.

Problem 3: long-range dependencies vanish

Even with LSTMs (Long Short-Term Memory), the cream of RNN technology (with their famous forget, input, and output "gates"), dependencies between distant words remain hard to capture.

Example: "The black cat that was sleeping on the blue carpet, next to the fireplace, under the window, near the piano... [20 words later] ...it woke up"

The RNN must connect "it" with "cat" through 20 sequential processing steps. At each step, the signal degrades a bit: this is the vanishing gradient problem (the correction signal shrinking as it travels back through the chain) already met in the lesson on backpropagation. After 20 steps, the link between "it" and "cat" is so weakened that the RNN no longer knows who "it" refers to.

The Transformer connects "it" directly to "cat" via the attention mechanism, in a single step. Whether 20 words or 200 separate them doesn't matter: the logical distance is always 1. Attention creates a direct path between any two positions in the sequence.

Why LSTMs try to solve this

LSTMs add "gates" (forget gate, input gate, output gate) to control the flow of information in the hidden state. The idea: the forget gate can "protect" certain information from being forgotten by letting it pass through intact. It's an ingenious stopgap against the vanishing gradient, but a stopgap all the same. It demands many parameters, delicate tuning, and only partially solves the problem.

The Transformer avoids the problem entirely: no gates, no sequential hidden state, just direct attention between all positions. Simpler architecture, better result.

Problem 4: RNNs don't scale well

Adding more layers to an LSTM? It helps a little, then plateaus. Adding more parameters? Same thing. Diminishing returns come fast. For RNNs there is no law that cleanly relates model size to resulting quality, and that is precisely what was missing.

The Transformer, on the other hand, follows remarkably regular and predictable scaling laws. Scaling up model size and data volume improves quality regularly enough that you can predict, before committing to an expensive training run, roughly what it will yield. This is what the work of Kaplan et al. (2020) at OpenAI showed, spelled out in the scaling laws lesson.

Scaling Laws for Neural Language Models (Kaplan et al., 2020)

That predictability is what made the race to large models possible: you dare to spend months of compute because you roughly know what you will get. RNNs never offered that guarantee, which made any large-scale bet far riskier.

That's why all modern LLMs (Large Language Models) (GPT-4, Claude, LLaMA, Gemini) are Transformers: the architecture scales up without breaking.

The Transformer's price: remaining problems

The Transformer won the war, but it pays a price. Two major limitations deserve to be understood:

Limitation 1: Quadratic complexity

ArchitectureMemory/compute complexity
RNNO(n)O(n), linear in the sequence length
TransformerO(n2)O(n^2), quadratic in the sequence length

A reminder on that notation: big O counts no operations, it describes how the work grows. O(n)O(n): double the length, double the work. O(n2)O(n^2): double the length, quadruple it.

For a sequence of 100,000 tokens, the attention matrix holds 100,000 × 100,000 = 10 billion elements, and that is per head, per layer. A single such matrix in 16-bit numbers (2 bytes each) would weigh 20 gigabytes: as much as the entire memory of a good-sized graphics card. Which is why no serious implementation ever builds it.

RNNs? Just O(n)O(n) linear. One token, one step, constant memory per step. Much more economical.

Chart of operations in millions against sequence length n, for a model dimension d of 512. The red attention curve, O(n squared times d), starts below the blue RNN line, O(n times d squared); the two cross at the marked point where n equals d equals 512, then the red curve takes off and exceeds 2000 million operations at n equal to 2000 while the blue line stays around 500.
The crossing point is what makes the trade-off interesting: as long as the sequence is shorter than the model dimension, attention is actually cheaper than the RNN. Beyond it the gap widens very fast, and that is what caps the size of context windows today.Source : Michael Brenndoerfer

Practical impact: quadratic complexity is what imposes context limits on current LLMs. Advertised windows now run into the millions of tokens, but those figures shift month to month and every one of them rests on a workaround (Flash Attention, sliding-window attention, sparse attention) rather than dense attention across the whole window. The underlying O(n2)O(n^2) problem persists.

The current AI bottleneck

O(n2)O(n^2) complexity is the biggest technical challenge in AI today (2024-2026). Flash Attention (an implementation optimization), Mamba (an alternative model), and linear attention variants are all trying to solve this problem. But no solution has yet replaced classical attention in terms of quality. The speed/quality trade-off remains open.

Limitation 2: Streaming and inference difficulties

RNNs are naturally streaming: you ingest a token, update the hidden state, produce an output. Constant O(1)O(1) memory, no need to store anything from past tokens.

The Transformer at inference must maintain the KV cache: all the Keys and Values computed for all previous tokens. Why keys and values and not queries? Because at each step the model needs only its own query, but the keys and values of everything before it; the full reasoning is in the multi-head attention lesson. Memory therefore grows linearly, at O(n)O(n).

Run the numbers for a LLaMA 2 70B, whose dimensions are public: 80 layers, 8 key/value sets per layer (the model uses GQA, the grouped-query attention explained in the multi-head attention lesson), 128 numbers per set, in 16 bits, so 2 bytes per number. For a 100,000-token context: 2 (keys and values) × 80 × 8 × 128 × 100,000 × 2 bytes ≈ 33 gigabytes. That is, for a single user, half the memory of an 80-gigabyte GPU, on top of the 140 gigabytes the model weights already take up.

This is a major practical burden for deployment: serving an LLM to thousands of simultaneous users requires massive amounts of GPU memory, primarily because of the KV cache.

Comparison table

AspectRNN/LSTMTransformer
Parallel trainingNo (sequential)Yes, massively
Long-range dependenciesDifficult (signal degrades)Easy (direct attention)
Compute cost for the whole sequenceO(n)O(n) linearO(n2)O(n^2) quadratic
Steps that cannot be parallelizednn1
Memory at inferenceO(1)O(1) constantO(n)O(n) growing (KV cache)
Scaling (bigger = better)Poor (diminishing returns)Excellent (scaling laws)
Practical contextA few hundred to a few thousand tokensHundreds of thousands and beyond, with workarounds

Verdict: The Transformer wins on everything that matters for performance (parallelism, scaling, long-range dependencies). The RNN wins on memory efficiency. And in practice, performance has largely prevailed.

The return of linear architectures (since 2023)

Since 2023, a new generation of architectures is trying to combine the best of both worlds: the Transformer's quality with the RNN's efficiency.

Mamba (State Space Models)

Mamba, developed by Albert Gu and Tri Dao, is the most promising alternative. The idea: a linear architecture like RNNs (complexity O(n)O(n)), but parallelizable during training like the Transformer. The SSMs (State Space Models) on which Mamba is based draw from control theory to model sequences.

  • At inference: constant O(1)O(1) memory, no KV cache. You can generate indefinitely without blowing up memory.
  • At training: full parallelism thanks to a clever mathematical reformulation (State Space Models can be computed as convolutions).

This is the most promising direction for overcoming the O(n2)O(n^2) barrier.

Detailed diagram of a Mamba block. The input splits into two branches: the left branch goes through a projection, a convolution, a Silu activation and then the Selective SSM module; the right branch goes through a projection and a Silu activation and acts as a multiplicative gate. The two branches meet at a multiplication, followed by a final projection to the output. On the left, a stack of identical Mamba blocks is shown.
The Mamba block replaces the Transformer's attention layer. At the center, the Selective SSM module is what stands in for the attention matrix: it carries information along the sequence through a state, without ever comparing every token to every other one. The right branch acts as a gate and decides how much of the signal gets through.Source : Maarten Grootendorst, A Visual Guide to Mamba and State Space Models

RWKV: RNN with linear attention

RWKV is an open-source project that reformulates the RNN with a form of linear attention. Performance approaches that of the Transformer on several benchmarks, with RNN-style inference memory. The model is actively developed and used by a growing community.

Jamba: the Mamba + Transformer hybrid

Developed by AI21 Labs, Jamba alternates Mamba layers and Transformer layers within the same model. The idea: use Mamba for efficiency on long sequences, and the Transformer for complex relationships that require full attention. A pragmatic compromise that works well in practice.

Reality 2024-2026

Despite the enthusiasm around Mamba and SSMs, the Transformer still dominates production. Why? Modern GPUs and TPUs (Tensor Processing Units, Google's accelerator chips) are specifically optimized for Transformers. Flash Attention exists and is mature; there's no equally mature equivalent on the Mamba side. Deployment infrastructures (vLLM, TensorRT-LLM) are built around Transformers.

The most reasonable hypothesis, and it should be read as a hypothesis, not a fact: a slow, pragmatic transition rather than a sudden flip, with Mamba and hybrid architectures gaining ground first where long sequences and memory thrift are critical.

Why this matters

Understanding why the Transformer replaced the RNN means understanding the deep forces shaping all of modern AI. It wasn't an arbitrary choice or a passing trend. It was a convergence of technical necessities:

  • GPUs demand parallelism, and the Transformer delivers
  • Language tasks require long-range dependencies, and attention solves them
  • The race for performance demands predictable scaling, and the Transformer obeys

Key takeaways

  1. The Transformer dominates because of: parallelism (full GPU utilization), scaling (predictable laws), and long-range dependencies (direct attention)
  2. The Transformer's price: O(n2)O(n^2) complexity in memory/compute and a KV cache that grows with each token
  3. RNNs had: linear O(n)O(n) complexity and natural streaming with constant memory
  4. Mamba and SSMs (State Space Models): are trying to combine the Transformer's parallelism with the RNN's linear efficiency
  5. In 2024-2026: the Transformer remains king in production, but alternatives are gaining credibility
Check your understanding0 / 4

1. What is the number one reason the Transformer beat RNNs?

2. What is the memory bottleneck specific to RNNs?

3. On what ground does the RNN still beat the Transformer?

4. What is the promise of Mamba and State Space Models?