Sub topic 7
Computing BLEU Reproducibly with SacreBLEU
This chapter assumes you can compute clipped n-gram precision, the brevity penalty, and the geometric mean that make up BLEU, and that you can run Python packages from pip. You will see why hand-rolled BLEU scores cannot be compared across papers and how SacreBLEU fixes that. You will also learn which settings to report.
Why the same output gets different BLEU scores
BLEU is a formula, but a formula needs inputs. Before any n-gram is counted, someone has to decide how to split the text into tokens. Different choices produce different scores for identical system output.
- Tokenization. Splitting "don't" into one token or into "do" and "n't" changes every n-gram count. So does treating "mat." as one token or as "mat" plus ".".
- Casing. Scoring "The Cat" against "the cat" gives different results from lowercasing both first.
- Reference preprocessing. Many older papers scored against references that had already been tokenized with a private script. The numbers could not be reproduced without that script.
- Smoothing. An unsmoothed BLEU is 0 whenever any n-gram order has no matches. Libraries differ in how they handle this.
- Implementation details. Libraries differ in how they pick the closest reference length and how they aggregate counts across a corpus.
A reported score such as "BLEU 27.4" therefore means little unless the setup is stated. SacreBLEU takes in raw, detokenized strings. It applies a fixed, named tokenization internally, and it prints a signature string that records every setting that affects the score.
A first run
The module-level function corpus_bleu is the quickest way to get a score. The hypotheses are a list of strings. The references are a list of reference streams, and each stream is a list of strings aligned with the hypotheses by position.
import sacrebleu
hypotheses = ["the cat sat on the mat", "there is a dog in the garden"]
references = [["the cat is on the mat", "a dog is in the garden"]] # one reference stream
bleu = sacrebleu.corpus_bleu(hypotheses, references)
print(bleu.score)
print(bleu) # score, per-order precisions, brevity penalty, lengthsYou can check this by hand. Summed over both sentences, the clipped counts are:
| n | Matches | Total | Precision |
|---|---|---|---|
| 1 | 11 | 13 | 0.846 |
| 2 | 6 | 11 | 0.545 |
| 3 | 2 | 9 | 0.222 |
| 4 | 0 | 7 | 0 |
The 4-gram precision is zero, so an unsmoothed BLEU would be 0. SacreBLEU's default smoothing is exp. It replaces a zero count with a small positive precision of 1 / (2 × total), which here is 1/14. The hypotheses total 13 tokens against 12 reference tokens, so the brevity penalty is 1. The geometric mean of 0.846, 0.545, 0.222, and 0.0714 is about 0.293, so the printed score should be close to 29.3. SacreBLEU reports scores on a 0 to 100 scale, not 0 to 1.
Note that the counts are summed over the whole corpus first, and the precisions are computed once from those sums. Averaging per-sentence BLEU scores would give a different and usually lower number. Short sentences with zero higher-order matches would drag the average down.
Reading the output and the signature
Printing the result object shows the score, the four precisions, the brevity penalty, the length ratio, and the hypothesis and reference lengths. The BLEU class lets you set options and ask for the signature:
from sacrebleu.metrics import BLEU
hypotheses = ["the cat sat on the mat", "there is a dog in the garden"]
references = [["the cat is on the mat", "a dog is in the garden"]]
metric = BLEU() # defaults: tokenize="13a", lowercase=False, smooth_method="exp"
result = metric.corpus_score(hypotheses, references)
print(f"BLEU = {result.score:.1f}")
print("precisions:", [round(p, 1) for p in result.precisions])
print("BP:", result.bp, "hyp_len:", result.sys_len, "ref_len:", result.ref_len)
print(metric.get_signature()) # for example: nrefs:1|case:mixed|eff:no|tok:13a|smooth:exp|version:2.x.yThe signature is the part you copy into a paper or a results table. Each field names a setting:
nrefsis the number of reference streams.caseismixedfor case-sensitive scoring andlcfor lowercased.effrecords whether effective order is on.tokis the tokenizer.smoothis the smoothing method.versionis the SacreBLEU release.
Two scores can be compared only when their signatures match.
Settings that change the score
| Option | Values | Effect |
|---|---|---|
| `tokenize` | `13a` (default), `intl`, `zh`, `ja-mecab`, `ko-mecab`, `char`, `none`, `flores101`, `flores200` | Chooses the internal tokenizer. Use `zh`, a Japanese or Korean option, or `char` for languages without spaces between words. Some of these tokenizers need extra packages. |
| `lowercase` | `False` (default), `True` | Lowercases hypotheses and references before counting. Scores are usually higher. |
| `smooth_method` | `exp` (default), `floor`, `add-k`, `none` | Controls what replaces zero n-gram counts. `none` gives 0 whenever any order has no matches. |
| `smooth_value` | number or `None` | Parameter for `floor` and `add-k`. |
| `effective_order` | `False` (default), `True` | Uses only the n-gram orders that can occur in the sentence. Intended for sentence-level scoring. |
| `force` | `False` (default), `True` | Suppresses the warning when your input looks already tokenized. |
The default 13a tokenizer mimics the tokenization used by the WMT evaluation scripts. For most European-language translation, keep it. If you change a setting, change it deliberately and report the new signature.
Multiple references
For several valid references, pass one stream per reference. Every stream must have one entry per hypothesis, in the same order.
from sacrebleu.metrics import BLEU
hypotheses = ["the cat sat on the mat", "there is a dog in the garden"]
references = [
["the cat is on the mat", "a dog is in the garden"], # reference set 1
["there is a cat on the mat", "a dog sits in the garden"], # reference set 2
]
metric = BLEU()
print(metric.corpus_score(hypotheses, references))
print(metric.get_signature()) # nrefs is now 2With several references, n-gram clipping uses the maximum count of each n-gram in any single reference. The brevity penalty uses the reference length closest to the hypothesis length. Scores with nrefs:2 are not comparable to scores with nrefs:1.
Common errors
- Wrong reference shape. Passing
references = ["ref one", "ref two"]instead of[["ref one", "ref two"]]is a frequent mistake. SacreBLEU typically raises an error, because a flat list of strings looks like many streams of one character each. - Misaligned streams. If the hypothesis list and a reference stream differ in length, SacreBLEU raises an error. If both are the same length but the order differs, you get a valid-looking and wrong score. Check alignment before scoring.
- Scoring pre-tokenized text. If your model emits "the cat sat on the mat ." with a space before the period, detokenize it first. SacreBLEU's tokenizer then handles the punctuation. Feeding split text with
tokenize="none"only makes sense if you intend to supply your own tokenization, and you must say so. - Averaging sentence scores.
sentence_scoreis useful for inspecting individual outputs. It is not a corpus score, and the mean of sentence scores is not corpus BLEU. - Comparing across test sets. BLEU depends on the references. A 30 on one test set and a 25 on another says nothing about which system is better.
- Reading small differences as real. A gap of a few tenths of a point can come from noise in the test set. SacreBLEU supports paired bootstrap resampling on the command line for significance testing. Use it before claiming one system beats another.
From the command line
SacreBLEU also ships a command-line tool. It reads one reference file and a hypothesis file with one segment per line:
sacrebleu reference.txt -i output.txt -m bleuThe tool prints a JSON block that includes the score and the signature. For standard test sets such as the WMT sets, it can download the data itself and ensure everyone scores against the same references (sacrebleu -t wmt20 -l en-de --echo src prints the source side).
Reporting checklist
- Run SacreBLEU on raw, detokenized strings and not on pre-tokenized text.
- Copy the full signature string into the paper, table, or experiment log.
- State the test set, the language pair, and the number of references.
- Use corpus-level BLEU for the headline number.
- Keep the SacreBLEU version fixed across the runs you compare.
Exercise
A colleague reports "BLEU = 31.2" for system A and you measure "BLEU = 29.8" for system B. Your signature is nrefs:1|case:lc|eff:no|tok:13a|smooth:exp|version:2.x.y. They did not share theirs. Can you conclude A is better? What would you ask for?
Show answer
No. Your run used lowercased scoring (case:lc), which usually raises BLEU, and their case setting, tokenizer, smoothing, number of references, and test set are unknown. Ask for their full signature and test set. Better still, rerun both systems yourself with the same SacreBLEU version and settings on the same references, and then compare.
Exercise
You have 500 hypotheses and two reference translations for each. How should you build the references argument for corpus_score, and what changes in the signature?
Show answer
Build a list of two lists, each with 500 strings. The first inner list holds the first reference for every sentence in hypothesis order, and the second inner list holds the second reference for every sentence. The signature then shows nrefs:2.