Majid Al-RaimiFull guide

ICS 582Lecture 03Full guide

N-gram language models

The whole lecture on one page, taught concept by concept. Work through the parts in order, mark each concept once you understand it, and open the slide chips when you want the original slides.

Parts
10
Concepts
54
Slides
105
Reading
324 min
Understood
0/54 concepts

Part 01: Why language models predict words

The motivation for language modeling, the applications that rely on next-word probabilities, the two equivalent views of what an LM computes, and the split between count-based and neural models.

5 concepts, slides 1-9

Why this part matters

Every system you will meet in this course, from spell checkers and speech recognizers to machine translation, phone keyboards and today's large language models, rests on one quantity: the probability of the next token given everything before it. This part pins down exactly what that quantity is before the lecture shows how n-grams estimate it.

The rest of the lecture is about estimation, evaluation and repair, and none of it makes sense until the target is clear. Exams routinely ask you to name an application and explain how a probability over word sequences helps it, and any research project that touches text generation, decoding or scoring uses the vocabulary set up here.

By the end you can

  1. Define a language model as a probability distribution over the next word given a history, and explain why it outputs a distribution rather than a single word.
  2. Explain how an LM helps spelling correction, speech recognition, machine translation, AAC and predictive text, using the candidates-plus-ranking (noisy channel) pattern.
  3. Relate next-word probabilities to whole-sentence probability through the chain rule, and compute the probability of a short sentence from given bigram values.
  4. Contrast count-based and neural language models on estimation, generalization and parameter growth.

Read the roadmap as one story. We want to predict the next word, so we count words in a corpus to estimate probabilities. We measure the result with Perplexity, and we look at what the model has learned by generating text from it. Then the model breaks: any word sequence it never saw gets probability zero. The second half of the lecture is the repair kit, from Smoothing through interpolation, Backoff and absolute discounting to Kneser-Ney, and it closes by connecting perplexity to Entropy.

  1. Motivation: predicting words. What an LM computes and where that number is used. This part.
  2. N-grams. The chain rule and the Markov assumption turn an impossible history into the last few words.
  3. Estimating n-gram probabilities. Counting and dividing: maximum likelihood estimates, and log probabilities to avoid underflow.
  4. Evaluating language models: perplexity. How to tell a better model from a worse one on held-out text without building a whole application.
  5. Sampling from an LM. Generating text by drawing from the distribution, which shows what the model has actually learned.
  6. Generalization and overfitting. Why a model tuned to its training corpus fails on new genres and assigns zero to unseen n-grams.
  7. Smoothing, interpolation and backoff. Moving probability mass to unseen events and mixing in shorter contexts.
  8. Absolute discounting. Subtracting a fixed amount from every seen count, justified by held-out data.
  9. Kneser-Ney intuition. A lower-order distribution built from how many contexts a word completes, not how often it occurs.
  10. Interpolated Kneser-Ney for bigrams. The full computation step by step on a toy corpus.
  11. General Kneser-Ney. The recursion to higher-order n-grams, the standard count-based baseline.
  12. Perplexity and entropy. The information-theoretic meaning of the evaluation metric.

Underneath the twelve stops there is a single question: how do we turn finite counts into a probability for every possible next word, including words never seen after this context? Stops 2 to 4 answer the easy half, for events we have seen. Stops 6 to 11 answer the hard half, for events we have not. The model family that carries all of it is the n-gram language model.

Finish this sentence: The water of Walden Pond is so beautifully ___. You probably thought of blue, green or clear. You did not think of refrigerator or this. You did not produce one word with certainty either. You produced a ranking with a sense of how much more likely some words are than others. That ranking, made numeric, is a language model.

A language model assigns a probability to each possible next word given the words so far, the history. Its output for one history is therefore a whole probability distribution over the vocabulary, and the task of producing it is next-word prediction. Writing the history as w<t, every word before position t:

P(wt∣w<t)for every wt∈V,∑w∈VP(w∣h)=1\begin{gathered} P(w_t \mid w_{<t}) \quad\text{for every } w_t \in V, \\ \sum_{w \in V} P(w \mid h) = 1 \end{gathered}
One history h, one distribution over the whole vocabulary V
Bars for the next word after 'The water of Walden Pond is so beautifully': blue and clear take most of the mass, refrigerator keeps a sliver that is small but not zero. Heights are illustrative, not measured.

The constraint that the probabilities sum to 1 is what makes the numbers comparable. If blue gains probability, something else must lose it. It also explains why the rest of the lecture worries about zeros: a model that spends all its mass on words it has seen has nothing left for refrigerator, even when a strange sentence really does continue that way.

This is not a toy objective. Jurafsky and Martin put it bluntly: large language models are built just by training them to predict words. GPT-3, with 175 billion parameters, is described by its authors as an autoregressive language model, which means exactly this: it computes P(w_t | w<t) one position at a time. A neural language model and an n-gram model answer the same question; they differ only in how they estimate the answer. GPT-3 itself was pretrained with plain next-token prediction, and modern LLMs use this objective or close variants of it; later tuning stages change the objective and shift the probabilities, but the output is still a distribution over the next token.

Recall

What exactly does a language model output for a given history?

A probability for every word or token in the vocabulary given that history: a distribution that sums to 1, not a single word.

Run a dictionary spell checker over Their are two midterms. Every word is in the dictionary, so it passes. The error is a real-word error: the typo produced another valid word, and nothing about any single word reveals it. What reveals it is context. There are is a very common Bigram and Their are is rare, so a model that compares P(There are) with P(Their are) flags the sentence at once. The same holds for Everything has improve, where the fix improved makes the more probable sentence.

Now speech. A recognizer hears something that sounds like I will be back soonish, but the audio is almost identical to I will be bassoon dish. The acoustic evidence cannot separate them. The language model can: back soonish is a far more probable continuation of I will be than bassoon dish.

Two transcriptions of the same audio feed one LM gauge; the LM scores 'be back soonish' as more probable English, the winner is checked and 'be bassoon dish' dims

The pattern: candidates in, ranking out

Both examples share a structure, and it is worth naming because it covers almost every classical application. Some other component proposes candidates: a set of spelling variants, an acoustic model, a translation model, a keyboard decoder. The language model does not know what you meant. It scores how plausible each candidate is as a piece of language, and the system combines that score with the evidence. Brown and colleagues wrote this down for statistical machine translation in 1990 as the noisy channel decoder: given a foreign sentence T, output the English sentence S that maximizes the product below, and they call the first factor the language model probability of S.

S^=arg⁡max⁡S  Pr⁡(S)⏟language model  Pr⁡(T∣S)⏟translation model\hat{S} = \arg\max_{S}\; \underbrace{\Pr(S)}_{\text{language model}}\; \underbrace{\Pr(T \mid S)}_{\text{translation model}}
Brown et al. 1990. In speech recognition the audio takes the place of T.

The split of labour is clean. Pr(T | S) rewards faithfulness to the input. Pr(S) rewards fluency, and it does not care about the input at all, which is why one well trained language model can be reused across speech, translation and spelling. It is also why these are the settings where language models are judged by extrinsic evaluation: a better LM is one that lowers the word error rate or raises the translation score of the whole system.

Prediction on its own

In a second family of applications there is no separate candidate generator. The prefix you have typed is the history, and the system shows the top few entries of P(next | prefix). Search autocomplete turns a quick into brown fox. A translation input box suggests think after what do you. A phone keyboard offers bro, brown and brother while you type The quick bro. All of these are argmax or top-k over the same distribution from the previous concept.

The application with the highest stakes is augmentative and alternative communication (AAC). People who cannot speak or sign may select words from a menu with eye gaze or other small movements. Trnka and colleagues report that AAC users often communicate at under 10 words per minute, against 150 to 200 for speech, and that in a study with simulated AAC users (able-bodied typists slowed by an artificial key delay), advanced word prediction produced 59.9% more words per minute than no prediction. More accurate predictions significantly improve the communication rate, so here a better language model is directly a faster conversation.

ApplicationCandidates come fromWhat the LM decidesExample
Spelling and grammar correctionVariants of the typed words: their, there, they're; improve, improvedWhich variant makes the more probable sentenceTheir are two midterms
Speech recognitionThe acoustic model, which proposes word sequences that match the audioWhich sound-alike transcription is fluent Englishback soonish / bassoon dish
Machine translationThe translation model, which proposes target sentences faithful to the sourceWhich faithful candidate is also well formedPr(S) Pr(T|S)
AACEvery word in the vocabulary, shown as a short menuWhich few words go on the menu, ranked by probabilityEye-gaze word selection
Search autocompleteContinuations of the typed query prefixWhich completions to show, before other ranking signalsa quick → brown fox
Mobile keyboardCompletions of the partial word and the next wordThe top three suggestions, the best in the centerThe quick bro → brown
Where the candidates come from and what the language model decides

Gboard is the best documented production example. Hard and colleagues describe how the keyboard shows three suggestions and the numbers behind them, and they make a useful benchmark for the comparison in the last concept of this part.

Gboard next-word prediction (Hard et al. 2018)

Suggestions shown
3 candidates, highest probability in the center
Baseline model
Katz-smoothed 5-gram, compiled as a finite-state transducer
Baseline size
1.25 million n-grams, 164,000 unigrams
Top-1 recall on server logs
n-gram 13.0%, federated CIFG 16.4%
Top-3 recall on server logs
n-gram 22.1%, federated CIFG 27.0%

Recall

Why can a spell checker that only consults a dictionary not fix 'Their are two midterms'?

Both words are valid, so it is a real-word error. Only the context probability, P(There are) greater than P(Their are), reveals it.

Recall

In the noisy-channel decoders of speech recognition and statistical MT, which factor is the LM and what does it contribute?

The LM is Pr(S), the prior over output sentences. It rewards fluent orderings, while the channel model Pr(T | S) or Pr(audio | S) rewards faithfulness to the input (Brown et al. 1990).

Quick check

A recognizer hears audio that fits both 'recognize speech' and 'wreck a nice beach'. Which component separates them?

Quick check

In the decoder argmax over S of Pr(S) Pr(T|S), what does the factor Pr(S) reward?

Compare all of a sudden I notice three guys standing on the sidewalk with on guys all I of notice sidewalk three a sudden standing the. Same twelve words, and none repeats, so there are 12! = 479,001,600 orderings. A good language model must put the fluent one near the top of all of them. That asks for something new: not a next word, but a probability for a whole sentence.

Twelve scrambled word tiles slide into the fluent order while the sentence-probability meter rises from almost nothing to high

Language models offer two views. View one is the next-word distribution, P(w_t | w<t). View two is the probability of an entire sequence, P(w_1:T). They are not two models. The chain rule of probability turns one into the other exactly:

P(w1:T)=∏t=1TP(wt∣w<t)P(w_{1:T}) = \prod_{t=1}^{T} P(w_t \mid w_{<t})
Sentence probability is the product of next-word probabilities. Part 02 derives it.

Going the other way, a next-word probability is a ratio of two sequence probabilities, P(w_t | w<t) = P(w_1:t) / P(w_1:t-1), so either view gives you the other. That is why slide 8 can call them equivalent. Here is a preview of the computation with the toy corpus Part 03 uses to teach counting.

Worked example

Preview: scoring a sentence with bigrams

  1. The corpus

    Three sentences, each wrapped in sentence boundary tokens: <s> I am Sam </s>, <s> Sam I am </s>, <s> I do not like green eggs and ham </s>.
  2. Read off the bigram probabilities

    A Bigram model conditions on one previous word. From the counts: P(I | <s>) = 2/3, P(am | I) = 2/3, P(Sam | am) = 1/2, P(</s> | Sam) = 1/2. How these come from counts is Part 03.
  3. Multiply along the sentence

    P(<s> I am Sam </s>) = 2/3 × 2/3 × 1/2 × 1/2.
  4. Result

    1/9 ≈ 0.111. The sentence probability is nothing but the next-word probabilities multiplied.

Is the sentence view really enough to recover word order? Brown and colleagues tested exactly the claim on slide 8 with an experiment they called bag translation. They cut sentences into an unordered bag of words, then asked a Trigram language model to choose the ordering with the highest Pr(S).

Worked example

Bag translation (Brown et al. 1990)

  1. Setup

    38 English sentences of fewer than 11 words, each shuffled into a bag.
  2. Decode

    Search over orderings for the one with the highest trigram probability. No grammar, no meaning, only Pr(S).
  3. Result

    24 of 38 (63%) came back in exactly the original order, and 32 (84%) came back with the meaning preserved.

The idea is older still. In 1948 Shannon drew each word of English text from the distribution of words that follow the previous word, a word bigram model done by hand, and got strings such as THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER: not meaningful, but recognizably English in its local order. Local next-word statistics already carry a surprising amount of a sentence's shape.

Recall

Write the relation between the two views of an LM.

P(w_1:T) = ∏ P(w_t | w<t) over t = 1 … T, the chain rule. With </s> at the end, the probabilities of sentences of all lengths sum to 1.

Recall

Using the SLP3 toy corpus, what is P(<s> I am Sam </s>) under the bigram model?

2/3 × 2/3 × 1/2 × 1/2 = 1/9 ≈ 0.111.

Quick check

If a model gives P(w_t | w_<t) at every position, what else does it give you directly?

Train a model on the cat sat on the mat, then ask it about the dog sat on the rug. A model that only counts has never seen dog sat, so it has no evidence for it beyond whatever Smoothing hands out. A model that knows dog behaves like cat and rug like mat can carry the probability across. That difference is the whole of slide 9.

Left, a bigram count table whose 'dog sat' cell is zero; right, an embedding space where dog drifts next to cat, and a teal line bridges the empty cell to the point that now borrows cat's evidence

A count-based language model, also called statistical, estimates P(w | h) by maximum likelihood estimation: the relative frequency of the exact n-gram among all n-grams that share its history. It is transparent, fast and cheap. Its weakness is Sparsity. Bengio and colleagues put the problem as the curse of dimensionality: modelling the joint distribution of 10 consecutive words with a vocabulary of 100,000 has potentially 100,000^10 − 1 = 10^50 − 1 free parameters, and a test sequence is likely to differ from every sequence seen in training.

A neural language model maps each word or token to a continuous vector and learns a function from those vectors to the next-word distribution. Bengio and colleagues explain why this generalizes: an unseen sequence gets high probability if it is made of words similar to words in an already-seen sentence. Jurafsky and Martin name the two n-gram problems neural models solve: the number of parameters increases exponentially as the n-gram order increases, and n-grams have no way to generalize from training to test examples unless they use identical words.

AspectCount-based (n-gram)Neural
How P(w | h) is estimatedRelative frequency of the exact n-gram, then smoothedA learned function of continuous word vectors
ParametersOne per observed n-gram; the possible table grows as |V|^nFixed by the network size, shared across all contexts
GeneralizationOnly across identical word sequencesAcross similar words: evidence about cat transfers to dog
Context lengthShort in practice: n of 2 to 5, so 1 to 4 previous wordsLong: hundreds to many thousands of tokens in transformers
Training costOne counting pass; fast and cheapGradient training over many passes; GPU hours to months
InterpretabilityEvery probability traces to a count you can inspectDistributed over millions or billions of weights
ExamplesSRILM, KenLM, modified Kneser-Ney 5-gramsBengio 2003 MLP, RNN and LSTM LMs, transformers such as GPT-3
Gboard, 20185-gram FST, 13.0% top-1 recallCIFG recurrent network, 16.4% top-1 recall
Count-based and neural language models side by side

This lecture is about count-based models only, which is why slide 9 sets them in bold. That is not nostalgia. Around the turn of the century the standard baseline was modified interpolated Kneser-Ney, available in public toolkits such as SRILM and KenLM, and it is still what you compare against when you need a cheap, inspectable model or a strong prior for a small device.

Recall

State two reasons Bengio et al. and SLP3 give for neural LMs beating n-grams.

n-gram parameters grow exponentially with order (10^50 − 1 for 10 words with |V| = 100,000), and n-grams cannot generalize across similar but non-identical words. Neural LMs use continuous word representations.

Quick check

What is the main reason count-based n-gram models generalize worse than neural language models?

Recap

If you remember nothing else

  • A language model assigns a probability to every possible next word given the history: a distribution, not a single guess.
  • Walden Pond: blue or clear are likely continuations, refrigerator is not. A good LM encodes that intuition numerically.
  • LLMs are pretrained with (variants of) next-token prediction, and in practice LMs run over tokens such as BPE pieces, not raw words.
  • In applications, another component proposes candidates and the LM ranks them by fluency, as in Pr(S) Pr(T|S) for MT.
  • Real-word errors like 'Their are' and acoustic ties like 'back soonish' against 'bassoon dish' are solved by context probability, not by a dictionary.
  • Autocomplete, keyboards (3 Gboard suggestions, 5-gram baseline with 1.25 million n-grams) and AAC menus are top-k predictions from P(next | prefix).
  • Two views, one model: P(w_t | w_<t) and P(w_1:T), linked by the chain rule. </s> makes sentence probabilities a proper distribution.
  • Bag translation: a trigram LM alone restored the exact word order of 63% of short sentences.
  • Count-based LMs estimate from exact n-gram counts. Neural LMs use continuous word representations to generalize to unseen but similar sequences.
  • This lecture covers count-based models. Training and test sets, perplexity, sampling and interpolation carry over to neural LMs; count smoothing does not.

Sources

Part 02: N-grams, the chain rule and the Markov assumption

What an n-gram is, why full histories cannot be counted, how the chain rule decomposes sentence probability, and how the Markov assumption truncates the history to the last n minus 1 words.

6 concepts, slides 10-16

Why this part matters

Every language model, from a 1913 vowel counter to a modern transformer, is a next-token predictor that the chain rule turns into a sentence scorer. This part builds that bridge. The Markov assumption is the first and simplest answer to the question every model has to settle, namely how much history to keep; transformers answer the same question with a context window. Perplexity (Part 04), sampling (Part 05) and smoothing (Parts 06 to 09) are all built on the algebra here, and exams routinely ask you to expand a sentence with these formulas by hand.

By the end you can

  1. Define an n-gram and list the bigrams and trigrams of a phrase.
  2. Explain why P(w | h) cannot be estimated by counting full histories.
  3. Write the chain rule for any sentence and state that it is exact.
  4. Apply the Markov assumption for a given N, with correct padding using <s> and </s>.
  5. Justify the end symbol as what makes the model a single probability distribution.
  6. Compare unigram, bigram and trigram models on context, fluency and sparsity.

N-grams: sliding windows over text

Take the phrase the water of Walden Pond and lay a frame two words wide over its start. Inside the frame you read the water. Slide it one word to the right and you read water of, then of Walden, then Walden Pond. Widen the frame to three words and the same sweep gives the water of, water of Walden and of Walden Pond. Those are the bigrams and trigrams of the phrase.

A width-2 frame and then a width-3 frame sweep the phrase. Five tokens give four bigrams and three trigrams.

The general rule: an n-gram is a contiguous run of n tokens, read in order. A Unigram is a single token. A sequence of L tokens contains exactly L - n + 1 n-grams of order n, because the frame has that many starting positions. For our five-token phrase that is 5, 4 and 3.

OrderCount (L - n + 1)N-grams
1 (unigram)5the · water · of · Walden · Pond
2 (bigram)4the water · water of · of Walden · Walden Pond
3 (trigram)3the water of · water of Walden · of Walden Pond
Every n-gram of the water of Walden Pond, by order

The word carries a second meaning that you must keep apart from the first. "N-gram" also names the probabilistic model that predicts a word from the previous n - 1 words, so a "bigram model" is built from bigram counts and predicts each word from one word of context. Jurafsky and Martin call this "a bit of terminological ambiguity" and use the same Walden Pond examples as the slide [SLP3, ch. 3]. Context nearly always disambiguates: "count the trigrams" means the sequences, "train a trigram" means the model.

The units need not be words. In current systems the frame often slides over BPE subword tokens from Lecture 02, and nothing in this part changes when it does; only the vocabulary does. To see what n-gram counting looks like at web scale, here are the n-gram counts Google released from about a trillion tokens of English web text, after dropping the rare ones.

Google Web 1T 5-gram corpus, Version 1 (LDC2006T13): n-grams seen at least 40 times, words seen at least 200 times

Tokens
1,024,908,267,229
Sentences
95,119,665,584
Unigrams (count ≥ 200)
13,588,391
Bigrams (count ≥ 40)
314,843,401
Trigrams (count ≥ 40)
977,069,902
Fourgrams (count ≥ 40)
1,313,818,354
Fivegrams (count ≥ 40)
1,176,470,663

Distinct bigrams, trigrams and fourgrams climb steeply even after rare n-grams are dropped. The fivegram row dips only because every n-gram seen fewer than 40 times was discarded, and the long tail is where most fivegrams live. Longer windows produce more distinct patterns, each seen fewer times. That is Sparsity, and it will drive the rest of this part.

Recall

List the trigrams of its water is so transparent, and say how many there are.

its water is, water is so, is so transparent: 5 - 3 + 1 = 3 trigrams.

Why full histories cannot be counted

Suppose you want the probability that the next word is blue given the history The water of Walden Pond is so beautifully. The most direct estimate is a relative frequency: of all the times this eight-word history appeared in a corpus, in what fraction was it followed by blue?

P(blue∣The water of Walden Pond is so beautifully)=C(The water of Walden Pond is so beautifully blue)C(The water of Walden Pond is so beautifully)\begin{aligned} &P(\text{blue} \mid \text{The water of Walden Pond is so beautifully}) \\ &\quad = \frac{C(\text{The water of Walden Pond is so beautifully blue})}{C(\text{The water of Walden Pond is so beautifully})} \end{aligned}
Counting a full history directly (SLP3 Eq. 3.2)

The formula is correct. The trouble is the denominator. How many times does that exact eight-word history occur, even on the whole web? Probably zero, and if it occurs at all, a handful of times, which is far too few to estimate a probability. Jurafsky and Martin put it plainly: "even the entire web isn't big enough", because language is creative and "new sentences are invented all the time" [SLP3, ch. 3]. Most sentences you will read today have never been written before.

The arithmetic of histories

A short calculation shows that no amount of data closes the gap. With a vocabulary of V = 10,000 words, the number of possible histories of length k is V^k. A corpus of a trillion tokens contains at most about 10^12 history occurrences, one per position.

History length kPossible histories V^kCoverage by 10^12 tokens
110^4Every history is seen often in a large corpus
210^8Most frequent pairs are seen; many are not
410^16Far more than any corpus has tokens
810^32At most a 10^-20 fraction can ever appear
Possible histories at V = 10^4 against what a trillion-token corpus can cover (derived)

At k = 8 there are 10^32 possible histories, so even if every position in the corpus held a different history, at most a 10^-20 fraction of them could be seen once. The model needs many observations of each history, and it gets zero for nearly all of them. This is Sparsity in its most extreme form.

Recall

Why can't we estimate P(blue | The water of Walden Pond is so beautifully) by counting?

Language is creative, so a long history almost never recurs and its count is zero or tiny. There are V^k possible histories of length k, which no corpus can cover.

The chain rule: an exact factorization

Before cutting the history short, look at what probability theory gives for free. The probability of the sentence its water is so transparent can be written as a product of five next-word probabilities:

P(its) P(water∣its)×P(is∣its water)×P(so∣its water is)×P(transparent∣its water is so)\begin{aligned} &P(\text{its})\,P(\text{water} \mid \text{its}) \\ &\quad \times P(\text{is} \mid \text{its water}) \\ &\quad \times P(\text{so} \mid \text{its water is}) \\ &\quad \times P(\text{transparent} \mid \text{its water is so}) \end{aligned}
Five words, five factors

Each factor predicts one word given all the words before it. Five words, five factors, and the product is exactly the joint probability. This is the chain rule of probability, which follows from applying the definition P(A, B) = P(A) P(B | A) repeatedly. In general:

P(w1:n)=∏k=1nP(wk∣w1:k−1)P(w_{1:n}) = \prod_{k=1}^{n} P(w_k \mid w_{1:k-1})
The chain rule (SLP3 Eq. 3.3 and 3.4)
Each link adds one factor, and the history arc behind it grows by one word. The fifth factor already conditions on four words.

What the chain rule buys is a change of question. "How probable is this sentence?" becomes "how probable is each next word, given what came before?", asked once per position. That is why a next-word predictor and a sentence scorer are the same object: give me one and I can build the other. Every language model you will meet, n-gram or neural, rests on this identity.

What it does not buy is any relief from the counting problem. Look at the last factor: P(transparent | its water is so) still conditions on the whole preceding history, and for a long sentence the late factors carry exactly the long histories that the previous concept showed we cannot count. As SLP3 admits, "using the chain rule doesn't really seem to help us!" It restates the problem in a usable shape; the next concept solves it.

Worked example

