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.
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
- Chunk 1 · 20 wordsAnnual leave. Full-time employees earn 24 days of annual leave per year. Leave accrues monthly at two days per month.
Guided experiments
- Fixed size, 20 words, no overlap, k = 1. How many questions are answered, and how many answers are split across two chunks?
- 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?
- 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?
- 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.
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.
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.
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.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
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
- The 5 Levels Of Text Splitting For Retrieval · Greg Kamradt · ~69 min. The classic walk through character, recursive, document-specific, semantic and agentic splitting, with code.
- The Best RAG Technique Yet? Anthropic’s Contextual Retrieval Explained! · Prompt Engineering · ~16 min. Anthropic’s contextual retrieval explained step by step, including the cost and where it helps.
Further reading
- Article Contextual retrieval · Anthropic. Prepending chunk-specific context before embedding and BM25, with measured drops in retrieval failures.
- Paper Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models · Günther et al., 2024. Embed the whole document first, then pool per chunk, so each chunk keeps its context.
- Article Evaluating Chunking Strategies for Retrieval · Chroma Research. A token-level evaluation of popular chunkers; a model for measuring your own.
GitHub repositories
- FullStackRetrieval-com/RetrievalTutorials: The 5 Levels of Text Splitting notebook that goes with the video; reimplement the semantic splitter.
- anthropics/claude-cookbooks: The contextual embeddings guide under capabilities: the prompt, caching and evaluation code for contextual retrieval.
- jina-ai/late-chunking: The paper’s code: how token embeddings are pooled per chunk after encoding the whole document.
- docling-project/docling: The HybridChunker: structure-aware chunking that respects a tokenizer’s limit.
Checkpoint quiz
Interview questions
- How do you choose a chunking strategy for a new corpus? What would you measure?
- Explain contextual retrieval. When is it worth the indexing cost?
- What is parent-child retrieval and what problem does it solve?
- How would you chunk a 40-page contract with nested clauses and tables?
- 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).