Algorithm Search⌘K

Algorithmcore

Kneser-Ney smoothing

Also called interpolated Kneser-Ney.

Absolute discounting whose lower order model uses continuation counts, the number of distinct contexts a word follows, rather than raw counts.

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
Reinhard Kneser, Hermann Ney, Stanley F. Chen, Joshua Goodman, 1995

Kneser-Ney smoothing is the way most n-gram language models were built from the late 1990s on. It takes a fixed discount DD from every seen n-gram count, as absolute discounting does, and gives the mass it took to a lower order distribution. The new idea is what that lower distribution counts. It does not ask how often a word was seen. It asks after how many different words it was seen, the continuation count N1+(⋅ w)N_{1+}(\cdot\, w). A word such as "Francisco" can be frequent and still follow almost only "San", so it should get little probability after a history where the full model has no data. This page gives the interpolated form of Chen and Goodman, which uses the lower order for every word; the 1995 original was a backoff model.

In plain words

To guess the next word, look first at what followed the same last few words in the training text. Trust those counts, but take a fixed small amount away from each one and put it in a pool.

The pool is shared out by a simpler guess that looks at fewer words. The simple guess is the clever part. It does not ask how often a word appeared. It asks how many different words it appeared after. A word that shows up after many different words is a good guess in a new place. A word that is common only inside one fixed phrase is not.

The pool and the simpler guess together fill the gap, so the chances after every history still add up to one.

The problem

The training corpus is a list of sentences. Each sentence is padded with n−1n - 1 copies of <s> on the left and one </s> on the right; </s> is predicted and counted, <s> is never predicted. The vocabulary VV is the set of predicted tokens, or a given closed set that contains them. For an order nn, the task is to give a conditional distribution P(w∣h)P(w \mid h) over VV for every history hh of n−1n - 1 tokens, with no zero for a word that was not seen after hh, and with the counts of the training text used as well as possible.

Write c(g)c(g) for the number of times the n-gram gg ends at a predicted token, and N1+(⋅ g)N_{1+}(\cdot\, g) for the number of distinct tokens xx such that xgx g was seen. The model has one level for each order m=1,…,nm = 1, \ldots, n. Level nn uses an(g)=c(g)a_n(g) = c(g), and each lower level uses am(g)=N1+(⋅ g)a_m(g) = N_{1+}(\cdot\, g). For a history hh of length m−1m - 1 let

T(h)=∑xam(hx),N1+(h ⋅)=∣{x:am(hx)>0}∣,h′=h without its first token.T(h) = \sum_x a_m(h x), \qquad N_{1+}(h\, \cdot) = |\{x : a_m(h x) > 0\}|, \qquad h' = h \text{ without its first token}.

Interpolated Kneser-Ney is the recursion

