Lab: Compare Two Retrieval Configurations
Run BM25 and vector search over the same held-out queries, save the rankings, compare mean precision@k and recall@k, read the per-query differences, test the gap with a sign test and a paired bootstrap, and trace the misses to their causes.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: the metric and the loaders
- Step 2: save each configuration's rankings
- Step 3: compare the means, then look per query
- Step 4: is the gap larger than chance?
- Step 5: read the misses
- Step 6: check whether k changes the answer
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of RAG Retrieval Evaluation
- Why Retrieval Is Measured Separately Concept · 10 min
- Precision@k and Recall@k by Hand and in Code Worked example · 20 min
- Building a Labeled Query Set Lab · 20 min
- Lab: Compare Two Retrieval Configurations Lab · 25 min
- Rank-Aware Metrics and the Limits of Labels Concept · 15 min
- Check: Compute and Compare Retrieval Metrics Knowledge check · 10 questions
What you will learn
- Compare two retrieval configurations against a test set.
Prerequisites: RAG Foundations
01. Goal and setup
In lesson 3 you froze a labelled query set. Now you use its 24 held-out test queries to compare two retrieval configurations from the hybrid search lab: keyword, the BM25 search, and vector, exact cosine search over the stand-in embedder. You will save each configuration's rankings as a run file, compute mean precision@k and recall@k with the function from lesson 2, look at the per-query differences behind the means, test whether the gap is larger than chance, and trace the differences to their causes.
The harness does not care what produced the rankings. Two chunk sizes, two embedding models, search with and without a reranker: any pair works, as long as both return ranked document ids for the same queries. BM25 belongs in most comparisons as the cheap baseline; in the BEIR benchmark, several dense retrievers of the time did worse than BM25 on datasets unlike their training data.
You need: the retrieval-eval folder from lesson 3 with its virtual environment, plus vector.py, bm25.py and fusion.py from hybrid-lab. Everything runs on Python 3.12 or later and NumPy (tested with NumPy 2.5.5).
cd retrieval-eval
source .venv/bin/activate # Windows: .venv\Scripts\activate
cp ../hybrid-lab/vector.py ../hybrid-lab/bm25.py ../hybrid-lab/fusion.py .
python -c "from bm25 import keyword_search; print(keyword_search('ERR-7702', 3))"['d08']retrieval-eval/
├── vector.py, bm25.py, fusion.py from hybrid-lab
├── metrics.py step 1: precision@k and recall@k, and loaders
├── demo_metrics.py step 1: a short ranking under two thresholds
├── run.py step 2: writes runs/keyword.jsonl and runs/vector.jsonl
├── compare.py step 3: means and per-query differences
├── stats.py step 4: sign test and paired bootstrap
└── misses.py step 5: what each run missed, and why02. Step 1: the metric and the loaders
precision_recall_at_k() is the function from lesson 2, unchanged, so the definitions stay the same: precision@k is the relevant documents in the top k divided by k, and recall@k is the relevant documents in the top k divided by all relevant documents in the reference set. Two loaders turn the JSONL files into dictionaries. load_set() applies the binary threshold, grade 1 or higher unless you ask for another.
"""Precision@k and recall@k from lesson 2, and loaders for the query set and runs."""
from validate import read_jsonl
def precision_recall_at_k(retrieved: list[str], relevant: set[str], k: int):
if k <= 0 or not relevant:
raise ValueError('k must be positive and relevant set non-empty')
top_k = retrieved[:k]
hits = sum(doc_id in relevant for doc_id in top_k)
return hits / k, hits / len(relevant)
def load_set(path: str, min_grade: int = 1) -> dict[str, dict]:
"""query id -> {"query": text, "relevant": ids graded min_grade or higher}."""
queries = {}
for row in read_jsonl(path):
relevant = {d for d, grade in row["relevant"].items() if grade >= min_grade}
queries[row["id"]] = {"query": row["query"], "relevant": relevant}
return queries
def load_run(path: str) -> dict[str, list[str]]:
"""query id -> ranked document ids, best first."""
return {row["id"]: row["ranked"] for row in read_jsonl(path)}The first edge case from lesson 2 now happens for real: BM25 only returns documents that share a term with the query, so it can return fewer than k results, and the function counts the empty slots as misses. Before scoring whole runs, check that behaviour and the binary threshold of load_set() on one test query.
from metrics import load_set, precision_recall_at_k
ranked = ["d02", "d01"] # a short list: only two results, scored at k = 3
for min_grade in (1, 2):
relevant = load_set("data/test.jsonl", min_grade)["q02"]["relevant"]
precision, recall = precision_recall_at_k(ranked, relevant, 3)
print(f"min_grade {min_grade}: relevant {sorted(relevant)}, "
f"precision@3 {precision:.3f}, recall@3 {recall:.3f}")min_grade 1: relevant ['d01', 'd13'], precision@3 0.333, recall@3 0.500
min_grade 2: relevant ['d01'], precision@3 0.333, recall@3 1.000Precision@3 is 1/3 under both thresholds, not 1/2: the one hit is divided by k, so the empty third slot counts as a miss. Recall moves with the threshold, because the threshold changes its denominator: the same ranking finds half of the relevant articles for q02, or all of them when only grade 2 counts.
03. Step 2: save each configuration's rankings
Score saved rankings rather than calling the retrievers inside the metric code. A run file records exactly what each configuration returned for each query, so you can recompute any metric at any k later, attach the evidence to your report, and still compare against a retriever that is slow, expensive or gone. Save more results than you plan to score; ten here.
"""Run each configuration over the test queries and save its rankings."""
import json
from pathlib import Path
from bm25 import keyword_search
from metrics import load_set
from vector import vector_search
CONFIGS = {"keyword": keyword_search, "vector": vector_search}
DEPTH = 10 # keep more results than any k you will report
queries = load_set("data/test.jsonl")
Path("runs").mkdir(exist_ok=True)
for name, search in CONFIGS.items():
with open(f"runs/{name}.jsonl", "w", encoding="utf-8", newline="\n") as f:
for query_id, item in queries.items():
ranked = search(item["query"], DEPTH)
f.write(json.dumps({"id": query_id, "ranked": ranked}) + "\n")
print(f"runs/{name}.jsonl: {len(queries)} queries")python run.py
head -n 2 runs/keyword.jsonlruns/keyword.jsonl: 24 queries
runs/vector.jsonl: 24 queries
{"id": "q02", "ranked": ["d02", "d01"]}
{"id": "q03", "ranked": ["d02", "d01"]}Both runs cover the 24 queries of data/test.jsonl, the held-out split. BM25 returned only two documents for q02 and q03, because no other article shares a word with them. In a real comparison, also record what produced each run (code version, parameters, model name) next to the file.
04. Step 3: compare the means, then look per query
"""Mean precision@k and recall@k of two runs, and the queries where they differ."""
import sys
from metrics import load_run, load_set, precision_recall_at_k
def per_query(run: dict[str, list[str]], queries: dict[str, dict], k: int) -> dict:
"""query id -> (precision@k, recall@k); the run must cover exactly these queries."""
if set(run) != set(queries):
raise ValueError("the run and the query set cover different queries")
return {
query_id: precision_recall_at_k(run[query_id], item["relevant"], k)
for query_id, item in queries.items()
}
def mean(values: list[float]) -> float:
return sum(values) / len(values)
if __name__ == "__main__":
name_a, name_b, k = sys.argv[1], sys.argv[2], int(sys.argv[3])
queries = load_set("data/test.jsonl")
scores = {}
for name in (name_a, name_b):
scores[name] = per_query(load_run(f"runs/{name}.jsonl"), queries, k)
print(f"{len(queries)} test queries, k = {k}")
for name, by_query in scores.items():
precision = mean([p for p, _ in by_query.values()])
recall = mean([r for _, r in by_query.values()])
print(f"{name:<8} precision@{k} {precision:.3f} recall@{k} {recall:.3f}")
print(f"recall@{k}, {name_b} minus {name_a}, where they differ:")
better = worse = 0
for query_id, item in queries.items():
diff = scores[name_b][query_id][1] - scores[name_a][query_id][1]
if diff:
better, worse = better + (diff > 0), worse + (diff < 0)
print(f" {query_id} {diff:+.2f} {item['query']}")
ties = len(queries) - better - worse
print(f"{name_b} better on {better}, worse on {worse}, tied on {ties}")python compare.py keyword vector 324 test queries, k = 3
keyword precision@3 0.375 recall@3 0.875
vector precision@3 0.417 recall@3 0.917
recall@3, vector minus keyword, where they differ:
q02 +0.50 money taken from my card two times
q12 +0.50 API returns 413 on exports
q20 -1.00 pdf invoice download
q31 +0.50 how many rows can I export
q37 +0.50 exports endpoint row limit
vector better on 4, worse on 1, tied on 19On the means, vector search is ahead: recall@3 of 0.917 against 0.875, precision@3 of 0.417 against 0.375. Two details keep these numbers honest. Precision@3 is low for both because most queries have a single relevant article, so even a perfect ranking scores 1/3 on them; use precision to compare configurations, not as an absolute grade. And per_query() refuses to score a run that covers different queries from the set, because a mean over different queries compares the queries, not the retrievers.
The per-query lines tell a different story from the means. Nineteen of the 24 queries are tied, and the whole difference comes from five queries: four in favour of vector, one in favour of keyword. The mean difference of 0.042 is exactly (4 × 0.5 − 1) / 24. Whenever a decision rests on a handful of queries, the next question is whether that handful could have split this way by chance.
05. Step 4: is the gap larger than chance?
Both tests below are paired: they compare the configurations query by query, as the bootstrap did when you compared embedding models in the Embeddings skill. Queries differ from each other far more than configurations do (an easy query is easy for both), and pairing removes that variation instead of counting it as noise.
- The sign test ignores ties and the size of each difference. If neither configuration were better, each query where they differ would favour either one with probability 1/2, like a coin toss. The p-value is the probability of a split at least as lopsided as the one observed, in either direction.
- The paired bootstrap resamples the 24 per-query differences with replacement 10,000 times and keeps the middle 95% of the resampled means as an interval for the mean difference. An interval that contains 0 means the data are consistent with no difference.
"""Could the recall@k difference between two runs be chance?"""
import math
import random
import sys
from compare import mean, per_query
from metrics import load_run, load_set
def sign_test(wins: int, losses: int) -> float:
"""Two-sided exact sign test; tied queries are left out."""
n = wins + losses
if n == 0:
return 1.0
tail = sum(math.comb(n, i) for i in range(min(wins, losses) + 1)) / 2**n
return min(1.0, 2 * tail)
def paired_bootstrap(diffs: list[float], rounds: int = 10_000, seed: int = 0):
"""95% interval for the mean difference, resampling whole queries."""
rng = random.Random(seed)
n = len(diffs)
means = sorted(sum(rng.choices(diffs, k=n)) / n for _ in range(rounds))
return means[int(0.025 * rounds)], means[int(0.975 * rounds) - 1]
if __name__ == "__main__":
name_a, name_b, k = sys.argv[1], sys.argv[2], int(sys.argv[3])
queries = load_set("data/test.jsonl")
a = per_query(load_run(f"runs/{name_a}.jsonl"), queries, k)
b = per_query(load_run(f"runs/{name_b}.jsonl"), queries, k)
diffs = [b[q][1] - a[q][1] for q in queries] # paired: same query, two runs
wins, losses = sum(d > 0 for d in diffs), sum(d < 0 for d in diffs)
p_value = sign_test(wins, losses)
low, high = paired_bootstrap(diffs)
print(f"mean recall@{k} difference ({name_b} - {name_a}): {mean(diffs):+.3f}")
print(f"sign test: {wins} better, {losses} worse, p = {p_value:.3f}")
print(f"bootstrap 95% interval for the difference: [{low:+.3f}, {high:+.3f}]")python stats.py keyword vector 3mean recall@3 difference (vector - keyword): +0.042
sign test: 4 better, 1 worse, p = 0.375
bootstrap 95% interval for the difference: [-0.083, +0.146]Four to one sounds convincing, but five fair coin tosses split at least that unevenly 37.5% of the time, and the bootstrap interval runs from −0.083 to +0.146, well across zero. The data do not show that vector search retrieves better on this set. They do not show that the two are equal either: five informative queries are simply not enough evidence.
Two facts help you plan the next round. With n differing queries, the smallest two-sided p-value a sign test can give is 1/2^(n−1), so five differing queries can never reach 0.05, however they split. And the same four-to-one ratio over 20 differing queries (16 to 4) gives p ≈ 0.012. A better set therefore needs queries that separate the configurations, not just more queries that both already get right.
Both tests are deliberately simple. IR research more often uses a paired t-test or a randomisation (permutation) test, which also use the size of each difference. SciPy's binomtest(4, 5) returns the same 0.375 as sign_test().
06. Step 5: read the misses
"""For each query where two runs differ, show what each run missed in its top k."""
import sys
import textwrap
from compare import per_query
from corpus import DOCS
from metrics import load_run, load_set
TEXT = {doc_id: text for doc_id, _, text in DOCS}
name_a, name_b, k = sys.argv[1], sys.argv[2], int(sys.argv[3])
queries = load_set("data/test.jsonl")
runs = {name: load_run(f"runs/{name}.jsonl") for name in (name_a, name_b)}
scores = {name: per_query(run, queries, k) for name, run in runs.items()}
for query_id, item in queries.items():
if scores[name_a][query_id] == scores[name_b][query_id]:
continue
print(f"{query_id} {item['query']!r}")
for name, run in runs.items():
top = run[query_id][:k]
missed = sorted(item["relevant"] - set(top))
print(f" {name:<8} top {k}: {' '.join(top):<12} missed: {missed}")
for doc_id in missed:
snippet = textwrap.shorten(TEXT[doc_id], 64, placeholder=" ...")
print(f" {doc_id}: {snippet}")python misses.py keyword vector 3q02 'money taken from my card two times'
keyword top 3: d02 d01 missed: ['d13']
d13: Charged twice after upgrading in the Android app? Google ...
vector top 3: d01 d02 d13 missed: []
q12 'API returns 413 on exports'
keyword top 3: d09 missed: ['d08']
d08: Error ERR-7702 means the export is larger than 100,000 rows. ...
vector top 3: d07 d09 d08 missed: []
q20 'pdf invoice download'
keyword top 3: d03 missed: []
vector top 3: d07 d09 d08 missed: ['d03']
d03: Download past invoices as PDF files from the Billing page.
q31 'how many rows can I export'
keyword top 3: d08 d07 missed: ['d09']
d09: The exports endpoint returns 413 when a report exceeds the ...
vector top 3: d07 d09 d08 missed: []
q37 'exports endpoint row limit'
keyword top 3: d09 missed: ['d08']
d08: Error ERR-7702 means the export is larger than 100,000 rows. ...
vector top 3: d09 d08 d07 missed: []The numbers say whether the configurations differ; reading the misses says why, and the why is what you can act on. Two patterns stand out.
- Every document keyword search missed is a grade-1 article. For q02 it is the Android version of the double-charge article; for q12, q31 and q37 it is the companion export article, d08 or d09. These queries share no word with the missed article, and BM25 cannot match words that are not there. The stand-in embedder maps the vocabulary of payments and of exports to shared directions, so vector search lifts the related article into the top 3.
- Vector search's one miss is a grade-2 article. In q20,
pdfandinvoicemean nothing to the stand-in embedder (it knows onlyinvoices), sodownloadalone pulls in the export articles. BM25 matchespdfexactly.
So vector search's lead rests entirely on partly relevant articles, while keyword search's single win is on the article that answers the query. Whether that matters depends on your relevance threshold and on what the generator needs. Findings like this, with the query, the missed document and the reason, are what the practice project asks you to write up.
07. Step 6: check whether k changes the answer
Run the same comparison at k = 1, the setting that matters when only the top result is shown or used.
python compare.py keyword vector 1
python stats.py keyword vector 124 test queries, k = 1
keyword precision@1 0.875 recall@1 0.708
vector precision@1 0.708 recall@1 0.583
recall@1, vector minus keyword, where they differ:
q02 +0.50 money taken from my card two times
q04 -1.00 where are my invoices for accounting
q12 -0.50 API returns 413 on exports
q20 -1.00 pdf invoice download
q21 -1.00 unlock a user account as admin
q22 -1.00 Face ID login
q31 -0.50 how many rows can I export
q33 +1.00 update payment card for my plan
q35 -0.50 cancel a plan bought through the App Store
q36 +1.00 which iPhone version does the app need
vector better on 3, worse on 7, tied on 14
mean recall@1 difference (vector - keyword): -0.125
sign test: 3 better, 7 worse, p = 0.344
bootstrap 95% interval for the difference: [-0.333, +0.083]The direction flips. At k = 1, keyword search is better on seven queries and worse on three: BM25 tends to put the article that shares the query's rarest word first, while the stand-in embedder often ranks a related article above the right one, which recall@3 does not penalise. Neither difference is significant, but the lesson holds generally: choose k from how the results are used, such as how many passages your prompt includes, before you compare, and report k with every number. Lesson 5 introduces metrics that reward putting the right document first without fixing a single cut-off.
08. Check your understanding
09. Apply it: stretch tasks
Complete the practice project: run your own retriever under two configurations on your labelled queries, save both runs in this format, and report mean precision@k and recall@k, the per-query differences, the sign test and bootstrap interval, and an analysis of at least two missed documents. Then go further:
- Hybrid. Import
hybrid_searchfromfusioninrun.py, add it toCONFIGSas"hybrid", rerun, and compare it with each of the other two. Every extra comparison is another chance of a lucky result, so decide beforehand which comparison answers your question. - Strict labels. Change
load_set("data/test.jsonl")toload_set("data/test.jsonl", min_grade=2)incompare.pyandstats.py, and explain from step 5 why the leader changes. - Use the dev split. Give
hybrid_search()a parameter for the RRF constant, try 10, 30 and 60 ondata/dev.jsonl, choose one, and only then score the chosen setting once on the test split. - A real embedder. Replace
embed()incorpus.pywith a real embedding model, rerun everything, and check which of the misses in step 5 disappear and which new ones appear.
10. Review prompt
Without looking back:
- Why save run files instead of scoring retrievers live?
- Why must the comparison be paired by query, and what does pairing remove?
- Can a sign test over five differing queries reach p < 0.05? Show why.
- What did the misses reveal that the means hid?
- Why can the leader change between k = 1 and k = 3, and how do you choose k before comparing?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 12 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.