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
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 was seen, its score is the relative frequency . If not, the score is a fixed factor times the score of after the shorter history. There is no discount and no normalization, so the scores are not probabilities, and Brants and colleagues write for them instead of . 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 copies of <s> on the left and one </s> on the right; </s> is predicted and counted, <s> is never predicted. Write for the number of times the m-gram () ends at a predicted token, for the number of predicted tokens and for the set of predicted tokens. For a history write , the number of times is followed by a predicted token, and for without its first token.
The task is to give a score to every word after every history of 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
with .
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 , 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.
SB-SCORE(w, h) ▷ h holds the last m - 1 tokens- 1
if c(h w) > 0 then - 2
return c(h w) / c(h) - 3
if h is empty then return 0 ▷ w was never seen - 4
return α · SB-SCORE(w, h')
The implementation keeps 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 and . There are 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 and </s> were not seen there, so they back off to and . The whole model is:
| 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 on the same text, the history <s> c was never seen; </s> then gets and each other word , 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 and as defined, because the padding gives every predicted position a full window of tokens. Lines L1 to L4 compute by induction on the length of , and the division at line L2 is safe because . Every word of gets a score in . After a seen history the scores sum to at least 1, since the seen words give exactly . After a history of length they sum to at most , which is below for .
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 copies of <s> and one </s>. For an m-gram with , is the number of predicted positions where ends, and for a history of length we write . The vocabulary is the set of predicted tokens, so for every . The score is
with the history without its first token, the number of predicted tokens and .
Lemma 1 (the counts). The training loop gives and as defined.
Proof. The loop visits each predicted position once and adds one to every suffix of length of the tokens that end at ; these suffixes exist because of the pads. So counts the predicted positions where ends. In the same step it adds one to , the history of . A history of length gets one for each position where some ends, which is .
Theorem 2 (the score). Lines L1 to L4 return .
Proof. Induction on the length of . Line L1 tests and line L2 returns ; here , so the division is defined. If and is empty, was never predicted, and line L3 returns 0. Otherwise line L4 returns times the score of the shorter history, which is correct by the induction hypothesis.
Theorem 3 (range). For and every , when , and when . For , .
Proof. A ratio from line L2 is in because . Line L4 multiplies a value in by . The recursion ends at the empty history at the latest, where for . So every score of a word of is a product of a positive ratio and some powers of . A word not in has for every , so it reaches line L3.
Theorem 4 (the sum is not 1). Let have length and let . Then
- if , then , with equality exactly when or every word of was seen after ;
- for every , when .
Proof. Split into the set of words with and the rest. The words of give by the definition of , when . The rest give , and by Theorem 3 this is positive exactly when and . This proves part 1.
For part 2 use induction on . For the sum is . For the words of give at most 1 (exactly 1 if is not empty, 0 if it is), and the rest give at most by the induction hypothesis. So the sum is at most .
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 and , 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 on the same text, the scores after <s> c sum to 38/75. So no choice of a constant 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 predicted tokens once and updates m-gram counts and history counts, so it takes expected operations with hash tables, and the tables hold at most keys. A query makes at most lookups of and one of , operations. Each operation hashes a tuple of up to tokens, so in word operations each bound is a factor 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 for all orders and all histories; 0.4 was set by hand.
- Bounded scores. Every score of a seen word is in , and a backed off score is at most .
- Exact. All scores are ratios of integer counts times powers of .
Variants and improvements
- Katz backoff has the same shape but discounts the seen counts and picks a weight for each history so that the probabilities sum to 1.
- Other factors. 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 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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0ZTM89 Edit this page History Report an error Markdown