Algorithm Search⌘K

Algorithmresearch

BERTScore

Also called BERT score.

Score a candidate text against a reference by greedy matching of their contextual token embeddings by cosine, as precision, recall and F1.

Time
O(n m d) worst
Space
O(n m) extra
Where
d = the embedding width; m = the number of candidate tokens; n = the number of reference tokens
Properties
deterministicexactofflineiterative
Origin
Tianyi Zhang, Varsha Kishore, Felix Wu, Kilian Q. Weinberger, Yoav Artzi, 2020

BERTScore compares a candidate text with a reference text through their contextual token embeddings, the vectors that a pretrained network such as BERT gives to each token in its sentence. Each reference token is matched to the most similar candidate token by cosine similarity, and the mean of these best similarities is the recall. Each candidate token is matched to the most similar reference token, and the mean is the precision. F1 is their harmonic mean. Tianyi Zhang, Varsha Kishore, Felix Wu, Kilian Weinberger and Yoav Artzi published it at ICLR 2020. Higher is better. The raw scores lie in [−1,1][-1, 1], and in practice in a narrow band near the top; a rescaling with a baseline spreads them out. The score is computed per sentence pair, and a system score is the mean over the test set. The computation from the embeddings is exact; that the score agrees with human judgments is a measurement.

In plain words

BLEU and ROUGE count words and n-grams that occur in both texts. They give no credit when the candidate says "the economy grew" and the reference says "the economy expanded".

BERTScore gives each word a vector that depends on the word and on the words around it. Similar meanings give vectors that point in similar directions. For each word of the reference, find the candidate word that is closest in meaning, and take how close it is. The mean over the reference words tells how much of the reference the candidate covers. Do the same the other way round to see how much of the candidate is supported by the reference.

Rare words carry more meaning than words like "the". An optional weight gives each token its idf, so that matching a rare word counts more.

The problem

The input is a reference with token embeddings x1,…,xnx_1, \ldots, x_n and a candidate with token embeddings x^1,…,x^m\hat x_1, \ldots, \hat x_m, all in Rd\mathbb{R}^d, and optional token weights. Without weights (Section 3 of the paper),

RBERT=1n∑i=1nmax⁡jxiTx^j,PBERT=1m∑j=1mmax⁡ixiTx^j,FBERT=2 PBERT⋅RBERTPBERT+RBERT,R_{\mathrm{BERT}} = \frac{1}{n}\sum_{i=1}^{n} \max_{j} x_i^{\mathsf T} \hat x_j, \qquad P_{\mathrm{BERT}} = \frac{1}{m}\sum_{j=1}^{m} \max_{i} x_i^{\mathsf T} \hat x_j, \qquad F_{\mathrm{BERT}} = 2\,\frac{P_{\mathrm{BERT}} \cdot R_{\mathrm{BERT}}}{P_{\mathrm{BERT}} + R_{\mathrm{BERT}}},

where the vectors are normalized to length 1, so that each inner product is a cosine. With importance weights, recall is ∑iidf(xi)max⁡jxiTx^j/∑iidf(xi)\sum_i \mathrm{idf}(x_i) \max_j x_i^{\mathsf T}\hat x_j / \sum_i \mathrm{idf}(x_i), and precision uses the idf of the candidate tokens in the same way. The idf of a word piece ww is computed over the MM references of the test set,

idf(w)=−log⁡1M∑k=1MI[w∈x(k)],\mathrm{idf}(w) = -\log \frac{1}{M}\sum_{k=1}^{M} \mathbb{I}[w \in x^{(k)}],

and the paper applies plus-one smoothing for word pieces that occur in no reference. Baseline rescaling replaces a score ss by (s−b)/(1−b)(s - b)/(1 - b), where bb is the mean score of random sentence pairs.

The algorithm

  1. BERTSCORE(x, x̂, w, ŵ, b) ▷ x: n reference vectors; x̂: m candidate vectors
  2. 1normalize every x_i and every x̂_j to length 1
  3. 2S_ij ← x_i · x̂_j for all i, j ▷ the n by m cosine matrix
  4. 3r_i ← max_j S_ij for each i ▷ best match of each reference token
  5. 4p_j ← max_i S_ij for each j ▷ best match of each candidate token
  6. 5R ← Σ_i w_i r_i / Σ_i w_i
  7. 6P ← Σ_j ŵ_j p_j / Σ_j ŵ_j
  8. 7F ← 2 P R / (P + R)
  9. 8optionally s ← (s - b_s) / (1 - b_s) for s in P, R, F
  10. 9return P, R, F

