Skip to content

Chunking

Chapter 6 0 code blocks 1105 words

Chunking: why, how, and how it affects everything after it

Say this

Chunking splits documents into pieces before embedding, because one vector per whole document blurs many topics into one point, the embedder has an input limit, and the prompt can only hold a few thousand tokens of evidence. Small chunks match precisely but lose context; big chunks keep context but dilute the meaning, so a specific fact or name gets weak. I split at structure, headings, paragraphs and line breaks, never inside a word or table, with an overlap so a sentence on a boundary survives whole. The size isn't a magic number: I pick it from the documents and the embedder, then measure Recall@k on a test set. In my project I use 1800 tokens with 150 overlap for news articles, and because big chunks dilute names, I added keyword search for rare words.

Why we need it, 5 reasons

  1. One vector can't hold a whole document. A 30-page report about loans, HR and IT becomes one averaged point near none of them, so a question about HR matches weakly.
  2. The embedder has an input limit (8192 tokens for mine). Text beyond it is cut off or rejected.
  3. The prompt has a budget. We can send maybe 3–6 pieces, so they must be small and relevant, not whole documents.
  4. Precise citations. [E2] points to a passage the user can check, not "somewhere in this 40-page PDF".
  5. Cost and speed. Fewer, shorter tokens in the prompt mean faster, cheaper answers.

The trade-off in one picture

Too small (50 tokens)
"...rate is 24%..."
  • + very precise match
  • − no context: 24% of what?
  • − many chunks, noisy top-k
Sweet spot
a paragraph or a section
  • + precise AND has context
Too big (whole document)
loans + HR + IT + ...
  • + full context
  • − meaning diluted, the fact is weak
  • − wastes the prompt budget

Overlap: the next chunk starts a little before the previous one ended.

chunk 1... the bank raised
chunk 2the bank raised the rate to 24% ...
overlap
a sentence cut at the end of chunk 1 is whole at the start of chunk 2
StrategyHowGood forWeakness
Fixed sizeevery N tokens, with overlapquick baselinecuts sentences and tables
Sentence-basedgroup whole sentences up to Nplain proseignores sections
Recursive / structuralsplit by headings, then paragraphs, then lines, then sentencesbest defaultneeds clean structure
Semanticstart a new chunk where neighbouring sentences' embeddings stop being similarlong mixed textslower, needs embeddings to split
Parent–childsearch small children (~128–300 tokens), send their parent (~1,000+)precision + contexttwo levels to store
Contextual chunksprepend a short summary of where the chunk sits ("From the 2025 loan policy, section 3: …")chunks that don't make sense alonean LLM call per chunk at indexing
Format-specificMarkdown by headers, code by function, tables kept whole or by row groups with the header repeateddocs, code, spreadsheetsone splitter per format

Choosing a size (typical ranges, then measure): 128–256 tokens for FAQs and short facts; 256–512 for general documents (the common default); 1,000–2,000 for narrative text like news, where one document is one topic and the embedder takes long input. Overlap about 10–20%. Then test 2–4 sizes on a labelled set and keep the one with the best Recall@k and answers.

My chunker, step by step (chunk_text)

max 1800 tokens ≈ 7,200 chars · overlap 150 tokens ≈ 600 chars
tokens estimated as characters / 4
  1. 1
    List every word with its start and end position
    never cut inside a word
  2. 2
    Extend from the current word
    while the piece stays ≤ 7,200 chars
  3. 3
    Look back for a line break
    if the last line break is past the half (3,600 chars), cut there: paragraphs stay whole, but a chunk is never tiny
  4. 4
    Save the chunk
    text, start_char, end_char, overlap_with_previous
  5. 5
    The next chunk starts 600 chars back
    at the first word ≥ end − 600: that is the overlap; it always moves forward, so it can never loop
  6. 6
    Repeat until the last word

Example: a 12,000-character article. Chunk 1 runs 0 → about 7,180 (the last paragraph end past 3,600). Chunk 2 starts about 600 characters earlier, at ~6,580, and runs to 12,000. The two share about 150 tokens.

Why 1800: my documents are news articles and web pages, usually one topic each, and qwen3-embedding takes 8192 tokens. Large chunks mean fewer cuts through a story.

The bug story: the first version produced start_char = −1, which broke every page longer than one chunk (over 7,200 characters); the database's start_char ≥ 0 check rejected it. I wrote tests for long pages with single newlines, blank lines, indented sections and one huge paragraph with no line breaks at all, fixed the code and re-indexed.

How chunking affects every later step

  • Embedding: a bigger chunk means one name is a smaller part of its meaning. That's exactly why "Zaxarova nima dedi?" failed in dense search, and why I added keyword search for rare words.
  • Threshold: bigger chunks give lower similarity scores in general. Change the chunk size → re-measure the threshold (my 0.50).
  • Context budget: 6 chunks × up to 1800 tokens ≈ 10,800 tokens of evidence. The LLM's context window must fit that plus the rules and the answer.
  • Citations: the chunk is the unit a user checks. Smaller means more precise citations.
  • Duplicates: overlap means neighbouring chunks share text; if both are retrieved, the prompt repeats it.

Rules

  • Never cut inside a word, a table or a code block.
  • Keep the document title (and section heading) with every chunk.
  • Store start and end positions, so a citation can point to the exact place.
  • Same chunking for every document of a type; re-index everything when it changes.
  • Choose the size by measurement, and re-measure the threshold after.

Gaps I would fix

  • Prepend the title to each chunk's text before embedding (the heading_path column exists but isn't filled yet).
  • Test parent–child: children of about 300 tokens for search, the 1800-token parent for the prompt. Keep it only if Recall@k improves.
  • Use the real tokenizer instead of characters / 4, which is rough for Uzbek and Cyrillic.
  • Fixed: 6 × 1800 estimated tokens is about 10.8k, and Cyrillic text uses more real tokens than characters ÷ 4 suggests, so the evidence could reach the 16k default context and get cut silently. The generate call now sets num_ctx from a chat_num_ctx setting (24,576; qwen3:8b supports 40,960), with a test. A good story: a silent failure found by reading my own pipeline's numbers.

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents