AI / ML Theory
Chapter 5 · 18 min

5.4 — N-gram models as a baseline

Goal: Build an n-gram language model from scratch, compute it on a toy corpus, and quantify the structural reasons it cannot scale: data sparsity, exponential parameter growth, and a fixed range that throws away any longer dependency.

1. Why this session exists

Before we deploy neural language models, we should know what the simplest baseline gives. An nn-gram model parameterises p(xt∣x<t)p(x_t \mid x_{<t}) by truncating the conditioning context to the last n−1n - 1 tokens and using an empirical estimate from a corpus. It has no parameters to train in the gradient-descent sense: the "training" is just counting.

Computing one on a toy corpus reveals the three reasons nn-grams can't be the answer:

  1. Sparsity. Most nn-grams never appear, even in massive corpora.
  2. Parameter explosion. Storage is Θ(Vn)\Theta(V^n), useless for n≥3n \ge 3 at LLM-scale vocabularies.
  3. Fixed range. Any dependency longer than n−1n - 1 tokens is mathematically inaccessible to the model.

These limits — and how badly they bite — are what a neural language model has to overcome.[1, 3]


2. The Markov assumption

Section 5.3 gave the universal autoregressive factorisation:

p(x1,…,xT)=∏t=1Tp(xt∣x<t).p(x_1, \dots, x_T) = \prod_{t=1}^{T} p(x_t \mid x_{<t}).

The conditional p(xt∣x<t)p(x_t \mid x_{<t}) in principle depends on the entire prefix x1,…,xt−1x_1, \dots, x_{t-1}. The nn-gram approximation truncates this conditioning to the last n−1n - 1 tokens:

 p(xt∣x<t)≈p(xt∣xt−n+1,xt−n+2,…,xt−1). \boxed{\ p(x_t \mid x_{<t}) \approx p(x_t \mid x_{t - n + 1}, x_{t - n + 2}, \dots, x_{t - 1}). \ }

This is the Markov assumption of order n−1n - 1. Names:

  • n=1n = 1: unigram. p(xt)p(x_t) — no conditioning at all. Bag of words.
  • n=2n = 2: bigram. p(xt∣xt−1)p(x_t \mid x_{t-1}) — depends on the immediately preceding token.
  • n=3n = 3: trigram. p(xt∣xt−2,xt−1)p(x_t \mid x_{t-2}, x_{t-1}).

The full conditioning is recovered only in the limit n→Tn \to T, which is not a useful model.

2.1 Parameter count

Under the bigram assumption, p(xt∣xt−1)p(x_t \mid x_{t-1}) is a V×VV \times V matrix: one row per possible xt−1x_{t-1}, each row a distribution over VV next-token possibilities. Number of free parameters (after the ∑kp(⋅∣xt−1)=1\sum_k p(\cdot \mid x_{t-1}) = 1 constraint per row): V(V−1)V(V - 1).

For an nn-gram, the conditioning context (xt−n+1,…,xt−1)(x_{t-n+1}, \dots, x_{t-1}) takes Vn−1V^{n-1} values, and each value has a VV-way distribution. Free parameters: Vn−1(V−1)≈VnV^{n-1}(V - 1) \approx V^n for VV large.

For V=50,000V = 50{,}000, even a trigram has ∼1014\sim 10^{14} parameters. Practical nn-grams use much smaller vocabularies (characters, or word-level with V≈10,000V \approx 10{,}000).


3. Maximum-likelihood estimation: counting

For a fixed corpus C\mathcal{C}, define the count of any contiguous kk-token sequence (w1,…,wk)(w_1, \dots, w_k) as

c(w1,…,wk)=number of times (w1,…,wk) appears in C.c(w_1, \dots, w_k) = \text{number of times } (w_1, \dots, w_k) \text{ appears in } \mathcal{C}.

The MLE for the bigram probability is the ratio:

 p^(xt=b∣xt−1=a)=c(a,b)c(a). \boxed{\ \hat p(x_t = b \mid x_{t-1} = a) = \frac{c(a, b)}{c(a)}. \ }

(Compare with the multinomial MLE of 0.7 §4: given counts, the maximum-likelihood probability is the count proportion.) For a general nn-gram:

p^(xt∣xt−n+1,…,xt−1)=c(xt−n+1,…,xt)c(xt−n+1,…,xt−1).\hat p(x_t \mid x_{t-n+1}, \dots, x_{t-1}) = \frac{c(x_{t-n+1}, \dots, x_t)}{c(x_{t-n+1}, \dots, x_{t-1})}.

This is the entire "training" procedure. Count the nn-grams in the corpus, divide by the (n−1)(n-1)-gram counts in the conditioning context, store the table.

3.1 Special sentence-boundary tokens

To make the model handle the start and end of a sentence, prepend n−1n - 1 copies of a special <bos> token and append one <eos>. Bigram example: the sentence "the cat sat" becomes the token sequence

⟨bos⟩, the, cat, sat, ⟨eos⟩,\langle\text{bos}\rangle,\ \text{the},\ \text{cat},\ \text{sat},\ \langle\text{eos}\rangle,

generating four bigrams: (bos,the)(\text{bos}, \text{the}), (the,cat)(\text{the}, \text{cat}), (cat,sat)(\text{cat}, \text{sat}), (sat,eos)(\text{sat}, \text{eos}). The ⟨eos⟩\langle\text{eos}\rangle token makes the model assign a probability to "the sentence ends here" — necessary so that the joint p(x1,…,xT)p(x_1, \dots, x_T) is a normalised distribution over sequences of any length.


4. A worked bigram

Take the toy corpus (sentence boundaries already inserted):

C={ ⟨bos⟩, I, am, Sam, ⟨eos⟩, ⟨bos⟩, Sam, I, am, ⟨eos⟩, ⟨bos⟩, I, do, not, like, green, eggs, and, ham, ⟨eos⟩ }.\mathcal{C} = \{\ \langle\text{bos}\rangle,\ \text{I},\ \text{am},\ \text{Sam},\ \langle\text{eos}\rangle,\ \langle\text{bos}\rangle,\ \text{Sam},\ \text{I},\ \text{am},\ \langle\text{eos}\rangle,\ \langle\text{bos}\rangle,\ \text{I},\ \text{do},\ \text{not},\ \text{like},\ \text{green},\ \text{eggs},\ \text{and},\ \text{ham},\ \langle\text{eos}\rangle\ \}.

(Three sentences, 18 tokens excluding boundaries.) Count unigrams and bigrams:

c(⟨bos⟩)=3,c(I)=3,c(am)=2,c(Sam)=2,c(do)=1,c(not)=1,c(like)=1,c(green)=1,c(eggs)=1,c(and)=1,c(ham)=1,c(⟨eos⟩)=3.\begin{aligned} c(\langle\text{bos}\rangle) &= 3, & c(\text{I}) &= 3, & c(\text{am}) &= 2, & c(\text{Sam}) &= 2, \\ c(\text{do}) &= 1, & c(\text{not}) &= 1, & c(\text{like}) &= 1, & c(\text{green}) &= 1, \\ c(\text{eggs}) &= 1, & c(\text{and}) &= 1, & c(\text{ham}) &= 1, & c(\langle\text{eos}\rangle) &= 3. \end{aligned}

Some bigrams of interest:

c(⟨bos⟩,I)=2,c(⟨bos⟩,Sam)=1,c(I,am)=2,c(I,do)=1,c(am,Sam)=1,c(am,⟨eos⟩)=1,c(Sam,I)=1,c(Sam,⟨eos⟩)=1.\begin{aligned} c(\langle\text{bos}\rangle, \text{I}) &= 2, & c(\langle\text{bos}\rangle, \text{Sam}) &= 1, \\ c(\text{I}, \text{am}) &= 2, & c(\text{I}, \text{do}) &= 1, \\ c(\text{am}, \text{Sam}) &= 1, & c(\text{am}, \langle\text{eos}\rangle) &= 1, \\ c(\text{Sam}, \text{I}) &= 1, & c(\text{Sam}, \langle\text{eos}\rangle) &= 1. \end{aligned}

Bigram MLEs:

p^(I∣⟨bos⟩)=23,p^(Sam∣⟨bos⟩)=13.\hat p(\text{I} \mid \langle\text{bos}\rangle) = \frac{2}{3}, \qquad \hat p(\text{Sam} \mid \langle\text{bos}\rangle) = \frac{1}{3}. p^(am∣I)=23,p^(do∣I)=13.\hat p(\text{am} \mid \text{I}) = \frac{2}{3}, \qquad \hat p(\text{do} \mid \text{I}) = \frac{1}{3}. p^(Sam∣am)=12,p^(⟨eos⟩∣am)=12.\hat p(\text{Sam} \mid \text{am}) = \frac{1}{2}, \qquad \hat p(\langle\text{eos}\rangle \mid \text{am}) = \frac{1}{2}.

4.1 Probability of a new sentence

Use the model to score the candidate sentence "Sam I am":

p^(⟨bos⟩, Sam, I, am, ⟨eos⟩)=p^(Sam∣⟨bos⟩)⋅p^(I∣Sam)⋅p^(am∣I)⋅p^(⟨eos⟩∣am).\hat p(\langle\text{bos}\rangle,\ \text{Sam},\ \text{I},\ \text{am},\ \langle\text{eos}\rangle) = \hat p(\text{Sam} \mid \langle\text{bos}\rangle) \cdot \hat p(\text{I} \mid \text{Sam}) \cdot \hat p(\text{am} \mid \text{I}) \cdot \hat p(\langle\text{eos}\rangle \mid \text{am}).

All four bigrams appear in the corpus, with counts 1,1,2,11, 1, 2, 1 respectively and denominator counts 3,2,3,23, 2, 3, 2:

=13⋅12⋅23⋅12=118.= \frac{1}{3} \cdot \frac{1}{2} \cdot \frac{2}{3} \cdot \frac{1}{2} = \frac{1}{18}.

4.2 Probability of an unseen bigram

Now try "I like ham":

p^(like∣I)=c(I,like)c(I)=03=0.\hat p(\text{like} \mid \text{I}) = \frac{c(\text{I}, \text{like})}{c(\text{I})} = \frac{0}{3} = 0.

The model assigns probability zero to any sentence containing the bigram (I,like)(\text{I}, \text{like}) — even though both "I" and "like" appear in the corpus, just never adjacent. The joint probability of the sentence is exactly zero, and the cross-entropy loss is +∞+\infty. This is the sparsity problem.


5. Why MLE breaks: sparsity and smoothing

Most nn-grams of length n≥2n \ge 2 never appear in any finite corpus. Heaps' law estimates the number of distinct nn-grams in a corpus of size NN at ∝Nβ\propto N^\beta with β∈(0,1)\beta \in (0, 1): vocabulary growth is sub-linear, but VnV^n grows exponentially in nn. By n=3n = 3 the fraction of valid trigrams in even a billion-token corpus is tiny.

The classical fix is smoothing — redistribute a small amount of probability mass to unseen events. The simplest is Laplace add-one:

p^add-1(b∣a)=c(a,b)+1c(a)+V.\hat p_\text{add-1}(b \mid a) = \frac{c(a, b) + 1}{c(a) + V}.

This guarantees every bigram gets positive probability, at the cost of a heavy bias toward unseen events. More sophisticated methods — Kneser–Ney smoothing, interpolation, backoff — improved the state of the art through the 1990s and 2000s. None of them solve the underlying structural problem: probability mass for unseen nn-grams is allocated by prior (uniform, or based on lower-order counts), not by generalisation from similar contexts.

A neural language model, by contrast, generalises through the embedding geometry of 5.2: tokens that play similar grammatical or semantic roles get similar embeddings, and the network interpolates its predictions across the embedding space. An unseen bigram still receives a meaningful probability because the embeddings of its constituents place them near seen patterns. That single capability — generalisation via continuous representations rather than discrete counting — is the qualitative jump from nn-grams to neural LMs.

[4]

6. Structural limits of nn-grams

Beyond sparsity, three structural facts box nn-grams in:

(a) Fixed range. The Markov assumption guarantees that any dependency longer than n−1n - 1 tokens is invisible. The model cannot resolve

The trophy did not fit in the suitcase because \rule{1cm}{0.4pt} was too big.

The disambiguator (whether \rule{1cm}{0.4pt} is "it" referring to the trophy or the suitcase) depends on the verb "big" nine tokens later and the noun "trophy" eight tokens earlier. No nn-gram with n≤8n \le 8 can see the relevant context. Increasing nn to fix this triggers parameter explosion.

(b) No compositionality. (the, red, car)(\text{the},\ \text{red},\ \text{car}) and (a, red, car)(\text{a},\ \text{red},\ \text{car}) are unrelated trigrams to the model. There is no notion that the determiner and the noun phrase have separate roles. Neural models share representations across context via the embedding matrix; nn-grams cannot.

(c) No syntactic generalisation. If the corpus contains (the, cat, sat)(\text{the},\ \text{cat},\ \text{sat}) but not (the, dog, sat)(\text{the},\ \text{dog},\ \text{sat}), the model has no reason to assign similar probabilities. Embeddings give the second a "similar" distribution because dog\text{dog} and cat\text{cat} are nearby in embedding space.

These three deficits motivate the move to neural language models, which Bengio et al. (2003) pioneered and which became the universal architecture by the late 2010s.


7. What we keep going forward

Two durable lessons from the nn-gram era:

  1. The left-to-right autoregressive factorisation is correct and reusable — neural LMs inherit it directly.
  2. Perplexity as a comparison metric comes from this era. Smoothed-trigram perplexities on news text were ∼200\sim 200; modern LLMs achieve ∼10\sim 10.

The nn-gram baseline gives us a number to beat. Every architecture from Chapter 5.5 onward is, mathematically, a parameterisation of p(xt∣x<t)p(x_t \mid x_{<t}) designed to fix the limitations above — parameter sharing across contexts (embeddings), unbounded conditioning (RNNs in §5.5, attention in §6), and generalisation via continuous representations.

Self-test

(a) Compute the bigram MLE table p^(b∣a)\hat p(b \mid a) for all a,ba, b pairs that have c(a)>0c(a) > 0 in the toy corpus of §4. Verify that each row sums to 1.

(b) Compute the probability of the sentence "I am Sam" under the bigram MLE, and compare it to the probability of "Sam I am" computed in §4.1. Which sentence does the model prefer? Why?

(c) Suppose you train a bigram on a corpus of NN tokens with vocabulary size VV. Approximately how many of the V2V^2 possible bigrams will have non-zero count when V=104V = 10^4 and N=106N = 10^6? (Use Heaps' law or an order-of-magnitude estimate.)

(d) Apply Laplace add-one smoothing to the bigram (I,like)(\text{I}, \text{like}) in the toy corpus with V=12V = 12 (counting all the distinct tokens in §4 including boundaries). What probability does the smoothed model assign? What probability does an unsmoothed bigram assign?

(e) A trigram language model on a vocabulary of size V=50,000V = 50{,}000 would have how many parameters in principle? How many of those are realistically estimable from a 1 trillion-token corpus, if Heaps' law says the count of distinct trigrams is ∼(1012)0.6≈4⋅107\sim (10^{12})^{0.6} \approx 4 \cdot 10^7? What does this imply about the usefulness of an MLE trigram at LLM scale?


References

  1. [1]

    Jurafsky, D., & Martin, J. H. (2024). Speech and Language Processing (3rd ed., draft). — Canonical reference for tokenisation (5.1), n-grams and smoothing (5.4), and language-modeling fundamentals (5.3). stanford.edu/~jurafsky/slp3

    ↩
  2. [2]

    Bengio, Y., Ducharme, R., Vincent, P., & Jauvin, C. (2003). "A neural probabilistic language model". JMLR, 3, 1137–1155. — First neural LM with learned word embeddings; the conceptual ancestor of every modern LLM (5.2, 5.4).

    ↩
  3. [3]

    Karpathy, A. "Neural Networks: Zero to Hero" lecture series, especially makemore (Lectures 2–5). karpathy.ai/zero-to-hero — Worked examples of bigrams, embeddings, and character-level LMs (5.4).

    ↩
  4. [4]

    Kudo, T., & Richardson, J. (2018). "SentencePiece: A simple and language independent subword tokenizer and detokenizer for neural text processing". arXiv:1808.06226 — SentencePiece (BPE-mode and unigram-mode) (7.2 §5.4).

    ↩