After this chapter you will be able to
write the probability of a sentence with the chain rule, and say what the Markov assumption removes;
estimate bigram probabilities by counting, with the padding and vocabulary conventions that change the numbers;
apply add- smoothing and say what it does to the probability mass;
compute perplexity from conditional probabilities, and explain why it equals ;
say what interpolation and backoff add, and what counting cannot fix.
This chapter builds on Chapter 8, for cross-entropy, and Chapter 3, for the long tail that makes smoothing necessary.
Finish this sentence.
How you
You said are. Everyone says are. Now try this one.
How much
Here the answers spread out, because is, does, time and longer are all reasonable, so you did not pick one answer but held several, ranked. That ranking is the subject of Part III, and a model that can produce it is a language model. The rest of this book is a series of steadily more capable ways to build one.
Notice how much you brought to a two word prompt. Lexical knowledge told you which words exist and which are common, syntactic rules told you that How are needs a subject next, and semantic cues ruled out How are cement. World knowledge told you that people greet each other this way, and pragmatics told you the sentence was a greeting and not a question about health. These are five kinds of knowledge, none of them written down anywhere, all applied in under a second.
The engineering question is how to put that box on a computer. For thirty years the field tried to write the five knowledge sources down as rules, and it did not work, for the reasons Chapter 1 gave.
This chapter takes the other road. Rather than encode the knowledge at all, it counts how often things happened and lets the counts stand in for all five. That sounds far too crude to work, yet it works very well, and where it fails it fails in ways that point straight at what comes next.
A language model assigns a probability to a sequence of words, and that is the whole definition. Pause on how strange it is, since nothing in it mentions grammar, meaning or truth, and a language model is simply a probability distribution over strings.
Yet this one idea is the foundation of everything after, because the neural models of Chapter 11, the recurrent networks of Chapter 12 and the large language models of Chapter 19 all answer the same question. Given what has been said so far, what comes next, and with what probability? Only the machinery changes.
Historically, because many language technologies reduce to choosing between candidate word sequences. A speech recogniser hears a signal that fits both “recognise speech” and “wreck a nice beach” and must pick one. A translation system generates a dozen candidate renderings and must rank them. A spelling corrector must decide whether “their going home” was meant to be “they’re going home”. In every case the winning move is the same, which is to prefer the candidate the language model scores higher. Today the motivation is more direct, because a modern large language model is a language model in this chapter’s sense, producing its output one next word distribution at a time.
We want the joint probability of a sentence , and the chain rule of probability factorises it with no approximation:
Equation (10.1) converts one impossible problem into merely difficult ones, where the impossible problem was a distribution over all sentences and the difficult one is a distribution over the next word given a history. It also shows why a language model is a generative model. Sample from the first factor, append the word, condition on it and sample again, repeating until you draw the stop symbol, and you have written a sentence.
The difficulty that remains is the history, because the context can be arbitrarily long and almost every particular history is one nobody has ever seen. No corpus contains reliable statistics for the exact prefix “The results of the 2026 municipal elections in Tenkasi suggest”, which has appeared once, in this book.
The n-gram model’s answer is bold, which is to forget the past. More precisely, assume the next word depends only on the previous words. A run of consecutive words is an n-gram, which is why this is the n-gram model:
With , a bigram model, each word depends only on its predecessor, while with , a trigram model, it depends on the previous two, and with , a unigram model, on nothing at all. This is a Markov assumption and it is plainly false, since in “The book that the committee rejected was short” the verb agrees with book, eight words away. The assumption is made because it buys something we cannot otherwise have, which is contexts short enough to recur.
The history “of the” appears thousands of times in a modest corpus, so statistics conditioned on it are trustworthy, whereas the history in the Tenkasi example appears once and statistics conditioned on it are worthless. The whole art of n-gram modelling is therefore one trade off. Longer context means a sharper prediction on thinner evidence, and shorter context means a blunter prediction on firmer evidence.
How do we get the conditional probabilities? By the most honest method available, which is counting. The maximum likelihood estimate (MLE) of a bigram probability is the fraction of times the context was followed by the word in question:
This is the whole method, with no optimisation and no training loop. Read the corpus, keep two counters, divide.
We will use three sentences for the whole chapter, so that every number in it can be verified by hand.
the cat sat the cat ran the dog sat
The word the occurs three times, twice followed by cat and once by dog, so
and every other continuation of the has probability zero. Hold on to that zero, because it becomes the villain of the chapter.
Before any two implementations of Equation (10.3) can agree, three bookkeeping conventions must match. They sound like pedantry, and each one changes the answers, so they must be fixed before any two sets of numbers are compared.
The first is padding. Each sentence is padded with
start symbols <s> and one stop symbol
</s>. The start padding gives the first word a
context, so that a bigram model can speak of
,
while the stop symbol does something deeper by making sentence
length part of the model. Without it the model only ever
assigns mass to continuing and never to stopping, so the probabilities
of all sentences of all lengths sum to more than one. With it, ending a
sentence is an event like any other.
The second concerns unknown words, because a model trained
on our three sentences will one day meet the word elephant. The
remedy is a designated symbol <unk>, to which every
word absent from the training vocabulary maps, and which is an ordinary
vocabulary item in its own right. So the vocabulary of our corpus is
Note what is not in
.
The start symbol is context only, so it is never predicted, never needs
a probability, and must never be mapped to <unk>.
The third convention settles what gets scored. Probabilities, and
later perplexity, are computed over the predicted tokens,
meaning the words of the sentence plus the one </s>,
and the start padding is never scored.
State these three and Equation (10.3) is reproducible to the last decimal. Omit them and two correct programs will disagree.
Our model believes and . The first claim is merely overconfident and the second is fatal, because under the chain rule a single zero factor drives the whole sentence to probability zero and its perplexity to infinity. Yet “the dog ran” is perfectly good English and merely failed to appear in three sentences of training data, so the model has confused unseen with impossible.
The remedy is to smooth, shaving a little mass off what we saw and handing it to what we did not. The simplest scheme is add- smoothing, which pretends every vocabulary item was seen extra times in every context:
The
in the denominator is what makes the probabilities sum to one again.
This is why the vocabulary convention matters and why
</s> and <unk> have to be counted
in
.
Set and , then look at every continuation of the, whose context was seen times.
| next word | count | MLE | add-1 | what changed |
|---|---|---|---|---|
| cat | 2 | 0.6667 | 0.3000 | lost |
| dog | 1 | 0.3333 | 0.2000 | lost |
| the | 0 | 0.0000 | 0.1000 | gained |
| sat | 0 | 0.0000 | 0.1000 | gained |
| ran | 0 | 0.0000 | 0.1000 | gained |
</s> |
0 | 0.0000 | 0.1000 | gained |
<unk> |
0 | 0.0000 | 0.1000 | gained |
| total | 3 | 1.0000 | 1.0000 |
Both columns sum to one, as they must, and the two seen words gave up between them while the five unseen words received each. The counts did not change, and the belief did. The same table for the context dog, which was seen only once, shows the weakness.
| next word | count | MLE | add-1 |
|---|---|---|---|
| sat | 1 | 1.0000 | 0.2500 |
| cat | 0 | 0.0000 | 0.1250 |
| dog | 0 | 0.0000 | 0.1250 |
| the | 0 | 0.0000 | 0.1250 |
| ran | 0 | 0.0000 | 0.1250 |
</s> |
0 | 0.0000 | 0.1250 |
<unk> |
0 | 0.0000 | 0.1250 |
| total | 1 | 1.0000 | 1.0000 |
This is the repair we wanted, since has risen from to and “the dog ran” is no longer impossible. It is also where add- shows its weakness, because moving from to is a scalping and not a shave, and the evidence for it was a single observation.
The effect scales badly. With a realistic vocabulary of tens of thousands the denominator is dominated by , so nearly all the mass goes to events nobody has ever seen. In practice one therefore uses a small tuned on held out data, or one of the better schemes in Section 10.8.
The principle never changes. Every language model, up to the largest, must reserve belief for things it has not seen.
Two colleagues each hand you a language model, and you must say which is better. The models are distributions, so let the data decide: the better model is the one that finds held out text less surprising, which is to say it assigns the text higher probability.
Raw probabilities are unwieldy because they shrink exponentially with length, so we normalise, and the average negative log probability per predicted token is the model’s cross-entropy on the text:
measured in bits per token. Its exponential is the perplexity:
Here
counts the predicted tokens, meaning the words plus
</s> by the convention above. Perplexity has a clean
reading as the model’s effective branching factor, the size of
the uniform distribution that would be equally surprised. A perplexity
of
means the model is as uncertain at each step as if it were choosing
among
equally likely words, so lower is better, and a model that knew the text
by heart would score
.
The zero we worried about gives
and hence perplexity
.
This is the formal statement of why unsmoothed models are unusable.
Equations (10.5) and (10.6) follow from a statement about probability alone, and the exponential of an entropy is what that statement turns into. Start with the probability the model assigns to the whole text. The chain rule splits it into one factor per predicted token:
Perplexity is the reciprocal of the geometric mean of those factors:
Two choices in that line do the work. Taking the reciprocal makes a better model score lower, because assigning high probability to genuine text is what we are rewarding. Raising to the power divides the length out, so a long passage is not penalised merely for being long. Without it every text would score worse than a shorter one and no two test sets could be compared. Rewrite Equation (10.8) as an exponential. For any positive we have , so
where the second step uses . Expanding with Equation (10.7) turns the logarithm of a product into a sum:
and the right hand side is from Equation (10.5). Substituting it into the exponent returns Equation (10.6), .
The two readings are one number. is the average number of bits the model spends per token, and raising to that power converts bits back into a count of equally likely choices. The branching factor reading above is therefore a restatement of the same quantity: is the number of uniform options those bits could index.
The base is bookkeeping. Use the natural logarithm in Equation (10.5) and the same derivation gives , the same number reached by a different route. Base is conventional because it reads directly as bits, the way Shannon entropy is usually quoted.
Take the bigram model with
and score the sentence the cat sat, which padded is
<s> the cat sat </s>,
giving four predicted tokens. Each row applies Equation (10.4) with
.
| predicted | context | count | of | ||
|---|---|---|---|---|---|
| the | <s> |
3 | 3 | ||
| cat | the | 2 | 3 | ||
| sat | cat | 1 | 2 | ||
</s> |
sat | 2 | 2 | ||
| sum | |||||
The count column is and of is , so every probability is . Now finish it:
The model is about as unsure at each step as if it were choosing
uniformly among
words, where the vocabulary holds
,
and on a corpus this small that is a respectable score. Two details in
that table need a note. The first row scores the in the context
<s>, the reason the padding exists. The last row
scores </s>, the reason
,
not
.
Perplexity gives us a way to pick , which is to try several and keep the best. The catch is which text you measure on. Here are two sentences, where the cat sat is in the training data while the dog ran is not, though every word of it is and only the bigram is new.
| PP on the cat sat | PP on the dog ran | |
|---|---|---|
| 0.01 | 1.3466 | 4.3297 |
| 0.02 | 1.3767 | 3.7788 |
| 0.05 | 1.4649 | 3.3211 |
| 0.10 | 1.6050 | 3.2047 |
| 0.15 | 1.7374 | 3.2408 |
| 0.20 | 1.8628 | 3.3166 |
| 0.50 | 2.4982 | 3.8394 |
| 1.00 | 3.2568 | 4.4721 |
| 2.00 | 4.1902 | 5.1845 |
The two columns tell opposite stories. The seen column falls all the way down, because less smoothing always looks better on text the model has memorised, and it would keep improving as . The held out column is a U, bottoming at and rising on both sides.
Both sides of that U have a cause. Too little smoothing and the single unseen bigram is crushed towards zero probability, while too much and the seen bigrams are robbed to pay for events that never happen. Tuning on training text would have chosen , which scores on new text against the best available , making it times worse from a decision that looked correct at the time.
Perplexity is only comparable across models that share a vocabulary and a tokenisation, because a model with a smaller vocabulary has an easier problem and the subword tokenisers of Chapter 5 change itself. Perplexity also measures surprise, not usefulness, so it correlates with downstream quality without guaranteeing it. Both cautions return with force in Chapter 23.
Everything so far suggests a simple way to improve the model, which is to use a longer context, on the grounds that if bigrams are good then trigrams should be better. They are, for a while, and then the arithmetic stops you.
An n-gram model needs one number per history and word, and there are possible histories with free choices inside each, since the last probability is fixed by the others:
That exponent is the whole problem.
| 1,000 | |||||
| 10,000 | |||||
| 50,000 |
Take the bottom right cell, where a 5-gram model over a word vocabulary has about parameters. Now count what could fill them. A corpus of a trillion tokens contains at most a trillion distinct 5-grams, one per position, so at most one cell in can hold a nonzero count.
The counts do not merely get thin. Almost the entire table is empty, and no corpus that will ever be assembled can change that.
Three consequences follow. Data sparsity means most n-grams have zero or tiny counts, so their probabilities cannot be estimated reliably. Overfitting means the model latches onto the exact phrases in the training text and generalises to nothing else. And computational cost means storing and searching the table grows with the same exponent.
The framework can be pushed further than add-, and three techniques matter. Pruning discards n-grams with low counts, which saves space and removes estimates that were never trustworthy. Interpolation mixes the orders, so that when the trigram evidence is thin you lean on the bigram, and when the bigram fails too you lean on the unigram:
subject to the one constraint , where the weights say how much to trust each level of context and are tuned on held out data like any other hyperparameter, a setting the experimenter chooses and the model does not learn. Backoff does the same job with a switch instead of a blend, using the trigram if you have seen it and otherwise dropping an order and trying again.
Take a four sentence corpus, so that the trigram counts can run out while the bigram counts still survive.
the cat sat on the mat the cat sat on the rug
the dog sat on the mat a cat ran to the mat
Set , and , then take four queries in decreasing order of evidence. All three estimates below are unsmoothed, so the failures stay visible.
| query | mixed | counts | |||
|---|---|---|---|---|---|
| 1.0000 | 1.0000 | 0.1071 | 0.9107 | tri 2, bi 3 | |
| 0.6667 | 0.4286 | 0.1071 | 0.5393 | tri 2, bi 3 | |
| 0.0000 | 0.2857 | 0.1071 | 0.0964 | tri 0, bi 2 | |
| 0.0000 | 0.0000 | 0.0357 | 0.0036 | tri 0, bi 0 |
Read the four rows as a staircase. Row one has full evidence at every order, because the trigram cat sat on was seen twice and never continued any other way, so all three estimates are high and so is the mixture.
Row two shows what the extra context buys, since the trigram is sharper than the bigram at against , because on the narrows the field more than the alone. Row three is the one that matters. The trigram on the cat never occurred, so and a pure trigram model would call the phrase impossible, whereas the bigram has seen the cat twice and says . The mixture returns and the sentence survives.
Row four is the last resort, where the word ran never follows the anywhere in this corpus, so both higher orders fail and only the unigram is left. The answer is small, and what matters is that it is not zero.
Kneser-Ney smoothing (Kneser and Ney 1995) is the state of the counting art, and it refines the lowest order term. What matters for an unseen context is how many distinct contexts a word occurs in, not how often it occurs, so that Francisco is common yet occurs almost only after San and deserves very little unseen-context mass. Refinements of this kind carried speech recognition and translation for two decades.
Run it.
code/worked_examples/ngram_lm.pyproduces every table in this chapter, using the conventions stated in this chapter.--countsprints the two smoothing tables,--perplexitythe four row calculation,--alphathe U shape,--paramsthe parameter explosion,--interpolatethe staircase, and--unkwhat happens to a word the model has never met.
Smoothing repairs the zeros and interpolation repairs thin evidence, while neither touches the two remaining blindnesses, and both of those are structural. The first is the Markov assumption. The model cannot know that book, eight words back, governs the verb it is about to emit, because eight words back does not exist for it. Raising does not solve this, since the parameter table of Equation (10.11) explodes long before reaches eight.
The second is that words are opaque strings. Suppose the corpus contains the cat sat many times and the dog only once, and a counter has no way to let cat lend statistical strength to dog, because to a counter they are two unrelated symbols.
Chapter 9 already built the cure for the second problem, when words became vectors and similar words came out near each other, and what was missing was a way to put those vectors to work on prediction. This is what the next chapter does, keeping the task, the corpus, the smoothing instinct and the perplexity yardstick while replacing the count table with a network.
Summary
A language model assigns a probability to a sentence, and the chain rule factorises it into next-word conditionals. The Markov assumption keeps only the last words, so the conditionals can be estimated by counting. Padding, the stop symbol and the vocabulary convention change the numbers, so they must be stated. Maximum likelihood gives zero to every unseen event, and add- smoothing moves mass to them, at a cost that grows when the context was rare. Perplexity is the inverse probability of the test set, normalised by length, and it equals , the effective number of equally likely choices. Parameters grow as the vocabulary to the power , so higher orders starve for data, and interpolation and backoff mix orders to compensate. Counting cannot share strength between related words and cannot see beyond the window, which is what the next chapter addresses.
Key terms
language model. a model that assigns a probability to a sequence of words.
chain rule. the factorisation of a joint probability into a product of conditionals.
Markov assumption. the approximation that a word depends only on the previous words.
smoothing. moving probability mass from seen events to unseen ones.
perplexity. the inverse probability of a test set normalised by its length, .
interpolation. a weighted mixture of n-gram models of different orders.
backoff. using a lower-order model when the higher-order context was not seen.
Jurafsky and Martin (2025) cover this material with more smoothing
variants and worked examples. Chen and Goodman (1999) remains the
definitive empirical comparison of smoothing methods. Manning and
Schütze (1999) treat the statistical foundations in depth. Kneser and
Ney (1995) introduce the smoothing method that held the record for
years. The class-based n-grams of Brown et al. (1992) are an early
attempt to share statistical strength between related words, which is
the problem Chapter 11 solves properly. The
models of this chapter are implemented in nltk.lm, whose
MLE, Laplace and
KneserNeyInterpolated classes correspond to three of the
estimators above, and the last exercise below is about the one thing
that library cannot guess. Shannon (1948) is where the entropy of a text
was first proposed as something measurable, and it remains readable.
10.1 Counting, by hand. On the
corpus the cat sat / the cat ran / the dog
sat, with the padding, <unk> and
conventions of this chapter, compute
and
first by maximum likelihood and then with add-one smoothing. Confirm the
move for the first and the
move for the second. Say in one sentence which convention makes the
second answer nonzero.
10.2 Perplexity to four decimals.
For the same add-one bigram model, compute the perplexity of the cat
sat. The predicted tokens are the, cat,
sat and </s>, so
.
Show the four conditional probabilities and their logs, and recover
.
Then recompute with
,
by wrongly leaving out </s>, and report how far off
you land.
10.3 Entropy to perplexity. A model spends an average of bits per token on a test set. What is its perplexity? Repeat for bits. In one sentence, say what the first number means in terms of choices.
10.4 The chain rule and the Markov cut. Write with the chain rule. Then write the bigram and trigram approximations, and say which conditional factors change.
Build and measure
10.5 Implement
perplexity(). Write a function that takes a
trained n-gram model and a token sequence and returns its perplexity. It
must handle the trigram case as well as the bigram, map out of
vocabulary tokens to <unk>, and score
</s>. Test it against your hand answer above.
10.6 Find the U yourself. Train bigram models on the three sentence corpus with ranging from to . Plot perplexity on the cat sat and on the dog ran. Explain why one curve is monotone and the other has a minimum, and state which one you would use to choose in a production project.
10.7 Calibrate before you measure. Write three short sentences and rank them, before computing, from least to most surprising under your model. Then compute their perplexities. Where your ranking was wrong, name the feature of the training counts you had mis-weighted.
10.8 Count the parameters. Using Equation (10.11), compute the parameter count for at . Then estimate how many distinct n-grams a corpus of one billion tokens could possibly contain. At which does the corpus stop being able to fill even one cell in a thousand?
10.9 Interpolate. On the four sentence corpus of Section 10.8, verify the four rows of the staircase table by hand. Then change the weights to and recompute. Which row changes most, and why is it the row where the higher orders had failed?
10.10 A library cannot guess your
conventions. Train nltk.lm.Laplace at order
on the three sentence corpus of this chapter and ask it for the
perplexity of “the cat sat”. It returns
where this chapter computes
.
Print len(m.vocab) and compare it against the
this chapter uses, then name the token the library is counting that this
chapter deliberately does not, and say which of the two is right. This
is the warning of Section 10.6
arriving as a number and not as advice: a perplexity without its
conventions is not a measurement.
In practice
10.11 Domain mismatch. A bigram model trained on news has perplexity on held-out news and on a sample of tweets. Give two reasons from this chapter, and say which of them smoothing could reduce.
10.12 Comparing two tokenisers. Model A is a word-level bigram model with perplexity . Model B is a subword model with perplexity . A colleague concludes that B is five times better. Use the chapter’s cautions to say why the comparison is not valid, and name what you would compute instead.
10.13 Why not order ten? A team proposes a ten-gram model on a corpus of one billion tokens because it fits the training set perfectly. Use the parameter count and the zero problem to explain what will go wrong on new text, and name the two mechanisms of this chapter that would help.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
ngram_lm.pySmoothing, perplexity and the U-curve
Add-alpha smoothing, held-out perplexity and interpolation, on three sentences of training data.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.