Sub topic 12
Measuring chunking quality with recall@k
This chapter assumes you know basic Python, what an embedding is, how vector similarity search ranks results, and what a token is. You should also have read the earlier chapters on chunk size, overlap, and the fixed-size and recursive splitters. Here you will learn how to compare chunking settings with numbers instead of intuition.
Why you need a measurement
Chunking choices feel arbitrary. Is 200 words better than 400? Does overlap help? Reading a few retrieved results by hand will not settle it, because each setting helps some questions and hurts others.
A small evaluation set fixes this. You write test questions, record which parts of the source documents answer them, and then check how often each chunking configuration retrieves those parts. Run the same questions against every configuration and compare the scores.
The evaluation set
An evaluation set has three parts per item:
- A question a real user might ask.
- The source document, and the span of text inside it, that answers the question.
- Optionally, a short reference answer.
Twenty to fifty questions is enough to see large differences. Draw them from real user queries or support tickets when you can. If you generate questions with a language model, review them by hand. Generated questions often copy wording from the source, which makes keyword-like retrieval look better than it will be in production.
EVAL_SET = [
{
"question": "How long do refunds take to process?",
"doc_id": "refund-policy",
"answer_span": "Refunds are processed within 5 to 7 business days",
},
{
"question": "Which regions support single sign-on?",
"doc_id": "sso-guide",
"answer_span": "Single sign-on is available in the US, EU, and UK regions",
},
]The key problem: chunk IDs change
Recall@k needs a list of "relevant" items. If your relevant items are chunk IDs, the labels become useless as soon as you change the chunker, because a different chunker produces different chunks. You would have to relabel for every experiment.
The fix is to label the answer span in the source document, not the chunk. After chunking, mark a chunk as relevant if it contains the answer span. Then the same labels work for every configuration.
def relevant_chunk_ids(chunks, answer_span):
"""chunks: list of dicts with 'id', 'doc_id', 'text'."""
return [c["id"] for c in chunks if answer_span in c["text"]]This check has a consequence worth knowing. If a chunker splits the answer span across two chunks, no chunk contains the whole span, so the question has no relevant chunk and scores zero. That is the correct result, because neither chunk alone carries the full answer. It is also how this metric exposes boundary damage. Keep spans short enough (one sentence or a key phrase) that a score of zero means a real split and not an overly long label.
Whitespace can also break the match. If the splitter normalizes newlines or spaces, normalize both the span and the chunk text the same way before comparing.
Recall@k
Recall@k asks: of the relevant items, what fraction appear in the top k results? This function is from the chapter's planned code.
def recall_at_k(retrieved_ids, relevant_ids, k=5):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)Take a question with two relevant chunks, and a retriever that returns [c7, c2, c9, c4, c1]. If c2 and c4 are relevant, both are in the top 5, so recall@5 is 1.0. If only c2 were in the top 5, recall@5 would be 0.5.
Note the behavior when relevant_ids is empty: the function returns 0.0. For chunking evaluation, an empty list usually means the chunker split the answer across chunks or the span did not match. Count these cases separately so you can see them.
Choosing k
Pick k to match how your application uses results. If the generator receives the top 4 chunks, measure recall@4. A recall@20 score tells you little if only four chunks reach the prompt. It is also useful to report two values, for example k=1 and k=5. Recall@1 shows how well the best chunk ranks. Recall@5 shows whether the answer is available at all.
A complete evaluation loop
The loop below chunks the corpus, builds an index, retrieves for each question, and averages recall@k. To keep it runnable without a model download or API key, it uses a simple bag-of-words cosine similarity as a stand-in for an embedding model. In a real project, replace embed with your embedding call. The measurement code stays the same.
import math
from collections import Counter
def embed(text):
return Counter(text.lower().split())
def cosine(a, b):
dot = sum(a[t] * b[t] for t in a if t in b)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def recall_at_k(retrieved_ids, relevant_ids, k=5):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)
def chunk_words(text, size=200, overlap=40):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
def build_index(docs, chunker):
index = []
for doc_id, text in docs.items():
for n, piece in enumerate(chunker(text)):
index.append({
"id": f"{doc_id}#{n}",
"doc_id": doc_id,
"text": piece,
"vec": embed(piece),
})
return index
def retrieve(index, question, k):
q = embed(question)
ranked = sorted(index, key=lambda c: cosine(q, c["vec"]), reverse=True)
return [c["id"] for c in ranked[:k]]
def evaluate(docs, eval_set, chunker, k=3):
index = build_index(docs, chunker)
scores, unlabeled = [], 0
for item in eval_set:
in_doc = [c for c in index if c["doc_id"] == item["doc_id"]]
relevant = [c["id"] for c in in_doc if item["answer_span"] in c["text"]]
if not relevant:
unlabeled += 1
scores.append(recall_at_k(retrieve(index, item["question"], k), relevant, k))
return sum(scores) / len(scores), unlabeled
docs = {
"refund-policy": (
"Customers may request a refund within 30 days of purchase. "
"Refunds are processed within 5 to 7 business days after approval. "
"Digital goods are refundable only if they have not been downloaded."
),
"sso-guide": (
"Single sign-on is available in the US, EU, and UK regions. "
"Administrators configure it from the security settings page."
),
}
eval_set = [
{"question": "How long do refunds take to process?",
"doc_id": "refund-policy",
"answer_span": "Refunds are processed within 5 to 7 business days"},
{"question": "Which regions support single sign-on?",
"doc_id": "sso-guide",
"answer_span": "Single sign-on is available in the US, EU, and UK regions"},
]
for size, overlap in [(8, 2), (20, 4), (60, 10)]:
chunker = lambda t, s=size, o=overlap: chunk_words(t, s, o)
score, missing = evaluate(docs, eval_set, chunker, k=2)
print(f"size={size:>3} overlap={overlap:>2} recall@2={score:.2f} no_relevant_chunk={missing}")Running this prints one line per configuration. On a corpus this tiny, the very small chunks tend to split the answer spans, which shows up in the no_relevant_chunk count, while the larger chunks keep spans whole. Real corpora produce subtler differences, so treat these three lines as a demonstration of the procedure and not as a result.
What the loop does
The diagram shows the order of steps. Only the chunker changes between runs. Everything else stays fixed.
Keep the comparison fair
A chunking experiment is only meaningful if you change one thing at a time.
- Use the same embedding model, the same similarity function, and the same k across runs.
- Compare chunkers at a similar average chunk size, or sweep size explicitly. A recursive splitter that happens to produce larger chunks may win because of size, not because of its boundaries.
- Check the number of chunks in each configuration. Smaller chunks mean more candidates, which makes a fixed k cover less of the corpus.
- Keep the question set fixed. If you edit questions after seeing results, you are tuning to the test.
Limits of recall@k
Recall@k is useful but narrow. Know what it does not tell you.
| Gap | Why it matters |
|---|---|
| Ignores ranking inside the top k | Rank 1 and rank k score the same. Add mean reciprocal rank (MRR) if order matters. |
| Ignores noise | A top 5 full of irrelevant chunks scores the same as a clean top 5. Precision@k measures this. |
| Rewards big chunks | A large chunk contains the span more often, so recall rises while the prompt fills with unrelated text. |
| Ignores answer quality | The right chunk can be retrieved and the model can still answer badly. |
| Depends on the labels | Wrong or overly strict spans distort every score. |
The third gap deserves attention. Recall@k alone pushes you toward bigger chunks, so pair it with a cost measure. Track the average number of tokens placed in the prompt, which is roughly k times the average chunk size. A configuration that gains 0.02 recall and doubles prompt tokens is usually a bad trade.
For a stronger check, run a small end-to-end test. Feed the retrieved chunks to the generator and grade the answers against the reference answers, by hand or with a rubric. Use recall@k to narrow the options cheaply, then confirm the top two or three configurations end to end.
Common errors
- Labeling chunk IDs instead of spans. Labels go stale with every chunker change. Label spans.
- Matching the span across documents. Short spans may appear in several documents. Filter by
doc_idfirst, as the loop does. - Tiny evaluation sets. With five questions, one question moves the score by 0.2. Use enough questions that single items cannot decide the result.
- Leaking test text into the system. If you tune the question wording and the chunk size together, the score becomes optimistic. Hold back a few questions you never tune on.
- Reading differences as real when they are noise. If two configurations differ by one or two questions, treat them as tied and choose the simpler or cheaper one.
- Measuring only the average. Look at which questions fail. Failures that cluster on tables, code, or long procedures point to a structure problem that a different splitter can fix.
Exercises
Exercise
Your evaluation labels list chunk IDs such as "refund-policy#3". Why does this make chunking experiments unreliable, and what should you label instead?
Show answer
A different chunker or setting produces different chunks, so the IDs no longer point to the same text and the labels must be redone for every experiment. Label the answer span in the source document, then mark any chunk that contains the span as relevant after chunking. The same labels then work for every configuration.
Exercise
A question has three relevant chunks. The retriever returns chunk IDs [c1, c8, c3, c5, c9] and c1, c3, and c7 are relevant. What is recall@5, and what is recall@2?
Show answer
In the top 5, c1 and c3 are found out of three relevant chunks, so recall@5 = 2/3, about 0.67. In the top 2 only c1 is found, so recall@2 = 1/3, about 0.33.
Exercise
Configuration A (large chunks) scores recall@5 of 0.90 and configuration B (medium chunks) scores 0.86. A sends about twice as many tokens to the model. Which would you pick, and what else would you check?
Show answer
Prefer B unless the 0.04 gap is clearly more than noise and matters for the application. A's higher recall may come only from large chunks containing the answer span more often, while the extra tokens add cost and noise. Check precision@k, the average prompt tokens, which questions differ, and an end-to-end answer grade on the failing questions.