A recurrent network carries the whole past in one state, updated one step at a time, so the first token reaches the last output only through one multiplication per step, forward and backward. Each model in this lineage shortened or protected that path: gates gave it an additive lane (LSTM, GRU), attention let the output read every state directly (Bahdanau 2014), dilated convolutions cut it to log2 n layers with no recurrence (WaveNet 2016), and the transformer kept only attention: one hop between any two positions, every position computed at once in training.
The figure beside this is the whole page in five lanes: each design below it in the order the page takes them, with the path from the first token to the last output drawn in blue.
You need: backpropagation as the chain rule (the parent's Topic: ml-fundamentals Reading tab) and the slopes of sigmoid and tanh (Activation functions). Attention in its modern forms (multi-head, GQA, MLA) is Attention variants's; this page has only the 2014 form that bridged RNNs to transformers.
The animations and 3D figures run real networks trained offline for this page (PyTorch, minutes on a laptop CPU; src/model/). Drag a 3D figure to turn it.
Blue: the path from x1 to the output at position 8. For length n, the transformer paper's Table 1: path O(n) recurrent, O(logk n) dilated convolution, O(1) self-attention; sequential steps O(n), O(1), O(1) (Vaswani et al. 2017). "In order" means in training; generation is one token at a time for all of them.
The running example is a task that needs memory and nothing else: a key (a, b, c or d), then a run of random distractors (w, x, y, z), then "?", and the network must answer the key. An 8-unit network reading b w w z y y x w w ? has to carry "b" across every distractor in 8 numbers. A recurrent network does it with one update applied at every step (Elman 1990):
Fig. 2 runs that sequence through a trained plain RNN, the one trained on sequences of 5 to 10 symbols (the Measured section has why that matters), with its real weights and states.
It is trained by backpropagation through time (BPTT; Werbos 1990): unroll the network into one layer per time step, all sharing weights, run ordinary backpropagation, and add up the gradients each copy contributes to the shared weights. Long sequences are usually cut into windows (truncated BPTT), which also caps how far back any gradient can reach.
Measured: norm of the loss gradient with respect to the hidden state k steps before the answer, relative to the answer's, mean of the same 256 sequences of length 100, untrained networks (seed 0; the LSTM's forget-gate bias starts at 1, so its gates begin near σ(1) ≈ 0.73), PyTorch autograd (grad_init, src/model/train_memory.py).
The loss at "?" teaches the network to store the key only through the gradient that reaches the key's step, and that gradient crosses one Jacobian per step: ∂at/∂ak = ∏j diag(f′)W. Fig. 2 showed it on one sequence; the chart beside this measures it over 100 steps on the toy's untrained networks: the plain RNN before, the LSTM after.
Predict how many orders of magnitude separate the plain RNN from the LSTM 50 steps back, then watch it.
The rule behind the picture (Pascanu, Mikolov and Bengio 2013, §2.1): if the largest eigenvalue of W (in absolute value) is below 1/γ, where γ bounds |f′| (1 for tanh, 1/4 for the sigmoid), the long-term terms vanish exponentially; above it is necessary, not sufficient, for them to explode. Exploding gradients have a cheap fix the same paper proposed, clipping the gradient's norm (the toys clip at 1); vanishing ones need a change of architecture. The difficulty was first identified in Hochreiter's 1991 diploma thesis and by Bengio, Simard and Frasconi 1994.
The long short-term memory network gives each unit a memory cell C whose update is an addition, guarded by sigmoid gates (Hochreiter and Schmidhuber 1997). Fig. 3 is one step of the toy LSTM (8 units, trained the same way as the other cells on sequences of 5 to 50 symbols), with its real activations on the running example at length 40: b w w z y y x w w ... ?. The input xt and the previous hidden state ht−1 are concatenated and fed to all four in parallel; the cell state runs along the back like a conveyor.
Not the textbook picture: this trained LSTM never shuts its input gate on the distractors (it averages 0.88 on unit 4); it keeps writing in the key's direction, and a saturated tanh reads a large cell the same way. The protected path is what matters for learning: along the cell, ∂Ct/∂Ct−1 is the forget gate alone.
The same four layers as formulas:
| Part | Formula | Role |
|---|---|---|
| Forget gate | ft = σ(Wf[ht−1, xt] + bf) | how much of the old cell Ct−1 to keep |
| Input gate | it = σ(Wi[ht−1, xt] + bi) | which units to write |
| Candidate | C̃t = tanh(WC[ht−1, xt] + bC) | what would be written |
| Output gate | ot = σ(Wo[ht−1, xt] + bo) | what part of the cell to expose |
| Updates | Ct = ft ⊙ Ct−1 + it ⊙ C̃t; ht = ot ⊙ tanh(Ct) | the cell is added to, not rewritten |
Why it works. Along the cell, ∂Ct/∂Ct−1 = diag(ft) plus terms through the gates' dependence on h: no weight matrix and no squashing slope on the direct path, only the forget gate, which the network can hold near 1. It is a skip connection through time, the idea residual networks later used through depth. It does not abolish vanishing gradients: the path through h still multiplies Jacobians, and a forget gate of 0.9 still shrinks the cell path by 0.950 ≈ 0.005 over 50 steps. Setting the forget-gate bias to 1 or more at initialisation, so that the cell starts by remembering, is the standard recommendation (Jozefowicz, Zaremba and Sutskever 2015) and is used in the toy.
"Peephole" connections from the cell to the gates were added by Gers and Schmidhuber in 2000 too; library LSTMs usually leave them out. Greff et al. 2015, §III, has the history of the variants.
The gated recurrent unit merges the cell and the hidden state and uses two gates (Cho et al. 2014, who called it a new hidden unit; the name is from Chung et al. 2014).
The same interpolating, additive trick with three weight blocks instead of four, so at equal width a GRU has exactly 3/4 of an LSTM's parameters: 3n(n + m + 1) against 4n(n + m + 1) for n units and m inputs derived (PyTorch keeps two bias vectors, so +2 instead of +1: the toy's recurrent layers, n = 8, m = 9, have 456 against 608). Quality is usually comparable, so the GRU's real advantage is a quarter fewer parameters at the same width.
Chung et al. 2014 "could not make concrete conclusion on which of the two gating units was better"; Jozefowicz et al. 2015 found that "adding a bias of 1 to the LSTM's forget gate closes the gap between the LSTM and the GRU"; Greff et al. 2015's search over eight LSTM variants found none significantly better than the standard LSTM, with the forget gate and the output activation its most critical parts.
All four cells on any sequence. The widget beside this runs the LSTM, the GRU, the plain RNN and the plain RNN trained only on short sequences, gate by gate, on a key and length you choose; the bottom line shows what each would answer if "?" came now. Switch to the plain RNN: no gate, and the answer drifts to a guess. Predict whether the fourth model, a plain RNN trained only on short sequences, holds the key at length 120.
Trained weights (8 units; LSTM 644 parameters, GRU 492, plain RNN 188), PyTorch's arithmetic (checked to 7.5e-8, src/check_cells.py). A widget: pick a cell, a key and a length, then step through; it opens on the answer. Gate by gate at the key, the first distractor and "?". Gates white (0) to green (1); states blue (+) and orange (−). GRU z in Cho et al.'s convention (share written; PyTorch's z is 1 − z).
The memory task as an experiment: each cell trained from scratch on sequences up to 10, 20, 50 or 100 symbols long, at three learning rates (0.003, 0.01, 0.03) and three seeds, 3,000 Adam steps of 64 sequences, gradient norm clipped at 1; then tested on 2,000 fresh sequences at each length from 5 to 200.
The plain RNN can hold a memory but cannot learn one from long sequences: trained on lengths up to 10 it solved the task in of 9 runs, and two of those hold the key correctly at every test length up to 200; trained on lengths up to 50 or 100 it solved it in none of 18, ending at 25% (chance) or 50% (one bit of the key kept). The gated cells learn it at every training length: . This is Bengio et al.'s 1994 diagnosis on a laptop: the trouble is the gradient that must find the key (the gradient section above), not the capacity to store it.
Toy scale, said plainly: 8 units, one task, nine runs per setting; it shows the mechanism, not how real language models compare. Scripts and every run's numbers: src/model/train_memory.py, runs/memory_results.json.
Translation maps a sequence to a sequence of a different length. The encoder-decoder answer of 2014: an encoder RNN reads the source and its final state becomes a fixed-size vector c; a decoder RNN, started from c, writes the target one word at a time, feeding back the word it just wrote (Cho et al. 2014, who also gave c to the decoder at every step; Sutskever, Vinyals and Le 2014). Everything about the source passes through one vector of fixed size, however long the sentence: Sutskever et al.'s 4-layer, 1,000-cell LSTM (384M parameters) had to fit every sentence in 8,000 numbers (cell and hidden state of every layer). Cho et al. found their smaller encoder-decoder's performance "degrades rapidly as the length of the sentence and the number of unknown words increase", and Bahdanau et al. built attention on that observation.
The model used 1,000-dimension embeddings. An ensemble of five scored 34.81 BLEU on WMT'14 English to French against 33.30 for the phrase-based baseline, "the first time that a pure neural translation system outperforms a phrase-based SMT baseline on a large scale MT task".
The toy: a translation that only memory can solve, copying a string of digits. Two models with the same GRU encoder and decoder (16-dimension embeddings, 32 units) and the same training, differing only in the context vector: the encoder's last state at every step (the fixed vector, as Cho et al.) or attention over all encoder states. Fig. 4 runs both on 12 digits of π with their trained weights (13,836 and 15,948 parameters, 8-bit; accuracy within a few points of full precision; greedy decoding; outputs equal to PyTorch's on 8 references).
Predict how many of the 12 digits the fixed vector gets right before step 3. Then type 25 digits, past the longest training string (20).
A one-way encoder where Bahdanau et al. used a bidirectional one. Strips: 32 numbers per digit. Streams: the attention weights (density) or the single vector.
The formula. Bahdanau, Cho and Bengio (2014, published at ICLR 2015) kept every encoder state hj (from a bidirectional RNN, so each state sees the whole sentence) and, at every output step i, let the decoder choose which to read:
The decoder now reads as many numbers as the source has states, so nothing has to be squeezed. In the paper's Table 1, trained on sentences up to 50 words, the attention model (RNNsearch-50) scored 26.75 BLEU against 17.82 without it (RNNencdec-50), and even the attention model trained up to 30 words (21.50) beat the plain one trained up to 50; RNNsearch-50 "shows no performance deterioration even with sentences of length 50 or more" (Figure 2). The weights α are soft word alignments, readable as a matrix. A year later Luong, Pham and Manning scored with a plain dot product, ht⊤h̄s; the transformer's softmax(QK⊤/√dk)V is that dot score with a scale and separate projections for queries, keys and values.
What the toy reproduces: the fixed vector copies 6 digits almost always (96%) and 12 almost never (4%), so 32 numbers are not enough for a dozen digits; reversing the source alone lifts 10 digits from 24% to 68% (Sutskever et al.'s effect); attention copies every trained length perfectly. What it adds: attention fixed the bottleneck, not length generalisation. Past 20 digits it degrades too (93% whole strings at 22, 1% at 26), and Bahdanau et al. claim no deterioration only for RNNsearch-50, the model trained on the longer sentences. Toy scale: digits, not language, two seeds.
1,000 fresh strings per length, two seeds per model (the fainter line is the second), 6,000 Adam steps of 128 strings, lengths 3 to 20. The reversed model is the fixed-vector model fed the digits backwards, Sutskever et al.'s trick.
Recurrence is sequential: step t waits for step t − 1, in training as in use. WaveNet (van den Oord et al., DeepMind 2016) generated raw audio one sample at a time (16,000 samples a second in its speech experiments) with a stack of causal convolutions: each output sees only the past, and every position of a training clip is computed in parallel. A plain causal stack grows its receptive field by one sample per layer (the paper's Figure 2: 4 layers, filter 2, field 5). Dilating the filters (skipping 1, 2, 4, ... inputs) doubles the field every layer instead.
Predict the receptive field of 4 dilated layers before the last step. Fig. 5 traces one output back through the paper's Figure 3 stack (behind) and a plain stack of the same depth (in front).
Filter width 2, as in the paper. Receptive field = 1 + (filter width − 1) × sum of dilations derived.
The paper repeats blocks of dilations 1, 2, 4, ..., 512: "each 1, 2, 4, ..., 512 block has receptive field of size 1024" (§2.1). Stack them:
Training is parallel, but generation is still one sample at a time, because each sample feeds the next. WaveNet's lesson for text came quickly: ByteNet and ConvS2S translated with convolutions, whose path between two positions is O(logk n) layers for dilated and O(n/k) for contiguous filters, against self-attention's O(1) (the transformer paper, §4; Attention Is All You Need).
Audio samples were μ-law companded and quantised to 256 values, so the output is a softmax over 256 classes instead of 65,536 (§2.2). Each layer uses the gated activation z = tanh(Wf ∗ x) ⊙ σ(Wg ∗ x), from gated PixelCNN, which "worked significantly better than the rectified linear activation" for audio (§2.3): the LSTM's gating idea without the recurrence, and an ancestor of the GLU family that ended in SwiGLU (Activation functions). Conditioned on linguistic features, its text-to-speech scored a mean opinion score of 4.21 in US English and 4.08 in Mandarin, against 3.86 and 3.79 for the best earlier systems and 4.55 and 4.21 for natural 16-bit speech (Table 1). The text-to-speech models had a 240 ms receptive field = 3,840 samples at 16 kHz.
The hero figure's last lane. The transformer (2017) kept only attention (self-attention in the encoder and in the decoder, cross-attention between them) and so removed both costs at once: parallelism, since a recurrent layer needs n sequential steps in training and self-attention one, and path length, one hop between any two positions instead of n or logk n. The price is a layer cost of O(n2·d) against the RNN's O(n·d2), cheaper while the sequence is shorter than the width (Table 1 and §4). Its paper page animates one sentence through a recurrent layer (11 sequential steps) against one self-attention layer and runs a small trained transformer (Attention Is All You Need, Reading tab and "Run a Transformer").
Two things the RNN gave for free had to be added back: word order, since attention is blind to it (Positional Encodings), and a bound on memory per token, since attention keeps every past state (the KV cache: The transformer from zero, section 9). Everything after lives in Topic: llm-architecture.
Recurrence returns. Constant memory and compute per generated token, the RNN's advantage, came back with recurrences that train in parallel over the sequence: state-space models such as Mamba, linear attention, RWKV and the hybrids in production are on Beyond attention, whose section 3 also traces the LSTM's descendants (Mamba's Theorem 1, which makes the gated RNN a special case of selection; xLSTM; "Were RNNs all we needed?").
Every model above reads words as vectors (the toys use one-hot symbols). Before 2013 a word was a one-hot vector, in which every pair of words is equally far apart. word2vec (Mikolov et al. 2013a) learned a dense vector per word by predicting neighbouring words with a deliberately shallow model, so it could be trained on billions of words; GloVe (Pennington, Socher and Manning 2014) fitted vectors whose dot products match the log co-occurrence counts. The two learn nearly the same thing (details closed below). Both were judged on the analogy test, "a is to b as c is to ?", answered by the word nearest to b − a + c; run here on the real 50-dimension GloVe vectors, all 19,544 questions, all 400,000 words:
Static, then contextual. One vector per word cannot tell the river bank from the money bank, and a word missing from the vocabulary has no vector at all. ELMo (Peters et al. 2018) replaced the lookup with the states of a bidirectional LSTM language model, so each word's vector is "a function of the entire input sentence"; BERT did the same with a transformer, and subword pieces solved the vocabulary problem (Tokenizers). The embedding matrix at the bottom of every LLM is the direct descendant of word2vec's input vectors. Query the 2,000 real vectors in the Word vectors tab.
Skip-gram predicts the words around a word from the word; CBOW (continuous bag of words) predicts a word from the average of its neighbours. The full softmax over a vocabulary of millions is too expensive, so the first word2vec paper used a hierarchical softmax (a Huffman tree, about log2 V outputs per word) and the second (Mikolov et al. 2013b) replaced it with negative sampling: push the true (word, context) pair together and k random words apart.
GloVe counts first, then fits: build the global word-by-word co-occurrence matrix X (pairs d words apart counted as 1/d), then fit vectors to the log counts by weighted least squares:
Why they agree. Skip-gram with negative sampling implicitly factorises the word-context pointwise mutual information matrix shifted by log k (Levy and Goldberg 2014), so "predictive" (word2vec) against "count-based" (GloVe) is a difference of method more than of what is learned. On the analogy test, 300-dimension GloVe trained on 6 billion tokens scored 71.7%, against 69.1% for skip-gram and 65.7% for CBOW trained by the GloVe authors on the same corpus (GloVe paper, Table 2). On these 50-dimension GloVe vectors man : programmer :: woman : ? gives "prodigy", not Bolukbasi's "homemaker", which came from word2vec's Google News vectors and a constrained search.
Negative sampling's descendant is InfoNCE, with the batch as the set of negatives (Contrastive and self-supervised learning).
Luong, Pham and Manning 2015 scored with the decoder's current state ht rather than the previous one, and compared three score functions, dot ht⊤h̄s, general ht⊤Wah̄s and concat (Bahdanau's form), plus "global" attention over all source words against "local" attention over a window. The transformer paper still describes its dot-product attention against "additive attention", Bahdanau's form.
The analogy scores (46.2%, 30.4%, 49.7%) are measured here on the released GloVe 6B 50d vectors, independently, with no published 50-dimension figure to compare against; the WaveNet receptive fields (5 for the paper's Figure 2, 1,024 per block of dilations 1 to 512) reproduce the paper independently from the formula; the toy models reproduce Bahdanau et al.'s and Sutskever et al.'s qualitative findings, not their numbers. Every number is recomputed by src/recompute.py.
2,000 words of the real GloVe 6B vectors (50 dimensions, trained on Wikipedia 2014 plus Gigaword 5, 400,000-word vocabulary; Pennington et al. 2014), stored in this page as 8-bit numbers. Ask for neighbours, solve analogies with and without the rule every published score uses, and run the analogy test yourself.
src/glove_subset.py.Try: "frog". The GloVe site shows its neighbours as frogs, toad, litoria, leptodactylidae, rana, lizard and eleutherodactylus (it does not say which of its vector sets); these 50-dimension vectors give snake, ape, toad, monkey, spider, lizard: the same neighbourhood, coarser. Then "bank": all ten full-vocabulary neighbours are financial, because one vector per word mixes every sense into one point, and here the financial sense dominates it.
Cosine similarity of unit vectors. The full-vocabulary list exists only for the preset words.
The analogy test asks "a is to b as c is to ?" and answers with the word whose vector is closest to b − a + c (cosine; "3CosAdd"). Every published score, word2vec's and GloVe's, removes a, b and c from the candidates first. Without that rule the closest word is very often one of the question words, because b − a + c stays near b and c (Linzen 2016; Nissim, van Noord and van der Goot 2020).
Try: man : king :: woman : ? with the rule switched off: the answer is "king". Then man : doctor :: woman : ?: "nurse" appears only because "doctor" is forbidden as an answer, which is Nissim et al.'s point about how such bias examples are produced.
The test set is questions-words.txt from the word2vec repository (Mikolov et al. 2013): 19,544 questions in 14 sections, 5 semantic (capitals, currencies, cities in states, family) and 9 syntactic (adjective to adverb, opposites, comparatives, superlatives, participles, nationalities, past tense, plurals, verb forms). The page runs a fixed sample of 40 questions per section (560) on its 2,000 words; the table below it has the full test on the full vocabulary, computed offline.
Full-vocabulary rows: all 19,544 questions (every word is in GloVe's lowercased vocabulary), 3CosAdd on unit vectors; "top 30,000" restricts both questions and candidates to the 30,000 most frequent words, as word2vec's own evaluation tool does. Measured here, not published: the GloVe paper reports 100 and 300 dimensions only (Table 2: 6B tokens, 300 dimensions, 71.7% total; 1.6B tokens, 100 dimensions, 60.3%), so there is no published 50-dimension figure to reproduce.
Mikolov et al.'s 2013 Figure 2 projected country and capital vectors to two dimensions and found the country-to-capital arrows roughly parallel. The same projection on GloVe, computed in the page (principal components of the chosen words only):
Links open in a new tab. Times are estimates: for knowledge base pages, the Reading tab's word count at 230 words a minute.
The lineage as one picture (path length and sequential steps); RNNs and BPTT; the gradient through time, plain RNN against LSTM; the LSTM gate by gate against a GRU and a plain RNN on real trained weights; who learns to remember, measured; seq2seq with and without attention on the same digits; WaveNet's receptive field; why the transformer replaced them; static word vectors and the analogy test.
2,000 real GloVe vectors: neighbours, analogies with the exclusion rule on and off, the analogy test by section, and the country-capital projection.
The parent: the training step component by component. Its Reading tab has the lineage table ("Sequence models before the transformer") and thread 3, vanishing gradients seen four ways, with the scalar BPTT slider; its "When training goes wrong" tab treats exploding gradients and clipping among its cases. (30 min, plus 1 in closed details)
Vanishing and exploding gradients in deep feed-forward stacks: initialisation scale, normalisation and residual paths. (23 min, plus 14 in closed details)
Sigmoid and tanh, the LSTM's gate functions, and the GLU family (SwiGLU) that descends from the gating used here and in WaveNet. (25 min, plus 5 in closed details)
Negative sampling's descendant: InfoNCE and the batch as the set of negatives. (31 min, plus 8 in closed details)
How subword vocabularies replaced word-level ones, and with them the out-of-vocabulary problem of word2vec and GloVe. (46 min, plus 15 in closed details)
Attention after 2017: multi-head, GQA, MQA, MLA, windows, sparse attention and sinks. This page stops at Bahdanau's form.
Where recurrence went next: SSMs, Mamba, linear attention, RWKV, the delta rule and the hybrids in production.
What the transformer had to add back once recurrence no longer supplied word order. (40 min, plus 21 in closed details)
Where the lineage ends: a recurrent layer against one self-attention layer on the same sentence (animated), Table 1's path lengths, and a small trained transformer to run. (14 min)
Recurrence returns as a selective state-space model; Theorem 1's gated RNN as a slider; the hybrids in production. (24 min)
Contextual embeddings from a transformer encoder: what replaced one vector per word. (23 min)
Toy models trained offline with PyTorch (src/model/train_memory.py, train_seq2seq.py, 2 CPU threads); GloVe 6B 50d from the gensim-data mirror, subset and analogy test by src/glove_subset.py; every number in the text recomputed by src/recompute.py; the page's JavaScript forward passes checked against the PyTorch outputs by src/check_page.mjs.