Macro BLEU and ROUGE silently discard unmatched batch entries
Bug description
On current master bffc0f45158e5290f5901fb00b106987fdc779fb, Bleu(average="macro"), RougeN, RougeL, and Rouge silently process only the common prefix when the numbers of predictions and reference lists differ. Bleu(average="micro") rejects the same input with a clear ValueError.
This can hide a dropped prediction or reference in an evaluator's batch/output transformation: the metric can report a perfect score for the matched prefix instead of identifying the misaligned batch. This was found through source analysis and reproduced locally, not during a production incident.
Expected: reject unequal outer batch lengths before accumulating scores, consistently with micro BLEU. The number of alternative reference sentences for each prediction may still vary.
Reproduction
No model or tokenizer data is needed; inputs are already tokenized.
from ignite.metrics.nlp import Bleu, Rouge, RougeL, RougeN
predictions = [["match"], ["wrong"]]
references = [[["match"]]]
for name, metric in [
("BLEU macro", Bleu(ngram=1, average="macro")),
("BLEU micro", Bleu(ngram=1, average="micro")),
("ROUGE-N", RougeN(ngram=1)),
("ROUGE-L", RougeL()),
("ROUGE", Rouge(variants=[1, "L"])),
]:
try:
metric.update((predictions, references))
except ValueError as error:
print(name, type(error).__name__, str(error))
else:
print(name, metric.compute())
Observed:
BLEU macro tensor(1., dtype=torch.float64)
BLEU micro ValueError nb of candidates should be equal to nb of reference lists (2 != 1)
ROUGE-N {'Rouge-1-P': 1.0, 'Rouge-1-R': 1.0, 'Rouge-1-F': 1.0}
ROUGE-L {'Rouge-L-P': 1.0, 'Rouge-L-R': 1.0, 'Rouge-L-F': 1.0}
ROUGE {'Rouge-1-P': 1.0, 'Rouge-1-R': 1.0, 'Rouge-1-F': 1.0, 'Rouge-L-P': 1.0, 'Rouge-L-R': 1.0, 'Rouge-L-F': 1.0}
As a valid control, replacing references with [[["match"]], [["expected"], ["expected"]]] makes every score above 0.5, including micro BLEU. This also checks that different numbers of references per prediction remain valid.
The same silent truncation occurs with one prediction and two reference lists, and when these metrics are attached to an Engine that returns the batch unchanged.
Owning code
In Bleu.update, the macro branch iterates over zip(y, y_pred) before passing singleton pairs to _sentence_bleu. The existing length check in _n_gram_counter therefore never sees the original mismatch. Micro averaging passes the complete batch to that check.
_BaseRouge.update also iterates over an unchecked outer zip; the combined Rouge metric delegates to those implementations.
Environment and validation
- macOS arm64, Python 3.13.16, PyTorch 2.14.1, Ignite 0.6.0 installed editable from the unchanged commit above.
- Verified both mismatch directions through direct calls and
Engineattachment for all five configurations. All 16 nonempty mismatch checks for the four affected configurations failed to raise; micro BLEU rejected them. All ten equal-length/multi-reference controls passed. - Existing CPU BLEU and NLP utility tests: 64 passed, 103 hardware/distributed cases deselected.
- Optional NumPy was not installed; PyTorch emitted its NumPy-initialization warning, but these checks do not use NumPy APIs. No GPU/distributed validation or full repository suite was run. The full ROUGE reference suite, which downloads NLTK data, was not run; the ROUGE checks above use actual metric implementations with tokenized inputs.
Prepared autonomously with AI assistance for investigation, reproduction code, and this report. No human pre-review is claimed.
Hi, I'd like to work on this. I'll submit a PR shortly.
As it stands, yes the issue is real and is present in the code.
Issue:
Whenever we group the data individually as (y_pred, y) in a tuple, if len(y_pred) is not equal to len(y), the zip() fn in python maps it elementwise until one of the two runs out and the rest left in the other one are completely discarded.
it can be seen in this code from bleu.py (macro):
ln 254-256 for refs, hyp in zip(y, y_pred): self._sum_of_bleu += self._sentence_bleu(references=refs, candidates=hyp) self._num_sentences += 1
As you can see, the discarded values/data is neither added to the sum of BLEU nor counted in number of sentences.
Similarly in RougeN and RougeL(which inherit the update method from their parent class _BaseRouge), I saw this:
for _candidate, _reference in zip(candidates, references): multiref_scores = [self._compute_score(candidate=_candidate, reference=_ref) for _ref in _reference] score = self._multiref_reducer(multiref_scores) precision = score.precision() recall = score.recall() self._precision += precision self._recall += recall precision_recall = precision * recall if precision_recall > 0: # avoid zero division self._fmeasure += precision_recall / ((1 - self._alpha) * precision + self._alpha * recall) self._num_examples += 1
Same problem, No checking of len and loop terminates as zip() tuple does.
And as Rouge()fn uses RougeN and Rouge N, it is vulnerable too.
However when I checked Micro Bleu, I found this:
same file ln 166-169 if len(references) != len(candidates): raise ValueError( f"nb of candidates should be equal to nb of reference lists ({len(candidates)} != {len(references)})" )
FYI, references here is y and candidates is y_pred.
Now as I can think, we stand with three options:
- Add a len check like in Bleu Micro
- Padding the leftover sentences(assigning them a 0 score while still adding to num sentences)
- Just warn the user about it using
warnings.warn(Okay but then leaves it up to the user, increasing the load).
Looking at the test suites (like test_bleu.py), the metrics expect strict 1-to-1 sample mapping per batch, making these zip() loops a bug.