AI Logic

Evaluation Metrics

BERTScore

Updated:

Computation of BERTScore. The left side shows the flow: the reference and candidate pass through a pretrained model, cosine similarities are computed for every pair of per-token contextual embeddings, and each token is matched to its most similar counterpart to give recall, precision, and F1. The right side shows a similarity table for the reference "today is very cold" and the candidate "now it's freezing" (illustrative values): the mean of the row maxima gives recall 0.805, the mean of the column maxima gives precision 0.870, and F1 is 0.836

Background and Overview

BERTScore is an evaluation metric that represents the tokens of a generated sentence (the candidate) and a human-written sentence (the reference) with contextual embeddings from a pretrained language model, and measures closeness in meaning through token-level cosine similarity. It produces three values: recall RBERTR_{\mathrm{BERT}}, precision PBERTP_{\mathrm{BERT}}, and their F1, FBERTF_{\mathrm{BERT}}. Higher values mean the sentence is closer to the reference.

RBERT=1∣xβˆ£βˆ‘xi∈xmax⁑x^j∈x^xi⊀x^j,PBERT=1∣x^βˆ£βˆ‘x^j∈x^max⁑xi∈xxi⊀x^j,FBERT=2PBERTβ‹…RBERTPBERT+RBERTR_{\mathrm{BERT}} = \frac{1}{|x|} \sum_{x_i \in x} \max_{\hat{x}_j \in \hat{x}} \mathbf{x}_i^{\top} \hat{\mathbf{x}}_j, \quad P_{\mathrm{BERT}} = \frac{1}{|\hat{x}|} \sum_{\hat{x}_j \in \hat{x}} \max_{x_i \in x} \mathbf{x}_i^{\top} \hat{\mathbf{x}}_j, \quad F_{\mathrm{BERT}} = 2 \frac{P_{\mathrm{BERT}} \cdot R_{\mathrm{BERT}}}{P_{\mathrm{BERT}} + R_{\mathrm{BERT}}}

xx is the token sequence of the reference, x^\hat{x} that of the candidate, and xi\mathbf{x}_i and x^j\hat{\mathbf{x}}_j are embeddings normalized to unit length. Because of the normalization, the inner product equals the cosine similarity.

BERTScore was proposed by Zhang et al. in 2019 and presented at ICLR 2020. Metrics that count n-gram matches, such as BLEU, had two weaknesses. The first is that they cannot evaluate paraphrases correctly. In the paper's example, for the reference "people like foreign cars", BLEU and METEOR score "people like visiting places abroad", which means something different, higher than "consumers prefer imported cars", which means the same thing. The second is that they cannot capture relations between distant words and only lightly penalize word-order changes that drastically alter the meaning. BERTScore addresses both by comparing meaning rather than surface form through contextual embeddings.

Definition and Computation

BERTScore is computed for one candidate–reference pair as follows.

  1. Split the candidate and the reference into tokens with the tokenizer of the chosen model (for BERT, WordPiece subwords).
  2. Pass each through the pretrained model and take the output of a chosen layer as the contextual embedding of each token. The same word gets different vectors depending on its surrounding words.
  3. Normalize the embeddings to unit length and compute the cosine similarity for every pair of a reference token and a candidate token.
  4. Greedy matching: for each reference token, pick the candidate token with the highest similarity and average those similarities to get recall RBERTR_{\mathrm{BERT}}. Conversely, average the maximum over the reference for each candidate token to get precision PBERTP_{\mathrm{BERT}}.
  5. Take the harmonic mean of the two to get FBERTF_{\mathrm{BERT}}.
  6. When there are multiple references, compute the score against each and use the highest value (the image-captioning experiments in the paper).

The right side of the figure at the top shows an example similarity table for the reference "today is very cold" and the candidate "now it's freezing" (the values are illustrative). Even when the wording differs, as with "cold" and "freezing", the similarity is high when the meanings are close. The mean of the row maxima gives recall 0.805, the mean of the column maxima gives precision 0.870, and F1 is 0.836.

The paper also presents two optional refinements.

  • idf weighting: rare words tend to carry more of a sentence's meaning, so each token is weighted in the average by its idf (a value that grows as fewer sentences contain the word), computed from the set of references being evaluated. In the paper's machine translation experiments, it helped in some cases and not in others.
  • Rescaling with a baseline: actual scores cluster in a narrow range and are hard to read. The score is therefore linearly transformed as R^BERT=(RBERTβˆ’b)/(1βˆ’b)\hat{R}_{\mathrm{BERT}} = (R_{\mathrm{BERT}} - b) / (1 - b), using the mean BERTScore bb between unrelated sentences (computed from 1 million random pairs of Common Crawl sentences). Rankings and correlations with human judgments do not change; the transformation is only for readability.

