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
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 and a candidate with token embeddings , all in , and optional token weights. Without weights (Section 3 of the paper),
where the vectors are normalized to length 1, so that each inner product is a cosine. With importance weights, recall is , and precision uses the idf of the candidate tokens in the same way. The idf of a word piece is computed over the references of the test set,
and the paper applies plus-one smoothing for word pieces that occur in no reference. Baseline rescaling replaces a score by , where is the mean score of random sentence pairs.
The algorithm
BERTSCORE(x, x̂, w, ŵ, b) ▷ x: n reference vectors; x̂: m candidate vectors- 1
normalize every x_i and every x̂_j to length 1 - 2
S_ij ← x_i · x̂_j for all i, j ▷ the n by m cosine matrix - 3
r_i ← max_j S_ij for each i ▷ best match of each reference token - 4
p_j ← max_i S_ij for each j ▷ best match of each candidate token - 5
R ← Σ_i w_i r_i / Σ_i w_i - 6
P ← Σ_j ŵ_j p_j / Σ_j ŵ_j - 7
F ← 2 P R / (P + R) - 8
optionally s ← (s - b_s) / (1 - b_s) for s in P, R, F - 9
return 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 for each model and language from one million random pairs of Common Crawl sentences, and rescales , and in the same way.
Example
Take two reference tokens and three candidate tokens in , with the vectors already given by the network: , , and , , . After normalization, the cosine matrix is
| best | ||||
|---|---|---|---|---|
| 1 | 0.6 | 0.8 | 1 | |
| 0 | 0.8 | -0.6 | 0.8 | |
| best | 1 | 0.8 | 0.8 |
Recall is , precision is , and . Both and take or as their best match, and matches although matches better: greedy matching does not use each token once. With idf weights 1 and 3 on the reference tokens, recall becomes . With a recall baseline of 0.8, the rescaled recall is .
Correctness
The following are theorems, with full proofs in the proofs file. After normalization, each entry of is the cosine of two tokens, so lines L3 to L7 compute the formulas of the paper exactly, and and lie in . A candidate equal to the reference scores . 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 and . 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. lies between and 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 and the candidate in , all nonzero, with . Let and be the weights (all 1 without idf). The definitions of the paper are
Lemma 1. After line L1, of line L2 equals .
Proof. Line L1 sets and . Then .
Theorem 1 (the output is the definition). Lines L3 to L7 return , and as defined, and .
Proof. By Lemma 1, of line L3 is , and of line L4 is . Lines L5 and L6 are the weighted means of the definition, and line L7 is the formula for . A cosine is in by the Cauchy-Schwarz inequality, and a weighted mean with positive weights of numbers in is in .
Theorem 2 (identity). If the candidate is the reference, then .
Proof. For each , , and no cosine is above 1, so . In the same way . Then and .
Theorem 3 (invariances). , and 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 and and keeps .
Proof. The cosine does not change when a vector is scaled by . 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 into the formula for and back, and is symmetric in and .
Theorem 4 (greedy and one-to-one matching). Let and let be any injective map from to . Then . Equality holds for the best when the maxima can be chosen pairwise distinct.
Proof. For each , . Multiply by , add over and divide by . If the maxima are distinct, the map is injective and reaches the bound, so it is the best one-to-one matching.
Theorem 5 (F lies between P and R). If and , then .
Proof. is the harmonic mean of and . Write and . Then , and .
Theorem 6 (rescaling keeps the order). For a baseline , the map is strictly increasing, maps 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 . The two values follow by substitution.
Remark (cost). Line L1 takes time, line L2 takes time and space, and lines L3 to L7 take time. The network that makes the vectors costs much more and is outside the algorithm.
Complexity
Line L1 takes time. Line L2 is a matrix product, with time and space. Lines L3 to L7 read the matrix once, in time. So one pair takes time. The idf table takes expected time for reference tokens in total. In practice the forward pass of the network costs far more than the matching: for a transformer with layers, it is about per sentence.
Properties
- Direction and range. Higher is better. Raw scores are in ; 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 , 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 and an 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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag T124HA Edit this page History Report an error Markdown