Sub topic 6
Measuring whether reranking helps
This chapter assumes you can run Python, know what a bi-encoder retriever and a cross-encoder reranker do, and have a retrieve-then-rerank pipeline like the one built earlier. It also assumes you know the basic retrieval terms: query, document, relevance. The goal is to decide, with numbers, whether the reranker earns its extra latency.
Why you need a measurement
A reranker can look good in a demo and still hurt in production. You try three queries, the top result looks right, and you ship. Then a different class of queries gets worse, or the gain is too small to justify the cost of scoring 50 passages per request.
Measurement needs three things:
- A set of queries.
- Relevance labels: which documents answer each query.
- Metrics that turn a ranked list into a number.
You then compute the metrics for the first-stage ranking (the baseline) and for the reranked list, and compare them on the same queries.
Building an evaluation set
An evaluation set is a list of queries, each with the IDs of its relevant documents. For graded relevance, each document also gets a gain, such as 0 (irrelevant), 1 (partly relevant), or 2 (fully relevant).
Some practical rules:
- Use real queries from your domain. Public benchmarks such as MS MARCO are useful for sanity checks, but they do not tell you how a model behaves on your documents.
- Aim for at least 100 queries. With fewer, a single query can swing the average.
- Label the documents your pipeline actually returns, not only a hand-picked "gold" document. If the labeler never sees what the reranker promotes, unlabeled documents count as irrelevant and the reranker is penalized for finding good answers you missed.
- Keep the set fixed. Do not tune the reranker on the same queries you report results on. Split into a development set and a held-out test set.
The three core metrics
Each metric answers a different question.
| Metric | Question it answers | Uses graded labels | Position-sensitive |
|---|---|---|---|
| recall@k | Did the relevant documents appear in the top k? | No | No, within the top k |
| MRR | How high is the first relevant document? | No | Yes |
| nDCG@k | How good is the whole top-k ordering? | Yes | Yes |
Recall@k
Recall@k is the fraction of a query's relevant documents found in the top k results:
recall@k = (relevant documents in the top k) / (all relevant documents)
Recall@k does not care about order inside the top k. That is why it is the right metric for the first stage. A reranker can only reorder what it receives, so recall at the candidate depth (for example recall@50) is a ceiling on what reranking can achieve.
Mean reciprocal rank
The reciprocal rank (RR) of a query is 1 divided by the rank of the first relevant document, or 0 if none appears. MRR is the mean of RR over all queries. A first relevant result at rank 1 gives 1.0, at rank 3 gives 0.33, and at rank 10 gives 0.1.
MRR suits questions with one right answer, such as a help-center lookup. It ignores everything after the first relevant hit.
nDCG
Discounted cumulative gain (DCG) adds up the gain of each result, divided by a discount that grows with rank:
DCG@k = sum over positions i of gain_i / log2(i + 1)
Normalized DCG (nDCG) divides DCG by the DCG of the ideal ordering, so scores fall between 0 and 1 and can be compared across queries with different numbers of relevant documents. nDCG is the best choice when you have graded labels or several relevant documents per query.
Computing the metrics
The functions below implement all three. The example compares one query before and after reranking. Document d1 is the only relevant one. Before reranking it sits at rank 3, and after reranking it sits at rank 1.
import math
def reciprocal_rank(ranked_ids, relevant):
for i, doc_id in enumerate(ranked_ids, start=1):
if doc_id in relevant:
return 1.0 / i
return 0.0
def recall_at_k(ranked_ids, relevant, k):
return len(set(ranked_ids[:k]) & relevant) / len(relevant)
def ndcg_at_k(ranked_ids, gains, k):
dcg = sum(gains.get(d, 0) / math.log2(i + 1)
for i, d in enumerate(ranked_ids[:k], start=1))
ideal = sorted(gains.values(), reverse=True)[:k]
idcg = sum(g / math.log2(i + 1) for i, g in enumerate(ideal, start=1))
return dcg / idcg if idcg else 0.0
before = ["d3", "d7", "d1", "d9"]
after = ["d1", "d3", "d7", "d9"]
relevant = {"d1"}
print(reciprocal_rank(before, relevant), reciprocal_rank(after, relevant))
print(recall_at_k(before, relevant, 2), recall_at_k(after, relevant, 2))
print(ndcg_at_k(before, {"d1": 1}, 4), ndcg_at_k(after, {"d1": 1}, 4))The output shows how each metric reacts to the same change:
- Reciprocal rank rises from 0.33 to 1.0.
- Recall@2 rises from 0 to 1, because
d1entered the top two. - nDCG@4 rises from 0.5 to 1.0. The discount for rank 3 is 1 / log2(4) = 0.5.
Recall@4 would be 1.0 both before and after, since d1 is in the top four either way. This is why you pick k to match how many results the downstream consumer actually reads. A language model that receives the top 5 passages cares about recall@5, not recall@50.
Reading the pipeline as two measurements
Evaluate the stages separately, because they fail in different ways.
placeholderThe diagram below shows where each metric applies.
- Pool quality is recall@N, where N is the candidate depth. If a relevant document is not in the pool, no reranker can recover it.
- Ordering quality is MRR and nDCG@k on the final list.
When overall results are poor, this split tells you where to look. Low recall@N means fix retrieval (a better embedding model, hybrid retrieval, a larger N). High recall@N but low nDCG@k means the reranker is the weak part.
Running a full comparison
The harness below evaluates any function that maps a query to a ranked list of document IDs, so you can pass in the baseline and the reranked pipeline unchanged. It reuses the metric functions above.
def evaluate(search_fn, eval_set, k=10):
"""eval_set: list of (query, gains) where gains maps doc_id -> grade."""
rr, rec, ndcg = [], [], []
for query, gains in eval_set:
ranked = search_fn(query)
relevant = {d for d, g in gains.items() if g > 0}
rr.append(reciprocal_rank(ranked, relevant))
rec.append(recall_at_k(ranked, relevant, k))
ndcg.append(ndcg_at_k(ranked, gains, k))
n = len(eval_set)
return {"MRR": sum(rr) / n,
f"recall@{k}": sum(rec) / n,
f"nDCG@{k}": sum(ndcg) / n}
eval_set = [
("rotate api key", {"d1": 2, "d4": 1}),
("reset password", {"d2": 2}),
]
def baseline(query):
return {"rotate api key": ["d3", "d1", "d4"],
"reset password": ["d2", "d5", "d6"]}[query]
def reranked(query):
return {"rotate api key": ["d1", "d4", "d3"],
"reset password": ["d2", "d5", "d6"]}[query]
print(evaluate(baseline, eval_set, k=3))
print(evaluate(reranked, eval_set, k=3))In this toy run, the reranker improves the first query and leaves the second unchanged. Averages hide this, so also look at per-query results. A reranker that helps 30 queries and hurts 10 can have the same mean gain as one that helps 5 and hurts none, and the two call for different decisions.
Judging whether a difference is real
A higher average does not prove the reranker is better. With a small evaluation set, the difference may be noise. Two habits help.
- Report the per-query win, tie, and loss counts. For example, "improved 38, unchanged 55, worse 7." This is easy to read and shows how consistent the effect is.
- Run a paired test or bootstrap. Both systems are scored on the same queries, so compare them per query. A paired bootstrap resamples the queries many times and counts how often the reranker's mean beats the baseline. If it wins in more than about 95% of resamples, the gain is unlikely to be chance.
Also check the effect size. An nDCG@10 gain of 0.002 can be statistically clear on 10,000 queries and still not worth the added latency.
Common mistakes
- Unlabeled documents counted as irrelevant. Reranking surfaces documents the baseline never showed to labelers. Label the pooled top results from both systems, or the metrics undercount the reranker.
- Measuring only the top-k you chose to display. If you evaluate nDCG@3 but your application reads 10 results, you are measuring the wrong thing.
- Tuning on the test queries. Candidate depth, score thresholds, and model choice all get tuned. Do that on the development split only.
- Comparing different candidate pools. Hold the first stage fixed when you compare rerankers. Change one thing at a time.
- Ignoring queries with no relevant document. Their recall is undefined (division by zero in the function above). Remove them from the recall calculation, or track them separately as "no answer" cases.
- Reporting only one metric. MRR can rise while nDCG falls, if the reranker finds the first answer faster but pushes secondary relevant documents down.
A decision rule
Combine quality and cost into one decision:
- Measure recall@N for the first stage. If it is low, improve retrieval before adding a reranker.
- Measure MRR and nDCG@k for baseline and reranked lists on a held-out set.
- Check per-query wins and losses and a paired significance test.
- Compare the gain with the added latency per request, which later chapters cover in detail.
Ship the reranker when the gain is consistent and large enough to matter for your application.
Exercise
A query has relevant documents {d2, d6}. The baseline ranking is [d4, d2, d9, d6]. The reranked list is [d2, d6, d4, d9]. Compute reciprocal rank and recall@2 for both lists, and explain why MRR alone would understate the improvement.
Show answer
Baseline: the first relevant document (d2) is at rank 2, so RR = 0.5. The top two are {d4, d2}, which contain one of two relevant documents, so recall@2 = 0.5. Reranked: d2 is at rank 1, so RR = 1.0. The top two are {d2, d6}, both relevant, so recall@2 = 1.0. MRR only looks at the first relevant hit, so it credits the move of d2 from rank 2 to 1 but ignores that d6 moved from rank 4 to rank 2. Recall@2 and nDCG capture that second improvement.
Exercise
Your first stage retrieves N = 20 candidates and recall@20 is 0.62. After reranking, nDCG@10 improves from 0.41 to 0.47. A teammate proposes switching to a larger cross-encoder. What should you check first, and why?
Show answer
Check the candidate pool. Recall@20 of 0.62 means 38% of relevant documents never reach the reranker, so no reranker can retrieve them. Raising N, using hybrid retrieval, or improving the embedding model may give a larger gain than a bigger cross-encoder. Measure recall@N at a larger N (for example 50 or 100) and rerun nDCG@10 on the held-out set before changing the model.