The embeddings come from one layer of a pretrained network, run on the reference and on the candidate separately. With all weights equal to 1, lines L5 and L6 are plain means. Line L3 and line L4 are the greedy matching: each token takes its best partner, and one token can be the best partner of several tokens on the other side. The paper computes the baseline bb for each model and language from one million random pairs of Common Crawl sentences, and rescales PP, RR and FF in the same way.

Example

Take two reference tokens and three candidate tokens in R2\mathbb{R}^2, with the vectors already given by the network: x1=(1,0)x_1 = (1, 0), x2=(0,2)x_2 = (0, 2), and x^1=(3,0)\hat x_1 = (3, 0), x^2=(0.6,0.8)\hat x_2 = (0.6, 0.8), x^3=(0.8,−0.6)\hat x_3 = (0.8, -0.6). After normalization, the cosine matrix is

x^1\hat x_1 x^2\hat x_2 x^3\hat x_3 best
x1x_1 1 0.6 0.8 1
x2x_2 0 0.8 -0.6 0.8
best 1 0.8 0.8

Recall is (1+0.8)/2=0.9(1 + 0.8)/2 = 0.9, precision is (1+0.8+0.8)/3=0.8667(1 + 0.8 + 0.8)/3 = 0.8667, and F=2⋅0.9⋅0.8667/1.7667=0.8830F = 2 \cdot 0.9 \cdot 0.8667 / 1.7667 = 0.8830. Both x^2\hat x_2 and x^3\hat x_3 take x1x_1 or x2x_2 as their best match, and x^3\hat x_3 matches x1x_1 although x^1\hat x_1 matches x1x_1 better: greedy matching does not use each token once. With idf weights 1 and 3 on the reference tokens, recall becomes (1⋅1+3⋅0.8)/4=0.85(1 \cdot 1 + 3 \cdot 0.8)/4 = 0.85. With a recall baseline of 0.8, the rescaled recall is (0.9−0.8)/0.2=0.5(0.9 - 0.8)/0.2 = 0.5.

Correctness

The following are theorems, with full proofs in the proofs file. After normalization, each entry of SS is the cosine of two tokens, so lines L3 to L7 compute the formulas of the paper exactly, and PP and RR lie in [−1,1][-1, 1]. A candidate equal to the reference scores P=R=F=1P = R = F = 1. The scores do not change when a vector is scaled by a positive number or when the tokens are reordered, and exchanging candidate and reference exchanges PP and RR. Greedy recall is never below the score of the best one-to-one matching, and the two are equal when the best partners are distinct. FF lies between PP and RR when both are positive. Rescaling is an increasing affine map, so it keeps the order of candidates and the correlation with human judgments.

Whether BERTScore measures quality is a question of measurement, not of proof. The paper reports higher correlation with human judgments than BLEU and other metrics on the WMT16 to WMT18 metric tasks and on image captions from COCO 2015, and more robustness on the adversarial paraphrases of PAWS.

Proof: BERTScore computes the defined precision, recall and F1, and greedy matching is never below the best one-to-one matchingfull

Let the reference have token vectors x1,…,xnx_1, \ldots, x_n and the candidate x^1,…,x^m\hat x_1, \ldots, \hat x_m in Rd\mathbb{R}^d, all nonzero, with n,m≥1n, m \ge 1. Let wi>0w_i > 0 and w^j>0\hat w_j > 0 be the weights (all 1 without idf). The definitions of the paper are

R=∑iwimax⁡jcos⁡(xi,x^j)∑iwi,P=∑jw^jmax⁡icos⁡(xi,x^j)∑jw^j,F=2PRP+R.R = \frac{\sum_i w_i \max_j \cos(x_i, \hat x_j)}{\sum_i w_i}, \qquad P = \frac{\sum_j \hat w_j \max_i \cos(x_i, \hat x_j)}{\sum_j \hat w_j}, \qquad F = \frac{2PR}{P + R}.

