Score bigrams with interpolated Kneser-Ney

Why it matters KN-smoothed n-gram models still back spelling correction, ASR rescoring and data-quality filters for LLM pretraining.

Kneser-Ney smoothing backs off to how many different contexts a word appears in, not how often it appears.

Write kn_prob(tokens, w_prev, w, d=0.75). From the bigram counts c(u, v) of the token list: P_cont(w) = (number of distinct u with c(u, w) > 0) / (number of distinct bigram types). If c(w_prev) as a first word is 0, return P_cont(w). Otherwise return max(c(w_prev, w) - d, 0) / c(w_prev) + lambda * P_cont(w), with lambda = d * (number of distinct v with c(w_prev, v) > 0) / c(w_prev), where c(w_prev) counts bigrams starting with w_prev.

Signaturedef kn_prob(tokens, w_prev, w, d=0.75)

Example

tokens "a b a b a c" has bigrams ab, ba, ab, ba, ac: 3 types. P(b | a) = (2 - 0.75) / 3 + 0.75 * 2 / 3 * (1 / 3) = 0.5833.

Understand the idea

Kneser-Ney smoothing gives unseen or rare bigrams sensible probabilities. It subtracts a fixed discount d from every seen bigram count and hands that saved mass to a backoff distribution. The clever part is the backoff: a word's continuation probability depends on how many different words it follows, not how often it appears. Worked example: tokens 'x y x z' give bigrams xy, yx, xz, so 3 bigram types. For P(y | x): c(x) = 2 bigrams start with x, c(x, y) = 1, and x is followed by 2 distinct words, so lambda = 0.75 * 2 / 2 = 0.75. y follows only x, so P_cont(y) = 1 / 3. P = (1 - 0.75) / 2 + 0.75 * 1/3 = 0.125 + 0.25 = 0.375. Rule: P_cont(w) = distinct left neighbours of w / number of bigram types. If no bigram starts with w_prev, return P_cont(w). Otherwise P = max(c(w_prev, w) - d, 0) / c(w_prev) + lambda * P_cont(w), with lambda = d * (distinct words after w_prev) / c(w_prev). Used in: classic n-gram language models for speech recognition and spelling correction.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplekn_prob('a b a b a c'.split(), 'a', 'b')
  • Sample 2: unseen bigramkn_prob('a b a b a c'.split(), 'b', 'c')