Expanding its water is so transparent

  1. k = 1

    P(its), history of 0 words.
  2. k = 2

    P(water | its), history of 1 word.
  3. k = 3

    P(is | its water), history of 2 words.
  4. k = 4

    P(so | its water is), history of 3 words.
  5. k = 5

    P(transparent | its water is so), history of 4 words.
  6. Result

    The k-th factor conditions on k - 1 words. The product equals P(its water is so transparent) exactly, with no approximation.

Recall

Write the chain rule for P(w_{1:4}) and say whether it is exact.

P(w1) P(w2 | w1) P(w3 | w1:2) P(w4 | w1:3). It is exact: an identity of probability theory, not a modelling assumption.

Here is the move that makes language modelling learnable. Instead of P(blue | The water of Walden Pond is so beautifully), use P(blue | beautifully). Instead of asking about an eight-word history nobody has ever written, ask how often blue follows beautifully, which a modest corpus can answer. A Trigram model keeps one more word and uses P(blue | so beautifully).

This is the Markov assumption: the next word depends only on the last few words, not on the whole history. Written generally, with N the order of the n-gram model:

P(wn∣w1:n−1)≈P(wn∣wn−N+1:n−1)P(w_n \mid w_{1:n-1}) \approx P(w_n \mid w_{n-N+1:n-1})
The Markov assumption for an N-gram model (SLP3 Eq. 3.8)

Read the subscripts carefully, because two letters share a name. Lowercase n is the position of the word being predicted. Uppercase N is the order of the model. The window w_(n-N+1) ... w_(n-1) contains exactly N - 1 words. For N = 2 it is P(w_n | w_(n-1)), the Bigram model; for N = 3 it is P(w_n | w_(n-2), w_(n-1)).

Window for each order, predicting blue in The water of Walden Pond is so beautifully blue

N = 2 (bigram)
Index range w_{n-1:n-1}, so the context is w_(n-1) alone. For the example: P(blue | beautifully). Context words: N - 1 = 1.
N = 3 (trigram)
Index range w_{n-2:n-1}, so the context is w_(n-2), w_(n-1). For the example: P(blue | so beautifully). Context words: N - 1 = 2.
Full history
Index range w_{1:n-1}, the exact chain-rule factor. For the example: P(blue | The water of Walden Pond is so beautifully). Context words: n - 1 = 8.
The full history fades into a forgotten tail. Only the last N-1 = 2 words light up as the window that predicts blue.

What the truncation trades

Cutting the history is a deliberate trade of long-range context for learnability. With a short window, each context recurs often enough to count. With a longer window, the model sees more of the sentence but each context is rarer, so the counts become sparse (Sparsity) and unreliable. The order N is the dial between the two, and the last concept of this part looks at where to set it.

In probability terms, an N-gram model is a Markov chain of order N - 1: the state that determines the next step is the last N - 1 tokens. Shannon described English text this way in 1948 as a "discrete Markoff process" [Shannon 1948].

Where the name comes from

In 1913 Andrei Markov took the first 20,000 letters of Pushkin's Eugene Onegin and classified each as a vowel or a consonant: 8,638 vowels and 11,362 consonants. If letters were independent, about 3,731 vowel-vowel pairs would be expected. He counted 1,104. The previous letter clearly mattered [Hayes 2013; Markov 1913, trans. 2006].

Worked example

Markov's vowel bigram

  1. Base rate

    P(vowel) = 8,638 / 20,000 ≈ 0.43.
  2. Conditional rate

    P(vowel | vowel) ≈ 1,104 / 8,638 ≈ 0.128.
  3. Result

    After a vowel, another vowel is less than a third as likely as its base rate. A two-symbol bigram model captures this; a unigram model cannot. That count is the first bigram language model.

Recall

In P(w_n | w_{n-N+1:n-1}), what are n and N, and how many context words are there?

n is the position of the predicted word, N is the model order, and there are N - 1 context words.

Apply the Markov assumption to every factor of the chain rule and a whole sentence becomes a product of short, countable pieces. Under a Bigram model, with the boundary symbols added:

P(⟨s⟩ its water is so transparent ⟨/s⟩)≈P(its∣⟨s⟩) P(water∣its)×P(is∣water) P(so∣is)×P(transparent∣so)×P(⟨/s⟩∣transparent)\begin{aligned} &P(\langle s\rangle\ \text{its water is so transparent}\ \langle /s\rangle) \\ &\quad \approx P(\text{its} \mid \langle s\rangle)\,P(\text{water} \mid \text{its}) \\ &\quad\quad \times P(\text{is} \mid \text{water})\,P(\text{so} \mid \text{is}) \\ &\quad\quad \times P(\text{transparent} \mid \text{so}) \\ &\quad\quad \times P(\langle /s\rangle \mid \text{transparent}) \end{aligned}
Six factors for five words

Two new sentence boundary tokens appear. <s> gives the first word something to condition on, so P(its | <s>) measures how likely its is to open a sentence. </s> is predicted after the last word, so P(</s> | transparent) measures how likely the sentence is to stop there. The general bigram formula is:

P(w1:n)≈∏k=1nP(wk∣wk−1)P(w_{1:n}) \approx \prod_{k=1}^{n} P(w_k \mid w_{k-1})
Bigram sentence probability (SLP3 Eq. 3.9)
Each word predicts the next. The last arrow, into </s>, is the model predicting that the sentence stops.

A Trigram model needs two words of context for the first real word, so it pads with two start symbols, as in P(I | <s><s>) [SLP3 3.1.3]. For our sentence: P(its | <s><s>) P(water | <s> its) P(is | its water) P(so | water is) P(transparent | is so) P(</s> | so transparent). Still one end symbol: stopping is predicted once.

Why the end symbol is not optional

It is tempting to treat </s> as tidy formatting. It is not. Without it, the model never has to spend probability on stopping, and the sentence probabilities stop adding up. SLP3's footnote states the consequence: without the end symbol, "the sentence probabilities for all sentences of a given length would sum to one", so the model defines "an infinite set of probability distributions, with one distribution per sentence length" (Exercise 3.5). A tiny vocabulary makes this concrete.

Worked example

A two-word language, with and without </s>

  1. Without </s>

    Vocabulary {a, b}, uniform bigram: P(a | ·) = P(b | ·) = 0.5. The 2 sentences of length 1 sum to 1. The 4 of length 2 each have 0.25 and also sum to 1. Every length sums to 1, so the total over all sentences is infinite. That is not a probability distribution.
  2. With </s>

    Now P(a | ·) = P(b | ·) = P(</s> | ·) = 1/3. A sentence of length L needs L word factors and one stop factor, so it has probability (1/3)^(L+1), and there are 2^L such sentences. Length 0 counts too: the empty sentence <s></s> has probability 1/3.
  3. Sum over all lengths

    ∑L≥02L(13)L+1=13⋅11−2/3=1\sum_{L \ge 0} 2^L \left(\tfrac{1}{3}\right)^{L+1} = \tfrac{1}{3} \cdot \frac{1}{1 - 2/3} = 1
  4. Sums to 1

    With </s> the model is a single distribution over sentences of every length. Long sentences pay for each extra "keep talking" decision.

Recall

Write the trigram approximation of P(its water is so transparent) with boundary tokens.

P(its | <s><s>) P(water | <s> its) P(is | its water) P(so | water is) P(transparent | is so) P(</s> | so transparent).

Recall

What goes wrong without </s>?

Probabilities sum to 1 within each sentence length, so the total over all sentences is infinite. You get one distribution per length instead of a single distribution.

Quick check

Why does a bigram model need the end symbol </s>?

Quick check

Under a trigram model, which context scores 'Pond' in 'the water of Walden Pond'?

In 1948 Claude Shannon generated text by sampling words from English statistics. Drawing each word independently by its frequency gave "REPRESENTING AND SPEEDILY IS AN GOOD APT OR COME CAN DIFFERENT NATURAL HERE HE THE A IN CAME THE TO OF TO EXPERT GRAY COME TO FURNISHES THE LINE MESSAGE HAD BE THESE." Drawing each word given the previous one gave "THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER THAT THE CHARACTER OF THIS POINT IS THEREFORE ANOTHER METHOD FOR THE LETTERS THAT ..." [Shannon 1948]. One word of context, and local syntax already appears.

The first sample is a Unigram model, P(w), with no context at all. It knows which words are common and nothing about order, a bag of words: it gives dog bites man and man bites dog exactly the same probability. The second is a Bigram model, and a Trigram model with two words of context reads more fluently still.

OrderContext wordsFactorPossible contexts at V = 10^4What it capturesGenerated sample
Unigram0P(w_k)1Word frequency only; order ignored (bag of words)REPRESENTING AND SPEEDILY IS AN GOOD APT OR COME CAN DIFFERENT NATURAL ...
Bigram1P(w_k | w_(k-1))10^4Local syntax between neighboursTHE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER THAT THE CHARACTER ...
Trigram2P(w_k | w_(k-2), w_(k-1))10^8Short phrases read fluentlyFly, and will rid me these news of price. Therefore the sadness of parting, as they say, 'tis done.
Model order against context, parameters and output (V = 10^4; unigram and bigram samples from Shannon 1948, trigram sample from SLP3 Fig. 3.4)

The price of context

Each extra word of context multiplies the number of possible contexts by V. At V = 10^4 the possible n-grams number 10^4, 10^8 and 10^12 for unigrams, bigrams and trigrams. Real corpora fill only a sliver of these tables. Shakespeare's works have N = 884,647 tokens and V = 29,066 types, giving V^2 ≈ 844 million possible bigrams and V^4 ≈ 7 × 10^17 possible 4-grams. With so few observed 4-grams per context, a 4-gram model trained on Shakespeare starts copying him verbatim, which Part 06 dissects. Even at web scale, Web 1T kept 314.8 million bigrams seen at least 40 times against about 1.85 × 10^14 possible over its 13.59 million unigram types, roughly a 1.7 × 10^-6 fraction (derived, a lower bound).

This is the same Sparsity that defeated full histories, now as a dial rather than a wall. A larger N captures more context but leaves most contexts unseen, giving zero counts and Overfitting to the training text. In practice SLP3 notes that "when there is sufficient training data we use trigram models ... or 4-gram or 5-gram models". At the modern extreme, infini-gram sidesteps the fixed dial altogether: it uses suffix arrays over about 5 trillion tokens to back off to the longest matching context of any length, with millisecond latency and about 47% next-token accuracy [Liu et al. 2024].

Quick check

Which statement about the chain rule and the Markov assumption is correct?

Quick check

Under a unigram model without boundary tokens, how do 'dog bites man' and 'man bites dog' compare?

Recap

If you remember nothing else

  • An n-gram is n adjacent tokens. "n-gram" also names the model that predicts a word from the previous n-1.
  • Counting P(w | h) directly fails because the number of histories grows as V^k and language is creative.
  • Chain rule: P(w_{1:n}) = ∏ P(w_k | w_{1:k-1}). It is exact and reduces sentence probability to next-word prediction.
  • Markov assumption: P(w_n | w_{1:n-1}) ≈ P(w_n | w_{n-N+1:n-1}), where N is the order and N-1 is the window.
  • Bigram LM: P(w_{1:n}) ≈ ∏ P(w_k | w_{k-1}), with w_0 = <s> and a final P(</s> | w_n). A trigram pads with <s><s>.
  • </s> turns one distribution per sentence length into a single distribution over all sentences.
  • Unigram is a bag of words, bigram gives local syntax, trigram gives more fluency. Possible contexts grow as V^(N-1), so a larger N means sparser counts.
  • Markov's 1913 Onegin count (20,000 letters, 1,104 vowel pairs against about 3,731 expected) was the first bigram model.

Sources

Part 03: Estimating n-gram probabilities with maximum likelihood

Relative-frequency (MLE) estimation for bigrams and general n-grams, worked on the I am Sam toy corpus and the Berkeley Restaurant Project tables, plus why we compute in log space and when longer n-grams pay off.

5 concepts, slides 17-28

Why this part matters

Part 02 reduced a sentence probability to a product of short conditional probabilities. This part answers the question that leaves open: where do the numbers come from? The answer is the simplest estimator in statistics, counting and dividing, and every later idea in the lecture (perplexity, sampling, smoothing, Kneser-Ney, stupid backoff) is built on these relative frequencies.

It is also the most reliably examined skill in the chapter. You will be handed a tiny corpus or a count table and asked for a bigram probability and a sentence probability, and the marks are lost on two details: which count goes in the denominator, and whether the <s> and </s> factors were included. Real toolkits such as KenLM then store everything as base 10 logarithms, which is the last idea here.

By the end you can

  1. Compute bigram and general n-gram MLE estimates by hand from a padded corpus.
  2. Explain why dividing by the history count normalizes each conditional distribution.
  3. Read count and probability tables like the BeRP tables and convert between them.
  4. Compute a sentence probability with <s> and </s>, in both linear and log space.
  5. Explain underflow and the tradeoffs of trigram to 5-gram models with their start padding.

Suppose the word "Chinese" occurs 400 times in a corpus of one million words. What probability should a unigram model give it? The obvious answer is 400 / 1,000,000 = 0.0004, and that obvious answer has a name: it is the maximum likelihood estimate. Among every possible value you could pick, 0.0004 is the one that makes the observed data, 400 occurrences in a million draws, most probable. SLP3 is careful about what this does and does not mean: it is not a claim that the "true" probability of Chinese in all English is 0.0004. It is the best fit to this one training set.

Stated generally, maximum likelihood chooses the parameters of a model M that maximize P(T | M), the probability of the training set T. For a language model made of n-gram probabilities, the maximizing parameters turn out to be relative frequencies: count how often something happened and normalize, meaning divide by a total so the results lie between 0 and 1 and sum to 1.

From counts to a conditional probability

A Bigram model needs P(w_n | w_(n-1)): given the previous word, how likely is each next word? The relative frequency is the count of the pair divided by the total count of all pairs that start with the same previous word. That is SLP3 equation 3.10:

P(wn∣wn−1)=C(wn−1 wn)∑wC(wn−1 w)P(w_n \mid w_{n-1}) = \frac{C(w_{n-1}\, w_n)}{\sum_{w} C(w_{n-1}\, w)}
Equation 3.10: normalize by every bigram that starts with the same history word.

The denominator looks awkward, but it collapses. Walk through the corpus and look at every occurrence of the word w_(n-1). Each occurrence is immediately followed by exactly one word, so it starts exactly one bigram. Summing the bigram counts over all possible followers therefore just counts the occurrences of w_(n-1) itself. The only occurrence that could break this is a word at the very end of a sentence, which has no follower, and closing every sentence with </s> fixes this too: the last real word is followed by the end token, so it too starts a bigram. The result is equation 3.11:

P(wn∣wn−1)=C(wn−1 wn)C(wn−1)P(w_n \mid w_{n-1}) = \frac{C(w_{n-1}\, w_n)}{C(w_{n-1})}
Equation 3.11: the bigram MLE. Numerator, the pair. Denominator, the history word alone.
The row after I: am was seen twice and do once. Divided by C(I) = 3, the two bars become one bar of length 1 split at 2/3.

It helps to see what the wrong denominator would give. If you divided C(w_(n-1) w_n) by the total number of bigrams N in the corpus, you would get the joint probability P(w_(n-1), w_n): how often this particular pair occurs among all pairs. That is a perfectly good number, but it answers a different question. All the joint values together sum to 1, while what theChain rule of probability needs is a distribution over next words for a fixed history.

Recall

Why must the denominator be C(w_(n-1)) and not the total number of bigrams?

The sum over all w of C(w_(n-1) w) equals C(w_(n-1)), so dividing by it makes each conditional distribution sum to 1. Dividing by the total bigram count gives a joint probability P(w_(n-1), w_n), not a conditional one.

Quick check

Why does the bigram MLE divide by C(w_(n-1))?

Doing MLE by hand on I am Sam, then for any N

The best way to make equation 3.11 automatic is to run it once by hand on a corpus small enough to hold in your head. SLP3 uses three sentences from Dr. Seuss, each wrapped in sentence boundary tokens:

<s> I am Sam </s>
<s> Sam I am </s>
<s> I do not like green eggs and ham </s>
The padded I am Sam corpus (slide 19).

Worked example

Bigram MLE on I am Sam

  1. Count every history word

    Count each word as it appears in the history position, that is, every token except </s>. <s> occurs 3 times (once per sentence), I occurs 3 times, am 2, Sam 2, and every other word once.
  2. Count the bigrams that start with each history

    After <s>: I twice, Sam once. After I: am twice, do once. After am: Sam once, </s> once. After Sam: </s> once, I once. Check: each history's followers add up to its own count, 2 + 1 = 3 and 1 + 1 = 2.
  3. Divide each pair by its history count

    P(I | <s>) = 2/3 = 0.67, P(Sam | <s>) = 1/3 = 0.33, P(am | I) = 2/3 = 0.67, P(do | I) = 1/3 = 0.33, P(</s> | Sam) = 1/2 = 0.5, P(Sam | am) = 1/2 = 0.5.
  4. Score a whole sentence

    P(<s> I am Sam </s>) = P(I | <s>) x P(am | I) x P(Sam | am) x P(</s> | Sam) = 2/3 x 2/3 x 1/2 x 1/2.
  5. Result

    P(<s> I am Sam </s>) = 1/9, about 0.111. Four factors for three words, because the end token is predicted too.
HistoryC(history)Bigrams that start with itMLE estimates
<s>3<s> I: 2, <s> Sam: 1P(I | <s>) = 2/3, P(Sam | <s>) = 1/3
I3I am: 2, I do: 1P(am | I) = 2/3, P(do | I) = 1/3
am2am Sam: 1, am </s>: 1P(Sam | am) = 1/2, P(</s> | am) = 1/2
Sam2Sam </s>: 1, Sam I: 1P(</s> | Sam) = 1/2, P(I | Sam) = 1/2
do, not, like, green, eggs, and, ham1 eachExactly one continuation each, ending with ham </s>Each is 1/1 = 1
The I am Sam counts as a tally: one row per history word

Now try it on your own data. The builder below pads every line, fills the count matrix and the MLE matrix, and scores any sentence as a product and as a sum of natural logs. Load the I am Sam preset and check the numbers above, then type a sentence containing a Bigram the corpus never saw and watch the product collapse to zero.

InteractiveBigram count-table builder
Counts C(row word, column word)
C(row)IamSam</s>donotlikegreeneggsandham
<s>320100000000
I302001000000
am200110000000
Sam210010000000
do100000100000
not100000010000
like100000001000
green100000000100
eggs100000000010
and100000000001
ham100010000000
MLE P(column | row) = count / C(row)
rowIamSam</s>donotlikegreeneggsandham
<s>2/301/300000000
I02/3001/3000000
am001/21/20000000
Sam1/2001/20000000
do000001/100000
not0000001/10000
like00000001/1000
green000000001/100
eggs0000000001/10
and00000000001/1
ham0001/10000000
  1. P(I | <s>) = 2/3
  2. P(am | I) = 2/3
  3. P(Sam | am) = 1/2
  4. P(</s> | Sam) = 1/2
Sentences3in corpus
P(sentence)0.111product
ln P-2.197sum of logs

Sentence probability 0.111, log probability -2.197

Highlighted cells are the bigrams the sentence uses. A teal factor is an unseen bigram: MLE gives it zero, the whole product collapses to zero, and its log is minus infinity.

From bigrams to any N

Nothing in the recipe depends on the history being one word. For an n-gram model, the Markov assumption keeps the last N - 1 words as the history, and the estimate is the count of the full n-gram divided by the count of its prefix (equation 3.12):

P(wn∣wn−N+1:n−1)=C(wn−N+1:n−1  wn)C(wn−N+1:n−1)\begin{aligned} &P(w_n \mid w_{n-N+1:n-1}) \\ &\quad = \frac{C(w_{n-N+1:n-1}\; w_n)}{C(w_{n-N+1:n-1})} \end{aligned}
Equation 3.12: numerator, the whole N-word sequence. Denominator, its first N - 1 words.

For a Trigram, P(Sam | I am) is C(I am Sam) / C(I am). In the toy corpus that is 1/2: "I am" occurs twice, followed once by Sam and once by </s>. The price of the longer history is Sparsity. With a vocabulary of V words there are V^(N-1) possible histories, and each needs enough occurrences for its row of fractions to mean anything. The rows get thinner fast.

Recall

From the I am Sam corpus, compute P(do | I) and P(Sam | am), and say what each denominator counts.

1/3 and 1/2. The denominators count the history word: C(I) = 3 and C(am) = 2.

Quick check

In the I am Sam corpus, what is the trigram MLE estimate of P(do | <s> I)?

In the Berkeley Restaurant Project corpus, the word i occurs 2533 times and the pair "i want" occurs 827 times. So the maximum likelihood estimate is P(want | i) = 827 / 2533 = 0.33: a third of the time a user of this system says i, the next word is want. That single division is all there is to reading a real Bigram table.

BeRP was a spoken question-answering system from the 1990s that answered questions about a database of restaurants in Berkeley, California. Its transcripts are exactly the sort of text an assistant hears: can you tell me about any good cantonese restaurants close by, i'm looking for a good place to eat breakfast. SLP3 uses 9332 sentences with a vocabulary of V = 1446 and shows an 8 by 8 slice of the bigram table for eight hand-picked words.

History (row)iwanttoeatchinesefoodlunchspend
i (2533)5827090002
want (927)2060816651
to (2417)204686206211
eat (746)0020162420
chinese (158)100008210
food (1093)1501501400
lunch (341)20000100
spend (278)10100000
BeRP bigram counts: row word followed by column word. The unigram count of each row word is in brackets (SLP3 figure 3.1)

Read the table as row then column: the row is the history and the column is the next word. The 827 in row i, column want means want followed i 827 times. To turn counts into probabilities, divide every cell in a row by that row word's unigram count. Row i is divided by 2533, row want by 927, row to by 2417, and so on:

EstimateBigram countRow word countProbability
P(want | i)82725330.33
P(to | want)6089270.66
P(eat | to)68624170.28
P(food | chinese)821580.52
P(lunch | eat)427460.056
P(spend | to)21124170.087
P(i | want)29270.0022
Count over unigram count gives the bigram probability
History (row)iwanttoeatchinesefoodlunchspend
i0.0020.3300.00360000.00079
want0.002200.660.00110.00650.00650.00540.0011
to0.0008300.00170.280.0008300.00250.087
eat000.002700.0210.00270.0560
chinese0.006300000.520.00630
food0.01400.01400.000920.003700
lunch0.005900000.002900
spend0.003600.003600000
BeRP bigram probabilities P(column | row), each count divided by its row word's unigram count (SLP3 figure 3.2)
All 64 cells rest dim; on activation only the bigrams BeRP actually saw light up, brightest for i to want, want to to, to to eat and chinese to food. Half the block stays dark.

Now look at the zeros. These eight words were chosen because they cohere, they are the words of "i want to eat chinese food" plus two neighbors, and still 32 of the 64 cells are zero. The full table has 1446 x 1446, about 2.09 million, cells, filled from only 9332sentences, so the overwhelming majority of the full table must be zero. That is Sparsity seen directly, and some of those zeros (chinese to and lunch to are both zero, yet "chinese to go" is ordinary English, while a zero for i lunch reflects grammar) are accidents of a small sample rather than facts about English.

Recall

Using the BeRP tables, compute P(want | i) and P(food | chinese).

827 / 2533 = 0.33 and 82 / 158 = 0.52.

Recall

Why does row i of the count table not sum to 2533?

Only 8 of the 1446 possible next words are shown, and </s> is missing, so the row is a partial view of the full row, which does sum to C(i).

With a table in hand, scoring a sentence is mechanical. The Chain rule of probability writes the sentence probability as a product of next-word probabilities, and the Markov assumption cuts each history down to one word. For "i want english food", with the boundary tokens included, that is five factors:

P(⟨s⟩ i want english food ⟨/s⟩)=P(i∣⟨s⟩) P(want∣i)×P(english∣want)×P(food∣english)×P(⟨/s⟩∣food)\begin{aligned} &P(\langle s\rangle\ \text{i want english food}\ \langle/s\rangle) \\ &\quad = P(\text{i} \mid \langle s\rangle)\, P(\text{want} \mid \text{i}) \\ &\quad\quad \times P(\text{english} \mid \text{want}) \\ &\quad\quad \times P(\text{food} \mid \text{english}) \\ &\quad\quad \times P(\langle/s\rangle \mid \text{food}) \end{aligned}

Worked example

Scoring i want english food with BeRP bigrams

  1. Collect the five factors

    P(i | <s>) = 0.25, P(want | i) = 0.33 (from the table), P(english | want) = 0.0011, P(food | english) = 0.5, P(</s> | food) = 0.68.
  2. Multiply left to right

    0.25 x 0.33 = 0.0825, then x 0.0011 = 0.0000908, then x 0.5 = 0.0000454, then x 0.68 = 0.0000309.
  3. Result

    P(<s> i want english food </s>) = 3.0855 x 10^-5, about 0.000031, the value SLP3 reports.
