Algorithm Search⌘K

Algorithmadvanced

Entropy-based n-gram pruning

Also called Stolcke pruning, relative entropy pruning.

Remove the n-grams whose removal least raises the relative entropy between the original and pruned backoff models, below a threshold.

Time
Θ(n E) prune
Space
Θ(E) extra
Where
E = the number of explicit n-grams; N = the number of predicted training tokens; n = the order of the model
Properties
deterministicnot exactgreedyoffline
Origin
Andreas Stolcke, 1998

Entropy-based pruning makes a backoff n-gram language model smaller with the least possible loss. A backoff model stores an explicit probability for each seen n-gram and falls back to a shorter history for the rest. Many explicit n-grams are almost useless: the backoff estimate would give them nearly the same probability. Stolcke measured the cost of removing one n-gram as the relative entropy between the model before and after, gave a closed form for it that needs only a few sums per history, and removed every n-gram whose cost is below a threshold. On Broadcast News a trigram model kept 26 percent of its size with no loss in word error rate.

In plain words

A backoff model remembers a number for each word sequence it saw. If it has no number for a sequence, it makes a guess from a shorter sequence.

For each stored number, ask: if I forget it and use the guess instead, how much worse does the model get? The answer has a precise measure, and it can be computed fast, because only the guesses after one history change.

Forget every number for which the answer is very small. Then fix the weights of the guesses so that the chances add up to one again. The model gets much smaller and predicts almost as well.

The problem

The input is a backoff model in the form of Katz backoff: for each history hh of length 1 to n−1n - 1 it has a set E(h)E(h) of explicit words with stored probabilities p∗(w∣h)p^*(w \mid h), and

p(w∣h)=p∗(w∣h) if w∈E(h),p(w∣h)=α(h) p(w∣h′) otherwise,p(w \mid h) = p^*(w \mid h) \text{ if } w \in E(h), \qquad p(w \mid h) = \alpha(h)\, p(w \mid h') \text{ otherwise},

where h′h' is hh without its first token and α(h)\alpha(h) makes the row sum to 1. With S1(h)=∑v∈E(h)p∗(v∣h)S_1(h) = \sum_{v \in E(h)} p^*(v \mid h) and S2(h)=∑v∈E(h)p(v∣h′)S_2(h) = \sum_{v \in E(h)} p(v \mid h'),

α(h)=1−S1(h)1−S2(h).\alpha(h) = \frac{1 - S_1(h)}{1 - S_2(h)}.

The unigrams are never removed. The task is to remove explicit n-grams so that the model gets small while its distribution stays close to the original. Stolcke measures closeness with the relative entropy of the joint models,

D(p∥p′)=∑hp(h)∑wp(w∣h)ln⁡p(w∣h)p′(w∣h).D(p \parallel p') = \sum_h p(h) \sum_w p(w \mid h) \ln \frac{p(w \mid h)}{p'(w \mid h)}.

Finding the best subset of a given size is a hard combinatorial problem, so the method scores each n-gram alone and uses a threshold.

The algorithm

