Skip to content
LearnAI

2.4From RNNs to attention

Why reading text one word at a time through a fixed-size memory hit a wall, and how attention, letting every word look directly at every other word, broke through it.

⏱ 13 minIntermediate

The problem: text has long-range structure

To predict the next word in The keys to the old cabinet in the hall ___, you need to know that the subject is keys, plural, so the verb is are, not is. The word that matters sits eight tokens back, and the nouns closest to the blank (cabinet, hall) are singular decoys. Language is full of these long-range links: pronouns pointing to names introduced paragraphs earlier, a closing bracket matching one opened 200 lines above, a plot twist that only makes sense given chapter one.

The previous lesson showed that counting-based n-gram models can’t handle this, because they only see the last few tokens. The first neural architecture that could, in principle, use the entire history was the recurrent neural network.

Recurrent neural networks: a running summary

A recurrent neural networkRecurrent neural network (RNN)A network that reads a sequence one step at a time, carrying a hidden state forward. LSTMs and GRUs are improved RNNs. (RNN) reads a sequence left to right. At each step it takes two inputs, the current token’s embedding and its own previous hidden stateHidden stateThe vector an RNN carries from one step to the next, summarizing everything it has read so far., and produces a new hidden state. That hidden state is a vector of fixed size, say 512 or 1,024 numbers, and it is the network’s entire memory of everything it has read so far. To predict the next token, the RNN looks only at the current hidden state.

This is elegant. The same small set of weights is reused at every step, so the network can process sequences of any length. Jeffrey Elman’s 1990 “simple recurrent network” showed these models could discover word categories and grammar-like structure from raw sequences. Through the 2010s, RNNs powered speech recognition, handwriting recognition and, eventually, Google Translate.

But two structural problems are baked into the design.

1. The bottleneck. Whether the sentence has 5 tokens or 5,000, everything must fit into the same fixed-size vector. New information keeps overwriting old information, so early tokens fade.

2. Sequential computation. You can’t compute hidden state 100 until you’ve computed hidden state 99. On a GPU, which is built to do thousands of things at once, this is a terrible fit. Training on long documents is slow no matter how much hardware you have.

ANALOGY· The telephone game versus a group chat

In the telephone game, a message is whispered from person to person down a line. Each person hears only their neighbor, and whatever they pass on is all that survives. By the tenth person, the start of the message is mostly gone. That is an RNN: each person is a time step, and the whisper is the hidden state.

Now put everyone in a group chat where the whole conversation is visible. Anyone can scroll up and quote any earlier message directly, and everyone can read at the same time. That is attention: no single bottleneck carries the past, the distance between any two messages is one step, and the reading happens in parallel.

See the bottleneck

The demo runs both ideas on our sentence. The top panel is a cartoon RNN reading one token per step; the colored bar shows how much of the current hidden state still “comes from” each word, assuming each step keeps a fraction λ of the old memory. The bottom panel shows attention, where every word computes a weighted mix of all earlier words in one go.

INTERACTIVERNN bottleneck vs attention
RNN: one token at a time, one fixed-size memorysequential step 11/11
Theh₁keysh₂toh₃theh₄oldh₅cabineth₆inh₇theh₈hallh₉areh₁₀missingh₁₁
What the current hidden state h₁₁ still remembers of each word (cartoon of λ-decay)
the
hall
are
missing
share of “keys” in memory
1.2%
steps from “keys” to “are”
8 (sequential)
gradient factor λ^8 back to “keys”
0.058
Attention: every token looks back at every earlier token directlyparallel step 1/1
Click a word to make it the one doing the looking. Line thickness = attention weight.
The1%keys44%to1%the2%old2%cabinet6%in5%the7%hall14%are20%missing
weight from “are” to “keys”
43.8%
steps from “keys” to “are”
1 (direct)
pairs compared (causal)
66 in parallel
Press Play to watch the RNN read token by token, and see early words fade from its fixed-size memory. Change λ to make it more or less forgetful. In the attention panel, click any word to see where it looks; 'are' reaches straight back to 'keys'.

