Chapter 10 left the n-gram model with two admitted blindnesses.
It cannot see far enough back. The Markov assumption throws away everything before the last words.
It cannot see that two words are related. To a counter, cat and dog are just different strings. A context seen with one lends no strength to the same context seen with the other.
This chapter repairs the second. 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. 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 is worth stating carefully.
A trigram model over words has one free number for every possible three word cell. That is about of them, as Equation (10.7) counted.
No corpus fills more than a vanishing fraction. Worse, the cells are entirely independent of one another.
Learning tells the model nothing whatsoever about . 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 , is to stop storing a number per context. Instead, compute the probability from a learned dense representation of each word.
Those are the distributed representations of Chapter 9. Similar words get similar vectors, and therefore, automatically, similar predictions.
Fix a context of the previous words. The model computes the distribution over the next word in four movements. Each one is machinery from Chapter 8.
Every word owns a row of an embedding matrix . The row is its dense vector.
The one-hot index of a context word selects its row. That is a lookup, not a multiplication, though it is convenient to write it as multiplying a one-hot vector by .
The same matrix serves every context position. This sharing is the whole point of the chapter.
The context embeddings are strung together into one vector
This is the model’s entire memory of the past. Note that its length is fixed the moment is chosen. That fact returns at the end of the chapter.
A hidden layer applies a learned affine map and a non-linearity:
This lets the model form non-linear combinations of the context. It is where “the of” can learn to behave differently from the sum of its parts.
An output map produces one score per vocabulary word, and a softmax turns the scores into a distribution:
The entry is the model’s estimate of .
The parameters are , , , and . They are learned jointly, and is learned along with the rest.
A hand count is clarifying, and it explains much of what the field did next.
Take a modest configuration. 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. The counter needed about cells. The network needs million, which is times fewer, or almost six orders of magnitude.
And the network shares them. What the model learns about dog is available in every context where dog appears. A count table shares nothing between cells.
Second, look at the share column. 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. That output softmax is the computational bottleneck of neural language modelling.
The tricks for dodging it are already familiar. Hierarchical softmax , noise-contrastive estimation, and the negative sampling of Chapter 9 all exist for this reason.
Training is maximum likelihood, exactly as before. The knob we turn is now the network’s weights rather than a table of counts.
The lectures derive the loss from first principles, and the derivation is short enough to give in full.
Write . For a single binary outcome this is a Bernoulli distribution, so
Take logs of Equation (11.3):
Maximising a log likelihood is minimising its negative, which gives the cross-entropy loss:
Our case is not binary but -way, and the true target is a one-hot vector. So the sum runs over the vocabulary:
where indexes the word that actually occurred. Because is one-hot, every term but one vanishes.
So the loss on one example is simply the negative log probability the model gave to the right answer.
Average Equation (11.6) over the corpus, take base two, and exponentiate. That is the perplexity of Section that section. Minimising cross-entropy and minimising perplexity are one objective in two sets of clothes.
Backpropagation sends the gradient of Equation (11.6) back through the softmax, through the hidden layer, and into itself. The word vectors are not given to the model. They are learned, as a by-product of learning to predict.
Take a model small enough to print. Vocabulary of five words, , , context of two words. 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.6) the loss is , which is nats.
A model scoring every token this way would have perplexity , against a vocabulary of five.
That is a model doing no better than guessing, which is correct. 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 :
And the prediction improves.
| 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. That claim is testable, so we should test it.
Build two families. Five pets rest in four indoor places. Five farm animals rest in four outdoor places.
| 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. That gives sentences.
The animal sits inside the trigram context, so a counter can see it too. Nothing is hidden from the baseline.
Hold out sentences. Keep more for deciding when to stop training. Train on the remaining . Score only the place slot, since the place is what the animal is supposed to determine.
Train the network and watch both perplexities.
| 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. 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. This 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. That is early stopping, and it is why a project needs three splits rather than two.
With early stopping in place, run six random splits.
| 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 .
The trigram model sits near because a held-out pair is a cell it never counted. It falls back to the smoothing floor, which is nearly uniform over the places. The network does not fall back. It computes.
Nobody told the model that kitten resembles cat, or that a sofa is not a meadow. Two matrices hold what it worked out. is where a word goes in. 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. Cat and puppy score while cat and horse score . The places do not separate at all. Sofa and cushion reach against sofa and meadow at , which is no distinction.
In it is the exact reverse. The places separate, against on those same two pairs. 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. Each word learned its structure in exactly the matrix it was used in.
That explains a design choice from two chapters ago. 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. A count table has no such geometry, and every unseen pair drops to the floor.
Try it yourself.
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 . It has no hidden layer and no non-linearity, and it still beat n-gram models on perplexity.
That result carries an argument. 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. That is the same job GloVe’s biases did in Chapter 9.
And Equation (11.7) is a dot product between a context vector and a word vector, followed by a softmax. That is the skip-gram objective seen from another angle.
So 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. The language model cares about the prediction and treats the vectors as a means. Both fall out together.
The representation gap is closed. Words that behave alike acquire vectors that sit alike. Prediction is computed rather than 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 exactly embeddings. 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. Everything before falls off the same cliff.
Take “the book that the committee rejected was short”. The subject sits eight words back. No window of three can reach it, however rich the embeddings inside that window are.
The lectures list the consequences, and they are worth naming as a group.
The model is memoryless. It does not know where the context came from or what preceded it.
It cannot accept arbitrary input length. The architecture is fixed the moment the window is chosen.
Every context is treated in isolation. Nothing carries from one prediction to the next.
It is not a state machine. Many language tasks need a summary of the whole sentence, and this model has nowhere to keep one.
Temporal dependencies are therefore lost. If a word occurs twice in a sentence and the window cannot span both, the model learns it twice as if they were unrelated.
What we need is an architecture with no fixed limit on the prior context. One that reads left to right, 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. The model that results is the recurrent neural network of Chapter 12.
It keeps every gain of this chapter. The shared embeddings, the softmax head, the cross-entropy objective and the perplexity yardstick all carry over untouched. Only the window finally goes.
is the founding paper of neural language modelling and remains readable. introduce the log-bilinear family. give the hierarchical softmax that first made the output layer affordable. present the same lookup, concatenate, mix and softmax structure used here.
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.
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.
Cross-entropy is perplexity. Show that minimising Equation (11.6), 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.
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 exactly one entry of that gradient is negative, and what would change if two words were correct.
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.
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.
What the log-bilinear model proves. Equation (11.7) 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.