Module: L2-M06 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L01 · Next: L03
1. Introduction
If the retrieval step does not put the right passage into the prompt, the generation step has nothing to rely on. That is why retrieval is measured separately, before looking at the answer: for each question that has a label saying "which passage contains the answer", we ask whether that passage is in the top-k and at what rank. This lesson defines five metrics (recall@k, precision@k, hit@k, MRR, nDCG), builds the labels from evidence spans, handles the edge cases, and reports the mean with an interval so you know when the data cannot tell two retrievers apart.
Every retriever, question and number in the lab is simulated or a toy (L01). The numbers describe the simulation, not a property of a real retriever. The output of the lesson: retrieval metrics on a labelled question set, with intervals and a list of the failing questions.
2. Learning objectives
- Compute recall@k, precision@k, hit@k, MRR and nDCG by hand on small lists. Practice: §8.3, §9 (TODO 1).
- Build relevance labels from evidence (document, sentence) and explain why the labels survive a change of chunking. Practice: §8.2 part D.
- Handle edge cases: an empty result, k larger than the corpus, no correct chunk, duplicates, tied ranks. Practice: §8.3, §9 (TODO 2).
- Report the mean with a bootstrap interval and conclude "cannot tell" when the interval contains 0. Practice: §8.2 part C, §9 (TODO 3).
- State what the metrics do not say. Practice: §6, §8.3 (last two lines).
3. Prerequisites and tools
- L2-M01-L04 (confidence intervals), L2-M05-L02 (bootstrap interval), L01 of this module. The code lab
code-labs/l2-m06. - Keeping the words "recall" and "precision" apart. recall@k (retrieval) is the share of correct passages found in the top k; it differs from the recall of a metric or of an answer grader (L2-M03-L01, L03) and from the framework's context recall (L05). The coverage of a confidence interval (L2-M01-L04) and the coverage of a dataset (L2-M02-L02) are different things. Precision@k is the share of the top k that are correct passages, which differs from the precision of a metric. The "positive class" of this lesson: relevant chunks.
4. Concepts
4.1 Recall@k, precision@k and hit@k
A ranking is a list of distinct chunks, best first. The relevant set is the question's relevant chunks. For the top k:
- recall@k = (number of correct chunks in the top k) / (number of correct chunks). Anthropic uses "1 − recall@20" as its measure, describing it as the share of relevant documents not retrieved in the first 20 chunks [R1].
- precision@k = (number of correct chunks in the top k) / k. The denominator is k, not the number of chunks returned: a retriever that returns fewer than k is penalized, and if the corpus is smaller than k the maximum value is below 1.
- hit@k = 1 if the top k has at least one correct chunk, otherwise 0.
If there is no correct chunk (a question outside the corpus), recall, precision, hit, MRR and nDCG are undefined; the lab returns None, leaves the question out of the mean and counts it separately. Assigning 0 or 1 would skew the mean either way.
4.2 MRR and nDCG
The reciprocal rank is 1 divided by the rank of the first correct chunk, and 0 if there is a correct chunk but it is not in the top k (different from the case with no correct chunk at all, §4.1: undefined); MRR is the mean over questions [R2]. Limitation: only the rank of the first correct chunk counts, and every later correct chunk is ignored [R2].
nDCG (normalized discounted cumulative gain) takes into account both rank and the degree of relevance (grade). DCG (discounted cumulative gain, a sum of gains discounted by rank) at p is the sum of the grade divided by log2(i + 1) over rank i; there is a variant that uses (2^grade − 1) as the numerator, which puts more weight on highly relevant chunks, and the two variants coincide when the grade is only 0 or 1 [R3]. nDCG = DCG / IDCG, where IDCG is the DCG of the ideal order, so the value lies between 0 and 1 [R3]. The lab uses the first form, and cuts the ideal order at k. The source page does not say what happens when IDCG is 0; the lab returns None when no chunk has a positive grade. Because log2 is irrational, the lab's nDCG is a floating-point number, compared with a tolerance of 1e-12, never with == (except when every rank involved is 1, 3 or 7, where log2 is an integer; IDCG can still be irrational). The other numbers are exact Fraction values.
4.3 Relevance labels from evidence
The lab's relevance labels (qrels, query relevance judgments) are derived from evidence. Each question records its evidence as a list of (document, sentence, grade) with grade 2 (the sentence contains the answer) or 1 (a supporting sentence). qrels_for gives each chunk the highest grade of the evidence spans that the chunk fully contains. Consequence: switching to chunk_sentences(corpus, 4, 0) changes the chunk ids but the labels stay correct; labelling directly with chunk ids would not (L01 §4.2). An evidence span cut in half by a chunk gives no chunk a positive grade (lost_evidence, L01).
5. Technical deep dive
5.1 Running two retrievers
evaluate(search, queries, chunks, k, groups) returns a per-question table; summarize takes the mean over the questions for which the metric is defined. The 25-question set has 3 questions outside the corpus (Q17, Q18, Q25), so the mean is over 22 questions with 3 undefined; if those three were counted as 0, precision@3 would drop from 37/66 to 37/75 (0.493 instead of 0.561). With BM25 and a 2-sentence window with overlap 1: k = 3 gives recall 61/66 (0.924), precision 37/66 (0.561), MRR 31/33 (0.939), nDCG 0.918; k = 1 gives recall 19/33 (0.576) but precision 10/11 (0.909). The toy embedding at k = 3: recall 0.795, MRR 0.841, nDCG 0.793. The two cannot be compared as two real retrievers: the toy one is weaker here because it hashes characters, not because vectors are worse than keywords. BEIR reports on real data that BM25 is a robust baseline, while dense and sparse models (together with re-ranking and late-interaction, according to the summary that was read) have mean results that differ depending on the architecture [R4] (abstract-only); that conclusion cannot be inferred from the lab.
The mean hides failing questions. At k = 3, BM25 has recall below 1 on three questions: Q06 (1/3), Q09 (1/2), Q16 (1/2); Q06 and Q16 are paraphrased questions with few words in common with the evidence, Q09 needs two documents. Always print this list next to the mean.
5.2 Two things that skew the metrics: overlap and duplicates
Overlap. With an overlap of 1 sentence, Q08 has three correct chunks (D03-c3 grade 2, D03-c1 and D03-c2 grade 1). A perfect retriever that returns D03-c3 at rank 1 gets only recall@1 = 1/3. The low recall@1 here is a consequence of the chunking, not a retrieval error, so compare retrievers only under the same chunking, and write the chunking in the report.
Duplicates. D12-c1 has the same content as D05-c1. If the retriever returns the duplicate and the label records only D05-c1, recall@1 is 0 even though the content is right. duplicate_groups maps chunks with the same content to the first id and canonical merges them before scoring: recall@1 changes from 0 to 1 (§8.3). Merging by content is a choice: it does not catch near-duplicates.
Tied scores. Ranking is deterministic (L01 §5.3), so two chunks with the same content have a fixed order. If the order depended on how a file was read, MRR could change between two runs with nobody editing anything.
k too large. With k larger than the number of chunks, evaluate still runs; precision@k is capped above by (number of chunks) / k. A retriever that returns the whole corpus has recall 1 and low precision: recall alone is not enough.
5.3 Bootstrap interval and paired comparison
With 22 questions, the mean has sampling error. bootstrap_mean_interval resamples the questions with replacement using SHA-256 hashing (1000 times; because it uses hashing it is identical on every machine) and takes the 2.5% and 97.5% percentiles. The MRR@3 of BM25 has an interval of 0.848 to 1.000. To compare two retrievers, paired_bootstrap_difference takes the difference per question (the same question, paired). The MRR@3 of BM25 minus the toy embedding is 0.098, with an interval of 0.015 to 0.205: here the interval lies above 0. This number describes the simulation and the 22 questions that the lab wrote; if the interval contains 0 you must conclude "cannot tell" (the exercise in §9). The interval speaks only about the sampling error of this question set, and says nothing about questions from a different distribution.
6. The QA perspective
6.1 What the metrics do not say
- They say nothing about the answer. A correct chunk in the top 3 does not guarantee a correct answer (L03, L04).
- They depend on the labels. The evidence was written by one person (the lab's author); a missing label makes recall falsely high, an extra label makes precision falsely low. No second person has labelled independently, so the reliability of the labels has not been measured (L2-M05).
- They depend on the chunking and on k. With the same retriever, changing the chunking or k changes the numbers; a comparison only means something when both are held fixed.
- MRR ignores the second correct chunk, and nDCG depends on the formula variant; state the variant.
- The mean hides individual questions. Print the list of questions with recall below 1 and the breakdown by question type (L04).
6.2 Minimum report
The chunking (size, overlap), k, the number of defined and undefined questions, each metric with its interval, the list of failing questions, the nDCG variant, how duplicates were handled, and the sentence "simulated numbers" or the source of the real retriever.
7. Real-world scenarios
Scenario 1 (fictional): "Increase the overlap, recall@1 changes though the retriever has not". The HocVui team increased the overlap to "improve retrieval" and saw the metrics change. The size of each question's set of correct chunks also changed (as in Q08: three chunks), so recall@1 cannot be compared between the two configurations. The team fixed the chunking when comparing retrievers and also reported the mean number of correct chunks per question.
Scenario 2 (fictional): "Mean 0.92 yet three questions fail". The report table had only recall@3 = 0.924. The per-question list showed three failing questions, two of them paraphrases; the team added a group of paraphrased questions to the test set (L04).
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l2-m06
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 80 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-04; the two versions give identical output). The retrievers are simulated:
A. hand-computed case: ranking [a, b, c, d], relevant {b, d, z}
recall@2 1/3 recall@4 2/3 precision@2 1/2 MRR 1/2
B. 25 questions, chunks of 2 sentences with overlap 1, BM25 and the toy embedding (simulated)
bm25 k=1: recall=0.576 precision=0.909 hit=0.909 rr=0.909 ndcg=0.909 defined/undefined: (22, 3)
bm25 k=3: recall=0.924 precision=0.561 hit=1.000 rr=0.939 ndcg=0.918 defined/undefined: (22, 3)
toy k=1: recall=0.508 precision=0.818 hit=0.818 rr=0.818 ndcg=0.818 defined/undefined: (22, 3)
toy k=3: recall=0.795 precision=0.485 hit=0.864 rr=0.841 ndcg=0.793 defined/undefined: (22, 3)
C. MRR@3 BM25 minus toy, paired over 22 questions: difference 0.098 interval 0.015 0.205
interval of the BM25 MRR@3 alone: 0.848 1.000
D. qrels of Q08 under two chunkings: {'D03-c3': 2, 'D03-c1': 1, 'D03-c2': 1} {'D03-c1': 2}
Reading the output: A is the hand-computed example (recall@2 = 1/3, MRR = 1/2); B is the mean of the two retrievers, 22 defined questions and 3 undefined; C is the interval of the MRR difference; D is the labels of Q08 under two chunkings: the ids change, the evidence stays correct.
8.3 Try it yourself
Save this as try_l02.py in the lab's root folder (next to lab/), run python try_l02.py, then delete the file:
import math
from fractions import Fraction as F
from lab import corpus as C, data, metrics as M, retrieve as R
print(M.dcg([1, 0, 1]), M.ndcg_at_k(["b", "a"], {"a": 2, "b": 1}, 2), (1 + 2 / math.log2(3)) / (2 + 1 / math.log2(3)))
print(M.recall_at_k([], {"a"}, 3), M.recall_at_k(["a"], set(), 3), M.precision_at_k(["a"], {"a"}, 3))
print(M.reciprocal_rank(["x", "a", "b"], {"a", "b"}), M.reciprocal_rank(["x", "y", "a"], {"a"}, k=2))
corpus = data.load_json("corpus.json")
chunks = C.chunk_sentences(corpus)
queries = data.load_jsonl("queries.jsonl")
groups = C.duplicate_groups(chunks)
print(M.recall_at_k(["D12-c1"], {"D05-c1"}, 1), M.recall_at_k(M.canonical(["D12-c1"], groups), {"D05-c1"}, 1))
bm = R.BM25(chunks)
for k in (1, 3):
rows = M.evaluate(bm.search, queries, chunks, k, groups)
print(k, M.summarize(rows, "recall")[0], M.summarize(rows, "precision")[0], M.summarize(rows, "rr")[0])
rows = M.evaluate(bm.search, queries, chunks, 3, groups)
print(M.summarize(rows, "precision")[0], M.summarize(rows, "precision")[0] * 22 / 25)
print([(r["id"], str(r["recall"])) for r in rows if r["recall"] is not None and r["recall"] < 1])
print([r["id"] for r in rows if r["rr"] is not None and r["rr"] < 1])
Output (Python 3.14.6 and 3.12.14 identical):
1.5 0.8597186998521972 0.8597186998521972
0 None 1/3
1/2 0
0 1
1 19/33 10/11 10/11
3 61/66 37/66 31/33
37/66 37/75
[('Q06', '1/3'), ('Q09', '1/2'), ('Q16', '1/2')]
['Q06', 'Q16']
Reading: line 1 is the DCG of [1, 0, 1] (1 + 1/2 = 1.5 exactly) and the nDCG of [b, a] with grades 2 and 1 (matching the hand formula). Line 2: an empty result gives recall 0; no correct chunk gives None; the precision@3 of ["a"] is 1/3. Line 3: MRR does not change when a second correct chunk is added (1/2); a correct chunk outside k gives 0. Line 4: scoring the duplicate raw gives 0, after canonical it gives 1. Lines 5 and 6: k, recall, precision and MRR of BM25 as fractions. Line 7: the mean precision@3 over 22 questions (37/66) and when the three undefined questions are counted as 0 (37/75). Line 8: the questions with recall@3 below 1. Line 9: the questions with MRR@3 below 1. What the metrics do not say: Q09 has MRR 1 but recall of only 1/2.
8.4 Run the lesson's tests
python -m pytest tests/test_l02_retrieval_metrics.py -v
Result: 18 passed. Read test_nothing_relevant_is_undefined_not_zero, test_ndcg_ties_in_grade_and_truncation and test_duplicates_are_collapsed_before_scoring. The tests run on in-memory values and the lab's data.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: a ranking may not repeat an id |
The ranking has a repeated id, which would be counted twice | Merge with canonical or remove duplicates |
ValueError: k must be an integer of at least 1 |
k is 0, negative or not an integer | Pass an integer k from 1 |
9. Independent exercise
Problem: Score two retrievers from a recorded ranking log and say whether the data can tell them apart.
Requirements: complete exercises/test_l02_retrieval_metrics.py:
- TODO 1:
RECALL_B_AT3andMRR_A(Fraction, the mean over defined questions; MRR uses k = 5) andNDCG_B_AT3(a floating-point number rounded to 3 decimal places, binary grade). - TODO 2:
UNDEFINED: the set of question ids for which recall is undefined. - TODO 3:
VERDICTis"A better","B better"or"cannot tell", according to the paired bootstrap interval of the MRR difference (A minus B).
Test data: exercises/ex_ranked.json (14 questions, each with two rankings of 5 chunks, generated so the answer is known).
Deliverable: the five variables above, in exercises/test_l02_retrieval_metrics.py itself.
Acceptance criteria: python -m pytest exercises/test_l02_retrieval_metrics.py passes (3 tests): the numbers are recomputed from the log with lab.metrics, the undefined set matches the data, and the verdict matches the interval. The test does not check whether you understand why the two means differ yet the interval still contains 0.
Hints: TODO 1: filter for questions that have a correct chunk before taking the mean. TODO 3: compute both the mean and the interval, then compare them side by side; do not conclude from the mean alone.
10. Knowledge check
0/16 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 function below defines precision@k but gives a wrong result when the retriever returns fewer than k chunks. Find the bug.
def precision_at_k(ranking, relevant, k):
top = ranking[:k]
if not relevant:
return None
return Fraction(len(set(top) & set(relevant)), len(top))P08 · Short answer
A set of 10 questions has 2 out-of-corpus questions. The recall@3 of the 8 defined questions are 1, 1, 1, 1, 1/2, 1/2, 1, 0. What is the average, and why not count the two out-of-corpus questions as 0?
P09 · Essay
Write 5-8 sentences: a report compares two simulated retrievers A and B on 12 fictional questions (k = 5, one correct chunk per question). MRR@5: A is 115/144 (≈ 0.799), B is 271/360 (≈ 0.753); the difference A minus B is 11/240 (≈ 0.046) with a paired bootstrap interval of 95% from −5/24 (≈ −0.208) to 73/240 (≈ 0.304), 1000 resamples, seed "p02b". State the conclusion and what the numbers do not tell.
P11 · Recall
Lesson: L2-M01-L04P12 · Recall
Lesson: L2-M06-L01P13 · Multiple choice
P14 · True or false
P15 · Select all that apply
P16 · Fill in the blank
11. Summary
- Concepts: the five retrieval metrics and the denominator of each; labels from evidence; undefined is not 0; bootstrap intervals for the mean and for the paired difference.
- Skills: computing by hand, handling empty, large k, duplicates and tied ranks; reporting with a list of failing questions.
- Traps: comparing recall across two chunkings, a duplicate counted as wrong, a mean that hides failing questions, concluding from the difference of means when the interval contains 0.
- You can now: read "recall@5 = 0.9" and ask: which chunking, how many defined questions, which interval.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Introducing Contextual Retrieval | Anthropic | https://www.anthropic.com/news/contextual-retrieval | 2026-11-04 | WebFetch (automatic summary): "1 − recall@20" |
| R2 | Mean reciprocal rank | Wikipedia | https://en.wikipedia.org/wiki/Mean_reciprocal_rank | 2026-11-04 | WebFetch (automatic summary), secondary source |
| R3 | Discounted cumulative gain | Wikipedia | https://en.wikipedia.org/wiki/Discounted_cumulative_gain | 2026-11-04 | WebFetch (automatic summary), secondary source |
| R4 | BEIR (Thakur et al., 2021) | arXiv | https://arxiv.org/abs/2104.08663 | 2026-11-04 | Abstract-only (WebFetch, automatic summary) |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Recall@k, precision@k, hit@k | Recall, precision, tỷ lệ trúng trong top k (của truy xuất) |
| MRR, nDCG | Hạng nghịch đảo trung bình, DCG chuẩn hóa |
| Relevance label (qrels) | Nhãn liên quan: chunk nào đúng, grade bao nhiêu |
| Undefined metric | Số đo không xác định (không có chunk đúng) |
| Paired bootstrap | Bootstrap có cặp: lấy mẫu lại cùng một tập câu hỏi cho cả hai bộ |