Removing hwh w alone changes only the row of hh: ww moves from the explicit set to the backed off set, and the weight becomes α′(h)\alpha'(h). All costs are computed on the original model, then the marked n-grams are removed together.

  1. PRUNE(model p, threshold θ)
  2. 1for each explicit n-gram h w of order 2 or more:
  3. 2p(h) ← the probability of h by the chain rule of p
  4. 3α'(h) ← (1 - S_1(h) + p*(w | h)) / (1 - S_2(h) + p(w | h'))
  5. 4B ← α(h) (1 - S_2(h)) ▷ the total probability of the backed off words of h
  6. 5D ← p(h) [ p*(w | h) ln( p*(w | h) / (α'(h) p(w | h')) ) + B ln( α(h) / α'(h) ) ]
  7. 6if e^D - 1 < θ then mark h w
  8. 7remove the marked n-grams and recompute α(h) for every h

Line L2 multiplies the model probabilities of the tokens of hh, each after the tokens before it; leading <s> pads count as 1. Lines L3 and L4 use S1(h)S_1(h) and S2(h)S_2(h), which are computed once per history. Line L5 is the relative entropy of the row of hh, weighted by p(h)p(h). Line L6 compares the relative increase of the perplexity, eD−1e^D - 1, with θ\theta.

The implementation builds the input model from a corpus with absolute discounting, p∗(w∣h)=(c(hw)−d)/c(h)p^*(w \mid h) = (c(h w) - d)/c(h) for every seen n-gram and d=1/2d = 1/2, and keeps the unigram undiscounted. It computes the costs from exact fractions and takes the logs in floats.

Example

Take the four sentences "a b", "a c", "b c" and "a b" with n=2n = 2 and d=1/2d = 1/2. The 12 predicted tokens give the unigram p(a)=p(b)=1/4p(\text{a}) = p(\text{b}) = 1/4, p(c)=1/6p(\text{c}) = 1/6 and p(</s>)=1/3p(\text{</s>}) = 1/3. After a, the bigram a b was seen twice and a c once, so p∗(b∣a)=1/2p^*(\text{b} \mid \text{a}) = 1/2, p∗(c∣a)=1/6p^*(\text{c} \mid \text{a}) = 1/6 and

α(a)=1−2/31−(1/4+1/6)=47.\alpha(\text{a}) = \frac{1 - 2/3}{1 - (1/4 + 1/6)} = \frac47.

To remove a c: α′(a)=(1−1/2)/(1−1/4)=2/3\alpha'(\text{a}) = (1 - 1/2)/(1 - 1/4) = 2/3, so c would get 23⋅16=19\frac23 \cdot \frac16 = \frac19 instead of 16\frac16. The backed off words a and </s> have B=1/3B = 1/3, and p(a)=1/4p(\text{a}) = 1/4 as a history. So

D=14[16ln⁡1/61/9+13ln⁡4/72/3]≈0.004048.D = \frac14 \left[ \frac16 \ln \frac{1/6}{1/9} + \frac13 \ln \frac{4/7}{2/3} \right] \approx 0.004048.

All seven explicit bigrams:

n-gram p(h)p(h) p∗(w∣h)p^*(w \mid h) DD eD−1e^D - 1
<s> a 1 5/8 0.264513 0.302796
<s> b 1 1/8 0 0
a b 1/4 1/2 0.040009 0.040820
a c 1/4 1/6 0.004048 0.004057
b </s> 1/4 1/2 0.016894 0.017038
b c 1/4 1/6 0.002172 0.002174
c </s> 1/6 3/4 0.060498 0.062366

The bigram <s> b costs nothing: after its removal α′(<s>)⋅p(b)=12⋅14=18\alpha'(\text{<s>}) \cdot p(\text{b}) = \frac12 \cdot \frac14 = \frac18, which is the stored value. With θ=0.01\theta = 0.01 the bigrams <s> b, a c and b c are removed. The new weights are α(a)=2/3\alpha(\text{a}) = 2/3 and α(b)=3/4\alpha(\text{b}) = 3/4, every row still sums to 1, and the perplexity of the training text goes from about 2.383 to about 2.525.

Correctness

The proof in the proofs file has four parts. Every row of the model sums to 1 and is positive, for the full model and for every pruned model, because S1(h)<1S_1(h) < 1 when d>0d > 0 and S2(h)<1S_2(h) < 1 when some word is not explicit. Removing hwh w changes no row of a history of length at most ∣h∣|h| except the row of hh, so the lower probabilities in line L5 are the same before and after. Splitting the relative entropy of the row of hh into the explicit words, ww and the backed off words gives the closed form of line L5, since the explicit words keep their values and every backed off word changes by the same ratio α/α′\alpha/\alpha'. Finally, θ=0\theta = 0 prunes nothing, a larger θ\theta prunes a superset, and the costs add up when the removed top order n-grams have different histories.

Proof: The closed form of Stolcke gives the relative entropy caused by removing one explicit n-gram, and the pruned model with recomputed backoff weights is again a proper positive distribution after every historyfull

We use the notation of the page. The backoff model has a set E(h)E(h) of explicit words for each history hh of length 1 to n−1n - 1, and

p(w∣h)=p∗(w∣h)=c(hw)−dc(h) if w∈E(h),p(w∣h)=α(h) p(w∣h′) otherwise,p(w \mid h) = p^*(w \mid h) = \frac{c(h w) - d}{c(h)} \text{ if } w \in E(h), \qquad p(w \mid h) = \alpha(h)\, p(w \mid h') \text{ otherwise},

with 0<d<10 < d < 1, p(w)=c(w)/Np(w) = c(w)/N at the empty history, and α(h)=1\alpha(h) = 1 when E(h)E(h) is empty. Here h′h' is hh without its first token. Every w∈E(h)w \in E(h) has c(hw)≥1c(h w) \ge 1. Write S1(h)=∑v∈E(h)p∗(v∣h)S_1(h) = \sum_{v \in E(h)} p^*(v \mid h) and S2(h)=∑v∈E(h)p(v∣h′)S_2(h) = \sum_{v \in E(h)} p(v \mid h'). The backoff weight is

α(h)=1−S1(h)1−S2(h).\alpha(h) = \frac{1 - S_1(h)}{1 - S_2(h)}.

The model is defined only if E(h)≠VE(h) \ne V for the full model; the code raises an error otherwise.

Theorem 1 (a proper distribution). For every set of explicit n-grams with E(h)⊆{w:c(hw)>0}E(h) \subseteq \{w : c(h w) > 0\} and E(h)≠VE(h) \ne V, every row p(⋅∣h)p(\cdot \mid h) is positive on VV and sums to 1. In particular this holds for the full model and for every pruned model.

Proof. Induction on the length of hh. At the empty history p(w)=c(w)/N>0p(w) = c(w)/N > 0 and the sum is 1. Let hh be longer. If E(h)E(h) is empty, the row equals the row of h′h'. Otherwise S1(h)=∑v∈E(h)(c(hv)−d)/c(h)≤1−d∣E(h)∣/c(h)<1S_1(h) = \sum_{v \in E(h)} (c(h v) - d)/c(h) \le 1 - d |E(h)| / c(h) < 1, because ∑v∈E(h)c(hv)≤c(h)\sum_{v \in E(h)} c(h v) \le c(h). Since E(h)≠VE(h) \ne V there is a word outside E(h)E(h), and its lower probability is positive by the induction hypothesis, so S2(h)<1S_2(h) < 1. Hence α(h)>0\alpha(h) > 0. Each explicit word gets p∗(w∣h)≥(1−d)/c(h)>0p^*(w \mid h) \ge (1 - d)/c(h) > 0 and each other word gets α(h)p(w∣h′)>0\alpha(h) p(w \mid h') > 0. The sum is S1(h)+α(h)(1−S2(h))=S1(h)+1−S1(h)=1S_1(h) + \alpha(h)(1 - S_2(h)) = S_1(h) + 1 - S_1(h) = 1, using that the lower row sums to 1. A pruned model has E′(h)⊆E(h)E'(h) \subseteq E(h), so E′(h)≠VE'(h) \ne V again. □\square

