Module 05 · Part I · Foundations
Sequences Before Transformers
Word Vectors, Recurrent Networks, Vanishing Gradients, the Seq2seq Bottleneck, and the First Attention
By the end you can explain why recurrence hit a wall, and how attention first appeared inside RNN translation models.
Check yourself ▸
Before you start, can you already…
- ☐train a tiny MLP end to end, diagnose overfitting, and read an experiment's result critically. (Module 4)
If any is shaky, the linked module teaches it.
The meaning of a word depends on the words around it, sometimes many words back. Before 2017, sequences were modelled by recurrent networks, which read one token at a time and carry a running summary forward. This module explains how they work, the two walls they hit (no parallelism, and gradients that vanish over long distances), and the fix invented inside them: attention. Module 6 shows what happens when attention is all that is left.
5.1 Word Vectors and What Similarity Means
After training, the embedding vectors of section 1.5 carry meaning in their directions. Nobody labels which words are related: tokens in similar contexts receive similar updates, so their vectors drift together, and "cat" ends up closer to "dog" than to "carburetor". Word2vec (Mikolov et al., 2013) showed that some relations become directions: "king" minus "man" plus "woman" lands near "queen". Inside large language models these regularities are rougher and differ by layer, but direction encoding meaning is what makes the dot product a sensible score.
Pick two words to see the angle between them. Then watch the word2vec analogy: the step from man to woman, added to king, lands near queen.
The arrow from man to woman is copied to start at king. Before looking, predict where it ends, and what it would mean if it ended far from queen.
In words. Words as arrows in a plane: cat and dog point nearly the same way, cat and carburetor almost opposite. The arrow from man to woman, moved to start at king, ends close to queen.
5.2 Recurrent NetworksRun this section
Recurrent neural networks (RNNs), including the Elman RNN and its gated variants LSTM and GRU, read one token at a time and keep a hidden state , a fixed-length summary of everything read so far, computed from the previous state and the current token:
, and are learned. This section writes vectors as columns, as the RNN papers do, so matrices multiply from the left.
The same weights apply at every step, so an RNN reads any length. But the state has a fixed size: everything about the first 500 words must fit in the same few hundred numbers as the first 5.
In words. The hidden state passes along a chain, one step per token; the first token reaches the third only through the second. The chain causes both problems below: steps cannot run at the same time, and gradients must travel back along the whole chain.
5.3 No Parallelism Across Time
Step needs , so an -token sequence takes matrix multiplications one after another: sequential steps. A GPU that could do thousands at once sits mostly idle.
5.4 Vanishing and Exploding GradientsRun this section
To learn from a mistake at step , training needs how much an earlier state contributed. By the chain rule (section 2.3), that is a product of one Jacobian per step in between:
Each factor is the diagonal Jacobian of (slopes , never more than 1; the is whatever was inside the at step ) times .
Let be the most one multiplication by can stretch a vector, the largest (formally the largest singular value, section 20.2). The factor never stretches, so after steps:
here is a step number, not a temperature, and is a constant independent of distance. If the bound shrinks exponentially: . This is the vanishing gradient; factors above 1 give the exploding gradient (section 2.6). LSTMs ease it with a memory path updated by addition rather than repeated multiplication, but still pass information between tokens apart through steps.
How a gradient shrinks travelling back through an RNN
The bound is a ceiling, not a prediction: the tanh slopes are below 1 and the gradient is rarely aligned with the largest stretch, so the measured sizes usually fall faster than σ_max^k. With large σ_max the tanh saturates, its slopes collapse, and even a stretching matrix can end up vanishing.
5.5 Seq2seq and the Fixed-Vector Bottleneck
In translation, input and output are sequences of different lengths with words in different orders. Sutskever, Vinyals and Le (2014) used two RNNs, sequence-to-sequence (seq2seq):
- The encoder reads the source sentence; its final hidden state summarizes it.
- The decoder starts from that summary and writes the translation one token at a time, feeding each output back in, until an end-of-sentence token.
It worked well on short sentences and badly on long ones, because the only link between the halves is one fixed-size vector: 5 words or 50 must fit in the same few hundred numbers. This fixed-vector bottleneck made quality fall as sentences grew.
5.6 The First AttentionRun this section
Bahdanau, Cho and Bengio (2014) removed the bottleneck: let the decoder look back at every encoder state and choose which to read at each step. Before writing output word , with its own state , the decoder:
- Scores every encoder state with a small learned network, .
- Turns the scores into weights summing to 1 with a softmax: .
- Reads their weighted average, the context vector:
and uses , alongside its own state, to choose the next word.
Nobody tells the model which words correspond; the weights are learned from the translation loss alone. Yet plotted, they line up: writing the French zone, the decoder weights the English area, and where word order differs, the weights cross over to follow it.
Rows are the French words being written; columns are the English source. Click a row to see the weights it uses.
In a French–English pair, adjectives usually come after the noun in French and before it in English. Before looking, predict what that does to the shape of the alignment pattern.
In words. A grid with the source sentence across the top and the translation down the side; each cell's shade is the weight on that source word while writing that output word. Most bright cells run along the diagonal, with detours where word order differs.
This first attention mechanism solved the bottleneck: the decoder could reach any source word directly. But the RNNs underneath kept both their problems. In 2017, Vaswani et al. asked whether the recurrence was needed at all.
The Transformer Breakthrough: Maximum Path Length
It was not. The transformer keeps only attention: between decoder and encoder, as Bahdanau had it, and within each sequence, every token attending to the others (self-attention). That removes the chain:
- Path length. Any two tokens are one step apart, , so no long product of factors builds up.
- Parallelism. In training, all tokens are processed at once as a few large matrix multiplications. (Generation is still one token at a time.)
Exercises
Name the two problems of recurrent networks that the transformer removes, and say which design feature causes both.
A gradient passes back through 40 RNN steps, each scaling it by at most . What is the largest it can be, as a fraction of its original size?
How many sequential steps does an RNN need to process a 1,000-token sequence, and how many sequential attention steps does one self-attention layer need for the same sequence?
In Bahdanau attention, the decoder's weights over four source words are and the encoder states are the scalars . Compute the context value.
Explain what information a seq2seq decoder loses on a 200-word sentence, and why attention fixes it without making the encoder's states any larger.
Core Academic References
- Mikolov et al. (2013): Efficient Estimation of Word Representations in Vector Space (word2vec). arXiv:1301.3781
- Elman (1990): Finding Structure in Time. Cognitive Science, 14(2): 179–211.
- Hochreiter & Schmidhuber (1997): Long Short-Term Memory. Neural Computation, 9(8): 1735–1780.
- Bengio, Simard & Frasconi (1994): Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2): 157–166.
- Sutskever, Vinyals & Le (2014): Sequence to Sequence Learning with Neural Networks. NeurIPS 2014. arXiv:1409.3215
- Bahdanau, Cho & Bengio (2014): Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015. arXiv:1409.0473