From 57cfa412cd12213914eec363eaa501f4ce2557b5 Mon Sep 17 00:00:00 2001 From: Richard lu <50914695+ippq@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:28:42 +0100 Subject: [PATCH 1/2] Fix BLEU brevity penalty with multiple references compute_bleu from tensorflow/nmt uses the shortest reference as the effective reference length. BLEU (Papineni et al., 2002), multi-bleu.perl, sacrebleu and NLTK use the reference closest in length to the prediction. Recompute the reference length, ratio, brevity penalty and score with the closest-length rule and update the README examples that showed the old behaviour. --- metrics/bleu/README.md | 8 ++++---- metrics/bleu/bleu.py | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/metrics/bleu/README.md b/metrics/bleu/README.md index 004d9011c..0472cc1e9 100644 --- a/metrics/bleu/README.md +++ b/metrics/bleu/README.md @@ -44,7 +44,7 @@ This metric takes as input a list of predicted sentences and a list of lists of >>> bleu = evaluate.load("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` ### Inputs @@ -68,7 +68,7 @@ The default tokenizer is based on whitespace and regexes. It can be replaced by Output Example: ```python -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. @@ -106,7 +106,7 @@ Example where the first prediction has 2 references: >>> bleu = evaluate.load("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` Example with the word tokenizer from NLTK: @@ -123,7 +123,7 @@ Example with the word tokenizer from NLTK: ... ] >>> results = bleu.compute(predictions=predictions, references=references, tokenizer=word_tokenize) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` ## Limitations and Bias diff --git a/metrics/bleu/bleu.py b/metrics/bleu/bleu.py index 38a10c3b3..77ad743d6 100644 --- a/metrics/bleu/bleu.py +++ b/metrics/bleu/bleu.py @@ -13,6 +13,8 @@ # limitations under the License. """ BLEU metric. """ +import math + import datasets import evaluate @@ -81,6 +83,14 @@ >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["bleu"]) 1.0 + + With several references, the brevity penalty uses the reference closest in length to the prediction: + + >>> predictions = ["the cat sat on the mat today"] + >>> references = [["the cat sat on the mat today in the sun", "the cat sat"]] + >>> results = bleu.compute(predictions=predictions, references=references) + >>> print(results["reference_length"], round(results["brevity_penalty"], 4)) + 10 0.6514 """ @@ -122,7 +132,17 @@ def _compute(self, predictions, references, tokenizer=Tokenizer13a(), max_order= score = compute_bleu( reference_corpus=references, translation_corpus=predictions, max_order=max_order, smooth=smooth ) - (bleu, precisions, bp, ratio, translation_length, reference_length) = score + (_, precisions, _, _, translation_length, _) = score + # compute_bleu uses the *shortest* reference for the brevity penalty. Papineni et al. (2002), + # multi-bleu.perl, sacrebleu and NLTK use the reference whose length is closest to the + # prediction (ties go to the shorter one), so recompute the brevity penalty that way. + reference_length = sum( + min((abs(len(r) - len(p)), len(r)) for r in refs)[1] for refs, p in zip(references, predictions) + ) + geo_mean = math.exp(sum(math.log(p) for p in precisions) / max_order) if min(precisions) > 0 else 0.0 + ratio = translation_length / reference_length + bp = 1.0 if ratio > 1.0 else math.exp(1 - 1.0 / ratio) + bleu = geo_mean * bp return { "bleu": bleu, "precisions": precisions, From eeab3563e7d459dc4358fe1484f4c3fed2affb94 Mon Sep 17 00:00:00 2001 From: Richard lu <50914695+ippq@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:33:16 +0100 Subject: [PATCH 2/2] Compute BLEU n-gram precisions locally so an empty alternate reference no longer crashes --- metrics/bleu/bleu.py | 51 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/metrics/bleu/bleu.py b/metrics/bleu/bleu.py index 77ad743d6..954ca91c7 100644 --- a/metrics/bleu/bleu.py +++ b/metrics/bleu/bleu.py @@ -13,16 +13,40 @@ # limitations under the License. """ BLEU metric. """ +import collections import math import datasets import evaluate -from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py from .tokenizer_13a import Tokenizer13a +def _ngram_counts(segment, max_order): + return collections.Counter( + tuple(segment[i : i + order]) for order in range(1, max_order + 1) for i in range(len(segment) - order + 1) + ) + + +def _ngram_precisions(reference_corpus, translation_corpus, max_order=4, smooth=False): + """Clipped n-gram precisions, as in https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py""" + matches_by_order = [0] * max_order + possible_matches_by_order = [0] * max_order + for references, translation in zip(reference_corpus, translation_corpus): + merged_ref_ngram_counts = collections.Counter() + for reference in references: + merged_ref_ngram_counts |= _ngram_counts(reference, max_order) + overlap = _ngram_counts(translation, max_order) & merged_ref_ngram_counts + for ngram, count in overlap.items(): + matches_by_order[len(ngram) - 1] += count + for order in range(1, max_order + 1): + possible_matches_by_order[order - 1] += max(len(translation) - order + 1, 0) + if smooth: + return [(m + 1.0) / (p + 1.0) for m, p in zip(matches_by_order, possible_matches_by_order)] + return [m / p if p > 0 else 0.0 for m, p in zip(matches_by_order, possible_matches_by_order)] + + _CITATION = """\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, @@ -91,6 +115,14 @@ >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["reference_length"], round(results["brevity_penalty"], 4)) 10 0.6514 + + An empty alternate reference is allowed: + + >>> predictions = ["a valid four word answer"] + >>> references = [["a valid four word answer", ""]] + >>> results = bleu.compute(predictions=predictions, references=references) + >>> print(results["bleu"], results["reference_length"]) + 1.0 5 """ @@ -129,19 +161,18 @@ def _compute(self, predictions, references, tokenizer=Tokenizer13a(), max_order= references = [[tokenizer(r) for r in ref] for ref in references] predictions = [tokenizer(p) for p in predictions] - score = compute_bleu( - reference_corpus=references, translation_corpus=predictions, max_order=max_order, smooth=smooth - ) - (_, precisions, _, _, translation_length, _) = score - # compute_bleu uses the *shortest* reference for the brevity penalty. Papineni et al. (2002), - # multi-bleu.perl, sacrebleu and NLTK use the reference whose length is closest to the - # prediction (ties go to the shorter one), so recompute the brevity penalty that way. + precisions = _ngram_precisions(references, predictions, max_order=max_order, smooth=smooth) + translation_length = sum(len(p) for p in predictions) + # The brevity penalty uses the reference whose length is closest to the prediction (ties go to + # the shorter one), as in Papineni et al. (2002), multi-bleu.perl, sacrebleu and NLTK. The TF + # nmt `compute_bleu` this metric used to call takes the *shortest* reference instead, and + # divides by its length before returning, so an empty alternate reference made it crash. reference_length = sum( min((abs(len(r) - len(p)), len(r)) for r in refs)[1] for refs, p in zip(references, predictions) ) geo_mean = math.exp(sum(math.log(p) for p in precisions) / max_order) if min(precisions) > 0 else 0.0 - ratio = translation_length / reference_length - bp = 1.0 if ratio > 1.0 else math.exp(1 - 1.0 / ratio) + ratio = translation_length / reference_length if reference_length > 0 else float("inf") + bp = 1.0 if ratio > 1.0 else (math.exp(1 - 1.0 / ratio) if ratio > 0 else 0.0) bleu = geo_mean * bp return { "bleu": bleu,