Search Tutorials
--Ads--Maximal Marginal Relevance (MMR)
Return results that are relevant and also different from each other.
Top-k search returns the k chunks most similar to the query. When a collection contains near-duplicates, such as the same paragraph in three versions of a policy, or a topic repeated across many pages, those k slots fill up with the same information. Maximal Marginal Relevance (MMR) picks results that are relevant to the query and different from each other, so the LLM sees more distinct evidence.
The algorithm
MMR builds the result list one item at a time. At each step it picks the candidate with the highest MMR score:
MMR = λ × similarity(candidate, query) − (1 − λ) × max similarity(candidate, already selected)
- The first term rewards relevance.
- The second term penalises candidates that are similar to something already chosen.
- λ (lambda), between 0 and 1, sets the balance. λ = 1 is plain top-k; λ = 0 maximises diversity and ignores relevance. Values from 0.5 to 0.8 are common.
MMR is usually applied to a candidate pool (for example the top 30 results), not the whole collection.
Implementation
import numpy as np
def mmr(query_vec: np.ndarray, doc_vecs: np.ndarray, k: int = 5, lambda_: float = 0.7,
pool: int = 30) -> list[int]:
"""Return indices of k documents chosen by Maximal Marginal Relevance.
All vectors must be normalised."""
relevance = doc_vecs @ query_vec
candidates = list(np.argsort(-relevance)[:pool])
selected: list[int] = []
while candidates and len(selected) < k:
if not selected:
best = candidates[0] # most relevant first
else:
redundancy = (doc_vecs[candidates] @ doc_vecs[selected].T).max(axis=1)
scores = lambda_ * relevance[candidates] - (1 - lambda_) * redundancy
best = candidates[int(np.argmax(scores))]
selected.append(best)
candidates.remove(best)
return selected
See the difference
from rag_helpers import embed
docs = [
"Employees get 18 days of paid leave in their first year.", # v2026
"Employees receive 18 days of paid leave during their first year.", # v2025 (near-duplicate)
"In the first year, staff are entitled to 18 paid leave days.", # FAQ (near-duplicate)
"Up to 5 unused leave days can be carried over to next year.",
"Leave requests must be approved by your manager in the HR portal.",
]
vecs = embed(docs)
q = embed("Tell me about the leave policy", query=True)[0]
print("top-k:")
for i in np.argsort(-(vecs @ q))[:3]:
print(" ", docs[i])
print("MMR:")
for i in mmr(q, vecs, k=3, lambda_=0.5):
print(" ", docs[i])
top-k:
Employees get 18 days of paid leave in their first year.
Employees receive 18 days of paid leave during their first year.
In the first year, staff are entitled to 18 paid leave days.
MMR:
Employees get 18 days of paid leave in their first year.
Leave requests must be approved by your manager in the HR portal.
Up to 5 unused leave days can be carried over to next year.
Plain top-k spends all three slots on the same fact. MMR covers three different aspects of the leave policy.
Using MMR in libraries
Many tools have MMR built in. In LangChain, any vector store retriever can use it:
retriever = vector_store.as_retriever(
search_type="mmr",
search_kwargs={"k": 5, "fetch_k": 30, "lambda_mult": 0.6},
)
When to use MMR
- Broad questions ("Summarise our leave policy", "What are the risks mentioned in the report?") benefit from diverse coverage.
- Collections with many near-duplicates, such as versions, mirrors and templated pages. Deduplication at indexing time (Cleaning and Deduplication) is the first fix; MMR handles what remains.
- Narrow factual questions may get slightly worse with strong diversity, because the second-best chunk is often a useful confirmation. Use a high λ (0.7 to 0.9) for such workloads.
Key takeaways
- MMR balances relevance to the query against similarity to already-selected results.
- λ controls the balance: 1 is plain top-k, lower values add diversity.
- Apply MMR to a candidate pool of the top 20 to 50 results.
- It helps most for broad questions and collections with near-duplicates.