Spaces:
Running
Running
Update Space (evaluate main: 828c6327)
Browse files- README.md +118 -5
- app.py +6 -0
- bertscore.py +208 -0
- requirements.txt +4 -0
README.md
CHANGED
@@ -1,12 +1,125 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
sdk_version: 3.0.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
|
|
|
|
10 |
---
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
title: BERT Score
|
3 |
+
emoji: 🤗
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: red
|
6 |
sdk: gradio
|
7 |
sdk_version: 3.0.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
tags:
|
11 |
+
- evaluate
|
12 |
+
- metric
|
13 |
---
|
14 |
|
15 |
+
# Metric Card for BERT Score
|
16 |
+
|
17 |
+
## Metric description
|
18 |
+
|
19 |
+
BERTScore is an automatic evaluation metric for text generation that computes a similarity score for each token in the candidate sentence with each token in the reference sentence. It leverages the pre-trained contextual embeddings from [BERT](https://huggingface.co/bert-base-uncased) models and matches words in candidate and reference sentences by cosine similarity.
|
20 |
+
|
21 |
+
Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language generation tasks.
|
22 |
+
|
23 |
+
## How to use
|
24 |
+
|
25 |
+
BERTScore takes 3 mandatory arguments : `predictions` (a list of string of candidate sentences), `references` (a list of strings or list of list of strings of reference sentences) and either `lang` (a string of two letters indicating the language of the sentences, in [ISO 639-1 format](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)) or `model_type` (a string specififying which model to use, according to the BERT specification). The default behavior of the metric is to use the suggested model for the target language when one is specified, otherwise to use the `model_type` indicated.
|
26 |
+
|
27 |
+
```python
|
28 |
+
from evaluate import load
|
29 |
+
bertscore = load("bertscore")
|
30 |
+
predictions = ["hello there", "general kenobi"]
|
31 |
+
references = ["hello there", "general kenobi"]
|
32 |
+
results = bertscore.compute(predictions=predictions, references=references, lang="en")
|
33 |
+
```
|
34 |
+
|
35 |
+
BERTScore also accepts multiple optional arguments:
|
36 |
+
|
37 |
+
|
38 |
+
`num_layers` (int): The layer of representation to use. The default is the number of layers tuned on WMT16 correlation data, which depends on the `model_type` used.
|
39 |
+
|
40 |
+
`verbose` (bool): Turn on intermediate status update. The default value is `False`.
|
41 |
+
|
42 |
+
`idf` (bool or dict): Use idf weighting; can also be a precomputed idf_dict.
|
43 |
+
|
44 |
+
`device` (str): On which the contextual embedding model will be allocated on. If this argument is `None`, the model lives on `cuda:0` if cuda is available.
|
45 |
+
|
46 |
+
`nthreads` (int): Number of threads used for computation. The default value is `4`.
|
47 |
+
|
48 |
+
`rescale_with_baseline` (bool): Rescale BERTScore with the pre-computed baseline. The default value is `False`.
|
49 |
+
|
50 |
+
`batch_size` (int): BERTScore processing batch size, at least one of `model_type` or `lang`. `lang` needs to be specified when `rescale_with_baseline` is `True`.
|
51 |
+
|
52 |
+
`baseline_path` (str): Customized baseline file.
|
53 |
+
|
54 |
+
`use_fast_tokenizer` (bool): `use_fast` parameter passed to HF tokenizer. The default value is `False`.
|
55 |
+
|
56 |
+
|
57 |
+
## Output values
|
58 |
+
|
59 |
+
BERTScore outputs a dictionary with the following values:
|
60 |
+
|
61 |
+
`precision`: The [precision](https://huggingface.co/metrics/precision) for each sentence from the `predictions` + `references` lists, which ranges from 0.0 to 1.0.
|
62 |
+
|
63 |
+
`recall`: The [recall](https://huggingface.co/metrics/recall) for each sentence from the `predictions` + `references` lists, which ranges from 0.0 to 1.0.
|
64 |
+
|
65 |
+
`f1`: The [F1 score](https://huggingface.co/metrics/f1) for each sentence from the `predictions` + `references` lists, which ranges from 0.0 to 1.0.
|
66 |
+
|
67 |
+
`hashcode:` The hashcode of the library.
|
68 |
+
|
69 |
+
|
70 |
+
### Values from popular papers
|
71 |
+
The [original BERTScore paper](https://openreview.net/pdf?id=SkeHuCVFDr) reported average model selection accuracies (Hits@1) on WMT18 hybrid systems for different language pairs, which ranged from 0.004 for `en<->tr` to 0.824 for `en<->de`.
|
72 |
+
|
73 |
+
For more recent model performance, see the [metric leaderboard](https://paperswithcode.com/paper/bertscore-evaluating-text-generation-with).
|
74 |
+
|
75 |
+
## Examples
|
76 |
+
|
77 |
+
Maximal values with the `distilbert-base-uncased` model:
|
78 |
+
|
79 |
+
```python
|
80 |
+
from evaluate import load
|
81 |
+
bertscore = load("bertscore")
|
82 |
+
predictions = ["hello world", "general kenobi"]
|
83 |
+
references = ["hello world", "general kenobi"]
|
84 |
+
results = bertscore.compute(predictions=predictions, references=references, model_type="distilbert-base-uncased")
|
85 |
+
print(results)
|
86 |
+
{'precision': [1.0, 1.0], 'recall': [1.0, 1.0], 'f1': [1.0, 1.0], 'hashcode': 'distilbert-base-uncased_L5_no-idf_version=0.3.10(hug_trans=4.10.3)'}
|
87 |
+
```
|
88 |
+
|
89 |
+
Partial match with the `bert-base-uncased` model:
|
90 |
+
|
91 |
+
```python
|
92 |
+
from evaluate import load
|
93 |
+
bertscore = load("bertscore")
|
94 |
+
predictions = ["hello world", "general kenobi"]
|
95 |
+
references = ["goodnight moon", "the sun is shining"]
|
96 |
+
results = bertscore.compute(predictions=predictions, references=references, model_type="distilbert-base-uncased")
|
97 |
+
print(results)
|
98 |
+
{'precision': [0.7380737066268921, 0.5584042072296143], 'recall': [0.7380737066268921, 0.5889028906822205], 'f1': [0.7380737066268921, 0.5732481479644775], 'hashcode': 'bert-base-uncased_L5_no-idf_version=0.3.10(hug_trans=4.10.3)'}
|
99 |
+
```
|
100 |
+
|
101 |
+
## Limitations and bias
|
102 |
+
|
103 |
+
The [original BERTScore paper](https://openreview.net/pdf?id=SkeHuCVFDr) showed that BERTScore correlates well with human judgment on sentence-level and system-level evaluation, but this depends on the model and language pair selected.
|
104 |
+
|
105 |
+
Furthermore, not all languages are supported by the metric -- see the [BERTScore supported language list](https://github.com/google-research/bert/blob/master/multilingual.md#list-of-languages) for more information.
|
106 |
+
|
107 |
+
Finally, calculating the BERTScore metric involves downloading the BERT model that is used to compute the score-- the default model for `en`, `roberta-large`, takes over 1.4GB of storage space and downloading it can take a significant amount of time depending on the speed of your internet connection. If this is an issue, choose a smaller model; for instance `distilbert-base-uncased` is 268MB. A full list of compatible models can be found [here](https://docs.google.com/spreadsheets/d/1RKOVpselB98Nnh_EOC4A2BYn8_201tmPODpNWu4w7xI/edit#gid=0).
|
108 |
+
|
109 |
+
|
110 |
+
## Citation
|
111 |
+
|
112 |
+
```bibtex
|
113 |
+
@inproceedings{bert-score,
|
114 |
+
title={BERTScore: Evaluating Text Generation with BERT},
|
115 |
+
author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},
|
116 |
+
booktitle={International Conference on Learning Representations},
|
117 |
+
year={2020},
|
118 |
+
url={https://openreview.net/forum?id=SkeHuCVFDr}
|
119 |
+
}
|
120 |
+
```
|
121 |
+
|
122 |
+
## Further References
|
123 |
+
|
124 |
+
- [BERTScore Project README](https://github.com/Tiiiger/bert_score#readme)
|
125 |
+
- [BERTScore ICLR 2020 Poster Presentation](https://iclr.cc/virtual_2020/poster_SkeHuCVFDr.html)
|
app.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import evaluate
|
2 |
+
from evaluate.utils import launch_gradio_widget
|
3 |
+
|
4 |
+
|
5 |
+
module = evaluate.load("bertscore")
|
6 |
+
launch_gradio_widget(module)
|
bertscore.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2020 The HuggingFace Evaluate Authors.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
""" BERTScore metric. """
|
15 |
+
|
16 |
+
import functools
|
17 |
+
from contextlib import contextmanager
|
18 |
+
|
19 |
+
import bert_score
|
20 |
+
import datasets
|
21 |
+
from packaging import version
|
22 |
+
|
23 |
+
import evaluate
|
24 |
+
|
25 |
+
|
26 |
+
@contextmanager
|
27 |
+
def filter_logging_context():
|
28 |
+
def filter_log(record):
|
29 |
+
return False if "This IS expected if you are initializing" in record.msg else True
|
30 |
+
|
31 |
+
logger = datasets.utils.logging.get_logger("transformers.modeling_utils")
|
32 |
+
logger.addFilter(filter_log)
|
33 |
+
try:
|
34 |
+
yield
|
35 |
+
finally:
|
36 |
+
logger.removeFilter(filter_log)
|
37 |
+
|
38 |
+
|
39 |
+
_CITATION = """\
|
40 |
+
@inproceedings{bert-score,
|
41 |
+
title={BERTScore: Evaluating Text Generation with BERT},
|
42 |
+
author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},
|
43 |
+
booktitle={International Conference on Learning Representations},
|
44 |
+
year={2020},
|
45 |
+
url={https://openreview.net/forum?id=SkeHuCVFDr}
|
46 |
+
}
|
47 |
+
"""
|
48 |
+
|
49 |
+
_DESCRIPTION = """\
|
50 |
+
BERTScore leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference
|
51 |
+
sentences by cosine similarity.
|
52 |
+
It has been shown to correlate with human judgment on sentence-level and system-level evaluation.
|
53 |
+
Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language
|
54 |
+
generation tasks.
|
55 |
+
|
56 |
+
See the project's README at https://github.com/Tiiiger/bert_score#readme for more information.
|
57 |
+
"""
|
58 |
+
|
59 |
+
_KWARGS_DESCRIPTION = """
|
60 |
+
BERTScore Metrics with the hashcode from a source against one or more references.
|
61 |
+
|
62 |
+
Args:
|
63 |
+
predictions (list of str): Prediction/candidate sentences.
|
64 |
+
references (list of str or list of list of str): Reference sentences.
|
65 |
+
lang (str): Language of the sentences; required (e.g. 'en').
|
66 |
+
model_type (str): Bert specification, default using the suggested
|
67 |
+
model for the target language; has to specify at least one of
|
68 |
+
`model_type` or `lang`.
|
69 |
+
num_layers (int): The layer of representation to use,
|
70 |
+
default using the number of layers tuned on WMT16 correlation data.
|
71 |
+
verbose (bool): Turn on intermediate status update.
|
72 |
+
idf (bool or dict): Use idf weighting; can also be a precomputed idf_dict.
|
73 |
+
device (str): On which the contextual embedding model will be allocated on.
|
74 |
+
If this argument is None, the model lives on cuda:0 if cuda is available.
|
75 |
+
nthreads (int): Number of threads.
|
76 |
+
batch_size (int): Bert score processing batch size,
|
77 |
+
at least one of `model_type` or `lang`. `lang` needs to be
|
78 |
+
specified when `rescale_with_baseline` is True.
|
79 |
+
rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline.
|
80 |
+
baseline_path (str): Customized baseline file.
|
81 |
+
use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. New in version 0.3.10.
|
82 |
+
|
83 |
+
Returns:
|
84 |
+
precision: Precision.
|
85 |
+
recall: Recall.
|
86 |
+
f1: F1 score.
|
87 |
+
hashcode: Hashcode of the library.
|
88 |
+
|
89 |
+
Examples:
|
90 |
+
|
91 |
+
>>> predictions = ["hello there", "general kenobi"]
|
92 |
+
>>> references = ["hello there", "general kenobi"]
|
93 |
+
>>> bertscore = evaluate.load("bertscore")
|
94 |
+
>>> results = bertscore.compute(predictions=predictions, references=references, lang="en")
|
95 |
+
>>> print([round(v, 2) for v in results["f1"]])
|
96 |
+
[1.0, 1.0]
|
97 |
+
"""
|
98 |
+
|
99 |
+
|
100 |
+
@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
|
101 |
+
class BERTScore(evaluate.EvaluationModule):
|
102 |
+
def _info(self):
|
103 |
+
return evaluate.EvaluationModuleInfo(
|
104 |
+
description=_DESCRIPTION,
|
105 |
+
citation=_CITATION,
|
106 |
+
homepage="https://github.com/Tiiiger/bert_score",
|
107 |
+
inputs_description=_KWARGS_DESCRIPTION,
|
108 |
+
features=datasets.Features(
|
109 |
+
{
|
110 |
+
"predictions": datasets.Value("string", id="sequence"),
|
111 |
+
"references": datasets.Sequence(datasets.Value("string", id="sequence"), id="references"),
|
112 |
+
}
|
113 |
+
),
|
114 |
+
codebase_urls=["https://github.com/Tiiiger/bert_score"],
|
115 |
+
reference_urls=[
|
116 |
+
"https://github.com/Tiiiger/bert_score",
|
117 |
+
"https://arxiv.org/abs/1904.09675",
|
118 |
+
],
|
119 |
+
)
|
120 |
+
|
121 |
+
def _compute(
|
122 |
+
self,
|
123 |
+
predictions,
|
124 |
+
references,
|
125 |
+
lang=None,
|
126 |
+
model_type=None,
|
127 |
+
num_layers=None,
|
128 |
+
verbose=False,
|
129 |
+
idf=False,
|
130 |
+
device=None,
|
131 |
+
batch_size=64,
|
132 |
+
nthreads=4,
|
133 |
+
all_layers=False,
|
134 |
+
rescale_with_baseline=False,
|
135 |
+
baseline_path=None,
|
136 |
+
use_fast_tokenizer=False,
|
137 |
+
):
|
138 |
+
get_hash = bert_score.utils.get_hash
|
139 |
+
scorer = bert_score.BERTScorer
|
140 |
+
|
141 |
+
if version.parse(bert_score.__version__) >= version.parse("0.3.10"):
|
142 |
+
get_hash = functools.partial(get_hash, use_fast_tokenizer=use_fast_tokenizer)
|
143 |
+
scorer = functools.partial(scorer, use_fast_tokenizer=use_fast_tokenizer)
|
144 |
+
elif use_fast_tokenizer:
|
145 |
+
raise ImportWarning(
|
146 |
+
"To use a fast tokenizer, the module `bert-score>=0.3.10` is required, and the current version of `bert-score` doesn't match this condition.\n"
|
147 |
+
'You can install it with `pip install "bert-score>=0.3.10"`.'
|
148 |
+
)
|
149 |
+
|
150 |
+
if model_type is None:
|
151 |
+
assert lang is not None, "either lang or model_type should be specified"
|
152 |
+
model_type = bert_score.utils.lang2model[lang.lower()]
|
153 |
+
|
154 |
+
if num_layers is None:
|
155 |
+
num_layers = bert_score.utils.model2layers[model_type]
|
156 |
+
|
157 |
+
hashcode = get_hash(
|
158 |
+
model=model_type,
|
159 |
+
num_layers=num_layers,
|
160 |
+
idf=idf,
|
161 |
+
rescale_with_baseline=rescale_with_baseline,
|
162 |
+
use_custom_baseline=baseline_path is not None,
|
163 |
+
)
|
164 |
+
|
165 |
+
with filter_logging_context():
|
166 |
+
if not hasattr(self, "cached_bertscorer") or self.cached_bertscorer.hash != hashcode:
|
167 |
+
self.cached_bertscorer = scorer(
|
168 |
+
model_type=model_type,
|
169 |
+
num_layers=num_layers,
|
170 |
+
batch_size=batch_size,
|
171 |
+
nthreads=nthreads,
|
172 |
+
all_layers=all_layers,
|
173 |
+
idf=idf,
|
174 |
+
device=device,
|
175 |
+
lang=lang,
|
176 |
+
rescale_with_baseline=rescale_with_baseline,
|
177 |
+
baseline_path=baseline_path,
|
178 |
+
)
|
179 |
+
|
180 |
+
(P, R, F) = self.cached_bertscorer.score(
|
181 |
+
cands=predictions,
|
182 |
+
refs=references,
|
183 |
+
verbose=verbose,
|
184 |
+
batch_size=batch_size,
|
185 |
+
)
|
186 |
+
output_dict = {
|
187 |
+
"precision": P.tolist(),
|
188 |
+
"recall": R.tolist(),
|
189 |
+
"f1": F.tolist(),
|
190 |
+
"hashcode": hashcode,
|
191 |
+
}
|
192 |
+
return output_dict
|
193 |
+
|
194 |
+
def add_batch(self, predictions=None, references=None, **kwargs):
|
195 |
+
"""Add a batch of predictions and references for the metric's stack."""
|
196 |
+
# References can be strings or lists of strings
|
197 |
+
# Let's change strings to lists of strings with one element
|
198 |
+
if references is not None:
|
199 |
+
references = [[ref] if isinstance(ref, str) else ref for ref in references]
|
200 |
+
super().add_batch(predictions=predictions, references=references, **kwargs)
|
201 |
+
|
202 |
+
def add(self, prediction=None, reference=None, **kwargs):
|
203 |
+
"""Add one prediction and reference for the metric's stack."""
|
204 |
+
# References can be strings or lists of strings
|
205 |
+
# Let's change strings to lists of strings with one element
|
206 |
+
if isinstance(reference, str):
|
207 |
+
reference = [reference]
|
208 |
+
super().add(prediction=prediction, reference=reference, **kwargs)
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# TODO: fix github to release
|
2 |
+
git+https://github.com/huggingface/evaluate.git@b6e6ed7f3e6844b297bff1b43a1b4be0709b9671
|
3 |
+
datasets~=2.0
|
4 |
+
bert_score
|