Sub topic 12
BERTScore: greedy matching of token embeddings
This chapter assumes you know precision, recall, and F1, and that you have a rough idea of what a transformer encoder produces. The previous chapter covered contextual embeddings and cosine similarity. Here we use them to build a metric.
The idea in one paragraph
BLEU and ROUGE count exact string matches, so "sitting" and "sat" count as a miss. BERTScore (Zhang et al., 2020) replaces the exact-match test with a soft test. It embeds every token of the candidate and of the reference with a pretrained encoder, then asks how similar each token is to its best partner in the other sentence. The result is a precision, a recall, and an F1 that vary smoothly with meaning instead of jumping between 0 and 1.
Step 1: embed both sentences
The candidate x has tokens x_1 ... x_m. The reference y has tokens y_1 ... y_k. Each sentence goes through the encoder separately, and you take the hidden states of one chosen layer. Two details matter:
- The vectors are contextual. The vector for "bank" in "river bank" differs from the one in "bank loan". Matching happens between context-aware vectors, not dictionary entries.
- Tokens are subword pieces. A rare word may split into several WordPiece or BPE tokens, and each piece gets its own vector. The special
[CLS]and[SEP]tokens are given zero weight by the library, so they do not affect the score.
Step 2: build the similarity matrix
Normalize every vector to unit length. The cosine similarity between two tokens is then a plain dot product. Compare all candidate tokens against all reference tokens and you get an m × k matrix. Row i holds how similar candidate token i is to every reference token.
Step 3: greedy matching
Each token picks its single best partner. There is no global assignment.
Precision = (1/m) * sum over candidate tokens x_i of max over reference tokens y_j of sim(x_i, y_j)
Recall = (1/k) * sum over reference tokens y_j of max over candidate tokens x_i of sim(x_i, y_j)
F1 = 2 * Precision * Recall / (Precision + Recall)In matrix terms, precision is the mean of the row maxima and recall is the mean of the column maxima. The roles mirror the overlap metrics you already know. Precision asks whether the candidate's tokens are supported by the reference. Recall asks whether the reference's tokens are covered by the candidate.
Worked example with toy vectors
Real embeddings have hundreds of dimensions. To follow the arithmetic, use 2-D unit vectors. Candidate tokens are "cat", "sat", and "mat". Reference tokens are "cat", "sitting", and "rug".
| Vector | cat | sat | mat |
|---|---|---|---|
| Candidate | (1, 0) | (0, 1) | (0.8, 0.6) |
| Vector | cat | sitting | rug |
|---|---|---|---|
| Reference | (1, 0) | (0.6, 0.8) | (0.8, 0.6) |
The cosine similarities are:
| Candidate \ Reference | cat | sitting | rug |
|---|---|---|---|
| cat | 1.00 | 0.60 | 0.80 |
| sat | 0.00 | 0.80 | 0.60 |
| mat | 0.80 | 0.96 | 1.00 |
Row maxima are 1.00, 0.80, and 1.00, so precision is 2.80 / 3 = 0.933. Column maxima are 1.00, 0.96, and 1.00, so recall is 2.96 / 3 = 0.987. F1 is about 0.959.
Look at the "sitting" column. Its best match is "mat" (0.96), not "sat" (0.80). Greedy matching is not one-to-one. "Mat" is used as the best partner for two reference tokens, and nothing stops that.
The same computation in NumPy
This function takes two matrices of token embeddings, one row per token. It runs as shown and reproduces the table above.
import numpy as np
def bertscore_from_embeddings(cand_emb, ref_emb):
cand = cand_emb / np.linalg.norm(cand_emb, axis=1, keepdims=True)
ref = ref_emb / np.linalg.norm(ref_emb, axis=1, keepdims=True)
sim = cand @ ref.T # shape (m, k)
precision = sim.max(axis=1).mean() # best reference match per candidate token
recall = sim.max(axis=0).mean() # best candidate match per reference token
f1 = 2 * precision * recall / (precision + recall)
return precision, recall, f1, sim
cand_emb = np.array([[1.0, 0.0], [0.0, 1.0], [0.8, 0.6]]) # cat, sat, mat
ref_emb = np.array([[1.0, 0.0], [0.6, 0.8], [0.8, 0.6]]) # cat, sitting, rug
p, r, f1, sim = bertscore_from_embeddings(cand_emb, ref_emb)
print(np.round(sim, 2))
print(round(p, 3), round(r, 3), round(f1, 3)) # 0.933 0.987 0.959The library does the same thing, with a real encoder supplying the embeddings and batching handled for you.
Using the `bert_score` package
from bert_score import score
candidates = ["The cat sat on the mat."]
references = ["A cat was sitting on the rug."]
P, R, F1 = score(candidates, references, lang="en", verbose=False)
print(P.item(), R.item(), F1.item())Practical points:
- Output shape.
scorereturns three tensors with one value per sentence pair. Average them yourself for a corpus-level number. - Default model. Setting
lang="en"selectsroberta-largeat layer 17. Other languages default to multilingual models. You can setmodel_typeandnum_layersexplicitly. - Layer choice. The paper picks the layer by correlation with human judgments on a validation set. Final layers are usually worse than a middle-to-late layer.
- Reuse the model. Creating a
BERTScorerobject once and calling itsscoremethod avoids reloading the encoder on every call. - Length limit. Inputs are truncated at the encoder's maximum length, normally 512 tokens. Long documents lose their tail silently.
How it differs from BLEU and ROUGE
| Property | BLEU | ROUGE-N | BERTScore |
|---|---|---|---|
| Unit of match | Exact n-gram | Exact n-gram | Single subword token |
| Match value | 0 or 1 | 0 or 1 | Cosine, roughly 0 to 1 |
| Word order | Captured by n-grams | Captured by n-grams and LCS | Only through context in the vectors |
| Needs a model | No | No | Yes, a GPU helps |
| Deterministic across setups | Yes, with SacreBLEU | Yes | Only for a fixed model and layer |
BERTScore has no explicit n-gram structure. Order enters only indirectly, because a contextual vector reflects the words around the token. It also has no brevity penalty. Recall plays that role, because a short candidate leaves reference tokens without a good partner.
Failure modes and gotchas
- Many-to-one matching. Because each token takes its own maximum, one good reference token can absorb credit for many candidate tokens. A candidate that repeats a single correct word many times is not clipped the way BLEU clips it. Repetition is cheap, though the repeated token still has to match the reference token well.
- Bunched scores. Contextual embeddings tend to occupy a narrow cone in vector space, so even unrelated tokens have a similarity well above 0. Raw scores often fall in a band such as 0.80 to 0.95, which makes differences look tiny. Baseline rescaling, covered in a later chapter, addresses this.
- Opposites look close. Antonyms such as "good" and "bad" occur in similar contexts, so their vectors can be near each other. "The film was good" and "The film was bad" may score high. Negation and numbers are weak spots.
- Subword effects. A long word split into five pieces contributes five matches to the average, while a short word contributes one. Token counts, not word counts, set the weights unless you use IDF.
- Not symmetric in use. Precision and recall swap if you swap the candidate and the reference. Check that you pass them in the order the function expects, because the F1 is symmetric but its two parts are not.
- Cost. Every score needs two forward passes through a large encoder. For large evaluation sets this is much slower than counting n-grams.
Exercise
A candidate has 2 tokens and a reference has 3. The cosine similarity matrix (rows are candidate tokens, columns are reference tokens) is [[0.9, 0.3, 0.2], [0.4, 0.5, 0.8]]. Compute BERTScore precision, recall, and F1 under greedy matching. Which reference token is the weakest match?
Show answer
Row maxima are 0.9 and 0.8, so precision = 1.7 / 2 = 0.85. Column maxima are 0.9, 0.5, and 0.8, so recall = 2.2 / 3 ≈ 0.733. F1 = 2 × 0.85 × 0.733 / (0.85 + 0.733) ≈ 0.787. The weakest reference token is the second column (best match 0.5), because no candidate token resembles it.
Exercise
Explain why greedy matching can give a high recall to a candidate that does not cover all of the reference's content, and name one remedy the original method does not use.
Show answer
Each reference token takes its best partner independently, so a single candidate token can serve as the best match for several reference tokens. The candidate then looks like it covers them all. A one-to-one assignment, such as an optimal bipartite matching, would let each candidate token be used once.