Papa Programmer
Lesson 04 of 15

How to chunk documents

9 min read

Optional

Why documents are split

A retriever cannot return a whole 40-page manual for every question. The manual would fill the model's context, and most of it would be unrelated. So the manual is split into ChunkingSplitting a document into passages that a retriever can return one at a time. Chunk size and boundaries decide what the model can read, so a bad cut can separate a rule from its condition. in advance, and the search ranks the chunks.

The chunk is the unit of everything that follows. Search compares a question with chunks. The model reads chunks. A citation points to a chunk. If a chunk is cut in the wrong place, no later step can repair it.

The size trade-off

Small chunksLarge chunks
Match a questionClosely, because they hold one ideaLoosely, because they hold several
Keep the surrounding detailOften notUsually
Cost in the promptLow for each chunk, so you can return moreHigh for each chunk
Typical failureA rule is separated from its conditionThe answer is buried among other text
Small chunks and large chunks

Size is easiest to think about in TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters., because the model's context is measured in tokens. A few hundred tokens is a common starting point, and the right size for your documents comes from testing, not from a rule. Questions that need one fact favour small chunks. Questions that need an explanation favour larger ones.

Fixed windows and overlap

The simplest method cuts the text every size words. It is easy to write and it ignores meaning, which is its weakness. The program below cuts a short policy into 12-word windows, first with no overlap and then with an overlap of 4 words.

python
text = "You can return an unused bike within 30 days. The bike must still have its original tyres. A refund goes to the original payment method within 5 business days."
words = text.split()

def windows(words, size, overlap):
	step = size - overlap
	return [" ".join(words[start:start + size]) for start in range(0, len(words) - overlap, step)]

for overlap in (0, 4):
	print(f"overlap {overlap}")
	for chunk in windows(words, 12, overlap):
		print("  ", chunk)

It prints:

text
overlap 0
   You can return an unused bike within 30 days. The bike must
   still have its original tyres. A refund goes to the original payment
   method within 5 business days.
overlap 4
   You can return an unused bike within 30 days. The bike must
   days. The bike must still have its original tyres. A refund goes
   tyres. A refund goes to the original payment method within 5 business
   method within 5 business days.

With no overlap, the first cut falls inside a sentence: "The bike must" ends one chunk, and "still have its original tyres" starts the next. A question about the condition for a return finds half of it. With an overlap of 4 words, the second chunk repeats the end of the first, so one chunk holds the whole sentence "The bike must still have its original tyres."

Overlap costs storage and creates repeats, so keep it modest. Between 10 and 20 per cent of the chunk size is a usual choice, and you can test it like any other setting.

Split on the structure instead

A document already has natural joints: headings, paragraphs, list items. Cutting there keeps related sentences together. This is why the previous Lesson kept the headings.

python
document = """# Returns
You can return an unused bike within 30 days.
The bike must still have its original tyres.

# Refunds
A refund goes to the original payment method within 5 business days.

# Shipping
Standard shipping takes 3 to 5 business days."""

def by_heading(document):
	chunks = []
	for section in document.split("\n# "):
		heading, *body = section.lstrip("# ").split("\n")
		chunks.append({"heading": heading, "text": " ".join(line for line in body if line)})
	return chunks

for chunk in by_heading(document):
	print(chunk["heading"], "|", len(chunk["text"].split()), "words |", chunk["text"])

It prints:

text
Returns | 17 words | You can return an unused bike within 30 days. The bike must still have its original tyres.
Refunds | 12 words | A refund goes to the original payment method within 5 business days.
Shipping | 8 words | Standard shipping takes 3 to 5 business days.

Each chunk is one topic, and the heading travels with it. Keeping the heading matters: a chunk that says only "30 days" is hard to match, and one that says "Returns: 30 days" is easy. Many systems add the heading to the start of the chunk's text for this reason.

Splitting by structure has its own limit. A section can be one line or ten pages. When a section is too long, split it again by paragraph or sentence, with a size limit as the fallback.

Return the neighbours

One more idea removes much of the size dilemma. Search small chunks, because they match well, and then return the larger section around the best one. This is often called parent-child retrieval: the small chunk finds the place, and its parent supplies the context.

Choosing a method

  1. Start with the document's structure: headings, then paragraphs.
  2. Add a size limit, and split anything longer by sentence.
  3. Add a small overlap where chunks are cut inside a section.
  4. Read twenty chunks yourself. Each should make sense alone.
  5. Test the settings against real questions, as the Lesson Measuring retrieval quality shows.
Cut at the jointsHeadings and paragraphs keep related sentences together.
Size is a tradeSmall chunks match closely. Large chunks keep detail.
Read your chunksEach one should make sense when it is read alone.

Your reading position is saved

0%

0 of 15 complete

Contents

Learning tools