MMR for RAG: Balance Relevance and Diversity with a Tested Reranker
Understand Maximal Marginal Relevance for RAG. Trace relevance and redundancy, compare lambda settings, define ties and score ranges, and run a tested Python selector.
MMR greedily selects candidates by balancing query relevance against their greatest similarity to already selected items. Define the seed, relevance weight, score ranges and tie rules explicitly. It diversifies an existing candidate pool; it cannot recover missing candidates or guarantee answer quality. RRF rank fusion is a separate retrieval-stage decision.
When the top passages repeat the same evidence
A RAG retriever returns several highly similar passages, leaving little room for another useful aspect of the question. Simply requesting more final passages can increase repetition and context size. Maximal Marginal Relevance, or MMR, addresses a different decision: from an available candidate pool, choose passages that balance query relevance with redundancy against what has already been selected.
This is a reranking and selection step, not a replacement for candidate retrieval or a guarantee of answer correctness. It cannot recover a missing passage that never entered the pool. Nor does a diverse selection establish that its sources are accurate, current or authorized for the caller. Keep those responsibilities visible around the selection stage.
This guide provides a small deterministic implementation with invented relevance and pairwise similarity scores. No embedding model, search engine or LLM was called. The purpose is to trace the greedy decision, compare parameter settings and test implementation behavior before using the idea with real retrieval data.
Score each remaining candidate against the selected set
After choosing an initial candidate, compute score(d) = lambda × relevance(d, query) − (1 − lambda) × max similarity(d, selected). The maximum is taken over the candidates already selected. Choose the remaining candidate with the greatest score, add it to the selected set, and recompute the redundancy comparison for the next step.
The original MMR work combines query relevance and novelty; the relevance and document-similarity functions need not be identical. This implementation uses explicit supplied scores, so its arithmetic can be inspected without relying on a particular embedding API. Its relevance weight lambda lies between zero and one, with larger values placing more weight on query relevance.
The first item requires a policy because no selected item yet exists for the redundancy term. Here it is always the highest-relevance candidate, with ascending ASCII ID settling a tie. That initialization also applies at lambda zero. Subsequent exact objective ties use the same ID rule. These are declared implementation choices, rather than assumptions about every library called MMR.
Trace why a lower-relevance candidate can be selected next
The four candidates have relevance A = 0.95, B = 0.94, C = 0.80 and D = 0.65. A and B are assigned a similarity of 0.99. The other pair similarities are A–C = 0.20, A–D = 0.10, B–C = 0.25, B–D = 0.15 and C–D = 0.40. These synthetic numbers are a reasoning fixture, not measured semantic judgments.
A is selected first. At lambda 0.5, B receives 0.5 × 0.94 − 0.5 × 0.99 = −0.025. C receives 0.30 and D receives 0.275, so C wins the second position. With A and C selected, D’s largest similarity to the set is now 0.40, giving an objective of 0.125. The selected sequence is A, C, D.
The redundancy term is not a permanent penalty computed against the first result alone. A new selected passage can become the closest neighbor of another candidate. The implementation maintains the largest selected-neighbor similarity after each step, while the independent reference rescans all selected candidates. Their agreement tests that incremental update.
| Relevance weight | Selected first three | Meaning in this fixture |
|---|---|---|
| 1 | A, B, C | Only relevance affects later objectives |
| 0.5 | A, C, D | Relevance is balanced against the closest selected neighbor |
| 0 | A, D, C | Relevance seeds the first item; later choices prioritize dissimilarity |
Define score ranges and failure behavior before integration
The teaching function accepts at most 32 candidates, unique nonempty ASCII IDs, nonnegative integer k, and relevance and similarity values in [0, 1]. It requires every ordered similarity pair, symmetry and a diagonal of one. It rejects missing pairs and nonfinite values. These checks define a compact local contract; they do not prove the supplied similarities represent useful semantic relationships.
Raw cosine similarity can be negative. This fixture intentionally rejects negative scores instead of silently clipping or transforming them. If a production system uses a different range, specify the transformation and evaluate its effect on both relevance and redundancy. Sharing a numeric range does not by itself make two unrelated scoring methods equally calibrated.
The function returns up to k candidates, even if a later objective is negative. It has no minimum relevance threshold or stopping threshold. Establish eligibility and any minimum-quality policy before selection when your application requires them. Do not reinterpret a negative objective as an automatic error or an answer-confidence value.
Run an exact-arithmetic greedy selector and a separate reference
Save the listing as mmr_demo.py and run python mmr_demo.py. It uses only the Python standard library. The tested runtime was Python 3.12.14. Fraction arithmetic represents the finite decimal inputs exactly for the main selector; the generated fixtures use Decimal arithmetic in an independent full-rescan reference.
The fixed assertions check the three weight settings and the numerical contribution trace. The generated section creates 300 small symmetric score matrices, varies k and the relevance weight, and compares both normal and reversed candidate input order. It completed 1,205 assertions. An additional 21 local checks covered invalid inputs, exact ties, empty candidates, k zero and k larger than the pool.
The matrices are synthetic and are not claimed to be valid outputs of any real embedding model. This is an algorithmic correctness fixture, not a retrieval-quality experiment. The trace returns the chosen ID, query relevance, selected-neighbor redundancy and objective; the seed has no redundancy or objective value because it follows the separate initialization policy.
from fractions import Fraction as F
from decimal import Decimal
import random
def unit(value):
if isinstance(value, bool) or not isinstance(value, (int, float, F)):
raise ValueError('Scores must be numeric, not booleans or strings')
try:
result = F(str(value))
except (ValueError, ZeroDivisionError):
raise ValueError('Scores must be finite') from None
if not 0 <= result <= 1:
raise ValueError('Scores must be between zero and one')
return result
def rerank(candidates, similarities, k, weight=F(1, 2)):
if isinstance(k, bool) or not isinstance(k, int) or k < 0:
raise ValueError('k must be a nonnegative integer')
weight = unit(weight)
if len(candidates) > 32:
raise ValueError('This teaching fixture accepts at most 32 candidates')
ids = [item[0] for item in candidates]
if any(not isinstance(x, str) or not x.isascii() or not x or
any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-' for c in x)
for x in ids) or len(set(ids)) != len(ids):
raise ValueError('Use unique nonempty ASCII letter/digit/_/- IDs')
relevance = {name: unit(score) for name, score in candidates}
try:
sim = {(a, b): unit(similarities[a, b]) for a in ids for b in ids}
except KeyError:
raise ValueError('Supply every ordered similarity pair') from None
if any(sim[a, a] != 1 for a in ids) or any(
sim[a, b] != sim[b, a] for a in ids for b in ids):
raise ValueError('This fixture requires symmetry and diagonal one')
if not ids or k == 0:
return [], []
first = min(ids, key=lambda x: (-relevance[x], x))
selected = [first]
trace = [(first, relevance[first], None, None)]
remaining = set(ids) - {first}
redundancy = {x: sim[x, first] for x in remaining}
while remaining and len(selected) < k:
score = {x: weight * relevance[x] - (1 - weight) * redundancy[x]
for x in remaining}
winner = min(remaining, key=lambda x: (-score[x], x))
trace.append((winner, relevance[winner], redundancy[winner], score[winner]))
selected.append(winner)
remaining.remove(winner)
for x in remaining:
redundancy[x] = max(redundancy[x], sim[x, winner])
return selected, trace
def oracle(candidates, similarities, k, weight):
# Independent full-rescan reference for the finite-decimal generated fixtures.
rel = {x: Decimal(str(v)) for x, v in candidates}
w = Decimal(str(weight))
pool = set(rel)
if not pool or k == 0:
return []
chosen = [min(pool, key=lambda x: (-rel[x], x))]
pool.remove(chosen[0])
while pool and len(chosen) < k:
scores = {x: w * rel[x] - (1 - w) * max(
Decimal(str(similarities[x, y])) for y in chosen) for x in pool}
winner = min(pool, key=lambda x: (-scores[x], x))
chosen.append(winner)
pool.remove(winner)
return chosen
def main():
candidates = [('A', .95), ('B', .94), ('C', .8), ('D', .65)]
pairs = {('A', 'B'): .99, ('A', 'C'): .2, ('A', 'D'): .1,
('B', 'C'): .25, ('B', 'D'): .15, ('C', 'D'): .4}
sim = {(a, a): 1 for a, _ in candidates}
for (a, b), value in pairs.items():
sim[a, b] = sim[b, a] = value
assert rerank(candidates, sim, 3, 1)[0] == ['A', 'B', 'C']
selected, trace = rerank(candidates, sim, 3, .5)
assert selected == ['A', 'C', 'D']
assert trace[1] == ('C', F(4, 5), F(1, 5), F(3, 10))
assert trace[2][-1] == F(1, 8)
assert rerank(candidates, sim, 3, 0)[0] == ['A', 'D', 'C']
print('Half relevance:', selected, trace)
rng = random.Random(109)
checks = 5
for _ in range(300):
ids = [f'd{i}' for i in range(rng.randrange(0, 12))]
candidates = [(x, rng.randrange(101) / 100) for x in ids]
sim = {(a, a): 1 for a in ids}
for i, a in enumerate(ids):
for b in ids[i+1:]:
sim[a, b] = sim[b, a] = rng.randrange(101) / 100
k, weight = rng.randrange(15), rng.randrange(11) / 10
for data in (candidates, list(reversed(candidates))):
got, _ = rerank(data, sim, k, weight)
assert got == oracle(candidates, sim, k, weight)
assert len(got) == min(k, len(ids)) and len(set(got)) == len(got)
checks += 2
print('PASS', checks, 'assertions; 300 seeded score fixtures, two input orders')
if __name__ == '__main__':
main()Keep candidate depth, selected count and prompt budget distinct
Candidate depth controls what MMR can choose from. Selected count controls how many candidates this function retains. Prompt budget controls how much text the downstream system can include. Increasing k cannot recover a relevant candidate excluded by a small retrieval window, and selecting k passages does not establish that they fit a token budget.
For example, a pool containing only A and B cannot produce C, regardless of the relevance weight. If the pool contains near-duplicates from one document, the similarity policy may reduce repetition, but it does not enforce a per-document quota. Add explicit source constraints only when that is the intended product behavior, and test the interaction rather than labeling every constraint MMR.
RRF and MMR operate on different evidence. Reciprocal Rank Fusion combines rank positions from multiple retrieval lists. The MMR fixture compares candidate relevance with pairwise redundancy after some candidates have already been selected. A pipeline can use a fusion stage to construct candidates and a diversity stage afterward, but raw fusion scores should not be mixed with another similarity scale without a deliberate policy.
Evaluate diversity alongside the evidence the answer needs
Compare candidate pools and selected passages on queries where the required evidence is known. Track whether the selection retains the necessary facts and whether repeated passages crowd out useful alternatives. A lower pairwise similarity score alone is not a success criterion: an unrelated passage may be different while adding no usable evidence.
Use a fixed baseline, a stable candidate pool and explicit relevance judgments while testing a weight change. Also examine narrow questions where overlapping passages provide necessary reinforcement or continuity. A preference for diverse examples is not a universal preference for different sources on every factual lookup.
Keep implementation order separate from engine output order. The local function returns greedy selection order. Elastic’s documented ES|QL MMR command preserves the input ordering of retained rows and requires an input limit. That example shows why an engine integration should verify selection, presentation order, limits and parameter meaning instead of assuming identical behavior from a shared algorithm name.
The fixture computes and stores a full pairwise matrix, so its storage grows with the square of candidate count. The small input bound makes that choice inspectable. It does not establish production latency, memory use with real vectors, network transfer cost or the quality of a chosen embedding space. Measure those separately on the actual pipeline.
Source: Elastic ES|QL MMR: input limits and retained output order ↗
Diversify a defined candidate pool with an explainable policy
MMR gives a practical way to penalize redundancy while retaining a relevance signal. Make initialization, similarity ranges, tie handling and stopping behavior explicit, then inspect a numerical trace before connecting the selector to a retrieval engine.
Use the related RRF guide when the problem is merging retrieval lists, the vector-similarity guide when score meaning is unclear, and the retrieval-metrics guide when assessing judged relevance. A correct diversity calculation is one component of a useful RAG system; it still needs evidence-focused evaluation and a clear context budget.
Your next steps
- Separate relevance, redundancy and candidate eligibility.
- Declare the seed and tie rules, including behavior at lambda zero.
- Keep score scales, candidate depth and token budget explicit.
- Evaluate retained evidence as well as repetition.
Sources & official resources
Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →