A language model is a counting machine first
Before attention, before transformers, before embeddings, the standard way to score a sentence was to count how often its fragments appear in a corpus and divide. An n-gram model says that the probability of a word depends only on the previous nā1 words, which throws away most of a sentence's structure and keeps enough to produce text that reads as locally fluent. The approximation is called the Markov assumption, and it is the reason these models are cheap to build, easy to debug, and still used today for spelling correction, autocomplete, and code completion on devices with no GPU.
The chain rule of probability lets you factor any sentence into a product of conditional probabilities. Truncating each condition to the last nā1 words converts an impossible estimation problem into a lookup table, and everything else in this lesson follows from filling that table honestly ā which means confronting the fact that most rows will be empty.
Extracting n-grams from a corpus
An n-gram is simply a contiguous window of n items. Unigrams ignore order entirely, bigrams capture immediate adjacency, and trigrams begin to encode short idioms like of the and as well as. Before counting anything you must decide how sentence boundaries are represented, because a bigram that spans two sentences teaches the model that the last word of one sentence predicts the first word of the next.
from collections import Counter, defaultdict
from itertools import islice
def tokenize_corpus(lines, pad=1):
out = []
for line in lines:
words = line.lower().strip().split()
if words:
out.append(["<s>"] * pad + words + ["</s>"])
return out
def ngrams(tokens, n):
for i in range(len(tokens) - n + 1):
yield tuple(tokens[i:i + n])
sentences = tokenize_corpus([
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
])
tokens = [t for s in sentences for t in s]
bigrams = Counter(ngrams(tokens, 2))
unigrams = Counter(ngrams(tokens, 1))
print("distinct bigrams:", len(bigrams))
print("total tokens:", sum(unigrams.values()))
for (a, b), c in bigrams.most_common(4):
print(f"P({b} | {a}) raw = {c}")
The count of a bigram divided by the count of its first word is the maximum-likelihood bigram estimate. It is unbiased under the model's assumptions, which is exactly why it fails when the data is sparse: any pair you have never observed gets probability zero.
The zero-probability problem
A bigram model over a 10,000-word vocabulary has up to 100,000,000 possible pairs, and a ten-million-word corpus fills a fraction of a percent of them. Worse, the unseen pairs are not uniformly distributed ā they include precisely the rare but legitimate combinations a model will meet at inference time. A single zero in the product collapses the probability of an entire sentence to zero, and a single zero in the log sum sends perplexity to infinity.
| Smoothing rule | Adjustment | Character |
|---|---|---|
| Add-one (Laplace) | Add 1 to every count, V to the denominator | Simple, flattens distribution badly |
| Add-k | Add a tuned constant k less than 1 | Less flattening, one hyperparameter |
| Good-Turing | Reassign mass from seen to unseen by frequency of frequencies | Elegant, data driven |
| Kneser-Ney | Discounted mass weighted by number of distinct continuations | Strongest general-purpose choice |
| Stupid Backoff | Interpolate with a lower order at a fixed penalty | Web-scale, no normalization needed |
import math
class NGramModel:
def __init__(self, n=2):
self.n = n
self.cond = defaultdict(Counter)
self.ctx = Counter()
self.uni = Counter()
self.V = 0
def train(self, corpus):
for sentence in corpus:
toks = ["<s>"] * (self.n - 1) + sentence + ["</s>"]
self.uni.update(toks)
self.V = len(self.uni)
for i in range(self.n - 1, len(toks)):
ctx = tuple(toks[i - self.n + 1:i])
self.cond[ctx][toks[i]] += 1
self.ctx[ctx] += 1
def prob_mle(self, word, ctx):
return self.cond[ctx][word] / self.ctx[ctx]
def prob_laplace(self, word, ctx, alpha=1.0):
return (self.cond[ctx][word] + alpha) / (
self.ctx[ctx] + alpha * self.V
)
def prob_interpolated(self, word, ctx, lam=0.7):
if not ctx:
return self.uni[word] / sum(self.uni.values())
lower = self.prob_interpolated(word, ctx[1:], lam)
bigram = self.cond[ctx][word] / max(self.ctx[ctx], 1)
return lam * bigram + (1 - lam) * lower
model = NGramModel(n=2)
model.train([["the", "cat", "sat"], ["the", "dog", "sat"], ["the", "cat", "chased"]])
print("P(sat|the) MLE:", round(model.prob_mle("sat", ("the",)), 3))
print("P(sat|the) laplace:", round(model.prob_laplace("sat", ("the",)), 3))
print("P(zzz|the) laplace:", round(model.prob_laplace("zzz", ("the",)), 6))
Laplace smoothing is the right first implementation and the wrong final one: adding one occurrence to every possible bigram in a 10,000-word vocabulary moves more probability mass onto nonsense than onto legitimate unseen events. Interpolation and backoff both fix this by delegating to a lower-order model instead of inventing mass from nothing.
Why Kneser-Ney works better
The standard fix takes the discounted mass from higher orders and redistributes it according to a continuation probability: rather than asking how often the precedes coffee, it asks how many different words can follow the at all. This matters because a word like coffee appears in many contexts but rarely as a sentence starter, and plain interpolation over-credits it. Kneser-Ney consistently wins bake-offs on perplexity, and the interpolated variant is the one implemented in every serious n-gram toolkit.
Interpolation and backoff are different strategies
Two families of fixes exist and they fail in different ways. Interpolation always blends every order together: the trigram estimate is mixed with a weighted bigram estimate, which is mixed with a unigram estimate, so probability is never delegated, it is averaged. This guarantees a normalized distribution and makes tuning a single set of weights, but it also means a strong trigram observation is always diluted by weaker evidence. Backoff instead trusts the highest order that has enough evidence and only falls through to a lower order when it does not, which preserves strong signals but requires careful normalization so the final distribution still sums to one. The choice shows up most clearly on idioms: as well as is common enough that interpolation with a weak unigram model visibly drags its probability down, while a backoff scheme reports the trigram almost unchanged. Interpolated Kneser-Ney is the practical synthesis, because it backoffs only the discounted remainder and interpolates the continuation term, giving the best of both behaviours with one set of hyperparameters.
Evaluating with perplexity
Perplexity is the exponentiated average negative log likelihood of a test set. A model that assigns probability 0.5 to each next token has perplexity 2, meaning it is on average choosing between two candidates; a model with perplexity 100 is choosing among a hundred. Lower is better, and perplexity is comparable across models only when they share the same tokenization and the same test set.
import math
def perplexity(model, test_corpus, alpha=1.0, smoothed=True):
log_sum, n_tokens = 0.0, 0
for sentence in test_corpus:
toks = ["<s>"] * (model.n - 1) + sentence + ["</s>"]
for i in range(model.n - 1, len(toks)):
ctx = tuple(toks[i - model.n + 1:i])
p = (model.prob_laplace(toks[i], ctx, alpha) if smoothed
else model.prob_mle(toks[i], ctx))
log_sum += math.log2(max(p, 1e-12))
n_tokens += 1
return 2 ** (-log_sum / n_tokens)
test = [["the", "cat", "sat"], ["the", "dog", "chased"]]
print("smoothed ppl:", round(perplexity(model, test), 3))
print("raw MLE ppl:", round(perplexity(model, test, smoothed=False), 3))
Two traps make perplexity misleading. Comparing across different tokenizers is meaningless, because a model that splits words into more pieces gets an easier per-token prediction task. And evaluating only on in-domain text hides the real failure: an n-gram model trained on news will show excellent perplexity on news and collapse the moment a user types a question.
Choosing n in practice
There is also a data-efficiency argument to weigh. A trigram model needs roughly an order of magnitude more text than a bigram model to populate its table to the same relative density, so on a corpus of one million words the extra context bought by n = 3 is frequently outweighed by the extra rows left empty. Practitioners therefore raise n only when the corpus grows with it, and even then cap the order at five, because beyond that the fraction of observed n-grams falls below the level where counting still beats guessing. When you must cover a large vocabulary on modest data, the winning configuration is usually a lower n combined with strong smoothing rather than a higher n with weak smoothing ā the evidence simply is not there to support the longer condition.
| n | Context captured | Parameter growth | Typical use |
|---|---|---|---|
| 1 | None | V | Baseline, stopword analysis |
| 2 | One previous word | V squared | Spell correction, autocomplete |
| 3 | Two previous words | V cubed | Phrase detection, local fluency |
| 4ā5 | Short idioms | Explodes | Statistical MT, legacy ASR |
Every step up in n buys a little more context and costs an order of magnitude more sparsity. Real systems therefore cap n at three or five, smooth aggressively, and ā since roughly 2016 ā treat n-grams as the fallback rather than the frontier.
ā ļøNever evaluate on your training sentences
Common Mistakes
Letting an unseen bigram produce probability zero
Fix: Smooth or interpolate; one zero in the product annihilates the whole sentence probability.
Comparing perplexity across different tokenizers
Fix: Perplexity is only comparable for identical vocabularies and identical test sets.
Using add-one smoothing as the final production rule
Fix: It moves most probability mass onto nonsense; use interpolated Kneser-Ney or simple backoff instead.
Forgetting sentence boundary tokens during training
Fix: Pad with explicit sentence-start and sentence-end markers so the model does not learn that sentence-final words predict sentence-initial ones.
Best Practices
- Cap n at three or five and spend the remaining budget on smoothing quality
- Store counts as integer maps and convert to probabilities lazily to keep memory flat
- Report perplexity together with a downstream metric, since the two can disagree
- Interpolate orders explicitly so higher n never has to stand alone on sparse evidence
Interview Questions
Q1: Why does an n-gram model assign zero probability to unseen pairs?
Maximum-likelihood estimation divides the observed count by the context count, and an unobserved pair has numerator zero; with up to V to the n possible n-grams and a finite corpus, most entries are unobserved.
Q2: What problem does Kneser-Ney smoothing solve that Laplace does not?
Laplace spreads mass uniformly over the vocabulary, while Kneser-Ney redistributes it by continuation probability, favouring words that appear in many distinct contexts rather than words that are simply frequent.
Q3: Why does perplexity depend on tokenization?
It is the geometric mean of per-token inverse probabilities, so a finer tokenization makes each prediction task easier and lowers perplexity without improving the model's actual language ability.
Key Takeaways
- n-grams approximate the chain rule by assuming a word depends only on the previous nā1 words
- Maximum-likelihood counts are unbiased but guarantee zero probability for unobserved n-grams
- Smoothing redistributes mass: Laplace is naive, interpolation is better, Kneser-Ney is best
- Perplexity is exponentiated average negative log likelihood and is only comparable within one tokenization
- Sparsity grows with n, so production systems pair a modest n with strong smoothing and a backoff path