Lemma 1. After line L1, SijS_{ij} of line L2 equals cos⁡(xi,x^j)\cos(x_i, \hat x_j).

Proof. Line L1 sets ui=xi/∥xi∥u_i = x_i / \|x_i\| and vj=x^j/∥x^j∥v_j = \hat x_j / \|\hat x_j\|. Then ui⋅vj=(xi⋅x^j)/(∥xi∥∥x^j∥)=cos⁡(xi,x^j)u_i \cdot v_j = (x_i \cdot \hat x_j) / (\|x_i\| \|\hat x_j\|) = \cos(x_i, \hat x_j). □\square

Theorem 1 (the output is the definition). Lines L3 to L7 return PP, RR and FF as defined, and −1≤P,R≤1-1 \le P, R \le 1.

Proof. By Lemma 1, ri=max⁡jSijr_i = \max_j S_{ij} of line L3 is max⁡jcos⁡(xi,x^j)\max_j \cos(x_i, \hat x_j), and pjp_j of line L4 is max⁡icos⁡(xi,x^j)\max_i \cos(x_i, \hat x_j). Lines L5 and L6 are the weighted means of the definition, and line L7 is the formula for FF. A cosine is in [−1,1][-1, 1] by the Cauchy-Schwarz inequality, and a weighted mean with positive weights of numbers in [−1,1][-1, 1] is in [−1,1][-1, 1]. □\square

Theorem 2 (identity). If the candidate is the reference, then P=R=F=1P = R = F = 1.

Proof. For each ii, max⁡jcos⁡(xi,xj)≥cos⁡(xi,xi)=1\max_j \cos(x_i, x_j) \ge \cos(x_i, x_i) = 1, and no cosine is above 1, so ri=1r_i = 1. In the same way pj=1p_j = 1. Then R=P=1R = P = 1 and F=2/2=1F = 2/2 = 1. □\square

Theorem 3 (invariances). PP, RR and FF do not change if a token vector is multiplied by a positive number, or if the tokens of either side are permuted together with their weights. Exchanging the reference and the candidate (with their weights) exchanges PP and RR and keeps FF.

Proof. The cosine does not change when a vector is scaled by c>0c > 0. A permutation reorders the terms of the sums and the sets over which the maxima are taken, and neither changes the value. Exchanging the two sides turns the formula for RR into the formula for PP and back, and FF is symmetric in PP and RR. □\square

Theorem 4 (greedy and one-to-one matching). Let n≤mn \le m and let σ\sigma be any injective map from {1,…,n}\{1, \ldots, n\} to {1,…,m}\{1, \ldots, m\}. Then R≥∑iwicos⁡(xi,x^σ(i))∑iwiR \ge \frac{\sum_i w_i \cos(x_i, \hat x_{\sigma(i)})}{\sum_i w_i}. Equality holds for the best σ\sigma when the maxima arg⁡max⁡jcos⁡(xi,x^j)\arg\max_j \cos(x_i, \hat x_j) can be chosen pairwise distinct.

Proof. For each ii, max⁡jcos⁡(xi,x^j)≥cos⁡(xi,x^σ(i))\max_j \cos(x_i, \hat x_j) \ge \cos(x_i, \hat x_{\sigma(i)}). Multiply by wi>0w_i > 0, add over ii and divide by ∑iwi\sum_i w_i. If the maxima jij_i are distinct, the map σ(i)=ji\sigma(i) = j_i is injective and reaches the bound, so it is the best one-to-one matching. □\square

Theorem 5 (F lies between P and R). If P>0P > 0 and R>0R > 0, then min⁡(P,R)≤F≤P+R2≤max⁡(P,R)\min(P, R) \le F \le \frac{P + R}{2} \le \max(P, R).

Proof. FF is the harmonic mean of PP and RR. Write a=min⁡(P,R)a = \min(P, R) and b=max⁡(P,R)b = \max(P, R). Then F−a=a(b−a)/(a+b)≥0F - a = a(b - a)/(a + b) \ge 0, and a+b2−F=(a+b)2−4ab2(a+b)=(b−a)22(a+b)≥0\frac{a + b}{2} - F = \frac{(a + b)^2 - 4ab}{2(a + b)} = \frac{(b - a)^2}{2(a + b)} \ge 0. □\square