Embeddings are taken from an intermediate layer, not the last layer. In the paper's appendix, correlation with human judgments dropped sharply toward the last layers. The layers the paper selected on validation data are layer 17 for RoBERTa-large (24 layers) and layer 9 for multilingual BERT (12 layers).

What It Measures and Its Limitations

BERTScore measures, through embedding closeness, whether the meaning of each reference token appears somewhere in the candidate (recall) and whether the meaning of each candidate token appears somewhere in the reference (precision). Because contextual embeddings also carry information about surrounding words, comparing tokens one at a time still reflects the meaning of the whole sentence to some extent.

It has the following limitations.

  • Scores depend on the model and layer: the paper itself states that no single setting beats all others and that the choice must fit the domain and language.
  • Less stable for languages other than English: the paper recommends multilingual BERT for other languages, but notes that performance is unstable for low-resource languages.
  • The absolute value carries little meaning: without rescaling, even unrelated sentences get fairly high scores. This is why the paper provides baseline rescaling.
  • Computation requires a GPU and a large model: in the paper, a GTX 1080 Ti processed 192.5 pairs per second, and the WMT18 Englishβ†’German test set (2,998 sentences) took 15.6 seconds, versus 5.4 seconds for BLEU with sacreBLEU. The paper considers the extra time negligible for use in validation and testing.
  • It inherits the model's biases: for domain-specific words absent from the pretraining data, or for expressions the model handles poorly, it may not measure closeness in meaning correctly.

BERTScore values are comparable only when the model, layer, use of idf, use of rescaling, and library version are all the same. The official library (bert_score) can output a hash describing these settings (for example, roberta-large_L17_no-idf_version=0.3.12(hug_trans=4.x)), which should be reported alongside the score. Also, depending on the task, recall rather than F1 agrees better with human judgments (the image-captioning experiments in the paper).

Validation in the Original Paper

The paper examined correlation with human judgments on the WMT18 machine translation evaluation data (14 language pairs, 149 systems) and on the COCO 2015 image captioning challenge (12 systems). It used the 24-layer RoBERTa-large for English, Chinese BERT for Chinese, and multilingual BERT for the other languages.

At the sentence level (WMT18, Kendall rank correlation), BERTScore substantially outperformed BLEU (sentence-level SentBLEU). Selected language pairs are shown below (left: other language→English, right: English→other language).

MetricCzechGermanChinese
BLEU0.233 / 0.3890.415 / 0.6200.178 / 0.311
YiSi-10.319 / 0.4960.488 / 0.6910.211 / 0.323
FBERTF_{\mathrm{BERT}}0.404 / 0.5620.550 / 0.7280.264 / 0.364

Since it substantially outperforms BLEU at the sentence level, the paper argues that BERTScore is well suited to analyzing individual examples. In system-level correlation, BERTScore also ranked consistently near the top. Which of RBERTR_{\mathrm{BERT}}, PBERTP_{\mathrm{BERT}}, and FBERTF_{\mathrm{BERT}} was best varied with the setting, but FBERTF_{\mathrm{BERT}} was reliably good across all settings, so the paper recommends F1 for machine translation.

For image captioning (COCO 2015), the paper compared Pearson correlation with the fraction of captions judged as good as or better than human captions (M1).

MetricCorrelation with M1
BLEUβˆ’0.019
ROUGE-L0.090
METEOR0.606
chrF++0.702
FBERTF_{\mathrm{BERT}}0.322
RBERTR_{\mathrm{BERT}}0.888
RBERTR_{\mathrm{BERT}} (with idf)0.917

Here recall performed especially well, and idf weighting helped substantially. The paper attributes this to humans placing weight on content words.

The paper also tested robustness on paraphrase detection built by swapping words (PAWS). The area under the ROC curve (ROC AUC) fell to near-random levels for BLEU (0.527), METEOR (0.532), and chrF++ (0.608), whereas FBERTF_{\mathrm{BERT}} reached 0.685 and degraded only slightly.

Where It Is Used

BERTScore is mainly used in the following settings.

  • Machine translation evaluation: alongside BLEU and chrF, it evaluates closeness in meaning, including paraphrases. The paper's results show it is particularly suited to sentence-by-sentence comparison.
  • Image caption generation: a task with multiple reference captions whose wording varies widely. In the paper, recall with idf weighting correlated well with human judgments.
  • Text generation in general, such as summarization and dialogue: in tasks where wording often diverges from the reference, it complements surface-matching metrics such as ROUGE.
  • Validation during training: since the added computation time is small, the paper suggests it can also be used for validation (for example, deciding when to stop training).

Comparison with Similar Metrics

The table compares BERTScore with other metrics used to evaluate text generation from the same perspectives.

