Module: L2-M03 · Duration: ~90 min (estimate, including the independent exercise) · Previous: L01 · Next: L03
1. Introduction
When a correct answer can be phrased many ways, the exact match of L01 wrongly rejects almost everything. The familiar fix is a similarity metric: a score from 0 to 1 for how "alike" an answer is to a reference answer, then a threshold. OpenAI's grader page lists several metrics of this kind, such as fuzzy_match, bleu, rouge_l and cosine [R2].
This lesson teaches you to compute a few metrics by hand, then measure whether the similarity score agrees with the right/wrong decision made by a human. The result in the lab is uncomfortable: an answer with one wrong number can score higher than a completely correct rephrasing. The output is a table of cases where similarity and correctness disagree, plus an acceptance rule that pairs the similarity score with a deterministic check.
2. Learning objectives
- Compute token F1 and ROUGE-L for a pair of sentences by hand and with
lab.similarity, and explain which metric notices word order. Practice: §8.3. - Point out three kinds of cases where similarity and correctness disagree (wrong number but alike, correct but different, flipped conclusion but alike). Practice: §8.2 parts A and D.
- Sweep thresholds, read the precision and recall table and conclude whether or not an acceptable threshold exists. Practice: §8.2 parts B and C.
- Explain why stripping Vietnamese diacritics breaks a word-based metric, and check it with code. Practice: §8.3 (last line) and
test_diacritics_change_the_tokens_not_just_the_look. - Design an acceptance rule that pairs similarity with a deterministic check and state which kinds of error still get through. Practice: §9.
3. Prerequisites and tools
- L2-M03-L01: the number-finding function, precision and recall of a metric against human labels.
- L2-M01-L03: code-based graders and their blind spots.
- The code lab
code-labs/l2-m03(self-contained). No need to know embeddings; §5.4 only talks about them.
4. Concepts
4.1 What a similarity metric measures
Every similarity metric answers one narrow question: how many components do two strings share? What counts as a component differs from metric to metric.
| Metric (in the lab) | Components compared | Notices order? | Notes |
|---|---|---|---|
token_f1 |
Words (a multiset: repeated words are counted) | No | Implemented in the lab |
rouge_l |
The longest common subsequence (LCS) of words | Yes, gaps allowed | Anthropic describes ROUGE-L for summarisation [R1] |
char_trigram_dice |
The set of 3-character groups | Almost not | Implemented in the lab; tolerates typos |
Anthropic describes ROUGE-L as measuring "the length of the longest common subsequence between the candidate and reference summaries" [R1]. BLEU is a method for evaluating machine translation [R3] and ROUGE is a package for evaluating summaries [R4]; only the title and publication details of the two original papers were read, not the abstract or the content, so this lesson claims nothing about how they are computed or how well they correlate. BERTScore, as its authors describe it, compares each token using contextual embeddings instead of exact matching [R5] (only the abstract was read). All three were proposed for translation, summarisation and image captioning, where "like the reference" is a reasonable proxy for "good"; an assistant that answers "right or wrong" is not in that group.
4.2 Token F1 and ROUGE-L by hand
Take the reference Đúng rồi, 6 nhân 4 bằng 24. (7 words: đúng, rồi, 6, nhân, 4, bằng, 24) and the system sentence Chính xác, tích của 6 và 4 là 24. (9 words). They share 3 words: 6, 4 and 24. The word-level precision is 3/9 (the system sentence's words that are in the reference), the recall is 3/7 (the reference's words that the system sentence states). F1 is the harmonic mean 2PR / (P + R) of the two numbers, which simplifies to 2 × 3 / (9 + 7) = 3/8 = 0.375. (The word-level precision and recall are only components of F1, different from the precision and recall of a metric against human labels, L01 and §5.1.) The lab gives exactly 3/8 (§8.3) because it uses Fraction, with no rounding error.
The second sentence Đúng rồi, 6 nhân 4 bằng 26. has 7 words and shares 6 words with the reference: F1 = 2 × 6 / (7 + 7) = 6/7 ≈ 0.857. The wrong-number sentence scores 0.857 and the correct rephrasing scores 0.375. ROUGE-L matches token F1 on these two sentences because the shared words appear in the same order; they only separate when the order changes. With 999 là số lớn nhất có ba chữ số. against Số lớn nhất có ba chữ số là 999. token F1 is 1 (exactly the same set of words) while ROUGE-L is 7/9 (the longest common sequence is 7 words in the right order, which in this example happen to be contiguous). A similarity of 1.000 only means "the same bag of words".
4.3 Similarity is not correctness
There are three kinds of cases where the similarity score and the human label disagree. The lab's dataset (data/sim_pairs.jsonl, 48 fictional pairs, 32 correct answers and 16 wrong) builds all three:
- One number wrong but still alike (
wrong_number): "Đúng rồi, 6 nhân 4 bằng 26." - Flipped conclusion but still alike (
flipped_or_negated): "Sai rồi, 6 nhân 4 bằng 24." or "Một giờ không có 60 phút." One word changed or one "không" (not) added flips the meaning but barely changes the score. - Correct but different (
paraphrase,extra_sentence,no_diacritics): a rephrasing, an added encouraging sentence, or typing without diacritics. The score is low although the answer is correct.
The first two kinds are false accepts (fp), the third is a false reject (fn); §5.1 shows that no threshold reduces both.
5. Technical deep dive
5.1 Threshold sweep: no threshold is good
similarity.sweep(pairs, metric, thresholds) accepts a pair when the score ≥ the threshold (inclusive, so a score exactly equal to the threshold is accepted) and returns the confusion matrix with precision and recall at each threshold. The scores are Fraction, the thresholds are Fraction too, so two equal numbers are never pushed apart by floating-point error. With token F1 on the 48 pairs:
| Threshold | tp | fp | fn | tn | precision | recall |
|---|---|---|---|---|---|---|
| 0.5 | 24 | 16 | 8 | 0 | 0.600 | 0.750 |
| 0.7 | 17 | 16 | 15 | 0 | 0.515 | 0.531 |
| 0.8 | 10 | 16 | 22 | 0 | 0.385 | 0.312 |
| 0.9 | 9 | 5 | 23 | 11 | 0.643 | 0.281 |
| 1.0 | 9 | 0 | 23 | 16 | 1.000 | 0.281 |
All 16 wrong answers are accepted at every threshold up to 0.8: they are only one word off or have one "không" added. To stop false accepts you must raise the threshold to 1.0, and recall drops to 0.281: 9 correct answers are accepted, made up of 8 answers identical to the reference plus 1 answer with reordered words. Every threshold either falsely accepts (fp > 0) or falsely rejects heavily. For the other two metrics, the highest recall at fp = 0 is 0.250 (ROUGE-L and char_trigram_dice; demo part C). On a grid of 11 thresholds from 0 to 1 in steps of 0.1, the best overall accuracy (the fraction classified correctly) of all three metrics is only 32/48 = 0.667, the same as accepting everything: no threshold beats a rule that does nothing.
Scope of the conclusion: this is a result on a dataset built to contain the three kinds of cases in §4.3 with 2/3 of the answers correct; a real dataset will differ. What you take away is the way of measuring.
5.2 Vietnamese text with diacritics
Many people type without diacritics on their phones (L2-M02 used this property as one dimension of the coverage matrix). For a word-based metric, moi ban duoc may vien and Mỗi bạn được mấy viên? share no word: token F1 is 0 although the content is the same (test_diacritics_change_the_tokens_not_just_the_look). The no_diacritics version of "Đúng rồi, 6 nhân 4 bằng 24." keeps only the three matching numbers: token F1 3/7 ≈ 0.429.
Stripping diacritics on both sides fixes this case (the score goes to 1) but creates a new error: bàn, bạn and bán all become ban, and the test proves the three are merged. This is a trade-off to record in the metric's documentation, not a bug to patch: stripping diacritics raises recall for people who type without them and lowers the ability to tell apart words with different meanings.
5.3 A deterministic guard next to the similarity score
A pragmatic solution: similarity checks "does it share the topic and phrasing", and a deterministic check covers what similarity cannot see. numbers_preserved(pred, ref) requires the set of numbers in the system sentence to equal the set of numbers in the reference, read by the L01 rules (24,0 equals 24). Results on the 48 pairs (demo part D):
| Kind of pair | Pairs | Pairs passing the guard |
|---|---|---|
| same, paraphrase, no_diacritics | 8 + 8 + 8 | 8 + 8 + 8 |
| wrong_number | 8 | 1 |
| flipped_or_negated | 8 | 8 |
| extra_sentence | 8 | 6 |
The guard catches 7 of the 8 wrong-number answers. The 8th gets through because the reference writes its number in words ("một phần hai bằng hai phần tư", one half equals two quarters), so there is no number to compare. It sees nothing in the 8 flipped-conclusion answers because the numbers do not change, and it wrongly rejects 2 correct answers that add a sentence containing a new number ("Số nhỏ nhất là 100", "cạnh nhân 4"). The minus sign is read (-24 differs from 24). "The sets of numbers are equal" is safer than "contains the right number" but rigid; for a high-risk criterion (L2-M01) a false reject is better than a false accept.
Accept when both agree, and record for each kind of error how it is detected: a wrong number by the guard, a flipped conclusion nobody catches yet (it needs a conclusion check such as verdict_of in L05, or a human). Exercise §9 asks you to find that list.
5.4 Embeddings and BERTScore: what the lab cannot do
The commonly suggested way past the "word matching" limit is to compare embeddings, vectors that represent the meaning of a word or sentence. Anthropic describes the cosine between SBERT (Sentence-BERT) embeddings as a measure suited to checking consistency because "similar questions should yield semantically similar answers, even if the wording varies" [R1]. BERTScore, according to its authors' abstract, correlates with human judgement better than existing metrics on machine translation and image captioning [R5] (the authors' claim; only the abstract was read, not independently checked).
The lab does not implement embeddings (they need a model and a data download, against the offline convention), so you cannot infer anything about their quality from the 48 pairs above. The right test is to run the same sweep and false_accepts on the same labelled pairs with an embedding metric. Embeddings solve the rephrasing case; whether they tell "equals 24" from "equals 26", or "right" from "wrong", is a measurable question, not an assumption.
6. The QA perspective
6.1 When to still use similarity
Similarity is useless only as a measure of right/wrong; for three other jobs it works as a signal, not a verdict: a tripwire (L2-M01-L03) when comparing the output of a new version with the old one on the same cases; consistency across runs (Anthropic uses cosine for this purpose [R1]); and duplicate detection in a dataset (L2-M02-L04 uses Jaccard for that). If you still use it to decide pass: pair it with a deterministic check for facts (§5.3), measure it on labelled pairs before choosing a threshold, and record the kinds of error that still get through in the limitations section of the report (L2-M01-L05).
6.2 Checking a similarity metric before trusting it
- Build a set of labelled pairs following the three kinds in §4.3, a few pairs of each, with labels decided by a human.
- Sweep the threshold and read both precision and recall; a table with only accuracy hides false accepts and false rejects inside each other.
- List the ids of the false accepts at the threshold you plan to use (
false_accepts) and read each answer. - Compare with a trivial baseline. Here "accept everything" reaches 0.667 accuracy and no threshold beats it; a metric that does not beat the baseline has no reason to be used yet.
- Record the sample size and how it was built. 48 pairs, 8 pairs of each kind, show the shape of the problem but not the real false-accept rate: the wrong answers are constructed.
7. Real-world scenarios
Scenario 1 (fictional): "The ROUGE score went up after the prompt change". The HocVui Tutor team changed the prompt and saw the average ROUGE-L rise. When they listed the highest-scoring answers, they found many nearly identical to the reference but with one number changed ("bằng 26" instead of "bằng 24"): the new prompt made the model repeat the structure of the examples more exactly, even when the number was wrong. The score rose because of more alike, not more correct. They added numbers_preserved to the acceptance rule and let similarity serve as a secondary signal.
Scenario 2 (fictional): "The 0.8 threshold". A team set "token F1 ≥ 0.8 passes" because it sounded strict. On the lab's 48 pairs, that threshold gives a precision of 0.385 and a recall of 0.312: 16 of the 26 accepted answers are wrong and 22 of the 32 correct answers are rejected. A threshold that "sounds strict" but is not measured is only a feeling.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l2-m03
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 63 passed
8.2 Run the demo
python -m lab.demo l02
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-03; the two versions give identical output):
A. one reference, a correct paraphrase and a wrong number
reference : Đúng rồi, 6 nhân 4 bằng 24.
paraphrase : Chính xác, tích của 6 và 4 là 24. (correct)
wrong : Đúng rồi, 6 nhân 4 bằng 26. (wrong)
token_f1 paraphrase 0.375 wrong number 0.857
rouge_l paraphrase 0.375 wrong number 0.857
char_trigram_dice paraphrase 0.145 wrong number 0.917
B. token_f1 swept over thresholds, 48 pairs (32 correct)
t=0.5 tp=24 fp=16 fn= 8 tn= 0 precision 0.600 recall 0.750
t=0.7 tp=17 fp=16 fn=15 tn= 0 precision 0.515 recall 0.531
t=0.8 tp=10 fp=16 fn=22 tn= 0 precision 0.385 recall 0.312
t=0.9 tp= 9 fp= 5 fn=23 tn=11 precision 0.643 recall 0.281
t=1.0 tp= 9 fp= 0 fn=23 tn=16 precision 1.000 recall 0.281
C. best recall that keeps zero false accepts, per metric
token_f1 threshold 0.94 recall 0.281
rouge_l threshold 0.94 recall 0.250
char_trigram_dice threshold 0.93 recall 0.250
D. a deterministic check (guard) next to the similarity score
same numbers preserved in 8/8
paraphrase numbers preserved in 8/8
wrong_number numbers preserved in 1/8
flipped_or_negated numbers preserved in 8/8
extra_sentence numbers preserved in 6/8
no_diacritics numbers preserved in 8/8
Reading the output:
- A. All three metrics give the wrong-number sentence a higher score than the correct rephrasing (
P13versusP12indata/sim_pairs.jsonl). - B. From threshold 0.5 to 0.8, fp is always 16: every wrong answer is accepted. Threshold 0.9 lets through 5 but recall is down to 0.281.
- C. With
fp = 0, the highest recall is 0.281 (token F1) and 0.250 (the other two metrics); the printed threshold is the lowest one on the 0.01 grid that reaches that recall. - D. The number guard passes 1/8 of the
wrong_numberanswers, 8/8 of theflipped_or_negatedanswers, and rejects 2 correctextra_sentenceanswers.
8.3 Compute and check it yourself
Save it as try_l02.py in the lab's root folder (next to lab/), run python try_l02.py, then delete the file:
from lab import similarity as s
ref = "Số lớn nhất có ba chữ số là 999."
perm = "999 là số lớn nhất có ba chữ số."
print(s.token_f1(perm, ref), s.rouge_l(perm, ref))
ref2 = "Đúng rồi, 6 nhân 4 bằng 24."
for label, pred in [("paraphrase", "Chính xác, tích của 6 và 4 là 24."), ("wrong number", "Đúng rồi, 6 nhân 4 bằng 26.")]:
print(label, s.token_f1(pred, ref2), round(float(s.token_f1(pred, ref2)), 3), s.numbers_preserved(pred, ref2))
print(s.token_f1("a a a a", "a"))
print(s.token_f1("", "tạ"), s.token_f1("tạ", "tạ tạ"))
print(s.token_f1("moi ban duoc may vien", "Mỗi bạn được mấy viên?"))
Output (identical on Python 3.14.6 and 3.12.14):
1 7/9
paraphrase 3/8 0.375 True
wrong number 6/7 0.857 False
2/5
0 2/3
0
Reading: the reordering gives token F1 of 1 and ROUGE-L of 7/9; 3/8 and 6/7 match the hand calculation in §4.2; a a a a against a scores only 2/5, not 1, because repeated words are counted; an empty sentence scores 0 instead of raising an error, while an empty reference is rejected; the sentence typed without diacritics scores 0 against the version with diacritics, not one word matches.
8.4 Run the lesson's tests
python -m pytest tests/test_l02_similarity.py -v
Result: 10 passed. Read test_a_wrong_number_scores_higher_than_a_correct_paraphrase, test_no_threshold_gives_both_zero_false_accepts_and_good_recall and test_numbers_guard_catches_changed_numbers_and_misses_the_rest.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: reference has no tokens |
The reference is empty or only punctuation | Fix the data |
| A score of 0 for sentences that look alike | Different diacritics or a different Unicode form | Normalise to NFC; see §5.2 |
| Two "equal" scores land on two sides of the threshold | You are using floats; the lab uses Fraction |
Use Fraction for thresholds and compare inclusively |
9. Independent exercise
Problem: Write the rule accept(pred, ref) combining a similarity score and a deterministic check for a pair (system sentence, reference answer), then find the kind of wrong answer that your rule still lets through.
Requirements: complete exercises/test_l02_guard.py:
- TODO 1: write
accept(pred, ref)returningTrueorFalse. It must reject everywrong_numberandunrelated_same_numbersanswer (the same numbers but talking about something else), accept at least 7 of the 8 correct answers, reject the empty string, and reject the version of every correct answer in which each number in it is increased by 1. - TODO 2: fill in
UNCAUGHT: the sorted list of ids of the wrongly labelled pairs that youracceptstill accepts. This list must not be empty: if it is empty, re-read theflipped_or_negatedpairs.
Test data: exercises/pairs.json (20 fictional pairs: 4 references, each with 5 variants: paraphrase, no_diacritics, wrong_number, flipped_or_negated and unrelated_same_numbers).
Deliverable: the function accept and the list UNCAUGHT.
Acceptance criteria: python -m pytest exercises/test_l02_guard.py passes (4 tests). Do not use an empty string or a constant to get through the tests: the third test generates number-changed variants itself.
Hint: the rule needs two components, each with its own way of letting wrong answers through (§5.1, §5.3). Try each component alone on the 20 pairs and see which ids it lets through, and only then combine them. Choose the threshold from the lowest score of a correct pair and the highest score of an unrelated_same_numbers pair, not by feel (in practice, choose the threshold on the dev part and report on the test part, L2-M02-L05).
10. Knowledge check
0/18 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
The acceptance rule below is meant to combine the similarity score with the number guard, but it has a bug that lets pair P43 (20 changed to 25 cm, token F1 is 0.9) still be accepted. Find the bug.
from fractions import Fraction
from lab import similarity as s
def accept(pred, ref):
return s.numbers_preserved(pred, ref) or s.token_f1(pred, ref) >= Fraction(9, 10)P08 · Short answer
Write the acceptance rule (one sentence) that combines token F1 with numbers_preserved, then name two kinds of wrong sentences it still lets through, with how to detect each kind.
P09 · Essay
A colleague proposes replacing token F1 with cosine between embeddings so the paraphrased sentences are no longer falsely rejected. Write 5-8 sentences: what you would measure before agreeing, on what data, and why this lab's results cannot yet answer that question.
P10 · Recall
Lesson: L2-M01-L03P11 · Multiple choice
P12 · Select all that apply
P13 · Fill in the blank
P14 · True or false
P15 · Recall
Lesson: L2-M02-L04P16 · Multiple choice
P17 · Select all that apply
11. Summary
- Concepts: a similarity metric measures how many components are shared, not right/wrong; token F1 ignores order, ROUGE-L notices it.
- Skills: computing F1 by hand; sweeping thresholds and reading precision and recall; listing the ids of false accepts; pairing similarity with a deterministic check.
- Traps: treating a high score as correct; choosing a threshold by feel; looking only at accuracy; trusting embeddings before measuring them on your cases.
- You can now: give a (correct, wrong) pair that the similarity score ranks backwards, explain why, and write an acceptance rule that knows which kinds of error still get through.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Define success criteria and build evaluations (Develop tests) | Anthropic | https://platform.claude.com/docs/en/test-and-evaluate/develop-tests | 2026-11-03 | ROUGE-L; cosine with SBERT for consistency (read 100,000 of 152,950 characters) |
| R2 | Graders (text similarity graders) | OpenAI | https://developers.openai.com/api/docs/guides/graders | 2026-11-03 | List of similarity metrics; used for open-ended text |
| R3 | Bleu: a Method for Automatic Evaluation of Machine Translation (Papineni et al., ACL 2002) | ACL Anthology | https://aclanthology.org/P02-1040/ | 2026-11-03 | Only the title and publication details were read |
| R4 | ROUGE: A Package for Automatic Evaluation of Summaries (Lin, 2004) | ACL Anthology | https://aclanthology.org/W04-1013/ | 2026-11-03 | Only the title and publication details were read |
| R5 | BERTScore: Evaluating Text Generation with BERT (Zhang et al.) | arXiv | https://arxiv.org/abs/1904.09675 | 2026-11-03 | Abstract-only; the conclusion is the authors' |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Similarity metric | Metric tương đồng |
| Token F1 | F1 theo từ (trung bình điều hòa của precision và recall của từ) |
| ROUGE-L | ROUGE-L (chuỗi con chung dài nhất của các từ) |
| Threshold sweep | Quét ngưỡng |
| Guard | Chốt kiểm (kiểm tất định đặt cạnh điểm tương đồng) |
| Paraphrase | Diễn đạt lại |
| Trivial baseline | Baseline tầm thường (quy tắc không làm gì, như chấp nhận tất cả) |
| Embedding | Embedding: vector biểu diễn nghĩa |