From 6f06b9faf486c15c1b1c6436a6bb1ba3004d3b6a Mon Sep 17 00:00:00 2001 From: Hani Mohanad <164931686+snygginghani@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:54:25 +0300 Subject: [PATCH] Refresh BERTScore IDF when the reference corpus changes --- metrics/bertscore/bertscore.py | 9 +++++ tests/test_bertscore_idf.py | 60 ++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 tests/test_bertscore_idf.py diff --git a/metrics/bertscore/bertscore.py b/metrics/bertscore/bertscore.py index 071e76ff3..97d714344 100644 --- a/metrics/bertscore/bertscore.py +++ b/metrics/bertscore/bertscore.py @@ -14,10 +14,12 @@ """ BERTScore metric. """ import functools +import warnings from contextlib import contextmanager import bert_score import datasets +from datasets.fingerprint import Hasher from packaging import version import evaluate @@ -149,8 +151,10 @@ def _compute( if idf: idf_sents = [r for ref in references for r in ref] + idf_fingerprint = Hasher.hash(idf_sents) else: idf_sents = None + idf_fingerprint = None get_hash = bert_score.utils.get_hash scorer = bert_score.BERTScorer @@ -199,6 +203,11 @@ def _compute( rescale_with_baseline=rescale_with_baseline, baseline_path=baseline_path, ) + elif idf_sents is not None and self._cached_idf_fingerprint != idf_fingerprint: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=r"^Overwriting the previous importance weights\.$") + self.cached_bertscorer.compute_idf(idf_sents) + self._cached_idf_fingerprint = idf_fingerprint (P, R, F) = self.cached_bertscorer.score( cands=predictions, diff --git a/tests/test_bertscore_idf.py b/tests/test_bertscore_idf.py new file mode 100644 index 000000000..7d987277b --- /dev/null +++ b/tests/test_bertscore_idf.py @@ -0,0 +1,60 @@ +from pathlib import Path + +import pytest + +import evaluate + + +def test_bertscore_refreshes_idf_for_changed_references(tmp_path): + pytest.importorskip("bert_score") + torch = pytest.importorskip("torch") + tokenizers = pytest.importorskip("tokenizers") + transformers = pytest.importorskip("transformers") + + vocabulary = { + token: index for index, token in enumerate("[PAD] [UNK] [CLS] [SEP] cat sat dog bird fish swam".split()) + } + backend = tokenizers.Tokenizer(tokenizers.models.WordLevel(vocabulary, unk_token="[UNK]")) + backend.pre_tokenizer = tokenizers.pre_tokenizers.Whitespace() + backend.post_processor = tokenizers.processors.TemplateProcessing( + single="[CLS] $A [SEP]", special_tokens=[("[CLS]", vocabulary["[CLS]"]), ("[SEP]", vocabulary["[SEP]"])] + ) + tokenizer = transformers.PreTrainedTokenizerFast( + tokenizer_object=backend, + pad_token="[PAD]", + unk_token="[UNK]", + cls_token="[CLS]", + sep_token="[SEP]", + model_max_length=64, + ) + tokenizer.save_pretrained(tmp_path) + with torch.random.fork_rng(devices=[]): + torch.manual_seed(23) + config = transformers.BertConfig( + vocab_size=len(vocabulary), + num_hidden_layers=1, + hidden_size=16, + num_attention_heads=2, + intermediate_size=32, + ) + transformers.BertModel(config).save_pretrained(tmp_path) + + metric_path = Path(__file__).resolve().parents[1] / "metrics" / "bertscore" + reused = evaluate.load(str(metric_path), keep_in_memory=True) + fresh = evaluate.load(str(metric_path), keep_in_memory=True) + options = { + "predictions": ["cat sat", "fish swam"], + "model_type": str(tmp_path), + "num_layers": 1, + "idf": True, + "nthreads": 0, + "device": "cpu", + "use_fast_tokenizer": True, + } + reused.compute(references=["cat dog", "cat bird"], **options) + cached_scorer = reused.cached_bertscorer + + references = [["cat sat"], ["fish cat", "bird fish"]] + expected = fresh.compute(references=references, **options) + assert reused.compute(references=references, **options) == expected + assert reused.cached_bertscorer is cached_scorer