Theorem 6 (rescaling keeps the order). For a baseline b<1b < 1, the map s↦(s−b)/(1−b)s \mapsto (s - b)/(1 - b) is strictly increasing, maps bb to 0 and 1 to 1. So two candidates scored against the same reference keep their order, and the correlation with human scores at the system level or the segment level by a rank statistic does not change.

Proof. The map is affine with slope 1/(1−b)>01/(1 - b) > 0. The two values follow by substitution. ■\blacksquare

Remark (cost). Line L1 takes O((n+m)d)O((n + m)d) time, line L2 takes O(nmd)O(nmd) time and O(nm)O(nm) space, and lines L3 to L7 take O(nm)O(nm) time. The network that makes the vectors costs much more and is outside the algorithm.

Complexity

Line L1 takes O((n+m)d)O((n + m)d) time. Line L2 is a matrix product, with O(nmd)O(nmd) time and O(nm)O(nm) space. Lines L3 to L7 read the matrix once, in O(nm)O(nm) time. So one pair takes O(nmd)O(nmd) time. The idf table takes O(L)O(L) expected time for LL reference tokens in total. In practice the forward pass of the network costs far more than the matching: for a transformer with ℓ\ell layers, it is about O(ℓ(n2d+nd2))O(\ell (n^2 d + n d^2)) per sentence.

Properties

  • Direction and range. Higher is better. Raw scores are in [−1,1][-1, 1]; with BERT-like models most pairs score in a band near the top, which is why the paper adds rescaling.
  • Sentence level. The score is defined for one candidate and one reference. A system score is the mean over the sentences.
  • Soft matching. Paraphrases and synonyms get partial credit, which n-gram metrics do not give.
  • Order is seen only through the embeddings. The matching itself ignores token order. Contextual embeddings encode some of it, so a shuffled candidate gets a lower score, but not as low as with n-gram metrics.
  • Depends on the model. Scores from different networks, layers or versions are not comparable. The paper selects the layer for each model on WMT16 data.
  • Not symmetric in P and R. Recall measures coverage of the reference, and precision measures support of the candidate.

Variants and improvements

  • One-to-one matching. Appendix C of the paper compares greedy matching with the best one-to-one (optimal transport) matching, as in word mover's distance and MoverScore. Greedy matching is faster and needs no solver for the assignment problem.
  • Idf weights. The weights of the problem section. The paper treats them as optional.
  • Multilingual models. The same algorithm with a multilingual encoder scores texts in other languages.
  • MaxSim in retrieval. ColBERT scores a document for a query with the same sum of maximum similarities over the query tokens, which is the unnormalized recall.
  • Trained metrics. COMET and BLEURT train a network on human judgments instead of using a fixed similarity.

When to use it

Use BERTScore to compare generation systems where paraphrases are common, such as summarization, captioning and translation, next to an n-gram metric such as ROUGE or BLEU. Report the model, the layer, the use of idf, the rescaling and the package version, because each changes the numbers. Do not use it to compare scores computed with different models. For a check of factual consistency or of fluency it is not enough: a candidate with a wrong number or a negation can still score high.

Pitfalls

  • Unnormalized vectors. The inner product of raw vectors is not a cosine. Line L1 is required.
  • Narrow range. Raw scores of 0.85 and 0.90 can be far apart in quality. Compare rescaled scores, or compare systems on the same data.
  • Special tokens. Tokens such as [CLS] and [SEP] are in every sentence and match each other perfectly. Decide whether they take part in the matching, and say so.
  • Idf from the test set. The idf weights are computed from the references being scored, so they change with the test set.
  • Division by zero. If P+R=0P + R = 0, FF is undefined. The code returns 0.
  • Word pieces, not words. The tokens are the pieces of the tokenizer of the model, such as WordPiece, so a long word adds several tokens to the means.

Implementations

