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 -gram model parameterises by truncating the conditioning context to the last 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 -grams can't be the answer:
- Sparsity. Most -grams never appear, even in massive corpora.
- Parameter explosion. Storage is , useless for at LLM-scale vocabularies.
- Fixed range. Any dependency longer than 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:
The conditional in principle depends on the entire prefix . The -gram approximation truncates this conditioning to the last tokens:
This is the Markov assumption of order . Names:
- : unigram. — no conditioning at all. Bag of words.
- : bigram. — depends on the immediately preceding token.
- : trigram. .
The full conditioning is recovered only in the limit , which is not a useful model.
2.1 Parameter count
Under the bigram assumption, is a matrix: one row per possible , each row a distribution over next-token possibilities. Number of free parameters (after the constraint per row): .
For an -gram, the conditioning context takes values, and each value has a -way distribution. Free parameters: for large.
For , even a trigram has parameters. Practical -grams use much smaller vocabularies (characters, or word-level with ).
3. Maximum-likelihood estimation: counting
For a fixed corpus , define the count of any contiguous -token sequence as
The MLE for the bigram probability is the ratio:
(Compare with the multinomial MLE of 0.7 §4: given counts, the maximum-likelihood probability is the count proportion.) For a general -gram:
This is the entire "training" procedure. Count the -grams in the corpus, divide by the -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 copies of a special <bos> token and append one <eos>. Bigram example: the sentence "the cat sat" becomes the token sequence
generating four bigrams: , , , . The token makes the model assign a probability to "the sentence ends here" — necessary so that the joint is a normalised distribution over sequences of any length.
4. A worked bigram
Take the toy corpus (sentence boundaries already inserted):
(Three sentences, 18 tokens excluding boundaries.) Count unigrams and bigrams:
Some bigrams of interest:
Bigram MLEs:
4.1 Probability of a new sentence
Use the model to score the candidate sentence "Sam I am":
All four bigrams appear in the corpus, with counts respectively and denominator counts :
4.2 Probability of an unseen bigram
Now try "I like ham":
The model assigns probability zero to any sentence containing the bigram — 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 . This is the sparsity problem.
5. Why MLE breaks: sparsity and smoothing
Most -grams of length never appear in any finite corpus. Heaps' law estimates the number of distinct -grams in a corpus of size at with : vocabulary growth is sub-linear, but grows exponentially in . By 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:
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 -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 -grams to neural LMs.
[4]6. Structural limits of -grams
Beyond sparsity, three structural facts box -grams in:
(a) Fixed range. The Markov assumption guarantees that any dependency longer than tokens is invisible. The model cannot resolve
The trophy did not fit in the suitcase because was too big.
The disambiguator (whether 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 -gram with can see the relevant context. Increasing to fix this triggers parameter explosion.
(b) No compositionality. and 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; -grams cannot.
(c) No syntactic generalisation. If the corpus contains but not , the model has no reason to assign similar probabilities. Embeddings give the second a "similar" distribution because and 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 -gram era:
- The left-to-right autoregressive factorisation is correct and reusable — neural LMs inherit it directly.
- Perplexity as a comparison metric comes from this era. Smoothed-trigram perplexities on news text were ; modern LLMs achieve .
The -gram baseline gives us a number to beat. Every architecture from Chapter 5.5 onward is, mathematically, a parameterisation of 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.
(a) Compute the bigram MLE table for all pairs that have 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 tokens with vocabulary size . Approximately how many of the possible bigrams will have non-zero count when and ? (Use Heaps' law or an order-of-magnitude estimate.)
(d) Apply Laplace add-one smoothing to the bigram in the toy corpus with (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 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 ? What does this imply about the usefulness of an MLE trigram at LLM scale?
References
- [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]
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]
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]
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).
↩