Things to try:

  1. Play with λ = 0.70. By the time the RNN reaches are, keys makes up only a few percent of its memory. The share readout turns red. The nearby decoys cabinet and hall are far more present.
  2. Push λ to 0.95. Old words survive longer, but now everything is mixed together in roughly equal parts, and the memory can’t single out the one word that matters. Remembering more isn’t the same as remembering selectively.
  3. Click are in the attention panel. Its strongest line goes straight to keys. The distance is one step regardless of how many words sit in between, and every word’s lookups are computed at the same time.
  4. Click cabinet, then missing. Different words look at different places. The pattern is computed from the content of the words, not fixed in advance. (Here it’s hand-designed; in a real model it is learned.)

Vanishing gradients and the LSTM

The demo’s fading memory has a twin problem during training. To learn that keys should influence the prediction at are, the error signal has to travel backward through every intermediate step, via backpropagationBackpropagationAn algorithm that computes the gradient of the loss with respect to every parameter by applying the chain rule backward through the network. through time. At each step, the gradient gets multiplied by roughly the same factor. If that factor is below 1, the signal shrinks exponentially: after 8 steps at 0.7 you’re left with 0.7⁸ ≈ 0.06, and after 50 steps essentially nothing. This is the vanishing gradientVanishing gradientsWhen gradients shrink exponentially as they flow backward through many layers (a product of many factors below 1), so early layers barely learn. The opposite failure is exploding gradients. problem, analyzed by Sepp Hochreiter in 1991 and by Bengio, Simard and Frasconi in 1994. (If the factor is above 1, gradients explode instead, which is easier to patch by clipping them.)

The fix that dominated for two decades was the long short-term memoryLong short-term memory (LSTM)An RNN variant (Hochreiter & Schmidhuber, 1997) with gated memory cells that let information and gradients survive over longer spans. network (LSTM), introduced by Hochreiter and Schmidhuber in 1997. An LSTM adds a separate cell state that flows from step to step mostly by addition rather than repeated multiplication, plus learned gates that decide what to write, what to keep and what to read out. Because information can pass along the cell state nearly unchanged, gradients survive over much longer spans, often hundreds of steps. The simpler GRU (Cho et al., 2014) uses the same idea with fewer gates.

LSTMs were a huge success, but they only softened the problems. The memory was still a fixed-size vector, and the computation was still sequential.

Seq2seq and the birth of attention

In 2014, Sutskever, Vinyals and Le showed that two LSTMs could translate whole sentences: an encoder reads the source sentence into its final hidden state, and a decoder generates the translation from it. This sequence-to-sequenceSequence-to-sequence (seq2seq)An encoder-decoder architecture that reads an input sequence and generates an output sequence, originally for machine translation. setup worked surprisingly well, but it made the bottleneck painfully explicit: an entire sentence, however long, had to be crammed into a single vector before the decoder saw anything. Translation quality dropped on long sentences.

That same year, Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio proposed the fix. Keep all the encoder’s hidden states, one per source word. At each decoding step, let the decoder compute a score for every source position (“how relevant is this word right now?”), turn the scores into weights with a softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total., and take the weighted average of the encoder states. When generating the French word for cat, the decoder can put most of its weight on the English cat, wherever it is in the sentence. This is attentionAttentionA mechanism that lets each position build its output as a weighted mix of other positions, with weights based on query–key similarity.. As a bonus, the weights were interpretable: plotting them showed soft word alignments between the two languages.

“Attention Is All You Need”

In 2017, a team at Google (Vaswani and seven co-authors) asked a radical question: if attention is doing the heavy lifting, do we need the recurrence at all? Their Transformer removed it entirely. Each layer lets every token attend to every other token (self-attentionSelf-attentionAttention in which the queries, keys and values all come from the same sequence.), followed by a small feed-forward network applied to each position independently. Word order, which an RNN got for free by reading left to right, is supplied by adding positional information to the embeddings.

The consequences were dramatic:

  • Parallel training. All positions in a layer are computed at once, as big matrix multiplications that GPUs excel at. The paper’s base model trained in about 12 hours on 8 GPUs, and the big model set a new state of the art on English-to-German translation (28.4 BLEU).
  • Short paths. Any token can reach any other token in a single layer, so long-range dependencies are no harder to learn than short ones.
  • Scalability. Because training is parallel, you can throw much more data and compute at it. Every major LLM since (GPT, Claude, Llama, Gemini, DeepSeek, Qwen) is built on the Transformer.