Lemma 2 (what one removal changes). Remove the explicit n-gram hwh w and recompute α(h)\alpha(h). Then the rows of all histories of length at most ∣h∣|h| do not change, except the row of hh. If hwh w has the top order nn, no other row of length n−1n - 1 changes either.

Proof. The row of a history gg depends on E(g)E(g) and on the rows of the suffixes of gg. Only E(h)E(h) changes. A history of length at most ∣h∣|h| other than hh does not have hh as a suffix. A history of length n−1n - 1 other than hh has the same length as hh, so it does not have hh as a suffix either. □\square

So for a top order n-gram the relative entropy between the two joint models p(h)p(w∣h)p(h) p(w \mid h) is p(h)p(h) times the relative entropy of the row of hh. For a lower order n-gram the rows of the longer histories that back off to hh also change. Stolcke counts only the row of hh, and so does the code; this is the approximation of the method.

Theorem 3 (the closed form). Let p′p' be the model after removing hwh w. Then

α′(h)=1−S1(h)+p∗(w∣h)1−S2(h)+p(w∣h′),\alpha'(h) = \frac{1 - S_1(h) + p^*(w \mid h)}{1 - S_2(h) + p(w \mid h')},

and

p(h)∑v∈Vp(v∣h)ln⁡p(v∣h)p′(v∣h)=p(h)[p∗(w∣h)ln⁡p∗(w∣h)α′(h) p(w∣h′)+(1−S1(h))ln⁡α(h)α′(h)].p(h) \sum_{v \in V} p(v \mid h) \ln \frac{p(v \mid h)}{p'(v \mid h)} = p(h) \left[ p^*(w \mid h) \ln \frac{p^*(w \mid h)}{\alpha'(h)\, p(w \mid h')} + \big(1 - S_1(h)\big) \ln \frac{\alpha(h)}{\alpha'(h)} \right].

