Algorithm Search⌘K

Algorithmadvanced

Modified Kneser-Ney smoothing

Also called Chen-Goodman smoothing.

Kneser-Ney with three discounts, for counts one, two and three or more, set from counts of counts. The best n-gram smoothing in the measurements of Chen and Goodman.

Time
Θ(n N) buildΘ(n) query
Space
Θ(n N) extra
Where
N = the number of predicted training tokens; V = the vocabulary; n = the order of the model
Properties
deterministicexactofflinerecursive
Origin
Stanley F. Chen, Joshua Goodman, 1998

Modified Kneser-Ney smoothing is Kneser-Ney smoothing with three discounts in place of one. A count of 1 loses D1D_1, a count of 2 loses D2D_2, and a count of 3 or more loses D3+D_{3+}. The mass taken goes, as in Kneser-Ney, to a lower order distribution built from continuation counts. Chen and Goodman introduced it in their 1998 and 1999 study of smoothing methods for n-gram language models, and it was the best method in their measurements on their corpora. It became a common default in n-gram toolkits. The three discounts come from the counts of counts with a formula close to the Good-Turing estimate, or from held-out data.

In plain words

Kneser-Ney takes the same small amount away from every count. But a word seen once after some words is much more likely to be luck than a word seen ten times. Modified Kneser-Ney takes a different amount away from words seen once, words seen twice, and words seen three or more times.

The amounts are chosen from how many word pairs were seen once, twice, three times and four times in the whole training text. The amount taken away is put in a pool, and the pool is shared out by a simpler guess. That guess counts how many different words each word was seen after, not how often it was seen. The chances after every history still add up to one.

The problem

The setting is that of Kneser-Ney smoothing. Sentences are padded with n−1n - 1 copies of <s> and one </s>; </s> is predicted and counted, <s> is never predicted. Level nn of the model uses the raw counts an(g)=c(g)a_n(g) = c(g), and each lower level mm uses the continuation counts am(g)=N1+(⋅ g)a_m(g) = N_{1+}(\cdot\, g), the number of distinct tokens xx such that xgx g was seen. For a history hh of length m−1m - 1 let T(h)=∑xam(hx)T(h) = \sum_x a_m(h x), and let N1(h ⋅)N_1(h\, \cdot), N2(h ⋅)N_2(h\, \cdot) and N3+(h ⋅)N_{3+}(h\, \cdot) be the numbers of words xx with am(hx)a_m(h x) equal to 1, equal to 2, and at least 3.

The discount of a count kk is D(0)=0D(0) = 0, D(1)=D1D(1) = D_1, D(2)=D2D(2) = D_2 and D(k)=D3+D(k) = D_{3+} for k≥3k \ge 3, with a separate triple for each level. The model is

