Sub topic 13
Measuring whether rewriting helps
This chapter assumes you can run a retrieval function that returns ranked document ids. It also assumes you have a few questions with known relevant documents, and that you know the rewriting techniques from earlier chapters. Rewriting adds model calls, so you should keep a technique only if the measurements show it helps.
Build a small labeled set
Collect 30 to 100 real questions. Include follow-ups, multi-part questions, and questions that use different vocabulary from your documents. For each question, record the ids of the documents that contain the answer. A small set that matches your real traffic is more useful than a large synthetic one.
Split the questions by failure mode, such as vocabulary mismatch, missing context, and multi-part. A technique may help one group and hurt another, and an overall average hides that.
Choose retrieval metrics
Score retrieval on its own before you look at the generated answer.
- Recall@k is the fraction of relevant documents that appear in the top k results. It tells you whether the evidence reached the model.
- Reciprocal rank (MRR when averaged) is 1 divided by the rank of the first relevant document. It rewards putting a good document near the top.
Multi-step retrieval often needs several documents for one question, so recall@k is usually the main metric.
from typing import Callable
Case = tuple[str, set[str]]
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
if not relevant:
return 0.0
return len(set(retrieved[:k]) & relevant) / len(relevant)
def reciprocal_rank(retrieved: list[str], relevant: set[str]) -> float:
for rank, doc_id in enumerate(retrieved, start=1):
if doc_id in relevant:
return 1.0 / rank
return 0.0
def compare(
cases: list[Case],
baseline: Callable[[str], list[str]],
candidate: Callable[[str], list[str]],
k: int = 5,
) -> None:
wins = losses = 0
base_total = cand_total = 0.0
for question, relevant in cases:
b = recall_at_k(baseline(question), relevant, k)
c = recall_at_k(candidate(question), relevant, k)
base_total += b
cand_total += c
wins += c > b
losses += c < b
n = len(cases)
print(f"baseline recall@{k}: {base_total / n:.2f}")
print(f"candidate recall@{k}: {cand_total / n:.2f}")
print(f"better on {wins}, worse on {losses}, of {n}")
cases = [
("how do I reset my password", {"auth-1"}),
("what about its pricing", {"price-1", "price-2"}),
]
base = lambda q: ["misc-9", "auth-1"] if "password" in q else ["misc-3"]
cand = lambda q: ["auth-1"] if "password" in q else ["price-1", "misc-3"]
compare(cases, base, cand)Both arguments are plain functions from a question to a ranked list. The baseline runs the raw question. The candidate runs the full rewrite pipeline, such as condensing, expansion, and fusion.
Read the results
Look at the win and loss counts as well as the averages. A technique with a higher mean but many losses may be harming questions that already worked. Read the losing cases by hand and check what the rewritten query looked like. Query drift, where the rewrite changes the meaning of the question, shows up here.
Weigh gain against cost
Measure latency and model calls in the same run. Record the median and the 95th percentile, because iterative loops have a long tail. Then compare the gain with the cost.
| Result | Decision |
|---|---|
| Large recall gain, small latency increase | Keep |
| Small gain, extra model call on every query | Restrict to the failure mode it fixes, using routing |
| No gain or more losses than wins | Drop |
Common errors
- Tuning on the test set. If you edit prompts until the same 50 questions pass, the score no longer predicts live results. Keep some questions held out.
- Judging only the final answer. Generation quality varies from run to run, which hides retrieval changes. Score retrieval first, then check answers.
- Testing on easy questions. Rewriting cannot help questions that the raw query already answers.
- Ignoring noise. With a small set, a difference of one or two questions may be chance. Rerun, and treat small gaps cautiously.
Exercise
A multi-query expansion change raises average recall@5 from 0.62 to 0.66, but it is worse on 12 of 60 questions and adds one model call per query. What should you check before keeping it?
Show answer
Read the 12 losing questions to see whether the generated variants drifted from the original meaning. Look at which failure-mode groups gained and which lost, and consider routing so expansion runs only where it helps. Also measure latency, including the 95th percentile. A 0.04 gain on 60 questions may be within noise, so rerun it or add more questions.