Each link's thickness is its bigram probability. want to english is a hairline at 0.0011, and the running product below drops by three orders of magnitude at that one link.

Four of the five factors lie between 0.25 and 0.68. The fifth, 0.0011, is what makes the sentence improbable: the running product falls from 0.0825 to about 0.00009 at that single step. A sentence probability is dominated by its rarest transition.

What the numbers know

The table was built by counting, yet it already encodes several kinds of knowledge. Some is syntactic: after to, the high-probability words are verbs (P(eat | to) = 0.28), and after eat SLP3 notes that what follows is usually a noun or an adjective (lunch, chinese). Some is about the task: sentences tend to start with i, and "i want" is how people talk to an assistant. Some is cultural: the corpus makes Chinese food much more probable than English food, compare P(english | want) = 0.0011 with P(chinese | want) = 0.0065.

Quick check

A five-word sentence is scored with a bigram model using both boundary tokens. How many factors are multiplied?

Scaling up: log probabilities and longer n-grams

Multiply 400 probabilities of 0.1 in Python and the answer is exactly 0.0. The true value, 10^-400, is far below the smallest positive normalized double, 2.2 x 10^-308, and even below the smallest subnormal, about 5 x 10^-324, so the hardware rounds it to zero. Four hundred tokens is a paragraph, not a book. Yet the logarithm of the same product is simply 400 x ln 0.1 = -921.03, an unremarkable number.

This failure is called numerical underflow, and SLP3 gives it as the reason language models always work with log probabilities: probabilities are at most 1, so the more of them you multiply, the smaller the product gets. The identity that saves us is that the log of a product is the sum of the logs (equation 3.13):

p1×p2×p3×p4=exp⁡(log⁡p1+log⁡p2+log⁡p3+log⁡p4)\begin{aligned} &p_1 \times p_2 \times p_3 \times p_4 \\ &\quad = \exp(\log p_1 + \log p_2 \\ &\qquad + \log p_3 + \log p_4) \end{aligned}
Equation 3.13: add log probabilities while computing, and take exp only when you need to report a probability.

Worked example

The BeRP sentence in log space

  1. Take the natural log of each factor

    ln 0.25 = -1.386, ln 0.33 = -1.109, ln 0.0011 = -6.812, ln 0.5 = -0.693, ln 0.68 = -0.386.
  2. Add them

    -1.386 - 1.109 - 6.812 - 0.693 - 0.386 = -10.386. The rare bigram is still visible: it contributes two thirds of the total.
  3. Convert back only at the end

    exp(-10.386) = 3.09 x 10^-5, the same 0.000031 as before.
  4. Result

    ln P = -10.386. In base 10 the same sum is -4.511 and in base 2 it is -14.984; all three describe the same probability.
Top: on a linear 0 to 1 axis the product slides into 0 and becomes invisible. Bottom: on a natural log axis each factor is a visible step left, and the steps add to -10.386.
import math, sys

print(0.1 ** 400)
print(400 * math.log(0.1))
print(sys.float_info.min, math.ulp(0.0))

factors = [0.25, 0.33, 0.0011, 0.5, 0.68]
log_p = sum(math.log(p) for p in factors)
print(log_p, math.exp(log_p))
Underflow and its log-space fix, runnable as is.

The script prints 0.0, then -921.034..., then 2.2250738585072014e-308 and 5e-324, then -10.386 and 3.0855e-05. Note that math.log is the natural log unless you pass a base.

Longer context

With enough data, a bigram history is too short. Production systems use Trigram, 4-gram and 5-gram models, and the recipe is equation 3.12 again. The first words of a sentence need a full-length history, so a model of order N prepends N - 1 start tokens. For a trigram that is two, and the first word is scored as P(I | <s> <s>).

NContext wordsStart paddingFluencyPossible histories V^(N-1)Parameters V^N
2 (bigram)1<s>Local, often choppy1446about 2.09 x 10^6
3 (trigram)2<s> <s>Clearly better phrasesabout 2.09 x 10^6about 3.02 x 10^9
4 (4-gram)3<s> <s> <s>Very fluent where seenabout 3.02 x 10^9about 4.37 x 10^12
5 (5-gram)4<s> x 4Copies training text on small dataabout 4.37 x 10^12about 6.32 x 10^15
What each extra word of context costs, with V = 1446 as in BeRP

The tradeoff is direct. Each extra word of context makes predictions more specific and the generated text more fluent, but multiplies the number of possible histories by V, so each history is seen less often and the table fills with zeros. On a small corpus a high-order MLE model has almost one continuation per history and simply copies training sentences, the Overfitting that Part 06 shows with Shakespeare samples.

At web scale the balance shifts. Google's Web 1T 5-gram corpus counted n-grams over about one trillion tokens, with 13,588,391 unigram types and 1,176,470,663 distinct five-grams. Brants and colleagues in 2007 trained on two trillion tokens, about 300 billion n-grams, with the stupid backoff scheme you will meet in Part 07. Infini-gram (2024) drops the fixed N entirely: it indexes five trillion tokens with suffix arrays and computes counts for an n-gram of any length at query time. Toolkits like KenLM make large models fit in memory by storing log10 probabilities, quantizing them to 4 to 8 bits, hashing words to 64-bit integers, storing n-grams in reverse tries, and pruning rare n-grams.

Recall

Compute ln P(<s> i want english food </s>) from the five factors and convert it back.

-1.386 - 1.109 - 6.812 - 0.693 - 0.386 = -10.386, and exp(-10.386) is about 3.1 x 10^-5.

Recall

How many start symbols does a trigram model need, and why?

Two. The first word needs a two-word history, so it is scored as P(w_1 | <s> <s>), and the second word as P(w_2 | <s> w_1).

Quick check

In float64, what does multiplying 400 probabilities of 0.1 give?

Quick check

How many <s> pseudo-words does a 4-gram model prepend?

Recap

If you remember nothing else

  • MLE is count then normalize: P(w_n | w_{n-1}) = C(w_{n-1} w_n) / C(w_{n-1}). It maximizes the likelihood of the training data, not the true probability.
  • The sum over w of C(w_{n-1} w) equals C(w_{n-1}), so each conditional row sums to 1. Dividing by the total number of bigrams would give a joint probability instead.
  • I am Sam gives P(I | <s>) = 2/3, P(Sam | <s>) = 1/3, P(am | I) = 2/3, P(do | I) = 1/3 and P(</s> | Sam) = 1/2, and P(<s> I am Sam </s>) = 1/9.
  • The general n-gram MLE divides the count of the full n-gram by the count of its (N-1)-word prefix. The number of possible histories is V^(N-1), so sparsity grows quickly with N.
  • BeRP has 9332 sentences and V = 1446. P(want | i) = 827/2533 = 0.33, and even among 8 hand-picked coherent words half the cells are zero.
  • P(<s> i want english food </s>) = 0.25 x 0.33 x 0.0011 x 0.5 x 0.68, about 0.000031. One rare bigram dominates the result.
  • Bigram statistics encode local syntax, task habits and cultural facts, all from one corpus and domain.
  • Store and add log probabilities: p1 ... pk = exp(sum of log pi). SLP3 uses ln, KenLM and ARPA files use log10, and perplexity work often uses log2. The base never changes a ranking.
  • Trigrams pad with <s> <s>. Longer n-grams are more fluent but sparser and larger, and on small corpora they copy the training data.

Sources

Part 04: Evaluating language models with perplexity

Extrinsic versus intrinsic evaluation, train, dev and test splits and contamination, and perplexity as the length-normalized inverse probability, read as a weighted branching factor.

5 concepts, slides 29-41

Why this part matters

Every language model paper you will read, from KenLM n-gram models to GPT-scale transformers, reports perplexity. On the exam you will be asked to compute it by hand and to explain why test data must stay unseen. In research, knowing when a perplexity comparison is invalid (leaked test data, a different vocabulary or tokenizer, a different boundary convention) is what separates a real gain from an artifact. In real systems, perplexity is the cheap signal you iterate on before paying for an end-to-end word error rate or BLEU run.

The part moves in five steps. First, what "better" even means for a language model and the two ways to measure it. Then the discipline of held-out data that makes any measurement honest. Then the definition of perplexity, derived from the probability of a test set, followed by the conventions you need to compute and compare it fairly. It ends with the most useful intuition for the number: an effective count of choices.

By the end you can

  1. Distinguish extrinsic from intrinsic evaluation and say when each is worth its cost.
  2. Explain the roles of training, dev and test sets, and how data contamination makes perplexity misleadingly low.
  3. Define perplexity as P(W)^(-1/N), expand it with the chain rule, and write the unigram and bigram forms.
  4. Compute perplexity by hand, in probability space and in log space, for a short sequence.
  5. State the conditions for a fair perplexity comparison: same test set, vocabulary, tokenization and boundary convention.
  6. Interpret perplexity as a weighted average branching factor, using the 3-color example.

Suppose you have two speech recognizers that are identical in every way except their Language model. The most convincing way to decide which LM is better is to run both systems on the same real audio and count how many words each gets wrong. Whichever has the lower word error rate has the better LM, for this task, on this data.

That is Extrinsic evaluation: you embed the model in an application and measure the application. SLP3 calls it "the only way to know if a particular improvement in the language model ... is really going to help the task at hand". Its weakness is cost. Every candidate model needs a full end-to-end run, and if you are trying twenty smoothing settings in an afternoon, twenty ASR decodes is not an option. Intrinsic evaluation trades realism for speed: it scores the model by itself, independent of any application. The standard intrinsic metric, for n-gram models and for neural LLMs alike, is Perplexity, which this part builds up step by step.

Extrinsic evaluationIntrinsic evaluation
What is measuredThe whole application with this LM plugged inThe LM alone, on held-out text
Typical metricWord error rate for ASR, BLEU or COMET for MTPerplexity
Cost per candidate modelA full end-to-end run of the systemOne pass of the LM over the test set
RealismThe only proof that the task improvedA proxy that usually, not always, tracks the task
When to use itBefore you claim a gain, and for final decisionsWhile iterating on many model variants
Extrinsic versus intrinsic evaluation of a language model

What "better" means: the Shannon game

To score a model by itself we need a definition of good that does not mention any application. The Shannon game supplies one. Cover the next word and ask the model to bet on it: "I always order pizza with cheese and ___". A good model spreads its bets over sensible continuations, say 0.1 on mushrooms, 0.1 on pepperoni, 0.01 on anchovies, a sliver on fried rice, and essentially nothing (10^-100 on the slide) on the word "and". Shannon ran the original version of this experiment in 1951 with letters rather than words, asking people to guess the next character of English text to estimate how predictable the language is. Contexts differ in how open they are: after "The 33rd President of the US was" almost all the probability belongs to one name, while after "I saw a" thousands of nouns are reasonable. The last concept of this part turns that difference into a number.

A Unigram model plays this game badly. It ignores the context entirely, so after "cheese and" it bets the same way it bets everywhere, heavily on frequent words like "the". The rule that falls out is simple: a better model is one that assigns a higher probability to the word that actually occurs. A perfect model would give each real next word probability 1. Applied to a whole held-out text, the better model gives the test text a higher probability, and perplexity is just a length-normalized way of reporting that probability.

Recall

You have twenty smoothing settings to try for a speech recognizer. Which evaluation do you use while iterating, which before claiming a gain, and why?

Intrinsic evaluation (perplexity on held-out text) while iterating, because it needs only one LM pass per variant. Extrinsic evaluation (word error rate of the full recognizer) before claiming a gain, because it is the only proof the task improved and perplexity gains do not always transfer.

You build a Bigram model and, by accident, five of your test sentences are also in the training corpus. Every bigram in those sentences now has a nonzero count, so the model assigns them a much higher probability than it would to genuinely new text, and the Perplexity drops. The model has not improved at all. It has simply seen the answers.

SLP3 names this precisely: if a test sentence is part of the training corpus, "we will mistakenly assign it an artificially high probability", a situation called training on the test set, or Data contamination, and it "causes huge inaccuracies in perplexity". The cure is to split the data into three disjoint parts with different jobs: a Training set, a Development set and a Test set.

Train, dev and test as three disjoint blocks. When test text leaks into training, the perplexity needle swings to a value that is too good to be true.

The three splits and how often you may look at each

Training set
Supplies the n-gram counts, so it decides every probability in the model. Look at it as often as you like.
Development set (devset)
Held out from training and used to tune hyperparameters such as an interpolation weight λ or the k of add-k smoothing. Look at it after every change; that is its job.
Test set
Held out from both, drawn from the target domain, large enough for a statistically significant comparison. Run it once, or a very few times, at the end.

The devset exists because models have knobs. Interpolation weights, the k of add-k smoothing and the discount in Kneser-Ney are all hyperparameters: they are not learned from counts, so they must be chosen by trying values and keeping the best. If you choose them by checking the test set, the test set has become part of training by another route. SLP3's rule is to do all testing on the devset "until the very end" and to run the test set "once, or a very few number of times".

Two further requirements make the test set meaningful. It should be drawn from the domain you care about: if the model will transcribe chemistry lectures or hotel booking requests, the test text should be chemistry lectures or booking requests, and the devset should look like the test set. And it should be large enough to give the statistical power to show a significant difference between two candidate models. A ten-sentence test set can make any two models look different by luck.

Quick check

For two weeks you pick interpolation weights by checking test-set perplexity after each change. What is the main problem?

The obvious intrinsic score is the probability the model assigns to the test set. It has one fatal flaw. The same Bigram model might give a 5-token sentence a probability around 10^-5 and a 50-token paragraph around 10^-50. Every extra token multiplies in another factor below 1, so raw probability mostly measures length, and two test sets of different sizes cannot be compared.

The running product of next-word probabilities for <s> i want english food </s> plunges on a log axis, while the per-token geometric mean (teal) stays near the top. Normalizing by length is what makes a comparable score.

Perplexity fixes this by taking the Nth root, which turns the product of N factors into a per-token average, and by inverting it so that the number grows as the model gets more surprised. For a test set W = w_1 ... w_N:

PP(W)=P(w1w2…wN)−1N=1P(w1w2…wN)N\begin{aligned} \mathrm{PP}(W) &= P(w_1 w_2 \ldots w_N)^{-\frac{1}{N}} \\ &= \sqrt[N]{\frac{1}{P(w_1 w_2 \ldots w_N)}} \end{aligned}
Perplexity: the inverse probability of the test set, normalized by the number of tokens (SLP3 Eq. 3.14)

Expanding the joint probability with the Chain rule of probability turns it into a product of next-word probabilities, so perplexity is the geometric mean of the inverse next-word probabilities:

PP(W)=∏i=1N1P(wi∣w1…wi−1)N\mathrm{PP}(W) = \sqrt[N]{\prod_{i=1}^{N} \frac{1}{P(w_i \mid w_1 \ldots w_{i-1})}}
Chain-rule form (SLP3 Eq. 3.15)

A specific model only changes what goes in the denominator. A Unigram model uses P(w_i); a bigram model, under the Markov assumption, uses P(w_i | w_(i-1)).

ModelEach factor inside the rootPerplexity
Unigram1 / P(w_i)PP(W) = (Π 1 / P(w_i))^(1/N)
Bigram1 / P(w_i | w_(i-1))PP(W) = (Π 1 / P(w_i | w_(i-1)))^(1/N)
Any model1 / P(w_i | w_1 ... w_(i-1))PP(W) = P(w_1 ... w_N)^(-1/N)
Perplexity for the unigram and bigram models (SLP3 Eq. 3.16 and 3.17)

Because the exponent is negative, lower perplexity means higher test probability. For a fixed test set N is fixed, and P^(-1/N) is strictly decreasing in P, so minimizing perplexity is exactly the same as maximizing the probability of the test set. The inversion is not arbitrary: it comes from the original definition of perplexity as two raised to a cross-entropy rate, which Part 10 develops.

A worked example with the Berkeley bigrams

Worked example

Perplexity of <s> i want english food </s>

  1. Multiply bigram probabilities

    Using the Berkeley Restaurant Project corpus estimates from SLP3: P(i | <s>) = 0.25, P(want | i) = 0.33, P(english | want) = 0.0011, P(food | english) = 0.5, P(</s> | food) = 0.68. The product is 0.25 × 0.33 × 0.0011 × 0.5 × 0.68 = 0.0000309 (SLP3 rounds it to 0.000031).
  2. Count N

    Five tokens were predicted: i, want, english, food and the end marker. The start marker is given, never predicted, so N = 5.
  3. Take the Nth root of the inverse

    PP = 0.0000309^(-1/5). In logs: log2 0.0000309 ≈ -14.98 bits, divided by 5 gives ≈ 3.00 bits per token, and 2^3.00 ≈ 7.98.
  4. Result

    PP ≈ 7.98. Per token, the model was about as uncertain as a fair choice among roughly 8 words, even though one factor (0.0011) was very small.

Compute it in log space

On a real test set of a million tokens the product underflows any floating-point type, so in practice you sum log probabilities instead, average them, and exponentiate once at the end:

PP(W)=2−1N∑i=1Nlog⁡2P(wi∣w1…wi−1)\mathrm{PP}(W) = 2^{-\frac{1}{N}\sum_{i=1}^{N} \log_2 P(w_i \mid w_1 \ldots w_{i-1})}
The same quantity, computed as two to the average number of bits of surprise per token

The exponent is the average number of bits the model needs per token, which is the bridge to cross-entropy in Part 10. The base does not matter as long as it matches: Hugging Face defines perplexity as "the exponentiated average negative log-likelihood of a sequence", using natural logs and exp, which gives the same number. The same documentation notes that perplexity is not well defined for masked models such as BERT, because they do not assign a left-to-right probability to the sequence.

Recall

Why is minimizing perplexity the same as maximizing test-set probability?

For a fixed test set, N is fixed and PP = P^(-1/N) is strictly decreasing in P. Any change that raises the test probability lowers the perplexity, and vice versa.

Recall

SLP3 exercise 3.12: training has 91 zeros and one each of the digits 1 to 9. The test set is 0 0 0 0 0 3 0 0 0 0. What is the unigram perplexity?

P(0) = 91/100 = 0.91 and P(3) = 0.01. With N = 10, PP = (0.91^9 × 0.01)^(-1/10) ≈ 1.73. The test set is mostly zeros, which the model predicts well, so the effective number of choices is far below 10.

Quick check

Why does perplexity take the Nth root of the inverse test-set probability?

Computing and comparing perplexity honestly

SLP3 trained Unigram, Bigram and Trigram models on 38 million words of Wall Street Journal text and measured Perplexity on a 1.5 million word test set. The results were 962, 170 and 109.

ModelPrevious words usedTest perplexity
Unigram0962
Bigram1170
Trigram2109
WSJ test perplexity by model order (SLP3 section 3.3)
Each extra word of context (teal chips) shortens the perplexity bar, drawn on a log scale: 962, then 170, then 109. The second word of context helps less than the first.

More context gives the model more information about the next word, so it is less surprised and its perplexity falls. Notice the diminishing return: the first word of context cuts perplexity by a factor of more than five, the second by about a third. The catch is data. A trigram model needs reliable counts for three-word sequences, and Sparsity grows fast with the order, so the gain holds only when the training set is large enough to estimate the longer n-grams. With too little data a higher order can be worse, which is the subject of Part 06.

Conventions that change the number

A real test corpus is many sentences, not one, so the model is run over the whole stream and the probability runs across sentence boundaries. If you use Sentence boundary tokens, they enter the count. SLP3 includes one token per sentence in N: the end marker </s>, but not the start marker <s>. The reason is that </s> is a genuine prediction (the model must decide where the sentence ends), while the step from </s> to the next <s> happens with probability almost 1, so counting it would add an almost-free token and flatter the score.

The deeper rule is that perplexity is a property of a model, a test set and a vocabulary together. SLP3 states that the perplexity of two language models "is only comparable if they use identical vocabularies". A model with a 10k-word vocabulary maps every rarer word to a single unknown token and then predicts that token easily, so its perplexity is lower on a task that is genuinely easier. In modern subword models the same applies to tokenization: Hugging Face warns that "the tokenization procedure has a direct impact on a model's perplexity". Even the evaluation procedure matters. GPT-2 large on WikiText-2 scores 19.44 with non-overlapping 1024-token windows and 16.44 with a sliding window of stride 512, because each token gets more context.

Perplexity is not the task

Lower perplexity often correlates with better downstream performance, which is why everyone uses it, but SLP3 is explicit that an intrinsic improvement "does not guarantee an (extrinsic) improvement". When the decision matters, confirm with the task metric: Extrinsic evaluation with word error rate for speech, BLEU or COMET for translation.

Recall

When using <s> and </s>, which one do you count in N, and why?

Count </s> but not <s>. </s> is a real prediction, the decision of where the sentence ends. <s> is never predicted: the transition from </s> to the next <s> has probability near 1, so counting it would distort perplexity (SLP3 footnote 2).

Recall

What do the WSJ results 962, 170 and 109 say, and what is the catch?

More context means the model is less surprised: a smaller effective branching factor. The catch is that higher orders need enough training data to estimate their counts reliably, otherwise sparsity erases the gain.

Recall

Give two reasons why a reported perplexity can be misleadingly low.

Test data leaked into training (contamination), or the model was tuned repeatedly on the test set. Also acceptable: a smaller vocabulary, a different tokenization or a more generous evaluation window, any of which makes the number not comparable with others.

Quick check

Team A reports perplexity 85 with a 10k-word vocabulary. Team B reports 120 with a 50k-word vocabulary on the same text. What follows?

Perplexity as a weighted branching factor

Take a toy language with three words, red, blue and green, where any word can follow any word. At every position there are three possible next words, so its Weighted branching factor is 3. Model A knows nothing and gives each word probability 1/3. On any test set of five words, PP_A = ((1/3)^5)^(-1/5) = 3. A uniform model's perplexity is exactly the number of choices.

Now Model B has learned that red is common: P(red) = 0.8, P(blue) = P(green) = 0.1. On the textbook Test set "red red red red blue", the probability is 0.8^4 × 0.1 = 0.04096 and PP_B = 0.04096^(-1/5) ≈ 1.89. Three words are still possible at every step, but the model is effectively choosing among fewer than two.

Three branches with equal weight at rest. Model B thickens red to 0.8 and thins blue and green to 0.1, and the effective number of branches shrinks from 3 to about 1.89 on the test set red red red red blue.

This is the intuition SLP3 offers: perplexity is the weighted average branching factor. The plain branching factor counts the possible next words. Perplexity weights them by how much probability the model puts on the words that actually occur, and reports the size of a uniform choice that would leave you equally uncertain. So the WSJ Trigram's 109 means that, on average, the model was as unsure as if it were picking uniformly from about 109 words at each step, out of a vocabulary of tens of thousands.

Worked example

One language, two models, two test sets

  1. Uniform model A

    Every factor is 1/3, so P(T) = (1/3)^5 and PP = 3 on any test set.
  2. Skewed model B on the textbook test set

    P(T) = 0.8^4 × 0.1 = 0.04096. In bits, log2 0.04096 ≈ -4.61, which is 0.922 bits per token, and 2^0.922 ≈ 1.89.
  3. Same model B on an all-blue test set

    P(T) = 0.1^5, so PP = (0.1^5)^(-1/5) = 10.
  4. Result

    3, 1.89 and 10. Skew helps only when it points at the words that actually occur; pointed the wrong way, it makes the model worse than knowing nothing.
ModelTest setP(T)Perplexity
A: uniform, 1/3 eachany 5 words(1/3)^5 ≈ 0.00413
B: red 0.8, blue 0.1, green 0.1red red red red blue0.8^4 × 0.1 = 0.04096≈ 1.89
B: red 0.8, blue 0.1, green 0.1blue blue blue blue blue0.1^5 = 0.0000110
The 3-color language under two models and two test sets

Recall

A uniform model over a vocabulary of V words is tested on any text. What is its perplexity?

Exactly V, since PP = ((1/V)^N)^(-1/N) = V. This is the plain branching factor, with no weighting.

Quick check

Model B has P(red) = 0.8 and P(blue) = P(green) = 0.1. What is its perplexity on the test set blue blue blue blue blue?

Recap

