Sub topic 2
Why We Chunk: Retrieval Precision, Recall, and Noise
This chapter assumes you know basic Python, what an embedding is, how vector similarity search ranks results, and the retrieve-then-generate idea behind RAG. It also assumes you know what a token is. The chapter explains the reasons for splitting documents, so that later chapters on size, overlap, and strategies have a clear purpose.
The core problem: one vector per unit of text
A retriever compares a query vector with stored vectors and returns the closest ones. Each stored vector summarizes one unit of text. That unit is the chunk, and you decide where its edges fall.
An embedding model compresses a whole passage into a single point. If the passage covers one topic, the point sits near that topic. If it covers five topics, the point lands somewhere between them and sits close to none. A query about one of the five topics then scores lower than it should.
You can see this with a toy model. The code below uses word counts as a stand-in for an embedding and measures cosine similarity. Real embedding models are far better at semantics, but they show the same dilution effect when a text mixes topics.
import math
import re
from collections import Counter
STOPWORDS = {"a", "an", "the", "to", "of", "and", "is", "in", "for", "on",
"my", "do", "i", "how", "your", "by", "are"}
def vectorize(text):
words = re.findall(r"[a-z]+", text.lower())
return Counter(w for w in words if w not in STOPWORDS)
def cosine(a, b):
dot = sum(a[w] * b[w] for w in a if w in b)
norm_a = math.sqrt(sum(v * v for v in a.values()))
norm_b = math.sqrt(sum(v * v for v in b.values()))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot / (norm_a * norm_b)
paragraphs = {
"refunds": "Refunds are issued within 14 days. Refund requests need an "
"order number. Refunds return to the original payment method.",
"shipping": "Shipping takes 3 to 5 days. Express shipping costs extra. "
"Tracking numbers arrive by email after shipping.",
"password": "To reset your password, open Settings and choose Reset "
"password. A reset link arrives by email.",
}
document = " ".join(paragraphs.values())
query = vectorize("How do I reset my password?")
print("whole document:", round(cosine(query, vectorize(document)), 3))
for name, text in paragraphs.items():
print(name + ":", round(cosine(query, vectorize(text)), 3))Running it prints:
whole document: 0.464
refunds: 0.0
shipping: 0.0
password: 0.811The password paragraph scores 0.811 on its own. Inside the combined document, the refund and shipping words add length without adding matches, so the score falls to 0.464. In a real index, a mixed document with a 0.46 score can lose to a short, mostly irrelevant page that mentions passwords once. That is the first reason to chunk: it keeps each vector about one thing.
Precision and recall at the chunk level
Two measures describe retrieval quality. Both depend on what you call "relevant."
- Precision@k is the share of the top k retrieved chunks that are relevant. It measures how much of what you retrieved is useful.
- Recall@k is the share of all relevant chunks that appear in the top k. It measures how much of what you needed you actually got.
Suppose a question needs information from 3 chunks in your corpus. You retrieve k = 5 chunks, and 2 of them are among those 3. Precision@5 is 2/5 = 0.4. Recall@5 is 2/3 ≈ 0.67.
Chunk size moves both numbers, usually in opposite directions:
- Large chunks tend to raise recall, because the needed fact is more likely to sit inside some retrieved chunk. They lower precision, because most of each chunk is unrelated to the query.
- Small chunks tend to raise precision, because each one is focused. They can lower recall, because the full answer may be spread across several chunks and k may not be large enough to cover them all.
"Relevant" is therefore partly a property of your chunking. If a fact is split across two chunks, neither one contains the answer by itself. A later chapter shows how to measure this on a test set.
Noise: what the generator has to read
Retrieval does not end the pipeline. The retrieved chunks go into the prompt, and the language model reads them to write the answer. Irrelevant text in that prompt is noise, and it costs you in three ways:
- Tokens and money. Every token in the prompt is billed and adds latency. A 2,000-token chunk that holds a 40-token answer wastes most of what you pay for.
- Distraction. Models can latch onto a plausible but wrong passage that sits next to the right one. A refund policy for one product line can leak into an answer about another.
- Position effects. Research on long prompts has found that models often use information in the middle of a long context less reliably than information at the start or end. Padding the prompt with noise can push the useful passage into a weak position. The size of this effect varies by model, so test it on yours.
A larger context window does not remove the need to chunk. It raises the limit on what fits, but it does not change the retrieval problem above, and it does not make noisy prompts cheaper or more accurate.
The two failure modes
Chunks that are too large and chunks that are too small fail in different ways.
Too large
A chunk that spans several topics gives you a diluted vector and a noisy prompt, as in the example above. Large chunks also hit the input limit of the embedding model. Text past that limit is usually cut off silently, so the end of the chunk never influences its vector. The next chapter covers those limits.
Too small
A chunk of one or two sentences is easy to match but often cannot be understood alone. Consider this passage:
Orders can be cancelled in the first hour. After that, the warehouse
has started packing. It must then be returned for a refund.If it is split after each sentence, the third chunk reads "It must then be returned for a refund." The word "It" has no referent, and a reader cannot tell what must be returned. A query about returns might match this chunk, but the model gets a fragment it cannot use. Small chunks also multiply the number of vectors you store and search, and they make the top-k list fill up with fragments of the same passage.
What a good chunk looks like
A useful chunk has three properties:
- It is about one thing. The vector represents a single idea, so similarity scores mean something.
- It can be understood on its own. Someone reading only that chunk, with no neighbors, can tell what it is about and what its terms refer to.
- It is small enough to be cheap. Several chunks must fit in the prompt with room for the question and instructions.
These properties pull against each other, so there is no universal best size. Much of this tutorial is about techniques that ease the conflict. Overlap repeats text across boundaries. Structure-aware splitting cuts at headings instead of arbitrary points. Metadata restores context a chunk has lost. Parent-child retrieval searches with small chunks and returns larger ones.
Chunk boundaries decide what is findable
The boundary is where the information loss happens. A boundary placed in the middle of a sentence or a table row can separate a question from its answer, a code comment from its code, or a condition from the rule it modifies.
Consider a policy that says: "Refunds are available for 14 days. This does not apply to digital goods." If a boundary falls between the two sentences, then a query about refunds on digital goods retrieves the first chunk, which gives the wrong answer with high confidence. The exception sits in a chunk that may never be retrieved.
This kind of error is hard to catch by reading results casually, because each retrieved chunk looks reasonable. It shows up only when you test with questions whose answers depend on both sides of a boundary.
Common mistakes at this stage
- Chunking by whatever the embedding model accepts. The input limit is a ceiling, not a target. A chunk can fit the limit and still mix five topics.
- Treating chunks as a storage detail. Chunk design changes which answers are findable, so it belongs in your quality work, not only in your ingestion script.
- Optimizing precision alone. Very small chunks give impressive precision on easy questions and fail when an answer needs surrounding context.
- Assuming a bigger context window fixes it. Retrieving more chunks raises recall, but it also raises noise and cost, and the position effects can offset the gain.
- Ignoring document type. Prose, code, tables, and FAQs fail differently. Splitting a table row from its header leaves numbers with no meaning.
Summary of the trade-offs
| Property | Larger chunks | Smaller chunks |
|---|---|---|
| Vector focus | Diluted across topics | Focused on one idea |
| Precision@k | Lower | Higher |
| Recall of full answers | Higher, since answers stay together | Lower at a fixed k, since answers split |
| Prompt noise and cost | Higher | Lower per chunk, but more chunks needed |
| Self-contained meaning | Usually good | Often lost |
| Main failure | Noise and truncation | Fragments without context |
Exercise
A question needs information found in 4 chunks of your corpus. You retrieve k = 6 chunks, and 3 of them are among those 4. Compute precision@6 and recall@6. Then say which way each number would likely move if you cut every chunk to half its size, and why.
Show answer
Precision@6 = 3/6 = 0.5. Recall@6 = 3/4 = 0.75. With chunks half the size, each retrieved chunk is more focused, so precision would likely rise. The needed information would now be spread over more, smaller chunks, so with k fixed at 6 you would likely cover less of it and recall would likely fall. The result depends on the corpus, so measure it on test questions.
Exercise
Using the toy code in this chapter, you add a fourth paragraph about warranty terms to the document and rerun the query "How do I reset my password?". Without running anything, predict whether the whole-document score rises, falls, or stays the same, and whether the password paragraph's own score changes. Explain.
Show answer
The whole-document score falls, assuming the warranty paragraph does not contain "reset" or "password". The dot product with the query stays the same, but the document vector gains new words, so its length grows and the cosine similarity shrinks. The password paragraph's own score stays 0.811, because that paragraph's vector did not change. This is the dilution effect that chunking avoids.