Algorithm Search⌘K

Algorithmadvanced

Stupid backoff

Also called Brants stupid backoff.

Unnormalized scores for very large n-gram models: the relative frequency if seen, else 0.4 times the score of the shorter n-gram.

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
Thorsten Brants, Ashok C. Popat, Peng Xu, Franz J. Och, Jeffrey Dean, 2007

Stupid backoff is a way to use an n-gram language model built from far more text than a normal smoothing method can handle. If the n-gram hwh w was seen, its score is the relative frequency c(hw)/c(h)c(h w)/c(h). If not, the score is a fixed factor α=0.4\alpha = 0.4 times the score of ww after the shorter history. There is no discount and no normalization, so the scores are not probabilities, and Brants and colleagues write SS for them instead of PP. In exchange, the model needs nothing but raw counts, which are easy to compute and to look up in a distributed system. On very large data it gave machine translation quality close to that of Kneser-Ney smoothing.

In plain words

To score the next word, look at what followed the same last few words in the training text. If the word appeared there, its score is the fraction of times it came next.

If it never came next, forget the oldest word of the history and look again with the shorter history. Each time you do this, multiply the score by 0.4, as a fixed penalty for having less context. With no history left, the score is just how often the word appears in the whole text.

The scores do not add up to one. That is fine for a translation system that only compares candidate sentences, and it makes the model very cheap to build from huge amounts of text.

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. Write c(g)c(g) for the number of times the m-gram gg (1≤m≤n1 \le m \le n) ends at a predicted token, NN for the number of predicted tokens and VV for the set of predicted tokens. For a history hh write c(h)=∑xc(hx)c(h) = \sum_x c(h x), the number of times hh is followed by a predicted token, and h′h' for hh without its first token.

The task is to give a score to every word ww after every history hh of n−1n - 1 tokens. The score must be cheap to compute from raw counts held on many machines, it must prefer words seen after longer histories, and it does not have to be a probability. The definition of Brants and colleagues is

S(w∣h)={c(hw)c(h)if c(hw)>0,α S(w∣h′)otherwise,S(w)=c(w)N,S(w \mid h) = \begin{cases} \dfrac{c(h w)}{c(h)} & \text{if } c(h w) > 0, \\[1ex] \alpha\, S(w \mid h') & \text{otherwise,} \end{cases} \qquad S(w) = \frac{c(w)}{N},

with α=0.4\alpha = 0.4.

The algorithm

Training is one pass of counting: at each predicted position, add one to the count of every m-gram that ends there, for m=1,…,nm = 1, \ldots, n, and one to the count of its history. At web scale this is a MapReduce word count over n-grams. A query walks down from the full history until it finds a seen n-gram.

  1. SB-SCORE(w, h) ▷ h holds the last m - 1 tokens
  2. 1if c(h w) > 0 then
  3. 2return c(h w) / c(h)
  4. 3if h is empty then return 0 ▷ w was never seen
  5. 4return α · SB-SCORE(w, h')

The implementation keeps c(h)c(h) in its own table. Brants and colleagues divide by the raw frequency of the history; the two are equal for every history without <s>, because such a history is always followed by a predicted token, at least </s>.

Example

Take the three sentences "a b", "a c" and "b c" with n=2n = 2 and α=2/5\alpha = 2/5. There are N=9N = 9 predicted tokens: a, b and c twice each, and </s> three times, so the unigram scores are 2/9, 2/9, 2/9 and 3/9. After <s>, a was seen twice and b once out of c(<s>)=3c(\text{<s>}) = 3; c and </s> were not seen there, so they back off to 25⋅29=445\frac25 \cdot \frac29 = \frac4{45} and 25⋅39=215\frac25 \cdot \frac39 = \frac2{15}. The whole model is:

hh a b c </s> sum
<s> 2/3 1/3 4/45 2/15 11/9
a 4/45 1/2 1/2 2/15 11/9
b 4/45 4/45 1/2 1/2 53/45
c 4/45 4/45 4/45 1 19/15

Every row sums to more than 1: the seen words alone already sum to 1, and the backed off words add to it. With n=3n = 3 on the same text, the history <s> c was never seen; </s> then gets 25⋅1\frac25 \cdot 1 and each other word 425⋅29=8225\frac4{25} \cdot \frac29 = \frac8{225}, which sums to 38/75, less than 1.

Correctness

There is no distribution to be correct about, so the proof shows what the scores are. The counting loop gives c(g)c(g) and c(h)c(h) as defined, because the padding gives every predicted position a full window of nn tokens. Lines L1 to L4 compute S(w∣h)S(w \mid h) by induction on the length of hh, and the division at line L2 is safe because c(h)≥c(hw)>0c(h) \ge c(h w) > 0. Every word of VV gets a score in (0,1](0, 1]. After a seen history the scores sum to at least 1, since the seen words give exactly ∑wc(hw)/c(h)=1\sum_{w} c(h w)/c(h) = 1. After a history of length m−1m - 1 they sum to at most 1+α+⋯+αm−11 + \alpha + \cdots + \alpha^{m-1}, which is below 1/(1−α)=5/31/(1 - \alpha) = 5/3 for α=0.4\alpha = 0.4.

Proof: Stupid backoff computes its recursive score, every score of a seen word lies in (0, 1], and the scores after a history of length m - 1 sum to at least 1 when the history was seen and to at most 1 + alpha + ... + alpha^(m-1)full

We use the notation of the page. Each sentence is padded with n−1n - 1 copies of <s> and one </s>. For an m-gram gg with 1≤m≤n1 \le m \le n, c(g)c(g) is the number of predicted positions where gg ends, and for a history hh of length m−1m - 1 we write c(h)=∑xc(hx)c(h) = \sum_x c(h x). The vocabulary VV is the set of predicted tokens, so c(w)≥1c(w) \ge 1 for every w∈Vw \in V. The score is

S(w∣h)=c(hw)c(h) if c(hw)>0,S(w∣h)=α S(w∣h′) otherwise,S(w∣())=c(w)N or 0,S(w \mid h) = \frac{c(h w)}{c(h)} \text{ if } c(h w) > 0, \qquad S(w \mid h) = \alpha\, S(w \mid h') \text{ otherwise}, \qquad S(w \mid ()) = \frac{c(w)}{N} \text{ or } 0,

with h′h' the history hh without its first token, N=c(())N = c(()) the number of predicted tokens and 0≤α≤10 \le \alpha \le 1.

Lemma 1 (the counts). The training loop gives c(g)c(g) and c(h)c(h) as defined.

Proof. The loop visits each predicted position ii once and adds one to every suffix gg of length m=1,…,nm = 1, \ldots, n of the tokens that end at ii; these suffixes exist because of the n−1n - 1 pads. So c(g)c(g) counts the predicted positions where gg ends. In the same step it adds one to c(g[:−1])c(g[{:}-1]), the history of gg. A history hh of length m−1m - 1 gets one for each position ii where some hxh x ends, which is ∑xc(hx)\sum_x c(h x). □\square

Theorem 2 (the score). Lines L1 to L4 return S(w∣h)S(w \mid h).

Proof. Induction on the length of hh. Line L1 tests c(hw)>0c(h w) > 0 and line L2 returns c(hw)/c(h)c(h w)/c(h); here c(h)≥c(hw)>0c(h) \ge c(h w) > 0, so the division is defined. If c(hw)=0c(h w) = 0 and hh is empty, ww was never predicted, and line L3 returns 0. Otherwise line L4 returns α\alpha times the score of the shorter history, which is correct by the induction hypothesis. □\square

Theorem 3 (range). For w∈Vw \in V and every hh, 0<S(w∣h)≤10 < S(w \mid h) \le 1 when α>0\alpha > 0, and 0≤S(w∣h)≤10 \le S(w \mid h) \le 1 when α=0\alpha = 0. For w∉Vw \notin V, S(w∣h)=0S(w \mid h) = 0.

Proof. A ratio from line L2 is in (0,1](0, 1] because 0<c(hw)≤c(h)0 < c(h w) \le c(h). Line L4 multiplies a value in [0,1][0, 1] by α∈[0,1]\alpha \in [0, 1]. The recursion ends at the empty history at the latest, where S(w∣())=c(w)/N>0S(w \mid ()) = c(w)/N > 0 for w∈Vw \in V. So every score of a word of VV is a product of a positive ratio and some powers of α\alpha. A word not in VV has c(hw)=0c(h w) = 0 for every hh, so it reaches line L3. □\square

Theorem 4 (the sum is not 1). Let hh have length m−1m - 1 and let Bm=1+α+⋯+αm−1B_m = 1 + \alpha + \cdots + \alpha^{m-1}. Then

  1. if c(h)>0c(h) > 0, then ∑w∈VS(w∣h)≥1\sum_{w \in V} S(w \mid h) \ge 1, with equality exactly when α=0\alpha = 0 or every word of VV was seen after hh;
  2. for every hh, ∑w∈VS(w∣h)≤Bm<1/(1−α)\sum_{w \in V} S(w \mid h) \le B_m < 1 / (1 - \alpha) when α<1\alpha < 1.

Proof. Split VV into the set AA of words with c(hw)>0c(h w) > 0 and the rest. The words of AA give ∑w∈Ac(hw)/c(h)=1\sum_{w \in A} c(h w)/c(h) = 1 by the definition of c(h)c(h), when c(h)>0c(h) > 0. The rest give α∑w∉AS(w∣h′)≥0\alpha \sum_{w \notin A} S(w \mid h') \ge 0, and by Theorem 3 this is positive exactly when α>0\alpha > 0 and A≠VA \ne V. This proves part 1.

For part 2 use induction on mm. For m=1m = 1 the sum is ∑wc(w)/N=1=B1\sum_w c(w)/N = 1 = B_1. For m≥2m \ge 2 the words of AA give at most 1 (exactly 1 if AA is not empty, 0 if it is), and the rest give at most α∑w∈VS(w∣h′)≤αBm−1\alpha \sum_{w \in V} S(w \mid h') \le \alpha B_{m-1} by the induction hypothesis. So the sum is at most 1+αBm−1=Bm1 + \alpha B_{m-1} = B_m. □\square

The bound is reached only in the limit, but the sum is often above 1. On the three sentences "a b", "a c" and "b c" with n=2n = 2 and α=2/5\alpha = 2/5, the scores after <s> are 2/3, 1/3, 4/45 and 2/15, which sum to 11/9. After a history that was never seen the sum can be below 1: with n=3n = 3 on the same text, the scores after <s> c sum to 38/75. So no choice of a constant α>0\alpha > 0 makes all rows sum to 1, and the scores are not a probability distribution. This is why stupid backoff has no perplexity.

Complexity

Training visits each of the NN predicted tokens once and updates nn m-gram counts and nn history counts, so it takes Θ(nN)\Theta(n N) expected operations with hash tables, and the tables hold at most nNn N keys. A query makes at most nn lookups of c(hw)c(h w) and one of c(h)c(h), Θ(n)\Theta(n) operations. Each operation hashes a tuple of up to nn tokens, so in word operations each bound is a factor nn larger. A query needs no data beyond the counts, while a normalized backoff model also stores a weight for every history.

Properties

  • Not a distribution. The scores after a history do not sum to 1, and the sum differs from row to row. The model has no perplexity.
  • Raw counts only. There is no discount, no count of counts and no per-history weight to compute, so training is a single counting job.
  • A fixed backoff factor. One constant α\alpha for all orders and all histories; 0.4 was set by hand.
  • Bounded scores. Every score of a seen word is in (0,1](0, 1], and a backed off score is at most α\alpha.
  • Exact. All scores are ratios of integer counts times powers of α\alpha.

Variants and improvements

  • Katz backoff has the same shape but discounts the seen counts and picks a weight α(h)\alpha(h) for each history so that the probabilities sum to 1.
  • Other factors. α\alpha is a parameter; a different value per order, tuned on held-out data, is a simple change.
  • Compact storage. Very large count tables are often stored with lossy or randomized structures such as a Bloom filter, and pruned before use, as in entropy-based pruning for normalized models.
  • Normalizing after the fact. Dividing each row by its sum gives a distribution, but it costs a sum over VV for each history and removes the reason to use the method.

When to use it

Use it when the training text is so large that counting is the only affordable step, and the model is used only to compare candidates, for example as a feature in a machine translation decoder. Brants and colleagues found it about 1 BLEU point below Kneser-Ney on the same smaller data, with the gap closing as the data grew. Do not use it when you need probabilities: for perplexity, for speech recognition with a calibrated score, or to mix with other models. Then use Kneser-Ney or Katz backoff.

Pitfalls

  • Reporting perplexity. The scores are not probabilities, so a perplexity computed from them has no meaning.
  • The wrong denominator. Dividing by the count of the history as a whole n-gram includes positions where it is not followed by a predicted token, for example the pads at the start of a sentence.
  • Unseen words. A word not in the training text scores 0 at every order. Map such words to <unk>.
  • Comparing across histories. Since rows sum to different totals, the score of a word after one history cannot be compared with its score after another as if they were probabilities.
  • Underflow. The scores of a long sentence multiply to a number below the smallest double. Sum logs instead.

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.

stupid_backoff.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stupid-backoff/. The authors are listed in prov/0ZTM89.jsonl.

"""Stupid backoff scores for an n-gram model (Brants, Popat, Xu, Och and Dean 2007).

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. The score is

    S(w | h) = c(h w) / c(h)        if c(h w) > 0
    S(w | h) = alpha S(w | h')      otherwise
    S(w)     = c(w) / N

where c(h) = sum_x c(h x) is the number of times h is followed by a
predicted token, h' is h without its first token, and N is the number of
predicted tokens. The scores are not probabilities: after a seen history
they sum to at least 1, and the sum can be larger.
"""

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

BOS, EOS = "<s>", "</s>"
ALPHA = Fraction(2, 5)  # 0.4, the value Brants et al. set by hand


class StupidBackoff:
    """Raw n-gram counts of every order and the stupid backoff score."""

    def __init__(self, corpus: Iterable[Sequence[str]], n: int, alpha: Fraction | float = ALPHA):
        if n < 1:
            raise ValueError("the order n must be at least 1")
        if not 0 <= alpha <= 1:
            raise ValueError("alpha must be in [0, 1]")
        self.n = n
        self.alpha = alpha
        self.c: Counter = Counter()  # c(g) for every m-gram g, m = 1 to n, 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 = {g[0] for g in self.c if len(g) == 1}

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

    def score(self, w: str, tokens: Sequence[str] = ()) -> Fraction | float:
        """S(w | the sentence so far). A word never seen in training scores 0."""
        return self._score(w, self.history(tokens))

    def _score(self, w: str, h: tuple) -> Fraction | float:
        k = self.c[h + (w,)]
        if k > 0:  # @line L1
            return Fraction(k, self.ch[h])  # @line L2
        if not h:  # @line L3
            return Fraction(0)
        return self.alpha * self._score(w, h[1:])  # @line L4

    def scores(self, tokens: Sequence[str] = ()) -> dict[str, Fraction | float]:
        """The score of every vocabulary word after the sentence so far."""
        return {w: self.score(w, tokens) for w in sorted(self.vocab)}

    def sentence_logscore(self, sent: Sequence[str]) -> float:
        """The sum of the natural logs of the scores, </s> included. Not a log probability."""
        sent = list(sent)
        total = 0.0
        for i, w in enumerate(sent + [EOS]):
            s = self.score(w, sent[:i])
            if s == 0:
                return -math.inf
            if isinstance(s, Fraction):
                total += math.log(s.numerator) - math.log(s.denominator)
            else:
                total += math.log(s)
        return total
test_stupid_backoff.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stupid-backoff/. The authors are listed in prov/0ZTM89.jsonl.

import math
import random
from fractions import Fraction

import pytest

from stupid_backoff import ALPHA, BOS, EOS, StupidBackoff

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 prefixes(corpus):
    out = {()}
    for s in corpus:
        for i in range(len(s) + 1):
            out.add(tuple(s[:i]))
    out.add(("zz", "zz", "zz"))
    return out


def brute_score(corpus, n, alpha, w, h):
    """The definition, with every count found by a scan of the padded sentences."""
    padded = [[BOS] * (n - 1) + s + [EOS] for s in corpus]

    def count(g):
        k = 0
        for toks in padded:
            for i in range(n - 1, len(toks)):
                if tuple(toks[i - len(g) + 1 : i + 1]) == g:
                    k += 1
        return k

    hist = sum(count(h + (x,)) for x in {t for toks in padded for t in toks if t != BOS})
    k = count(h + (w,))
    if k > 0:
        return Fraction(k, hist)
    if not h:
        return Fraction(0)
    return alpha * brute_score(corpus, n, alpha, w, h[1:])


def test_check_corpus_by_hand():
    sb = StupidBackoff(CHECK, 2)
    assert sb.score("a") == Fraction(2, 3)
    assert sb.score("b") == Fraction(1, 3)
    assert sb.score("c") == ALPHA * Fraction(2, 9)
    assert sb.score(EOS) == ALPHA * Fraction(3, 9)
    assert sum(sb.scores().values()) == Fraction(11, 9)  # not a distribution
    assert sb.score("q") == 0


@pytest.mark.parametrize("n", [1, 2, 3])
def test_matches_brute_force(n):
    corpus = random_corpus(n, 10, ["x", "y", "z", "u"], 5)
    sb = StupidBackoff(corpus, n)
    for toks in list(prefixes(corpus))[:15]:
        h = sb.history(toks)
        for w in sorted(sb.vocab):
            assert sb.score(w, toks) == brute_score(corpus, n, ALPHA, w, h)


@pytest.mark.parametrize("n,seed", [(2, 1), (3, 2), (4, 3)])
def test_scores_are_bounded_but_not_normalized(n, seed):
    corpus = random_corpus(seed, 40, ["a", "b", "c", "d", "e", "f"], 6)
    sb = StupidBackoff(corpus, n)
    bound = sum(ALPHA**k for k in range(n))
    above_one = 0
    for toks in prefixes(corpus):
        sc = sb.scores(toks)
        assert all(0 < s <= 1 for s in sc.values())
        total = sum(sc.values())
        assert total <= bound
        if sb.ch[sb.history(toks)] > 0:
            assert total >= 1
        above_one += total > 1
    assert above_one > 0


def test_alpha_zero_is_maximum_likelihood_after_seen_histories():
    corpus = random_corpus(4, 30, ["a", "b", "c", "d"], 5)
    sb = StupidBackoff(corpus, 3, alpha=0)
    for toks in prefixes(corpus):
        if sb.ch[sb.history(toks)] > 0:
            assert sum(sb.scores(toks).values()) == 1


def test_float_alpha_agrees_with_fraction():
    corpus = random_corpus(5, 30, ["a", "b", "c", "d"], 5)
    exact = StupidBackoff(corpus, 3)
    approx = StupidBackoff(corpus, 3, alpha=0.4)
    for toks in list(prefixes(corpus))[:20]:
        for w in exact.vocab:
            assert float(approx.score(w, toks)) == pytest.approx(float(exact.score(w, toks)), rel=1e-12)


def test_log_space_where_the_product_underflows():
    corpus = random_corpus(6, 40, ["a", "b", "c", "d", "e", "f"], 8)
    sb = StupidBackoff(corpus, 3)
    rng = random.Random(7)
    sent = [rng.choice(["a", "b", "c", "d", "e", "f"]) for _ in range(1500)]
    product, log_sum = 1.0, 0.0
    for i, w in enumerate(sent + [EOS]):
        s = float(sb.score(w, sent[:i]))
        product *= s
        log_sum += math.log(s)
    assert product == 0.0
    ls = sb.sentence_logscore(sent)
    assert ls < -745 and ls == pytest.approx(log_sum, rel=1e-12)
    assert sb.sentence_logscore(["q"]) == -math.inf


def test_bad_input():
    with pytest.raises(ValueError):
        StupidBackoff(CHECK, 0)
    with pytest.raises(ValueError):
        StupidBackoff(CHECK, 2, alpha=Fraction(3, 2))

History

Brants, Popat, Xu, Och and Dean (2007) built n-gram models from up to 1.8 trillion tokens of web text for the Google machine translation system. Kneser-Ney smoothing needs counts of counts and per-history weights, which are expensive at that scale, so they used raw relative frequencies with a fixed backoff factor and called the method stupid backoff. They counted with MapReduce on about 1500 machines in about a day, stored the counts across many servers, and showed that the BLEU score of stupid backoff kept growing with the data, until with the web data it was 0.82 BLEU points above the best Kneser-Ney model on smaller data.

References

  1. Brants, Popat, Xu, Och and Dean 2007, equations 5 and 6 (the score S and its recursion), footnote 2 (the value 0.4 was set by hand), Section 7.3 (no perplexity for stupid backoff), Section 7.4 (BLEU against Kneser-Ney as the data grows)

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