Sub topic 6
BLEU part 3: combining n-gram orders, corpus-level scoring, and smoothing
This chapter assumes you have read the two earlier BLEU chapters. You should know clipped n-gram precision and the brevity penalty (BP), and be comfortable with collections.Counter. Here we combine those pieces into one score, explain why BLEU is a corpus-level metric, and cover what to do when an n-gram order has no matches.
The full BLEU formula
BLEU combines the clipped precisions p1 to pN (usually N = 4) with a weighted geometric mean, then multiplies by the brevity penalty:
BLEU = BP × exp( Σ wn · log pn ), with w_n = 1/N
With uniform weights this is the fourth root of p1 · p2 · p3 · p4, scaled by BP.
Why a geometric mean
An arithmetic mean would let a high unigram precision hide a bad 4-gram precision. A geometric mean punishes imbalance. If one order collapses toward zero, the whole score collapses with it. This matches the intent: a good translation should match short phrases (adequacy) and longer phrases (fluency and word order).
It also creates the main practical problem. If any pn is exactly 0, then log pn is undefined and the product is 0. The unsmoothed sentence_bleu from the earlier example returns 0.0 in that case.
A worked example
Take a candidate and two references.
- Candidate:
the cat sat on the mat(6 tokens) - Reference 1:
the cat is on the mat - Reference 2:
there is a cat on the mat
| n | Matching candidate n-grams | Clipped / total | p_n |
|---|---|---|---|
| 1 | the (2), cat, on, mat; `sat` misses | 5/6 | 0.833 |
| 2 | `the cat`, `on the`, `the mat` | 3/5 | 0.600 |
| 3 | `on the mat` | 1/4 | 0.250 |
| 4 | none | 0/3 | 0 |
The candidate length is 6 and the closest reference length is 6, so BP = 1. The unsmoothed BLEU is 0, even though the sentence is a near-perfect translation. One missing 4-gram order is enough.
Corpus-level scoring
BLEU was designed to score a whole test set, not single sentences. The corpus-level procedure does not average sentence scores. It pools counts first:
- For every sentence and every n, compute the clipped match count and the candidate n-gram total.
- Sum those counts across the corpus, separately for each n.
- Compute one precision per order from the pooled sums.
- Sum the candidate lengths and the closest-reference lengths over all sentences, and compute BP once from those two totals.
- Combine as in the formula above.
Pooling matters for two reasons. First, long sentences contribute more n-grams, so they carry more weight, which is usually what you want. Second, zeros become rare. Across thousands of sentences, some 4-gram will match somewhere, so the corpus-level geometric mean is almost never 0. The brevity penalty also works over the whole corpus: a few short outputs can be offset by long ones, and only a systematic tendency to under-generate is penalized.
The consequence is that the average of sentence-level BLEU scores is a different quantity from corpus BLEU, and the two should not be compared.
Smoothing
Smoothing replaces zero counts with small positive values so the geometric mean stays defined. It matters mainly for sentence-level BLEU, small test sets, and per-sample diagnostics. Common methods, following Chen and Cherry (2014) and the SacreBLEU options:
| Method | What it does | Where it appears |
|---|---|---|
| Add-one (for n > 1) | Adds 1 to the numerator and denominator of p_n for n ≥ 2 | Lin and Och; NLTK method 2 |
| Floor | Replaces a zero numerator with a small constant such as 0.1 | SacreBLEU `floor` |
| Exponential decay | Each zero numerator becomes 1/2^k, where k counts the zero orders seen so far, divided by the total | SacreBLEU `exp` (default) |
| Add-k | Adds a constant k to numerators and denominators for n ≥ 2 | SacreBLEU `add-k` |
Add-one leaves p_1 untouched, because unigram precision is rarely zero and smoothing it would change scores for good systems.
Implementing corpus BLEU with smoothing
This version is self-contained. It pools counts across the corpus and offers optional add-one smoothing.
import math
from collections import Counter
def ngrams(tokens, n):
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def clipped_counts(candidate, references, n):
cand_counts = ngrams(candidate, n)
max_ref_counts = Counter()
for ref in references:
for gram, count in ngrams(ref, n).items():
max_ref_counts[gram] = max(max_ref_counts[gram], count)
clipped = sum(min(count, max_ref_counts[gram]) for gram, count in cand_counts.items())
return clipped, sum(cand_counts.values())
def closest_ref_len(candidate_len, references):
# ties go to the shorter reference
return min((len(r) for r in references), key=lambda l: (abs(l - candidate_len), l))
def corpus_bleu(candidates, references_list, max_n=4, smooth=False):
clipped = [0] * max_n
total = [0] * max_n
cand_len = 0
ref_len = 0
for cand, refs in zip(candidates, references_list):
for n in range(1, max_n + 1):
c, t = clipped_counts(cand, refs, n)
clipped[n - 1] += c
total[n - 1] += t
cand_len += len(cand)
ref_len += closest_ref_len(len(cand), refs)
if cand_len == 0:
return 0.0
precisions = []
for i in range(max_n):
c, t = clipped[i], total[i]
if smooth and i > 0: # add-one for n >= 2
c, t = c + 1, t + 1
precisions.append(c / t if t else 0.0)
if min(precisions) == 0:
return 0.0
bp = 1.0 if cand_len > ref_len else math.exp(1 - ref_len / cand_len)
return bp * math.exp(sum(math.log(p) for p in precisions) / max_n)
candidates = ["the cat sat on the mat".split()]
references_list = [[
"the cat is on the mat".split(),
"there is a cat on the mat".split(),
]]
print(corpus_bleu(candidates, references_list)) # 0.0
print(round(corpus_bleu(candidates, references_list, smooth=True), 4)) # 0.4855The smoothed value follows from the table above. The precisions become 5/6, 4/6, 2/5, and 1/4. Their product is 1/18, and the fourth root of that is about 0.4855.
Smoothing changes the number
Different smoothing methods give different scores for the same output. SacreBLEU exposes the choice directly:
import sacrebleu
hypotheses = ["the cat sat on the mat"]
references = [["the cat is on the mat"], ["there is a cat on the mat"]] # two reference streams
for method in ["none", "exp"]:
result = sacrebleu.corpus_bleu(hypotheses, references, smooth_method=method)
print(method, round(result.score, 1))With none this prints 0.0. With exp it prints about 38.0, because the single zero 4-gram numerator becomes 1/2 over a total of 3, giving p_4 = 1/6. Our add-one version gave 0.4855 (48.5 on SacreBLEU's 0 to 100 scale) for the same sentence. Neither is wrong, but they are not comparable.
Edge cases to check
- Scale. BLEU is defined on 0 to 1, but SacreBLEU and most papers report 0 to 100. Do not mix them.
- Empty candidates. Return 0 explicitly. Otherwise the brevity penalty divides by zero.
- Multiple references. Clipping uses the maximum count per n-gram across references, and the reference length is the closest one per sentence. Both rules apply to every sentence before pooling.
- Tokenization. Differences in tokenization change every count. The next chapter covers how SacreBLEU fixes this.
- Averaging sentence scores. Mean sentence BLEU is lower and noisier than corpus BLEU. Smoothed sentence BLEU is acceptable for ranking individual outputs, but not as a replacement for corpus BLEU.
Exercise
A corpus has two sentence pairs. For 4-grams, sentence A has 0 clipped matches out of 3, and sentence B has 6 clipped matches out of 20. What is the pooled p_4, and why is the corpus-level geometric mean not zero even though sentence A's unsmoothed BLEU is 0?
Show answer
Pooled p_4 = (0 + 6) / (3 + 20) = 6/23, about 0.261. Corpus BLEU sums counts over all sentences before dividing, so sentence A's zero is absorbed by sentence B's matches. Only a zero in the pooled count for some order, which is unlikely on a large corpus, would make the geometric mean zero.
Exercise
With add-one smoothing for n ≥ 2, a candidate of 5 tokens has clipped counts 4, 2, 0, 0 for n = 1 to 4, and BP = 1. Compute the smoothed BLEU.
Show answer
The totals are 5, 4, 3, 2. After smoothing, p1 = 4/5, p2 = 3/5, p3 = 1/4, p4 = 1/3. The product is (4·3·1·1)/(5·5·4·3) = 12/300 = 0.04. The fourth root of 0.04 is about 0.447, so BLEU ≈ 0.447.