Chapter 22 of 40 · ~20 min read & lab+75 XP
Chapter 22 · Generative AI

RAG Document Chunking: Fixed-Overlap, Sentence-Boundary & Contextual

Why bad chunking ruins even the best LLM: sliding-window overlap math (stride = size − overlap), sentence-boundary & recursive markdown splitters, Parent-Document retrieval, and Anthropic's Contextual Retrieval.

What Is It?

Document Chunking splits long PDFs and articles into retrieval-sized passages using fixed-size overlap, sentence boundaries, or contextual headers before embedding.

Why Is It Required?

Embedding an entire 40-page PDF blurs its vector into mush, while slicing mid-sentence cuts facts in half; smart chunking is the #1 lever for RAG recall.

Everyday Analogy: Cutting a textbook into index cards with a few overlapping lines so no key formula gets sliced across two cards.
Why ML Engineers & Data Scientists Actually Need This

80% of 'LLM hallucination' bugs in RAG are actually chunking bugs — if the retriever chops a negation or drops the company name, no 400B LLM can guess the missing half!

ML / AI Engineer

Picking the right chunk size (~256–512 tokens), 10%–20% overlap, and structure-aware splitting (Markdown headers, AST code blocks, PDF tables) is the highest-ROI lever in RAG engineering.

Data Scientist

Anthropic showed that simply prepending a 1-sentence LLM-generated document context header to every chunk before indexing cuts failed retrievals by 49% (and 67% with Reranking!).

Interview & Debug Edge

Hands-on RAG interview favorite: 'Implement both a Fixed-Overlap Chunker and a Sentence-Boundary Chunker, and explain how you would chunk a 200-page financial PDF with tables!'

Step 0 · Test Your Gut Before Any Math!

What happens to a single 1536-dim embedding vector if you embed an entire 5,000-word chapter as ONE giant chunk?

What You Will Master in This Chapter
  • Implement fixed-size sliding-window chunking cleanly using stride = chunk_size − overlap
  • Explain the Chunk-Size Goldilocks trade-off: too small loses surrounding context; too large dilutes the embedding vector
  • Implement sentence-boundary chunking so propositions and negations ('NOT 30 days') are never sliced in half
  • Apply Contextual Retrieval (prepending document summaries) and Small-to-Big (Parent Document) retrieval in production RAG
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
stride=S−O\text{stride} = S - OSay aloud:“sliding window stride”
Plain-English Meaning
Step advance between consecutive fixed chunks of size S with overlap O (must satisfy O < S!)
Everyday Example
S=512, O=64 → stride=448 tokens
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Chunking is like making index cards for an open-book exam. If you write only 3 words per card, you lose the meaning ('is NOT'); if you staple an entire 20-page chapter onto 1 card, you can never find the one formula you need! The sweet spot is 1 clean paragraph per card with a short header at the top ([ACME Q3 2026 — Refunds]) and a 1-sentence overlap bridge!

1. Fixed-Size Sliding Window Chunking & Overlap Math

Everyday Story First (Zero Math Yet!)

Adjust the Overlap slider in the mini-lab below to see how stride = size − overlap creates overlapping bridges across chunk edges.

Fixed-Size Sliding Window Chunking with Overlap (Stride = Size − Overlap)Chunk 1 (Tokens 0–511)Chunk 2 (Tokens 448–959)64-tok Overlap Bridge
Zero-overlap fixed chunking slices key facts in half across boundaries; adding 10%–20% sliding overlap preserves cross-boundary entities and context.

Sliding Window Loop Invariants

Given token/word list tokens, chunk size S>0S > 0, and overlap 0≤O<S0 \le O < S:

  • Stride: stride = S - O
  • Slices: tokens[i : i + S] for i = 0, stride, 2*stride, ...
  • Crucial Tail Guard: Break as soon as i + S >= len(tokens) so you don't emit tiny redundant tail fragments already 100% covered by the previous chunk!
Animated Mini-Lab • 4.3

Chunk Size (5 words) + Sliding Overlap Slicer

Chunk 1:RAG combines retrieval with LLMs.
Chunk 2:with LLMs. Chunk overlap prevents
Chunk 3:overlap prevents lost facts.

2. Sentence-Boundary & Recursive Structure-Aware Splitting

Everyday Story First (Zero Math Yet!)

Never chop right through 'NOT | 30 days'! Sentence-boundary and Recursive splitters respect natural text hierarchy.

Naive Character Chop vs. Sentence-Boundary ChunkingNaive Fixed Split (Breaks Facts!)C1: "The refund deadline is NOT"C2: "30 days; it is 7 days."Retriever fetches C2 alone → hallucinates 30 days!Sentence-Boundary / Recursive SplitC1: "The refund deadline is NOT 30 days; it is 7 days."Complete proposition preserved intact ✓
Sentence-boundary and recursive semantic chunkers keep complete propositions intact instead of chopping mid-sentence or mid-codeblock.

The Recursive Separator Hierarchy

Production splitters try coarse boundaries first, falling back only if a block exceeds max_tokens:

  1. Markdown headings (## , ### ) & Code AST function boundaries
  2. Double newlines (\n\n — paragraphs)
  3. Sentence boundaries (. , ? , ! )
  4. Whitespace / tokens (last resort for giant unpunctuated strings)

3. Contextual Retrieval & Parent-Document (Small-to-Big) RAG

Everyday Story First (Zero Math Yet!)

Even a perfect sentence chunk like 'Revenue grew 14% YoY.' is an orphan once separated from its document title — Contextual Retrieval fixes this completely!

Contextual Retrieval: Prepending Document Context Before IndexingRaw Orphan Chunk"Revenue grew 14% YoY."Which company? Which quarter?!Contextualized Chunk (Embed + BM25)[ACME Corp Q3 2026 10-Q Filing — Financial Summary]"Revenue grew 14% YoY."Cuts failed retrievals by 49% (67% with Reranking!)
Anthropic's Contextual Retrieval prepends a short document-level summary ('From Q3 2026 ACME earnings...') to each chunk before embedding & BM25 indexing — slashing retrieval failures by up to 49%!

Two Modern Upgrades Over Basic Chunking

  • Contextual Retrieval: Use a cheap fast LLM (with Prompt Caching on the full document!) to prepend a 1–2 sentence context header to every chunk before embedding & BM25 indexing.
  • Small-to-Big (Parent Document): Embed small 200-token child chunks for razor-sharp retrieval, store parent_id in metadata, and hand the full 1,000-token parent section to the generator LLM!
Walk Through With Me · Interactive Worked Example

Worked Example: Fixed-Overlap Chunking Edge Case

10 words, chunk_size = 4, overlap = 2 (stride = 2).

11. Trace start indices i = 0, 2, 4, 6Step 1 / 2

[0:4], [2:6], [4:8], [6:10] — stop at i = 6 because 6 + 4 >= 10!

Teacher's Note: If you didn't break at i + S >= N, i = 8 would emit [8:10], which is 100% redundant with [6:10]!
Pause & Check · Quick Intuition Pulse

In fixed-size chunking with chunk_size = 500 and overlap = 100, what is the stride (step size) between consecutive chunk starts?

Try It YourselfStandard

Why do Markdown tables and Python functions break badly under naive 500-character chunking?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Start with 256–512 tokens and 10%–15% overlap using a recursive paragraph/sentence splitter — then measure Recall@5 on your own eval set before tuning!

Interactive Visual Lab
Lab Challenge: Toggle Overlap ON vs. OFF in the 60 FPS Chunk-Boundary Animator to see how sliding overlap prevents chopping facts in half.
Interactive Animation • 4.3 Deep Lab

Chunk-Boundary Context Preservation Animator

Toggle Overlap ON vs. OFF to see how sliding overlap prevents chopping facts right across a chunk boundary.

Overlap ON (Safe)
Chunk #1 [0–4]:"Refunds are valid for 7 days."
Chunk #2 [3–7]:"for 7 days. Enterprise plans get 30 days."
0%
Active Chunk 1 of 2
Intuition Takeaway: Good chunking balances sharp embeddings (256–512 tokens) with intact meaning via sliding overlap, sentence/structure boundaries, Small-to-Big parent expansion, and Contextual Retrieval headers.
Where This Powers Real ML, Deep Learning & Generative AI

Codebase RAG (AST-Aware Chunking)

Uses Tree-sitter to chunk by complete functions/classes with file path & class signature prepended.

Enterprise Legal & Finance RAG

Combines Contextual Retrieval headers + Parent-Document expansion so clause numbers and parties are never lost.

Production NumPy & PyTorch Code Patterns
import re

# Sentence-Boundary Chunking with Overlap (preserves complete ideas for RAG)
def sentence_chunk(text: str, max_chars: int = 90, overlap_sentences: int = 1) -> list[str]:
    sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s.strip()]
    chunks, cur = [], []
    for sent in sentences:
        if cur and sum(len(x) for x in cur) + len(sent) > max_chars:
            chunks.append(" ".join(cur))
            cur = cur[-overlap_sentences:] if overlap_sentences > 0 else []
        cur.append(sent)
    if cur:
        chunks.append(" ".join(cur))
    return chunks

doc = "RAG grounds LLMs in private data. Good chunking avoids cutting sentences in half. Overlap keeps cross-boundary context intact."
for i, ch in enumerate(sentence_chunk(doc, max_chars=80, overlap_sentences=1), 1):
    print(f"Chunk {i}: {ch}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting to guard overlap >= chunk_size (infinite loop) or emitting redundant tiny trailing chunks.
Best Practice: Assert 0 <= overlap < chunk_size and break when start + chunk_size >= len(tokens)!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1How does Small-to-Big (Parent Document) retrieval solve the Chunk-Size Goldilocks dilemma?

Apply What You Learned — Solve Matching Coding Problems