n-gram Language Models and Perplexity
A language model assigns a probability to a sequence of words. With the chain rule, any sequence probability splits into next-word predictions:
Language Modeling as Next-Token Prediction derives this factorisation and the cross-entropy objective, and Perplexity defines the metric. This lesson builds the model that ruled speech recognition, spelling correction and machine translation for three decades before neural networks: the count-based -gram model. It is worth building for three reasons. It is a baseline any neural LM must beat. Its failure, sparsity, is exactly what neural LMs fix. And every engineering question of modern LMs (held-out evaluation, smoothing as regularisation, sampling, memorisation) shows up here in a form you can compute by hand.
The Markov assumption and counting
An -gram model keeps only the last words of the history:
With (bigram) the next word depends on the previous word, with (trigram) on the previous two. The maximum-likelihood estimate is a ratio of counts:
where counts the history followed by and counts as a history. Each sentence is padded with start symbols <s> (so the first word has a history) and one end symbol </s> (so the model learns where sentences stop, and the probabilities of all finite sentences sum to 1).
The corpus is generated by a small seeded grammar: people who buy, sell, walk, wait, find and paint things at places and times, with Zipf-like weights so some words are common and others rare. 1200 sentences are split contiguously: the first 800 for training, the next 200 for validation (choosing hyperparameters), the last 200 for test. On real text, contiguous (or by-document) splits matter: a random split of sentences from the same documents puts near-copies in both parts and makes perplexity look better than it will be on new text.
import numpy as np
from collections import Counter
rng = np.random.default_rng(0)
def words(s):
return [[w] for w in s.split()]
G = { # a small grammar; earlier alternatives are more frequent (Zipf-like weights 1/rank)
"S": [["NP", "VP", "TIME"], ["NP", "VP"], ["TIME", "NP", "VP"], ["NP", "VP", "and", "VP"]],
"NP": [["the", "N"], ["the", "ADJ", "N"], ["my", "N"], ["a", "ADJ", "N"], ["our", "N"]],
"N": words("baker fisherman sister neighbour tourist teacher doctor farmer driver child poet nurse"),
"ADJ": words("old young tired happy quiet clever angry lucky"),
"VP": [["bought", "THING"], ["sold", "THING"], ["walked", "to", "PLACE"], ["waited", "at", "PLACE"],
["said", "that", "NP", "was", "ADJ"], ["found", "THING", "near", "PLACE"], ["painted", "PLACE"]],
"THING": [["fresh", "bread"], ["three", "fish"], ["a", "red", "umbrella"], ["some", "apples"],
["the", "newspaper"], ["a", "warm", "coat"], ["two", "tickets"], ["a", "broken", "clock"]],
"PLACE": [["the", "harbour"], ["the", "market"], ["the", "station"], ["the", "old", "bridge"],
["the", "library"], ["the", "church"], ["the", "big", "hotel"]],
"TIME": [["in", "the", "morning"], ["after", "the", "rain"], ["on", "monday"], ["at", "noon"],
["before", "dinner"], ["last", "winter"]],
}
def expand(sym):
if sym not in G:
return [sym]
w = 1 / np.arange(1, len(G[sym]) + 1)
rule = G[sym][rng.choice(len(w), p=w / w.sum())]
return [t for s in rule for t in expand(s)]
sents = [expand("S") for _ in range(1200)]
train, val, test = sents[:800], sents[800:1000], sents[1000:] # contiguous split, no shuffling
def padded(s, n): # n-1 start symbols, one end symbol
return ["<s>"] * (n - 1) + s + ["</s>"]
def ngram_counts(sents, n):
c = Counter()
for s in sents:
p = padded(s, n)
c.update(tuple(p[i:i + n]) for i in range(len(p) - n + 1))
return c
print("example:", " ".join(train[0]), "|", " ".join(train[1]))
uni, bi, tri = (ngram_counts(train, n) for n in (1, 2, 3))
V = len(uni) # word types + </s> (<s> is never predicted)
print("training tokens:", sum(len(s) + 1 for s in train), "| vocabulary V =", V)
def p_mle(w, h): # P(w | h) = c(h, w) / c(h)
ctx = bi if len(h) == 1 else tri
hist = sum(c for g, c in ctx.items() if g[:-1] == h)
return ctx[h + (w,)] / hist if hist else 0.0
print("P(fish | three) =", round(p_mle("fish", ("three",)), 3))
print("P(bridge | the old) =", round(p_mle("bridge", ("the", "old")), 3))
for n, c in [(2, bi), (3, tri)]:
seen = sum(1 for s in test for i in range(len(padded(s, n)) - n + 1) if c[tuple(padded(s, n)[i:i + n])])
total = sum(len(s) + 1 for s in test)
print(f"{n}-grams: {len(c)} types seen out of {V ** n} possible; test {n}-grams unseen in training: {1 - seen / total:.1%}")example: the baker bought the newspaper | the happy sister found the newspaper near the harbour and said that the tourist was old
training tokens: 7522 | vocabulary V = 72
P(fish | three) = 1.0
P(bridge | the old) = 0.23
2-grams: 457 types seen out of 5184 possible; test 2-grams unseen in training: 0.9%
3-grams: 1235 types seen out of 373248 possible; test 3-grams unseen in training: 6.8%
Even this tiny language has possible trigrams, and 800 sentences show 1,235 of them. 6.8 % of the trigrams in the test sentences never appeared in training, although the test text comes from exactly the same grammar. With a real vocabulary of 50,000 words there are possible trigrams, and no corpus covers them.
Perplexity, and why MLE fails on new text
Perplexity on a held-out text of predicted tokens (every word and every </s>, never <s>) is the exponential of the average negative log-likelihood:
A model that spreads its probability uniformly over words has perplexity ; lower is better. One unseen -gram gives , , and the perplexity of the whole text is infinite.
Add- smoothing pretends every -gram was seen extra times:
is Laplace smoothing. is a hyperparameter: choose it on validation text, then report the test number once.
import numpy as np
from collections import Counter
rng = np.random.default_rng(0)
def words(s):
return [[w] for w in s.split()]
G = { # a small grammar; earlier alternatives are more frequent (Zipf-like weights 1/rank)
"S": [["NP", "VP", "TIME"], ["NP", "VP"], ["TIME", "NP", "VP"], ["NP", "VP", "and", "VP"]],
"NP": [["the", "N"], ["the", "ADJ", "N"], ["my", "N"], ["a", "ADJ", "N"], ["our", "N"]],
"N": words("baker fisherman sister neighbour tourist teacher doctor farmer driver child poet nurse"),
"ADJ": words("old young tired happy quiet clever angry lucky"),
"VP": [["bought", "THING"], ["sold", "THING"], ["walked", "to", "PLACE"], ["waited", "at", "PLACE"],
["said", "that", "NP", "was", "ADJ"], ["found", "THING", "near", "PLACE"], ["painted", "PLACE"]],
"THING": [["fresh", "bread"], ["three", "fish"], ["a", "red", "umbrella"], ["some", "apples"],
["the", "newspaper"], ["a", "warm", "coat"], ["two", "tickets"], ["a", "broken", "clock"]],
"PLACE": [["the", "harbour"], ["the", "market"], ["the", "station"], ["the", "old", "bridge"],
["the", "library"], ["the", "church"], ["the", "big", "hotel"]],
"TIME": [["in", "the", "morning"], ["after", "the", "rain"], ["on", "monday"], ["at", "noon"],
["before", "dinner"], ["last", "winter"]],
}
def expand(sym):
if sym not in G:
return [sym]
w = 1 / np.arange(1, len(G[sym]) + 1)
rule = G[sym][rng.choice(len(w), p=w / w.sum())]
return [t for s in rule for t in expand(s)]
sents = [expand("S") for _ in range(1200)]
train, val, test = sents[:800], sents[800:1000], sents[1000:] # contiguous split, no shuffling
import math
def train_counts(sents): # counts of 1-, 2- and 3-grams and of their histories
c, h = Counter(), Counter()
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
for m in (1, 2, 3):
g = tuple(p[i - m + 1:i + 1])
c[g] += 1
h[g[:-1]] += 1
return c, h
def perplexity(prob, sents, n): # exp of the mean negative log-likelihood per token
nll, N = 0.0, 0
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
q = prob(p[i], tuple(p[i - n + 1:i]))
if q == 0:
return math.inf
nll -= math.log(q)
N += 1
return math.exp(nll / N)
c, h = train_counts(train)
vocab = sorted(g[0] for g in c if len(g) == 1) # word types and </s>
V = len(vocab)
def mle(w, hist):
return c[hist + (w,)] / h[hist] if h[hist] else 0.0
def add_k(k):
return lambda w, hist: (c[hist + (w,)] + k) / (h[hist] + k * V)
print("test words never seen in training:", sum(w not in vocab for s in test for w in s))
for n in (1, 2, 3):
print(f"MLE {n}-gram: train PP = {perplexity(mle, train, n):.2f}, validation PP = {perplexity(mle, val, n):.2f}")
best = {}
for n in (1, 2, 3):
scores = {k: perplexity(add_k(k), val, n) for k in (1, 0.1, 0.01, 0.001)}
best[n] = min(scores, key=scores.get)
print(f"add-k {n}-gram, validation PP by k:", {k: round(v, 2) for k, v in scores.items()})
for n in (1, 2, 3):
print(f"test PP, {n}-gram with k = {best[n]}: {perplexity(add_k(best[n]), test, n):.2f}")test words never seen in training: 0
MLE 1-gram: train PP = 38.29, validation PP = 39.23
MLE 2-gram: train PP = 4.53, validation PP = inf
MLE 3-gram: train PP = 3.19, validation PP = inf
add-k 1-gram, validation PP by k: {1: 39.21, 0.1: 39.22, 0.01: 39.23, 0.001: 39.23}
add-k 2-gram, validation PP by k: {1: 7.08, 0.1: 5.21, 0.01: 5.1, 0.001: 5.25}
add-k 3-gram, validation PP by k: {1: 9.23, 0.1: 5.29, 0.01: 4.88, 0.001: 5.37}
test PP, 1-gram with k = 1: 38.65
test PP, 2-gram with k = 0.01: 4.90
test PP, 3-gram with k = 0.01: 4.78
The MLE bigram and trigram fit the training text well (perplexity 4.53 and 3.19) and are infinite on validation text. Add- fixes that, but the amount matters: moves so much mass to unseen trigrams that the trigram (9.23) is worse than the bigram (7.08). With , chosen on validation, the trigram reaches a test perplexity of 4.78, the bigram 4.90 and the unigram 38.65. Add- is crude because it gives every unseen word the same share, whether it is plausible ("the old church") or not ("the old the").
Interpolation and backoff
Better: when the trigram has little evidence, lean on the bigram, and below it on the unigram. Linear interpolation (Jelinek-Mercer) mixes the three estimates:
The are tuned on validation text. Because each part is a distribution and the weights sum to 1, the mixture is a distribution too. Backoff instead uses the trigram when it was seen and falls back to the bigram only when it was not. Proper backoff (Katz) has to discount the seen counts and redistribute the freed mass to stay normalised. Stupid backoff (Brants et al. 2007, built for web-scale MT language models trained on up to 2 trillion tokens) skips that and multiplies by a fixed :
import numpy as np
from collections import Counter
rng = np.random.default_rng(0)
def words(s):
return [[w] for w in s.split()]
G = { # a small grammar; earlier alternatives are more frequent (Zipf-like weights 1/rank)
"S": [["NP", "VP", "TIME"], ["NP", "VP"], ["TIME", "NP", "VP"], ["NP", "VP", "and", "VP"]],
"NP": [["the", "N"], ["the", "ADJ", "N"], ["my", "N"], ["a", "ADJ", "N"], ["our", "N"]],
"N": words("baker fisherman sister neighbour tourist teacher doctor farmer driver child poet nurse"),
"ADJ": words("old young tired happy quiet clever angry lucky"),
"VP": [["bought", "THING"], ["sold", "THING"], ["walked", "to", "PLACE"], ["waited", "at", "PLACE"],
["said", "that", "NP", "was", "ADJ"], ["found", "THING", "near", "PLACE"], ["painted", "PLACE"]],
"THING": [["fresh", "bread"], ["three", "fish"], ["a", "red", "umbrella"], ["some", "apples"],
["the", "newspaper"], ["a", "warm", "coat"], ["two", "tickets"], ["a", "broken", "clock"]],
"PLACE": [["the", "harbour"], ["the", "market"], ["the", "station"], ["the", "old", "bridge"],
["the", "library"], ["the", "church"], ["the", "big", "hotel"]],
"TIME": [["in", "the", "morning"], ["after", "the", "rain"], ["on", "monday"], ["at", "noon"],
["before", "dinner"], ["last", "winter"]],
}
def expand(sym):
if sym not in G:
return [sym]
w = 1 / np.arange(1, len(G[sym]) + 1)
rule = G[sym][rng.choice(len(w), p=w / w.sum())]
return [t for s in rule for t in expand(s)]
sents = [expand("S") for _ in range(1200)]
train, val, test = sents[:800], sents[800:1000], sents[1000:] # contiguous split, no shuffling
import math
def train_counts(sents): # counts of 1-, 2- and 3-grams and of their histories
c, h = Counter(), Counter()
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
for m in (1, 2, 3):
g = tuple(p[i - m + 1:i + 1])
c[g] += 1
h[g[:-1]] += 1
return c, h
def perplexity(prob, sents, n): # exp of the mean negative log-likelihood per token
nll, N = 0.0, 0
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
q = prob(p[i], tuple(p[i - n + 1:i]))
if q == 0:
return math.inf
nll -= math.log(q)
N += 1
return math.exp(nll / N)
c, h = train_counts(train)
vocab = sorted(g[0] for g in c if len(g) == 1) # word types and </s>
V = len(vocab)
def p_ml(w, hist): # maximum likelihood, 0 for an unseen history
return c[hist + (w,)] / h[hist] if h[hist] else 0.0
def interp(l3, l2, l1): # Jelinek-Mercer interpolation, l3 + l2 + l1 = 1
def prob(w, hist):
return (l3 * p_ml(w, hist[-2:]) + l2 * p_ml(w, hist[-1:])
+ l1 * (c[(w,)] + 1) / (h[()] + V)) # add-1 unigram: never zero
return prob
grid = [(round(1 - b - a, 2), b, a) for a in (0.001, 0.01, 0.05) for b in (0.05, 0.1, 0.2, 0.3, 0.4)]
val_pp = {lam: perplexity(interp(*lam), val, 3) for lam in grid}
best = min(val_pp, key=val_pp.get)
print("best (l3, l2, l1) on validation:", best, f"PP = {val_pp[best]:.2f}")
print(f"test PP, interpolated trigram: {perplexity(interp(*best), test, 3):.2f}")
def stupid_backoff(w, hist, alpha=0.4): # a score, not a probability
if not hist:
return c[(w,)] / h[()]
if c[hist + (w,)] > 0:
return c[hist + (w,)] / h[hist]
return alpha * stupid_backoff(w, hist[1:], alpha)
for hist in [("the", "old"), ("the", "harbour")]:
total = sum(stupid_backoff(w, hist) for w in vocab)
p = interp(*best)
print(f"sum over the vocabulary after {' '.join(hist)!r}: stupid backoff {total:.3f},",
f"interpolated {sum(p(w, hist) for w in vocab):.3f}")best (l3, l2, l1) on validation: (0.69, 0.3, 0.01) PP = 4.50
test PP, interpolated trigram: 4.28
sum over the vocabulary after 'the old': stupid backoff 1.195, interpolated 1.000
sum over the vocabulary after 'the harbour': stupid backoff 1.128, interpolated 1.000
Interpolation with reaches a test perplexity of 4.28, better than the best add- trigram (4.78). The second half shows why stupid backoff is "stupid": after "the old", its scores sum to 1.195 over the vocabulary, so it is not a probability distribution and perplexity is meaningless for it. It is fine for ranking candidates (choosing between translations), and at web scale it was nearly as good as the best smoothing.
The best classical method is Kneser-Ney smoothing. It subtracts a fixed discount from every seen count and gives the lower-order model a continuation probability: how many different histories a word follows, not how often it occurs. "Francisco" is frequent but almost only after "San", so it should get little mass as a new continuation. For decades modified Kneser-Ney was the standard to beat.
Generating text
A language model is also a generator: sample , append it, repeat until </s>. A temperature reshapes the distribution as , renormalised (the same knob as for neural LMs, see Sampling and Temperature).
import numpy as np
from collections import Counter
rng = np.random.default_rng(0)
def words(s):
return [[w] for w in s.split()]
G = { # a small grammar; earlier alternatives are more frequent (Zipf-like weights 1/rank)
"S": [["NP", "VP", "TIME"], ["NP", "VP"], ["TIME", "NP", "VP"], ["NP", "VP", "and", "VP"]],
"NP": [["the", "N"], ["the", "ADJ", "N"], ["my", "N"], ["a", "ADJ", "N"], ["our", "N"]],
"N": words("baker fisherman sister neighbour tourist teacher doctor farmer driver child poet nurse"),
"ADJ": words("old young tired happy quiet clever angry lucky"),
"VP": [["bought", "THING"], ["sold", "THING"], ["walked", "to", "PLACE"], ["waited", "at", "PLACE"],
["said", "that", "NP", "was", "ADJ"], ["found", "THING", "near", "PLACE"], ["painted", "PLACE"]],
"THING": [["fresh", "bread"], ["three", "fish"], ["a", "red", "umbrella"], ["some", "apples"],
["the", "newspaper"], ["a", "warm", "coat"], ["two", "tickets"], ["a", "broken", "clock"]],
"PLACE": [["the", "harbour"], ["the", "market"], ["the", "station"], ["the", "old", "bridge"],
["the", "library"], ["the", "church"], ["the", "big", "hotel"]],
"TIME": [["in", "the", "morning"], ["after", "the", "rain"], ["on", "monday"], ["at", "noon"],
["before", "dinner"], ["last", "winter"]],
}
def expand(sym):
if sym not in G:
return [sym]
w = 1 / np.arange(1, len(G[sym]) + 1)
rule = G[sym][rng.choice(len(w), p=w / w.sum())]
return [t for s in rule for t in expand(s)]
sents = [expand("S") for _ in range(1200)]
train, val, test = sents[:800], sents[800:1000], sents[1000:] # contiguous split, no shuffling
import math
def train_counts(sents): # counts of 1-, 2- and 3-grams and of their histories
c, h = Counter(), Counter()
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
for m in (1, 2, 3):
g = tuple(p[i - m + 1:i + 1])
c[g] += 1
h[g[:-1]] += 1
return c, h
def perplexity(prob, sents, n): # exp of the mean negative log-likelihood per token
nll, N = 0.0, 0
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
q = prob(p[i], tuple(p[i - n + 1:i]))
if q == 0:
return math.inf
nll -= math.log(q)
N += 1
return math.exp(nll / N)
c, h = train_counts(train)
vocab = sorted(g[0] for g in c if len(g) == 1) # word types and </s>
V = len(vocab)
def prob(w, hist, lam=(0.69, 0.3, 0.01)): # the interpolated trigram, weights tuned on validation
p3 = c[hist + (w,)] / h[hist] if h[hist] else 0.0
p2 = c[hist[-1:] + (w,)] / h[hist[-1:]] if h[hist[-1:]] else 0.0
return lam[0] * p3 + lam[1] * p2 + lam[2] * (c[(w,)] + 1) / (h[()] + V)
def generate(rng, temperature=1.0, max_len=25):
out = ["<s>", "<s>"]
while out[-1] != "</s>" and len(out) < max_len:
p = np.array([prob(w, tuple(out[-2:])) for w in vocab]) ** (1 / temperature)
out.append(vocab[rng.choice(V, p=p / p.sum())])
return out[2:-1] if out[-1] == "</s>" else out[2:]
seen = {" ".join(s) for s in train}
g = np.random.default_rng(1)
for t in (1.0, 1.0, 1.0, 0.5, 2.0):
s = " ".join(generate(g, t))
print(f"T={t}: {s}" + (" [copied from training]" if s in seen else ""))T=1.0: the tourist bought two tickets
T=1.0: the happy fisherman bought three fish
T=1.0: the fisherman painted the harbour [copied from training]
T=0.5: the old bridge
T=2.0: umbrella tourist to the fisherman bought two tickets
At the sentences are fluent locally, and one of them, "the fisherman painted the harbour", is a verbatim copy of a training sentence: an -gram model memorises short sentences outright, a small version of the memorisation question for LLMs. At the sample "the old bridge" stops after a noun phrase: the model sees only two words of history, and after "old bridge" the most likely continuation is </s>, because in training "the old bridge" usually ended a sentence ("walked to the old bridge"). At the output falls apart. Two words of context cannot know whether the sentence already has a verb.
The library version: NLTK
NLTK's nltk.lm module has MLE, Laplace, Lidstone (add-), WittenBellInterpolated and KneserNeyInterpolated. Its vocabulary also contains <s> and an <UNK> symbol, so is 2 larger than ours; with the same the add-1 numbers agree.
import numpy as np
from collections import Counter
rng = np.random.default_rng(0)
def words(s):
return [[w] for w in s.split()]
G = { # a small grammar; earlier alternatives are more frequent (Zipf-like weights 1/rank)
"S": [["NP", "VP", "TIME"], ["NP", "VP"], ["TIME", "NP", "VP"], ["NP", "VP", "and", "VP"]],
"NP": [["the", "N"], ["the", "ADJ", "N"], ["my", "N"], ["a", "ADJ", "N"], ["our", "N"]],
"N": words("baker fisherman sister neighbour tourist teacher doctor farmer driver child poet nurse"),
"ADJ": words("old young tired happy quiet clever angry lucky"),
"VP": [["bought", "THING"], ["sold", "THING"], ["walked", "to", "PLACE"], ["waited", "at", "PLACE"],
["said", "that", "NP", "was", "ADJ"], ["found", "THING", "near", "PLACE"], ["painted", "PLACE"]],
"THING": [["fresh", "bread"], ["three", "fish"], ["a", "red", "umbrella"], ["some", "apples"],
["the", "newspaper"], ["a", "warm", "coat"], ["two", "tickets"], ["a", "broken", "clock"]],
"PLACE": [["the", "harbour"], ["the", "market"], ["the", "station"], ["the", "old", "bridge"],
["the", "library"], ["the", "church"], ["the", "big", "hotel"]],
"TIME": [["in", "the", "morning"], ["after", "the", "rain"], ["on", "monday"], ["at", "noon"],
["before", "dinner"], ["last", "winter"]],
}
def expand(sym):
if sym not in G:
return [sym]
w = 1 / np.arange(1, len(G[sym]) + 1)
rule = G[sym][rng.choice(len(w), p=w / w.sum())]
return [t for s in rule for t in expand(s)]
sents = [expand("S") for _ in range(1200)]
train, val, test = sents[:800], sents[800:1000], sents[1000:] # contiguous split, no shuffling
import math
def train_counts(sents): # counts of 1-, 2- and 3-grams and of their histories
c, h = Counter(), Counter()
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
for m in (1, 2, 3):
g = tuple(p[i - m + 1:i + 1])
c[g] += 1
h[g[:-1]] += 1
return c, h
def perplexity(prob, sents, n): # exp of the mean negative log-likelihood per token
nll, N = 0.0, 0
for s in sents:
p = ["<s>", "<s>"] + s + ["</s>"]
for i in range(2, len(p)):
q = prob(p[i], tuple(p[i - n + 1:i]))
if q == 0:
return math.inf
nll -= math.log(q)
N += 1
return math.exp(nll / N)
c, h = train_counts(train)
vocab = sorted(g[0] for g in c if len(g) == 1) # word types and </s>
V = len(vocab)
from nltk.lm import Laplace
from nltk.lm.preprocessing import padded_everygram_pipeline, pad_both_ends
from nltk.util import bigrams
ngrams_iter, words_iter = padded_everygram_pipeline(2, train)
lm = Laplace(2) # add-1 bigram
lm.fit(ngrams_iter, words_iter)
val_bigrams = [bg for s in val for bg in bigrams(pad_both_ends(s, n=2))]
print("NLTK vocabulary size:", len(lm.vocab), "(our V =", V, "+ <s> + <UNK>)")
print("NLTK Laplace bigram, validation PP:", round(lm.perplexity(val_bigrams), 2))
Vn = len(lm.vocab)
ours = perplexity(lambda w, hist: (c[hist + (w,)] + 1) / (h[hist] + Vn), val, 2)
print("ours with the same V: ", round(ours, 2))
print("P(fish | three):", round(lm.score("fish", ["three"]), 4), round((c[("three", "fish")] + 1) / (h[("three",)] + Vn), 4))NLTK vocabulary size: 74 (our V = 72 + <s> + <UNK>)
NLTK Laplace bigram, validation PP: 7.14
ours with the same V: 7.14
P(fish | three): 0.578 0.578
Why neural language models
The trigram model above stores a table of counts, 1,235 trigrams for this toy language and billions for English, and it knows nothing about similarity: seeing "the baker bought fresh bread" tells it nothing about "the farmer bought fresh bread". The words "baker" and "farmer" are just different keys.
Bengio et al. (2003) replaced the table with a neural network that reads word embeddings of the history (Word Embeddings) and outputs a softmax over the vocabulary. Similar words get similar vectors, so evidence is shared between histories, and the number of parameters no longer grows with the number of distinct -grams. Recurrent networks then removed the fixed window (Sequence Models for Text), and transformers made a long context cheap to train (Inside a Decoder-Only LM). The evaluation you just did, perplexity on contiguous held-out text, with every token counted and the same tokenisation for every model, is still how those models are compared.
Pitfalls
- Comparing perplexities across vocabularies or tokenisers. Perplexity is per token: a model with a smaller vocabulary or longer tokens is not comparable. Compare per word or per character, or use bits per byte (Perplexity shows the conversion).
- Tuning on the test set. Pick or the on validation text, then evaluate on test once.
- Forgetting
</s>. Without the end symbol the model never learns to stop, and its perplexity is computed on different events. - Out-of-vocabulary words. Real test text contains words never seen in training. Map rare training words to
<UNK>so the model has a probability for unknown words, and use the same vocabulary for every model you compare. - Random sentence splits. They leak near-duplicate sentences into the test set; split by document or by position.
- Perplexity of a non-normalised score. Stupid backoff, or any model whose probabilities do not sum to 1, cannot be compared by perplexity.
Practice
- A bigram model assigns these probabilities to the 4 predicted tokens of a held-out sentence: 0.5, 0.25, 0.5, 0.125. What is its perplexity?
- In training, "three" occurs 99 times as a history and is followed by "fish" every time, and NLTK's is 74. Compute the add-1 estimate of , compare it with the MLE, and check it against the last line of the NLTK example.
- Why did the trigram with lose to the bigram with , although the trigram has more context?
- Change
generateso that it never copies a training sentence verbatim. Is that enough to say the model does not memorise? - Why can't you interpolate the trigram with in this code?
Answers
- The mean negative log-likelihood is , so .
- , the value both lines print. The MLE is : Laplace smoothing takes 42 % of the mass away from a continuation that is certain in this language and spreads it over 73 impossible words. That is why is far too much here.
- Trigram histories are much rarer than bigram histories, so is small and the pseudo-counts in the denominator swamp the real counts. Most of the probability goes to implausible words. With small (0.01) the trigram wins.
- Reject samples that are in
seenand draw again. It is not enough: long substrings can still be copied, and the model still assigns high probability to training sentences. Memorisation is measured by how much more likely training sequences are than similar unseen ones, not only by exact copies. - Then a word whose trigram and bigram were both unseen gets probability 0, and the perplexity becomes infinite again. The add-1 unigram term is what guarantees every word a non-zero probability.
Test yourself
What is the Markov assumption of a trigram model?
- Each word is independent of the others
- The next word depends only on the previous two words
- The next word depends on the whole sentence
- Words are generated in reverse order
The MLE trigram has training perplexity 3.19. What is its validation perplexity in the example?
- About 3.2
- About 4.9
- Infinite
- About 39
Why is perplexity meaningless for stupid backoff?
- It is too slow to compute
- Its scores are not a probability distribution: after 'the old' they sum to 1.195
- It only works for bigrams
- It has no hyperparameters
What does Kneser-Ney's continuation probability measure for a word?
- Its total frequency
- The number of different words it follows
- Its length in characters
- Its frequency in the test set
Which main weakness of -gram models do neural language models fix?
- They cannot generate text
- They cannot be evaluated with perplexity
- Sparsity: every n-gram is a separate key, so evidence is not shared between similar words
- They need a GPU