Chunking
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
- 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.
- The embedder has an input limit (8192 tokens for mine). Text beyond it is cut off or rejected.
- The prompt has a budget. We can send maybe 3–6 pieces, so they must be small and relevant, not whole documents.
- Precise citations. [E2] points to a passage the user can check, not "somewhere in this 40-page PDF".
- Cost and speed. Fewer, shorter tokens in the prompt mean faster, cheaper answers.
The trade-off in one picture
- + very precise match
- − no context: 24% of what?
- − many chunks, noisy top-k
- + precise AND has context
- + full context
- − meaning diluted, the fact is weak
- − wastes the prompt budget
Overlap: the next chunk starts a little before the previous one ended.
| Strategy | How | Good for | Weakness |
|---|---|---|---|
| Fixed size | every N tokens, with overlap | quick baseline | cuts sentences and tables |
| Sentence-based | group whole sentences up to N | plain prose | ignores sections |
| Recursive / structural | split by headings, then paragraphs, then lines, then sentences | best default | needs clean structure |
| Semantic | start a new chunk where neighbouring sentences' embeddings stop being similar | long mixed text | slower, needs embeddings to split |
| Parent–child | search small children (~128–300 tokens), send their parent (~1,000+) | precision + context | two levels to store |
| Contextual chunks | prepend a short summary of where the chunk sits ("From the 2025 loan policy, section 3: …") | chunks that don't make sense alone | an LLM call per chunk at indexing |
| Format-specific | Markdown by headers, code by function, tables kept whole or by row groups with the header repeated | docs, code, spreadsheets | one 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)
- 1List every word with its start and end positionnever cut inside a word
- 2Extend from the current wordwhile the piece stays ≤ 7,200 chars
- 3Look back for a line breakif the last line break is past the half (3,600 chars), cut there: paragraphs stay whole, but a chunk is never tiny
- 4Save the chunktext, start_char, end_char, overlap_with_previous
- 5The next chunk starts 600 chars backat the first word ≥ end − 600: that is the overlap; it always moves forward, so it can never loop
- 6Repeat 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_pathcolumn 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_ctxfrom achat_num_ctxsetting (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.