Algorithm Search⌘K

Algorithmcore

BLEU

Also called bilingual evaluation understudy.

The geometric mean of clipped n-gram precisions for n = 1 to 4 against reference translations, times a brevity penalty. Higher is better, from 0 to 1, at the corpus level.

Time
O(N² L log L) worst
Space
O(N L) extra
Where
L = the number of tokens in all candidates and references; N = the largest n-gram order
Properties
deterministicexactonlineiterative
Origin
Kishore Papineni, Salim Roukos, Todd Ward, Wei Jing Zhu, 2002

BLEU scores a machine translation output by counting how many of its word n-grams also occur in human reference translations. It clips each count, takes the geometric mean of the precisions for n = 1 to 4 over the whole test set, and multiplies by a penalty for output that is too short. The score goes from 0 to 1 (often printed times 100), higher is better, and it is defined at the corpus level, not as a mean of sentence scores. It depends on the tokenization, so a BLEU value means something only with its tokenizer and its test set.

In plain words

You have a set of machine translations and, for each sentence, one or more translations by people. BLEU asks how many of the words and short word sequences of the machine output also appear in a human translation.

A word may count only as many times as it appears in one reference. Without this rule, an output that repeats "the" seven times would get full marks. BLEU does this for single words, pairs, triples and sequences of four words, and takes a kind of average of the four results.

Precision alone favors short output, because a three-word output can be all correct. So BLEU also lowers the score when the output is shorter in total than the references.

All counts are added over the whole test set before the score is computed. A single sentence often has no matching four-word sequence, and its unsmoothed score is then 0.

The problem

A candidate yy is a list of tokens, and it comes with a non-empty list RyR_y of references, each a list of tokens. For an nn-gram gg, countx(g)\mathrm{count}_x(g) is the number of times gg occurs in the list xx. Over a corpus of candidates, define the clipped matches and the totals for n=1,…,Nn = 1, \ldots, N:

mn=∑y∑gmin⁡(county(g), max⁡x∈Rycountx(g)),tn=∑ymax⁡(∣y∣−n+1,0),m_n = \sum_{y} \sum_{g} \min\Bigl(\mathrm{count}_y(g),\ \max_{x \in R_y} \mathrm{count}_x(g)\Bigr), \qquad t_n = \sum_y \max(|y| - n + 1, 0),

and the precision pn=mn/tnp_n = m_n / t_n. Let cc be the total candidate length and rr the sum over candidates of the reference length closest to ∣y∣|y| (the effective reference length). Then

