Look at the context your RAG system sent to the model on a few real queries and you will often find the same text more than once. The question was about the refund window, and three of the five slots hold the refund paragraph: once from the help-center page, once from a PDF export of that page, once from an older version that was never deleted. Each copy scored well on similarity because each copy is relevant. Together they used three fifths of your retrieval budget to say one thing, and the chunk that held the exception ("except for annual plans") came in sixth and was cut.
Every chunk was relevant; the set as a whole was not informative. Top-k scores each chunk on its own, so it cannot notice that a candidate repeats something already picked. Below are three fixes, cheapest first, and a way to tell whether a fix helped or just pushed out the chunks you needed.
Why top-k fills up with copies
Near-identical passages land at almost the same distance from the query and fill neighbouring ranks. Common sources of duplicates:
- The same content in several formats. An HTML page, its PDF export and a copy pasted into a wiki all get indexed.
- Versioned documents. Policy v3 and policy v4 may share most of their text, and without a filter both are searchable.
- Overlapping chunks. A sliding window with a 50% overlap means neighbouring chunks share half their text. Both match the query for the same reason.
- Boilerplate. Disclaimers, footers and "contact support" blocks repeated on every page can match generic queries surprisingly well.
The cost is more than tokens: repetition can make a claim look better supported than it is, and with a fixed budget every duplicate pushes a distinct chunk out.
Layer 1: remove exact copies after normalizing
Start with the cheapest fix: collapse chunks that are the same text.
Normalize before hashing: lowercase, collapse whitespace, strip punctuation that varies between exports. Then hash the result. Chunks with the same hash are the same content; keep the one with the best score, or the one from the source you trust most.
import hashlib, re
def content_key(text: str) -> str:
norm = re.sub(r"\s+", " ", text.lower())
norm = re.sub(r"[^\w\s]", "", norm).strip()
return hashlib.sha256(norm.encode()).hexdigest()
def drop_exact_dupes(candidates):
# candidates: list of dicts with "text" and "score", best score first
seen, kept = set(), []
for c in candidates:
k = content_key(c["text"])
if k not in seen:
seen.add(k)
kept.append(c)
return keptThis catches the HTML-vs-PDF case when extraction is clean. It misses copies that differ by a date, a product name or one edited sentence. Those need the second layer.
Better still, do this at index time: store one copy and keep the others as alternate source URLs on it. Query-time deduplication is the fallback for duplicates you have not cleaned up yet.
Layer 2: maximal marginal relevance
Maximal marginal relevance (MMR), introduced by Carbonell and Goldstein at SIGIR 1998, builds the result set one item at a time. At each step it picks the candidate that best balances two things: how relevant it is to the query, and how different it is from what has already been picked. With λ between 0 and 1:
MMR(d) = λ · sim(d, query) − (1 − λ) · max over s in Selected of sim(d, s)When λ = 1 this reduces to plain relevance ranking. Lower values penalize candidates that resemble anything already selected. Here is a self-contained implementation over normalized embeddings:
import numpy as np
def mmr(query_vec, cand_vecs, k=5, lam=0.7):
"""query_vec: (d,), cand_vecs: (n, d); all L2-normalized.
Returns indices of selected candidates, in selection order."""
rel = cand_vecs @ query_vec # relevance to the query
pair = cand_vecs @ cand_vecs.T # candidate-to-candidate similarity
selected = [int(np.argmax(rel))]
remaining = set(range(len(cand_vecs))) - set(selected)
while remaining and len(selected) < k:
idx = list(remaining)
redundancy = pair[np.ix_(idx, selected)].max(axis=1)
scores = lam * rel[idx] - (1 - lam) * redundancy
best = idx[int(np.argmax(scores))]
selected.append(best)
remaining.remove(best)
return selectedThe pipeline that uses it has three steps. Over-fetch candidates by plain similarity (say 30 to 50), run MMR down to the k you actually send, then pass those to the prompt. MMR can only choose among the candidates you give it, so if you fetch exactly k it has nothing to choose from. The extra candidates are the whole point.
Why it works: the redundancy term is computed against the chunks already selected, not against the query. The second copy of the refund paragraph is still highly relevant, but its similarity to the first copy is close to 1, so its score can drop below a less relevant chunk that adds something new, such as the annual-plan exception.
"Can" matters. The penalty only wins when it outweighs the relevance gap. In a toy test with three near-copies (relevance about 0.95) and one distinct chunk (relevance 0.8), λ = 0.7 still picked all three copies, λ = 0.5 swapped in the distinct chunk, and λ = 0.3 also pulled in a chunk with zero relevance. The right λ depends on how spread out your similarity scores are, which is why you tune it on data rather than copying a default.
Where it fails:
- λ too low drifts off topic. A chunk that is merely different can beat one that is relevant, as the toy test showed.
- Embedding similarity is not semantic equivalence. Two chunks that say opposite things about the same topic ("refunds allowed within 30 days" and "refunds no longer offered") can have very high cosine similarity. MMR may drop one as redundant, and that one may be the current policy. If conflicting versions are a real risk in your corpus, filter by version or date before MMR rather than hoping it keeps the right one.
- Some questions need repetition. "List every place the docs mention the rate limit" is an enumeration query, and the near-duplicates are the answer. Diversity is the wrong objective there.
Many vector-store libraries ship MMR with the same two knobs. LangChain's vector stores, for example, expose max_marginal_relevance_search with fetch_k and lambda_mult parameters. Check which direction your library's parameter runs before you tune it. In LangChain's convention, 1.0 means maximum relevance and 0.0 maximum diversity.
Layer 3: limit chunks per source
A cruder rule: allow at most n chunks from any one document or URL. It costs nothing, is easy to explain while debugging, and stops one big document taking over the context.
It misses the same content under two source IDs (the HTML-vs-PDF case), so it complements Layer 1, and it hurts when one long document really is the only relevant source. A cap of two or three per source, applied after deduplication, is a reasonable starting point to test, not a rule.
Measuring whether diversification helped
Judge diversification with retrieval metrics on a labeled set, not by eyeballing a few answers. For each eval query you need the set of distinct facts (or gold chunk groups) needed to answer it. Group duplicate gold chunks into one fact: retrieving either copy counts as covering it.
Then compare baseline top-k and the diversified pipeline on:
- Fact coverage at k: the fraction of required facts with at least one supporting chunk in the final context. This is the metric diversification should raise.
- Duplicate rate: the fraction of final chunks whose content key, or whose similarity to an earlier chunk above some threshold, matches a chunk already in the context. This tells you whether the problem was there in the first place.
- Relevance floor: the fraction of final chunks a reviewer, or a calibrated judge, marks as off-topic. This is how you catch a λ that has drifted too low.
A concrete test case worth keeping in the suite:
- id: refund-window-annual-exception
query: "Can I get a refund after 20 days?"
required_facts:
- refund_window_30_days # satisfied by help-center, PDF, or wiki copy
- annual_plan_exception
must_not_include_version: policy_v2
expect: both facts present within k=5Sweep λ (for example 1.0, 0.85, 0.7, 0.5) and fetch size, and plot coverage against the relevance floor. Choose the point where coverage stops improving before relevance starts dropping. Break the results down by query type too: enumeration queries should be tested separately, and may need diversification switched off.
Finally, check answers, not only retrieval. Higher coverage should mean fewer answers that miss an exception. If it does not, the bottleneck is elsewhere, likely the prompt.
Checklist
- Sample real contexts sent to the model and count repeated content before changing anything.
- Normalize and hash chunks; deduplicate at index time and again at query time as a fallback.
- Over-fetch (several times k) and apply MMR down to k; sweep λ from 1.0 down to about 0.5 on data.
- Filter by document version or date before MMR so it can't drop the current version as "redundant".
- Consider a per-source cap of two or three chunks, applied after deduplication.
- Evaluate with fact coverage at k, duplicate rate and an off-topic rate, with duplicate gold chunks grouped into one fact.
- Test enumeration-style queries separately; they may need diversification off.
- Confirm that higher retrieval coverage actually turns into answers that miss fewer conditions.
Further reading
- Carbonell, J. and Goldstein, J. (1998). The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries. SIGIR '98. DOI: 10.1145/290941.291025.
- Google Cloud, Perform Maximal Marginal Relevance search with LangChain on Bigtable: documents the
fetch_kandlambda_multparameters ofmax_marginal_relevance_search.
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.