Sub topic 11
Semantic chunking: splitting where meaning shifts
This chapter assumes you have read the earlier chapters on fixed-size and recursive splitting. It also assumes you can compute cosine similarity between two embedding vectors.
The idea
Fixed-size and recursive chunkers split on length or punctuation. They never check whether the topic changes at the boundary. Semantic chunking does check. It embeds each sentence, compares neighbouring sentences, and starts a new chunk where the similarity drops. A drop suggests the text has moved to a new topic.
A minimal implementation
The function below takes any embed function that maps a string to a list of numbers. It also closes a chunk when it reaches max_sentences, so one long topic cannot produce an oversized chunk.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def semantic_chunks(sentences, embed, threshold=0.3, max_sentences=12):
if not sentences:
return []
vectors = [embed(s) for s in sentences]
chunks, current = [], [sentences[0]]
for i in range(1, len(sentences)):
sim = cosine(vectors[i - 1], vectors[i])
if sim < threshold or len(current) >= max_sentences:
chunks.append(" ".join(current))
current = []
current.append(sentences[i])
chunks.append(" ".join(current))
return chunks
# Toy embedding: word counts over a tiny vocabulary.
VOCAB = ["cat", "dog", "pet", "tax", "invoice", "payment"]
def toy_embed(sentence):
words = sentence.lower().replace(".", "").split()
return [words.count(w) for w in VOCAB]
sentences = [
"The cat is a pet.",
"The dog is a pet too.",
"Each invoice needs a tax line.",
"Payment for each invoice is due in 30 days.",
]
for chunk in semantic_chunks(sentences, toy_embed):
print(chunk)This prints two chunks: the two pet sentences, then the two invoice sentences. The toy embedding only counts words. In practice you would call a real embedding model, such as a sentence-transformer or a hosted API.
Choosing the breakpoint
A fixed threshold such as 0.3 works only for one embedding model. Different models give different similarity ranges. Two common alternatives adapt to the document:
- Percentile breakpoint. Compute all neighbour similarities in the document and split at the lowest 10 to 25 percent. Every document then gets some splits, even a uniform one.
- Windowed comparison. Compare the average embedding of the last few sentences with the next few. This smooths out single short sentences like "Yes." or "See below.", which often score low for no good reason.
Costs and failure modes
| Issue | Effect | Mitigation |
|---|---|---|
| One embedding call per sentence | Slower and more expensive ingestion | Batch the calls and cache the vectors |
| Uneven chunk sizes | Tiny chunks, or chunks above the model's input limit | Set minimum and maximum sizes, and merge or force-split |
| Noisy similarity on short sentences | Spurious splits | Use windows, or merge sentences under a minimum length |
| Topics that return later | A sudden dip splits one argument in two | Raise the percentile or add overlap |
| Structured content | Tables, code, and lists embed poorly as sentences | Chunk those with structure-aware rules first |
The embedding model used for chunking does not need to be the model used for retrieval. Using the same one keeps the notion of "similar" consistent, though.
When it is worth it
Semantic chunking helps most on long, loosely structured prose such as transcripts, essays, and support threads. In these, topics change without headings. If your documents already have headings, structure-aware chunking gives you boundaries for free. Published comparisons of semantic and simple recursive splitting have been mixed, and recursive splitting often performs about as well at a fraction of the cost. Do not adopt semantic chunking on belief. Run it against your own questions with recall@k, as in the evaluation chapter, and keep it only if the gain justifies the extra ingestion cost.
Exercise
Your semantic chunker produces a few chunks of 3,000 tokens and many chunks of 15 tokens. Name two changes that would make the sizes more even.
Show answer
Add a maximum size, so a long run of similar sentences is force-split. Add a minimum size, so a tiny chunk is merged into its neighbour. Using a window of sentences instead of single sentences, or a percentile breakpoint, also reduces the noise that produces the tiny chunks.