Sub topic 11
Semantic chunking: splitting where meaning shifts
This chapter assumes you can read basic Python and know what an embedding is. It also assumes you know that cosine similarity measures how close two embeddings are, and that you have seen fixed-size and recursive chunking from earlier chapters.
Fixed-size and recursive splitters cut text by length or by punctuation. Neither knows whether the topic changed. Semantic chunking uses embeddings to find the places where the topic changes and cuts there.
The idea
Sentences inside one topic tend to have similar embeddings. When the text moves to a new topic, the embedding of the next sentence is farther from the previous ones. A semantic chunker measures that distance for every pair of neighbouring positions and starts a new chunk where the distance is unusually large.
The procedure has five steps:
- Split the text into sentences.
- Embed each sentence, or each small group of sentences around a position.
- Compute the distance between the two sides of every gap. Distance here is 1 minus cosine similarity.
- Pick a threshold. Gaps with a distance above it become chunk boundaries.
- Join the sentences between boundaries into chunks.
Comparing windows, not single sentences
Short sentences are noisy. "Yes, that works." has an embedding that says little about the topic. A sentence like that can look far from both neighbours, which produces a false boundary.
The usual fix is a window. For the gap after sentence i, embed the last window sentences up to and including i. Embed the next window sentences after it. Compare those two embeddings. A window of 1 is the plain sentence-to-sentence comparison. Windows of 2 or 3 smooth the distance curve, so only real topic shifts stand out.
Choosing the threshold
The threshold decides how many chunks you get. There are three common choices.
| Method | How it works | Behaviour |
|---|---|---|
| Percentile | Cut at gaps above the Nth percentile of this document's distances | Adapts to each document. Always cuts about (100 − N)% of gaps, even in a document with no topic changes. |
| Standard deviation | Cut at gaps above mean + k × standard deviation | Adapts to the spread. Cuts fewer gaps in uniform text. |
| Fixed value | Cut at gaps above a constant such as 0.4 | Predictable, but the right value depends on the embedding model. |
Distances from different embedding models are not comparable. A fixed threshold tuned for one model usually fails on another. Percentile thresholds avoid that problem but have the always-cuts weakness shown above.
A runnable implementation
The function below takes any embed function that maps a list of strings to a list of vectors. To run it without an API key, the example uses a toy embedder. It hashes content words into a fixed-size count vector. Replace toy_embed with a real embedding model for actual use.
import math
import re
import zlib
STOP = {"the", "a", "an", "in", "of", "to", "and", "for", "with",
"you", "can", "also"}
def toy_embed(texts, dim=512):
vectors = []
for text in texts:
vec = [0.0] * dim
for word in re.findall(r"[a-z]+", text.lower()):
if word not in STOP:
vec[zlib.crc32(word.encode()) % dim] += 1.0
vectors.append(vec)
return vectors
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot / (norm_a * norm_b)
def percentile(values, q):
ordered = sorted(values)
index = max(0, min(len(ordered) - 1, math.ceil(q / 100 * len(ordered)) - 1))
return ordered[index]
def split_sentences(text):
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
def semantic_chunks(sentences, embed, window=1, q=90,
min_sentences=2, max_sentences=12):
if not sentences:
return []
if len(sentences) == 1:
return [sentences[0]]
gaps = len(sentences) - 1
before = [" ".join(sentences[max(0, i - window + 1):i + 1]) for i in range(gaps)]
after = [" ".join(sentences[i + 1:i + 1 + window]) for i in range(gaps)]
vectors = embed(before + after)
distances = [1 - cosine(vectors[i], vectors[gaps + i]) for i in range(gaps)]
threshold = percentile(distances, q)
chunks, current = [], [sentences[0]]
for i, distance in enumerate(distances):
is_shift = distance > threshold and len(current) >= min_sentences
too_long = len(current) >= max_sentences
if is_shift or too_long:
chunks.append(" ".join(current))
current = [sentences[i + 1]]
else:
current.append(sentences[i + 1])
chunks.append(" ".join(current))
return chunks
text = (
"Boil the pasta in a large pot of water. "
"Add salt to the water and wait for the pasta to boil. "
"Drain the pasta and stir in the sauce. "
"A Python list stores items in order. "
"You can append items to a list with the append method. "
"Python lists also support list slicing."
)
for n, chunk in enumerate(semantic_chunks(split_sentences(text), toy_embed, q=80), 1):
print(n, chunk)With this input, the only gap above the 80th percentile is the one between the sauce sentence and the Python sentence. The output is two chunks, one about pasta and one about Python lists. The two sentences on either side of that gap share no content words, so their distance is the maximum.
The min_sentences and max_sentences arguments matter in practice. Without a minimum, a run of noisy gaps produces one-sentence chunks that carry too little context. Without a maximum, a long uniform section becomes one chunk that may exceed the embedding model's input limit.
What goes wrong
Chunks that are too small. Semantic boundaries are not tied to length. A document that jumps between topics produces many tiny chunks, and tiny chunks lose the context that makes them retrievable. Enforce a minimum, or merge a small chunk into its more similar neighbour.
Chunks that are too large. A long, coherent section has no strong gaps, so it stays whole. Enforce a maximum in tokens, not only in sentences. If a chunk is over the limit, fall back to recursive splitting inside it.
Sentence splitting errors. The regex above splits on ., ! and ? followed by whitespace. It breaks on abbreviations ("Dr. Smith"), decimals followed by a space, and code. Use a proper sentence segmenter for real prose, and do not use this approach on source code or tables.
Structure ignored. Semantic chunking sees only text similarity. It can cut through the middle of a table, a code block, or a list, and it can merge a heading into the wrong section. Split on structure first, as in the structure-aware chapter, then apply semantic splitting inside long sections.
Dependence on the embedding model. Boundaries move when you change models. Re-chunk and re-evaluate after any model swap.
Cost. Every sentence is embedded at least once, and with windows each sentence is embedded in several groups. That is several times the embedding calls of a fixed-size splitter, paid at ingestion and repeated whenever documents change. You then embed the final chunks again for the index. You can reduce this by caching sentence embeddings and averaging them for windows instead of re-embedding the joined text.
When it is worth trying
Semantic chunking tends to help when documents have little formatting but real topic changes. Examples are transcripts, long emails, support chats, and scraped articles with no headings. It tends not to help when documents already have clear structure, since headings and paragraphs are cheaper and more reliable boundaries. It also tends not to help when pieces are short and uniform, such as FAQ entries.
To test it, hold everything else constant and vary only the splitter. Use the same embedding model, the same top-k, and the same questions. Compare recall@k from the evaluation chapter, and also compare the chunk size distribution. If a method scores well only because it produces very large chunks, the comparison is not fair to the others.
Tuning checklist
- Start with
window=2and a percentile of 90 to 95, then adjust. - Set a minimum chunk size near the smallest unit that still answers a question on its own.
- Set a maximum below the embedding model's token limit, with room for any metadata you prepend.
- Print the distance values for a few documents. If they form a flat line, there are no topic shifts to find, and a percentile threshold will cut at noise.
- Add overlap or neighbour context only if the evaluation shows boundary losses.
Exercise
You run the chunker with q=95 on two documents. Document A is a long single-topic tutorial. Document B is a transcript that covers five unrelated subjects. Both produce roughly the same number of chunks per 100 sentences. Why is this a warning sign, and what change would you make?
Show answer
A percentile threshold always cuts about (100 − q)% of gaps, whatever the content. Document A has no real topic shifts, so its boundaries are placed at noise, while Document B's cuts may line up with real subject changes. Similar chunk counts show the threshold is not adapting to meaning. Switch to a standard-deviation or fixed threshold so that uniform text yields few cuts, or inspect the distance values directly. Keep a min and max chunk size either way.
Exercise
A semantic chunker produces many chunks of one or two sentences each on a chat transcript. Name two changes that would fix this without switching to another chunking method.
Show answer
Increase min_sentences so a boundary is allowed only after a minimum amount of text. Increase window so the distance curve is smoother and noisy single-sentence replies do not trigger cuts. Raising the percentile, or merging small chunks into the most similar neighbour, also works.