If you remember nothing else

  • Extrinsic evaluation (WER, BLEU/COMET inside a task) is the real test but costs a full run. Intrinsic evaluation with perplexity is cheap and fast for iterating.
  • Training counts, the devset tunes hyperparameters, the test set is touched once. Leaking or repeatedly tuning on test data makes perplexity look too good.
  • PP(W) = P(w_1...w_N)^(-1/N): the geometric mean of inverse next-word probabilities. Lower is better, and minimizing PP is maximizing test probability.
  • Compute it in log space: PP = 2^(-(1/N) Σ log2 P). A single zero probability makes PP infinite.
  • With boundary tokens, count </s> in N but not <s>, and keep the convention fixed across models.
  • WSJ, 38M training words, 1.5M test words: unigram 962, bigram 170, trigram 109. More context helps when there is enough data.
  • Perplexities are comparable only with identical vocabularies and tokenization. Lower PP usually, but not always, means better task performance.
  • Perplexity is a weighted branching factor: uniform over 3 colors gives 3. P(red) = 0.8 on red red red red blue gives about 1.89. The same model on all blue gives 10.

Sources

Part 05: Sampling sentences from a language model

How to generate text from a unigram or n-gram model by placing words on the unit interval and drawing random numbers, walked through step by step on a deep learning example.

5 concepts, slides 42-53

Why this part matters

Sampling is how every generative language model turns probabilities into text. Shannon did it by hand in 1948 with a stack of books, n-gram models do it with a table of counts, and a modern LLM does it with a softmax over a hundred thousand tokens. The loop is the same in all three: look at the context, get a distribution over the next word, draw one, slide the window, repeat.

For an n-gram model, sampling is also the fastest way to see what the model actually learned. A table of a billion probabilities tells you nothing at a glance; ten sampled sentences tell you how far its fluency reaches, whether it is parroting its training data, and what genre it was trained on. Expect exam questions that hand you a number line and a random number, or a walkthrough and ask what the model conditions on. The same mechanics reappear in your research the moment you call a text generation API and set its temperature or top-p.

By the end you can

  1. Explain why sampling reveals what a language model has learned.
  2. Sample a unigram word from cumulative intervals given a random number.
  3. Run the n-gram sampling loop from <s> to </s> and compute the sampled path probability.
  4. Contrast random sampling with greedy decoding and explain why greedy text is repetitive.
  5. Track the sliding context window and identify the slide walkthrough as trigram, not bigram.

In 1948 Claude Shannon wanted to show what a statistical model of English "knows", so he generated text from one. His first-order word approximation picks each word independently, with its real frequency:

REPRESENTING AND SPEEDILY IS AN GOOD APT OR COME CAN DIFFERENT NATURAL HERE HE THE A IN CAME THE TO OF TO EXPERT GRAY COME TO FURNISHES THE LINE MESSAGE HAD BE THESE.

His second-order approximation picks each word given the one before it, using word-transition probabilities:

THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER THAT THE CHARACTER OF THIS POINT IS THEREFORE ANOTHER METHOD FOR THE LETTERS THAT THE TIME OF WHO EVER TOLD THE PROBLEM FOR AN UNEXPECTED.

The jump is obvious. The first is a bag of English words; the second has runs like "ATTACK ON AN ENGLISH WRITER" that read as real phrases. Shannon observed that such samples "have reasonably good structure out to about twice the range that is taken into account in their construction". Nobody had to inspect a single probability to see the difference. Jurafsky and Martin make this the official motivation: "One important way to visualize what kind of knowledge a language model embodies is to sample from it", crediting the idea to Shannon and to Miller and Selfridge (1950).

The rule behind it is simple. A Language model is a probability distribution over sentences. Sampling draws sentences from that distribution, so a sentence the model gives probability 0.001 shows up ten times as often as one it gives 0.0001. The sentences you see are therefore a portrait of where the model puts its mass. Train N-gram models of increasing order on Shakespeare and sample from each:

OrderSample (Shakespeare)What it shows
UnigramTo him swallowed confess hear both. Which. Of save on trail for are ay device and rote life haveReal Shakespearean words, no order between them at all
BigramWhy dost stand forth thy canopy, forsooth; he is this palpable hit the King Henry. Live king. Follow.Each adjacent pair is plausible; the sentence goes nowhere
TrigramFly, and will rid me these news of price. Therefore the sadness of parting, as they say, 'tis done.Phrases hold together over three or four words
4-gramKing Henry. What! I will go seek the traitor Gloucester. Exeunt some of the watch. A great banquet serv'd in; / It cannot be but so.Fluent, because it is largely copied: "It cannot be but so" is a line from King John
Sentences sampled from n-gram models trained on Shakespeare (SLP3, Fig 3.4); a slash separates two samples
Four rows of word blocks, unigram at the top. As the visual comes alive, longer runs of blocks lock into line on the lower rows: coherence reaches further as n grows, and the 4-gram row is one long copied run.

Reading samples like these gives you three diagnostics at once.

  • Local coherence grows with n. The window of words that make sense together is about twice the model order, as Shannon noted.
  • Verbatim fragments are a warning. A line you can find word for word in the training text, like the 4-gram's "It cannot be but so", means the model is replaying its corpus. Fluent output here is Overfitting, not understanding; Part 06 shows the sparse counts that cause it.
  • Samples reveal the genre. The same procedure on 40 million words of Wall Street Journal text produces talk of percentages, dollars and interest rates instead. That is Genre dependence made visible, and Part 06 draws the lesson for choosing training data.

Recall

Name the three things that ten sampled sentences reveal about an n-gram model.

How far its local coherence reaches (about twice the model order), whether it is copying its training text verbatim (overfitting), and which genre it was trained on. None of them is a score: perplexity is the metric.

Unigram sampling on the unit interval

Start with the simplest model, a Unigram model computed from the text of the SLP3 book. Lay its words end to end along a ruler from 0 to 1, giving each word a strip exactly as wide as its probability. "the" has probability 0.06, so it owns [0, 0.06). "of" has 0.03 and owns [0.06, 0.09). Then "a" owns [0.09, 0.11), "to" owns [0.11, 0.13), and "in" owns [0.13, 0.15). Far along the line, "however" (p = 0.0003) sits near 0.66, and "polyphonic" (p = 0.0000018) is a hairline near 0.99.

Now draw a random number. If u = 0.10, it lands in [0.09, 0.11), so the model emits "a". If u = 0.07, it lands in [0.06, 0.09) and the model emits "of". That is the whole algorithm. Because u is uniform, the chance it lands in a strip equals the strip's width, and the width is P(w). Every word is drawn with exactly its model probability.

Strips for the, of, a, to and in, then a long compressed gap to the hairlines for however and polyphonic (the head is magnified, not to scale). Darts fall uniformly and the wide strips light up first.

The general rule: inverse-CDF sampling

Put the vocabulary in any fixed order w_1, w_2, …, w_V and compute the running totals F(w_k), the cumulative distribution. Draw u from the uniform distribution on [0, 1), and return the first word whose running total exceeds u. Statisticians call this the inversion or inverse-CDF method: you are reading the cumulative distribution backwards, from a height on the vertical axis to the word underneath it.

w=wk such that F(wk−1)≤u<F(wk),F(wk)=∑j≤kP(wj), u∼U[0,1)\begin{gathered} w = w_k \text{ such that } \\ F(w_{k-1}) \le u < F(w_k), \\ F(w_k)=\sum_{j\le k} P(w_j),\ u\sim\mathcal{U}[0,1) \end{gathered}
Inverse-CDF sampling over a discrete vocabulary

Worked example

Two draws on the slide 44 line

  1. Build the cumulative sums

    The relative frequencies 0.06, 0.03, 0.02, 0.02, 0.02 give running totals 0.06, 0.09, 0.11, 0.13, 0.15. These are the tick marks on the slide.
  2. Draw u = 0.10

    0.09 ≤ 0.10 < 0.11, so u falls in the interval of "a". Emit "a".
  3. Draw u = 0.07

    0.06 ≤ 0.07 < 0.09, so u falls in the interval of "of". Emit "of".
  4. Result

    Over many draws, "a" is emitted with chance 0.11 − 0.09 = 0.02 and "of" with chance 0.09 − 0.06 = 0.03: the widths of their intervals, which are their probabilities.

A unigram model has no context, so to produce a sentence you simply repeat the draw. When do you stop? SLP3 generates "until we randomly generate the sentence-final token" </s>. That only works if </s> is itself a word on the line, which is one more reason the Sentence boundary tokens are part of the vocabulary. It also fixes the length distribution. If P(</s>) = p, every draw ends the sentence with chance p, so sentence length (counting </s>) is geometric with mean 1 / p. With p = 0.05, sentences average 20 tokens.

In code, this is exactly what Python's random.choices does: it turns weights into cumulative weights ("[10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]") and binary searches them with bisect. The five-word toy below renormalizes over just those five words by scaling u by the total.

import bisect, itertools, random

words = ["the", "of", "a", "to", "in"]
probs = [0.06, 0.03, 0.02, 0.02, 0.02]
cumulative = list(itertools.accumulate(probs))
u = random.random() * cumulative[-1]
word = words[bisect.bisect_right(cumulative, u)]
Inverse-CDF sampling with a binary search over cumulative sums

Recall

Describe unigram sampling in three steps.

Lay the words on [0, 1) with interval widths equal to P(w). Draw u uniformly and emit the word whose interval contains u. Repeat until </s> is drawn.

Recall

On slide 44, why is 'however' drawn near 0.66 if its probability is 0.0003?

0.66 is the cumulative position on the line where its interval sits, roughly the total probability of the words before it. Its width, which is its probability, is 0.0003.

Recall

If a unigram model gives </s> probability 0.05, what is the average sampled sentence length?

Length is geometric with mean 1 / 0.05 = 20 tokens, counting </s>.

Quick check

On the slide 44 line, the occupies [0, 0.06), of [0.06, 0.09), a [0.09, 0.11) and to [0.11, 0.13). The draw is u = 0.125. Which word is emitted?

Stanford's CS224N trains a Trigram model on about 1.7 million words of Reuters news and starts generating from "today the ___". The model's top candidates are "company" (0.153), "bank" (0.153) and "price" (0.077). It samples "price", a lower-ranked word, and the window moves to "the price ___", where "of" has probability 0.308. Keep going and you get:

today the price of gold per ton , while production of shoe lasts and shoe industry , the bank intervened …

CS224N's verdict is "Surprisingly grammatical! …but incoherent." Every three-word window is plausible newswire; the sentence as a whole is about nothing.

The loop

The unigram number line had a single, fixed line. A Bigram or trigram model has one line per context, and the loop chooses which line to throw at.

  1. Start from <s>. A bigram needs one start symbol; a trigram pads with two, so the first context is <s> <s>.
  2. Draw w_1 from P(w | <s>) using the number-line method on that conditional distribution. SLP3 describes it as "first generating a random bigram that starts with <s>", then choosing "a random bigram starting with w".
  3. In general draw w_i from P(w_i | w_(i−N+1) … w_(i−1)): the Markov assumption decides how many previous words select the line.
  4. Stop when </s> is drawn. Without </s> there is no stopping event, and no proper distribution over sentence lengths.
wi∼P(wi∣wi−N+1:i−1),w−N+2:0=⟨s⟩, stop when wi=⟨/s⟩\begin{gathered} w_i \sim P(w_i \mid w_{i-N+1:i-1}), \\ w_{-N+2:0}=\langle s\rangle,\ \text{stop when } w_i=\langle/s\rangle \end{gathered}
The n-gram sampling loop

Because each draw is made with exactly its conditional probability, the probability of producing a particular sentence is the product of the conditionals you drew along the way. That is the Chain rule of probability under the Markov assumption, run forwards as a generator instead of backwards as a scorer. In practice you would add log probabilities rather than multiply.

P(sampled sentence)=∏iP(wi∣wi−N+1:i−1)\begin{aligned} &P(\text{sampled sentence}) \\ &\quad =\prod_i P(w_i\mid w_{i-N+1:i-1}) \end{aligned}
The sampled sentence's probability is the product of the drawn conditionals

SLP3 chapter 7 writes the same loop for neural language models, under the name random multinomial sampling: i ← 1; w_i ∼ p(w); while w_i != EOS: i ← i + 1; w_i ∼ p(w_i | w_<i). The only change is that an LLM conditions on all of w_<i, not on the last N − 1 words.

Greedy decodingRandom sampling
Choice ruleargmax P(w | context)w ~ P(w | context)
Deterministic?Yes: same context, same word, every runNo: each run draws a fresh u
DiversityOne output per prefixMany outputs, frequent ones more often
Failure modeBland, generic, loops and repetitionOccasional low-probability nonsense from the tail
UseClosed tasks with one right answerOpen-ended generation, and diagnosing what a model learned
Greedy decoding versus random sampling

For an n-gram model the reason greedy text repeats is mechanical. The context is just the last N − 1 words, so there are finitely many contexts, and greedy decoding maps each context to one fixed next word. Greedy output either reaches </s> before any context repeats, or it comes back to a context it has already been in. From then on it must repeat everything it produced from there, forever: it already went through that stretch once without drawing </s>, so it never will. Sampling escapes because each visit draws a fresh u.

Quick check

What role does </s> play when sampling sentences from an n-gram model?

The lecture's walkthrough generates a phrase about machine learning one word at a time. After the context "deep", the model's top continuations are "learning" 0.23, "reinforcement" 0.05, "convolutional" 0.04, "neural" 0.04, "multi" 0.02, "-" 0.02 and "image" 0.01. The listed words add up to 0.41, so 0.59 of the probability sits on words the slide does not show. The draw lands on "learning".

Next, conditioning on "deep learning", the distribution is much flatter: "models" 0.06, "." 0.05, ";" 0.05, "based" 0.05, "," 0.05, "for" 0.04, "methods" 0.04, a listed mass of 0.34. The draw is ",", even though "models" is the single most likely word.

Three operations per step

  1. The context selects one conditional distribution out of the model's table.
  2. That distribution is laid on [0, 1), exactly like the unigram line.
  3. A fresh u is drawn and the word whose interval contains it is emitted.

Worked example

Placing slide 49 on the number line

  1. Lay the listed words out in order from 0

    models [0, 0.06), "." [0.06, 0.11), ";" [0.11, 0.16), based [0.16, 0.21), "," [0.21, 0.26), for [0.26, 0.30), methods [0.30, 0.34).
  2. Give the rest of the vocabulary its share

    Every unlisted word together occupies [0.34, 1), a block of width 0.66.
  3. Draw u = 0.23

    0.21 ≤ 0.23 < 0.26, so the comma is emitted.
  4. Result

    Any u in [0.21, 0.26), a 5% chance, produces ",". Greedy decoding would produce "models" on every run.
One context node fanning out to its seven listed continuations. The thick branch to models is the greedy choice and is identical every time; a thinner branch, the comma, lights up in teal as the sampled draw.

The shape of the two distributions matters as much as the draws. After "deep", one word holds 0.23 and the model is fairly confident. After "deep learning", the top word holds only 0.06: many continuations are plausible, the model is uncertain, and its effective Weighted branching factor is large. That is precisely what Perplexity from Part 04 measures when averaged over a test set. Flat steps are also where samples become diverse.

Recall

What would greedy decoding output after 'deep learning', and why does nobody use it for open-ended text?

"models" (0.06), every time. Greedy is deterministic and tends to produce bland, repetitive text (SLP3 7.6.1, Holtzman et al. 2020).

Quick check

After 'deep learning', the slide samples ',' (0.05) even though 'models' has 0.06. Why?

The output so far is "deep learning ,". To pick the next word, the model strikes "deep" out of its context and conditions on "learning ,". The distribution there is "and" 0.14, "we" 0.07, "which" 0.05, "the" 0.05, "where" 0.03, "a" 0.02, "but" 0.02, listed mass 0.38. The draw is "but", whose interval in listed order is [0.36, 0.38). The output becomes "deep learning , but", and "deep" is still printed at the front.

The probability of this particular path, given the start "deep", is the product of the three drawn conditionals: 0.23 × 0.05 × 0.02 = 0.00023. Three ordinary-looking steps already put the continuation at about one chance in four thousand, which is why sampled texts almost never repeat.

The tokens deep, learning, comma and a blank. The bracket under deep learning fades, deep is struck out, and a new bracket draws itself under learning and the comma before but appears in the blank.

The window is a queue

An order-N model keeps exactly the last N − 1 tokens as its context. After each draw, the new token is pushed onto the back and the oldest is popped off the front: a first-in, first-out queue of fixed length. Two details are easy to get wrong.

  • The popped word leaves the context, not the output. The text keeps growing; only the conditioning window has a fixed length.
  • Punctuation is a token like any other. The comma fills one of the two context slots, which is why the Trigram context after "deep learning ," is "learning ," and not "deep learning".
Output so farBigram contextTrigram context
deepdeep(<s>) deep
deep learninglearningdeep learning
deep learning ,,learning ,
Bigram versus trigram context at each step of the walkthrough

This is the Markov assumption made physical. Once "deep" has scrolled out, nothing it contributed can influence any later draw. The model cannot remember that the sentence is about deep learning three words later, which is exactly why the Reuters sample drifts from gold to shoes to banks: every window is locally fluent, and the sentence is globally incoherent. The same queue mislabelled as a bigram explains the errata in the previous concept: a bigram queue has one slot, and the slides clearly hold two.

The obvious fix is a longer window, and CS224N states the dilemma directly: "We need to consider more than three words at a time if we want to model language well. But increasing n worsens sparsity problem, and increases model size". Longer windows mean more never-seen contexts, the Sparsity problem that leads to the memorized 4-gram Shakespeare. Breaking that trade-off is what a Neural language model does: SLP3 chapter 7 runs the very same loop, sampling each token "conditioned on our previous choices", but with a context of thousands of tokens that is represented rather than counted.

Recall

Using slide 52's listed order starting at 0, which interval belongs to 'but'?

[0.36, 0.38), after and 0.14, we 0.07, which 0.05, the 0.05, where 0.03 and a 0.02.

Recall

What is the probability of the drawn continuation 'learning , but' in the walkthrough?

0.23 × 0.05 × 0.02 = 0.00023.

Recall

After 'deep learning ,' what does a trigram condition on, and what does a bigram condition on?

The trigram conditions on "learning ,". The bigram conditions only on ",".

Quick check

A trigram sampler has produced 'deep learning ,'. What does it condition on for the next draw?

Recap

If you remember nothing else

  • Sampling draws sentences in proportion to their model probability. It is a qualitative window into the model, not an evaluation metric.
  • Unigram sampling lays words on [0, 1) with widths P(w), draws u from U[0, 1), and emits the word whose interval contains u. The order on the line is arbitrary.
  • On slide 44, 0.66 and 0.99 are cumulative positions on the line, not probabilities. The probabilities of however and polyphonic are 0.0003 and 0.0000018.
  • The n-gram loop starts at <s>, draws w_i from P(w_i | previous N - 1 words), and stops when </s> is drawn. The product of the drawn conditionals is the sentence's probability.
  • Sampling is not argmax. After "deep learning" the walkthrough draws "," (0.05) over "models" (0.06), and greedy decoding is deterministic and repetitive.
  • The context is a sliding window. The oldest word leaves the context but stays in the output.
  • The "Bigram example" slides condition on two words from slide 48 onward, so they are trigram sampling.
  • n-gram samples are locally fluent but globally incoherent. Larger n copies the training text (the 4-gram "It cannot be but so" comes from King John).

Sources

Part 06: Generalization, overfitting and add-one smoothing

How higher-order n-grams memorize sparse training data and depend on genre, why unseen n-grams create zero probabilities, and how Laplace and add-k smoothing fix zeros at a cost.

6 concepts, slides 54-67

Why this part matters

The maximum likelihood bigram and trigram models from the previous parts are easy to build and easy to sample from, but they fail in two ways that decide whether an n-gram language model is usable at all. They memorize, or simply mismatch, the text they were trained on. And they give probability zero to perfectly plausible text, which breaks perplexity and any application that multiplies probabilities.

This part diagnoses both failures and then introduces the first cure, smoothing, in its simplest form: Laplace (add-one) smoothing and its softer cousin add-k. Smoothing is the bridge to every serious count-based model in the rest of the lecture, the add-one bigram is a standard exam computation, and the samepseudo-count trick reappears in Naive Bayes text classification and in any research project that estimates probabilities from limited data, Arabic dialect corpora very much included.

By the end you can

  1. Explain why higher-order n-grams become more fluent but copy training text on small corpora.
  2. Argue why training data must match the target genre, domain and dialect.
  3. Distinguish unseen tokens from unseen n-grams and show why one zero makes perplexity undefined.
  4. Explain smoothing as moving a fixed probability budget from seen to unseen events, using the 'denied the' counts.
  5. Compute Laplace unigram probabilities on a toy corpus, then bigram probabilities and reconstituted counts on BeRP numbers.
  6. Explain why add-one over-discounts, and write and tune add-k with a dev set.

Longer context buys fluency, then memorization

Train four models on the complete works of Shakespeare, a unigram, a bigram, a trigram and a 4-gram model, and generate sentences from each by sampling one word at a time. The unigram model produces "To him swallowed confess hear both." Every word is Shakespearean, but no word knows its neighbor. The bigram model produces "What means, sir. I confess she?": each adjacent pair is locally fluent, yet the sentence has no plan. The trigram output starts to sound like a play. And the 4-gram model produces "It cannot be but so.", which is not an imitation of Shakespeare at all. It is a line from King John, copied word for word.

OrderSampleWhat it shows
UnigramTo him swallowed confess hear both. Which. Of save on trail for are ay device and rote life haveReal Shakespearean words, no relation between neighbors
BigramWhat means, sir. I confess she? then all sorts, he is trim, captain.Each adjacent pair is plausible; the sentence as a whole is not
TrigramThis shall forbid it should be branded, if renown made it empty.Reads like Shakespeare for several words at a time
4-gramIt cannot be but so.Copied word for word from King John
Samples from n-gram models trained on Shakespeare (SLP3 Fig. 3.4)

Why does more context first help and then turn into copying? A longer context makes the model fit the training set more closely, because each prediction is conditioned on more of what actually happened. But the count table becomes far sparser at the same time. The Shakespeare corpus has N = 884,647 tokens and a vocabulary of V = 29,066 types. There are V² ≈ 844 million possible bigrams, so even the bigram table is overwhelmingly empty, and there are V⁴ ≈ 7 × 10¹⁷ possible 4-grams against fewer than a million observed positions. This is sparsity at its most extreme: almost every long prefix was seen once or a handful of times.

Once the 4-gram sampler has generated "It cannot be", the corpus offers only six words that ever followed that prefix: but, I, that, thus, this and the period. The conditional distribution has only six nonzero entries, each one a continuation that actually occurs in the plays, so sampling from it does not invent anything. It replays training text. That is overfitting in an n-gram model: the parameters describe the particular sentences in the training data rather than the language they came from.

As the prefix grows from 'It' to 'It cannot be', the fan of observed continuations shrinks to the six words Shakespeare ever wrote next. The teal line is the one the 4-gram model follows to copy 'but so.' from King John.

Recall

Why does the 4-gram Shakespeare model copy 'It cannot be but so' verbatim?

With N ≈ 885K tokens, the prefix "It cannot be" has only six observed continuations, so the conditional distribution is a short list of real continuations and sampling replays training text. The model has overfit through sparsity.

Quick check

A 4-gram model trained on Shakespeare generates 'It cannot be but so.' word for word. What is the best explanation?

A model only knows its own genre

Now train the same kinds of models on about 40 million words of the Wall Street Journal. The trigram model produces "They also point to ninety nine point six billion dollars from two hundred four oh six three percent of the rates of interest stores as Mexico and Brazil on market conditions." This is unmistakably newswire, read aloud with the numbers spelled out. Jurafsky and Martin point out that the Shakespeare and WSJ samples share no generated sentences, and barely even short phrases, although both models were trained on English.

ShakespeareWall Street Journal
Training size884,647 tokensAbout 40 million words
Vocabulary flavorthou, hath, forsooth, captain, King Henrypercent, corporation, billion, fiscal, Mexico
Trigram sampleThis shall forbid it should be branded, if renown made it empty.They also point to ninety nine point six billion dollars from two hundred four oh six three percent of the rates of interest...
Shared materialFunction words and short phrases at mostFunction words and short phrases at most
Two English corpora, two very different models

The lesson is that a language model is not a model of "English". It is a model of its own corpus, with that corpus's vocabulary, topics, register and sentence shapes. This is genre dependence, and it means the training data has to match the text the model will be used on, the test set in evaluation and the real input in deployment. Match it along several axes at once:

  • Genre and domain. An LM that helps translate legal documents needs legal text. A question-answering system needs a corpus of questions, whose word order and opening words differ sharply from declarative prose.
  • Dialect and variety. Tweets in African American English use forms such as finna and den with their own n-gram statistics, and Nigerian Pidgin tweets mix English and local vocabulary in patterns a standard-English model has never counted.
  • Style and time. Formal versus conversational register, and language from different decades, shift the counts just as much.