Proof. The new explicit set is E(h)∖{w}E(h) \setminus \{w\}, so the sums lose the term of ww, which gives α′(h)\alpha'(h). By Lemma 2 the lower rows do not change, so p(w∣h′)p(w \mid h') has the same value in both models. Split the sum over vv in three. For v∈E(h)v \in E(h) with v≠wv \ne w, p′(v∣h)=p∗(v∣h)=p(v∣h)p'(v \mid h) = p^*(v \mid h) = p(v \mid h), and the term is 0. For v=wv = w, p(w∣h)=p∗(w∣h)p(w \mid h) = p^*(w \mid h) and p′(w∣h)=α′(h)p(w∣h′)p'(w \mid h) = \alpha'(h) p(w \mid h'), which is the first term. For v∉E(h)v \notin E(h), p(v∣h)=α(h)p(v∣h′)p(v \mid h) = \alpha(h) p(v \mid h') and p′(v∣h)=α′(h)p(v∣h′)p'(v \mid h) = \alpha'(h) p(v \mid h'), so the ratio is α(h)/α′(h)\alpha(h)/\alpha'(h) for each such vv, and their total weight is ∑v∉E(h)p(v∣h)=1−S1(h)\sum_{v \notin E(h)} p(v \mid h) = 1 - S_1(h) by Theorem 1. □\square

Line L4 of the page computes this weight as α(h)(1−S2(h))\alpha(h)(1 - S_2(h)), which is the same number. The value is a relative entropy of two distributions, so it is at least 0 by Gibbs' inequality; the code clamps a float rounding error below 0 to 0.

Theorem 4 (the threshold). With the costs D(g)D(g) computed once on the original model:

  1. θ=0\theta = 0 prunes nothing;
  2. if θ1≤θ2\theta_1 \le \theta_2, every n-gram pruned at θ1\theta_1 is pruned at θ2\theta_2;
  3. if the pruned top order n-grams have pairwise different histories, the relative entropy of the pruned model is the sum of their costs. With two removed words after the same history it is not, in general.

Proof. (1) D(g)≥0D(g) \ge 0, so eD(g)−1≥0e^{D(g)} - 1 \ge 0 is never below 0. (2) The test eD(g)−1<θe^{D(g)} - 1 < \theta compares a fixed number with θ\theta. (3) By Lemma 2 each removal changes only its own row, and the rows of different histories enter the relative entropy as separate terms. Two removals from the same row change α(h)\alpha(h) together, and the new weight is not the one of either single removal. The test file has an example where the joint value differs from the sum by more than 10−610^{-6}. □\square

Why the threshold is a perplexity ratio. If text is drawn from pp, the cross entropy of p′p' on it is H(p)+D(p∥p′)H(p) + D(p \parallel p') per token, so the perplexity ratio is PP′/PP=eD\mathrm{PP}'/\mathrm{PP} = e^{D} and the relative increase is eD−1e^D - 1. The threshold θ\theta bounds this increase for each removed n-gram alone.

Complexity

With S1S_1, S2S_2 and p(h)p(h) cached for each history, each explicit n-gram costs a constant number of lookups plus O(n)O(n) for the chain rule of p(h)p(h), so the costs take Θ(nE)\Theta(n E) expected time with hash tables, for EE explicit n-grams. Recomputing the weights in line L7 sums the explicit words of each history once, Θ(E)\Theta(E) more. The extra space is Θ(E)\Theta(E) for the costs and the cached sums.

Properties

  • Greedy and one-pass. Every cost is computed on the original model and the n-grams are not ranked against each other; the joint effect of the removals is not computed.
  • A perplexity bound per n-gram. eD−1e^D - 1 is the relative increase of the perplexity on text drawn from the model, so θ\theta has a direct meaning.
  • Exact for one top order n-gram. For an n-gram of the top order the closed form is the exact relative entropy of the whole model. For a lower order n-gram it ignores the change in the longer histories that back off to it.
  • Monotone in θ\theta. A larger threshold removes a superset of the n-grams.
  • Model based. It needs only the model, not the training counts.