Pm(w∣h)=max⁡(am(hw)−Dm,0)T(h)+Dm N1+(h ⋅)T(h) Pm−1(w∣h′),P_m(w \mid h) = \frac{\max(a_m(h w) - D_m, 0)}{T(h)} + \frac{D_m\, N_{1+}(h\, \cdot)}{T(h)}\, P_{m-1}(w \mid 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, and P0(w)=1/∣V∣P_0(w) = 1 / |V|. With D1=0D_1 = 0, level 1 is the continuation unigram N1+(⋅ w)/N1+(⋅ ⋅)N_{1+}(\cdot\, w) / N_{1+}(\cdot\, \cdot).

The algorithm

Training counts the n-grams once and derives every lower level from the distinct n-grams above it. A query walks down the levels.

  1. KN-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_m ← n_1 / (n_1 + 2 n_2), from the counts of counts of a_m; D_1 ← 0
  5. KN-PROB(w, h) ▷ h holds m - 1 tokens
  6. 4if m = 1 then lower ← 1 / |V| else lower ← KN-PROB(w, h')
  7. 5T ← Σ_x a_m(h x)
  8. 6if T = 0 then return lower ▷ h was never seen at this level
  9. 7γ ← D_m · N_{1+}(h ·) / T
  10. 8return max(a_m(h w) - D_m, 0) / T + γ · lower

Line L1 is the only pass over the text. Line L2 turns the distinct (m+1)(m+1)-grams into continuation counts: each distinct xgx g adds one left context to gg. Line L3 is the default discount of Ney, Essen and Kneser (1994) that Chen and Goodman use, with nrn_r the number of keys of level mm whose count is rr. Here it is computed from the counts that level actually uses, so the lower levels take it from their continuation counts; this is a choice of the implementation. The totals T(h)T(h) and N1+(h ⋅)N_{1+}(h\, \cdot) are stored for every history at training time, so lines L5 and L7 are table lookups.

Example

Take the three sentences "a b", "a c" and "b c" with n=2n = 2, D2=3/4D_2 = 3/4 and D1=0D_1 = 0. The padded text has the 7 bigram types <s> a (seen twice), <s> b, a b, a c, b c, b </s> and c </s> (seen twice). Line L2 counts the distinct left contexts:

ww left contexts N1+(⋅ w)N_{1+}(\cdot\, w) P1(w)P_1(w)
a <s> 1 1/7
b <s>, a 2 2/7
c a, b 2 2/7
</s> b, c 2 2/7

After <s>, T=3T = 3 and N1+(<s> ⋅)=2N_{1+}(\text{<s>}\, \cdot) = 2, so γ=(3/4)⋅2/3=1/2\gamma = (3/4) \cdot 2 / 3 = 1/2. Then

P(a∣<s>)=2−3/43+12⋅17=4184,P(</s>∣c)=2−3/42+38⋅27=4156.P(\text{a} \mid \text{<s>}) = \frac{2 - 3/4}{3} + \frac12 \cdot \frac17 = \frac{41}{84}, \qquad P(\text{</s>} \mid \text{c}) = \frac{2 - 3/4}{2} + \frac38 \cdot \frac27 = \frac{41}{56}.

The whole model is:

hh a b c </s>
<s> 41/84 19/84 1/7 1/7
a 3/28 19/56 19/56 3/14
b 3/28 3/14 19/56 19/56
c 3/56 3/28 3/28 41/56

Every row sums to 1. The word a is seen as often as b and c, but always after <s>, so after any other history it gets the least. With n=3n = 3 on the same text, level 2 counts <s> a once, not twice, because both occurrences have the same left context <s>.

Correctness

The proof in the proofs file has three parts. Lines L1 and L2 compute the counts as defined, because every (m+1)(m+1)-gram that ends at a predicted token is the suffix of an n-gram, thanks to the padding. Every conditional distribution sums to 1 when 0≤Dm≤10 \le D_m \le 1, by induction on mm: the seen words of hh lose exactly DmN1+(h ⋅)/T(h)D_m N_{1+}(h\, \cdot) / T(h), which is the weight γ\gamma of the lower level, and the lower level sums to 1. And in a bigram model the continuation unigram is the only lower distribution for which the model keeps the unigram marginals of the data, ∑vP(v)P(w∣v)=c(w)/N\sum_v P(v) P(w \mid v) = c(w) / N. This is the constraint that led to the method.

Proof: Interpolated Kneser-Ney gives a proper distribution after every history, and its continuation unigram is the one that keeps the unigram marginalsfull

We use the notation of the page. Every sentence is padded with n−1n - 1 copies of <s> and one </s>. Level nn uses the raw counts an(g)=c(g)a_n(g) = c(g), and each level m<nm < n uses am(g)=N1+(⋅ g)a_m(g) = N_{1+}(\cdot\, g), the number of distinct tokens xx such that the (m+1)(m+1)-gram xgx g was seen. For a history hh of length m−1m - 1, Tm(h)=∑xam(hx)T_m(h) = \sum_x a_m(h x) and N1+(h ⋅)=∣{x:am(hx)>0}∣N_{1+}(h\, \cdot) = |\{x : a_m(h x) > 0\}|. Level 0 is the uniform distribution 1/∣V∣1/|V| on the vocabulary VV.

Lemma 1 (the counts of lines L1 and L2). After lines L1 and L2, an(g)a_n(g) is the number of positions where the nn-gram gg ends at a predicted token, and for m<nm < n, am(g)a_m(g) is the number of distinct xx such that xgx g occurs as an (m+1)(m+1)-gram that ends at a predicted token.

Proof. Line L1 visits each predicted position once and adds 1 to the nn-gram that ends there. For m<nm < n, line L2 runs once for each distinct key xgx g of am+1a_{m+1}, and it adds 1 to the key gg. So am(g)a_m(g) counts the distinct first tokens xx of the keys of am+1a_{m+1} that end with gg. The keys of ana_n are the seen nn-grams. Because each sentence has n−1n - 1 copies of <s> in front, every (m+1)(m+1)-gram that ends at a predicted position is the suffix of the nn-gram that ends at the same position, so by induction on n−mn - m the keys of am+1a_{m+1} are exactly the seen (m+1)(m+1)-grams. □\square

Theorem 2 (a proper distribution). Let 0≤Dm≤10 \le D_m \le 1 for every level mm. Then for every level m≥0m \ge 0 and every history hh of length m−1m - 1 (no history for m=0m = 0), Pm(w∣h)≥0P_m(w \mid h) \ge 0 for every w∈Vw \in V and ∑w∈VPm(w∣h)=1\sum_{w \in V} P_m(w \mid h) = 1. If D1=0D_1 = 0, assume also that every word of VV was seen; then the same holds, and every Pm(w∣h)P_m(w \mid h) with m≥1m \ge 1 is positive when every DmD_m with m≥2m \ge 2 is positive.

Proof. Induction on mm. For m=0m = 0 the uniform distribution sums to 1. Let m≥1m \ge 1 and assume the claim for m−1m - 1. If Tm(h)=0T_m(h) = 0, line L6 returns Pm−1(w∣h′)P_{m-1}(w \mid h'), which sums to 1. Otherwise split VV into the set S={w:am(hw)>0}S = \{w : a_m(h w) > 0\} and the rest. Every count in SS is an integer at least 1, so am(hw)−Dm≥0a_m(h w) - D_m \ge 0 there, and the max in line L8 is zero outside SS. So

∑w∈Vmax⁡(am(hw)−Dm,0)Tm(h)=∑w∈Sam(hw)−Dm∣S∣Tm(h)=1−DmN1+(h ⋅)Tm(h),\sum_{w \in V} \frac{\max(a_m(h w) - D_m, 0)}{T_m(h)} = \frac{\sum_{w \in S} a_m(h w) - D_m |S|}{T_m(h)} = 1 - \frac{D_m N_{1+}(h\, \cdot)}{T_m(h)},

since ∑w∈Sam(hw)=Tm(h)\sum_{w \in S} a_m(h w) = T_m(h) and ∣S∣=N1+(h ⋅)|S| = N_{1+}(h\, \cdot). The second term of line L8 adds γ(h)∑wPm−1(w∣h′)=DmN1+(h ⋅)/Tm(h)\gamma(h) \sum_w P_{m-1}(w \mid h') = D_m N_{1+}(h\, \cdot) / T_m(h) by the induction hypothesis. The total is 1, and every term is non-negative.

At level 1 with D1=0D_1 = 0, P1(w)=a1(w)/T1()P_1(w) = a_1(w) / T_1(). Every seen word ww is predicted at some position, so it ends some bigram, and a1(w)≥1a_1(w) \ge 1 by Lemma 1 (for n=1n = 1, a1(w)=c(w)≥1a_1(w) = c(w) \ge 1). So P1(w)>0P_1(w) > 0 on VV. For m≥2m \ge 2 with Dm>0D_m > 0, either Tm(h)=0T_m(h) = 0 and Pm=Pm−1>0P_m = P_{m-1} > 0, or γ(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. □\square

The condition Dm≤1D_m \le 1 is needed. With Dm>1D_m > 1, a word seen once after hh gets 0 from the first term, but the backoff weight still counts it in DmN1+(h ⋅)D_m N_{1+}(h\,\cdot), and the total is 1+∑w∈Smax⁡(Dm−am(hw),0)/Tm(h)>11 + \sum_{w \in S} \max(D_m - a_m(h w), 0) / T_m(h) > 1.

Theorem 3 (why continuation counts). Take a bigram model (n=2n = 2) and fix 0<D≤10 < D \le 1. Write c(vw)c(v w) for the bigram counts, c(v)=∑wc(vw)c(v) = \sum_w c(v w), c(w)=∑vc(vw)c(w) = \sum_v c(v w) and N=∑v,wc(vw)N = \sum_{v, w} c(v w). Let the bigram level be

P(w∣v)=max⁡(c(vw)−D,0)c(v)+D N1+(v ⋅)c(v) q(w)P(w \mid v) = \frac{\max(c(v w) - D, 0)}{c(v)} + \frac{D\, N_{1+}(v\, \cdot)}{c(v)}\, q(w)

for some distribution qq. Then the model keeps the unigram marginals of the data, that is

∑vc(v)NP(w∣v)=c(w)Nfor every w,\sum_v \frac{c(v)}{N} P(w \mid v) = \frac{c(w)}{N} \quad \text{for every } w,

if and only if q(w)=N1+(⋅ w)/N1+(⋅ ⋅)q(w) = N_{1+}(\cdot\, w) / N_{1+}(\cdot\, \cdot).

Proof. Multiply the bigram level by c(v)c(v) and sum over vv. Since D≤1D \le 1, the first term gives ∑v:c(vw)>0(c(vw)−D)=c(w)−D N1+(⋅ w)\sum_{v : c(v w) > 0} (c(v w) - D) = c(w) - D\, N_{1+}(\cdot\, w). The second term gives D q(w)∑vN1+(v ⋅)=D q(w) N1+(⋅ ⋅)D\, q(w) \sum_v N_{1+}(v\, \cdot) = D\, q(w)\, N_{1+}(\cdot\, \cdot), because both sums count the distinct bigram types. So

∑vc(v)P(w∣v)=c(w)−D N1+(⋅ w)+D q(w) N1+(⋅ ⋅),\sum_v c(v) P(w \mid v) = c(w) - D\, N_{1+}(\cdot\, w) + D\, q(w)\, N_{1+}(\cdot\, \cdot),

and this equals c(w)c(w) for every ww if and only if q(w)=N1+(⋅ w)/N1+(⋅ ⋅)q(w) = N_{1+}(\cdot\, w) / N_{1+}(\cdot\, \cdot), since D N1+(⋅ ⋅)>0D\, N_{1+}(\cdot\, \cdot) > 0. This qq is a distribution: its values are non-negative and sum to 1. □\square

This is the derivation of Chen and Goodman (1999, Section 2.7) for the interpolated form. The same computation at each level m<nm < n against the level above gives the continuation counts N1+(⋅ hw)N_{1+}(\cdot\, h w) of every lower level. Kneser and Ney (1995) reached the same lower distribution for the backoff form by a different derivation, as Chen and Goodman note.

Complexity

Line L1 visits the NN predicted tokens once. Line L2 visits each distinct (m+1)(m+1)-gram once for each level, at most NN keys per level, so training takes Θ(nN)\Theta(n N) expected n-gram operations with hash tables. A query makes one lookup per level, Θ(n)\Theta(n) operations, and a full distribution over VV takes Θ(n∣V∣)\Theta(n |V|). Each operation hashes a tuple of up to nn tokens, so in word operations each bound is a factor nn larger. The tables hold at most NN keys per level, Θ(nN)\Theta(n N) space.

Properties

  • A proper distribution. Every conditional distribution sums to 1 exactly for 0≤Dm≤10 \le D_m \le 1, and every word gets a positive probability when the discounts above level 1 are positive.
  • Marginals. The lower order is chosen so that the model keeps the lower order marginals of the training text, which is the reason for the continuation counts.
  • Interpolated. Every word, seen or not, gets a share of the lower level. In the backoff form only the unseen words do.
  • One discount per order. Counts of 1 and of 100 lose the same DmD_m. Modified Kneser-Ney uses three discounts.
  • Exact. All values are ratios of integer counts and rational discounts.

Variants and improvements

  • Backoff Kneser-Ney, the 1995 form, uses (c(hw)−D)/c(h)(c(h w) - D)/c(h) for the seen words and α(h)P(w∣h′)\alpha(h) P(w \mid h') for the rest, with α(h)\alpha(h) chosen to make the sum 1.
  • Modified Kneser-Ney smoothing uses the discounts D1D_1, D2D_2 and D3+D_{3+} for counts 1, 2 and 3 or more.
  • Absolute discounting is the same recursion with raw counts at every level.
  • The hierarchical Pitman-Yor language model of Teh (2006) is a Bayesian model whose approximate inference gives interpolated Kneser-Ney; MacKay and Peto (1995) had built a hierarchical Dirichlet model in the same spirit.
  • Jelinek-Mercer smoothing and Dirichlet prior smoothing are the retrieval versions of linear interpolation with a background model.

When to use it

Use it as the default smoothing for a count-based n-gram model, for example in a speech recognizer, in a spelling corrector, or as a baseline for a neural model measured by perplexity. Use the modified form if you have enough data to estimate three discounts. For very large web corpora where a proper distribution is not needed, stupid backoff is cheaper to build. To make the model smaller, prune it with entropy-based pruning.

Pitfalls

  • Raw counts in the lower levels. The continuation counts are the point of the method. With c(w)c(w) in the lower levels it is absolute discounting.
  • Only the unigram level changed. Every level below nn uses continuation counts, not only level 1.
  • A discount above 1. Then words seen once lose more than their count, and the sum exceeds 1. The default n1/(n1+2n2)n_1 / (n_1 + 2 n_2) is always in (0,1](0, 1], but it fails when n1=0n_1 = 0.
  • Sentence starts. Without the padding, an n-gram at the start of a sentence has no left context, and its continuation count is 0. The padding with <s> gives it the context <s>.
  • Unseen words. With D1=0D_1 = 0 a word that never appeared in training gets 0. Map such words to <unk>, or use D1>0D_1 > 0 so the uniform level gets some mass.
  • Testing with floats. Check that rows sum to 1 in exact arithmetic; float sums hide small errors in the weights.

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.

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

"""Interpolated Kneser-Ney smoothing of an n-gram language model, 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 the raw counts a_n(g) = c(g). Each lower level m < n uses the
continuation counts a_m(g) = N_1+(. g), the number of distinct tokens x such
that the (m + 1)-gram x g was seen. With T(h) = sum_x a_m(h x) and
N_1+(h .) the number of x with a_m(h x) > 0, the recursion is

    P_m(w | h) = max(a_m(h w) - D_m, 0) / T(h) + D_m N_1+(h .) / T(h) P_m-1(w | h')
    P_m(w | h) = P_m-1(w | h')                     if T(h) = 0

where h' is h without its first token. Below level 1 sits the uniform
distribution 1 / |V|. The discount of level 1 is 0 by default, so level 1 is
the continuation unigram N_1+(. w) / N_1+(. .).
"""

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

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


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]:  # each distinct (m + 1)-gram x g adds one left context of g
            a[m][g[1:]] += 1  # @line L2
    return a


def default_discount(counts: Counter) -> Fraction:
    """D = n_1 / (n_1 + 2 n_2), from the counts of counts of one level."""
    cc = Counter(counts.values())
    n1, n2 = cc[1], cc[2]
    if n1 == 0:
        raise ValueError("no count equals 1 at this level; give the discounts explicitly")
    return Fraction(n1, n1 + 2 * n2)  # @line L3


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

    def __init__(
        self,
        corpus: Iterable[Sequence[str]],
        n: int,
        discounts: Sequence[Fraction | int] | None = None,
        vocab: Iterable[str] | None = None,
    ):
        """discounts[m - 1] is D_m for m = 1 to n. By default D_1 = 0 and D_m = n_1 / (n_1 + 2 n_2)."""
        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 = [Fraction(0)] + [default_discount(self.a[m]) for m in range(2, n + 1)]
        if len(discounts) != n:
            raise ValueError("give one discount for each order 1 to n")
        self.d = {m: Fraction(discounts[m - 1]) for m in range(1, n + 1)}
        for m, d in self.d.items():
            if not 0 <= d <= 1:
                raise ValueError(f"the discount of order {m} must be in [0, 1]")
        if self.d[1] == 0 and self.vocab != seen:
            raise ValueError("a vocabulary larger than the training tokens needs D_1 > 0")
        # T(h) and N_1+(h .) for every history of every level.
        self.total = {m: Counter() for m in range(1, n + 1)}
        self.types = {m: Counter() for m in range(1, n + 1)}
        for m in range(1, n + 1):
            for g, k in self.a[m].items():
                self.total[m][g[:-1]] += k
                self.types[m][g[:-1]] += 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
        d = self.d[m]
        gamma = d * self.types[m][h] / t  # @line L7
        return max(self.a[m][h + (w,)] - d, Fraction(0)) / 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."""
        total = 0.0
        sent = list(sent)
        for i, w in enumerate(sent + [EOS]):
            total += log_fraction(self.prob(w, sent[:i]))
        return total


def log_fraction(p: Fraction) -> float:
    """ln p for a positive Fraction, without converting a tiny p to float first."""
    if p <= 0:
        raise ValueError("the log of a probability needs p > 0")
    return math.log(p.numerator) - math.log(p.denominator)
test_kneser_ney_smoothing.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kneser-ney-smoothing/. The authors are listed in prov/M3W0NG.jsonl.

import math
import random
from fractions import Fraction

import pytest

from kneser_ney_smoothing import BOS, EOS, KneserNeyLM, default_discount, level_counts, log_fraction

CHECK = [["a", "b"], ["a", "c"], ["b", "c"]]


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 histories(lm, corpus):
    """Sentence prefixes that reach every seen history, plus a few unseen ones."""
    out = {()}
    for s in corpus:
        for i in range(len(s) + 1):
            out.add(tuple(s[:i]))
    out.add(("zz",) * (lm.n - 1))
    return out


def test_check_value_bigram():
    lm = KneserNeyLM(CHECK, 2, discounts=[0, Fraction(3, 4)])
    assert len(lm.a[2]) == 7
    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_continuation_unigram():
    lm = KneserNeyLM(CHECK, 2, discounts=[0, Fraction(3, 4)])
    uni = {w: lm._prob(w, ()) for w in lm.vocab}
    assert uni == {"a": Fraction(1, 7), "b": Fraction(2, 7), "c": Fraction(2, 7), EOS: Fraction(2, 7)}


def test_lower_level_uses_continuation_counts_not_raw_counts():
    # "francisco" is frequent but follows only "san"; "the" follows many words.
    corpus = [["san", "francisco"]] * 5 + [["a", "the"], ["b", "the"], ["c", "the"]]
    lm = KneserNeyLM(corpus, 2, discounts=[0, Fraction(3, 4)])
    assert lm.a[1][("francisco",)] == 1
    assert lm.a[1][("the",)] == 3
    # Raw counts are 5 and 3, but the lower level ranks the two words the other way.
    assert lm._prob("francisco", ()) == Fraction(1, 10)
    assert lm._prob("the", ()) == Fraction(3, 10)
    # Neither word was seen after "francisco", so the lower level decides.
    assert lm.prob("the", ["san", "francisco"]) == 3 * lm.prob("francisco", ["san", "francisco"])


def naive_prob(corpus, n, d, vocab, w, h):
    """The same model, with every count found again by a scan over all positions."""
    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})

    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
    types = sum(1 for x in followers if a(h + (x,)) > 0)
    return max(a(h + (w,)) - d[m - 1], Fraction(0)) / t +d[m - 1] * Fraction(types, t) * lower


@pytest.mark.parametrize("n", [1, 2, 3])
def test_matches_naive_reference(n):
    corpus = random_corpus(7 + n, 12, ["x", "y", "z", "u"], 5)
    lm = KneserNeyLM(corpus, n, discounts=[Fraction(1, 3)] + [Fraction(2, 3)] * (n - 1), vocab=["x", "y", "z", "u", "v"])
    d = [lm.d[m] for m in range(1, n + 1)]
    for toks in list(histories(lm, corpus))[: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, 4)])
def test_every_distribution_sums_to_one(n, seed):
    corpus = random_corpus(seed, 40, ["a", "b", "c", "d", "e"], 6)
    lm = KneserNeyLM(corpus, n)
    for toks in histories(lm, corpus):
        dist = lm.distribution(toks)
        assert sum(dist.values()) == 1
        assert all(p > 0 for p in dist.values())


def test_sums_to_one_with_open_vocabulary_and_uniform_base():
    corpus = random_corpus(11, 30, ["a", "b", "c"], 5)
    lm = KneserNeyLM(corpus, 3, discounts=[Fraction(1, 2), Fraction(3, 4), Fraction(3, 4)], vocab=["a", "b", "c", "<unk>", "q"])
    for toks in histories(lm, corpus):
        dist = lm.distribution(toks)
        assert sum(dist.values()) == 1
        assert dist["q"] > 0


def test_default_discount_from_counts_of_counts():
    corpus = random_corpus(5, 50, ["a", "b", "c", "d"], 6)
    a = level_counts(corpus, 3)
    for m in (2, 3):
        n1 = sum(1 for k in a[m].values() if k == 1)
        n2 = sum(1 for k in a[m].values() if k == 2)
        assert default_discount(a[m]) == Fraction(n1, n1 + 2 * n2)
    lm = KneserNeyLM(corpus, 3)
    assert lm.d[1] == 0
    assert lm.d[3] == default_discount(a[3])


def test_log_space_where_the_product_underflows():
    corpus = random_corpus(3, 30, ["a", "b", "c", "d", "e", "f"], 8)
    lm = KneserNeyLM(corpus, 2)
    rng = random.Random(9)
    long_sent = [rng.choice(["a", "b", "c", "d", "e", "f"]) for _ in range(1500)]
    product = 1.0
    log_sum = 0.0
    for i, w in enumerate(long_sent + [EOS]):
        p = lm.prob(w, long_sent[:i])
        product *= float(p)
        log_sum += math.log(float(p))
    assert product == 0.0
    lp = lm.sentence_logprob(long_sent)
    assert math.isfinite(lp) and lp < -745
    assert lp == pytest.approx(log_sum, rel=1e-12)
    assert log_fraction(Fraction(1, 10**400)) == pytest.approx(-400 * math.log(10))


def test_bad_input():
    with pytest.raises(ValueError):
        KneserNeyLM(CHECK, 0)
    with pytest.raises(ValueError):
        KneserNeyLM(CHECK, 2, discounts=[0, Fraction(5, 4)])
    with pytest.raises(ValueError):
        KneserNeyLM(CHECK, 2, discounts=[0, Fraction(1, 2)], vocab=["a", "b", "c", "q"])
    lm = KneserNeyLM(CHECK, 2, discounts=[0, Fraction(3, 4)])
    with pytest.raises(KeyError):
        lm.prob("q")

History

Kneser and Ney (1995) proposed a backoff model whose lower order distribution is fitted so that the model keeps the marginals of the data, which gives the counts of distinct contexts. Their paper was about backoff. Chen and Goodman (1998, 1999) gave the interpolated form, derived it from the same constraint, and found that it beats the backoff form in their experiments; they note that Ney and colleagues had observed this independently. In the same work they introduced modified Kneser-Ney. MacKay and Peto (1995) had built a hierarchical Dirichlet language model, and Teh (2006) gave the Bayesian reading of the method: he showed that interpolated Kneser-Ney comes out of approximate inference in a hierarchical Pitman-Yor language model.

References

  1. Reinhard Kneser and Hermann Ney, Improved backing-off for M-gram language modeling, Proceedings of ICASSP 1995, volume 1, pages 181 to 184, the backoff model whose lower order distribution counts the distinct contexts of a word
  2. 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 2.6 (absolute discounting and the estimate D = n_1 / (n_1 + 2 n_2)), Section 2.7 on pages 366 to 368 (the marginal constraint and the interpolated form, equations 12 to 14), Section 2.8 (backoff against interpolation), Section 4.1 (the implementation with N_1+ counts at every lower order)
  3. Chen and Goodman 1998, the longer report behind the 1999 paper, with the interpolated and modified forms
  4. David J. C. MacKay and Linda C. Bauman Peto, A hierarchical Dirichlet language model, Natural Language Engineering 1(3), 1995, pages 289 to 308, a Bayesian n-gram model with Dirichlet priors shared across orders
  5. Teh 2006, interpolated Kneser-Ney as an approximate inference scheme in a hierarchical Pitman-Yor language model

Where this leads

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