SLP3 puts it bluntly: statistical models are "pretty useless as predictors if the training sets and the test sets are as different as Shakespeare and the WSJ." For a research project on Arabic this is concrete. A model trained on Modern Standard Arabic news will assign low probability to Gulf or Egyptian dialect text and report a high perplexity, not because the model is weak but because it was built for a different variety.

Two vocabulary clusters, Shakespeare on the left and WSJ on the right. When they drift together they overlap only in a thin sliver of function words such as 'the', 'of' and 'and'.

Recall

Why is a Shakespeare-trained trigram model a poor model of WSJ text, and what should training data match?

An LM encodes the statistics of its own corpus. The two genres share almost no n-grams beyond function words, so WSJ n-grams get zero or tiny counts and perplexity is high. Training data should match the target genre and domain, dialect and style.

Suppose the training data contains the word ruby and the word slippers, but never the phrase ruby slippers. The maximum likelihood bigram estimate is then P(slippers | ruby) = C(ruby slippers) / C(ruby) = 0. A test sentence containing that phrase gets probability exactly zero, however natural it is.

It helps to separate two kinds of novelty. Older word-level systems faced unseen words, which they mapped to a special <UNK> token. Modern LMs work on subword or byte tokens (BPE from Lecture 02), and with byte-level BPE any word can be spelled from known pieces, so the test set can never contain an unseen token, even when it contains unseen words. But that guarantee is about single tokens. The sequences of known tokens are a different matter: most possible bigrams and trigrams never occur in any finite training set. SLP3 calls these zeros, "sequences that don't occur in the training set but do occur in the test set", and they occur all the time.

Zeros cause two separate problems.

  1. They underestimate plausible text. A speech recognizer or translation system that scores "ruby slippers" as impossible will prefer a worse but previously seen alternative.
  2. They destroy evaluation. A test-set probability is a product of conditional probabilities, so a single zero sends the whole product to zero, and perplexity is defined from that product.
PP(W)=P(w1w2…wN)−1N=1P(w1w2…wN)N\begin{aligned} \mathrm{PP}(W) &= P(w_1 w_2 \ldots w_N)^{-\frac{1}{N}} \\ &= \sqrt[N]{\frac{1}{P(w_1 w_2 \ldots w_N)}} \end{aligned}
Perplexity of a test sequence of N tokens

With P(W) = 0 the formula asks for 1/0. In SLP3's words, "we can't compute perplexity at all, since we can't divide by zero." This is the zero-probability problem, a direct consequence of sparsity.

Worked example

One zero in a four-token test sentence

  1. Write the bigram factors

    Test sentence <s> ruby slippers sparkle </s>, so N = 4 predicted tokens. Suppose the MLE gives P(ruby | <s>) = 0.01, P(slippers | ruby) = 0, P(sparkle | slippers) = 0.1 and P(</s> | sparkle) = 0.5.
  2. Multiply

    P(W) = 0.01 × 0 × 0.1 × 0.5 = 0. The three healthy factors are irrelevant.
  3. Try to compute perplexity

    PP(W) = 0^(-1/4) = 1/0, which is undefined. The whole test set inherits this if it contains the sentence.
  4. Replace the zero with a small smoothed value

    If smoothing gives P(slippers | ruby) = 0.001, then P(W) = 0.01 × 0.001 × 0.1 × 0.5 = 5 × 10⁻⁷ and PP(W) = (5 × 10⁻⁷)^(-1/4) ≈ 37.6.
  5. Result

    One unsmoothed zero makes perplexity undefined; any small nonzero value makes it finite and comparable.
Four multiplied bigram probabilities. One tile is 0, so on activation the product bar collapses to nothing and the perplexity readout shows 1/0, undefined.

The standard fix is smoothing, also called discounting: lower the probability of what was seen and give the freed mass to what was not.

Recall

BPE guarantees no unseen tokens. Why do we still need smoothing?

Unseen combinations of known tokens (n-grams) still get MLE probability 0, and one zero makes P(test) = 0 and perplexity undefined.

Quick check

A trigram model assigns probability 0 to one trigram in the test set. What happens to test-set perplexity?

Look at the words that followed denied the in a small corpus: allegations three times, reports twice, claims once and request once, seven observations in all. The MLE gives P(allegations | denied the) = 3/7 and gives exactly zero to attack, man, outcome and offer, although "denied the offer" is an ordinary phrase.

Smoothing changes the counts before normalizing. In this example each seen count gives up half a unit, so the counts become 2.5, 1.5, 0.5 and 0.5, and the two freed units are pooled as "other" and shared among the unseen words. The total is still seven, so the distribution still sums to one, but now 2/7 ≈ 0.29 of the probability mass covers words the corpus never showed after denied the.

WordCount beforeCount after
allegations32.5
reports21.5
claims10.5
request10.5
attack, man, outcome, offer, ...0share of 2 ("other")
Total77
P(w | denied the) before and after smoothing (example modified from Dan Klein)
The 'denied the' counts as bars. On activation a half-unit slice lifts off each seen bar and reappears as short teal stubs on the unseen words; the total height of all bars stays at 7. How the 2 units split among unseen words is illustrative.

That is the whole idea of smoothing: when the statistics are sparse, steal a little probability mass from frequent events and give it to unseen ones, so that plausible unseen sequences such as "ruby slippers" or "denied the offer" get a nonzero probability. Every smoothing method answers two questions differently: how much mass to take from each seen count (the discount), and how to divide it among the unseen events. The rest of this part covers the simplest answer, and later parts cover better ones.

Recall

In the 'denied the' example, what fraction of the mass moves to unseen words, and which later method does this resemble?

Two of seven units, about 0.29, taken by subtracting 0.5 from each seen count. That fixed subtraction resembles absolute discounting.

Take a toy vocabulary of five types with counts a = 4, b = 3, c = 2, d = 1 and e = 0, so N = 10 tokens and V = 5 types. The MLE is the relative frequency: 0.4, 0.3, 0.2, 0.1 and a zero for e. Now pretend every type was seen once more than it was. The counts become 5, 4, 3, 2, 1, the total becomes 15, and the probabilities become 5/15, 4/15, 3/15, 2/15, 1/15. Nothing is zero, and the five values still sum to one.

TypeCountMLELaplace
a44 / 10 = 0.45 / 15 ≈ 0.333
b33 / 10 = 0.34 / 15 ≈ 0.267
c22 / 10 = 0.23 / 15 = 0.2
d11 / 10 = 0.12 / 15 ≈ 0.133
e00 / 10 = 01 / 15 ≈ 0.067
Sum10115 / 15 = 1
Add-one on a toy unigram distribution (N = 10, V = 5)

That is Laplace (add-one) smoothing. The detail that matters is the denominator. Adding one to each of V counts adds V to the total, so the denominator must grow from N to N + V. Forget it and the probabilities sum to more than one.

PLaplace(wi)=ci+1N+VP_{\text{Laplace}}(w_i)=\frac{c_i+1}{N+V}
Add-one unigram estimate

For bigrams the same reasoning applies row by row. Each row of the bigram table is the distribution of words following one prefix w_{n-1}. Add one to every cell of that row, including all the zero cells, and the row total grows by the number of cells, which is V.

PLaplace(wn∣wn−1)=C(wn−1wn)+1∑w(C(wn−1w)+1)=C(wn−1wn)+1C(wn−1)+V\begin{aligned} &P_{\text{Laplace}}(w_n\mid w_{n-1}) \\ &\quad =\frac{C(w_{n-1}w_n)+1}{\sum_w \left(C(w_{n-1}w)+1\right)} \\ &\quad =\frac{C(w_{n-1}w_n)+1}{C(w_{n-1})+V} \end{aligned}
Add-one bigram estimate: one pseudo-count per possible continuation

To see how much smoothing changed the model, it is useful to turn the smoothed probability back into a count on the original scale. Multiplying the smoothed probability by the prefix count gives the reconstituted (or adjusted) count C*, which can be compared directly with the raw count.

C∗(wn−1wn)=[C(wn−1wn)+1] C(wn−1)C(wn−1)+V\begin{aligned} &C^*(w_{n-1}w_n) \\ &\quad =\frac{\left[C(w_{n-1}w_n)+1\right]\,C(w_{n-1})}{C(w_{n-1})+V} \end{aligned}
Reconstituted count after add-one smoothing

Now apply this to the Berkeley Restaurant Project corpus from Part 03: 9332 sentences and V = 1446, with unigram counts i 2533, want 927, to 2417, eat 746, chinese 158, food 1093, lunch 341 and spend 278. The smoothed count table on the slides is simply the raw table plus one in every cell: i want goes from 827 to 828, want to from 608 to 609, chinese food from 82 to 83, and every former zero becomes 1.

Worked example

Add-one bigram probabilities on BeRP

  1. MLE baseline for P(want | i)

    C(i want) / C(i) = 827 / 2533 = 0.3265 ≈ 0.33.
  2. Add one to the numerator and V to the denominator

    P(want | i) = (827 + 1) / (2533 + 1446) = 828 / 3979 = 0.2081 ≈ 0.21, the value on the smoothed probability slide.
  3. Reconstitute the count

    C*(i want) = 828 × 2533 / 3979 ≈ 527.1, matching SLP3 Fig. 3.8. Smoothing took about 300occurrences away from one of the most frequent bigrams in the corpus.
  4. An unseen bigram in the same row

    C(i to) = 0, so P(to | i) = 1 / 3979 ≈ 0.00025. It is small but no longer zero, and every continuation of i that never occurred in training gets the same amount.
  5. Result

    P(want | i) drops from 0.33 to 0.21 and C* is about 527; the mass removed from seen bigrams pays for the 0.00025 each unseen one receives.
BigramCC(prefix)MLEAdd-one PC*
i want82725330.33828 / 3979 ≈ 0.21527
want to6089270.66609 / 2373 ≈ 0.26238
chinese food821580.5283 / 1604 ≈ 0.0528.2
i to (unseen)0253301 / 3979 ≈ 0.000250.64
MLE versus add-one on three BeRP bigrams and one unseen bigram (V = 1446)

Add-one is old. It goes back to Laplace's 1812 law of succession, and was applied to the zero-frequency problem by Jeffreys (1948) after Johnson (1932); Chen and Goodman also credit Lidstone (1920) with the idea of pretending each event occurred once more. SLP3 is clear that Laplace smoothing "does not perform well enough to be used in modern n-gram models", but it is the natural baseline and it works well enough in text classification, where you will meet it again in Naive Bayes.

Recall

Why does the add-one bigram denominator add V rather than 1?

One pseudo-count goes to each of the V possible continuations of w_{n-1}, so the row total grows by V. Adding only 1 would make the row sum exceed 1.

Recall

Compute the add-one P(want | i) given C(i want) = 827, C(i) = 2533, V = 1446, and the reconstituted count.

828 / 3979 ≈ 0.21, down from 0.33. C* = 828 × 2533 / 3979 ≈ 527.

Quick check

With C(i want) = 827, C(i) = 2533 and V = 1446, what is the add-one estimate of P(want | i)?

What add-one costs, and add-k as the softer fix

Compare raw and reconstituted counts. C(want to) falls from 608 to C* ≈ 238, a discount ratio d_c = C*/C = 0.39, and P(to | want) falls from 0.66 to 0.26. C(chinese food) falls from 82 to 8.2, a ratio of d_c = 0.10: the model now believes food follows chinese one time in twenty instead of about half the time. A frequent, highly predictable bigram has been cut by a factor of ten.

BigramCC*d_c = C* / CPseudo-counts in the denominator
want to6082380.391446 / 2373 ≈ 61%
i want8275270.641446 / 3979 ≈ 36%
chinese food828.20.101446 / 1604 ≈ 90%
How hard add-one discounts three BeRP bigrams

The last column explains the pattern. In the chinese row the denominator is 158 + 1446 = 1604, and 1446 of that, about 90%, is pseudo-counts. The invented evidence outweighs the real evidence nine to one. In the i row the pseudo-counts are only 1446 / 3979 ≈ 36%, so the damage is milder. Add-one moves too much mass to unseen events, and it hits rare contexts hardest, because V is fixed while the real count of the prefix is small. In a realistic vocabulary of tens of thousands of types, almost every context is rare in this sense. That is why add-one is a teaching baseline rather than a production language model.

Add-k: a smaller pseudo-count

The obvious repair is to add less. Add-k smoothing adds a fractional k to every count, and therefore kV to the denominator.

PAdd-k(wn∣wn−1)=C(wn−1wn)+kC(wn−1)+kVP_{\text{Add-}k}(w_n\mid w_{n-1})=\frac{C(w_{n-1}w_n)+k}{C(w_{n-1})+kV}
Add-k bigram estimate; k = 1 is Laplace, k → 0 is the MLE

Nothing in the training counts tells you what k should be: 0.5, 0.1, 0.01? It is a hyperparameter, chosen by trying several values and keeping the one with the lowest perplexity on a development set. The table shows the trade-off on the chinese and want rows. Here the pseudo-count share is kV / (C(h) + kV), the part of the denominator made of pseudo-counts. It is not the same as the mass given to unseen words, because some pseudo-counts land on seen words too.

kP(food | chinese)C*(chinese food)Pseudo-count share, chinese rowP(to | want)
10.05178.20.900.2566
0.50.093614.80.820.3688
0.10.271342.90.480.5675
0.010.475575.10.0840.6458
0 (MLE)0.5198200.656
Add-k on BeRP: P(food | chinese) has MLE 0.519 and P(to | want) has MLE 0.656

As k shrinks, the smoothed estimates climb back toward the MLE, and at k = 0 they are the MLE again, zeros included. So k slides between "trust the counts" and "trust the uniform distribution". Try it yourself below.

SimulatorAdd-k on a BeRP bigram row

Upper bar: MLE C(h w) / C(h). Lower bar: add-k (C(h w) + k) / (C(h) + kV) with V = 1446 and C(chinese) = 158. Eight of the 1446 columns are shown.

  • chinese i0.006330.00125
  • chinese want00.000623
  • chinese to00.000623
  • chinese eat00.000623
  • chinese chinese00.000623
  • chinese food0.5190.0517
  • chinese lunch0.006330.00125
  • chinese spend00.000623
P(food | chinese)0.0517MLE 0.519
C* (chinese food)8.2of 82discount d = 0.0997
Pseudo-count share90.1%of rowkV out of 1,604 in the denominator

Even a well-tuned k does not make additive smoothing a good language model. Gale and Church (1994), as summarized in SLP3, found that add-k gives counts with poor variances and often inappropriate discounts, and Chen and Goodman's large comparison concludes flatly that "additive smoothing performs poorly". The flaw is structural: every unseen continuation of a prefix gets the same pseudo-count, whether it is offer or a random rare word, and the same k is used for every context regardless of how much evidence it has. Real systems use interpolation, backoff and Kneser-Ney, which start in Part 07 with absolute discounting.

Recall

How is k chosen in add-k, and what happens as k → 0?

k is a hyperparameter tuned on a dev set by minimizing perplexity. As k → 0 the estimate returns to the MLE, zeros included.

Quick check

Add-one cut C(chinese food) from 82 to 8.2 but C(want to) only from 608 to 238. Why?

Recap

If you remember nothing else

  • Higher n fits the training set better. On Shakespeare (N = 884,647, V = 29,066) the 4-gram copies "It cannot be but so" because only six words ever follow "It cannot be".
  • LMs encode their corpus. Shakespeare and WSJ samples barely overlap, so match genre, domain and dialect.
  • Subword tokenization removes unseen tokens but not unseen n-grams (zeros).
  • One zero makes P(test) = 0 and PP = P^(-1/N) undefined. The fix is smoothing, also called discounting.
  • Smoothing moves mass from seen to unseen events while keeping the total at 1 (denied the: 2 of 7 units go to "other").
  • Laplace: (c+1)/(N+V) for unigrams and (C(w_{n-1}w_n)+1)/(C(w_{n-1})+V) for bigrams. P(want | i) goes from 0.33 to 0.21.
  • C* = (C+1)·C(w_{n-1})/(C(w_{n-1})+V). want to falls from 608 to 238 (d_c = C*/C = 0.39) and chinese food from 82 to 8.2 (d_c = 0.10).
  • Add-k replaces 1 with a small k tuned on a dev set. It is still a poor LM smoother and serves as a baseline.

Sources

Part 07: Interpolation, backoff and absolute discounting

Combining n-gram orders by linear interpolation or backoff, stupid backoff at web scale, tuning on held-out data, and the Church and Gale observation that motivates subtracting a fixed discount of about 0.75.

6 concepts, slides 68-80

Why this part matters

Part 06 left you with a model that assigns probability zero to any n-gram it never saw, and with add-one smoothing as a blunt first repair. Every count-based language model that people actually ship goes further: it combines several n-gram orders and it discounts counts in a measured way. Modified interpolated Kneser-Ney was the standard n-gram baseline from around 2000 and is what KenLM builds today. Stupid backoff powered Google's machine translation language models trained on 2 trillion tokens. And the move of mixing one distribution with another under a tuned weight is still alive in research, for example in the kNN-LM, which interpolates a neural model with a nearest-neighbour distribution.

This part builds those ingredients one at a time: mixing orders by interpolation, choosing the mixing weights on held-out data, backing off when the long context has nothing to say, and subtracting a fixed discount whose size you can read off a real experiment. Exams typically ask you to contrast interpolation with backoff, to compute an interpolated or discounted probability by hand, and to justify d ≈ 0.75 from the Church and Gale table. All three are rehearsed below.

By the end you can

  1. Compute an interpolated trigram probability from given λs and component estimates, and explain why the λs must sum to 1.
  2. Explain how λs and other hyperparameters are tuned on held-out data, and why training and test data cannot be used.
  3. Contrast interpolation, Katz-style backoff and stupid backoff, and compute a stupid backoff score down to its unigram base case.
  4. Read the Church and Gale held-out table and argue for a fixed discount of about 0.75.
  5. Compute interpolated absolute discounting for a bigram, including λ(w_{i-1}) and d = n1/(n1 + 2n2).

Suppose you need the probability of food after want chinese. The Unigram estimate is P(food) = 0.01, the Bigram estimate is P(food | chinese) = 0.52, and the Trigram want chinese food never occurred in training, so its maximum likelihood estimate is 0. A pure trigram model would declare the sentence impossible. Instead, take a weighted average of the three with weights λ = (0.1, 0.3, 0.6): 0.1 × 0.01 + 0.3 × 0.52 + 0.6 × 0 = 0.001 + 0.156 + 0 = 0.157. The zero is gone, and the estimate is driven by the evidence that does exist.

That is linear interpolation. The trigram is the sharpest predictor when it has data, but Sparsity means it very often has none, which is exactly the Zero-probability problem of part 06. Lower orders are blunter but almost always have counts. Mixing them lets each order contribute what it is good at. SLP3 writes the trigram version as follows.

P^(wn∣wn−2wn−1)=λ1P(wn)+λ2P(wn∣wn−1)+λ3P(wn∣wn−2wn−1),∑iλi=1\begin{aligned} &\hat{P}(w_n \mid w_{n-2} w_{n-1}) \\ &\quad = \lambda_1 P(w_n) + \lambda_2 P(w_n \mid w_{n-1}) \\ &\quad + \lambda_3 P(w_n \mid w_{n-2} w_{n-1}), \\ &\sum_i \lambda_i = 1 \end{aligned}
Simple linear interpolation, SLP3 eq. 3.29

The constraint that the λs sum to 1 is not decoration. Each component is itself a probability distribution over the vocabulary, so summing the mixture over every possible next word gives λ1 · 1 + λ2 · 1 + λ3 · 1 = Σλ = 1. With weights summing to more than 1 the model would invent probability mass, and with less it would leak some. A weighted average of distributions is a distribution, and that is all the constraint guarantees.

Three estimates, one per order, flow into a single bar whose segments are their weights 0.1, 0.3 and 0.6; the weights sum to 1

Worked example

Interpolating P(food | want chinese)

  1. Collect the three estimates

    P(food) = 0.01, P(food | chinese) = 0.52, P(food | want chinese) = 0 because the trigram is unseen.
  2. Weight and add

    0.1 × 0.01 + 0.3 × 0.52 + 0.6 × 0 = 0.001 + 0.156 + 0 = 0.157.
  3. Now suppose the trigram had been seen

    With P(food | want chinese) = 0.8, the same weights give 0.001 + 0.156 + 0.6 × 0.8 = 0.001 + 0.156 + 0.48 = 0.637. The trigram dominates, but the lower orders still contribute.
  4. Result

    Interpolation turns an impossible event into 0.157 and still lets a well-attested trigram push the estimate up to 0.637.

Weights that depend on the context

A single fixed λ vector treats every context alike, which wastes information. If the bigram want chinese has been seen thousands of times, the trigrams built on it are well estimated and deserve more weight; if it has been seen twice, they do not. SLP3 therefore lets each λ be a function of the two preceding words, which is context-dependent interpolation. In its words, if we have particularly accurate counts for a particular bigram, we assume that the counts of the trigrams based on this bigram will be more trustworthy.

P^(wn∣wn−2:n−1)=λ1(wn−2:n−1) P(wn)+λ2(wn−2:n−1) P(wn∣wn−1)+λ3(wn−2:n−1) P(wn∣wn−2:n−1)\begin{aligned} &\hat{P}(w_n \mid w_{n-2:n-1}) \\ &\quad = \lambda_1(w_{n-2:n-1})\, P(w_n) \\ &\quad + \lambda_2(w_{n-2:n-1})\, P(w_n \mid w_{n-1}) \\ &\quad + \lambda_3(w_{n-2:n-1})\, P(w_n \mid w_{n-2:n-1}) \end{aligned}
Context-conditioned interpolation, SLP3 eq. 3.30; for every context the three weights still sum to 1

The idea is old. Jelinek and Mercer introduced interpolated estimation in 1980, which is why it is also called Jelinek-Mercer smoothing or deleted interpolation. Chen and Goodman's large empirical study found that interpolated models, which always combine the higher and lower orders, typically work better than backoff models, because low counts of 1 or 2 are poorly estimated and benefit from being blended even when they are not zero (Goodman 2001). Jurafsky's own slide states the verdict in three words: interpolation works better.

Quick check

With λ1 = 0.1, λ2 = 0.3 and λ3 = 0.6, the trigram is unseen, P(w | previous word) = 0.5 and P(w) = 0.02. What is the interpolated probability?

Recall

Why must the interpolation weights sum to 1?

Each component is a distribution summing to 1, so Σλ_i · 1 = 1 keeps the mix a valid distribution. Weights summing to more than 1 would create probability mass; weights summing to less would lose it.

Choosing the weights on held-out data

Where do the numbers 0.1, 0.3, 0.6 come from? Try them out. Take three tokens from a development set and write down, for each, the unigram, bigram and trigram estimates that the training counts give.

TokenP1 (unigram)P2 (bigram)P3 (trigram)
Token 10.010.520
Token 20.020.300.50
Token 30.0050.100.40
Three dev tokens and their component estimates

Now score the same three tokens under three candidate weight vectors. For each, mix the components, multiply the token probabilities, take the base-2 log, and turn that into Perplexity with PP = 2^(−log2 L / 3).

λ = (λ1, λ2, λ3)Token probabilitieslog2 likelihoodPerplexity
(0.1, 0.3, 0.6)0.157, 0.392, 0.2705−5.9093.92
(0.6, 0.3, 0.1)0.162, 0.152, 0.073−9.128.22
(0, 0, 1)0, 0.50, 0.40−∞∞
Searching λ on held-out data: the first setting wins

The first vector gives a held-out perplexity of 3.92, the second 8.22, and the third, which is the pure maximum likelihood trigram, gives probability 0 to the first token and therefore infinite perplexity. You pick the first. That is the whole procedure, done properly: the λs are hyperparameters, values that are not counts and are not learned from the counts. SLP3 says so in a footnote, contrasting them with regular counts that are learned from the training data. The recipe has two stages. First fit every n-gram probability on the training set and freeze it. Then search over λ to maximize the likelihood of a separate held-out corpus, which is the same as minimizing its perplexity. The same holds for k in add-k and for the discount d later in this part.

Why not tune on the training data itself? Because on training data the maximum likelihood trigram already fits best: every training trigram has a nonzero count, so the likelihood keeps rising as λ3 grows and peaks at λ3 = 1. That is exactly the third row of the table, which collapses on any new text. Held-out data contains the unseen n-grams that the lower orders exist to cover, so only it can reward them. And the Test set is off limits, because once you tune on it the reported perplexity is no longer an honest estimate of performance on unseen text.

Recall

Why tune λ on held-out data and not on training data?

On training data the MLE trigram already maximizes likelihood, so the optimum is λ3 = 1, which gives zeros on new data. The test set is reserved for the final evaluation only.

Backoff, and stupid backoff at web scale

