Sub topic 3
Building an evaluation set with relevance labels
Every metric later in this tutorial, including precision@k, recall@k, MRR, and nDCG, is computed against an evaluation set. If the set is small, skewed, or mislabeled, the numbers will look precise and still mislead you. This chapter covers how to build a set you can trust.
This chapter assumes you know how a RAG pipeline works (chunking, embedding, vector search, prompting), can read Python, and know precision and recall from classification. The earlier chapters in this tutorial separated retrieval failures from generation failures. The evaluation set is where you start measuring them separately.
What an evaluation set contains
An evaluation set is a fixed collection of test cases. Each case has at least these parts:
- A question. It is phrased the way a real user would phrase it.
- Relevance labels. These say which documents or chunks in your corpus contain the information needed to answer the question.
- Optionally, a reference answer. A short, verified answer that you can compare against. This is useful for correctness checks, but the retrieval metrics do not need it.
The labels are the part that makes retrieval measurable. Without them you can only judge retrieval by reading results, which does not scale and is not repeatable.
Labels come in two forms:
| Label type | Example | Works with |
|---|---|---|
| Binary | `d2` is relevant, `d9` is not | precision@k, recall@k, hit rate, MRR |
| Graded | `d2` = 3, `d1` = 1, `d9` = 0 | nDCG, and all binary metrics after you pick a threshold |
Graded labels carry more information, and you can always collapse them to binary by treating any grade of 1 or higher as relevant. You cannot go the other way. If you can afford the extra labeling effort, record grades.
Choosing the unit you label
Decide first what a "document" means in your labels. You have two common options.
- Document-level labels name the source file or page. They survive changes to your chunking, so you can re-chunk without relabeling.
- Chunk-level labels name the exact chunk that contains the answer. They are more precise, but every labeled ID becomes invalid when you change chunk size or overlap.
A practical compromise is to label at the document level and record the answer span as text. When you change chunking, map the span back to the new chunks automatically. At minimum, store a stable ID for each chunk and keep the chunking configuration version with the evaluation set.
Where questions come from
Mix several sources, because each has a blind spot.
- Real user queries. Logs, support tickets, and search history show how people actually ask. They are the most representative source, but they are often short, ambiguous, or full of typos. Remove personal data before you store them.
- Domain expert questions. Ask people who know the material to write hard questions. Experts cover rare but important cases that logs miss.
- Synthetic questions. Prompt an LLM to write a question that a given passage answers. This is cheap and gives you a label for free, because the source passage is relevant by construction. The risk is lexical overlap: generated questions often reuse words from the passage, so keyword-heavy retrievers look better than they will on real traffic. Review a sample and rewrite questions that copy the passage's wording.
Whatever the mix, cover the question types your system will face:
- Simple lookups with one relevant passage.
- Multi-hop questions that need two or more passages.
- Questions whose answer is spread across many chunks.
- Questions with near-duplicate distractors, such as two product versions with different warranty terms.
- Unanswerable questions, where the corpus has no answer.
Unanswerable questions deserve special attention. A good system should retrieve nothing useful and decline to answer. If every question in your set is answerable, you cannot detect a system that invents answers. Label these with an empty relevant set, and remember that recall is undefined for them, which is why the recall_at_k function earlier in this tutorial returns None in that case.
The labeling process
Pool candidates, do not label from one retriever
The obvious shortcut is to run your current retriever, show its top results to annotators, and mark which are relevant. This biases the set. Documents your retriever never returns are never labeled, so they count as non-relevant by default. A better retriever that surfaces those documents will be punished for it.
To reduce this bias, build a candidate pool from several sources: dense retrieval, keyword search (BM25), and a deeper top-k than you plan to evaluate at. Annotators label the pooled results. Unlabeled documents still count as non-relevant, but the pool makes that assumption far less harmful.
Write labeling guidelines
Annotators disagree most when "relevant" is vague. Write a short rubric with examples. A common graded scale:
- 3, directly answers. The passage contains the answer in a form a reader could quote.
- 2, partial answer. It contains a necessary piece but not the whole answer.
- 1, related background. The topic matches, but the passage does not help answer the question.
- 0, not relevant.
Decide in advance how to handle near-duplicates, outdated versions, and passages that answer the question only when combined with another one.
Measure annotator agreement
Have a second person label a sample, typically 10 to 20 percent of questions. Compare their labels with Cohen's kappa, which corrects raw agreement for chance. A kappa below roughly 0.6 usually means the guidelines are unclear, and the fix is to rewrite them, not to average the labels. Resolve each disagreement by discussion and record the decision in the guidelines.
A storage format and a validator
Store the set as JSON Lines, one case per line. It diffs cleanly in version control and streams easily. The code below defines a small set, checks it for common mistakes, and summarizes question types.
import json
from collections import Counter
RAW = """\
{"qid": "q1", "type": "lookup", "question": "How long is the warranty?", "relevant": {"d2": 3, "d1": 1}, "answerable": true}
{"qid": "q2", "type": "multi_hop", "question": "Does the warranty cover a repaired part?", "relevant": {"d5": 2, "d1": 2}, "answerable": true}
{"qid": "q3", "type": "unanswerable", "question": "What is the CEO's salary?", "relevant": {}, "answerable": false}
{"qid": "q4", "type": "lookup", "question": "How do I reset the device?", "relevant": {"d9": 3}, "answerable": true}
"""
CORPUS_IDS = {"d1", "d2", "d5", "d7", "d9"}
REQUIRED = {"qid", "type", "question", "relevant", "answerable"}
def load_records(text):
return [json.loads(line) for line in text.splitlines() if line.strip()]
def validate(records, corpus_ids, max_grade=3):
problems = []
seen = set()
for r in records:
qid = r.get("qid", "<missing qid>")
missing = REQUIRED - r.keys()
if missing:
problems.append(f"{qid}: missing fields {sorted(missing)}")
continue
if qid in seen:
problems.append(f"{qid}: duplicate qid")
seen.add(qid)
for doc_id, grade in r["relevant"].items():
if doc_id not in corpus_ids:
problems.append(f"{qid}: unknown document id {doc_id}")
if not 0 <= grade <= max_grade:
problems.append(f"{qid}: grade {grade} outside 0-{max_grade}")
has_labels = any(g > 0 for g in r["relevant"].values())
if r["answerable"] and not has_labels:
problems.append(f"{qid}: answerable but has no relevant documents")
if not r["answerable"] and has_labels:
problems.append(f"{qid}: unanswerable but has relevant documents")
return problems
records = load_records(RAW)
print(validate(records, CORPUS_IDS)) # []
print(Counter(r["type"] for r in records))
records.append(
{"qid": "q5", "type": "lookup", "question": "Where is the serial number?",
"relevant": {"d99": 5}, "answerable": True}
)
for p in validate(records, CORPUS_IDS):
print(p)
# q5: unknown document id d99
# q5: grade 5 outside 0-3The validator catches mistakes that otherwise surface later as silently wrong metrics: a typo in a document ID makes a relevant document look missing, and so lowers recall for no real reason. Run it in your test suite every time the set or the corpus changes.
How big should the set be
There is no universal number, but there are useful anchors:
- Under 30 questions can catch crashes and gross failures. It cannot reliably show that one configuration beats another.
- 100 to 300 questions is a reasonable starting range for comparing configurations on a single domain.
- More is needed if you want to compare many question types separately, because each subgroup needs enough cases of its own.
The size you need depends on how small a difference you want to detect. A later chapter shows how to put a confidence interval around a score so you can check whether a change is larger than the noise. Until then, treat differences of a few points on a small set with suspicion.
Keeping the set honest
- Hold out a test split. If you tune chunk size, prompts, and retrieval settings against the same questions, you will overfit to them. Keep a portion untouched until you are ready to make a final comparison.
- Version it. Record the evaluation set version, corpus snapshot, and chunking configuration alongside every reported score. A score without these is not reproducible.
- Watch for staleness. When documents are updated, labels can become wrong. A relevant passage may be rewritten or deleted. Re-validate after corpus changes.
- Do not leak. If you use LLM-generated questions, keep the same documents out of any fine-tuning data for the retriever or generator you are testing.
Exercise
A teammate builds labels by running the current retriever, showing its top 5 results to annotators, and marking which are relevant. Later, a new retriever scores lower precision@5 on this set, even though reviewers think its answers are better. Give one likely cause and one fix.
Show answer
The labels are biased toward the old retriever. Documents it never returned were never reviewed, so they count as non-relevant, and the new retriever is penalized when it returns correct passages that nobody labeled. Fix it by pooling candidates from several retrievers (for example dense search and BM25, at a deeper top-k) before labeling, and by labeling the new retriever's results that are missing from the pool.
Exercise
Why should an evaluation set include unanswerable questions, and what should their relevant set contain?
Show answer
Without them you cannot detect a system that answers confidently when the corpus has no answer. Their relevant set is empty, they are marked as not answerable, and recall@k is undefined for them, so exclude them from recall averages and score them with a separate check, such as whether the system declines to answer.