Variants and improvements

  • Weighted difference pruning (Seymore and Rosenfeld 1996) scores hwh w by N(hw)[ln⁡p(w∣h)−ln⁡p′(w∣h)]N(h w)[\ln p(w \mid h) - \ln p'(w \mid h)] with the training count N(hw)N(h w). It looks like the first term of line L5 with a count in place of p(h)p∗(w∣h)p(h) p^*(w \mid h), and it has no term for the backed off words.
  • Count cutoffs remove all n-grams seen fewer than kk times. They are simpler and use no model at all.
  • Pruning a smoothed model. The criterion works for any backoff model. With Kneser-Ney models the lower orders hold continuation probabilities, not estimates of the marginals, so p(h)p(h) from the chain rule and the backed off estimates are poor, and the costs are less accurate.
  • Iterative pruning recomputes the costs after each round. It sees the joint effect within a history at a higher cost.

When to use it

Use it to fit a backoff n-gram model into a fixed memory budget, for example on a device, in a first pass of a speech recognizer, or in a decoder where the model is held in memory. It needs a normalized backoff model. For unnormalized scores as in stupid backoff there is no relative entropy to compute.

Pitfalls

  • Forgetting to recompute α\alpha. After the removal the backoff weights must be recomputed, or the rows no longer sum to 1.
  • Sequential costs. Computing each cost on the partly pruned model makes the result depend on the order of the loop. Stolcke computes all costs on the original model.
  • Holes in the history set. In the ARPA file format a history that is still used by a longer n-gram must keep its entry. Some implementations keep the n-grams that are prefixes of kept n-grams.
  • The wrong p(h)p(h). Using the relative frequency of hh instead of the model probability changes the criterion; the method uses the chain rule of the model.
  • A row with no backed off words. If every word was seen after hh, α(h)\alpha(h) has no meaning, and its denominator is 0. The implementation rejects such a model.

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.

entropy_based_ngram_pruning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/entropy-based-ngram-pruning/. The authors are listed in prov/AG7MBF.jsonl.

"""Entropy-based pruning of a backoff n-gram model (Stolcke 1998).

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; "<s>" is never predicted.

The model is a backoff model with absolute discounting:

    p(w | h) = (c(h w) - d) / c(h)          if (h, w) is explicit
    p(w | h) = alpha(h) p(w | h')           otherwise
    p(w)     = c(w) / N

where h' is h without its first token and alpha(h) makes the row sum to 1.
Pruning removes explicit n-grams of order 2 or more. The cost of removing
(h, w) alone is the relative entropy D between the model and the model
without it, which only changes the row of h. All costs are computed on the
original model, the n-grams with exp(D) - 1 < theta are removed, and the
backoff weights are computed again.
"""

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

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


def log_fraction(p: Fraction) -> float:
    """ln p for a positive Fraction, without float underflow."""
    return math.log(p.numerator) - math.log(p.denominator)


class BackoffLM:
    """A backoff n-gram model with absolute discounting and an explicit n-gram set."""

    def __init__(self, corpus: Iterable[Sequence[str]], n: int, d: Fraction = Fraction(1, 2)):
        if n < 1:
            raise ValueError("the order n must be at least 1")
        if not 0 < d < 1:
            raise ValueError("the discount d must be in (0, 1)")
        self.n, self.d = n, Fraction(d)
        self.c: Counter = Counter()  # c(g) for every m-gram g ending at a predicted token
        self.ch: Counter = Counter()  # c(h) = sum_x c(h x)
        for sent in corpus:
            toks = [BOS] * (n - 1) + list(sent) + [EOS]
            for i in range(n - 1, len(toks)):
                for m in range(1, n + 1):
                    g = tuple(toks[i - m + 1 : i + 1])
                    self.c[g] += 1
                    self.ch[g[:-1]] += 1
        self.vocab = sorted(g[0] for g in self.c if len(g) == 1)
        self.total = self.ch[()]
        self.explicit: dict[tuple, set] = defaultdict(set)  # h -> the words w with (h, w) explicit
        for g in self.c:
            if len(g) >= 2:
                self.explicit[g[:-1]].add(g[-1])
        self._finish()

    def _finish(self) -> None:
        """Compute alpha(h) for every history with explicit words."""
        self._memo: dict = {}
        self.alpha: dict[tuple, Fraction] = {}
        for h, ws in self.explicit.items():
            if not ws:
                continue
            num = 1 - sum(self.pstar(h + (w,)) for w in ws)
            den = 1 - sum(self.prob(w, h[1:]) for w in ws)
            if den == 0:
                raise ValueError(f"every word was seen after {h}; nothing is left to back off to")
            self.alpha[h] = num / den

    def pstar(self, g: tuple) -> Fraction:
        """The discounted estimate of an explicit n-gram g = h w."""
        return (self.c[g] - self.d) / self.ch[g[:-1]]

    def num_explicit(self) -> int:
        return sum(len(ws) for ws in self.explicit.values())

    def history(self, tokens: Sequence[str]) -> tuple:
        if self.n == 1:
            return ()
        return tuple([BOS] * (self.n - 1) + list(tokens))[-(self.n - 1) :]

    def prob(self, w: str, h: tuple) -> Fraction:
        """p(w | h) for a history tuple of at most n - 1 tokens."""
        key = (w, h)
        if key not in self._memo:
            if not h:
                p = Fraction(self.c[(w,)], self.total)
            elif w in self.explicit.get(h, ()):
                p = self.pstar(h + (w,))
            else:
                p = self.alpha.get(h, Fraction(1)) * self.prob(w, h[1:])
            self._memo[key] = p
        return self._memo[key]

    def distribution(self, h: tuple) -> dict[str, Fraction]:
        return {w: self.prob(w, h) for w in self.vocab}

    def history_prob(self, h: tuple) -> Fraction:
        """p(h) by the chain rule of the model; the leading <s> pads have probability 1."""
        p = Fraction(1)
        for i, x in enumerate(h):
            if x != BOS:
                p *= self.prob(x, h[:i][-(self.n - 1) :] if self.n > 1 else ())
        return p

    def sentence_logprob(self, sent: Sequence[str]) -> float:
        sent = list(sent)
        return sum(log_fraction(self.prob(w, self.history(sent[:i]))) for i, w in enumerate(sent + [EOS]))

    def without(self, removed: Iterable[tuple]) -> "BackoffLM":
        """A copy of the model with the explicit n-grams in removed taken out and alpha recomputed."""
        new = object.__new__(BackoffLM)
        new.n, new.d, new.c, new.ch, new.vocab, new.total = self.n, self.d, self.c, self.ch, self.vocab, self.total
        new.explicit = defaultdict(set, {h: set(ws) for h, ws in self.explicit.items()})
        for g in removed:
            if len(g) < 2:
                raise ValueError("unigrams are never pruned")
            new.explicit[g[:-1]].discard(g[-1])
        new._finish()
        return new


def pruning_cost(lm: BackoffLM, g: tuple, sums: dict | None = None) -> float:
    """D(p || p') when only the explicit n-gram g = h w is removed from lm."""
    h, w = g[:-1], g[-1]
    if w not in lm.explicit.get(h, ()):
        raise ValueError(f"{g} is not an explicit n-gram")
    if sums is None or h not in sums:
        s1 = sum(lm.pstar(h + (v,)) for v in lm.explicit[h])
        s2 = sum(lm.prob(v, h[1:]) for v in lm.explicit[h])
        if sums is not None:
            sums[h] = (s1, s2)
    else:
        s1, s2 = sums[h]
    ph = lm.history_prob(h)  # @line L2
    p, lower = lm.pstar(g), lm.prob(w, h[1:])
    alpha = lm.alpha[h]
    alpha_new = (1 - s1 + p) / (1 - s2 + lower)  # @line L3
    backed_off = alpha * (1 - s2)  # @line L4
    cost = ph * (p * (log_fraction(p) - log_fraction(alpha_new * lower)))
    if backed_off > 0:
        cost += ph * backed_off * (log_fraction(alpha) - log_fraction(alpha_new))
    return max(float(cost), 0.0)  # @line L5


def prune(lm: BackoffLM, theta: float) -> tuple[BackoffLM, list[tuple]]:
    """Remove every explicit n-gram whose relative perplexity increase exp(D) - 1 is below theta."""
    if theta < 0:
        raise ValueError("theta must be at least 0")
    sums: dict = {}
    marked = []
    for h in sorted(lm.explicit):
        for w in sorted(lm.explicit[h]):  # @line L1
            if math.expm1(pruning_cost(lm, h + (w,), sums)) < theta:  # @line L6
                marked.append(h + (w,))
    return lm.without(marked), marked  # @line L7
test_entropy_based_ngram_pruning.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/entropy-based-ngram-pruning/. The authors are listed in prov/AG7MBF.jsonl.

import math
import random
from fractions import Fraction

import pytest

from entropy_based_ngram_pruning import BOS, EOS, BackoffLM, log_fraction, prune, pruning_cost

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


def zipf_corpus(seed, sentences, size, max_len):
    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(1, max_len)) for _ in range(sentences)]


def kl(p, q):
    return sum(float(p[v]) * (log_fraction(p[v]) - log_fraction(q[v])) for v in p if p[v] > 0)


def brute_cost(lm, g):
    """Remove g by hand, renormalize the row of h directly, and take p(h) times the KL of the row."""
    h, w = g[:-1], g[-1]
    keep = lm.explicit[h] - {w}
    old = lm.distribution(h)
    lower = lm.distribution(h[1:])
    left = 1 - sum(lm.pstar(h + (v,)) for v in keep)
    lower_left = sum(lower[v] for v in lm.vocab if v not in keep)
    new = {v: lm.pstar(h + (v,)) if v in keep else left * lower[v] / lower_left for v in lm.vocab}
    assert sum(new.values()) == 1
    return float(lm.history_prob(h)) * kl(old, new)


def full_kl(lm, pruned):
    """The sum over every seen history of length n - 1 of p(h) KL(row of lm, row of pruned)."""
    total = 0.0
    for h in lm.ch:
        if len(h) == lm.n - 1:
            total += float(lm.history_prob(h)) * kl(lm.distribution(h), pruned.distribution(h))
    return total


def explicit_ngrams(lm, order=None):
    return [h + (w,) for h in sorted(lm.explicit) for w in sorted(lm.explicit[h]) if order in (None, len(h) + 1)]


