TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › n-gram Language Models and Perplexity

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:

P(w1,…,wT)=∏t=1TP(wt∣w1,…,wt−1)P(w_1, \dots, w_T) = \prod_{t=1}^{T} P(w_t \mid w_1, \dots, w_{t-1})

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 nn-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 nn-gram model keeps only the last n−1n - 1 words of the history:

P(wt∣w1,…,wt−1)≈P(wt∣wt−n+1,…,wt−1)P(w_t \mid w_1, \dots, w_{t-1}) \approx P(w_t \mid w_{t-n+1}, \dots, w_{t-1})

With n=2n = 2 (bigram) the next word depends on the previous word, with n=3n = 3 (trigram) on the previous two. The maximum-likelihood estimate is a ratio of counts:

PML(w∣h)=c(h,w)c(h)P_{\text{ML}}(w \mid h) = \frac{c(h, w)}{c(h)}

where c(h,w)c(h, w) counts the history hh followed by ww and c(h)c(h) counts hh as a history. Each sentence is padded with n−1n - 1 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.

python · try it yourself
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 723=373,24872^3 = 373{,}248 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 1.25⋅10141.25 \cdot 10^{14} possible trigrams, and no corpus covers them.

Perplexity, and why MLE fails on new text

Perplexity on a held-out text of NN predicted tokens (every word and every </s>, never <s>) is the exponential of the average negative log-likelihood:

PP⁡=exp⁡(−1N∑t=1Nln⁡P(wt∣ht))\operatorname{PP} = \exp\Bigl(-\frac{1}{N} \sum_{t=1}^{N} \ln P(w_t \mid h_t)\Bigr)

A model that spreads its probability uniformly over VV words has perplexity VV; lower is better. One unseen nn-gram gives P=0P = 0, ln⁡0=−∞\ln 0 = -\infty, and the perplexity of the whole text is infinite.

Add-kk smoothing pretends every nn-gram was seen kk extra times:

Padd-k(w∣h)=c(h,w)+kc(h)+kVP_{\text{add-}k}(w \mid h) = \frac{c(h, w) + k}{c(h) + kV}

k=1k = 1 is Laplace smoothing. kk is a hyperparameter: choose it on validation text, then report the test number once.

python · try it yourself
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-kk fixes that, but the amount matters: k=1k = 1 moves so much mass to unseen trigrams that the trigram (9.23) is worse than the bigram (7.08). With k=0.01k = 0.01, chosen on validation, the trigram reaches a test perplexity of 4.78, the bigram 4.90 and the unigram 38.65. Add-kk 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:

Pint(w∣u,v)=λ3PML(w∣u,v)+λ2PML(w∣v)+λ1Padd-1(w),λ1+λ2+λ3=1P_{\text{int}}(w \mid u, v) = \lambda_3 P_{\text{ML}}(w \mid u, v) + \lambda_2 P_{\text{ML}}(w \mid v) + \lambda_1 P_{\text{add-1}}(w), \qquad \lambda_1 + \lambda_2 + \lambda_3 = 1

The λ\lambda 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 α=0.4\alpha = 0.4:

S(w∣h)={c(h,w)c(h)c(h,w)>0α S(w∣h′)otherwise, h′=h without its first wordS(w \mid h) = \begin{cases} \dfrac{c(h, w)}{c(h)} & c(h, w) > 0 \\[4pt] \alpha\, S(w \mid h') & \text{otherwise, } h' = h \text{ without its first word} \end{cases}
python · try it yourself
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 (λ3,λ2,λ1)=(0.69,0.3,0.01)(\lambda_3, \lambda_2, \lambda_1) = (0.69, 0.3, 0.01) reaches a test perplexity of 4.28, better than the best add-kk 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 D≈0.75D \approx 0.75 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 wt∼P(⋅∣ht)w_t \sim P(\cdot \mid h_t), append it, repeat until </s>. A temperature TT reshapes the distribution as pi1/Tp_i^{1/T}, renormalised (the same knob as for neural LMs, see Sampling and Temperature).

python · try it yourself
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 T=1T = 1 the sentences are fluent locally, and one of them, "the fisherman painted the harbour", is a verbatim copy of a training sentence: an nn-gram model memorises short sentences outright, a small version of the memorisation question for LLMs. At T=0.5T = 0.5 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 T=2T = 2 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-kk), WittenBellInterpolated and KneserNeyInterpolated. Its vocabulary also contains <s> and an <UNK> symbol, so VV is 2 larger than ours; with the same VV the add-1 numbers agree.

python · try it yourself
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 nn-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 kk or the λ\lambda 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

  1. 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?
  2. In training, "three" occurs 99 times as a history and is followed by "fish" every time, and NLTK's VV is 74. Compute the add-1 estimate of P(fish∣three)P(\text{fish} \mid \text{three}), compare it with the MLE, and check it against the last line of the NLTK example.
  3. Why did the trigram with k=1k = 1 lose to the bigram with k=1k = 1, although the trigram has more context?
  4. Change generate so that it never copies a training sentence verbatim. Is that enough to say the model does not memorise?
  5. Why can't you interpolate the trigram with λ1=0\lambda_1 = 0 in this code?
Answers
  1. The mean negative log-likelihood is −14(ln⁡0.5+ln⁡0.25+ln⁡0.5+ln⁡0.125)=14(1+2+1+3)ln⁡2=1.75ln⁡2-\frac{1}{4}(\ln 0.5 + \ln 0.25 + \ln 0.5 + \ln 0.125) = \frac{1}{4}(1 + 2 + 1 + 3)\ln 2 = 1.75 \ln 2, so PP⁡=21.75≈3.36\operatorname{PP} = 2^{1.75} \approx 3.36.
  2. 99+199+74=100173≈0.578\frac{99 + 1}{99 + 74} = \frac{100}{173} \approx 0.578, the value both lines print. The MLE is 9999=1\frac{99}{99} = 1: 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 k=1k = 1 is far too much here.
  3. Trigram histories are much rarer than bigram histories, so c(h)c(h) is small and the kV=72kV = 72 pseudo-counts in the denominator swamp the real counts. Most of the probability goes to implausible words. With small kk (0.01) the trigram wins.
  4. Reject samples that are in seen and 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.
  5. 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?

  1. Each word is independent of the others
  2. The next word depends only on the previous two words
  3. The next word depends on the whole sentence
  4. Words are generated in reverse order

The MLE trigram has training perplexity 3.19. What is its validation perplexity in the example?

  1. About 3.2
  2. About 4.9
  3. Infinite
  4. About 39

Why is perplexity meaningless for stupid backoff?

  1. It is too slow to compute
  2. Its scores are not a probability distribution: after 'the old' they sum to 1.195
  3. It only works for bigrams
  4. It has no hyperparameters

What does Kneser-Ney's continuation probability measure for a word?

  1. Its total frequency
  2. The number of different words it follows
  3. Its length in characters
  4. Its frequency in the test set

Which main weakness of nn-gram models do neural language models fix?

  1. They cannot generate text
  2. They cannot be evaluated with perplexity
  3. Sparsity: every n-gram is a separate key, so evidence is not shared between similar words
  4. They need a GPU