Why did the Transformer architecture replace RNNs for sequence modeling?
Last updated
Transformers replaced RNNs mainly because self-attention processes all positions in parallel and connects any two tokens in one step. That makes training far faster on GPUs and long-range dependencies easier to learn, which in turn enabled scaling to huge models and datasets.
Parallelism over the sequence:
An RNN computes
h_tfromh_{t-1}, so there areO(N)sequential steps.Attention is a few big matmuls over all tokens at once, which suits GPUs and TPUs.
Short path between any two tokens:
The path is
O(1)per layer versusO(N)in an RNN.Distant dependencies and their gradients don't decay through many recurrent steps.
No fixed-size memory bottleneck:
An RNN squeezes the whole history into one hidden vector.
Attention can look up any earlier token directly, which made the attention bolted onto seq2seq RNNs redundant.
Scales well:
Stable deep stacks with residuals and LayerNorm, plus predictable scaling laws.
This enabled large pretraining followed by fine-tuning (BERT, GPT).
Trade-offs:
Attention costs
O(N²)time and memory in sequence length.It needs positional encodings, since attention is order-agnostic.
Autoregressive inference is still sequential and needs a growing KV cache.
These costs are why linear RNNs and state-space models (Mamba, RWKV) are seeing renewed interest.