Before Transformers: Word Vectors, RNNs, LSTMs, CNNs
Word vectors, RNNs, LSTMs and CNNs, and why attention won.
A transformer makes more sense once you have seen what it replaced. For decades, language models were built from counting tables, then from networks that read one token at a time, then from networks that slid small filters across text. Each design fixed a real problem and hit a real wall, and the transformer is a direct answer to those walls.
This chapter moves quickly and stays at the level of ideas. Its experiments use the same Shakespeare text as Chapters 2 and 3, so a counting model, a small feed-forward network, a vanilla RNN and an LSTM can be compared on equal footing. The results are not what the usual story predicts.
4.1N-gram models
Count what follows what. The first language models, and the baseline that still tells you whether a neural model learned anything.
An n-gram model predicts the next token from the previous n − 1 tokens by counting: the probability of a token after a context is the number of times it followed that context in the training text, divided by the number of times the context appeared. That is the whole model: a lookup table built in one pass over the data, with no training loop. The assumption that only the last few tokens matter is called the Markov assumption. Claude Shannon used models like this in 1948 to study the statistics of English, and they powered speech recognition and machine translation into the 2010s.
Two problems appear immediately, and both show in a real run. I built character n-gram models on the Shakespeare text for n from 1 to 8, with and without backoff, the standard repair for contexts never seen in training: blend each estimate with the estimate from a shorter context.
- validation, with backoff
- training, with backoff
- validation, no backoff
The reason longer contexts stop helping is in the counts:
| n | Context | Contexts seen in training | Possible contexts | Validation contexts never seen |
|---|---|---|---|---|
| 2 | 1 character | 65 | 65 | 0.0% |
| 4 | 3 characters | 11,228 | 274,625 | 1.4% |
| 6 | 5 characters | 133,293 | 1.16 billion | 10.1% |
| 8 | 7 characters | 413,620 | 4.9 trillion | 34.8% |
Sparsity is the first wall. The number of possible contexts grows exponentially, so most long contexts never occur, and at eight characters a third of the validation text falls where the table has no entry. Rigidity is the second: every context has its own row, so nothing learned about “the king said” transfers to “the queen said.” And storage grows with the data: the 6-gram model keeps about 459,000 counts to describe one megabyte of text.
Now look at the level it reaches anyway. A 4-gram sees three characters of context, exactly like the feed-forward model in Chapter 3, and scores 1.77 against that model’s 2.03. Counting is a strong baseline on small data.
N-gram thinking never left. Keyword search with BM25 scores overlapping terms (Chapter 14). Overlap metrics such as BLEU and ROUGE count shared n-grams (Chapter 23). Repetition penalties block repeated n-grams during generation. And training a BPE tokenizer is repeated bigram counting (Chapter 6).
Common take“N-grams are obsolete.”
Sharper take“An n-gram model is the baseline that tells me whether my neural model learned anything. On small data it can be hard to beat.”
4.2Word vectors
Meaning becomes geometry once a model is trained on the company each word keeps.
An n-gram table treats every word as an unrelated symbol. In vector terms each word is one-hot, a long vector with a single 1, and every pair of different words is equally dissimilar. The way out came from an old observation in linguistics: words that appear in similar contexts tend to mean similar things. Represent each word by the company it keeps, and similar words end up with similar representations.
word2vec (2013) made the idea cheap and famous: train a very small network to predict a word’s neighbors, then keep its input weights as the word’s vector. GloVe (2014) reached similar vectors by factorizing a table of co-occurrence counts directly, and later analysis showed the two are close relatives, since word2vec’s training implicitly factorizes a matrix of co-occurrence statistics. Either way, an embedding is compressed co-occurrence.
To show how little machinery that takes, I built word vectors with no neural network at all. Count which words appear within four words of each other across the Shakespeare text (204,062 words), reweight the counts so that surprising pairings matter more than frequent ones, and compress the resulting matrix to 100 dimensions.
| Word | Occurrences | Nearest neighbors (cosine similarity) |
|---|---|---|
| king | 885 | richard 0.77, edward 0.74, iv 0.70, vi 0.70, henry 0.67 |
| queen | 360 | margaret 0.79, elizabeth 0.77, mischance 0.48, gloucester 0.47, xi 0.46 |
| father | 267 | son 0.68, my 0.50, heir 0.49, child 0.47, prince 0.47 |
| thou | 1,402 | art 0.77, dost 0.61, hast 0.60, thyself 0.58, wilt 0.56 |
| eyes | 145 | tears 0.57, eye 0.52, contempt 0.51, thine 0.49, mine 0.47 |
| blood | 190 | shed 0.59, veins 0.52, thy 0.47, youthful 0.46, which 0.45 |
| sword | 54 | put 0.50, lay 0.45, tutor 0.43, hands 0.41, villain 0.40 |
“king” lands beside the kings and “queen” beside the queens. “thou” sits with the verb forms that follow it, “eyes” with “tears”, “blood” with “shed” and “veins”. The cosine similarity between “king” and “queen” is 0.39; between “king” and “sword” it is 0.06. One-hot vectors would give exactly 0 for both.
The limits show just as clearly. “sword” appears only 54 times and its neighbors are noise, the same effect as the rare letter in section 2.3. And the famous analogy fails: king − man + woman returns “vi” and “edward” here, not “queen”. Clean analogies need billions of words, not a few hundred thousand.
Two limits remain however much data you add. Each word gets one vector, so “bank” has the same representation beside a river and inside a sentence about money. And the vocabulary is fixed, so a new word has no vector at all. Contextual embeddings (ELMo in 2018, then BERT and GPT) removed the first limit by computing each token’s vector from its surroundings, which is what every transformer layer does (section 2.3). Subword tokenizers removed the second (Chapter 6). The embedding table at the bottom of every LLM is still this idea, trained end to end, and the sentence embeddings behind vector search are its descendants (Chapter 14).
- titles
- family
- body
- other words
Common take“Embeddings are something neural networks invented.”
Sharper take“An embedding is compressed co-occurrence statistics. word2vec made embeddings cheap; transformers made them depend on context.”
4.3Recurrent networks
One hidden state carried through time, with the same weights at every step.
A feed-forward model like the one in Chapter 3 sees a fixed window. A recurrent neural network (RNN) removes the window. It reads one token at a time and keeps a hidden state, a vector that summarizes everything read so far:
The same weights are applied at every step, so a fixed number of parameters handles a sequence of any length, and in principle the hidden state can carry information across any distance.
Training uses backpropagation through time: unroll the network over the sequence, as in the figure, and it becomes an ordinary deep network with one layer per time step and shared weights. Chapter 3’s chain rule applies unchanged. In practice the unrolling is cut off after a fixed number of steps, 64 in the runs below, to bound memory.
Two properties matter for everything that follows. The state is a bottleneck by design: all the model knows about the past must fit in one vector, 128 numbers here. And the computation is sequential: step t needs step t − 1, so a 1,000-token sequence takes 1,000 dependent steps that no amount of hardware can run side by side. That second property is what eventually ended the RNN era (section 4.9).
On the Shakespeare text, a vanilla RNN with 31,000 parameters reaches a validation loss of 1.87 after 3,000 training steps, ahead of Chapter 3’s three-character window at 2.03.
Common take“An RNN can remember arbitrarily long context.”
Sharper take“In principle. In practice its memory is one fixed-size vector, rewritten through a multiplication at every step, and the next section measures what that does to learning.”
4.4Vanishing gradients through time
Backprop multiplies one factor per step, so distant tokens stop mattering.
Unrolled through time, an RNN is a very deep network, and the vanishing-gradient problem from section 3.8 returns with depth measured in time steps. The gradient reaching a state k steps back has been multiplied k times by the recurrent weights and by the slope of tanh. If that factor averages below 1 the signal shrinks geometrically; above 1 it explodes.
I measured it on the trained models. Take the loss at the last position of a 100-character sequence, backpropagate it, and record the size of the gradient that arrives at each earlier position.
- vanilla RNN, trained
- LSTM cell state, trained
- the same two at initialization
A model cannot learn a dependency it receives no gradient for. This RNN can learn that “q” is followed by “u”. It cannot learn to close a quotation mark opened 60 characters earlier, or to make a verb agree with a subject two clauses back, because the error signal from those mistakes never reaches the step where the information would have to be stored.
The opposite failure, exploding gradients, is handled by clipping (section 3.6); in these runs clipping fired on 0.5% of the RNN’s training steps. Clipping does nothing for vanishing gradients, because there is nothing left to clip.
Common take“The RNN forgot because its hidden state was too small.”
Sharper take“It never learned to remember. The gradient from 50 steps away is billions of times too small to teach it anything.”
4.5LSTMs and GRUs
Gates build a protected memory lane, an additive path that gradients can survive.
The long short-term memory network (LSTM, 1997) fixes the gradient’s path, not the size of the state. It adds a second state, the cell state, that is updated by addition where the plain RNN used a full matrix multiplication:
Three gates, each a sigmoid layer producing values between 0 and 1, direct the traffic. The forget gate f decides how much old memory to keep. The input gate i decides how much of a new candidate g to write. The output gate decides how much of the cell to expose as the hidden state.
Along the cell state, the gradient from one step to the previous one is multiplied by the forget gate and nothing else. While a gate stays near 1, both the information and the gradient pass through almost unchanged. This is Chapter 3’s residual connection (section 3.9), an identity path with slope 1, found for time 18 years before ResNets applied it to depth. The trained LSTM uses it: 69% of its forget-gate activations are above 0.9, and about 5% are below 0.1. It learned to hold most of its memory most of the time and to reset a small part of it.
The GRU (2014) is a lighter variant with two gates and a single state; it usually performs about as well with fewer parameters. One practical detail carried over from this era: initialize the forget gate’s bias to 1, so memory starts open.
The result on this text is a useful corrective. The LSTM reaches 1.87, the same as the vanilla RNN, with three times the parameters. Longer memory has little to buy here: on a megabyte of plays, most of what is predictable about the next character sits in the last few characters, as the n-gram results already showed. The LSTM’s advantage is in figure 4.4 and in tasks that need the reach. From about 2014 to 2017, LSTMs held the state of the art in machine translation, speech recognition and language modeling.
What stayed broken: the computation is still sequential, the state is still a fixed size, and the gradient still fades over hundreds of steps.
Common take“LSTMs solved long-range memory.”
Sharper take“LSTMs gave gradients an additive path, which stretched useful memory from around ten steps to a hundred or more. The state is still fixed-size and the computation still sequential.”
4.6Convolutional networks
Slide one small filter everywhere, and let depth widen the view.
A convolutional layer takes the opposite approach to a sequence: no state at all. It slides one small filter, a handful of weights, across the input and applies it at every position. Three ideas come packaged together. Weight sharing: the same filter is used everywhere, so a pattern learned in one place is recognized anywhere, and the parameter count doesn’t depend on input length. Locality: each output depends on a small window. Hierarchy: stacking layers widens the window.
Convolutional networks (CNNs) took over computer vision when AlexNet won the ImageNet competition in 2012, and ResNet (2015) made them very deep with the residual connections of section 3.9. In language they classified sentences, and with dilation they generated audio (WaveNet, 2016) and translated text (ByteNet and ConvS2S, 2016–2017). Their advantage over RNNs was parallelism: every position in a layer can be computed at once.
Their limit is reach. Connecting two tokens 1,000 positions apart takes about 500 layers of width-3 filters, or about nine layers with doubling dilation. Information from far away arrives late and blended with everything in between.
Convolutions are still at work wherever nearby elements matter most. A vision transformer cuts an image into patches with what is effectively a strided convolution (Chapter 12). Whisper’s speech encoder begins with two convolution layers before its transformer blocks. And small on-device models lean on them for efficiency.
Common take“Convolutions are for images.”
Sharper take“A convolution is a weight-shared local filter. It’s the right tool whenever nearby elements matter most, which is why it still sits at the front of vision and audio models.”
4.7Seq2seq and the bottleneck
Squeeze the whole input into one vector, and long inputs break it.
Translation needs a model that reads one sequence and writes another of a different length. The 2014 answer was the encoder–decoder, also called sequence-to-sequence or seq2seq. One RNN, the encoder, reads the source sentence, and its final hidden state becomes a summary of it. A second RNN, the decoder, starts from that summary and generates the translation one token at a time. Trained end to end on sentence pairs, this simple design became competitive with, and soon better than, phrase-based translation systems that had been engineered for a decade.
Encoder–decoder, 2014
With attention
The weakness is in the first diagram: the entire source has to pass through one fixed-size vector. A five-word sentence and a fifty-word sentence are squeezed into the same number of dimensions. Translation quality fell as sentences grew longer, and tricks such as feeding the source in reverse helped only because they shortened some of the paths.
The vocabulary of this design outlived it. BERT is an encoder, GPT is a decoder, and T5 is both (Chapter 5). The decoder’s procedure, generate a token, append it, repeat, is the loop from section 2.1.
Common take“Make the summary vector bigger.”
Sharper take“A bigger vector postpones the problem. Any fixed-size summary loses detail as the input grows. The fix is to stop forcing everything through one point.”
4.8Attention
Let the decoder look back at every input state, weighted by relevance.
In late 2014, Bahdanau, Cho and Bengio removed the single summary. Keep every encoder state. At each decoding step, score each encoder state for its relevance to what the decoder is about to produce, turn the scores into weights with a softmax, and give the decoder the weighted average. The decoder receives a different, purpose-built summary at every step, as in the second diagram of figure 4.7.
Three things changed at once. Long sentences stopped degrading. The weights turned out to be readable: plotted as a grid, they showed the model lining up each output word with the source words it was translating, an alignment nobody had labeled. And the path from any output to any input shrank to a single step, so the gradient no longer had to survive a long recurrent chain.
In the terms modern models use, the decoder’s state is the query, and each encoder state serves as a key, the thing that is scored, and a value, the thing that is averaged. That is the operation from section 2.4. The remaining step was to notice that if attention can connect a decoder to an encoder, it can also connect a sequence to itself, and that once it does, the recurrent network underneath is no longer needed. The 2017 paper that took that step put the claim in its title: “Attention Is All You Need.”
Common take“Attention was invented by the transformer paper.”
Sharper take“Attention was added to RNNs in 2014 to remove the bottleneck. The transformer’s contribution was removing everything else.”
4.9Why the transformer won
Parallel training, a one-step path between any two tokens, and returns that keep coming with scale.
The 2017 paper compared the three kinds of layer on the properties this chapter has been tracking, for a sequence of length n and a model of width d:
| Layer | Work per layer | Steps that must run in sequence | Longest path between two tokens |
|---|---|---|---|
| Recurrent | n · d² | n | n |
| Convolutional | k · n · d² for width k | 1 | About log n with dilation |
| Self-attention | n² · d | 1 | 1 |
Three consequences decided the outcome:
- Training parallelizes. Every position in a sequence is processed at once, so a GPU does in one pass what an RNN did in thousands of dependent steps. The same hardware could suddenly train on far more text.
- Every pair of tokens is one step apart. Nothing has to survive a long chain, so long-range dependencies get a real gradient.
- It kept scaling. With residual connections and normalization (section 3.9), more layers and more width kept paying off, and pretraining on raw text followed by adaptation (GPT and BERT, 2018) turned that scale into general capability (Chapters 8 and 9).
The price is the other column of the table. Attention costs grow with the square of the sequence length (section 2.4), order has to be injected because attention has none (section 2.5), and memory grows with context. That last cost is the mirror image of the RNN’s: a recurrent state is fixed-size and lossy, while a transformer’s state at inference is its KV cache (section 2.7), which keeps everything and grows with every token.
Here is the scoreboard for this chapter’s models, all trained and evaluated on the same split of the same text:
Counting
Neural
At this scale, counting still wins. That is the lesson, not a flaw in the experiment. Neural models did not overtake n-grams by being cleverer on small data. They overtook them because they keep improving as data, parameters and compute grow, while a count table saturates and its storage explodes. On this same text, a 10M-parameter character transformer reaches about 1.47, the figure reported in the nanoGPT repository, and Chapter 7 builds one.
5-gram model
ROMEO: Do, go wear opposit weath, I have pity to-nighting sky in desperatesby; we and be, what I have not most The honour loves: what ever beat am north chaps is zear of yon lord, them to know In …
Vanilla RNN
ROMEO: My excest of conglive, did, and the dofald the curs are han what I wat a grese how live mear rist, and the you arm of geath shall be would be this seare, not should dud sairenting sicker the …
LSTM
ROMEO: My dracle more this? KING RICHARD III: He tile you are han that Rotard I shood you grace to spirece, will you as come a mingain: alldow the brove the lett she she may he courth. PHAUEN …
Common take“Transformers won because attention is smarter than recurrence.”
Sharper take“They won on hardware economics. Every position trains in parallel and every pair of tokens is one step apart, so they could absorb far more data. The quadratic cost is the bill for that.”
4.10What came back
Recurrent state returns wherever sequences get very long.
The transformer’s bill comes due on very long sequences, where attention’s cost grows with the square of the length and the KV cache grows without limit. A family of newer layers attacks exactly that by bringing back a fixed-size state. State-space models such as Mamba (2023) and linear-attention layers update a compact state token by token, in time proportional to the sequence length. Unlike the RNNs in this chapter, they are designed so that training still runs in parallel.
By 2026 this had moved from research into shipping models. Qwen3.5, released in February 2026, is a hybrid: most of its layers are a linear-attention design that carries a recurrent state, and every fourth layer is ordinary full attention. A systematic comparison at equal training compute, first posted in late 2025, found hybrids of attention and state-space layers matching or outperforming the standard transformer. Pure attention remains the default in many other models, so treat this as a live design question, not a settled one.
The durable lesson is the trade itself. A fixed-size state is cheap and lossy; attention over everything is exact and expensive. The same trade appears at every level of a system: recurrent layers versus attention inside the model, the KV-cache budget when serving it (section 2.7), and, in an application, summarizing an agent’s history versus keeping the whole transcript (Chapter 20).
Common take“RNNs are dead.”
Sharper take“Sequential training is dead. Recurrent state is back inside hybrid models, because a fixed-size memory is the only thing that scales linearly with length.”
Key takeaways
- An n-gram model is a lookup table of counts. It is the baseline to beat, and on small data it is hard to beat: here a 6-gram scored 1.63 against 1.87 for a small RNN and LSTM.
- Longer contexts run into sparsity. At eight characters, a third of the validation contexts had never appeared in training.
- An embedding is compressed co-occurrence. Vectors built by counting alone put “king” beside the kings; clean analogies need far more data.
- An RNN reads one token at a time into a fixed-size state, and its gradient vanishes through time: 50 steps back it was about 4 × 10⁻¹⁰ of its size at the loss.
- An LSTM’s cell state is an additive path guarded by gates, the residual connection applied to time. At 50 steps it carried about two million times more gradient.
- Convolutions share one small filter across positions and run in parallel, but distant tokens connect only through many layers.
- Seq2seq forced the input through one vector. Attention removed the bottleneck in 2014 by letting the decoder weight every input state.
- The transformer kept attention and dropped recurrence: parallel training and one-step paths, paid for with quadratic cost and a cache that grows with context.
- Fixed-size state versus attention over everything is a permanent trade, and hybrids of the two were shipping by 2026.
Check your understanding
-
Your new LSTM reaches a validation loss of 1.87 on a small text corpus, and your 6-gram baseline reaches 1.63. A colleague concludes that neural models are the wrong tool for this data. What is right and what is wrong in that conclusion, what would you check, and what experiment would separate “model family” from “scale”?
Answer outline
Right: at this data size and training budget, counting wins, and if 1.63 meets the need the table is the cheaper thing to ship. Wrong: the comparison is between regimes, not families. The count table has already saturated (its validation loss rose past n = 6, and a third of long contexts are unseen), and its storage grows with the data, while a network keeps improving with more data, parameters and steps. Check the LSTM’s training loss and learning curve for underfitting. Then rerun both at ten times the data or model size, and test long-range behavior, such as closing quotes or following a play’s layout, that a short count window cannot see.
-
A vanilla RNN language model gets agreement right between adjacent words but fails whenever the subject and verb are more than about 15 tokens apart. Someone proposes doubling the hidden size. Say what the gradient measurement in this chapter predicts, why a larger state is unlikely to help, and name two changes that would.
Answer outline
In the trained RNN the gradient 20 steps back was 0.02% of its size at the loss, so errors on distant agreement send almost no learning signal to the step where the subject would need to be stored. Capacity is not the constraint, so a bigger state changes little; clipping does not help either, since it only addresses explosion. Two changes that work: a gated, additive path (an LSTM or GRU), which kept 3.6% of the gradient at 20 steps, or attention, which gives a one-step path from the verb to the subject.
-
You need a model for on-device keyboard prediction. It must run in a few megabytes of memory, process text as a stream, and never slow down as a session gets longer. Compare a small transformer with a recurrent or state-space model for this job using sections 4.9 and 4.10, and say what you would measure before deciding.
Answer outline
A transformer’s state is its KV cache, which grows with context, so memory and per-token cost rise through a session unless the context is cut to a fixed window. A recurrent or state-space model has constant memory and constant cost per token and streams naturally, but its memory is lossy. Measure prediction quality at the context lengths that matter for typing, per-token latency and memory on the target device over a long session, and how much quality the transformer loses when its context is capped at a window small enough to fit. The decision turns on that measured quality gap.
Further reading
- Dan Jurafsky and James Martin, Speech and Language Processing (3rd edition draft, free online): the chapters on n-gram language models, embeddings, and RNNs and LSTMs.
- Dive into Deep Learning (d2l.ai, free): the convolutional, recurrent and attention chapters, each with runnable code.
- Andrej Karpathy, “The Unreasonable Effectiveness of Recurrent Neural Networks” and Christopher Olah, “Understanding LSTM Networks” (both 2015): the two classic essays on character RNNs and on what the gates do.
- Bahdanau, Cho and Bengio (2014), “Neural Machine Translation by Jointly Learning to Align and Translate”, and Vaswani et al. (2017), “Attention Is All You Need”, whose first table is the comparison in section 4.9.