BP={1c>re1−r/cc≤r,BLEU=BP⋅exp⁡(1N∑n=1Nln⁡pn).\mathrm{BP} = \begin{cases} 1 & c > r \\ e^{1 - r/c} & c \le r \end{cases}, \qquad \mathrm{BLEU} = \mathrm{BP} \cdot \exp\Bigl(\frac{1}{N}\sum_{n=1}^{N} \ln p_n\Bigr).

Papineni et al. (2002) use N=4N = 4 and the uniform weights 1/N1/N. The task is to compute this number. Higher is better. The score is 0 when some mnm_n is 0, and 1 only when every nn-gram of the candidates is matched and c≥rc \ge r.

Tokenization. The tokens are part of the definition. The standard today is the 13a tokenizer of sacreBLEU, which copies the NIST script mteval-v13a: it joins lines, unescapes ", &, < and >, puts spaces around punctuation and symbols, splits a period or a comma from a word unless it stands between two digits, splits a hyphen that follows a digit, and then splits on white space. The case is kept. The references must be tokenized the same way as the candidates, by the scorer and not by the system.

The algorithm

The input is a list of candidates with their references and the order NN. Distinct nn-grams are found with a hash table.

  1. BLEU(Y, R, N) ▷ Y: candidates, R_y: the references of y
  2. 1m_n ← 0 and t_n ← 0 for n = 1 .. N
  3. 2c ← 0; r ← 0
  4. 3for each candidate y in Y do
  5. 4c ← c + |y|
  6. 5r ← r + the length in R_y closest to |y|, the shorter one on a tie
  7. 6for n ← 1 to N do
  8. 7for each distinct n-gram g of y do
  9. 8m_n ← m_n + min(count_y(g), max over x in R_y of count_x(g))
  10. 9t_n ← t_n + max(|y| - n + 1, 0)
  11. 10if some m_n = 0 then return 0 ▷ or smooth, see below
  12. 11BP ← 1 if c > r, else exp(1 - r / c)
  13. 12return BP · exp((1/N) Σ_n ln(m_n / t_n))

Lines L1 to L9 collect the sufficient statistics: 2N+22N + 2 integers. Line L8 is the clipping: a candidate nn-gram counts at most as often as it occurs in the reference where it occurs most. The maximum is per reference, not a sum over references. Line L5 picks the effective reference length per sentence, and the sum over sentences is the rr of the brevity penalty. Lines L10 to L12 compute the score once from the sums.

Tie rule. When two references are equally close in length to the candidate, line L5 takes the shorter one, as sacreBLEU does. A longer rr gives a smaller BP, so the rule matters.

Smoothing for one sentence. For sentence BLEU, line L10 returns 0 too often. Method 3 of Chen and Cherry (2014), the one in the NIST tool, gives the kk-th order with mn=0m_n = 0 the precision 1/(2ktn)1/(2^k t_n) instead. The implementation offers it for sentence scores and leaves corpus BLEU unsmoothed.

Example

The candidate "the cat sat on the mat" (6 tokens) has the one reference "the cat sat on the red mat" (7 tokens), tokenized by white space.

nn candidate nn-grams matched pnp_n
1 the, cat, sat, on, the, mat all 6 ("the" occurs twice in the reference) 6/6
2 the cat, cat sat, sat on, on the, the mat all but "the mat" 4/5
3 the cat sat, cat sat on, sat on the, on the mat all but "on the mat" 3/4
4 the cat sat on, cat sat on the, sat on the mat all but "sat on the mat" 2/3

The geometric mean is (1⋅0.8⋅0.75⋅0.6667)1/4=0.41/4=0.795271(1 \cdot 0.8 \cdot 0.75 \cdot 0.6667)^{1/4} = 0.4^{1/4} = 0.795271. With c=6c = 6 and r=7r = 7, BP=e1−7/6=0.846482\mathrm{BP} = e^{1 - 7/6} = 0.846482, so BLEU=0.673182\mathrm{BLEU} = 0.673182, or 67.32 on the scale of 100.

Clipping: the candidate "the the the the the the the" against "the cat is on the mat" has 7 unigrams that all occur in the reference, but "the" occurs only twice there, so p1=2/7p_1 = 2/7 and not 7/77/7.

Corpus level: add the pair "a dog ran in the park" with an identical reference. The sums are m=(12,9,7,5)m = (12, 9, 7, 5), t=(12,10,8,6)t = (12, 10, 8, 6), c=12c = 12, r=13r = 13, and corpus BLEU is 0.8281. The mean of the two sentence scores, 0.6732 and 1, is 0.8366.

Correctness

The claim is that the procedure returns the value of the formula, and that this value is in [0,1][0, 1]. Lines L3 to L9 compute each sum of the definition, because the sum over the distinct nn-grams of yy equals the sum over all nn-grams (the others add 0), and a list of length ℓ\ell has max⁡(ℓ−n+1,0)\max(\ell - n + 1, 0) nn-grams. Clipping gives mn≤tnm_n \le t_n, so each ln⁡pn≤0\ln p_n \le 0, and BP is at most 1, so the score is at most 1. It is 1 exactly when every pn=1p_n = 1 and c≥rc \ge r. These are theorems; the full proof is in the proofs file.

How well the score agrees with human judgments is a different question, and the answer is only measured.

Proof: The BLEU procedure computes the clipped precisions, the brevity penalty and a score in [0, 1]full

Fix the maximum order N≥1N \ge 1 and a corpus of candidates y(1),…,y(S)y^{(1)}, \ldots, y^{(S)}, each a list of tokens, where candidate ss has a non-empty list RsR_s of references. For a list xx of tokens and an nn-gram gg (a tuple of nn tokens), countx(g)\mathrm{count}_x(g) is the number of positions ii with xi…xi+n−1=gx_i \ldots x_{i+n-1} = g. The definition of Papineni et al. (2002) is

mn=∑s∑gmin⁡(county(s)(g), max⁡x∈Rscountx(g)),tn=∑s∑gcounty(s)(g),m_n = \sum_s \sum_{g} \min\Bigl(\mathrm{count}_{y^{(s)}}(g),\ \max_{x \in R_s} \mathrm{count}_x(g)\Bigr), \qquad t_n = \sum_s \sum_g \mathrm{count}_{y^{(s)}}(g),

with gg over all nn-grams, pn=mn/tnp_n = m_n / t_n, c=∑s∣y(s)∣c = \sum_s |y^{(s)}|, r=∑srsr = \sum_s r_s where rsr_s is the length in RsR_s closest to ∣y(s)∣|y^{(s)}| (the shorter one on a tie), BP=1\mathrm{BP} = 1 if c>rc > r and e1−r/ce^{1 - r/c} otherwise, and

BLEU=BP⋅exp⁡(1N∑n=1Nln⁡pn),\mathrm{BLEU} = \mathrm{BP} \cdot \exp\Bigl(\frac{1}{N} \sum_{n=1}^{N} \ln p_n\Bigr),

taken as 0 when some mn=0m_n = 0 (the logarithm is −∞-\infty there, and the exponential of −∞-\infty is 0).

Lemma 1 (the counts). After the loop of lines L3 to L9, the variables mnm_n, tnt_n, cc and rr hold the values of the definition.

Proof. Lines L1 and L2 set all of them to 0. The loop body for candidate ss adds ∣y(s)∣|y^{(s)}| to cc (line L4) and rsr_s to rr (line L5). For each nn, line L8 runs over the distinct nn-grams gg of y(s)y^{(s)}, so it adds the inner sum of mnm_n over those gg. An nn-gram that does not occur in y(s)y^{(s)} has county(s)(g)=0\mathrm{count}_{y^{(s)}}(g) = 0 and adds 0 to the definition, so the sum over the distinct nn-grams of y(s)y^{(s)} equals the sum over all gg. A list of length ℓ\ell has exactly max⁡(ℓ−n+1,0)\max(\ell - n + 1, 0) positions where an nn-gram starts, so ∑gcounty(s)(g)=max⁡(∣y(s)∣−n+1,0)\sum_g \mathrm{count}_{y^{(s)}}(g) = \max(|y^{(s)}| - n + 1, 0), which line L9 adds to tnt_n. Addition is commutative, so after all candidates every variable holds its sum over ss. □\square

Lemma 2 (the range of a precision). For each nn, 0≤mn≤tn0 \le m_n \le t_n.

Proof. Each term of mnm_n is a minimum of two non-negative integers, so it is at least 0 and at most county(s)(g)\mathrm{count}_{y^{(s)}}(g). Summing the upper bound over gg and ss gives tnt_n. □\square

Theorem. The procedure returns the value BLEU\mathrm{BLEU} of the definition, and 0≤BLEU≤10 \le \mathrm{BLEU} \le 1. The score is 1 exactly when mn=tn>0m_n = t_n > 0 for every nn and c≥rc \ge r.

Proof. By Lemma 1 the variables hold the values of the definition when line L10 runs. If some mn=0m_n = 0, line L10 returns 0, which is the value of the definition. Otherwise every mn≥1m_n \ge 1, so by Lemma 2 every tn≥1t_n \ge 1, every pnp_n is in (0,1](0, 1], and c≥t1≥1c \ge t_1 \ge 1, so r/cr / c is defined. Line L11 computes BP as defined, and line L12 returns the formula of the definition.

For the range: if line L10 returns, the score is 0. Otherwise each ln⁡pn≤0\ln p_n \le 0, so the exponential is in (0,1](0, 1]. If c>rc > r then BP=1\mathrm{BP} = 1, and if c≤rc \le r then 1−r/c≤01 - r/c \le 0 and BP=e1−r/c∈(0,1]\mathrm{BP} = e^{1 - r/c} \in (0, 1]. The product of two numbers in (0,1](0, 1] is in (0,1](0, 1].

For the case of equality: the product of two numbers in (0,1](0, 1] is 1 only if both are 1. The exponential is 1 only if every ln⁡pn=0\ln p_n = 0, that is mn=tnm_n = t_n, and these are positive because line L10 did not return. BP is 1 if c>rc > r, and for c≤rc \le r it is 1 only if r/c=1r / c = 1, that is c=rc = r. Conversely, if mn=tn>0m_n = t_n > 0 for all nn and c≥rc \ge r, both factors are 1. □\square

Remark (sentence order). The statistics are sums over the candidates, so the score does not depend on the order of the sentences, and the statistics of two parts of a corpus add up to the statistics of the whole. The score itself does not add up: corpus BLEU is in general not the mean of the sentence scores, because the logarithm and the brevity penalty are applied once, to the sums. The tests check both facts.

Remark (smoothing). With smoothing method 3 of Chen and Cherry (2014), line L10 does not return. The kk-th order with mn=0m_n = 0, counted from n=1n = 1, gets pn=1/(2ktn)p_n = 1 / (2^k t_n). If tn≥1t_n \ge 1 this is in (0,1)(0, 1), so the range proof above still gives a score in (0,1](0, 1]. If some tn=0t_n = 0 (a candidate shorter than nn tokens), the implementation returns 0 in both modes.

Remark (complexity). For one candidate with ℓ\ell tokens and references with ℓ′\ell' tokens in total, line L8 needs the counts of the nn-grams of the candidate and of each reference. With a hash table keyed by the nn-gram, building them takes O(n(ℓ+ℓ′))O(n (\ell + \ell')) expected time, and the clipped sum takes O(nℓ)O(n \ell). Summed over n≤Nn \le N and over the corpus with LL tokens in all, this is O(N2L)O(N^2 L) expected time and O(NL)O(N L) space for one sentence at a time.

Complexity

Let LL be the number of tokens in all candidates and references. For each nn, the nn-grams of a sentence and of its references are counted, and each nn-gram has nn tokens. With a hash table this takes O(N2L)O(N^2 L) expected time. With sorting in place of hashing, the worst case is O(N2Llog⁡L)O(N^2 L \log L). For N=4N = 4 both are linear in practice. One sentence at a time needs O(NL)O(N L) space for its counts, and the corpus needs only the 2N+22N + 2 statistics.

Properties

  • Range and direction. From 0 to 1, higher is better (a theorem). Most papers print it times 100.
  • Corpus level. The statistics add over sentences and the score is computed once. Corpus BLEU is not the mean of sentence BLEU.
  • Online. The statistics of a new sentence are added in time linear in its length, and the score is updated from 2N+22N + 2 numbers.
  • Precision only. There is no recall term. The brevity penalty works on the total length only, so one long sentence can hide a short one.
  • Order of words. Only the higher-order nn-grams see the order. Any permutation that keeps the same nn-grams gets the same score.
  • More references, higher score. A larger RyR_y can only raise each clipped count, so scores with different numbers of references are not comparable.
  • Tokenization. Post (2018) measured differences of up to 1.8 points between common settings on the same output (a measurement).

Variants and improvements

  • Smoothed sentence BLEU. Lin and Och (2004) added one to the counts for n≥2n \ge 2. Chen and Cherry (2014) compared seven methods. Sentence BLEU is used for tuning and for minimum risk training, where a zero score gives no signal.
  • sacreBLEU. Post (2018) fixed the tokenization, the tie rule and the effective order in one tool, which prints a signature of its settings next to the score.
  • Other tokenizers. For Chinese and Japanese, which have no spaces between words, sacreBLEU has tokenizers by character or by a morphological analyzer. The score then counts other units and is not comparable to a score of 13a.
  • NIST. The NIST score of Doddington (2002) weights each matched nn-gram by how rare it is and uses an arithmetic mean.
  • Character n-grams. chrF uses character n-grams and both precision and recall. It is less sensitive to tokenization and morphology.
  • Edit-based and learned scores. TER counts edits, and COMET and BERTScore use neural representations.

When to use it

Use corpus BLEU to compare systems on the same test set, with the same references and the same tokenizer, and report the sacreBLEU signature. It is fast, needs no model and has a long record, so it works for tracking a system during development. Do not use it to compare scores across papers that do not state their settings, to compare scores across test sets or languages, or to judge single sentences. For final claims, measured agreement with human judgments is better for chrF and for learned scores such as COMET.

Pitfalls

  • Your own tokenization. Scoring tokenized or BPE-split output against tokenized references gives a higher number than sacreBLEU on detokenized text. Score the detokenized output.
  • Mean of sentence scores. Averaging sentence BLEU does not give corpus BLEU, and unsmoothed sentence scores are often 0.
  • The scale. Code that returns 0 to 1 and a table that prints 0 to 100 get mixed up. State the scale.
  • Sum over references. Clipping at the sum of the reference counts, instead of the maximum, lets a repeated word score too often.
  • Shortest or closest. Some old scripts used the shortest reference length for BP. With several references this gives another score.
  • Small differences. A gap of a few tenths of a point can come from chance in the test set. Use paired bootstrap resampling before claiming a gain. Callison-Burch et al. (2006) also showed that a higher BLEU does not always mean a better translation.

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.

bleu.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bleu/. The authors are listed in prov/FSSX1F.jsonl.

"""BLEU of Papineni, Roukos, Ward and Zhu (2002), at the corpus level.

The input is pre-tokenized: a candidate is a list of str tokens, and each
candidate has a list of one or more references, each a list of tokens. The
score depends on the tokenization; to compare with published numbers, tokenize
with the 13a tokenizer of sacreBLEU first. This module does no tokenization.

The clipped counts and the precisions are exact Fractions. The final score is
a float on the 0 to 1 scale.

Effective reference length: for each candidate, the reference length closest
to the candidate length, and the shorter one on a tie (as in sacreBLEU).

Smoothing: "none" (the paper), or "exp", method 3 of Chen and Cherry (2014):
the k-th order with zero matches gets the precision 1 / (2^k * t_n). An order
with no candidate n-grams at all (t_n = 0) gives the score 0 in both modes.
"""

import math
from collections import Counter
from dataclasses import dataclass
from fractions import Fraction
from typing import List, Sequence, Tuple

Tokens = Sequence[str]


def ngram_counts(tokens: Tokens, n: int) -> Counter:
    """Return the multiset of the n-grams of tokens, as a Counter of tuples."""
    return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))


def closest_ref_length(c: int, ref_lengths: Sequence[int]) -> int:
    """Return the reference length closest to c, the shorter one on a tie."""
    return min(ref_lengths, key=lambda r: (abs(r - c), r))


@dataclass
class BleuStats:
    """The sufficient statistics of corpus BLEU."""

    matches: List[int]  # m_n, the clipped matches of order n = 1 .. N
    totals: List[int]  # t_n, the candidate n-grams of order n
    c: int  # the total candidate length
    r: int  # the total effective reference length


def sentence_stats(candidate: Tokens, references: Sequence[Tokens], max_n: int = 4) -> BleuStats:
    """Return the BLEU statistics of one candidate against its references."""
    if not references:
        raise ValueError("each candidate needs at least one reference")
    c = len(candidate)  # @line L4
    r = closest_ref_length(c, [len(x) for x in references])  # @line L5
    matches, totals = [], []
    for n in range(1, max_n + 1):  # @line L6
        cand = ngram_counts(candidate, n)  # @line L7
        best = Counter()
        for ref in references:
            for g, k in ngram_counts(ref, n).items():
                if k > best[g]:
                    best[g] = k
        # clip each count at its largest count in one reference
        matches.append(sum(min(k, best[g]) for g, k in cand.items()))  # @line L8
        totals.append(max(c - n + 1, 0))  # @line L9
    return BleuStats(matches, totals, c, r)


def add_stats(a: BleuStats, b: BleuStats) -> BleuStats:
    """Return the sum of two sets of statistics."""
    return BleuStats([x + y for x, y in zip(a.matches, b.matches)],
                     [x + y for x, y in zip(a.totals, b.totals)], a.c + b.c, a.r + b.r)


def precisions(stats: BleuStats) -> List[Fraction]:
    """Return the clipped precisions p_n = m_n / t_n as Fractions (0 when t_n = 0)."""
    return [Fraction(m, t) if t else Fraction(0) for m, t in zip(stats.matches, stats.totals)]


def brevity_penalty(c: int, r: int) -> float:
    """Return BP = 1 if c > r, else exp(1 - r / c). BP is 0 for c = 0."""
    if c > r:  # @line L11
        return 1.0
    if c == 0:
        return 0.0
    return math.exp(1 - r / c)


def bleu_from_stats(stats: BleuStats, smoothing: str = "none") -> float:
    """Return BLEU = BP * exp(sum_n (1/N) log p_n) from the statistics."""
    if smoothing not in ("none", "exp"):
        raise ValueError("smoothing must be 'none' or 'exp'")
    big_n = len(stats.matches)
    logs = []
    k = 0
    for m, t in zip(stats.matches, stats.totals):
        if t == 0:
            return 0.0
        if m == 0:  # @line L10
            if smoothing == "none":
                return 0.0
            k += 1
            logs.append(-math.log(2 ** k * t))
        else:
            logs.append(math.log(m) - math.log(t))
    return brevity_penalty(stats.c, stats.r) * math.exp(sum(logs) / big_n)  # @line L12


def corpus_stats(candidates: Sequence[Tokens], references: Sequence[Sequence[Tokens]],
                 max_n: int = 4) -> BleuStats:
    """Return the summed statistics of a corpus."""
    if len(candidates) != len(references):
        raise ValueError("one list of references per candidate")
    zeros = [0] * max_n  # @line L1
    total = BleuStats(zeros, list(zeros), 0, 0)  # @line L2
    for cand, refs in zip(candidates, references):  # @line L3
        total = add_stats(total, sentence_stats(cand, refs, max_n))
    return total


def corpus_bleu(candidates: Sequence[Tokens], references: Sequence[Sequence[Tokens]],
                max_n: int = 4, smoothing: str = "none") -> float:
    """Return corpus BLEU on the 0 to 1 scale. It is not the mean of sentence BLEU."""
    return bleu_from_stats(corpus_stats(candidates, references, max_n), smoothing)


def sentence_bleu(candidate: Tokens, references: Sequence[Tokens], max_n: int = 4,
                  smoothing: str = "exp") -> float:
    """Return BLEU of one sentence, smoothed by default (method 3 of Chen and Cherry)."""
    return bleu_from_stats(sentence_stats(candidate, references, max_n), smoothing)


def bleu_details(candidates: Sequence[Tokens], references: Sequence[Sequence[Tokens]],
                 max_n: int = 4) -> Tuple[List[Fraction], float, float]:
    """Return the precisions, the brevity penalty and the unsmoothed BLEU."""
    st = corpus_stats(candidates, references, max_n)
    return precisions(st), brevity_penalty(st.c, st.r), bleu_from_stats(st)
test_bleu.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bleu/. The authors are listed in prov/FSSX1F.jsonl.

import math
import random
from fractions import Fraction

from bleu import (
    bleu_details,
    brevity_penalty,
    closest_ref_length,
    corpus_bleu,
    corpus_stats,
    sentence_bleu,
    sentence_stats,
)


def toks(s):
    return s.split()


def brute_clipped(cand, refs, n):
    """Clipped matches and total by scanning lists, with no Counter."""
    grams = [tuple(cand[i:i + n]) for i in range(len(cand) - n + 1)]
    seen = []
    m = 0
    for g in grams:
        if g in seen:
            continue
        seen.append(g)
        in_cand = sum(1 for x in grams if x == g)
        in_ref = 0
        for r in refs:
            k = sum(1 for i in range(len(r) - n + 1) if tuple(r[i:i + n]) == g)
            in_ref = max(in_ref, k)
        m += min(in_cand, in_ref)
    return m, len(grams)


def test_check_value():
    cand = toks("the cat sat on the mat")
    ref = toks("the cat sat on the red mat")
    ps, bp, score = bleu_details([cand], [[ref]])
    assert ps == [Fraction(6, 6), Fraction(4, 5), Fraction(3, 4), Fraction(2, 3)]
    assert abs(bp - 0.846482) < 1e-6
    assert abs(score - 0.673182) < 1e-6


def test_papineni_clipping():
    cand = toks("the the the the the the the")
    st = sentence_stats(cand, [toks("the cat is on the mat")], 1)
    assert Fraction(st.matches[0], st.totals[0]) == Fraction(2, 7)
    st2 = sentence_stats(cand, [toks("the cat is on the mat"), toks("there is a cat on the mat")], 1)
    assert Fraction(st2.matches[0], st2.totals[0]) == Fraction(2, 7)


def test_identical_and_empty():
    s = toks("a b c d e f")
    assert corpus_bleu([s], [[s]]) == 1.0
    assert corpus_bleu([[]], [[s]]) == 0.0
    # three tokens: no 4-gram, so the unsmoothed and the smoothed score are 0
    assert corpus_bleu([toks("a b c")], [[toks("a b c")]]) == 0.0
    assert sentence_bleu(toks("a b c"), [toks("a b c")]) == 0.0


def test_brevity_penalty():
    assert brevity_penalty(7, 6) == 1.0
    assert brevity_penalty(6, 6) == 1.0
    assert abs(brevity_penalty(6, 7) - math.exp(1 - 7 / 6)) < 1e-15
    assert brevity_penalty(0, 3) == 0.0
    # a candidate longer than the reference gets no penalty
    cand = toks("the cat sat on the red mat today")
    ps, bp, _ = bleu_details([cand], [[toks("the cat sat on the red mat")]])
    assert bp == 1.0
    assert ps[0] == Fraction(7, 8)


def test_closest_reference_tie():
    assert closest_ref_length(5, [3, 7]) == 3
    assert closest_ref_length(5, [7, 3]) == 3
    assert closest_ref_length(5, [6, 9, 4]) == 4
    assert closest_ref_length(5, [5, 4]) == 5


def test_zero_count_and_smoothing():
    cand = toks("a b x c d")
    ref = toks("a b y c d")
    st = sentence_stats(cand, [ref])
    assert st.matches == [4, 2, 0, 0]
    assert sentence_bleu(cand, [ref], smoothing="none") == 0.0
    # method 3: p3 = 1/(2 * 3), p4 = 1/(4 * 2)
    want = math.exp((math.log(4 / 5) + math.log(2 / 4) + math.log(1 / 6) + math.log(1 / 8)) / 4)
    assert abs(sentence_bleu(cand, [ref], smoothing="exp") - want) < 1e-12


def test_corpus_is_not_mean_of_sentences():
    c1, r1 = toks("the cat sat on the mat"), toks("the cat sat on the red mat")
    c2, r2 = toks("a dog ran in the park"), toks("a dog ran in the park")
    corpus = corpus_bleu([c1, c2], [[r1], [r2]])
    mean = (corpus_bleu([c1], [[r1]]) + corpus_bleu([c2], [[r2]])) / 2
    assert abs(corpus - mean) > 0.005
    ps, bp, _ = bleu_details([c1, c2], [[r1], [r2]])
    assert ps == [Fraction(12, 12), Fraction(9, 10), Fraction(7, 8), Fraction(5, 6)]
    assert abs(bp - math.exp(1 - 13 / 12)) < 1e-15


def test_random_against_brute_force():
    rng = random.Random(311)
    vocab = ["a", "b", "c", "d"]
    for _ in range(300):
        cand = [rng.choice(vocab) for _ in range(rng.randint(0, 9))]
        refs = [[rng.choice(vocab) for _ in range(rng.randint(1, 9))] for _ in range(rng.randint(1, 3))]
        st = sentence_stats(cand, refs)
        for n in range(1, 5):
            assert (st.matches[n - 1], st.totals[n - 1]) == brute_clipped(cand, refs, n)
        lens = [len(r) for r in refs]
        best = min(abs(x - len(cand)) for x in lens)
        assert st.r == min(x for x in lens if abs(x - len(cand)) == best)
        score = corpus_bleu([cand], [refs])
        assert 0.0 <= score <= 1.0
        if 0.0 < score:
            assert all(m > 0 for m in st.matches)


def test_corpus_stats_add_up():
    rng = random.Random(7)
    vocab = ["x", "y", "z"]
    cands = [[rng.choice(vocab) for _ in range(rng.randint(1, 8))] for _ in range(5)]
    refs = [[[rng.choice(vocab) for _ in range(rng.randint(1, 8))]] for _ in range(5)]
    total = corpus_stats(cands, refs)
    parts = [sentence_stats(c, r) for c, r in zip(cands, refs)]
    assert total.matches == [sum(p.matches[i] for p in parts) for i in range(4)]
    assert total.totals == [sum(p.totals[i] for p in parts) for i in range(4)]
    assert total.c == sum(p.c for p in parts) and total.r == sum(p.r for p in parts)

History

Kishore Papineni, Salim Roukos, Todd Ward and Wei-Jing Zhu of IBM described BLEU in a research report in 2001 and at ACL 2002. They wanted a cheap score that would let researchers test changes daily, and they showed that it ranked systems in the same order as human judges on their data. NIST adopted a variant for its evaluations, and BLEU became the main score of statistical and then neural machine translation. Its limits were known early: Callison-Burch, Osborne and Koehn (2006) showed cases where large BLEU differences did not match human judgments. In 2018 Matt Post released sacreBLEU to make reported scores comparable. Since about 2020 the WMT metrics tasks have found learned metrics to agree better with people, and many papers now report BLEU next to chrF and COMET.

References

  1. Kishore Papineni, Salim Roukos, Todd Ward and Wei-Jing Zhu, BLEU, a method for automatic evaluation of machine translation, ACL 2002, pages 311 to 318, Section 2.1 (modified n-gram precision and clipping), Section 2.2 (the brevity penalty and the effective reference length), Section 2.3 (the formula with N = 4 and uniform weights)
  2. Matt Post, A Call for Clarity in Reporting BLEU Scores, Third Conference on Machine Translation (WMT), 2018, pages 186 to 191, the abstract (differences of up to 1.8 points between common settings, mostly from the tokenization and normalization of the references) and the description of sacreBLEU
  3. Boxing Chen and Colin Cherry, A Systematic Comparison of Smoothing Techniques for Sentence-Level BLEU, Ninth Workshop on Statistical Machine Translation, 2014, pages 362 to 367, Section 2 (the smoothing methods, with method 3 as the exponential decay of the NIST tool)
  4. Callison-Burch, Osborne and Koehn 2006, the argument that a higher BLEU does not always mean a better translation

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.worst
  • 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