After “the keys near the dog by the door”, the next word must be “are”. A bigram model sees only “door” and prefers “is”, 0.18 to 0.11. A plain RNN reads all eight words and still leans to “is”. An LSTM says “are” at 0.30 and “is” at under 0.001.
Drag the slider to put more phrases between the subject and its verb, then switch the subject. Watch which model keeps the verb right. Then we build each one from zero: counts, a fixed window, a recurrent memory, the gradient that fades, and the gate that keeps it.
You need a little Python, what a probability is and the chain rule from calculus. We build the rest from zero.
Lecture 4, "Language Models and RNNs", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi). Its readings include Bengio, Simard and Frasconi (1994) on why long-range links are hard to learn, and Pascanu, Mikolov and Bengio (2013) on training RNNs. Before: Lecture 3, Backpropagation. Next: Lecture 5, Transformers.
Illustrative toy, computed live in your browser from weights we trained offline: a 21-word grammar we wrote, 8,000 sentences, 16 hidden units, PyTorch. Every noun between the subject and the verb has the other number. Bars show run 1 of 4 for each network; Chapter 9 shows all eight runs.
Chapter 0
Type with a keyboard that guesses, and see why a whole sentence is a chain of guesses
Your phone shows three words above the keyboard as you type. To choose them, it gives a probability to every word it knows and shows the top three. That guesser is a language model: a system that gives a probability to each possible next word, given the words so far.
The same model does two jobs. It can generate: pick a likely word, add it, and ask again. It can also score: say how likely a whole sentence is, so a speech recogniser can prefer "recognise speech" over "wreck a nice beach".
The bars are the model's next-word probabilities. Tap a word to add it. The line below multiplies one probability per word.
Illustrative toy: the LSTM from the hero (run 1), trained on our 21-word grammar. A real keyboard model knows tens of thousands of words.
How does a model score a sentence of n words? Call the words w1 to wn. Ask for the first word, then the second given the first, and so on. Probability theory says the product of these guesses is exact:
P of w-one through w-n equals the product, over i from one to n, of P of w-i given w-one through w-i-minus-one.
Walk through the sentence. At each word w-i, ask the model how likely w-i is after all the words before it. Multiply the answers. This rule is the chain rule of probability, and it is exact.
With made-up numbers: P(the) = 0.07, P(cat | the) = 0.002 and P(sat | the cat) = 0.05. The product is 0.07 × 0.002 × 0.05 = 0.000007. Its natural log is −11.87, which is why code adds logs instead of multiplying tiny numbers.
So the whole job is the next-word guess. The trouble is the history it depends on. With 50,000 words, the 10th word has 50,0009, about 2 × 1042, possible histories. No text holds enough examples to estimate a guess for each one. Every model in this lesson is a way to squeeze the history into something we can learn.
Symptom: a model that stores a guess for each full history gives no answer for a new sentence.
Measure: count how many test histories never appear in the training text. For long histories it is nearly all of them.
Fix: condition on fewer words (Chapter 1), or squeeze the history into a vector (Chapter 4).
Chapter 1
Keep only the last word of the history, count which word follows it, and find the zero that breaks the count
The simplest way to shorten the history is to forget most of it. An n-gram model keeps only the last n − 1 words. This is the Markov assumption: the next word depends on a few words back, not on all of them. A bigram model (n = 2) keeps one word.
Its guesses come from counting. Take a tiny corpus of four sentences: "the cat sat on the mat", "the cat ate the fish", "the dog sat on the mat" and "the dog ate the bone". Each starts with a start mark <s>.
Press Play or Step to scan the corpus one pair at a time. Then pick a sentence to score, and switch on add-one.
Illustrative toy: the four sentences of the Code Lab below. There is no end mark, so a sentence's last word starts no pair.
How likely is "cat" after "the"? Count the pair "the cat". Call that c(the, cat). Count every pair that starts with "the". Call that c(the). Their ratio is the estimate:
P of w given v equals c of v, w, divided by c of v.
Find every place where v has a word after it. Count them: that is c(v). Count the places where that next word is w: that is c(v, w). Divide.
From the corpus: "the" has a next word 8 times, and 2 of those are "cat". So P(cat | the) = 2 / 8 = 0.25. "sat" follows "cat" once in 2, so P(sat | cat) = 0.5. Then P(the cat sat) = P(the | <s>) × P(cat | the) × P(sat | cat) = 1 × 0.25 × 0.5 = 0.125.
In the Code Lab, you turn the count table into the model: divide each row by its total.
Symptom: "the cat on the mat" gets probability 0, though it is a fine phrase.
Measure: c(cat, on) = 0. One zero factor makes the whole product 0. This is sparsity: most possible pairs never appear. With 50,000 words there are 50,0005, about 3 × 1023, possible 5-grams.
Fix: smoothing. Add-one adds 1 to every pair count and the 9 possible next words to every row count. Then P(on | cat) = (0 + 1) / (2 + 9) = 0.091, and the phrase scores 0.00030.
Smoothing hides the zero but learns nothing new. A count model that has seen "the cat sat" a thousand times knows nothing about "the kitten sat". To it, "cat" and "kitten" are different strings. A larger n sees more context but makes zeros far more common, and the table grows with every new n-gram.
Chapter 2
Average the surprise at each true word, undo the log, and read the result as a count of choices
Two models read the same test text. Which is better? The better one gives the words that came next a higher probability. We measure this as surprise.
The surprise at a word is −log P(the true word). A word the model expected (P near 1) costs almost nothing. A word it thought impossible costs a lot. The average surprise over a test text is the cross-entropy loss L, the same number training makes small. Perplexity undoes the log:
PPL equals e to the power of: minus one over N, times the sum over i of log P of w-i given w-one through w-i-minus-one.
For each word w-i of the test text, take the probability the model gave it, and take minus its log. Average these surprises over all N words: that is L. Raise e to the power L.
The made-up guesses from Chapter 0: 0.07, 0.002 and 0.05. Their surprises are 2.66, 6.21 and 3.00, so L = 3.96. PPL = e3.96 = 52.3. On average the model is as unsure as a fair pick among 52 words.
Each bar is the probability a model gave the word that came next. Pick a model and watch the perplexity.
Illustrative toy: our grammar and the hero's models. "Uniform" gives each of the 21 possible next words the same chance.
A model that guesses uniformly among V words has perplexity exactly V. So perplexity reads as an effective number of choices. On 1,000 test sentences of our grammar, the bigram scores 3.70 and the LSTM runs about 3.33.
Real numbers show what RNNs did for the field. On the One Billion Word benchmark, a Kneser-Ney 5-gram model scores 67.6 (Chelba et al., 2013). In 2016 the best single LSTM scored 30.0, down from a previous best of 51.3 (Jozefowicz et al., 2016).
Symptom: a model with a smaller vocabulary "wins" on perplexity.
Measure: with fewer words to choose from, every guess is easier. Uniform over 10,000 words is 10,000; over 50,000 it is 50,000.
Fix: compare perplexities only on the same test text with the same vocabulary and tokens.
Chapter 3
Replace counts with learned vectors so similar words share what they learn, and find the window's edge
Counts treat "cat" and "kitten" as strangers. In 2003 Yoshua Bengio and colleagues replaced the count table with a neural network. It reads word vectors: a short list of learned numbers per word, as in Lecture 2. Words used in similar places get similar vectors, so what the model learns about "cat" carries over to "kitten".
Their model reads a fixed window of the last n words. Here is the data flow for a window of 4 words. Each word vector has 128 numbers, there are 256 hidden units, and the vocabulary has 10,000 words:
The frame marks the words the model can see. Widen it until it reaches the subject "keys", and watch the weight matrix W grow.
Sizes follow the example in the text (vocabulary 10,000, vectors of 128, 256 hidden units). Biases are left out of the counts.
The worked number: E has 10,000 × 128 = 1,280,000 weights. W has 512 × 256 = 131,072, and U has 256 × 10,000 = 2,560,000. That is 3.97 million in all. The output layer U is the largest part, because it scores every word of the vocabulary.
This model has no zeros: an unseen window still gets a sensible guess from nearby vectors. Bengio's model beat the best smoothed n-grams on perplexity. But the window brings two new problems. W grows with n, since each extra word adds 128 inputs. And each window position has its own slice of W, so the model learns "cat" in position 1 apart from "cat" in position 4.
Symptom: after "the keys near the dog by the door", a window of 4 sees only "dog by the door". It must guess the verb without the subject.
Measure: accuracy on agreement as the gap grows. Our 4-gram count model, a window of 3 words back, falls from 0.98 with no phrase to about 0.4 with one or more (Chapter 9).
Fix: a model whose size does not depend on the length it reads (Chapter 4).
Chapter 4
Read one word at a time, fold it into a running memory, and reuse the same weights at every step
What if the model read one word at a time and kept a running summary? That summary is the hidden state h: a vector of learned numbers that the model updates after each word. A model built this way is a recurrent neural network (RNN). Jeffrey Elman's 1990 network is the simple form we use here.
At step t, two things go in: the vector of the current word, xt, and the previous state, ht−1. The matrix Wh weighs the old memory. The matrix Wx weighs the new word. The state before the first word is all zeros.
h-t equals tanh of: W-h times h-t-minus-one, plus W-x times x-t, plus b.
Multiply the old state h-t-minus-one by W-h. Multiply the word vector x-t by W-x. Add both and b, then squash each number with tanh. That is h-t. A softmax layer turns h-t into the next-word probabilities, as in Chapter 3.
With the weights of the device: "the" = (0.5, −0.3) and h0 = 0. So Wx x1 = (0.26, −0.13, −0.30) and h1 = (0.254, −0.129, −0.291). Then "cat" = (0.8, 0.2): Wh h1 = (0.029, −0.014, 0.023), Wx x2 = (0.28, 0.20, −0.14), so h2 = (0.299, 0.184, −0.117).
Each column is one step. Press Step. Then turn the memory off and compare the two columns for "the".
Illustrative toy: hand-picked weights from the worked example, shared with the Code Lab below.
The same Wh and Wx run at every step. Five words or five hundred, the model has the same number of weights. That fixes the window's two problems. The size does not grow with length, and a word means the same thing at any position.
Symptom: training an RNN on long texts is slow, even on a big GPU.
Measure: step t needs ht−1, so the T steps of a sequence run one after another. Time per sequence grows with its length.
Fix: none inside the RNN. The Transformer in Lecture 5 drops the recurrence, so every position runs in parallel.
Chapter 5
Unroll the network over the sentence, send the loss back through every copy, and add up what each copy says
To train an RNN language model, feed it a real sentence. At each step it predicts the next word, and it pays the surprise −log P(true next word). Then it reads the true word, not its own guess. Feeding the true word is called teacher forcing. The loss is the average surprise over all steps, the L of Chapter 2.
Training needs the gradient of L with respect to Wh. Draw the network unrolled: one copy per step, all sharing Wh. Backpropagation (Lecture 3) runs back through the copies. This is backpropagation through time (BPTT). Since one matrix sits in every copy, each copy gives a piece of the gradient:
d-L by d-W-h equals the sum, over t from one to T, of d-L by d-W-h through copy t.
Pretend each step has its own copy of W-h. Backpropagate to find the gradient for each copy. Add the T gradients. That sum is the gradient for the one shared W-h.
A one-number RNN, ht = tanh(0.8 ht−1 + xt), reads x = 1, 0, 0, 0, and the output is h4 = 0.316. The copies at steps 1 to 4 give 0, 0.257, 0.326 and 0.368. Their sum is 0.951. Nudging the weight from 0.8 by a tiny amount and measuring h4 gives 0.951 too.
Purple circles are the states going forward. Pink bars are each copy's share of the gradient. Make the sequence longer, then truncate the backward pass.
Illustrative toy: one hidden number, weight 0.8, input 1 at step 1 and 0 after. The output at the last step stands in for the loss.
Long documents make full BPTT costly: the backward pass needs every state, so the forward pass keeps them all. For 1,000 steps, a batch of 64 and 512 hidden units in 4-byte floats, that is 131 MB of states. Truncated BPTT cuts the document into chunks of, say, 35 steps. The state carries forward across chunks, but the gradient stops at each chunk's start: 4.6 MB instead.
Symptom: memory use climbs batch after batch, or PyTorch complains about going backward through the graph a second time.
Measure: the hidden state passed to the next chunk still links to the old graph.
Fix: h = h.detach() at each chunk boundary. The value carries on; the gradient path stops.
Chapter 6
Multiply the same factor once per step back, and watch the learning signal die or blow up
Multiply 0.9 by itself 100 times: 0.000027. Multiply 1.1 by itself 100 times: 13,781. That is the whole problem in two numbers.
For the loss at step T to teach the model about step t, its gradient must pass back through every step between them. Each step multiplies it by a Jacobian: the matrix of how hk changes when hk−1 changes. Call the tanh slope at step k 1 − hk2, one number per unit, placed on a diagonal. The chain is:
d-h-T by d-h-t equals the product, over k from t-plus-one to T, of diag of one minus h-k squared, times W-h.
Start at step T. Go back one step: multiply by W-h and by the tanh slopes. Repeat T − t times. If each factor shrinks the signal, the product dies fast. If each factor grows it, the product explodes.
With made-up numbers: one hidden unit, Wh = 0.8 and slope 1. Ten steps back, 0.810 = 0.107 survives; fifty steps back, 0.850 = 0.000014. With a slope of 0.75, each factor is 0.6 and ten steps leave 0.006. With Wh = 1.1, fifty steps give 117.
The curve is the gradient that survives k steps back, on a log scale. Drag the weight across 1. Turn on the tanh slope, then clipping.
Illustrative: one hidden unit, so each factor is the weight times the slope. With a matrix Wh, its largest singular value plays the weight's part in the bound.
Bengio, Simard and Frasconi showed in 1994 that gradient descent struggles to learn links across long gaps for this reason. The fix for exploding gradients is gradient clipping (Pascanu, Mikolov and Bengio, 2013). If the gradient's length ‖g‖ is above a threshold τ, multiply g by τ / ‖g‖. A gradient (30, 40) has length 50; clipped at 5 it becomes (3, 4), same direction.
Symptom: the loss jumps, then turns into NaN.
Measure: log the gradient norm each step; it spikes by orders of magnitude just before the NaN.
Fix: clip the norm (5 is a common threshold). Clipping cannot fix vanishing: a signal of 0.000014 has nothing left to rescale. That needs a new cell (Chapter 7).
Chapter 7
Give the network a second track that it updates by adding, and gates that decide what to keep and what to write
The plain RNN rewrites its whole memory at every step. The LSTM (long short-term memory; Hochreiter and Schmidhuber, 1997) keeps a second vector, the cell state c, that it changes by adding. Three gates control it. Each gate is a sigmoid layer that reads ht−1 and xt. It outputs one number per cell unit, from 0 (closed) to 1 (open).
The forget gate ft says how much of the old cell to keep. Gers, Schmidhuber and Cummins added it in 2000. The input gate it says how much new content to write. The new content c̃t is a tanh layer, like the plain RNN's update. The cell changes like this:
c-t equals f-t times c-t-minus-one, plus i-t times c-tilde-t, each unit by itself.
Scale each unit of the old cell c-t-minus-one by its forget gate f-t. Scale each unit of the candidate c-tilde-t by its input gate i-t. Add the two. Then an output gate o-t picks what to show: h-t = o-t ⊙ tanh(c-t).
With made-up numbers: ct−1 = (0.8, 0.2), ft = (0.9, 0.3), it = (0.1, 0.8), c̃t = (0.5, −0.4). Then ct = (0.72 + 0.05, 0.06 − 0.32) = (0.77, −0.26). Unit 1 kept its memory; unit 2 took new content. With ot = (0.7, 0.6), ht = (0.453, −0.153).
Why does this help the gradient? Along the cell, going back one step multiplies by ft only, with no Wh and no squash. If the forget gates stay near 1, the signal survives: 0.9950 = 0.61, against 0.850 = 0.000014 in Chapter 6.
The subject "keys" writes +1 (plural). Each later noun has the other number. Set the forget gate, then let every noun write.
Illustrative toy with hand-set numbers: one memory unit. The plain RNN is h = tanh(0.8 h + x). The cell is c = f c + i x. Its input gate i is 1 at the subject and 0.05 at later nouns, unless you open it.
The GRU (Cho et al., 2014) merges the cell into h and uses two gates. The GRU lesson trains one live in your browser. An LSTM layer has four weight blocks. With 512 hidden units and 256 inputs, that is 1.57 million weights against a plain RNN's 393,216.
Symptom: a new LSTM learns long links no better than a plain RNN.
Measure: with the forget gate's bias at 0, gates start near 0.5, and ten steps keep 0.510 = 0.001.
Fix: a common trick starts the forget gate's bias at 1, so the gates begin mostly open.
Chapter 8
Squeeze a whole sentence into one vector, see what gets lost, and let the decoder look back instead
An RNN can translate. One RNN, the encoder, reads the source sentence. Its last state goes to a second RNN, the decoder, which writes the translation word by word as a language model. This is sequence to sequence (Sutskever, Vinyals and Le, 2014).
The catch: the decoder gets one vector, whatever the sentence length. Five words or fifty, everything passes through the encoder's last state. Cho and colleagues found in 2014 that translation quality fell as sentences grew longer.
Attention (Bahdanau, Cho and Bengio, 2015) lets the decoder look at every encoder state at each step. Call the decoder's state at output step t dt, and the encoder's state at source word s hs. Score each source word by a dot product, turn the scores into weights with a softmax, and mix:
a-t equals the sum over s of: softmax over s of d-t dot h-s, times h-s.
Score every source state h-s against the decoder state d-t. Softmax the scores into weights. Multiply each h-s by its weight and add. The decoder uses that mix a-t to pick its next word.
With made-up numbers: dt = (1, 0.5) and three source states (1, 0), (0.2, 1) and (−0.5, 0.5). The scores are 1.0, 0.7 and −0.25. The softmax gives weights 0.49, 0.37 and 0.14. So at = (0.50, 0.44).
Pick an output word. Lines show its attention weights over the source. Turn attention off to see the single-vector bottleneck.
Illustrative toy: hand-made 4-number states in which each French word's decoder state points at its English partner. The scale multiplies every score before the softmax.
The lecture's last reading is "Attention Is All You Need" (Vaswani et al., 2017). It keeps attention and drops the recurrence, which is the Transformer of Lecture 5.
Symptom: a sequence-to-sequence model translates short sentences well and long ones badly.
Measure: score translations in groups by source length.
Fix: attention, so the decoder reads each source state directly instead of one summary.
Chapter 9
Open up the hero, compare every run, and generate text from the model you pick
These are the hero's models, all of them. Two count models: a bigram and a 4-gram, both with add-one. Four plain RNN runs and four LSTM runs: same grammar, same size (16 hidden units), same 30 passes over 8,000 sentences. Only the random seed differs.
Pick a model. The top shows its guess for the sentence. The pink bars show its accuracy at every gap. Then press Generate.
Illustrative toy. Accuracy and perplexity come from our offline test, recomputed with the rounded weights this page uses. That test has 200 sentences per gap, each phrase noun of the other number, and 1,000 ordinary sentences for perplexity. The page computes the guess and the generated text live.
What to look at. The bigram is right with no phrase and wrong on every hard sentence after one: it copies the nearest noun. The 4-gram sees three words back, so it is near a coin flip once the subject leaves its window. RNN 2 learned agreement at every gap. RNNs 1, 3 and 4 did not: their accuracy sits near 0.3, 0.5 and 0. All four LSTMs score 1.0 at every gap, and they have the lowest perplexity, 3.32 to 3.33, against 3.42 to 3.57 for the plain RNNs.
That is the lecture in one table. The plain RNN can carry the subject, as RNN 2 shows. Training rarely finds those weights, because the signal from the verb back to the subject must cross every phrase. The LSTM's additive cell gave all four runs a path for it.
Check yourself. Set the temperature to 0.2 and generate several times: why are the sentences so alike? At 2.0, why do some break the grammar? Temperature divides the scores before the softmax, so a low value sharpens the distribution and a high one flattens it (Sampling and decoding).
Chapter 10
Keep the models, the numbers, the code, and where the course goes next
A language model gives a probability to each next word; the chain rule turns those guesses into the probability of a sentence. N-grams count short histories and break on zeros. A fixed-window network shares strength between similar words but sees only its window. An RNN reads any length with one set of weights, trained by backpropagation through time, but its learning signal shrinks with every step back. The LSTM's additive cell keeps a path open, and attention lets a decoder look back instead of remembering.
| Model | Context it uses | Weights grow with | Fails on |
|---|---|---|---|
| n-gram (counts) | the last n − 1 words | every new n-gram seen | unseen n-grams (zeros); anything beyond the window |
| Fixed-window network (Bengio et al., 2003) | the last n words, as vectors | the window n | anything beyond the window |
| Plain RNN (Elman, 1990) | all earlier words, in h | nothing: same weights at every length | learning long links (vanishing gradient) |
| LSTM (1997; forget gate 2000) | all earlier words, in c and h | nothing; 4 times a plain RNN | still sequential; the longest links still hard |
| RNN with attention (2015) | every encoder state, weighted | nothing | still sequential in time |
| Number | Value | Where |
|---|---|---|
| P(cat | the), four-sentence corpus | 2 / 8 = 0.25 | Chapter 1 |
| Perplexity of guesses 0.07, 0.002, 0.05 | 52.3 | Chapter 2 |
| One Billion Word: KN 5-gram → best LSTM (2016) | 67.6 → 30.0 | Chelba et al. 2013; Jozefowicz et al. 2016 |
| Fixed-window weights (10,000 words, 128, 256, n = 4) | 3.97 million | Chapter 3 |
| h2 of the tiny RNN | (0.299, 0.184, −0.117) | Chapter 4 |
| Surviving gradient at 0.8 per step, 10 and 50 back | 0.107 and 0.000014 | Chapter 6 |
| Forget gate 0.99, 50 steps back | 0.61 | Chapter 7 |
| Toy agreement across 1 to 5 phrases | plain RNN 1 of 4 runs; LSTM 4 of 4 | Chapter 9 |
The core as code: an RNN language model and one training step with truncated BPTT and clipping, in PyTorch.
python import torch, torch.nn as nn, torch.nn.functional as F class RNNLM(nn.Module): def __init__(self, V, d=128, h=256, cell=nn.LSTM): super().__init__() self.emb = nn.Embedding(V, d) # [V, d]: one vector per word self.rnn = cell(d, h, batch_first=True) # nn.RNN for the plain tanh RNN self.out = nn.Linear(h, V) # [h] -> scores over V words def forward(self, x, state=None): # x: [batch, T] word ids y, state = self.rnn(self.emb(x), state) # y: [batch, T, h] return self.out(y), state # [batch, T, V] def train_chunk(model, opt, chunk, state): # chunk: [batch, T + 1] inputs, targets = chunk[:, :-1], chunk[:, 1:] # teacher forcing: true previous word in logits, state = model(inputs, state) loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1)) opt.zero_grad(); loss.backward() # BPTT through the T steps of this chunk nn.utils.clip_grad_norm_(model.parameters(), 5.0) # tame exploding gradients opt.step() state = tuple(s.detach() for s in state) if isinstance(state, tuple) else state.detach() return loss.item(), state # perplexity = exp(loss)
Where the course goes next. Lecture 5 keeps attention and drops the recurrence: the Transformer. Pretraining (Lecture 7) trains such models as language models on huge text, with the same next-word loss you met here.
Now teach it: press Present or Teach. Explain why the bigram copies the nearest noun, why the plain RNN usually fails to learn agreement, and what the forget gate changes. Then go back to the hero, set five phrases and predict each model's verdict before you look.