Majid Al-RaimiN-grams, the chain rule and the Markov assumption

ICS 582Lecture 03Part 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.

Concepts
6
Slides
10-16
Reading
36 min
Understood
0/6 concepts

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