MetricUnit comparedPrecision / recallRobustness to paraphraseCompute costExtra tools
BERTScoreContextual token embeddingsBoth (F1)Strong (compares meaning)Heavy (GPU preferred)Pretrained language model
BLEUWord n-grams (1–4)Precision + brevity penaltyWeak (surface match only)LightTokenization
chrFCharacter n-grams (1–6)Both (F-score)Moderate (robust to inflection)LightNone
METEORWord alignmentBoth (recall weighted)Fairly strong (stems and synonyms match)MediumStemmer and synonym dictionary
ROUGEWord n-grams, longest common subsequenceMainly recallWeakLightTokenization

Guidelines for choosing:

  • Comparing with prior work: always report the standard metrics of the field, such as BLEU or ROUGE, and add BERTScore as a complementary measure of closeness in meaning.
  • Generation with many paraphrases (captions, summaries, dialogue): use BERTScore. When there are multiple references and content coverage matters, also look at recall.
  • Languages other than English: it can be computed with a multilingual model, but it is less stable, so report chrF alongside it.
  • Limited compute: rely mainly on light metrics such as BLEU and chrF, and add BERTScore only for the final evaluation.

PyTorch example

Show code
python
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer


def embed(texts, tok, model, layer):
  """For each sentence, return the contextual embeddings (unit-normalized) from the given layer. Special tokens such as [CLS] and [SEP] are removed."""
  out = []
  for t in texts:
    enc = tok(t, return_tensors="pt", return_special_tokens_mask=True)
    special = enc.pop("special_tokens_mask")[0].bool()
    with torch.no_grad():
      h = model(**enc, output_hidden_states=True).hidden_states[layer][0]  # (num tokens, dim)
    out.append(F.normalize(h[~special], dim=-1))
  return out


def bert_score(cands, refs, name="bert-base-multilingual-cased", layer=9):
  """BERTScore of Zhang et al. (2020) (no idf, no rescaling). Returns (P, R, F1) per sentence.
  layer=9 is the layer recommended for multilingual BERT in Table 8 of the paper's appendix."""
  tok = AutoTokenizer.from_pretrained(name)
  model = AutoModel.from_pretrained(name).eval()  # evaluation, so eval() (disables dropout)
  results = []
  for c, r in zip(embed(cands, tok, model, layer), embed(refs, tok, model, layer)):
    sim = r @ c.T                      # cosine similarity, (reference tokens, candidate tokens)
    R = sim.max(dim=1).values.mean()   # each reference token -> most similar candidate token
    P = sim.max(dim=0).values.mean()   # each candidate token -> most similar reference token
    results.append((P.item(), R.item(), (2 * P * R / (P + R)).item()))
  return results


print(bert_score(["Now it's freezing"], ["Today is very cold"]))

# Official library (pip install bert-score). Specifying lang uses the model and layer chosen in the paper
# (layer 17 of roberta-large for English, layer 9 of bert-base-multilingual-cased otherwise)
from bert_score import score

P, R, F1 = score(["Now it's freezing"], ["Today is very cold"], lang="en",
                 idf=False,                  # True computes idf weights from the set of references
                 rescale_with_baseline=False,  # True rescales the score. The library has no Japanese baseline,
                                               # so for Japanese pass one you computed via baseline_path
                 return_hash=False)
print(P, R, F1)

FAQ

Q. Which should I report: recall, precision, or F1?
A.

When in doubt, F1 (FBERTF_{\mathrm{BERT}}). In the paper's machine translation experiments, which of the three was best varied with the setting, but F1 gave reliably good results across all settings. However, in tasks where capturing the reference's content matters, such as image captioning, recall agreed better with human judgments. Reporting all three makes it easier for readers to judge.

Q. Why can BERTScore exceed 0.8 even when the sentences differ in meaning?
A.

Contextual embeddings give fairly high cosine similarity even between unrelated sentences. Scores tend to cluster in a narrow range, so the absolute value alone cannot be relied on. The paper provides rescaling that subtracts the mean bb for unrelated sentences and transforms the score as (Rβˆ’b)/(1βˆ’b)(R - b)/(1 - b). Rescaling does not change rankings, so compare scores computed with the same settings, in relative terms.

Q. Can it be used to evaluate Japanese sentences?
A.

Yes. Specifying lang="en" in the official library uses layer 9 of multilingual BERT (bert-base-multilingual-cased). However, the paper notes that multilingual BERT is unstable for low-resource languages, and correlation with human judgments for Japanese was not verified in the original paper. If you switch to a model trained on Japanese, you need to choose the layer yourself, and the scores are no longer comparable with other settings.

References

  1. Zhang, T., Kishore, V., Wu, F., Weinberger, K. Q., & Artzi, Y. (2020). BERTScore: Evaluating Text Generation with BERT. ICLR 2020. arXiv:1904.09675.
  2. bert_score (official implementation, GitHub repository).
  3. Lightning AI. torchmetrics.text.BERTScore (API reference).