There is a price. Comparing every token with every other token costs time and memory proportional to the square of the sequence length, while an RNN’s cost grows linearly. Much of Part 4 is about taming that quadratic cost. And at generation time, Transformers still produce one token at a time; the parallelism is in training and in processing the prompt.

MATH CORNER · optionalWhy gradients vanish, and what attention changes

A simple RNN updates its hidden state with

ht=tanh⁡ ⁣(Whht−1+Wxxt+b).h_t = \tanh\!\left(W_h h_{t-1} + W_x x_t + b\right) .

By the chain rule, the gradient of a later state with respect to an earlier one is a product of per-step Jacobians:

∂ht∂hk=∏i=k+1tdiag⁡ ⁣(tanh⁡′(ai)) Wh,\frac{\partial h_t}{\partial h_k} = \prod_{i=k+1}^{t} \operatorname{diag}\!\big(\tanh'(a_i)\big)\, W_h ,

where aia_i is the pre-activation. Since ∣tanh⁡′∣≤1|\tanh'| \le 1, the size of this product is roughly bounded by σmax⁡(Wh) t−k\sigma_{\max}(W_h)^{\,t-k}: it shrinks or grows exponentially in the distance t−kt-k.

Worked example (scalar RNN, ignoring the tanh factor). If each step multiplies the gradient by ww:

distance t−kt-kw=0.5w = 0.5w=0.9w = 0.9w=1.1w = 1.1
10.50.91.1
50.0310.591.61
100.000980.352.59
200.000000950.126.73

Only a factor very close to 1 survives long distances, and that is a knife-edge. LSTMs make the cell-state update additive, ct=ft⊙ct−1+it⊙c~tc_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t, so with the forget gate ft≈1f_t \approx 1 the gradient along the cell passes through nearly unchanged.

Attention changes the path length. In self-attention, the output at position tt is a weighted sum that includes xkx_k directly:

yt=∑k≤tαtk vk,y_t = \sum_{k \le t} \alpha_{tk}\, v_k ,

so ∂yt/∂vk=αtk\partial y_t / \partial v_k = \alpha_{tk}, one step regardless of t−kt - k. The 2017 paper summarizes the trade-off per layer for sequence length nn and width dd:

layer typecompute per layersequential stepslongest path
recurrentO(n⋅d2)O(n \cdot d^2)O(n)O(n)O(n)O(n)
self-attentionO(n2⋅d)O(n^2 \cdot d)O(1)O(1)O(1)O(1)

In code

The difference is visible in the shape of the code: a Python loop over time for the RNN, a single batched call for attention.

import torch
import torch.nn.functional as F

T, d = 11, 64
x = torch.randn(T, d)                       # 11 token embeddings

# RNN: a sequential loop, one fixed-size state
W_h, W_x = torch.randn(d, d) * 0.1, torch.randn(d, d) * 0.1
h = torch.zeros(d)
for t in range(T):                          # step t needs step t-1 first
    h = torch.tanh(h @ W_h + x[t] @ W_x)
print(h.shape)                              # (64,): the whole sentence, squeezed

# Attention: every position at once, each sees all earlier positions
q = k = v = x.unsqueeze(0)                  # (batch=1, T, d); real models use learned projections
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(y.shape)                              # (1, 11, 64): one context-aware vector per token
COMMON MISCONCEPTIONS
  • “Attention was invented by the Transformer paper.” Attention for neural networks was introduced for translation in 2014 (Bahdanau et al.), on top of RNNs. The 2017 contribution was showing you could drop recurrence and use attention alone.
  • “LSTMs solved long-range memory.” They extended the useful range a lot, but the memory is still a fixed-size vector updated sequentially, and performance still degrades over long distances.
  • “Transformers generate text in parallel.” Training and prompt processing are parallel. Generation is still one token at a time, because each new token depends on the previous one.
  • “Attention is free.” Its cost grows with the square of the sequence length. That is the main reason context windows are limited and why so much engineering goes into efficient attention.

Check your understanding

0/5 answered
  1. Q1.What is the 'bottleneck' in a basic RNN language model?

  2. Q2.An RNN's gradient shrinks by a factor of 0.8 at each step back in time. Roughly how much of the signal reaches a token 10 steps back?

  3. Q3.What did Bahdanau-style attention add to seq2seq translation?

  4. Q4.Why do Transformers train so much faster than RNNs on GPUs?

  5. Q5.What is the main cost of self-attention compared with recurrence?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.