The code takes the token embeddings of the network as given (an n×dn \times d and an m×dm \times d list of vectors) and implements the normalization, the greedy matching, the idf weights and the rescaling; it does not run or train a network.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bertscore.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bertscore/. The authors are listed in prov/T124HA.jsonl.

"""BERTScore (Zhang, Kishore, Wu, Weinberger and Artzi, ICLR 2020).

The code takes the contextual token embeddings of the network as given: a
reference is a list of n vectors of width d, and a candidate is a list of m
vectors of width d. It does not run or train a network. It implements the
greedy matching by cosine similarity, the optional idf weights and the
baseline rescaling.
"""

import math
from typing import Dict, Hashable, List, Optional, Sequence, Tuple

Vec = Sequence[float]


def normalize(v: Vec) -> List[float]:
    """Return v divided by its Euclidean length. A zero vector stays zero."""
    n = math.sqrt(sum(a * a for a in v))
    if n == 0.0:
        return [0.0 for _ in v]
    return [a / n for a in v]


def similarity_matrix(ref: Sequence[Vec], cand: Sequence[Vec]) -> List[List[float]]:
    """S[i][j] = cosine of reference token i and candidate token j (n x m)."""
    x = [normalize(v) for v in ref]
    y = [normalize(v) for v in cand]
    return [[sum(a * b for a, b in zip(u, v)) for v in y] for u in x]


def idf_from_references(references: Sequence[Sequence[Hashable]]) -> Dict[Hashable, float]:
    """idf(w) = log((M + 1) / (df(w) + 1)) over M reference token lists.

    This is one way to apply the plus-one smoothing that the paper names; a
    token not seen in any reference gets log(M + 1) (see unknown_idf).
    """
    m = len(references)
    df: Dict[Hashable, int] = {}
    for toks in references:
        for w in set(toks):
            df[w] = df.get(w, 0) + 1
    return {w: math.log((m + 1) / (c + 1)) for w, c in df.items()}


def unknown_idf(num_references: int) -> float:
    """The idf of a token that occurs in no reference."""
    return math.log(num_references + 1)


def weighted_mean(values: Sequence[float], weights: Optional[Sequence[float]]) -> float:
    if not values:
        return 0.0
    if weights is None:
        return sum(values) / len(values)
    total = sum(weights)
    if total == 0.0:
        return 0.0
    return sum(w * v for w, v in zip(weights, values)) / total


def bertscore(
    ref: Sequence[Vec],
    cand: Sequence[Vec],
    ref_weights: Optional[Sequence[float]] = None,
    cand_weights: Optional[Sequence[float]] = None,
) -> Tuple[float, float, float]:
    """Return (P, R, F) for one candidate and one reference.

    ref_weights and cand_weights are the idf weights of the tokens, or None
    for equal weights.
    """
    n, m = len(ref), len(cand)
    if n == 0 or m == 0:
        return 0.0, 0.0, 0.0
    x = [normalize(v) for v in ref]  # @line L1
    y = [normalize(v) for v in cand]
    s = [[sum(a * b for a, b in zip(u, v)) for v in y] for u in x]  # @line L2
    best_for_ref = [max(s[i][j] for j in range(m)) for i in range(n)]  # @line L3
    best_for_cand = [max(s[i][j] for i in range(n)) for j in range(m)]  # @line L4
    r = weighted_mean(best_for_ref, ref_weights)  # @line L5
    p = weighted_mean(best_for_cand, cand_weights)  # @line L6
    f = 2 * p * r / (p + r) if p + r != 0.0 else 0.0  # @line L7
    return p, r, f  # @line L9


def rescale(score: float, baseline: float) -> float:
    """Baseline rescaling (score - b) / (1 - b), for a baseline b < 1."""
    return (score - baseline) / (1.0 - baseline)  # @line L8


def bertscore_rescaled(
    ref: Sequence[Vec],
    cand: Sequence[Vec],
    baselines: Tuple[float, float, float],
    ref_weights: Optional[Sequence[float]] = None,
    cand_weights: Optional[Sequence[float]] = None,
) -> Tuple[float, float, float]:
    """(P, R, F), each rescaled with its own baseline (b_P, b_R, b_F)."""
    p, r, f = bertscore(ref, cand, ref_weights, cand_weights)
    bp, br, bf = baselines
    return rescale(p, bp), rescale(r, br), rescale(f, bf)