Pm(w∣h)=am(hw)−D(am(hw))T(h)+γ(h) Pm−1(w∣h′),γ(h)=D1N1(h ⋅)+D2N2(h ⋅)+D3+N3+(h ⋅)T(h),P_m(w \mid h) = \frac{a_m(h w) - D(a_m(h w))}{T(h)} + \gamma(h)\, P_{m-1}(w \mid h'), \qquad \gamma(h) = \frac{D_1 N_1(h\, \cdot) + D_2 N_2(h\, \cdot) + D_{3+} N_{3+}(h\, \cdot)}{T(h)},

with Pm(w∣h)=Pm−1(w∣h′)P_m(w \mid h) = P_{m-1}(w \mid h') when T(h)=0T(h) = 0, h′h' the history without its first token, and P0(w)=1/∣V∣P_0(w) = 1/|V|. Level 1 has zero discounts by default, so it is the continuation unigram.

The algorithm

Let nrn_r be the number of keys of a level whose count is rr. Chen and Goodman (1999, equation 17) estimate

Y=n1n1+2n2,D1=1−2Yn2n1,D2=2−3Yn3n2,D3+=3−4Yn4n3.Y = \frac{n_1}{n_1 + 2 n_2}, \qquad D_1 = 1 - 2Y \frac{n_2}{n_1}, \qquad D_2 = 2 - 3Y \frac{n_3}{n_2}, \qquad D_{3+} = 3 - 4Y \frac{n_4}{n_3}.
  1. MKN-TRAIN(corpus, n)
  2. 1for each predicted position of each padded sentence: a_n(the n-gram ending there) += 1
  3. 2for m ← n - 1 downto 1: for each distinct key x g of a_{m+1}: a_m(g) += 1
  4. 3for m ← 2 to n: (D_1, D_2, D_3+) ← equation 17 on n_1 .. n_4 of a_m; check 0 ≤ D(k) ≤ k
  5. MKN-PROB(w, h) ▷ h holds m - 1 tokens
  6. 4if m = 1 then lower ← 1 / |V| else lower ← MKN-PROB(w, h')
  7. 5T ← Σ_x a_m(h x)
  8. 6if T = 0 then return lower
  9. 7γ ← (D_1 N_1(h ·) + D_2 N_2(h ·) + D_3+ N_3+(h ·)) / T
  10. 8k ← a_m(h w); return (k - D(k)) / T + γ · lower

Lines L1 and L2 are the counting of Kneser-Ney. Line L3 is new. The check in line L3 matters: the estimates can leave the range [0,k][0, k] on small data, and then the row would not sum to 1. The totals T(h)T(h) and the three numbers N1(h ⋅)N_1(h\, \cdot), N2(h ⋅)N_2(h\, \cdot), N3+(h ⋅)N_{3+}(h\, \cdot) are stored for each history at training time, so a query costs one lookup per level.

Example

Take six sentences: "x y" three times, "x z" twice and "x u" once, with n=2n = 2. After the history x the counts are y 3, z 2 and u 1, so T=6T = 6 and each count class has one word. The text has 7 bigram types, and the continuation unigram is 1/71/7 for each of x, y, z and u and 3/73/7 for </s>, which follows three words.

With the discounts D1=1/2D_1 = 1/2, D2=1D_2 = 1 and D3+=3/2D_{3+} = 3/2, γ(x)=(1/2+1+3/2)/6=1/2\gamma(\text{x}) = (1/2 + 1 + 3/2) / 6 = 1/2. Kneser-Ney with D=3/4D = 3/4 has γ(x)=(3/4)⋅3/6=3/8\gamma(\text{x}) = (3/4) \cdot 3 / 6 = 3/8. The two rows after x are:

ww count modified, D(k)D(k) modified P(w∣x)P(w \mid \text{x}) Kneser-Ney P(w∣x)P(w \mid \text{x})
y 3 3/2 1.5/6+1/14=9/281.5/6 + 1/14 = 9/28 2.25/6+3/56=3/72.25/6 + 3/56 = 3/7
z 2 1 1/6+1/14=5/211/6 + 1/14 = 5/21 1.25/6+3/56=11/421.25/6 + 3/56 = 11/42
u 1 1/2 0.5/6+1/14=13/840.5/6 + 1/14 = 13/84 0.25/6+3/56=2/210.25/6 + 3/56 = 2/21
</s> 0 0 3/143/14 9/569/56
x 0 0 1/141/14 3/563/56

Both rows sum to 1. Here the modified form takes more from the frequent word and less from the singleton. On real data the estimates come from equation 17. For a trigram model on 300 random sentences over 50 words with Zipf weights, the top level had n1,…,n4=605,75,16,8n_1, \ldots, n_4 = 605, 75, 16, 8, which gives Y=121/151≈0.80Y = 121/151 \approx 0.80 and D1≈0.80D_1 \approx 0.80, D2=5614/3775≈1.49D_2 = 5614/3775 \approx 1.49 and D3+=211/151≈1.40D_{3+} = 211/151 \approx 1.40.

Correctness

The proofs file shows four things. Every conditional distribution sums to 1 exactly when 0≤D(k)≤k0 \le D(k) \le k for every kk: the seen words lose ∑D(am(hw))/T(h)\sum D(a_m(h w)) / T(h), which is exactly γ(h)\gamma(h) once the words are grouped by count class, and the lower level sums to 1. Every probability is positive when the discounts above level 1 are positive. With D1=D2=D3+D_1 = D_2 = D_{3+} the model is Kneser-Ney. And in equation 17, D1=YD_1 = Y always, Dr=r−Yr∗D_r = r - Y r^* with r∗r^* the Good-Turing adjusted count, and D2D_2 or D3+D_{3+} can be negative on small or odd data, which is why line L3 checks the range.

Proof: Modified Kneser-Ney gives a proper distribution after every history when each discount D(k) lies in [0, k], and it reduces to Kneser-Ney when the three discounts are equalfull

We use the notation of the page. Level nn uses the raw counts an(g)=c(g)a_n(g) = c(g), and each level m<nm < n uses the continuation counts am(g)=N1+(⋅ g)a_m(g) = N_{1+}(\cdot\, g). Lines L1 and L2 compute them as on the Kneser-Ney page, with the same proof: every (m+1)(m+1)-gram that ends at a predicted token is the suffix of the n-gram that ends there, because of the padding with n−1n - 1 copies of <s>. For a history hh of length m−1m - 1 we write T(h)=∑xam(hx)T(h) = \sum_x a_m(h x) and Nr(h ⋅)N_r(h\, \cdot) for the number of xx with am(hx)=ra_m(h x) = r, with N3+(h ⋅)N_{3+}(h\, \cdot) for r≥3r \ge 3. The discount of a count kk at level mm is D(0)=0D(0) = 0, D(1)=D1D(1) = D_1, D(2)=D2D(2) = D_2 and D(k)=D3+D(k) = D_{3+} for k≥3k \ge 3.

Theorem 1 (a proper distribution). Assume that at every level 0≤D1≤10 \le D_1 \le 1, 0≤D2≤20 \le D_2 \le 2 and 0≤D3+≤30 \le D_{3+} \le 3, that is 0≤D(k)≤k0 \le D(k) \le k for every kk. Then for every level m≥0m \ge 0 and every history hh of length m−1m - 1, Pm(w∣h)≥0P_m(w \mid h) \ge 0 and ∑w∈VPm(w∣h)=1\sum_{w \in V} P_m(w \mid h) = 1.

Proof. Induction on mm. Level 0 is uniform on VV. Let m≥1m \ge 1. If T(h)=0T(h) = 0, line L6 returns Pm−1(w∣h′)P_{m-1}(w \mid h'), which sums to 1. Otherwise, by the assumption am(hw)−D(am(hw))≥0a_m(h w) - D(a_m(h w)) \ge 0 for every ww, and it is 0 when am(hw)=0a_m(h w) = 0. Sum line L8 over ww:

∑wam(hw)−D(am(hw))T(h)=1−∑w: am(hw)>0D(am(hw))T(h)=1−D1N1(h ⋅)+D2N2(h ⋅)+D3+N3+(h ⋅)T(h)=1−γ(h),\sum_w \frac{a_m(h w) - D(a_m(h w))}{T(h)} = 1 - \frac{\sum_{w :\, a_m(h w) > 0} D(a_m(h w))}{T(h)} = 1 - \frac{D_1 N_1(h\, \cdot) + D_2 N_2(h\, \cdot) + D_{3+} N_{3+}(h\, \cdot)}{T(h)} = 1 - \gamma(h),

where the middle step groups the seen words by their count. The second term adds γ(h)∑wPm−1(w∣h′)=γ(h)\gamma(h) \sum_w P_{m-1}(w \mid h') = \gamma(h) by the induction hypothesis, and γ(h)≥0\gamma(h) \ge 0. So the total is 1 and every term is non-negative. □\square

The bounds are tight. If D2>2D_2 > 2, a word seen twice gets a negative first term; if only D1>1D_1 > 1, a word seen once does. The code raises an error instead of clipping, because a clipped discount no longer matches γ(h)\gamma(h) and the row no longer sums to 1.

Theorem 2 (positivity). Assume in addition that the discounts of level 1 are 0, that every word of VV was seen, and that all discounts of the levels m≥2m \ge 2 are positive. Then Pm(w∣h)>0P_m(w \mid h) > 0 for all ww and hh.

Proof. At level 1 with zero discounts, P1(w)=a1(w)/T()P_1(w) = a_1(w) / T(), and a1(w)≥1a_1(w) \ge 1 for every seen word because it ends at least one seen bigram (for n=1n = 1, a1(w)=c(w)≥1a_1(w) = c(w) \ge 1). At a level m≥2m \ge 2 with T(h)>0T(h) > 0, at least one word was seen after hh, so γ(h)>0\gamma(h) > 0 and Pm(w∣h)≥γ(h)Pm−1(w∣h′)>0P_m(w \mid h) \ge \gamma(h) P_{m-1}(w \mid h') > 0. With T(h)=0T(h) = 0 the level returns Pm−1P_{m-1}. □\square

Theorem 3 (equal discounts give Kneser-Ney). If D1=D2=D3+=DD_1 = D_2 = D_{3+} = D at every level, the model is interpolated Kneser-Ney with the discount DD at that level.

Proof. Then D(k)=DD(k) = D for every k≥1k \ge 1, so a−D(a)=max⁡(a−D,0)a - D(a) = \max(a - D, 0) for every integer a≥0a \ge 0 when D≤1D \le 1, and γ(h)=D(N1+N2+N3+)(h ⋅)/T(h)=DN1+(h ⋅)/T(h)\gamma(h) = D (N_1 + N_2 + N_{3+})(h\, \cdot) / T(h) = D N_{1+}(h\, \cdot) / T(h). These are the two terms of Kneser-Ney. □\square

Lemma 4 (the default discounts). Let nrn_r be the number of keys of a level with count rr, with n1,n2>0n_1, n_2 > 0, and Y=n1/(n1+2n2)Y = n_1 / (n_1 + 2 n_2). The estimates of Chen and Goodman are Dr=r−(r+1)Ynr+1/nrD_r = r - (r+1) Y n_{r+1} / n_r for r=1,2r = 1, 2 and D3+=3−4Yn4/n3D_{3+} = 3 - 4 Y n_4 / n_3. Then:

  1. D1=YD_1 = Y, so 0<D1≤10 < D_1 \le 1 always.
  2. Dr=r−Yr∗D_r = r - Y r^*, where r∗=(r+1)nr+1/nrr^* = (r+1) n_{r+1} / n_r is the Good-Turing adjusted count.
  3. D2D_2 and D3+D_{3+} can be negative. So the default needs a check.

Proof. (1) D1=1−2Yn2/n1=1−2n2/(n1+2n2)=n1/(n1+2n2)=YD_1 = 1 - 2 Y n_2 / n_1 = 1 - 2 n_2 / (n_1 + 2 n_2) = n_1 / (n_1 + 2 n_2) = Y, and 0<Y≤10 < Y \le 1. (2) is the definition of r∗r^* rewritten. (3) Take n1=n2=1n_1 = n_2 = 1 and n3=6n_3 = 6. Then Y=1/3Y = 1/3 and D2=2−3⋅13⋅6=−4D_2 = 2 - 3 \cdot \frac13 \cdot 6 = -4. □\square

When n3=0n_3 = 0 the formula for D3+D_{3+} divides by zero, and when n2=0n_2 = 0 the formula for D2D_2 does. The implementation raises an error in all of these cases and accepts explicit discounts.

Complexity

As for Kneser-Ney: training makes one pass over the NN predicted tokens and one pass over the distinct n-grams of each level, Θ(nN)\Theta(n N) expected n-gram operations with hash tables. Line L3 adds one pass over the counts of each level. A query takes Θ(n)\Theta(n) operations, and a full distribution Θ(n∣V∣)\Theta(n |V|). The tables take Θ(nN)\Theta(n N) space; the three numbers per history add a constant factor.

Properties

  • A proper distribution for discounts in range, exactly, in rational arithmetic.
  • Three discounts per level. The discount depends on the count class. Equation 17 does not force it to grow with the count: in the trigram example above, D3+<D2D_{3+} < D_2.
  • Contains Kneser-Ney as the case of equal discounts.
  • Discounts from data. The default needs no held-out data. Chen and Goodman's best variant fitted the discounts on held-out data instead.

Variants and improvements

  • kneser-ney-mod and kneser-ney-mod-fix. In the experiments of Chen and Goodman, the first optimizes the discounts on held-out data and the second uses equation 17; the second did slightly worse.
  • Backoff form. The variant kneser-ney-mod-backoff of Chen and Goodman uses the lower level only for unseen words. It did worse than the interpolated form for small counts.
  • Two discounts. Ney and colleagues (1997) independently suggested two discounts in place of one, as Chen and Goodman report.
  • Pruned models. Large modified Kneser-Ney models are often made smaller with entropy-based pruning, which removes the n-grams whose loss changes the model least.

When to use it

Use it for a count-based n-gram model when the corpus is large enough that the counts of counts n1n_1 to n4n_4 are stable at every level. It is the usual baseline that later neural language models were compared with, as in Bengio and colleagues (2003). On very small corpora the estimates can fail; use plain Kneser-Ney or fit the discounts on held-out data. For web-scale counts where only a score is needed, stupid backoff is much cheaper to build.

Pitfalls

  • "The best smoothing". It was the best of the methods Chen and Goodman measured, on their corpora (Brown, North American Business news, Switchboard and Broadcast News) and their n-gram orders. That is a measurement, not a theorem.
  • Out-of-range discounts. Equation 17 can give D2<0D_2 < 0 or D3+<0D_{3+} < 0, for example with n1=n2=1n_1 = n_2 = 1 and n3=6n_3 = 6. Clipping the discount without changing γ\gamma breaks the sum to 1. Check and fall back to explicit values.
  • Division by zero. n2=0n_2 = 0 or n3=0n_3 = 0 makes equation 17 undefined. This happens at low levels of small models, and in corpora where rare n-grams were removed before counting.
  • Counts of counts of the wrong level. Each level needs its own discounts, from the counts that level uses.
  • Lower levels with raw counts. As for Kneser-Ney, every level below nn uses continuation counts.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

modified_kneser_ney_smoothing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modified-kneser-ney-smoothing/. The authors are listed in prov/R2ZAVZ.jsonl.

"""Interpolated modified Kneser-Ney smoothing (Chen and Goodman), exact in Fraction.

A corpus is a list of sentences, and a sentence is a list of str tokens.
Each sentence is padded with n - 1 copies of "<s>" on the left and one
"</s>" on the right. "</s>" is predicted and counted; "<s>" is never
predicted.

Level n uses raw counts and each lower level m < n uses the continuation
counts N_1+(. g). A count k loses D(k): 0 for k = 0, D1 for k = 1, D2 for
k = 2 and D3+ for k >= 3. With T(h) = sum_x a(h x) and N_r(h .) the number
of x with a(h x) = r (N_3+ for r >= 3),

    P_m(w | h) = (a(h w) - D(a(h w))) / T(h) + gamma(h) P_m-1(w | h')
    gamma(h)   = (D1 N_1(h .) + D2 N_2(h .) + D3+ N_3+(h .)) / T(h)

and P_m(w | h) = P_m-1(w | h') when T(h) = 0. Below level 1 sits the
uniform distribution 1 / |V|. The discounts of level 1 are 0 by default.
"""

import math
from collections import Counter
from fractions import Fraction
from typing import Iterable, Sequence

BOS, EOS = "<s>", "</s>"

Discounts = tuple[Fraction, Fraction, Fraction]


def pad(sent: Sequence[str], n: int) -> list[str]:
    """Return the sentence with n - 1 copies of <s> in front and </s> at the end."""
    return [BOS] * (n - 1) + list(sent) + [EOS]


def level_counts(corpus: Iterable[Sequence[str]], n: int) -> dict[int, Counter]:
    """Return a[m] for m = 1 to n: raw counts of the n-grams, continuation counts below."""
    a = {n: Counter()}
    for sent in corpus:
        toks = pad(sent, n)
        for i in range(n - 1, len(toks)):
            a[n][tuple(toks[i - n + 1 : i + 1])] += 1  # @line L1
    for m in range(n - 1, 0, -1):
        a[m] = Counter()
        for g in a[m + 1]:
            a[m][g[1:]] += 1  # @line L2
    return a


def chen_goodman_discounts(counts: Counter) -> Discounts:
    """D1, D2, D3+ from the counts of counts n_1 to n_4 of one level (Chen and Goodman, eq. 17)."""
    cc = Counter(counts.values())
    n1, n2, n3, n4 = cc[1], cc[2], cc[3], cc[4]
    if n1 == 0 or n2 == 0 or n3 == 0:
        raise ValueError("n_1, n_2 and n_3 must be positive; give the discounts explicitly")
    y = Fraction(n1, n1 + 2 * n2)  # @line L3
    d1 = 1 - 2 * y * Fraction(n2, n1)
    d2 = 2 - 3 * y * Fraction(n3, n2)
    d3 = 3 - 4 * y * Fraction(n4, n3)
    return check_discounts((d1, d2, d3))


def check_discounts(d: Sequence[Fraction | int]) -> Discounts:
    """Return the three discounts as Fractions; each D(k) must lie in [0, k]."""
    if len(d) != 3:
        raise ValueError("give three discounts D1, D2, D3+")
    d1, d2, d3 = (Fraction(x) for x in d)
    if not (0 <= d1 <= 1 and 0 <= d2 <= 2 and 0 <= d3 <= 3):
        raise ValueError(f"discounts out of range: D1 in [0, 1], D2 in [0, 2], D3+ in [0, 3], got {d1}, {d2}, {d3}")
    return d1, d2, d3


class ModifiedKneserNeyLM:
    """An interpolated modified Kneser-Ney n-gram model over a closed vocabulary."""

    def __init__(
        self,
        corpus: Iterable[Sequence[str]],
        n: int,
        discounts: Sequence[Sequence[Fraction | int]] | None = None,
        vocab: Iterable[str] | None = None,
    ):
        """discounts[m - 1] = (D1, D2, D3+) for level m. By default level 1 has (0, 0, 0)."""
        if n < 1:
            raise ValueError("the order n must be at least 1")
        corpus = [list(s) for s in corpus]
        self.n = n
        self.a = level_counts(corpus, n)
        seen = {g[-1] for g in self.a[n]}
        self.vocab = set(seen) if vocab is None else set(vocab) | {EOS}
        if BOS in self.vocab:
            raise ValueError("<s> is never predicted, so it is not in the vocabulary")
        if not seen <= self.vocab:
            raise ValueError("the vocabulary must hold every training token")
        if discounts is None:
            discounts = [(0, 0, 0)] + [chen_goodman_discounts(self.a[m]) for m in range(2, n + 1)]
        if len(discounts) != n:
            raise ValueError("give three discounts for each order 1 to n")
        self.d = {m: check_discounts(discounts[m - 1]) for m in range(1, n + 1)}
        if self.vocab != seen and self.d[1] == (0, 0, 0):
            raise ValueError("a vocabulary larger than the training tokens needs discounts at level 1")
        # T(h), and N_1(h .), N_2(h .), N_3+(h .) for every history of every level.
        self.total = {m: Counter() for m in range(1, n + 1)}
        self.nr = {m: {} for m in range(1, n + 1)}
        for m in range(1, n + 1):
            for g, k in self.a[m].items():
                h = g[:-1]
                self.total[m][h] += k
                row = self.nr[m].setdefault(h, [0, 0, 0])
                row[min(k, 3) - 1] += 1

    def discount(self, m: int, k: int) -> Fraction:
        """D(k) at level m."""
        return Fraction(0) if k == 0 else self.d[m][min(k, 3) - 1]

    def history(self, tokens: Sequence[str]) -> tuple:
        """The last n - 1 tokens of <s> ... <s> tokens: the history of the next prediction."""
        if self.n == 1:
            return ()
        return tuple([BOS] * (self.n - 1) + list(tokens))[-(self.n - 1) :]

    def prob(self, w: str, tokens: Sequence[str] = ()) -> Fraction:
        """P(w | the sentence so far), where tokens is the sentence so far without <s>."""
        if w not in self.vocab:
            raise KeyError(f"{w!r} is not in the vocabulary")
        return self._prob(w, self.history(tokens))

    def _prob(self, w: str, h: tuple) -> Fraction:
        m = len(h) + 1
        if m == 1:  # @line L4
            lower = Fraction(1, len(self.vocab))
        else:
            lower = self._prob(w, h[1:])
        t = self.total[m][h]  # @line L5
        if t == 0:  # @line L6
            return lower
        d1, d2, d3 = self.d[m]
        n1, n2, n3 = self.nr[m][h]
        gamma = (d1 * n1 + d2 * n2 + d3 * n3) / t  # @line L7
        k = self.a[m][h + (w,)]
        return (k - self.discount(m, k)) / t + gamma * lower  # @line L8

    def distribution(self, tokens: Sequence[str] = ()) -> dict[str, Fraction]:
        """The full conditional distribution over the vocabulary."""
        return {w: self.prob(w, tokens) for w in sorted(self.vocab)}

    def sentence_logprob(self, sent: Sequence[str]) -> float:
        """The natural log of the probability of the sentence, </s> included, summed in log space."""
        sent = list(sent)
        total = 0.0
        for i, w in enumerate(sent + [EOS]):
            p = self.prob(w, sent[:i])
            total += math.log(p.numerator) - math.log(p.denominator)
        return total
test_modified_kneser_ney_smoothing.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modified-kneser-ney-smoothing/. The authors are listed in prov/R2ZAVZ.jsonl.

import math
import random
from collections import Counter
from fractions import Fraction

import pytest

from modified_kneser_ney_smoothing import (
    BOS,
    EOS,
    ModifiedKneserNeyLM,
    chen_goodman_discounts,
    check_discounts,
    level_counts,
)

CHECK = [["a", "b"], ["a", "c"], ["b", "c"]]
Q = Fraction(3, 4)


def random_corpus(seed, sentences, words, max_len):
    rng = random.Random(seed)
    return [[rng.choice(words) for _ in range(rng.randint(0, max_len))] for _ in range(sentences)]


def zipf_corpus(seed, sentences, size, max_len):
    """Words w0, w1, ... with weights 1, 1/2, 1/3, ..., so that small counts are common."""
    rng = random.Random(seed)
    words = [f"w{i}" for i in range(size)]
    weights = [1 / (i + 1) for i in range(size)]
    return [rng.choices(words, weights, k=rng.randint(0, max_len)) for _ in range(sentences)]


def prefixes(corpus, n):
    out = {()}
    for s in corpus:
        for i in range(len(s) + 1):
            out.add(tuple(s[:i]))
    out.add(("zz",) * max(n - 1, 1))
    return out


def test_equal_discounts_give_the_kneser_ney_check_value():
    lm = ModifiedKneserNeyLM(CHECK, 2, discounts=[(0, 0, 0), (Q, Q, Q)])
    assert lm.prob("a") == Fraction(41, 84)
    assert lm.prob("b") == Fraction(19, 84)
    assert lm.prob("c") == Fraction(1, 7)
    assert lm.prob(EOS) == Fraction(1, 7)
    assert lm.prob(EOS, ["a", "c"]) == Fraction(41, 56)


def test_chen_goodman_discounts_by_hand():
    # counts of counts n_1..n_4 = 6, 3, 2, 1
    counts = Counter({i: k for i, k in enumerate([1] * 6 + [2] * 3 + [3] * 2 + [4])})
    y = Fraction(6, 12)
    d1, d2, d3 = chen_goodman_discounts(counts)
    assert d1 == 1 - 2 * y * Fraction(3, 6) == y
    assert d2 == 2 - 3 * y * Fraction(2, 3) == 1
    assert d3 == 3 - 4 * y * Fraction(1, 2) == 2


def test_d1_always_equals_y():
    rng = random.Random(3)
    for _ in range(50):
        n1, n2, n3, n4 = (rng.randint(1, 40) for _ in range(4))
        counts = Counter({i: k for i, k in enumerate([1] * n1 + [2] * n2 + [3] * n3 + [4] * n4)})
        try:
            d = chen_goodman_discounts(counts)
        except ValueError:
            continue
        assert d[0] == Fraction(n1, n1 + 2 * n2)


def test_one_history_by_hand():
    # After "x": y three times, z twice, u once. Discounts (1/2, 1, 3/2).
    corpus = [["x", "y"]] * 3 + [["x", "z"]] * 2 + [["x", "u"]]
    d = [(0, 0, 0), (Fraction(1, 2), 1, Fraction(3, 2))]
    lm = ModifiedKneserNeyLM(corpus, 2, discounts=d)
    gamma = (Fraction(1, 2) * 1 + 1 * 1 + Fraction(3, 2) * 1) / 6
    assert gamma == Fraction(1, 2)
    uni = lm._prob("y", ())
    assert uni == Fraction(1, 7)  # 7 bigram types, and y follows only x
    assert lm.prob("y", ["x"]) == (3 - Fraction(3, 2)) / 6 + gamma * uni
    assert lm.prob("u", ["x"]) == (1 - Fraction(1, 2)) / 6 + gamma * lm._prob("u", ())
    assert sum(lm.distribution(["x"]).values()) == 1


def naive_prob(corpus, n, d, vocab, w, h):
    m = len(h) + 1
    lower = Fraction(1, len(vocab)) if m == 1 else naive_prob(corpus, n, d, vocab, w, h[1:])
    grams = []
    for s in corpus:
        toks = [BOS] * (n - 1) + s + [EOS]
        for i in range(n - 1, len(toks)):
            grams.append(tuple(toks[i - n + 1 : i + 1]))

    def a(g):
        if m == n:
            return sum(1 for x in grams if x == g)
        return len({x[-m - 1] for x in grams if x[-m:] == g})

    def disc(k):
        return Fraction(0) if k == 0 else Fraction(d[m - 1][min(k, 3) - 1])

    followers = {g[-1] for g in grams if g[-m:-1] == h}
    t = sum(a(h + (x,)) for x in followers)
    if t == 0:
        return lower
    gamma = sum(disc(a(h + (x,))) for x in followers) / t
    k = a(h + (w,))
    return (k - disc(k)) / t + gamma * lower


@pytest.mark.parametrize("n", [1, 2, 3])
def test_matches_naive_reference(n):
    corpus = random_corpus(20 + n, 14, ["x", "y", "z", "u"], 5)
    d = [(Fraction(1, 3), Fraction(1, 2), Fraction(1, 2))] + [(Fraction(1, 2), Fraction(5, 4), 2)] * (n - 1)
    vocab = ["x", "y", "z", "u", "v"]
    lm = ModifiedKneserNeyLM(corpus, n, discounts=d, vocab=vocab)
    for toks in list(prefixes(corpus, n))[:25]:
        h = lm.history(toks)
        for w in sorted(lm.vocab):
            assert lm.prob(w, toks) == naive_prob(corpus, n, d, lm.vocab, w, h)


@pytest.mark.parametrize("n,seed", [(1, 1), (2, 2), (3, 3), (4, 5)])
def test_every_distribution_sums_to_one_with_default_discounts(n, seed):
    corpus = zipf_corpus(seed + 2, 300, 50, 6)
    lm = ModifiedKneserNeyLM(corpus, n)
    for m in range(2, n + 1):
        assert lm.d[m][0] == chen_goodman_discounts(level_counts(corpus, n)[m])[0]
    for toks in list(prefixes(corpus, n))[:60]:
        dist = lm.distribution(toks)
        assert sum(dist.values()) == 1
        assert all(p > 0 for p in dist.values())


def test_sums_to_one_at_the_edges_of_the_ranges():
    corpus = random_corpus(8, 40, ["a", "b", "c"], 6)
    for d in [(0, 0, 0), (1, 2, 3), (1, 0, 3), (Fraction(1, 7), 2, 0)]:
        lm = ModifiedKneserNeyLM(corpus, 3, discounts=[(Fraction(1, 2),) * 3, d, d], vocab=["a", "b", "c", "q"])
        for toks in prefixes(corpus, 3):
            assert sum(lm.distribution(toks).values()) == 1


def test_log_space_where_the_product_underflows():
    corpus = zipf_corpus(3, 300, 50, 6)
    lm = ModifiedKneserNeyLM(corpus, 2)
    sent = zipf_corpus(9, 1, 50, 1)[0] + [w for s in zipf_corpus(10, 400, 50, 6) for w in s]
    assert len(sent) > 900
    product, log_sum = 1.0, 0.0
    for i, w in enumerate(sent + [EOS]):
        p = float(lm.prob(w, sent[:i]))
        product *= p
        log_sum += math.log(p)
    assert product == 0.0
    lp = lm.sentence_logprob(sent)
    assert lp < -745 and lp == pytest.approx(log_sum, rel=1e-12)


def test_bad_input():
    with pytest.raises(ValueError):
        check_discounts((Fraction(3, 2), 1, 1))
    with pytest.raises(ValueError):
        check_discounts((1, 1, 4))
    with pytest.raises(ValueError):
        check_discounts((1, 1))
    with pytest.raises(ValueError):
        chen_goodman_discounts(Counter({"a": 1, "b": 2}))  # n_3 = 0
    with pytest.raises(ValueError):
        # n_1..n_4 = 1, 1, 6, 0: Y = 1/3 and D2 = 2 - 3 (1/3) 6 = -4
        chen_goodman_discounts(Counter({i: k for i, k in enumerate([1, 2, 3, 3, 3, 3, 3, 3])}))
    with pytest.raises(ValueError):
        ModifiedKneserNeyLM(CHECK, 2, discounts=[(0, 0, 0), (Q, Q, Q)], vocab=["a", "b", "c", "q"])

History

Chen and Goodman (1998, 1999) compared the main smoothing methods of the time on several corpora, training set sizes and n-gram orders. They found interpolated Kneser-Ney the best of the existing methods and proposed this modification, with three discounts per level. In their discussion, the modified form "consistently outperformed all other algorithms" in their experiments, and the largest single factor in its success was the lower order distribution of Kneser and Ney. They credit the estimates of equation 17 to Ries (1997), and note that Ney and colleagues had independently proposed two discounts. Modified Kneser-Ney then became a common default in n-gram toolkits.

References

  1. Stanley F. Chen and Joshua Goodman, An empirical study of smoothing techniques for language modeling, Computer Speech and Language 13(4), 1999, pages 359 to 394, Section 3 on pages 370 to 371 (the three discounts, gamma, and the estimates of equation 17), Section 4.1 (the variants kneser-ney-mod and kneser-ney-mod-fix), Section 6 on pages 390 to 391 (the discussion of the results)
  2. Chen and Goodman 1998, the longer report with the full set of experiments
  3. Reinhard Kneser and Hermann Ney, Improved backing-off for M-gram language modeling, Proceedings of ICASSP 1995, volume 1, pages 181 to 184, the continuation counts of the lower order distribution

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.query
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example