After this chapter you will be able to
count the parameters of a neural language model and say which matrix dominates;
explain why the embedding matrix is shared across context positions;
write the cross-entropy loss for a -way prediction, and say why it is perplexity in disguise;
trace one forward and one backward pass through the five-word model;
read an overfitting curve and say what early stopping does;
name the two limits of a fixed window that the next chapters remove.
This chapter builds on Chapters 10 and 8, which supply the task and the learning machine.
Chapter 10 left the n-gram model with two admitted blindnesses. It cannot see far enough back, because the Markov assumption throws away everything before the last words. And it cannot see that two words are related, since to a counter cat and dog are just different strings, so a context seen with one lends no strength to the same context seen with the other.
This chapter repairs the second and the chapter after it repairs the first. The task does not change by a single symbol. We still want , we still train by maximum likelihood, and we still measure ourselves with the perplexity of Section that section. Only the apparatus that produces the probability is replaced.
The fix follows from the diagnosis, so the diagnosis deserves care. A trigram model over words has one free number for every possible three word cell, which is about of them as Equation (10.11) counted, and no corpus fills more than a vanishing fraction of those. Worse, the cells are entirely independent of one another.
Learning tells the model nothing whatsoever about , because the two are different cells and the table has no notion that dog and puppy are neighbours. The founding idea of neural language modelling, due to Bengio et al. (2003), is to stop storing a number per context and instead compute the probability from a learned dense representation of each word. Those are the distributed representations of Chapter 9, where similar words get similar vectors and therefore, automatically, similar predictions.
Fix a context of the previous words, and the model computes the distribution over the next word in four movements, each of them machinery from Chapter 8.
The first movement is a lookup. Every word owns a row of an embedding matrix , and the row is its dense vector. The one-hot index of a context word selects its row, which is a lookup and not a multiplication, though it is convenient to write it as multiplying a one-hot vector by . The same matrix serves every context position, and this sharing is the central idea of the chapter. The second is to concatenate, stringing the context embeddings together into one vector
which is the model’s entire memory of the past. Note that its length is fixed the moment is chosen, and that fact returns at the end of the chapter.
The third is to mix, where a hidden layer applies a learned affine map and a non-linearity:
This lets the model form non-linear combinations of the context, and it is where “the of” can learn to behave differently from the sum of its parts.
The fourth movement scores and normalises, with an output map producing one score per vocabulary word and a softmax turning the scores into a distribution:
The entry is the model’s estimate of . The parameters are , , , and , all learned jointly, with learned along with the rest.
A hand count is clarifying, and it explains much of what the field did next. Take a modest configuration, with vocabulary , embedding dimension , a context of words and a hidden layer of units.
| matrix | shape | parameters | share |
|---|---|---|---|
| 500,000 | 32.8% | ||
| 15,000 | 1.0% | ||
| 1,000,000 | 65.6% | ||
| biases | 10,100 | 0.7% | |
| total | 1,525,100 |
Two lessons fall out of that table. First, compare the total against the trigram table, where the counter needed about cells while the network needs million, which is times fewer, or almost six orders of magnitude. The network shares them, so what the model learns about dog is available in every context where dog appears, whereas a count table shares nothing between cells.
Second, look at the share column, where two thirds of the parameters sit in , whose size is and therefore grows with the vocabulary. Every training step must compute the softmax denominator in Equation (11.2), a sum over all words, and that output softmax is the computational bottleneck of neural language modelling. The tricks for dodging it are already familiar, since hierarchical softmax (Morin and Bengio 2005), noise-contrastive estimation (which trains the model to tell real words from noise) and the negative sampling of Chapter 9 all exist for this reason.
Training is maximum likelihood as before, and the knob we turn is now the network’s weights and not a table of counts. Chapter 8 derived the binary cross-entropy of Equation (8.6) from a Bernoulli likelihood, and said why a log likelihood is negated before anything is minimised. Our case is -way, not binary, and the same argument runs again. A single draw from a vocabulary of words is a categorical outcome. Write for the one-hot vector marking which word occurred, and its probability under the model is
The exponents do the selecting. Each is for the word that occurred and for the rest, and anything raised to the power zero is one. The product therefore collapses to the single factor .
Take logs of Equation (11.3) and the product becomes a sum:
Negate it for the same two reasons, and the loss follows:
where indexes the word that occurred, and the second equality is that same collapse. The loss on one example is the negative log probability the model gave to the right answer.
Equation (8.4) is the two-outcome case of Equation (11.3) written out. At the product has two factors, and . Nothing extra was assumed in moving between them. That matters, because every classification objective later in this book is Equation (11.5) over a different vocabulary.
Average Equation (11.5) over the corpus, take base two and exponentiate, and that is the perplexity of Section that section, so minimising cross-entropy and minimising perplexity are one objective in two sets of clothes. Backpropagation sends the gradient of Equation (11.5) back through the softmax, through the hidden layer and into itself. The word vectors are learned, not given, as a by-product of learning to predict.
Take a model small enough to print, with a vocabulary of five words, , and a context of two words, where the context is the cat and the target is sat. Look up and concatenate:
Mix through Equation (11.1), then score and normalise through Equation (11.2).
| word | score | |||
|---|---|---|---|---|
| the | 0.5804 | 0.1524 | ||
| cat | 0.8115 | 0.2131 | ||
| dog | 0.7066 | 0.1855 | ||
| sat | 0.7103 | 0.1865 | target | |
| ran | 1.0000 | 0.2625 | ||
| total | 1.0000 |
The target received , so by Equation (11.5) the loss is , which is nats. A model scoring every token this way would have perplexity against a vocabulary of five, which is to say it is doing no better than guessing. This is expected, because it has not been trained yet.
The gradient at the output layer is , the same prediction minus target that appeared in Chapter 9.
| word | effect | |
|---|---|---|
| the | push down | |
| cat | push down | |
| dog | push down | |
| sat | pull up | |
| ran | push down |
One step of gradient descent with moves every parameter, including the two context rows of :
The prediction improves, and the loss falls with it.
| word | before | after | change |
|---|---|---|---|
| the | 0.1524 | 0.1427 | |
| cat | 0.2131 | 0.1911 | |
| dog | 0.1855 | 0.1524 | |
| sat | 0.1865 | 0.3210 | |
| ran | 0.2625 | 0.1929 |
The loss fell from to . Repeat a few million times and you have a language model.
The claim so far is that shared representations let the model handle word combinations it never saw, and that claim is testable, so we should test it.
Build two families, so that five pets rest in four indoor places while five farm animals rest in four outdoor places. The structure is simple on purpose.
| pets | cat, dog, puppy, kitten, hamster |
| indoor | sofa, carpet, cushion, basket |
| farm | horse, cow, goat, sheep, donkey |
| outdoor | meadow, barn, paddock, pasture |
Every sentence has the form “the ANIMAL rests PLACE” and each animal is only ever paired inside its own family, which gives sentences. The animal sits inside the trigram context, so a counter can see it too and nothing is hidden from the baseline. Hold out sentences, keep more for deciding when to stop training, and train on the remaining , scoring only the place slot since the place is what the animal is supposed to determine.
Train the network and watch both perplexities. The training curve tells you what the model fits, and the held-out curve tells you what it learned.
| steps | train | held out |
|---|---|---|
| 0 | 21.978 | 22.152 |
| 200 | 4.973 | 8.758 |
| 400 | 3.362 | 14.135 |
| 800 | 3.131 | 47.298 |
| 1200 | 3.030 | 92.122 |
| 1600 | 2.980 | 178.799 |
| 2000 | 2.957 | 316.618 |
Training perplexity falls the whole way and never looks back, while held-out perplexity bottoms early and then climbs by a factor of more than ten. The model has stopped learning the pattern and started memorising the pairs it was given, which is overfitting, and a network with more parameters than training examples will do it every time.
The remedy is the third split. Watch perplexity on the development set and keep the weights from its best moment, which is early stopping, and it is why a project needs three splits instead of two.
With early stopping in place, run six random splits. A single split could flatter the model by luck.
| seed | stopped at | trigram | neural | ratio |
|---|---|---|---|---|
| 0 | 300 | 36.357 | 7.879 | 4.61 |
| 1 | 400 | 37.940 | 6.953 | 5.46 |
| 2 | 400 | 37.940 | 5.186 | 7.32 |
| 3 | 200 | 40.376 | 8.553 | 4.72 |
| 4 | 300 | 42.969 | 9.877 | 4.35 |
| 5 | 300 | 42.640 | 13.938 | 3.06 |
The neural model wins on every split, by an overall factor of , taking that as the ratio of the two mean perplexities. The trigram model sits near because a held-out pair is a cell it never counted, so it falls back to the smoothing floor, which is nearly uniform over the places. The network does not fall back, because it computes.
Nothing told the model that kitten resembles cat, or that a sofa is not a meadow. Two matrices hold what it worked out, where is where a word goes in and is where a word comes out.
| pair | cosine in | cosine in |
|---|---|---|
| cat / puppy | ||
| cat / kitten | ||
| horse / cow | ||
| cat / horse | ||
| sofa / cushion | ||
| meadow / barn | ||
| sofa / meadow |
Read the two columns separately, because they disagree. In the animals separate cleanly, with cat and puppy at while cat and horse score , whereas the places do not separate at all. The reason is that sofa and cushion reach against sofa and meadow at , which is no distinction.
In it is the exact reverse. The places separate, at against on those same two pairs, while the animals stop separating, with cat and horse reaching .
The cause is the template. An animal only ever appears as context, so only its row of is trained. A place only ever appears as a target, so only its column of is trained, and each word learned its structure in the matrix it was used in.
That explains a design choice from two chapters ago, since it is why word2vec keeps two vectors per word and why GloVe keeps and . Being a context and being a target are different jobs, and one vector cannot hold both.
The generalisation now follows. A held-out animal lands near an animal the model has seen, so its prediction transfers, whereas a count table has no such geometry and every unseen pair drops to the floor.
Run it.
code/worked_examples/neural_lm.pyproduces every table in this chapter.--paramsprints the parameter breakdown,--forwardthe forward and backward pass, and--generaliseruns the whole experiment, including the overfitting curve and the two cosine columns. Add--seeds 10to check that the result is not luck.
Between the count-based world and the fully neural one sits a model clean enough to deserve its own section. Strip the hidden non-linearity of Equation (11.1) away entirely, predict a single target feature vector by a linear combination of the context embeddings, , then score each candidate word by how well its own embedding matches that prediction:
This is the log-bilinear model of Mnih and Hinton (2008), which has no hidden layer and no non-linearity and still beat n-gram models on perplexity. That result carries an argument, namely that the gain came from shared representations, not from depth.
Two of its details are quietly illuminating. The per-word bias ends up encoding roughly the unigram log frequency of word , so the model reconstructs the frequency prior for free, the same job GloVe’s biases did in Chapter 9. Equation (11.6) is a dot product between a context vector and a word vector followed by a softmax, the skip-gram objective seen from another angle.
The embeddings of Chapter 9 and the language models of this chapter are the same machine with two emphases. word2vec cares about the vectors and treats prediction as a means, while the language model cares about the prediction and treats the vectors as a means, and each gets the other for free.
The representation gap is closed, since words that behave alike acquire vectors that sit alike, prediction is computed, not looked up, and generalisation to unseen combinations is now measurable. On the first blindness of Chapter 10 the model has made no progress at all, and one line of the architecture already said why. The context is a fixed-length concatenation of embeddings, so choosing freezes the window as rigidly as it was frozen for the counter. A neural 4-gram model sees three words of history and not one word more, and everything before that falls off the same cliff.
Take “the book that the committee rejected was short”, where the subject sits eight words back. No window of three can reach it, however rich the embeddings inside that window are.
The consequences come as a group. The model is memoryless, since it does not know where the context came from or what preceded it. It cannot accept arbitrary input length, because the architecture is fixed the moment the window is chosen. Every context is treated in isolation, so nothing carries from one prediction to the next. It is not a state machine, though many language tasks need a summary of the whole sentence and this model has nowhere to keep one. And temporal dependencies are therefore lost, so that if a word occurs twice in a sentence and the window cannot span both, the model learns it twice as if the two were unrelated.
What we need is an architecture with no fixed limit on the prior context, one that reads left to right while carrying a summary of everything seen so far and updating it at each word. That summary is a state, the update rule is a recurrence, and the model that results is the recurrent neural network of Chapter 12.
It keeps every gain of this chapter, since the shared embeddings, the softmax head, the cross-entropy objective and the perplexity yardstick all carry over untouched. Only the window finally goes.
Summary
A neural language model replaces the count table by a network that reads embeddings of the previous words, concatenates them, passes them through a hidden layer and predicts the next word with a softmax. Most of its parameters sit in the output matrix, and the embedding matrix is shared across positions, so what is learned about one word is available everywhere. Training is maximum likelihood, and the average cross-entropy is the logarithm of perplexity. A first attempt on a small corpus fails and a second works, and held-out perplexity rises again after its minimum, so early stopping is needed. The model is a log-bilinear relative of word2vec. Its context is still a fixed window, so it is memoryless and cannot take arbitrary input length.
Key terms
neural language model. a network that predicts the next word from embeddings of the previous words.
embedding matrix. the learned matrix whose rows are word vectors, shared across context positions.
categorical cross-entropy. the negative log probability of the observed word under the softmax output.
early stopping. keeping the weights from the point where held-out error was lowest.
log-bilinear model. a language model that scores a word by a dot product with a context vector, with no hidden nonlinearity.
Bengio et al. (2003) is the founding paper of neural language modelling and remains readable. Mnih and Hinton (2008) introduce the log-bilinear family. Morin and Bengio (2005) give the hierarchical softmax that first made the output layer affordable. Jurafsky and Martin (2025) present the same lookup, concatenate, mix and softmax structure used here.
11.1 Where the parameters live. For , , a context of words and , count the parameters in , and separately and confirm the total of . Which matrix holds the majority, and how does its size scale as the vocabulary grows? Now recompute with and say which share moved.
11.2 The softmax bottleneck. Explain why computing the loss for one training example requires a sum over the entire vocabulary. Name two techniques from this chapter that avoid the full sum, and say in one line what each computes instead.
11.3 Cross-entropy is perplexity. Show that minimising Equation (11.5), averaged over the corpus, is the same objective as minimising the perplexity of Section that section. Name the one operation that turns an average cross-entropy into a perplexity.
11.4 One step by hand. Using the five word model of this chapter, verify that the loss on the target is nats and that the output gradient is . Then explain why one entry of that gradient is negative, and what would change if two words were correct.
11.5 A longer window. The configuration above uses a context of words. Recompute the parameter table for contexts of and words. Which matrix grows, which does not, and what does that say about the cost of a longer window?
Build and measure
11.6 Reproduce the overfitting curve. Run the generalisation experiment and record held-out perplexity every steps. Where is the minimum? Now shrink the hidden layer to and run again. Does the curve still turn upwards, and if so, later or earlier? Explain the answer in terms of parameters against training examples.
11.7 Explain the two columns. The chapter finds that animals separate in while places separate in . Design a template that would make a word appear both as context and as target, predict what the two columns would then look like, and test your prediction.
11.8 Predict the minimum. Before running anything, predict whether a model with twice the embedding size reaches its held-out minimum earlier or later, and whether the minimum is lower. Then run it and report both numbers.
11.9 What the log-bilinear model proves. Equation (11.6) has no hidden non-linearity, yet it beats n-gram models on perplexity. Argue what this says about the source of the neural model’s advantage, shared representations against depth. Then explain the sense in which the model is the same machine as word2vec.
In practice
11.10 Choosing the vocabulary. A team raises the vocabulary from to words. Use the parameter count to estimate the change in model size and in the cost of one softmax, and name the two techniques that would keep the cost down.
11.11 The window that is too short. A model with a four-word window completes the keys to the cabinet with is. Say why a fixed window makes this error likely, and what kind of model removes the limit.
11.12 Reading a curve. Training loss falls steadily while held-out loss falls and then rises. Name the phenomenon, say which of the three splits you used to detect it, and say what you report as the final result.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
neural_lm.pyA neural LM, counted and trained
The parameter count, one forward and backward pass, and an overfit caught by a third split.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.