test_bertscore.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bertscore/. The authors are listed in prov/T124HA.jsonl.

import math
import random
from itertools import permutations

from bertscore import (
    bertscore,
    bertscore_rescaled,
    idf_from_references,
    normalize,
    rescale,
    similarity_matrix,
    unknown_idf,
)

TOL = 1e-12


def rand_vecs(rng, k, d):
    return [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(k)]


def test_page_example():
    ref = [[1.0, 0.0], [0.0, 2.0]]
    cand = [[3.0, 0.0], [0.6, 0.8], [0.8, -0.6]]
    s = similarity_matrix(ref, cand)
    want = [[1.0, 0.6, 0.8], [0.0, 0.8, -0.6]]
    assert all(abs(s[i][j] - want[i][j]) < TOL for i in range(2) for j in range(3))
    p, r, f = bertscore(ref, cand)
    assert abs(r - 0.9) < TOL
    assert abs(p - 2.6 / 3) < TOL
    assert abs(f - 2 * 0.9 * (2.6 / 3) / (0.9 + 2.6 / 3)) < TOL
    assert abs(f - 0.883019) < 1e-6
    # With idf weights 1 and 3 on the reference tokens, recall is (1 + 3 * 0.8) / 4.
    _, rw, _ = bertscore(ref, cand, ref_weights=[1.0, 3.0])
    assert abs(rw - 0.85) < TOL


def direct(ref, cand, wr=None, wc=None):
    """Recompute P, R and F from the definition, without the module's matrix code."""
    def cos(u, v):
        return sum(a * b for a, b in zip(u, v)) / (math.hypot(*u) * math.hypot(*v))
    wr = wr or [1.0] * len(ref)
    wc = wc or [1.0] * len(cand)
    r = sum(w * max(cos(u, v) for v in cand) for w, u in zip(wr, ref)) / sum(wr)
    p = sum(w * max(cos(u, v) for u in ref) for w, v in zip(wc, cand)) / sum(wc)
    return p, r, 2 * p * r / (p + r)


def test_against_direct_formula():
    rng = random.Random(2020)
    for _ in range(300):
        d = rng.randint(1, 6)
        ref = rand_vecs(rng, rng.randint(1, 6), d)
        cand = rand_vecs(rng, rng.randint(1, 6), d)
        wr = [rng.uniform(0.1, 3.0) for _ in ref]
        wc = [rng.uniform(0.1, 3.0) for _ in cand]
        got = bertscore(ref, cand, wr, wc)
        want = direct(ref, cand, wr, wc)
        if abs(want[0] + want[1]) < 1e-9:
            continue
        assert all(abs(a - b) < 1e-9 for a, b in zip(got, want))
        assert all(-1 - 1e-12 <= x <= 1 + 1e-12 for x in got[:2])


def test_identical_and_invariances():
    rng = random.Random(7)
    for _ in range(100):
        ref = rand_vecs(rng, rng.randint(1, 6), 4)
        p, r, f = bertscore(ref, ref)
        assert abs(p - 1) < 1e-12 and abs(r - 1) < 1e-12 and abs(f - 1) < 1e-12
        cand = rand_vecs(rng, rng.randint(1, 6), 4)
        base = bertscore(ref, cand)
        # Scaling a vector by a positive number changes nothing.
        scaled = [[3.5 * a for a in v] for v in cand]
        assert all(abs(a - b) < 1e-12 for a, b in zip(bertscore(ref, scaled), base))
        # The order of the tokens does not matter once the embeddings are fixed.
        shuffled = cand[:]
        rng.shuffle(shuffled)
        assert all(abs(a - b) < 1e-12 for a, b in zip(bertscore(ref, shuffled), base))
        # Swapping the roles swaps precision and recall.
        p2, r2, f2 = bertscore(cand, ref)
        assert abs(p2 - base[1]) < 1e-12 and abs(r2 - base[0]) < 1e-12