def test_small_model_by_hand():
    lm = BackoffLM(SMALL, 2)
    assert lm.alpha == {(BOS,): Fraction(1, 2), ("a",): Fraction(4, 7), ("b",): Fraction(2, 3), ("c",): Fraction(3, 8)}
    assert lm.distribution((BOS,)) == {EOS: Fraction(1, 6), "a": Fraction(5, 8), "b": Fraction(1, 8), "c": Fraction(1, 12)}
    assert lm.distribution(("c",)) == {EOS: Fraction(3, 4), "a": Fraction(3, 32), "b": Fraction(3, 32), "c": Fraction(1, 16)}
    # removing <s> b changes nothing: alpha'(<s>) p(b) = 1/2 * 1/4 = 1/8 = p*(b | <s>)
    assert pruning_cost(lm, (BOS, "b")) == 0.0
    assert lm.without([(BOS, "b")]).distribution((BOS,)) == lm.distribution((BOS,))
    assert pruning_cost(lm, ("a", "c")) == pytest.approx(brute_cost(lm, ("a", "c")), rel=1e-12)


def test_history_prob_is_the_chain_rule():
    lm = BackoffLM(SMALL, 3)
    assert lm.history_prob((BOS, BOS)) == 1
    assert lm.history_prob((BOS, "a")) == lm.prob("a", (BOS,))
    assert lm.history_prob(("a", "b")) == lm.prob("a", ()) * lm.prob("b", ("a",))


@pytest.mark.parametrize("n,seed", [(2, 1), (3, 2), (4, 3)])
def test_cost_matches_brute_force(n, seed):
    lm = BackoffLM(zipf_corpus(seed, 40, 15, 5), n)
    for g in explicit_ngrams(lm):
        assert pruning_cost(lm, g) == pytest.approx(brute_cost(lm, g), rel=1e-9, abs=1e-15)


@pytest.mark.parametrize("n,seed", [(2, 4), (3, 5)])
def test_top_order_cost_is_the_model_relative_entropy(n, seed):
    lm = BackoffLM(zipf_corpus(seed, 40, 15, 5), n)
    for g in explicit_ngrams(lm, order=n)[::3]:
        assert pruning_cost(lm, g) == pytest.approx(full_kl(lm, lm.without([g])), rel=1e-9, abs=1e-15)


def test_costs_add_only_across_different_histories():
    lm = BackoffLM(zipf_corpus(6, 40, 15, 5), 2)
    by_h = {}
    for g in explicit_ngrams(lm):
        by_h.setdefault(g[:-1], []).append(g)
    hs = [h for h in sorted(by_h) if len(by_h[h]) >= 2]
    g1, g2 = by_h[hs[0]][:2]
    same = full_kl(lm, lm.without([g1, g2]))
    assert abs(same - (pruning_cost(lm, g1) + pruning_cost(lm, g2))) > 1e-6
    g3 = by_h[hs[1]][0]
    apart = full_kl(lm, lm.without([g1, g3]))
    assert apart == pytest.approx(pruning_cost(lm, g1) + pruning_cost(lm, g3), rel=1e-9)


