Skip to content

Courses / RAG Systems / Module 3

Module 3: Chunking strategies: structural, semantic, late chunking, contextual retrieval

8 h · theory 2 · hands-on 3 · project 2 · revision 1

You will be able to

  • Compare fixed, structural and semantic chunking on your golden set
  • Add contextual headers to chunks
  • Explain late chunking and parent-child retrieval
  • Pick chunk size from measurements, not habit

Capstone increment: Configurable chunker with a measured choice of strategy recorded in an ADR.

Job-description skills: Chunking · Lab tools: docling, sentence-transformers

1. Chunking is a retrieval decision

A chunk is the unit you retrieve and the unit you pay for in context. Too small, and the facts needed for an answer land in different chunks, or a chunk loses the words that say what it is about. Too large, and each embedding averages several topics so it matches nothing well, and every answer drags in hundreds of irrelevant tokens.

Try the lab below: change the chunk size, overlap, number of retrieved chunks and contextual headers, and watch which questions survive. An answer only counts if one retrieved chunk contains every fact it needs.

Chunking labAn 8-section leave and travel policy, 8 questions. Change how it is chunked and watch which answers survive retrieval.

16 chunks · answered 3 of 8 · answers split across chunks 4 · about 27 context tokens per question

How many annual leave days do I earn, and how many can I carry over?missed: answer split
When do I need a medical certificate for sick leave?answered
How much paid leave do adoptive parents get?missed: answer split
What is my notice period for resignation after confirmation?missed: answer split
What is the daily allowance in metro cities?answered
Do expensive hotel bills need approval, and from whom?answered
What is the deadline for submitting expense claims?missed: answer split
How often are fully remote arrangements reviewed?missed: wrong chunk retrieved

Click a question to see what was retrieved for it. Facts it needs: 24 days of annual leave + 10 unused days carry over

  1. Chunk 1 · 20 words
    Annual leave. Full-time employees earn 24 days of annual leave per year. Leave accrues monthly at two days per month.
Guided experiments
  1. Fixed size, 20 words, no overlap, k = 1. How many questions are answered, and how many answers are split across two chunks?
  2. Set size 30 and k = 3, then add 10 words of overlap. Which answer does the overlap rescue, and what does overlap cost you in index size?
  3. Push fixed chunks to 200 words. Every question is answered. Compare the tokens per question with “by section” at 60 words. Which would you pay for at a million questions a month?
  4. Switch to “by section”, 20 words, k = 1, and turn contextual headers on and off. Which question flips, and why does a heading help a chunk that never repeats the topic word?

2. Fixed, recursive, structural and semantic

Fixed-size chunking cuts every N tokens with some overlap. It is simple and predictable but cuts sentences and tables in half. Recursive splitting (the LangChain default) tries paragraph breaks first, then lines, then sentences, then words, so pieces stay under the size limit with natural boundaries.

Structural chunking uses the document’s own structure from Module 2: one chunk per section or subsection, tables and lists kept whole, split at sentence ends only when a section is too long. It is usually the best starting point for policies, manuals and documentation. Semantic chunking splits where the embedding similarity between consecutive sentences drops; it costs an embedding per sentence and often adds little over structural chunking, so measure before adopting it.

Common misconception: “512 tokens with 50 overlap is the standard.” There is no standard. The right size depends on your documents, your questions and your embedding model, and you find it by measuring.

3. Contextual headers and contextual retrieval

A chunk that says “Up to 10 days carry over” doesn’t say it is about annual leave. Prepending the document title and section path (“Leave policy › Annual leave”) before embedding and keyword indexing gives every chunk the words that say what it is about. It costs a few tokens per chunk and is the cheapest large win in chunking.

Anthropic’s Contextual Retrieval goes further: an LLM writes one or two sentences situating each chunk within its whole document, and that text is prepended before both embedding and BM25 indexing. Anthropic reported it cut failed retrievals by 49%, and by 67% when combined with re-ranking. The cost is one model call per chunk at indexing time; prompt caching of the document makes it affordable.

Tip: Do contextual headers from your parser’s section paths first. Add LLM-written context only if your golden set shows chunks are still retrieved without their topic.

4. Index small, return big: parent-child and late chunking

Parent-child retrieval embeds small child chunks for precise matching, then returns their larger parent section to the model so it has enough context to answer. Deduplicate parents when several children match. LlamaIndex calls a variant of this auto-merging retrieval; you can build it with two tables and a join.

Late chunking (Jina AI, 2024) attacks the same problem inside the embedding model: run the whole document through a long-context embedding model once, then average the token embeddings for each chunk’s span. Each chunk vector then carries context from the rest of the document. It needs a model that supports it and documents that fit its context length.

Sectionparent, ~800 tokensChild chunks~150 tokens eachAdd headerdoc › section titleEmbed + BM25children onlyQueryuser questionMatch childrenprecise hitsFetch parentsdedupe by sectionTo the modelfull contextIndex small, return bigAt query timesearch
Small chunks match precisely; their parent sections give the model enough context to answer. Late chunking gets a similar effect inside the embedding model.

5. Pick the size from measurements

Run a sweep: two or three strategies times three or four sizes (for example 128, 256, 512 and 1,024 tokens), each scored on your golden set for recall@5 and for tokens sent to the model per answer. Plot both. Choose the smallest context cost that keeps recall within a point of the best.

Record the decision in an architecture decision record with the numbers, the date and the corpus version. Revisit it when the corpus or the embedding model changes. Chunking choices interact with the embedding model’s maximum input length: a model that truncates at 512 tokens silently ignores the end of a 1,000-token chunk.

In production: Store chunk text, its parent id, section path, page numbers and the chunker version. Changing the chunker then means re-chunking from saved parse output, not re-parsing every file.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

Lab 3.1: Chunking sweep

On the capstone corpus, compare fixed (256 and 512 tokens, 15% overlap), recursive (512) and structural chunking, each with and without contextual headers. Score recall@5 and tokens per answer on the golden set.

Expected: A results table and a plot of recall@5 against tokens per answer.

Lab 3.2: Contextual retrieval

For your best strategy, generate a one-sentence context per chunk with an LLM (use prompt caching for the document), re-index, and re-score. Note indexing time and cost.

Expected: The recall change and the indexing cost per 1,000 chunks, side by side.

Lab 3.3: Configurable chunker and ADR (capstone increment)

Add src/ingest/chunk.py with the strategy, size and header options read from config, and write docs/adr/0002-chunking.md recording the measured choice.

Expected: Re-chunking runs from saved parse output with one config change; the ADR cites your numbers.

Go deeper

Videos

Further reading

GitHub repositories

Checkpoint quiz

1. Your fixed 100-token chunks often split an answer’s two facts across chunks. First fix to try?
2. What does a contextual header add to a chunk?
3. In parent-child retrieval, what is embedded and what is returned?
4. Your embedding model truncates at 512 tokens and your chunks are 1,000 tokens. Effect?
5. How should you choose the chunk size?

Interview questions

  1. How do you choose a chunking strategy for a new corpus? What would you measure?
  2. Explain contextual retrieval. When is it worth the indexing cost?
  3. What is parent-child retrieval and what problem does it solve?
  4. How would you chunk a 40-page contract with nested clauses and tables?
  5. What breaks if you change the chunker after launch, and how do you roll it out safely?

Ask the professor

Sign in to ask questions about this module.

Discussion

Community discussion appears here once giscus is configured (see README).