Score floor after quietly on the, in a corpus of N = 10,000 tokens. The four-gram quietly on the floor has count 0, so drop the oldest context word. The trigram on the floor also has count 0, even though on the itself was seen 20 times, so drop another word. The bigram the floor has count 3 and the has count 60, so its Relative frequency is 3 / 60 = 0.05. Each step down cost a factor of 0.4, so the score is S = 0.4 × 0.4 × 0.05 = 0.008.

This is Backoff: use the highest order whose full n-gram count is above 0, and otherwise drop one context word and try again. Unlike interpolation it uses exactly one order per word. Notice what triggered each step. The context on the was perfectly familiar; it was the n-gram on the floor that was missing. Backoff fires on a zero n-gram count, not on an unseen context.

A dot steps down the staircase of contexts, picking up a ×0.4 factor at each stair, until the bigram the floor has a count; the empty-context unigram stair waits below as the base case

The specific recipe: stupid backoff

The factor 0.4 is the signature of Stupid backoff, introduced by Brants, Popat, Xu, Och and Dean at EMNLP-CoNLL 2007 for Google's translation system. Their equation 5 defines a score, and their equation 6 ends the recursion at the unigram level.

S(wi∣wi−k+1i−1)={f(wi−k+1i)f(wi−k+1i−1)if f(wi−k+1i)>0α S(wi∣wi−k+2i−1)otherwiseS(wi)=f(wi)N\begin{gathered} S(w_i \mid w_{i-k+1}^{i-1}) = \begin{cases} \dfrac{f(w_{i-k+1}^{i})}{f(w_{i-k+1}^{i-1})} & \text{if } f(w_{i-k+1}^{i}) > 0 \\[2mm] \alpha\, S(w_i \mid w_{i-k+2}^{i-1}) & \text{otherwise} \end{cases} \\ S(w_i) = \frac{f(w_i)}{N} \end{gathered}
Stupid backoff with its base case, Brants et al. 2007, eqs. 5 and 6; α = 0.4 in all their experiments

If the bigram the floor had also been unseen and floor occurred 5 times, the recursion would reach the base case: S = 0.4³ × 5 / 10,000 = 0.064 × 0.0005 = 0.000032. The authors write S instead of P to emphasize that these are not probabilities but scores, and the reason is easy to see. In the context on the, the relative frequencies of the continuations that were seen already sum to 1. Every unseen continuation then adds 0.4 × S(w | the) on top. For floor alone that is 0.4 × 0.05 = 0.02, so the total over the vocabulary is at least 1.02, and every other unseen word pushes it higher.

A proper backoff model fixes this in two ways at once. Katz backoff (Katz 1987) first discounts the seen n-grams, replacing the relative frequency with a smaller P*, which frees some probability mass in each context. Then it gives the lower order a context-dependent normalizing weight α(context) chosen so that the freed mass is spread over exactly the unseen words. SLP3 (Jan 2023 edition, section 3.5) is explicit that without discounting the total probability would be greater than 1; the current draft adds that stupid backoff gives up the idea of trying to make the language model a true probability distribution. Discounting is therefore not optional for backoff, and it is the subject of the rest of this part.

PBO(wn∣wn−N+1:n−1)={P∗(wn∣wn−N+1:n−1)if C(wn−N+1:n)>0α(wn−N+1:n−1) PBO(wn∣wn−N+2:n−1)otherwise\begin{aligned} &P_{\text{BO}}(w_n \mid w_{n-N+1:n-1}) \\ &\quad = \begin{cases} P^{*}(w_n \mid w_{n-N+1:n-1}) & \text{if } C(w_{n-N+1:n}) > 0 \\ \alpha(w_{n-N+1:n-1})\, P_{\text{BO}}(w_n \mid w_{n-N+2:n-1}) & \text{otherwise} \end{cases} \end{aligned}
Katz backoff, SLP3 Jan 2023 edition, eq. 3.30: discounted P* plus a normalizing α

Why did Google accept a model that is not a distribution? A translation decoder only compares candidate outputs, so it needs relative scores, not normalized probabilities. Stupid backoff needs no discount estimation and no α per context, so it is cheap to compute with MapReduce over training data that reached 2 trillion tokens and a model of about 300 billion n-grams. At small data sizes it was about 1 BLEU point behind Kneser-Ney, and the gap narrowed as data grew until the two were close. The authors' footnote explains the name: it originated at a time when they thought such a simple scheme could not possibly be good; their view changed, but the name stuck.

InterpolationKatz backoffStupid backoff
When are lower orders used?Always, for every word, seen or unseenOnly when the full n-gram count is 0Only when the full n-gram count is 0
Discounting of seen n-gramsImplicit, through the λ weightsYes, Katz discounts P* to free massNone
True probability distribution?Yes, because Σλ = 1Yes, with the normalizing αNo, it returns scores
Where usedClassic speech and text LMs; the base of Kneser-NeyKatz 1987 style speech recognizersGoogle MT, trained on 2 trillion tokens
Three ways to use lower orders

Quick check

Why is the stupid backoff score not a true probability distribution?

Recall

State the difference between interpolation and backoff in one sentence each.

Interpolation always mixes all orders, even when the higher order is seen. Backoff uses only the highest order whose n-gram count is above 0, and drops to lower orders only when that count is zero.

Recall

Give the two facts that make stupid backoff not a distribution, and why Google still used it.

It has no discounting of seen n-grams, and it uses a fixed 0.4 weight, so scores for a context can sum to more than 1. MT decoding needs only relative scores, it is cheap to compute with MapReduce at 2 trillion tokens, and it approaches Kneser-Ney as data grows.

Why add-k is not enough: the idea of discounting

Look at what add-one smoothing did to the Berkeley Restaurant Project corpus. The bigram want to occurred 608 times. After adding one to every cell and renormalizing, its reconstituted count is 238, and P(to | want) falls from 0.66 to 0.26.

Add-one on the Berkeley Restaurant bigrams, SLP3 sections 3.6.1 and 3.6.2

C(want to), raw count
608
C*(want to), reconstituted after add-one
238
P(to | want), MLE
0.66
P(to | want), add-one
0.26
Discount ratio d_c = C*/C for want to
0.39
Discount ratio d_c = C*/C for chinese food
0.10
Bigram cells sharing the added mass
about 1446² ≈ 2.1 million

One of the most frequent, most reliable bigrams in the table lost more than half its probability. The discount ratio d_c, reconstituted count over original count, is 0.39 for want to and 0.10 for chinese food. The mass went to the roughly 1446² possible bigram cells, most of which are zeros. SLP3 sums it up: too much probability mass is moved to all the zeros. Making the added amount smaller does not cure it. Add-k with k = 0.05 moves less mass, but SLP3 reports that it still does not work well for language modeling, generating counts with poor variances and often inappropriate discounts (Gale and Church 1994).

Read the problem the other way round. Any Smoothing method that gives mass to unseen events must take it from seen events, which is why SLP3 says these methods are called smoothing or Discounting. The question is not whether to discount but how much, and from which counts. A good discount barely touches large counts, whose estimates are already reliable, and mostly adjusts small counts, where most of the uncertainty lives. And the amount should be measured, on data the model did not train on, not guessed. The next concept does exactly that measurement.

Slide 75's last point, smoothing that respects how language uses context, is a preview: the discount here fixes how much mass moves, and Kneser-Ney smoothing in the next part fixes where it goes.

Recall

What two properties should a good discount have that add-one and add-k lack?

It should barely touch large counts, whose estimates are already reliable, and mostly adjust small counts, where the uncertainty lives. And its size should be measured on held-out data rather than fixed by a formula that ignores how reliable each count is.

Take every bigram that appeared exactly 4 times in the first 22 million words of AP newswire, and count how often each appears in the next 22 million words. The average is 3.23, not 4. The bigrams did not change; the first count was partly luck.

This is the experiment of Church and Gale (1991), reported in SLP3 (Jan 2023 edition, section 3.7.1, Fig. 3.9). Repeat it for every training count from 0 to 9 and subtract the held-out average from the training count.

Training count cAverage held-out countc minus held-out
00.0000270mass MLE sets to zero
10.4480.552
21.250.75
32.240.76
43.230.77
54.210.79
65.230.77
76.210.79
87.210.79
98.260.74
Church and Gale bigram counts, 22M AP words for training and 22M for held-out

For every count from 2 to 9 the gap is nearly constant, between 0.74 and 0.79. Training counts systematically overestimate future counts, and by a fixed amount rather than by a fixed percentage. SLP3 concludes that, except for the held-out counts for 0 and 1, all the other bigram counts could be estimated pretty well by just subtracting 0.75. This held-out data plays exactly the role of the Development set in the second concept: it measures a quantity the training counts cannot reveal about themselves.

Held-out averages sit on a line parallel to y = x and 0.75 below it; only the count-1 dot drifts off, about 0.55 below

The two exceptions are informative. The count-0 row, 0.0000270, is the mass that maximum likelihood wrongly sets to zero. It is a tiny average, but it is averaged over an enormous number of unseen pairs, so in total it adds up to real probability that a discount must supply. The count-1 row is the outlier: singletons reappear 0.448 times, a gap of about 0.55, so a single discount of 0.75 would overcharge them. That is why SLP3 suggests a separate discount of 0.5 for count 1, and why Modified Kneser-Ney uses separate discounts for counts 1, 2 and 3+.

Quick check

In Church and Gale's AP newswire data, bigrams seen 5 times in the first 22 million words occur on average how often in the next 22 million?

Recall

What does the count-1 row (0.448) of the Church and Gale table tell you?

Singletons lose about 0.55, not 0.75, so one discount overcharges them. This is why the textbook suggests 0.5 for count 1, and why modified Kneser-Ney uses separate discounts D1, D2 and D3+.

Absolute discounting and choosing d

The context chinese was seen 10 times, followed by food 6 times, restaurant 3 times and cuisine once. Subtract d = 0.75 from each count: food keeps 5.25 / 10 = 0.525, restaurant keeps 2.25 / 10 = 0.225, cuisine keeps 0.25 / 10 = 0.025. Together they keep 0.775. The missing 3 × 0.75 / 10 = 0.225 is a pot of freed probability, and it is handed out to every word in proportion to its unigram probability.

That is interpolated absolute discounting, the direct use of the Church and Gale finding. Its bigram form subtracts a fixed d from every nonzero count and interpolates with the unigram distribution.

PAD(wi∣wi−1)=max⁡(C(wi−1wi)−d, 0)C(wi−1)+λ(wi−1) P(wi)\begin{aligned} &P_{\text{AD}}(w_i \mid w_{i-1}) \\ &\quad = \frac{\max\big(C(w_{i-1} w_i) - d,\ 0\big)}{C(w_{i-1})} \\ &\quad + \lambda(w_{i-1})\, P(w_i) \end{aligned}
Interpolated absolute discounting for bigrams: SLP3 Jan 2023 eq. 3.32, with the max(·, 0) of the Kneser-Ney form, eq. 3.38
λ(wi−1)=dC(wi−1)×∣{w:C(wi−1w)>0}∣\begin{aligned} \lambda(w_{i-1}) &= \frac{d}{C(w_{i-1})} \\ &\quad \times \big|\{w : C(w_{i-1} w) > 0\}\big| \end{aligned}
The weight is the freed mass: d times the number of distinct continuation types, over the context count (the normalizing λ of SLP3 Jan 2023 eq. 3.39, stated there for Kneser-Ney)

Each part of the formula has a job. The first term is the discounted relative frequency: big counts barely move, small counts move a lot, as the previous concept demanded. The max(·, 0) keeps unseen bigrams at zero in this term instead of letting them go negative. The weight λ(w_{i-1}) is the Backoff weight (lambda), and it is not a free parameter: it is exactly the mass the first term removed, so the two terms together sum to 1.

Worked example

P_AD after chinese with d = 0.75

  1. Discount the seen bigrams

    (6 − 0.75)/10 = 0.525, (3 − 0.75)/10 = 0.225, (1 − 0.75)/10 = 0.025. Sum 0.775.
  2. Compute the freed mass

    Three continuation types, so λ(chinese) = 0.75 × 3 / 10 = 0.225 = 1 − 0.775.
  3. A seen word

    With P(food) = 0.02: P_AD(food | chinese) = 0.525 + 0.225 × 0.02 = 0.525 + 0.0045 = 0.5295.
  4. An unseen word

    With P(tea) = 0.001: P_AD(tea | chinese) = 0 + 0.225 × 0.001 = 0.000225. Not zero.
  5. Check normalization

    Summing over the whole vocabulary: 0.775 + 0.225 × Σ_w P(w) = 0.775 + 0.225 × 1 = 1.
  6. Result

    The distribution after chinese sums to exactly 1, food stays near its MLE of 0.6, and tea gets a small positive probability. Note that cuisine, a singleton, lost 75% of its count; the count-1 row of the Church and Gale table says that is too much, which is the argument for a smaller discount on singletons.
Each seen count pays the same 0.75 cap into a shared pot; the pot is then spread across every word in proportion to its unigram probability

Choosing d

The discount d is the one Hyperparameter left, and there are two standard ways to set it. The first is to read it off the table: SLP3 says setting all the d values to 0.75 would work very well, or perhaps keeping a separate second discount of 0.5 for the bigrams with counts of 1. Jurafsky's slide puts it as save ourselves some time and just subtract 0.75. The second is a closed-form estimate from Ney, Essen and Kneser (1994), which uses only the count of counts of the training data.

d=n1n1+2 n2d = \frac{n_1}{n_1 + 2\, n_2}
Ney, Essen and Kneser 1994 (SLP3 Jan 2023, eq. 3.33): n1 and n2 are the numbers of n-grams of this order seen once and twice

For example, with n1 = 6000 bigram types seen once and n2 = 1500 seen twice, d = 6000 / (6000 + 3000) = 6000 / 9000 ≈ 0.667. The estimate needs no held-out data, and its value lands close to the 0.75 that Church and Gale measured directly. In practice, KenLM estimates modified Kneser-Ney with separate discounts for counts 1, 2 and 3+, while BerkeleyLM ships plain absolute discounting in which every discount is 0.75.

The next part keeps this exact structure, a discounted higher-order term plus a λ times a lower-order distribution, and changes only the lower-order distribution. Kneser-Ney smoothing replaces the unigram P(w_i) with a continuation probability, which asks how many different contexts a word appears in rather than how often it appears.

Quick check

With absolute discounting, d = 0.75, context h seen 20 times with 8 distinct following word types. What is λ(h)?

Recall

Compute d if a corpus has 6000 bigram types seen once and 1500 seen twice.

d = 6000 / (6000 + 2 · 1500) = 6000 / 9000 ≈ 0.667.

Recall

In absolute discounting, where does λ(w_{i-1}) come from?

It is exactly the freed mass, d × (number of distinct continuation types of w_{i-1}) / C(w_{i-1}). It is fixed by normalization, not tuned.

Recap

If you remember nothing else

  • Linear interpolation: P̂ = λ1 P(w) + λ2 P(w | w_{n-1}) + λ3 P(w | w_{n-2} w_{n-1}) with Σλ = 1; it always mixes every order, and λ can depend on the context.
  • λs, k and d are hyperparameters: fix the counts, then choose them to maximize held-out likelihood (minimize held-out perplexity), for example with EM.
  • Backoff uses the highest order whose n-gram count is above zero; a correct backoff model must discount and renormalize (Katz).
  • Stupid backoff (Brants et al. 2007) uses raw relative frequencies, a fixed 0.4 per step, and ends at S(w) = count(w)/N; scores, not probabilities, but close to Kneser-Ney at web scale.
  • Add-one discounts badly: C(want to) drops from 608 to 238 and P(to | want) from 0.66 to 0.26.
  • Church and Gale: across 22M + 22M AP words, bigrams of count 2 to 9 reappear about c − 0.75 times; singletons reappear 0.448 times.
  • Interpolated absolute discounting: max(C − d, 0)/C(w_{i-1}) + λ(w_{i-1}) P(w), with λ(w_{i-1}) = d × types / C(w_{i-1}) and d ≈ 0.75 or n1/(n1 + 2n2).
  • Kneser-Ney (next part) keeps this structure and replaces the unigram P(w) with a continuation probability.

Sources

Part 08: Kneser-Ney smoothing for bigrams

Why backing off to raw unigram frequency fails (reading Kong versus reading glasses), the continuation probability that counts distinct contexts, the interpolated Kneser-Ney bigram formula, and a full step-by-step toy computation.

6 concepts, slides 81-94

Why this part matters

Kneser-Ney is the payoff of the whole smoothing story. It keeps the discount from absolute discounting but changes what the model backs off to: instead of asking how often a word occurs, it asks in how many different contexts the word has been seen. Modified Kneser-Ney was the standard n-gram baseline for about two decades after Chen and Goodman's 1998 study, and it is still what KenLM and SRILM build and what shallow-fusion decoders in speech recognition and translation plug in.

The part follows one toy corpus from start to finish: 30 copies of "Hong Kong" and four different words before "glasses". First we watch frequency-based backoff make the wrong choice, then we build the continuation probability that fixes it, write the full bigram formula, derive its weight λ from first principles, and finally compute every number by hand. That last computation is the one exams ask for, so expect to do it on paper.

By the end you can

  1. Explain why backing off to raw unigram frequency ranks Kong above glasses after "reading".
  2. Define the continuation count and P_cont and compute them from a list of bigram types.
  3. Write the interpolated Kneser-Ney bigram formula and say what each of its two terms does.
  4. Derive lambda(h) from the discounted mass and prove that P_KN(. | h) sums to 1.
  5. Compute P_KN for any word and history in the toy corpus, including the Hong sanity check.

Fill the gap: "I can't see without my reading ___." Every English speaker says "glasses". Now suppose a Bigram model has never seen the pair (reading, glasses), or has seen it so rarely that it must lean on a lower-order estimate. With classic Backoff or Absolute discounting, that lower-order estimate is the Unigram probability P(w), and in a corpus full of news about "Hong Kong" the word Kong is very frequent.

Make it concrete with the toy corpus used throughout this part: C(Hong Kong) = 30 and one each of reading glasses, sun glasses, safety glasses and my glasses. Count the second word of each of the 34 bigram tokens. Kong appears 30 times and glasses 4 times, so the maximum-likelihood unigram gives P(Kong) = 30 / 34 ≈ 0.882 and P(glasses) = 4 / 34 ≈ 0.118. Absolute discounting with d = 0.75 keeps 1 − 0.75 = 0.25 for the one observed bigram after "reading" and spreads the freed 0.75 by the unigram:

PAD(w∣h)=max⁡(C(hw)−d, 0)C(h)+λ(h) P(w)\begin{aligned} P_{\text{AD}}(w \mid h) &= \frac{\max(C(hw) - d,\, 0)}{C(h)} \\ &\quad + \lambda(h)\, P(w) \end{aligned}
Absolute discounting interpolated with a raw unigram (JM Appendix C, Eq. C.1)

That gives P_AD(Kong | reading) = 0.75 × 0.882 ≈ 0.662 and P_AD(glasses | reading) = 0.25 + 0.75 × 0.118 ≈ 0.338. Kong, a word that has only ever followed Hong, gets about twice the probability of the word that actually fits. (The slides state the problem in words; these numbers are ours, computed from the slide 88 corpus.)

Frequency backoff asks how common w is; Kneser-Ney asks how many contexts lead to w

The failure is in the question, not the arithmetic. When the model backs off, it is in a situation it has not seen: this history has not been followed by this word before. The useful question there is not "how likely is w?" but "how likely is w to show up as a novel continuation, after a context it has never followed?" Jurafsky and Martin phrase it exactly that way, and the answer to the second question is the Continuation probability, the lower-order distribution of Kneser-Ney smoothing. Raw frequency is a poor proxy for it because frequency can be concentrated: thirty tokens of Kong all come from one fixed phrase, which tells us nothing about Kong turning up somewhere new. This is the same Sparsity problem as before, now hitting the fallback instead of the main estimate.

Lower-order distributionQuestion it answersKongglasses
Raw unigram P(w)How likely is w?30 / 34 ≈ 0.8824 / 34 ≈ 0.118
Continuation P_cont(w)How likely is w as a novel continuation?1 / 5 = 0.24 / 5 = 0.8
Two lower-order distributions in the toy corpus

Recall

Why does an absolute-discounting model that backs off to the raw unigram rank Kong above glasses after "reading"?

The unigram counts tokens. Kong has 30 tokens, all from "Hong Kong", so its P(w) = 30 / 34 is large even though it has only ever followed one word. The backoff term then gives Kong about 0.662 and glasses about 0.338.

Look at the words immediately to the left of each target. Kong has exactly one left neighbour, Hong. glasses has four: reading, sun, safety and my. Kong appears 30 times, but every one of those tokens is the same context repeated, so it earns credit for only one. That number of distinct left neighbours is the Continuation count:

N1+(∙ w)=∣{ v:C(v w)>0 }∣N_{1+}(\bullet\, w) = \bigl|\{\, v : C(v\,w) > 0 \,\}\bigr|
Continuation count: how many distinct words have been seen before w

To turn it into a probability, divide by the total number of bigram types, |{(u, w′) : C(uw′) > 0}|. The reasoning is that every bigram type was a novel continuation the first time it appeared, so the set of bigram types is the full record of "a word showed up in a new context", and each word's share of that record is its continuation probability. Jurafsky and Martin also write the denominator as the sum of every word's continuation count (Eq. C.6). The two are the same number, because each bigram type contributes one to exactly one word's count; in the toy corpus both equal 5.

Pcont(w)=∣{ v:C(v w)>0 }∣∣{ (u,w′):C(u w′)>0 }∣=N1+(∙ w)∑w′N1+(∙ w′)\begin{aligned} P_{\text{cont}}(w) &= \frac{\bigl|\{\, v : C(v\,w) > 0 \,\}\bigr|}{\bigl|\{\, (u, w') : C(u\,w') > 0 \,\}\bigr|} \\ &= \frac{N_{1+}(\bullet\, w)}{\sum_{w'} N_{1+}(\bullet\, w')} \end{aligned}
Continuation probability (JM Appendix C, Eq. C.4 to C.6)
WordTokens as second wordDistinct preceding wordsContinuation countP_cont
Kong30Hong11 / 5 = 0.2
glasses4reading, sun, safety, my44 / 5 = 0.8
Hong0none00 / 5 = 0
Token counts against continuation counts in the toy corpus (5 bigram types)
Kong: 30 tokens but 1 context. glasses: 4 tokens and 4 contexts

This is a different kind of Relative frequency: the unit being counted is a context, not a token. As Jurafsky and Martin put it, a frequent word occurring in only one context will have a low continuation probability, and SRILM's manual describes its lower-order Kneser-Ney estimate as proportional to the number of unique words that precede it in the training data. The same machinery handles any vocabulary: the words "Francisco" (almost always after San) and "York" (after New) look just like Kong.

Recall

Define the continuation count and P_cont, and compute both for Kong and glasses in the toy corpus.

The continuation count is |{v : C(vw) > 0}|, the number of distinct left neighbours. P_cont divides it by the number of bigram types. Kong: 1, so 1 / 5 = 0.2. glasses: 4, so 4 / 5 = 0.8.

Quick check

Why does Kneser-Ney give glasses a higher continuation probability than Kong?

The interpolated Kneser-Ney bigram formula

Take P_KN(glasses | reading) in Kneser-Ney smoothing. The bigram "reading glasses" was seen once. The first term keeps what that count earned after paying the discount, (1 − 0.75) / 1 = 0.25. The second term adds a share of the freed mass, chosen by how widely glasses is used as a continuation. Written in general:

PKN(wi∣wi−1)=max⁡(C(wi−1wi)−d, 0)∑vC(wi−1v)⏟discounted bigram+λ(wi−1) Pcont(wi)⏟weighted continuation\begin{aligned} &P_{\text{KN}}(w_i \mid w_{i-1}) \\ &\quad = \underbrace{\frac{\max\bigl(C(w_{i-1} w_i) - d,\, 0\bigr)}{\sum_{v} C(w_{i-1} v)}}_{\text{discounted bigram}} \\ &\quad + \underbrace{\lambda(w_{i-1})\, P_{\text{cont}}(w_i)}_{\text{weighted continuation}} \end{aligned}
Interpolated Kneser-Ney for bigrams (JM Appendix C, Eq. C.7). First term: the bigram's own evidence minus a flat discount. Second term: the freed mass shared by continuation probability.

The denominator is the count of wi−1w_{i-1} as a history, ∑vC(wi−1v)\sum_{v} C(w_{i-1} v), which Jurafsky and Martin write explicitly in Eq. C.1 and C.8. The second term scales the Continuation probability by the Backoff weight (lambda) λ of the history, the mass the discount freed. Everything else is inherited: the Discounting step is exactly absolute discounting, and the structure is that of Linear interpolation with one difference that matters a lot, the lower order is P_cont instead of the Maximum likelihood estimation unigram.

The model is called interpolated because the second term is added for every word, even for bigrams that were seen. A backoff version of Kneser-Ney uses the continuation term only when C(wi−1wi)=0C(w_{i-1} w_i) = 0 and rescales it accordingly. Both exist in practice: SRILM builds either, and its -interpolate flag selects the interpolated form. Kneser and Ney introduced the method in 1995, and Chen and Goodman's large comparison found that a Kneser-Ney variant consistently outperforms all the other smoothing algorithms they evaluated.

History "reading" has one token and one continuation type. Discounting that single bigram removes 0.75 / 1 = 0.75 of the probability mass, so the continuation term must hand out exactly 0.75: λ(reading) = 0.75. History "Hong" has 30 tokens and still one type, so discounting frees only 0.75 / 30 = 0.025. The Backoff weight (lambda) is not chosen; it is whatever the discount removed.

λ(wi−1)=d∑vC(wi−1v)⋅∣{ w:C(wi−1w)>0 }∣\begin{aligned} \lambda(w_{i-1}) &= \frac{d}{\sum_{v} C(w_{i-1} v)} \\ &\quad \cdot \bigl|\{\, w : C(w_{i-1} w) > 0 \,\}\bigr| \end{aligned}
Normalized discount times the number of word types that follow the history, which is the number of types that were discounted (JM Eq. C.8)
N1+(h ∙)=∣{ w:C(h w)>0 }∣N_{1+}(h\,\bullet) = \bigl|\{\, w : C(h\,w) > 0 \,\}\bigr|
Number of distinct word types that follow h (the mirror image of N1+(• w))

Read it as two factors. d / C(h) is how much one discount costs in probability units for this history, and the set size N1+(h •) is how many times the discount was paid, once per distinct word that follows h. The product is the total mass removed, and the proof that the distribution is still a proper one is three lines long.

Worked example

Proof that P_KN(· | h) sums to 1

  1. Sum the discounted terms

    Only the N1+(h •) seen words contribute, and each loses exactly d: Σ_w max(C(hw) − d, 0) / C(h) = (C(h) − d · N1+(h •)) / C(h).
  2. Recognize lambda

    That equals 1 − d · N1+(h •) / C(h) = 1 − λ(h).
  3. Sum the continuation terms

    P_cont is a distribution, so Σ_w λ(h) P_cont(w) = λ(h) · 1 = λ(h).
  4. Result

    (1 − λ(h)) + λ(h) = 1. For "reading": 0.25 + 0.75 = 1. For "Hong": 0.975 + 0.025 = 1.

The d = 0.75 used throughout is the same discount Part 07 measured: the Church and Gale held-out experiment held-out table shows counts of 2 to 9 shrinking by about 0.75, and d = n1 / (n1 + 2 n2) estimates it from counts of counts. Kneser-Ney inherits that discount unchanged; what it changes is where the freed mass goes.

Recall

Show that P_KN(· | h) sums to 1.

The discounted terms sum to (C(h) − d · N1+(h •)) / C(h) = 1 − λ(h), because each of the N1+(h •) seen types loses exactly d. The continuation terms sum to λ(h) · Σ P_cont = λ(h). The total is 1.

Recall

If C(h) doubles but the number of continuation types after h stays the same, what happens to λ(h), and why does that make sense?

λ(h) halves, since it is d · N1+(h •) / C(h). More evidence for the history means its own bigram counts are more trustworthy, so the model backs off less.

Quick check

In λ(h) = d / C(h) × |{w : C(hw) > 0}|, what does the set size count?

Here is the full computation on the slide corpus. Every Kneser-Ney smoothing question, by hand or in code, follows the same order: continuation probabilities first, then the weight of the history, then each word's discounted term and continuation term, and finally a check that the probabilities sum to 1.

The toy corpus (slide 88)

C(Hong Kong)
30
C(reading glasses)
1
C(sun glasses)
1
C(safety glasses)
1
C(my glasses)
1
Discount d
0.75
Bigram types
5

Worked example

P_KN after the history reading, d = 0.75

  1. Step 1: continuation probabilities

    Kong has one left context (Hong), glasses has four (reading, sun, safety, my), and there are 5 bigram types. P_cont(Kong) = 1 / 5 = 0.2 and P_cont(glasses) = 4 / 5 = 0.8.
  2. Step 2: the backoff weight of reading

    "reading" occurs once as a history and is followed by one type, so λ(reading) = 0.75 / 1 × 1 = 0.75.
  3. Step 3: glasses after reading

    P_KN(glasses | reading) = max(1 − 0.75, 0) / 1 + 0.75 × 0.8 = 0.25 + 0.6 = 0.85.
  4. Step 4: Kong after reading

    C(reading Kong) = 0, so P_KN(Kong | reading) = 0 + 0.75 × 0.2 = 0.15.
  5. Result

    0.85 + 0.15 = 1. Every other word has P_cont = 0 in this corpus, so nothing else gets mass after "reading".
The 0.75 shaved from reading is poured out by P_cont: 0.6 to glasses, 0.15 to Kong

Notice where glasses gets its probability. The bigram "reading glasses" contributes only 0.25; the other 0.6 arrives through the continuation term, because glasses is a word that turns up after many different words. With a single observation of the history, the model trusts the history little (λ is large) and the continuation distribution does most of the work.

Quick check

In the slide 88 toy corpus with d = 0.75, what is P_KN(Kong | reading)?

Put the two models side by side. After "reading", frequency-unigram Backoff gave Kong about 0.662 and glasses about 0.338; Kneser-Ney smoothing gives Kong 0.15 and glasses 0.85. The ranking flips. But does Kneser-Ney now treat Kong unfairly where Kong belongs? Check the history Hong, which the slides start and leave unfinished.

C(Hong) = 30 with one continuation type, so λ(Hong) = 0.75 / 30 × 1 = 0.025. Then P_KN(Kong | Hong) = 29.25 / 30 + 0.025 × 0.2 = 0.975 + 0.005 = 0.98 and P_KN(glasses | Hong) = 0 + 0.025 × 0.8 = 0.02, which sum to 1. Kong keeps almost all the mass after Hong. Kneser-Ney did not punish Kong; it only removed Kong's unearned advantage in contexts it was never seen in.

HistoryWordFrequency backoffKneser-Ney
readingKong0.6620.15
readingglasses0.3380.85
HongKong0.9970.98
Hongglasses0.0030.02
Frequency-unigram backoff against Kneser-Ney, toy corpus, d = 0.75 (frequency backoff uses P(Kong) = 30/34, P(glasses) = 4/34)
λ shrinks as the evidence for a history grows: 0.025 for Hong, 0.75 for reading

The two histories show the full logic. Where the history is strong evidence, λ is tiny and the bigram dominates. Where the history is thin, λ is large and the continuation distribution decides, and there diversity beats frequency. The slogan to remember is that backoff should model continuation diversity, not token frequency.

From the toy to real toolkits

Real systems use Modified Kneser-Ney, which replaces the single d with three discounts, D1, D2 and D3+, for n-grams seen once, twice, and three or more times (JM C.2; Part 09 derives them). It is the default in KenLM, whose documentation says it estimates unpruned language models with modified Kneser-Ney smoothing, and in SRILM through -kndiscount (with -ukndiscount for the original single-discount version). Heafield and colleagues built an unpruned modified Kneser-Ney model on 126 billion tokens on one machine with 140 GB of RAM in 2.8 days, and it gained 0.8 BLEU in the WMT 2013 translation task.

Recall

Compute P_KN(glasses | Hong) and P_KN(Kong | Hong) with d = 0.75.

λ(Hong) = 0.75 / 30 = 0.025. Kong: 29.25 / 30 + 0.025 × 0.2 = 0.98. glasses: 0 + 0.025 × 0.8 = 0.02. They sum to 1.

Recall

In the toy corpus, what is P_cont(Hong), and why is that a problem for a real model?

It is 0, because Hong never appears as a second word. So P_KN(Hong | reading) = 0, a new zero. Full Kneser-Ney interpolates the lowest order with a uniform 1 / V (JM Eq. C.11), covered in Part 09.

Quick check

For history Hong (C(Hong) = 30, one continuation type, d = 0.75), what is λ(Hong)?

Recap

If you remember nothing else

  • Backing off to P(w) asks "how frequent is w?", so Kong, inflated by "Hong Kong", beats glasses after "reading".
  • Kneser-Ney backs off to P_cont(w) = distinct left contexts of w / number of bigram types. In the toy corpus Kong gets 1/5 = 0.2 and glasses gets 4/5 = 0.8.
  • P_KN(w | h) = max(C(hw) - d, 0) / C(h) + lambda(h) P_cont(w). It is interpolated: the backoff term is added even for seen bigrams.
  • lambda(h) = d / C(h) times the number of distinct continuations of h, which is exactly the mass removed by discounting, so the distribution sums to 1.
  • Toy corpus with d = 0.75: lambda(reading) = 0.75, P_KN(glasses | reading) = 0.25 + 0.6 = 0.85, P_KN(Kong | reading) = 0.15.
  • History Hong: lambda(Hong) = 0.025, P_KN(Kong | Hong) = 0.98, P_KN(glasses | Hong) = 0.02. Strong histories barely back off.
  • Slogan: backoff should model continuation diversity, not token frequency. Modified Kneser-Ney (D1, D2, D3+) is the version real toolkits use.

Sources

Part 09: Recursive and modified Kneser-Ney

The recursive interpolated Kneser-Ney form for higher-order n-grams, the KN count that switches to continuation counts at lower orders, termination at a uniform distribution, modified KN with three discounts, and why neural LMs came next.

6 concepts, slides 95-101

Why this part matters

Part 08 built Kneser-Ney for bigrams. Real systems use trigrams, 4-grams and 5-grams, so the method has to work at any order. This part turns the bigram formula into a recursion, fixes exactly which count each level uses, shows where the recursion stops, and upgrades the single discount to the three discounts of modified Kneser-Ney.

This matters in three places. Almost every strong n-gram model you will build or meet in a paper, from KenLM features in machine translation to rescoring in speech recognition and baselines in language-model papers, is interpolated modified Kneser-Ney. Exams ask what c_KN means at each level and why there are three discounts. And Bengio's neural language model was measured against modified Kneser-Ney (its backoff form, built with SRILM), and its learned word vectors are the idea behind the word embeddings of lecture 04.

By the end you can

  1. Write the recursive interpolated Kneser-Ney equation and the backoff weight that keeps every level normalized.
  2. Say which count c_KN uses at the highest order and at each lower order, and compute continuation counts from a corpus.
  3. Carry a trigram probability down to the uniform floor and give the probability of <UNK>.
  4. Compute the modified Kneser-Ney discounts D1, D2 and D3+ from counts of counts and explain why there are three.
  5. Name the toolkits and flags that build modified KN models and the two limits that pushed the field to neural LMs.

Start from the bigram formula of Part 08: a discounted bigram term plus λ(h) times a lower-order distribution. Now lift it one level. For a trigram model and the history "her reading", the probability of the next word is the discounted trigram term plus λ(her reading) times P_KN(w | reading). That bigram probability is itself a Kneser-Ney estimate, so it in turn is a discounted bigram term plus λ(reading) times the unigram level. One formula, applied to shorter and shorter histories, covers every order.

PKN(wi∣wi−n+1:i−1)=max⁡(cKN(wi−n+1:i)−d, 0)∑vcKN(wi−n+1:i−1 v)+λ(wi−n+1:i−1) PKN(wi∣wi−n+2:i−1)\begin{aligned} &P_{KN}(w_i \mid w_{i-n+1:i-1}) \\ &\quad = \frac{\max\bigl(c_{KN}(w_{i-n+1:i}) - d,\, 0\bigr)}{\sum_v c_{KN}(w_{i-n+1:i-1}\, v)} \\ &\quad + \lambda(w_{i-n+1:i-1})\, P_{KN}(w_i \mid w_{i-n+2:i-1}) \end{aligned}
Recursive interpolated Kneser-Ney (JM Appendix C, Eq. C.9). The last factor drops the oldest word of the history.

The slide leaves λ undefined for the general form, but it is forced by the same argument as in part 08. The Absolute discounting step removes d from every n-gram type that follows the history h, and the backoff weight must hand exactly that mass to the shorter history:

λ(h)=d∑vcKN(h v)×∣{ w:cKN(h w)>0 }∣\begin{aligned} \lambda(h) &= \frac{d}{\sum_v c_{KN}(h\, v)} \\ &\quad \times \bigl|\{\, w : c_{KN}(h\, w) > 0 \,\}\bigr| \end{aligned}
The general backoff weight: the normalized discount times the number of distinct continuations of h (JM Eq. C.8 generalized; SRILM writes it bow(a_) = D n(a_*) / c(a_)).

Because λ(h) equals the removed mass, each level sums to 1 on its own, provided the level below is a proper distribution. The proof is the three-line argument from Part 08, applied once per level. This is Linear interpolation with weights that are computed rather than tuned, and it is what Chen and Goodman found works best: Heafield and colleagues summarize their result as the recursion p(w_n | w_1^(n−1)) = u(w_n | w_1^(n−1)) + b(w_1^(n−1)) p(w_n | w_2^(n−1)), where u is the discounted term and b the backoff weight. The SRILM manual writes the same thing as p(a_z) = g(a_z) + bow(a_) p(_z) and adds that each n-gram order uses a different discounting constant.

Each level keeps its discounted evidence and passes λ(h) of the mass to the next shorter history, down to 1/V
AspectInterpolated KNBackoff KN
When the lower order is usedAlways, for every word, seen or unseenOnly when the n-gram is unseen
Weight on the lower orderλ(h) = d · N1+(h•) / Σ_v c_KN(hv)A backoff weight α(h) rescaled so that only unseen words share the freed mass
Seen n-gram probabilityDiscounted count plus a share of the lower orderDiscounted count only
SRILM flags-kndiscount -interpolate-kndiscount
Interpolated against backoff Kneser-Ney

Recall

Write the recursive interpolated KN equation and give λ(h).

P_KN(w | h) = max(c_KN(hw) − d, 0) / Σ_v c_KN(hv) + λ(h) P_KN(w | h′), where h′ drops the oldest word of h, and λ(h) = d / Σ_v c_KN(hv) × |{w : c_KN(hw) > 0}|, which is exactly the discounted mass.

The recursion writes c_KN everywhere, and the whole method depends on what that count means at each level. Take a small corpus of seven sentences, with no boundary tokens to keep the arithmetic short:

The toy corpus for this part

Sentence 1 and 2 (twice)
she wore her reading glasses
Sentence 3
he lost his reading glasses
Sentence 4
she wore her sun glasses
Sentence 5
he visited hong kong
Sentence 6
she visited hong kong
Sentence 7
he loves hong kong
Vocabulary V
13

The bigram "reading glasses" occurs 3 times: twice after "her" and once after "his". At the bigram level of a trigram model, though, Kneser-Ney does not use that raw count. It uses the number of distinct words seen immediately to its left, which is 2 ({her, his}). The two copies of "her reading glasses" count once. The same rule applies one level further down: "glasses" occurs 4 times but follows only 2 distinct words ({reading, sun}), and "kong" occurs 3 times but always after "hong", so its count is 1.

cKN(⋅)={count(⋅)for the highest ordercontinuationcount(⋅)for lower ordersc_{KN}(\cdot) = \begin{cases} \text{count}(\cdot) & \text{for the highest order} \\ \text{continuationcount}(\cdot) & \text{for lower orders} \end{cases}
The KN count (JM Appendix C, Eq. C.10)

The Continuation count is the number of unique single-word contexts, which for a bigram reads:

cKN(wi−1wi)=∣{ v:C(v wi−1wi)>0 }∣c_{KN}(w_{i-1} w_i) = \bigl|\{\, v : C(v\, w_{i-1} w_i) > 0 \,\}\bigr|
Continuation count of a bigram: how many distinct words have been seen right before it

The denominators switch too. At the bigram level the history "reading" has Σ_v c_KN(reading v) = 2, not C(reading) = 3, because every term in the sum is a continuation count. At the unigram level, dividing c_KN(w) by Σ_w c_KN(w) gives back the Continuation probability of Part 08 (before discounting), so the bigram model there was simply the two-level case of this recursion. SRILM's manual puts the rule in one sentence: the modified probability for a lower-order n-gram is proportional to the number of unique words that precede it.

N-gramLevelRaw countc_KNDistinct left neighbours
reading glassesbigram32her, his
glassesunigram42reading, sun
hongunigram32visited, loves
kongunigram31hong
sheunigram40none (always first)
Raw count against c_KN in the toy corpus, at the level where each n-gram is used as a lower order
Three tokens each, but reading glasses has 2 left contexts and kong only 1

The last row of the table shows why the boundary edge case matters. "she" begins every sentence it is in, so nothing ever precedes it and its continuation count is 0. In a real model with Sentence boundary tokens, every sentence starts with <s>, and nothing can precede <s> either. If n-grams starting with <s> used continuation counts, they would all collapse to zero. Both KenLM and SRILM therefore keep raw counts for n-grams that start with <s>: Heafield defines the adjusted count as a(w) = c(w) when the order is the highest or w_1 = <s>, and SRILM says only the highest-order n-grams and n-grams that start with <s> keep their regular counts. The slide omits this exception.

Recall

In the toy corpus, why is C(reading glasses) = 3 but c_KN(reading glasses) = 2?

At a lower order you count distinct left contexts, here {her, his}. The two "her reading glasses" tokens count once.

Quick check

In an interpolated trigram KN model, what does c_KN(reading glasses) count?

Part 08 ended with P_KN(Hong | reading) = 0, because Hong never appeared as a second word: a word that never appears after anything has continuation probability 0, so no history can ever predict it. The recursion has to end somewhere, and Kneser-Ney ends it in a way that removes this last zero. The Unigram level is itself discounted and interpolated, with the uniform distribution over the vocabulary:

PKN(w)=max⁡(cKN(w)−d, 0)∑w′cKN(w′)+λ(ϵ) 1V\begin{aligned} P_{KN}(w) &= \frac{\max\bigl(c_{KN}(w) - d,\, 0\bigr)}{\sum_{w'} c_{KN}(w')} \\ &\quad + \lambda(\epsilon)\, \frac{1}{V} \end{aligned}
Unigram termination (JM Appendix C, Eq. C.11). ε is the empty history, and λ(ε) = d × (words with c_KN > 0) / Σ c_KN.

Every word, seen or not, now receives at least λ(ε)/V at the unigram level, which ends the Zero-probability problem for good. That includes the unknown word: <UNK> token is treated as an ordinary vocabulary entry whose count is 0, so the first term vanishes and its probability is exactly λ(ε)/V. Heafield and colleagues describe the same design in KenLM: recursion terminates when unigrams are interpolated with the uniform distribution, and the unknown word has count zero, so its probability is b(ε)/|vocabulary|.

Worked example

P_KN(glasses | her reading) on the toy corpus, d = 0.75 at every level

  1. Unigram level

    V = 13. The continuation counts sum to 15 (one per bigram type), and 11 words have c_KN > 0, so λ(ε) = 0.75 × 11 / 15 = 0.55. Then P(glasses) = 1.25 / 15 + 0.55 / 13 = 0.0833 + 0.0423 = 0.1256 (exactly 49/390) and P(kong) = 0.25 / 15 + 0.0423 = 0.0590 (exactly 23/390). "she" and "he" have continuation count 0, so they get only the floor, 0.0423. In this corpus she plays Hong's role and is rescued by the floor.
  2. Bigram level, history reading

    Σ_v c_KN(reading v) = 2 with 1 type, so λ(reading) = 0.75 × 1 / 2 = 0.375. P(glasses | reading) = 1.25 / 2 + 0.375 × 0.1256 = 0.625 + 0.0471 = 0.6721 and P(kong | reading) = 0 + 0.375 × 0.0590 = 0.0221.
  3. Trigram level, history her reading

    Raw C(her reading glasses) = 2, the history total is 2 with 1 type, so λ(her reading) = 0.375. P(glasses | her reading) = 0.625 + 0.375 × 0.6721 = 0.625 + 0.2520 = 0.8770 and P(kong | her reading) = 0 + 0.375 × 0.0221 = 0.0083.
  4. Result

    An unseen trigram, "her reading kong", still gets a non-zero and sensible probability, and kong stays low because its continuation count is 1. Each level sums to 1 over the vocabulary (checked with exact fractions).
SimulatorRecursive Kneser-Ney on the reading glasses corpus

Seven sentences, V = 13. The top level uses raw trigram counts; the bigram and unigram levels use continuation counts (distinct left neighbours), denominators included. Each row adds its discounted term to λ times the row below it.

  1. trigramraw countmax(2 − d, 0) / 2 = 0.625; λ(her reading) = d × 1 / 2 = 0.375P(glasses) = 0.8770
  2. bigramcontinuation countmax(2 − d, 0) / 2 = 0.625; λ(reading) = d × 1 / 2 = 0.375P(glasses) = 0.6721
  3. unigramcontinuation countmax(2 − d, 0) / 15 = 0.083; λ(ε) = d × 11 / 15 = 0.55P(glasses) = 0.1256
  4. uniform1 / V = 1 / 130.0769
Top probability0.8770P_KN(glasses | her reading)
Uniform floor0.0423λ(ε) / V: every vocabulary word gets at least this at the unigram level. <UNK> gets it only if it is counted in V
Top-level weight0.375λ(her reading): mass the top level passes down

Try history "wore her" with target "she" in the simulator. No level has ever seen "she" after anything, yet the probability is about 0.016, all of it trickling down from the uniform floor through three λ weights. Then push d up: every λ grows, the top level trusts its own counts less, and the floor rises.

Recall

What probability does <UNK> receive in KN and why is it non-zero?

λ(ε)/V, because the unigram level is interpolated with a uniform distribution and <UNK> has count 0, so only the uniform share reaches it.

Quick check

At the end of the KN recursion, the unigram distribution is interpolated with what?

Look again at the held-out experiment behind d = 0.75. Church and Gale counted bigrams in 22 million words of AP newswire and checked how often each appeared in another 22 million. Bigrams seen twice appeared on average 1.25 times (they shrink by 0.75), those seen three times 2.24 times (by 0.76), and those seen four times 3.23 times (by 0.77). But bigrams seen once appeared only 0.448 times, a shrink of 0.55. One discount cannot fit both.

Church and Gale: count-1 bigrams shrink by 0.55, counts 2 to 4 by about 0.75

The Church and Gale numbers show that a single d is a compromise: it over-discounts singletons and slightly under-discounts the rest. Jurafsky and Martin already hint at the fix, suggesting perhaps keeping a separate second discount value of 0.5 for the bigrams with counts of 1. Chen and Goodman made it systematic. Modified Kneser-Ney uses D1 for n-grams seen once, D2 for those seen twice and D3+ for three or more (the slide writes d1, d2, d3+), and Jurafsky and Martin call it the best-performing version of Kneser-Ney smoothing.

Estimating the three discounts

The discounts are not guessed. They come in closed form from the counts of counts of each order: n_k is the number of distinct n-grams of that order seen exactly k times. The original single-discount Kneser-Ney already used this idea, with d = n1 / (n1 + 2 n2) from Ney et al. (JM Eq. C.2, SRILM -ukndiscount). Modified Kneser-Ney keeps that quantity as Y and derives three discounts from it:

Y=n1n1+2n2D1=1−2Yn2n1D2=2−3Yn3n2D3+=3−4Yn4n3\begin{gathered} Y = \frac{n_1}{n_1 + 2 n_2} \qquad D_1 = 1 - 2Y\frac{n_2}{n_1} \\ D_2 = 2 - 3Y\frac{n_3}{n_2} \qquad D_{3+} = 3 - 4Y\frac{n_4}{n_3} \end{gathered}
Modified KN discounts from counts of counts, computed separately for each order (SRILM ngram-discount)
Dn(k)=k−(k+1) tn,1 tn,k+1(tn,1+2tn,2) tn,kD_n(k) = k - \frac{(k+1)\, t_{n,1}\, t_{n,k+1}}{(t_{n,1} + 2 t_{n,2})\, t_{n,k}}
The same formula as Heafield et al. write it, with t(n, k) the number of order-n n-grams with adjusted count k

Worked example

Discounts from counts of counts

  1. Counts of counts

    Suppose an order has n1 = 1000, n2 = 300, n3 = 150 and n4 = 90.
  2. Y

    Y = 1000 / (1000 + 600) = 0.625.
  3. The three discounts

    D1 = 1 − 2 × 0.625 × 300/1000 = 0.625, D2 = 2 − 3 × 0.625 × 150/300 = 1.0625, D3+ = 3 − 4 × 0.625 × 90/150 = 1.5.
  4. Result

    The discount grows with the count bucket: singletons lose 0.625, frequent n-grams lose 1.5.

The reserved mass changes with it

The structure stays the same: discount, then interpolate. What changes is the mass a history reserves for the lower order. Instead of d times the number of continuation types, each type contributes the discount of its own bucket, where N_k(h•) is the number of words seen exactly k times after h:

γ(h)=D1 N1(h∙)+D2 N2(h∙)+D3+ N3+(h∙)∑wc(h w)\gamma(h) = \frac{\begin{gathered} D_1\, N_1(h\bullet) + D_2\, N_2(h\bullet) \\ + D_{3+}\, N_{3+}(h\bullet) \end{gathered}}{\sum_w c(h\, w)}
Backoff weight of modified KN (Heafield et al. call it b)

Worked example

Reserved mass for one history

  1. The history

    A history h is followed by four word types with counts 1, 1, 2 and 5, so Σ c(hw) = 9.
  2. Reserved mass

    γ(h) = (0.625 × 2 + 1.0625 × 1 + 1.5 × 1) / 9 = 3.8125 / 9 = 0.4236. A single d = 0.75 would reserve 0.75 × 4 / 9 = 0.333.
  3. Discounted terms

    Count 5: 3.5 / 9 = 0.3889. Count 2: 0.9375 / 9 = 0.1042. Each count 1: 0.375 / 9 = 0.0417.
  4. Result

    The discounted terms sum to 0.5764, and adding γ(h) = 0.4236 gives exactly 1. Because D2 and D3+ exceed 0.75, the continuations seen 2 and 5 times free more mass, so this history reserves more for the lower order than a single d = 0.75 would.
AspectKneser-NeyModified Kneser-Ney
Discounts per order1 (d)3 (D1, D2, D3+)
How the discount is estimatedd = n1 / (n1 + 2 n2)Dk = k − (k+1) Y n(k+1) / n(k)
Reserved mass for history hd · N1+(h•) / Σ c(hw)(D1 N1 + D2 N2 + D3+ N3+) / Σ c(hw)
SRILM flag-ukndiscount-kndiscount
KenLMNot offeredlmplz (default)
Kneser-Ney against modified Kneser-Ney

Recall

Give the modified KN discount formulas.

Y = n1 / (n1 + 2 n2), D1 = 1 − 2Y n2/n1, D2 = 2 − 3Y n3/n2, D3+ = 3 − 4Y n4/n3, computed separately for each order.

Quick check

Why does modified Kneser-Ney use three discounts?

Quick check

With D1 = 0.625, D2 = 1.0625 and D3+ = 1.5, a history followed by four types with counts 1, 1, 2, 5 reserves how much mass?

Suppose you need a 5-gram language model for a translation or speech system. You do not implement the recursion yourself. You run one of two toolkits, and both build interpolated modified Kneser-Ney:

lmplz -o 5 <corpus.txt >model.arpa
ngram-count -order 5 -text corpus.txt -kndiscount -interpolate -lm model.arpa
KenLM and SRILM building the same kind of 5-gram model

The discounts are hyperparameters, but rarely hand-tuned ones. Both toolkits estimate them in closed form from the counts of counts of the training data, a separate set per order. They can also be tuned on a development set by minimizing perplexity, which is what the slide means by smoothing parameters tuned on held-out data. KenLM's documentation states that it estimates unpruned language models with modified Kneser-Ney smoothing, and its --discount_fallback option supplies 0.5, 1.0 and 1.5 for singletons, doubletons and higher counts when the counts of counts are unusable, for instance on tiny or deduplicated data.

KenLM and SRILM at a glance

KenLM smoothing
Interpolated modified Kneser-Ney, unpruned by default
KenLM command
lmplz -o 5 <text >model.arpa
KenLM fallback discounts
--discount_fallback uses 0.5, 1.0 and 1.5 when counts of counts are unusable
KenLM scale
126 billion tokens in 2.8 days on one machine with 140 GB RAM
SRILM command
ngram-count -order 5 -kndiscount -interpolate
SRILM variants
-kndiscountn modified, -ukndiscountn original, -interpolaten interpolated, per order n

Kneser-Ney shines at high orders. In a 5-gram model most 5-word contexts are seen once or never, so most predictions lean on the lower levels, and that is where continuation counts make the difference. This is the sparsity problem in its sharpest form. Chen and Goodman's study showed the advantages of modified interpolated Kneser-Ney, which became the standard n-gram baseline around the turn of the century. Goodman later reported that a combination of techniques including interpolated Kneser-Ney gave a 38% to 50% perplexity reduction against a Katz trigram, and an 8.9% word error rate reduction. At scale, Heafield and colleagues estimated an unpruned model on 126 billion tokens in 2.8 days on one machine with 140 GB of RAM, gaining 0.8 BLEU, and on 302 million tokens KenLM used 7.7% of SRILM's RAM and 14.0% of its wall time.

Quick check

Which SRILM option set builds the interpolated modified Kneser-Ney model taught in this part?

With a vocabulary of V = 50,000, a trigram model has V³ = 1.25 × 10^14 possible trigrams. Bengio and colleagues put it more starkly: modelling 10 consecutive words with V = 100,000 means 10^50 − 1 free parameters. And even a perfectly smoothed N-gram model that has read "the cat is walking in the bedroom" learns nothing about "a dog was running in a room", because none of its n-grams match.

These are the two walls. First, n-gram parameters grow exponentially in n, so longer contexts are almost never observed and smoothing has to do more and more of the work. Second, n-grams generalize only through exact matches: cat and dog are just different strings, so evidence about one never transfers to the other. Kneser-Ney makes the best of counts, but it cannot fix either problem, because both come from treating words as atomic symbols.

A count table needs an exact row; an embedding space puts cat near dog and bedroom near room

A Neural language model maps each word into a continuous vector space where similar words, and similar contexts, get similar vectors. A sentence about a cat then raises the probability of the same sentence about a dog, and the number of parameters grows only linearly with V and n. Bengio et al. reported test perplexity about 24% lower on Brown and about 8% lower on AP News than the best n-gram model on each corpus: a class-based model on Brown and modified Kneser-Ney backoff on AP News. Mixing the neural model with a trigram always helped further. Lecture 04 develops this idea of words as vectors: word embeddings. Transformer language models, later in the course, are the descendants of this idea.

Aspectn-gram KNNeural LM
ParametersUp to V^n counts, exponential in nGrow linearly with V and n
GeneralizationOnly through exact matches of the contextThrough similar vectors for similar words and contexts
Context lengthFixed and short (3 to 5 words in practice)Longer windows; later models use whole documents
ComputeCounting and lookup, very cheapTraining by gradient descent, far more expensive
Kneser-Ney n-gram models against neural language models

Recall

Why can no smoothing method, however good, let evidence about cat help predict dog?

Smoothing only moves probability mass among atomic symbols; it has no notion that two words are similar. Only a representation that places cat and dog near each other, as a neural LM's word vectors do, lets evidence transfer between them.

Recap

If you remember nothing else

  • P_KN(w|h) = max(c_KN(hw) − d, 0) / Σ_v c_KN(hv) + λ(h) P_KN(w|h'), with λ(h) = d × (distinct continuations of h) / Σ_v c_KN(hv).
  • c_KN is the raw count at the highest order and the continuation count (distinct left contexts) at every lower order, denominators included. N-grams that start with <s> keep raw counts.
  • The recursion ends with the unigram interpolated with uniform 1/V. <UNK> is a count-0 word and gets λ(ε)/V.
  • Modified KN uses D1, D2 and D3+ per order: Y = n1/(n1 + 2n2), Dk = k − (k+1) Y n_{k+1}/n_k. Each continuation type is discounted by the D of its count bucket, so the reserved mass depends on how often h's continuations were seen (D1 always equals the single-discount Y = n1/(n1 + 2n2)).
  • Interpolated modified KN is the standard n-gram baseline in KenLM (lmplz) and SRILM (-kndiscount -interpolate).
  • n-grams have exponentially many parameters and no generalization across similar words. Neural LMs fix both with continuous representations, beating the best n-gram model by about 24% perplexity on Brown (a class-based model) and 8% on AP News (modified KN backoff) in Bengio et al. 2003.

Sources

Part 10: Entropy, cross-entropy and chapter summary

Entropy as uncertainty in bits, cross-entropy of a model as an upper bound on true entropy, perplexity as two to the cross-entropy, and the chapter's key takeaways.

4 concepts, slides 102-105

Why this part matters

Perplexity looks like an arbitrary formula until you see that it is 2 raised to a cross-entropy measured in bits. That single identity explains why we invert the probability, why lower is better, why no model can beat the true entropy of the language, and why neural language models report their loss in nats and compute PPL = exp(loss).

It also turns perplexity into compression. A model that achieves 7 bits per word could, with an arithmetic coder, store text in about 7 bits per word, which is how Brown and colleagues turned a trigram model into an upper bound of 1.75 bits per character for English. The textbook marks this material as advanced, but exams regularly ask you to show that the two definitions of perplexity agree. The part ends with the whole chapter compressed into one chain of problems and fixes.

By the end you can

  1. Compute the entropy in bits of a small discrete distribution and read it as average surprise.
  2. Explain why the cross-entropy H(p, m) upper-bounds the true entropy H(p) and what the gap measures.
  3. Derive PP(W) = 2^H(W) = P(W)^(-1/N) and convert between bits, nats and perplexity.
  4. Recompute the 3-color perplexities (3 and 1.89) through entropy.
  5. Summarize the chapter as a chain of problems and the technique that fixes each one.

Entropy as average surprise in bits

Suppose you must radio the winner of a horse race to a bookie, using as few bits as possible. With 8 equally likely horses there is nothing to exploit: you label them 000 to 111 and spend 3 bits per race. Now suppose the odds are skewed: one horse wins half the time, the next a quarter, then an eighth, a sixteenth, and the last four 1/64 each. Give the favorite the one-bit code 0, the second 10, and so on down to six-bit codes for the long shots. Averaged over many races you now spend exactly 2 bits per race.

HorseProbabilityCodewordLength in bits
11/201
21/4102
31/81103
41/1611104
5 to 81/64 each111100, 111101, 111110, 1111116
A prefix code for the skewed race (SLP3 section 3.7)

The average length is 1/2(1) + 1/4(2) + 1/8(3) + 1/16(4) + 4/64(6) = 2. No code that can be decoded without ambiguity does better, and that floor has a name. The Entropy of a random variable is the average number of bits the best possible code needs per outcome:

H(X)=−∑xp(x)log⁡2p(x)H(X) = -\sum_x p(x)\log_2 p(x)
Entropy in bits (SLP3 eq. 3.32; Shannon 1948)

Read the formula in two pieces. The quantity -log2 p(x) is the surprise of outcome x: a sure thing (p = 1) has surprise 0, a coin flip has surprise 1 bit, and a 1/64 long shot has surprise 6 bits, exactly its codeword length above. Entropy is then the probability-weighted average of the surprise. With base 2 the unit is bits; with the natural log the same quantity comes out in nats.

Three color bars move from uniform to 0.8/0.1/0.1; each teal stick is -log2 p, short for red and tall for blue and green, and the dashed average falls from 1.58 to 0.92 bits

Now apply this to the 3-color language from the perplexity part, where the only words are red, blue and green. If all three are equally likely, every word carries log2 3 = 1.585 bits. If red has probability 0.8, red becomes cheap (0.322 bits) while blue and green become expensive (3.322 bits each), but because red is so common the average drops.

Worked example

Entropy of the 3-color language

  1. Uniform

    3 x (1/3)(log2 3) = log2 3 = 1.585 bits.
  2. Skewed, term by term

    0.8 x 0.322 + 2 x 0.1 x 3.322 = 0.258 + 0.664.
  3. Result

    H = 0.922 bits. Raising 2 to these values gives 3 and 1.89, the two perplexities you computed for this language from probabilities alone.
The flat depth-3 tree for 8 uniform horses dims while a lopsided prefix tree draws itself: codes 0, 10, 110, 1110 and four 6-bit leaves average 2 bits
DistributionH (bits)2^H
Fair coin12
0.9/0.1 coin0.4691.38
8 uniform horses38
Skewed horses (1/2, 1/4, 1/8, 1/16, 1/64 x4)24
3 uniform colors1.5853
0.8/0.1/0.1 colors0.9221.89
Entropy and two to the entropy for the distributions in this part

The last column is the bridge to the rest of the part. 2^H is the number of equally likely choices that would carry the same uncertainty: a 0.9/0.1 coin is as unpredictable as a fair die with 1.38 faces. That is exactly the weighted branching factor reading of Perplexity. Shannon used the Shannon game of guessing the next letter to estimate printed English at about 2.3 bits per letter with 8 letters of context, falling to something of the order of 1 bit per letter with about 100 letters of context. More context lowers entropy, which is the whole reason to condition on history.

Recall

Why is the uniform 8-horse race 3 bits but the skewed race only 2 bits?

Entropy is average surprise. In the uniform race every horse has surprise -log2(1/8) = 3. In the skewed race likely horses get short codes (the favorite at p = 1/2 gets the one-bit code 0), so the probability-weighted average code length falls to 2 bits.

Quick check

A model assigns P(red) = 0.8 and P(blue) = P(green) = 0.1. What is its entropy?

In real life we never know the true distribution p of a language. We only have a model m, and we can only observe how well m codes the data that p produces. Keep the color source fixed at p = (0.8, 0.1, 0.1) and score it with several models. Coding each word with lengths -log2 m(x) but drawing words from p gives an average cost per word of

H(p,m)=−∑xp(x)log⁡2m(x)H(p,m) = -\sum_x p(x)\log_2 m(x)
Cross-entropy: outcomes drawn from p, code lengths chosen by m
Model mH(p, m) in bitsGap over H(p)Perplexity 2^H(p,m)
Uniform (1/3, 1/3, 1/3)1.5850.6633
(0.6, 0.2, 0.2)1.0540.1322.08
Overconfident (0.9, 0.05, 0.05)0.9860.0641.98
m = p (0.8, 0.1, 0.1)0.92201.89
Cross-entropy of four models against the true source p = (0.8, 0.1, 0.1)

The pattern in the table is the content of slide 103. Every wrong model pays extra bits, including the overconfident one that gives red even more than its true share. The minimum, 0.922 bits, is reached only when m = p, and it equals the true Entropy. In general the Cross-entropy is an upper bound on the entropy:

H(p)≤H(p,m)=H(p)+DKL(p ∥ m)H(p) \le H(p,m) = H(p) + D_{\mathrm{KL}}(p \,\|\, m)
The gap is the KL divergence, which is never negative (Gibbs' inequality)

The gap is the Kullback-Leibler divergence, or relative entropy: the extra bits you pay for coding with the wrong codebook. Gibbs' inequality guarantees it is never negative and is zero only when the two distributions agree. That is why a lower cross-entropy means a better model, and also why no model can push its cross-entropy below the true entropy of the source.

A bits axis with the true entropy H(p) = 0.922 fixed in teal; the three model markers slide left toward it and stop short, and each gap is labelled as its KL divergence

Reverse the roles and the punishment becomes clear. Let the test data be uniform over the three colors and score it with the model (0.8, 0.1, 0.1). Two thirds of the words are ones the model thinks are rare, each costing 3.322 bits, so H = 2.32 bits and the perplexity is 5, worse than the honest uniform model at 3. A model that is confidently wrong is punished hard, and a model that gives an observed word probability 0 pays infinitely many bits, which is the zero problem seen from the information side.

From a distribution to one long test sequence

The sum over x needs p, which we do not have. The practical estimate, SLP3 eq. 3.42, scores one long test sequence W of N words and averages the Log probability:

H(W)=−1Nlog⁡2P(w1…wN)H(W) = -\tfrac{1}{N}\log_2 P(w_1\ldots w_N)
Per-word cross-entropy of the model on the test sequence W

The Shannon-McMillan-Breiman theorem says that for a stationary, ergodic source this average converges to the cross-entropy as N grows, so a long enough sample stands in for the sum over all sequences. Natural language is neither perfectly stationary nor perfectly ergodic, which is one reason the number is an estimate, but it is the number every paper reports. Exponentiate it and you get Perplexity:

PP(W)=2H(W)=P(w1…wN)−1/N\text{PP}(W) = 2^{H(W)} = P(w_1\ldots w_N)^{-1/N}
SLP3 eq. 3.42 and the perplexity identity

Worked example

Two perplexity definitions agree on red red red red blue

  1. Log probability under P(red) = 0.8, P(blue) = 0.1

    log2 P(W) = 4(-0.322) + (-3.322) = -4.610.
  2. Per-word cross-entropy

    H(W) = 4.610 / 5 = 0.922 bits per word.
  3. Exponentiate

    2^0.922 = 1.89.
  4. Direct definition

    P(W) = 0.8^4 x 0.1 = 0.04096, and 0.04096^(-1/5) = 1.89.
  5. Result

    Both routes give PP = 1.89. Under the uniform model the same sentence costs 1.585 bits per word and PP = 3.

Bits, nats, and real systems

UnitLog basePerplexityWhere you meet it
Bits2PP = 2^HTextbooks, compression, Shannon
NatsePP = e^HTraining loss in PyTorch and most neural LM code
Conversion1 nat = 1.4427 bitsH in bits = H in nats / ln 2
Bits against nats

Neural language models train on the average negative log-likelihood per token in nats, and report PPL = exp(loss). Hugging Face describes this as the exponentiation of the cross-entropy between the data and the model's predictions. A test loss of 3.0 nats per token is 3.0 / ln 2 = 4.33 bits, and both e^3 and 2^4.33 give a perplexity of about 20.1. The unit changes the cross-entropy number but never the perplexity. What does change it is the vocabulary: Hugging Face notes that tokenization affects perplexity, and SLP3 says perplexities are comparable only between models with identical vocabularies. A subword model and a word model are coding different symbols, so their per-symbol costs cannot be compared directly.

SimulatorEntropy, cross-entropy and perplexity on three colors
Model m
True source p
0.800
0.100
0.100
Model m
0.333
0.333
0.333
1 nat = 1.4427 bits. Perplexity is the same number in either unit.
H(p)0.922bits2^H = 1.89
H(p, m)1.585bits
KL gap0.663bitsnever negative
Perplexity3.002 to H(p, m)
P(W) to the -1/N3.000P(W) = 0.00412, N = 5
2 to the H(W)3.000H(W) = 1.585 bits per word

The bound also gives research a tool. Brown, Della Pietra, Della Pietra, Lai and Mercer trained a word trigram model on 583 million words and measured its cross-entropy on the Brown Corpus (about 5.96 million characters). The result, 1.75 bits per character, is an upper bound on the entropy of English precisely because H(p) <= H(p, m): whatever the true entropy is, it cannot be above what a real model already achieves.

Perplexity remains an Intrinsic evaluation measure: it tells you how well a model codes text, and gains in perplexity usually, but not always, carry over to downstream tasks.

Recall

Show that 2^H(W) equals P(W)^(-1/N).

With H(W) = -(1/N) log2 P(W), we get 2^H(W) = 2^(log2 P(W) x (-1/N)) = P(W)^(-1/N).

Recall

Why can a model's cross-entropy never be below the true entropy, and what does the gap mean?

H(p, m) = H(p) + KL(p || m), and the KL divergence is never negative (Gibbs' inequality). The gap measures how wrong the model is, in extra bits per symbol, and it is zero only when m = p.

Recall

A transformer reports a test loss of 3.0 nats per token. Give its perplexity and its cross-entropy in bits.

PP = e^3 = 20.1. In bits, 3 / ln 2 = 4.33, and 2^4.33 is also about 20.1.

Recall

The test set 'red red blue green' is scored by P(red) = 0.8, P(blue) = P(green) = 0.1. Give H(W) and PP.

log2 P = 2(-0.322) + 2(-3.322) = -7.288 over 4 words, so H(W) = 1.822 bits and PP = 2^1.822 = 3.54, matching 0.0064^(-1/4).

Quick check

A bigram model has a per-word cross-entropy of 7 bits on a test set. What is its perplexity?

Quick check

Model m1 scores 6.2 bits and model m2 scores 5.9 bits of cross-entropy on the same held-out text, with the same vocabulary. What follows?

Quick check

On slide 103, what must H(W) be for PP(W) = 2^H(W) to equal P(W)^(-1/N)?

Follow one sentence, "I want Chinese food", through everything this chapter built. A Language model must give it a probability. The Chain rule of probability writes that probability exactly as a product of next-word probabilities, each conditioned on the whole history, which no corpus can estimate. The Markov assumption cuts the history to a fixed window, so P(food | I want Chinese) becomes P(food | Chinese). Maximum likelihood estimation fills in those numbers by counting and normalizing in a training corpus. Then Sparsity strikes: some perfectly good bigram in a test sentence never appeared in training, its count is 0, and the whole sentence gets probability 0.

Model and count
P(food | Chinese) = C(Chinese food) / C(Chinese)

Exact chain rule, a fixed Markov window, then counts normalized in the training corpus.

A zero
C = 0

An unseen bigram sends the whole sentence to probability 0.

Repair, then score
add-k, interpolation, KN; PP = 2^H(W)

Move mass to the unseen (KN uses continuation counts), then report perplexity on held-out test data.

One sentence through the chapter: exact chain rule, Markov window, counts, a zero, the repair, the score

Smoothing repairs the zero. Add-k smoothing moves a fixed amount of mass to every event, Linear interpolation mixes trigram, bigram and unigram estimates, and Backoff drops to a shorter context only when the longer one has no evidence. Backing off to raw unigram frequency exposes the next failure: "Kong" is frequent, but almost only after "Hong", so it should not be a strong guess after an unfamiliar context, while "glasses" follows many different words. Kneser-Ney smoothing replaces the unigram with a Continuation probability that counts how many contexts a word completes. A single discount still fits poorly, because counts of 1, 2 and 3 or more need different amounts removed, so Modified Kneser-Ney uses three discounts, D1, D2 and D3+.

Every step is judged the same way. Tune choices such as k or the interpolation weights on a Development set, then report Perplexity once on the Test set, which, as the previous concept showed, is 2 to the per-word cross-entropy. It is the standard Intrinsic evaluation metric, and lower is better because it means fewer bits of surprise per word. Sampling from an LM from the model shows what it learned in a way numbers cannot, including Overfitting: a 4-gram model trained on Shakespeare mostly reproduces Shakespeare.

ProblemFixSlides
Full history is intractableMarkov assumption13 to 14
Probabilities are unknownMLE from counts17 to 21
Need to judge modelsPerplexity on test data, tuning on dev data29 to 41
Need to see what was learnedSampling42 to 56
Unseen n-grams get zeroSmoothing: add-k, interpolation, backoff58 to 74
Unigram backoff overrates words like KongContinuation probability (Kneser-Ney)81 to 97
One discount fits counts 1, 2 and 3+ poorlyModified KN with D1, D2, D3+98 to 99
Problem, fix, and the slides where it appears

Recall

Match each failure to its fix: zeros, 'Kong' overrated in backoff, one discount fits poorly.

Zeros go to smoothing (add-k, interpolation, backoff). The "Kong" problem goes to the Kneser-Ney continuation probability. The single-discount problem goes to modified KN with D1, D2 and D3+.

The lecture follows Jurafsky and Martin's Speech and Language Processing, third edition, chapter 3, and slide 105 credits the manuscript dated January 6, 2026. That citation was correct when the slides were made, but SLP3 is a living draft published chapter by chapter on the authors' site, and the copy at the same address is now dated August 19, 2026.

For deeper reading on this part, go to the sources themselves: Shannon's 1948 paper defines entropy and the coding theorem behind it, his 1951 paper runs the guessing game on printed English, and Brown et al. (1992) shows how a language model becomes an upper bound on the entropy of a language. MacKay's free textbook covers relative entropy and Gibbs' inequality in chapter 2.

Recap

If you remember nothing else

  • H(X) = -sum p log2 p is average surprise in bits: 3 bits for 8 uniform horses, 2 bits for the skewed race, 0.922 bits for the 0.8/0.1/0.1 colors.
  • The cross-entropy of a model m, H(p, m) = -sum p log2 m, is always at least H(p). The gap is the KL divergence, so the better model has the lower cross-entropy.
  • Estimate it on one long test sequence: H(W) = -(1/N) log2 P(w1...wN). Then PP(W) = 2^H(W) = P(W)^(-1/N).
  • Slide 103 leaves H(W) undefined. It is the model's per-word cross-entropy on W, not the true entropy of W.
  • Neural LMs work in nats: PPL = exp(mean NLL). Perplexities compare only with identical vocabularies and tokenization.
  • Chapter chain: chain rule, Markov window, MLE counts, sparsity and zeros, smoothing (add-k, interpolation, backoff), Kneser-Ney continuation, modified KN discounts, all judged by perplexity on held-out data.

Sources