@pytest.mark.parametrize("n,seed", [(2, 7), (3, 8)])
def test_rows_sum_to_one_after_pruning(n, seed):
    lm = BackoffLM(zipf_corpus(seed, 60, 20, 6), n)
    histories = {h for h in lm.ch if len(h) <= n - 1} | {("zz",) * (n - 1)}
    for theta in [0, 1e-4, 1e-3, 1e-2]:
        pruned, _ = prune(lm, theta)
        for h in histories:
            row = pruned.distribution(h[-(n - 1) :] if n > 1 else ())
            assert sum(row.values()) == 1 and all(p > 0 for p in row.values())


def test_threshold_order():
    lm = BackoffLM(zipf_corpus(9, 80, 20, 6), 3)
    assert prune(lm, 0)[1] == []
    sizes, last = [], set()
    for theta in [0, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1]:
        pruned, marked = prune(lm, theta)
        assert last <= set(marked)
        last = set(marked)
        sizes.append(pruned.num_explicit())
        assert pruned.num_explicit() + len(marked) == lm.num_explicit()
    assert sizes == sorted(sizes, reverse=True) and sizes[0] > sizes[-1]


def test_huge_threshold_leaves_the_unigram():
    lm = BackoffLM(zipf_corpus(10, 40, 15, 5), 3)
    pruned, marked = prune(lm, 1e9)
    assert len(marked) == lm.num_explicit() and pruned.num_explicit() == 0
    uni = pruned.distribution(())
    assert pruned.distribution(("w0", "w1")) == uni
    assert uni == {w: Fraction(lm.c[(w,)], lm.total) for w in lm.vocab}


def test_pruned_model_is_close_on_training_text():
    corpus = zipf_corpus(11, 80, 20, 6)
    lm = BackoffLM(corpus, 3)
    pruned, marked = prune(lm, 1e-3)
    assert marked
    full = sum(lm.sentence_logprob(s) for s in corpus)
    small = sum(pruned.sentence_logprob(s) for s in corpus)
    assert small < full  # the training text loses probability, but not much
    tokens = sum(len(s) + 1 for s in corpus)
    assert math.exp((full - small) / tokens) < 1.5


def test_log_space_where_the_product_underflows():
    lm = BackoffLM(zipf_corpus(12, 40, 15, 5), 3)
    rng = random.Random(13)
    sent = [rng.choice(lm.vocab[1:]) for _ in range(1500)]
    product = 1.0
    for i, w in enumerate(sent + [EOS]):
        product *= float(lm.prob(w, lm.history(sent[:i])))
    assert product == 0.0
    assert lm.sentence_logprob(sent) < -745


def test_bad_input():
    lm = BackoffLM(SMALL, 2)
    with pytest.raises(ValueError):
        BackoffLM(SMALL, 0)
    with pytest.raises(ValueError):
        BackoffLM(SMALL, 2, d=1)
    with pytest.raises(ValueError):
        prune(lm, -1)
    with pytest.raises(ValueError):
        lm.without([("a",)])
    with pytest.raises(ValueError):
        pruning_cost(lm, ("c", "a"))
    with pytest.raises(ValueError):
        BackoffLM([["a", "a"]], 2)  # a is followed by every word, a and </s>

History

Seymore and Rosenfeld (1996) pruned backoff models by a weighted difference of the log probabilities before and after the removal of an n-gram. Stolcke (1998) replaced it with the relative entropy between the two models, showed that it has a closed form that needs only sums over the explicit words of one history, and defined the threshold as the relative increase of the perplexity. On Broadcast News, with the threshold 10−810^{-8}, a trigram model was cut to 26 percent of its size, its perplexity rose from 163.0 to 172.3, and the word error rate stayed at 32.6 percent. He found that the pruned sets of the two methods overlap by about 85 percent. The method is in the SRILM toolkit.

References

  1. Stolcke 1998, the pruning criterion (equation 2 for the relative entropy of one removal, the new backoff weight and the threshold on the relative perplexity increase), Section 4 (the Broadcast News results), Section 5 (the comparison with Seymore and Rosenfeld)
  2. Seymore and Rosenfeld 1996, the weighted difference criterion for pruning n-grams from a backoff model

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.prune
  • 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
  • at least three sources
  • a scene preset for the example