def test_greedy_at_least_optimal_assignment():
    # Greedy matching lets many tokens match one token, so it is never below
    # the best one-to-one matching (Appendix C of the paper compares the two).
    rng = random.Random(11)
    for _ in range(200):
        n = rng.randint(1, 4)
        m = rng.randint(n, 6)
        ref = rand_vecs(rng, n, 3)
        cand = rand_vecs(rng, m, 3)
        s = similarity_matrix(ref, cand)
        best = max(sum(s[i][perm[i]] for i in range(n)) for perm in permutations(range(m), n)) / n
        _, r, _ = bertscore(ref, cand)
        assert r >= best - 1e-12
        # Equality when every reference token has a different best match.
        argmax = [max(range(m), key=lambda j: s[i][j]) for i in range(n)]
        if len(set(argmax)) == n:
            assert abs(r - best) < 1e-12


def test_f_between_p_and_r():
    rng = random.Random(3)
    for _ in range(200):
        ref = [[abs(x) for x in v] for v in rand_vecs(rng, rng.randint(1, 5), 3)]
        cand = [[abs(x) for x in v] for v in rand_vecs(rng, rng.randint(1, 5), 3)]
        p, r, f = bertscore(ref, cand)
        assert min(p, r) - 1e-12 <= f <= max(p, r) + 1e-12
        assert f <= (p + r) / 2 + 1e-12


def test_idf():
    refs = [["the", "cat", "sat"], ["the", "dog"], ["a", "cat", "cat"]]
    idf = idf_from_references(refs)
    assert abs(idf["the"] - math.log(4 / 3)) < TOL
    assert abs(idf["cat"] - math.log(4 / 3)) < TOL
    assert abs(idf["dog"] - math.log(2)) < TOL
    assert abs(unknown_idf(3) - math.log(4)) < TOL
    # Equal weights give the unweighted score.
    rng = random.Random(5)
    ref = rand_vecs(rng, 4, 3)
    cand = rand_vecs(rng, 5, 3)
    a = bertscore(ref, cand)
    b = bertscore(ref, cand, [2.0] * 4, [2.0] * 5)
    assert all(abs(x - y) < 1e-12 for x, y in zip(a, b))


def test_rescale():
    assert abs(rescale(0.9, 0.8) - 0.5) < TOL
    assert rescale(1.0, 0.83) == 1.0
    assert abs(rescale(0.83, 0.83)) < TOL
    # Rescaling is increasing, so it keeps the ranking of candidates.
    rng = random.Random(13)
    ref = rand_vecs(rng, 4, 3)
    cands = [rand_vecs(rng, 4, 3) for _ in range(20)]
    raw = [bertscore(ref, c)[1] for c in cands]
    res = [bertscore_rescaled(ref, c, (0.8, 0.82, 0.81))[1] for c in cands]
    assert sorted(range(20), key=lambda i: raw[i]) == sorted(range(20), key=lambda i: res[i])


def test_edge_cases():
    assert bertscore([], [[1.0]]) == (0.0, 0.0, 0.0)
    assert normalize([0.0, 0.0]) == [0.0, 0.0]
    # Orthogonal tokens: P = R = 0 and F is set to 0.
    assert bertscore([[1.0, 0.0]], [[0.0, 1.0]]) == (0.0, 0.0, 0.0)

History

Earlier metrics for text generation compared surface forms: BLEU (2002) and ROUGE (2004) count n-grams, and METEOR (2005) adds stems and synonyms from WordNet. Metrics based on word embeddings, such as the word mover's distance (2015) and the greedy matching of word vectors used in dialogue evaluation, used static vectors. BERTScore used the contextual vectors of BERT and its successors, which had appeared in 2018 and 2019. The paper tested 12 models; for English it recommended a large RoBERTa model. Trained metrics such as BLEURT (2020) and COMET (2020) followed in the same year.

References

  1. Tianyi Zhang, Varsha Kishore, Felix Wu, Kilian Q. Weinberger and Yoav Artzi, BERTScore, Evaluating Text Generation with BERT, ICLR 2020, Section 3 (token representation, cosine similarity, the recall, precision and F1 formulas, importance weighting by idf, baseline rescaling), Section 4 and Section 5 (the experiments on WMT16 to WMT18, COCO 2015 and PAWS), Appendix C (greedy and optimal matching)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example