Select a relevant but less repetitive evidence set, calibrate the novelty penalty and preserve essential corroborating passages.
Maximal marginal relevance: diversify retrieval without losing support
MMR is a second-stage selection rule
Maximal marginal relevance chooses one result at a time from an already retrieved candidate set. It balances query relevance against similarity to material already selected. With relevance weight lambda, a common form is lambda times query relevance minus one minus lambda times the maximum similarity to any selected result. A high lambda favors the original ranking; a lower one rewards novelty. This does not find passages absent from the candidate pool. If candidate recall is weak, tune the first-stage search before applying diversity. Run authorization and deletion filters before this selection rule.
The two scores need compatible meaning
A BM25 score can span a different scale from cosine similarity or token overlap. Plugging raw values into the formula makes lambda meaningless. Convert query relevance and passage-passage similarity to stable ranges using judged data, and record the score versions. The example uses bounded relevance values and Jaccard token overlap solely to make the behavior inspectable. A production selector may use embedding similarity, lexical overlap, lineage or a combination. Fusion calibration explains why numeric scale is a policy, not a label. One duplicate detector should not accidentally penalize unrelated facts that use the same technical vocabulary.
Diversity is not the same as independent evidence
Two passages from different documents can repeat one syndicated announcement. Conversely, two passages in one manual can provide distinct facts needed to answer a multi-part question. MMR's similarity penalty is a ranking signal, not proof of source independence. Preserve document revision, lineage and passage identity in the selected packet. Independent-support checks decide whether sources truly corroborate a claim. Document grouping is a presentation rule; it should not silently discard a second passage required for an answer.
Choose the evidence budget deliberately
The first selected item normally has no novelty penalty. Later selections can trade a small relevance drop for a new angle, but an aggressive penalty may push a weak or unrelated passage into a short context window. Reserve slots for mandatory exact matches and explicitly requested sources before running diversity over the remaining eligible pool. Keep conflicting evidence visible when the user asks for comparison or when active sources disagree. Claim-conflict handling must see the competing claims rather than receive a falsely tidy packet. Inspect the final ordered context, not merely the selection scores.
Evaluate both variety and answer support
Measure unique-parent count, near-duplicate rate and intent coverage at a fixed K, then check whether answer-bearing spans and contradictions survived. A higher diversity number can coexist with lower supported-answer rate. Compare several lambda values under the same first-stage pool and token budget. Log the relevance and novelty component for each chosen passage so a missing citation can be diagnosed. Context packing then assigns actual token slots and may reject a selected item that is too large. MMR improves candidate mix only when the final evidence remains sufficient.
Worked contract
from dataclasses import dataclass
@dataclass(frozen=True)
class Passage:
passage_id: str
relevance: float
terms: frozenset[str]
permitted: bool
def overlap(left: Passage, right: Passage) -> float:
union = left.terms | right.terms
return len(left.terms & right.terms) / len(union) if union else 0.0
def select_mmr(candidates: list[Passage], limit: int,
relevance_weight: float) -> list[Passage]:
if limit < 0 or not 0 <= relevance_weight <= 1:
raise ValueError("invalid selection settings")
remaining = [item for item in candidates if item.permitted]
if any(not 0 <= item.relevance <= 1 for item in remaining):
raise ValueError("relevance must be normalized")
chosen = []
while remaining and len(chosen) < limit:
winner = max(remaining, key=lambda item: (
relevance_weight * item.relevance
- (1 - relevance_weight) * max(
(overlap(item, prior) for prior in chosen), default=0.0),
item.passage_id))
chosen.append(winner)
remaining.remove(winner)
return chosen
hits = [Passage("seal-v3-a", .92, frozenset({"seal", "pressure"}), True),
Passage("seal-v3-b", .89, frozenset({"seal", "pressure"}), True),
Passage("pump-81", .78, frozenset({"pump", "inspection"}), True),
Passage("private-note", .99, frozenset({"seal"}), False)]
assert [hit.passage_id for hit in select_mmr(hits, 2, .6)] == [
"seal-v3-a", "pump-81"]Performance and operating cost
For N candidates and K selected passages, this direct implementation compares each remaining candidate with every selected item on every round. If token-set comparison costs L, time is O(K squared times N times L) in the worst case and the remaining/chosen lists use O(N + K) space beyond stored terms. Incrementally storing each candidate's maximum similarity to chosen items can reduce repeated work to O(KNL) and O(N) extra state. Pairwise precomputation costs O(N squared times L) time and memory. Keep N bounded, because diversity selection is a reranking step, not a replacement for first-stage retrieval.
Common Mistakes
- Applying MMR before permission filtering and allowing a private passage to influence public ranking.
- Combining unscaled BM25 and bounded similarity values as if lambda had a stable interpretation.
- Treating a novel result as independent corroboration without checking lineage.
- Optimizing unique-source count while dropping the only passage that supports a required claim.
Validation drill
For 61 multi-aspect queries, compare three relevance weights at the same top-30 candidate pool and six-passage context budget. Record unique source lineages, supported-answer rate, omitted contradictions and p95 selection time.
