Algorithmcore
Maximal marginal relevance
Also called MMR.
Greedily adds the document that maximizes lambda times relevance minus (1 - lambda) times maximum similarity to those already chosen.
- Time
- O(n log n + n k) worst
- Space
- O(n) extra
- Where
- k = the number of results; n = the number of candidates
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jaime Carbonell, Jade Goldstein, 1998
Maximal marginal relevance (MMR) is a greedy method that reorders a list of retrieved documents so that each new document is both relevant to the query and different from the documents already chosen. Jaime Carbonell and Jade Goldstein introduced it in 1998, for search results and for summaries built from sentences. One parameter sets the balance: gives the plain ranking by relevance, and smaller values push near duplicates down. The problem itself, and the methods that model the intents of a query explicitly, such as IA-Select and xQuAD, are on the search result diversification page; MMR is the implicit method, which only looks at how similar the documents are to each other.
In plain words
Suppose a search returns ten pages that all say the same thing. The first is useful, but the next nine add little. MMR builds the result list one item at a time. It always takes the item with the best balance of two things: how well it matches the query, and how different it is from everything already in the list. An item that is almost a copy of one already chosen gets a large penalty, even if it matches the query well. A slider decides how much the difference counts, from not at all to a lot.
The problem
The input is a set of candidate documents, usually the top of a first ranking, a relevance score for each, a similarity between documents, and a length . The output is a list of documents. Carbonell and Goldstein allow any two similarity functions; the usual choice is cosine similarity of term vectors for both. The method is a heuristic: it does not claim to optimize a stated measure of the whole list, so its gains on diversity metrics are measured on test collections.
The algorithm
With the list chosen so far, the next document is
The maximum over the empty set is taken as 0, so for the first pick is the most relevant document. Ties go to the smaller document id. The largest similarity of each candidate to only changes by one new term per step, so the procedure keeps it in an array:
MMR(R, rel, sim, λ, k)- 1
rest ← R sorted by id - 2
S ← empty list - 3
for each d in rest: closest[d] ← 0 - 4
while rest is not empty and |S| < k: - 5
for each d in rest: - 6
score(d) ← λ · rel(d) − (1 − λ) · closest[d] - 7
b ← the d with the largest score, ties to the smaller id; move b from rest to S - 8
for each d in rest: - 9
closest[d] ← sim(d, b) if |S| = 1, else max(closest[d], sim(d, b)) - 10
return S
Example
Take query q2, "posting list merge", on the eight documents of the shared toy collection. Both similarities are cosines of raw term-count vectors, with no stop words removed. Four documents share a term with the query:
| doc | text | rel |
|---|---|---|
| d2 | merge sort merges two sorted runs into one sorted array | 0.1667 |
| d3 | an inverted index maps each term to a posting list | 0.3651 |
| d4 | a posting list is a sorted list of document ids | 0.4629 |
| d5 | skip pointers speed up the merge of two posting lists | 0.3651 |
The similarities to d4 are 0.1543 for d2, 0.4226 for d3 and 0.1690 for d5: d3 and d4 share "a", "posting" and "list". With the order is the ranking by relevance, d4, d3, d5, with the tie of d3 and d5 broken by the id. With :
| step | d2 | d3 | d4 | d5 | pick |
|---|---|---|---|---|---|
| 1 | 0.1167 | 0.2556 | 0.3240 | 0.2556 | d4 |
| 2 | 0.0704 | 0.1288 | 0.2049 | d5 | |
| 3 | 0.0619 | 0.1288 | d3 |
At step 2, d3 loses for its overlap with d4, while d5 loses only , so d5, the document that the judgments of the collection rate highest for q2, moves up to second place. With the order becomes d4, d5, d2: d3 is now penalized below d2, which is not relevant at all. Too small a trades relevance for difference, which is why is tuned on judged queries.
Correctness
The file proofs/correctness.md proves that the loop picks, at every step, the document of the MMR formula with the tie rule. The invariant is that before each pass, is the largest similarity of to the chosen documents, or 0 before the first pick. Line L9 keeps it, because the maximum over is the larger of the maximum over and . Then line L6 computes the MMR score exactly. The proof also shows the two ends of the range: gives the ranking by relevance, and ignores relevance entirely: every first score is 0, so the first pick is the smallest id, and each later pick is the document least similar to the chosen ones.
Proof: The incremental MMR loop picks the item of the MMR formula at every stepfull
Let be a finite set of candidate ids with a total order, , and . For a chosen list (as a set) and , define the penalty for and , and the MMR score
The MMR selection of Carbonell and Goldstein, with the tie rule of this page, is the list with , where is the smallest id among the maximizers of over and .
Lemma 1 (invariant). At the start of each pass of the loop of line L4, with the set of ids chosen so far, for every remaining .
Proof. By induction on . For , line L3 sets every value to . Suppose the claim holds before a pass that adds , so . If , lines L8 and L9 set for every remaining , whatever its sign. Otherwise they set , because the maximum over is the larger of the maximum over and the new term.
Theorem 2 (output). The procedure returns , each with its score .
Proof. By Lemma 1, line L6 computes for each remaining . Line L1 sorts the ids, and the scan of line L5 replaces the current best only on a strictly larger score, so it keeps the smallest id among the maximizers, which is . Line L7 records it with its score and removes it. The loop runs while ids remain and fewer than are chosen, so it makes passes.
Corollary 3 (the ends of the range of lambda). For the output is the first ids in the order rel descending, then id ascending. For the first pick is the smallest id, because every score is , and each later pick minimizes the largest similarity to the chosen ids.
Proof. For the score is and does not depend on , so the picks are the remaining maxima in turn. For the score is .
Cost. Let . Each of the passes scores at most ids in line L6 and calls at most times in line L8, so the procedure makes at most calls of and other operations, after the sort of line L1 in . It keeps one value for each id, extra space. The direct form of the formula recomputes from scratch and calls times.
The test file checks Theorem 2 step by step against that direct form, on the toy collection and on random instances, many of them with values on a grid of so that ties are frequent.
Complexity
Each of the at most passes scores at most documents and computes at most similarities, so MMR makes at most calls of and other work, after an sort of the ids. It keeps one value per candidate, extra space. If a similarity costs time, as a cosine of sparse vectors with terms does, the total is . The direct form of the formula, which recomputes the maximum over at every step, needs similarities.
Properties
- Greedy and myopic. Each pick is final, and MMR does not look ahead. It gives no approximation guarantee for an objective of the whole list.
- Implicit. It knows nothing about the intents of the query. It assumes that documents that are different from each other cover different needs, which Santos, Macdonald and Ounis call implicit diversification.
- Scale-sensitive. Relevance and similarity are subtracted, so they must be on comparable scales for to mean anything.
- Reduces to relevance ranking. With the output is the first ranking, so MMR can only help when .
- Deterministic. The tie rule fixes the output.
Variants and improvements
- Other similarities. Any measure works, such as Jaccard similarity of shingles, distances between embeddings, or the overlap of topic distributions.
- Summaries. Carbonell and Goldstein also used MMR to choose sentences for a summary, with sentences in the place of documents. It is still a common baseline for extractive summarization.
- Recommendation and retrieval for language models. Recommender systems and retrieval-augmented generation use MMR to pick a varied set of items or passages from the top of a nearest-neighbour search.
- Explicit methods. When the intents of a query are known, IA-Select and xQuAD reward the coverage of each intent. They have the same greedy shape, with a novelty term per intent in place of the largest similarity.
- Sum in place of maximum. Some variants penalize the sum or the average similarity to , which punishes a document that resembles many chosen documents a little.
When to use it
Use MMR when the top of a ranking contains near duplicates and you have no model of the intents of the query: it needs only a similarity function and one parameter. Tune on judged queries with a diversity measure such as alpha-nDCG, and expect the best value to be close to 1 when the first ranking is good. If query intents are available, the explicit methods usually do better in the published comparisons, which are measurements on specific test collections.
Pitfalls
- The meaning of lambda. In MMR, weights relevance; in xQuAD, weights diversity. Do not carry a tuned value from one to the other.
- Scores on different scales. A relevance score such as BM25 is not bounded by 1, while a cosine is. Normalize the relevance scores, for example by dividing by the largest, before mixing them with similarities.
- Shared stop words. Raw cosines are dominated by words such as "a" and "the", as in the example. Use tf-idf weights or remove stop words before computing similarities.
- Quadratic similarity cost. For long lists, similarities of long vectors are the main cost. Rerank only the top few hundred documents.
- Different is not useful. A document can be different from the chosen ones because it is off topic. Keep large enough that relevance still counts.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
maximal_marginal_relevance.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-marginal-relevance/. The authors are listed in prov/2ZKYCZ.jsonl.
"""Maximal marginal relevance (Carbonell and Goldstein, 1998).
Greedy selection of k items from a candidate list. At each step the item
with the largest
lam * rel(d) - (1 - lam) * max over chosen j of sim(d, j)
is added; for the first pick the maximum over the empty set is taken as 0.
Ties go to the smaller id. The largest similarity of each remaining item
to the chosen set is kept up to date, so each step costs one similarity
per remaining item.
"""
def mmr_steps(candidates, rel, sim, lam, k):
"""Return the list of (id, MMR score at the time it was picked)."""
if not 0.0 <= lam <= 1.0:
raise ValueError("lam must lie in [0, 1]")
remaining = sorted(set(candidates)) # @line L1
chosen = [] # @line L2
closest = {d: 0.0 for d in remaining} # @line L3
while remaining and len(chosen) < k: # @line L4
best, best_score = None, None
for d in remaining: # @line L5
score = lam * rel[d] - (1.0 - lam) * closest[d] # @line L6
if best_score is None or score > best_score: # ties keep the smaller id
best, best_score = d, score
chosen.append((best, best_score)) # @line L7
remaining.remove(best)
for d in remaining: # @line L8
s = sim(d, best)
if len(chosen) == 1 or s > closest[d]:
closest[d] = s # @line L9
return chosen # @line L10
def mmr(candidates, rel, sim, lam, k):
"""Return the ids that MMR picks, in order."""
return [d for d, _ in mmr_steps(candidates, rel, sim, lam, k)]
test_maximal_marginal_relevance.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-marginal-relevance/. The authors are listed in prov/2ZKYCZ.jsonl.
import math
import random
from collections import Counter
import pytest
import irtoy
from maximal_marginal_relevance import mmr, mmr_steps
TOL = 1e-12
VEC = {d: Counter(irtoy.tokenize(irtoy.DOCS[d])) for d in irtoy.DOCS}
def cosine(a, b):
dot = sum(a[t] * b[t] for t in a)
if dot == 0:
return 0.0
return dot / math.sqrt(sum(x * x for x in a.values()) * sum(x * x for x in b.values()))
def toy(qid):
q = Counter(irtoy.tokenize(irtoy.QUERIES[qid]))
rel = {d: cosine(q, VEC[d]) for d in VEC}
cands = [d for d in VEC if rel[d] > 0]
return cands, rel, lambda i, j: cosine(VEC[i], VEC[j])
def direct(candidates, rel, sim, lam, k):
"""The formula of Carbonell and Goldstein, with the maximum over S recomputed at every step."""
s, out = [], []
rest = sorted(set(candidates))
while rest and len(s) < k:
scores = {}
for d in rest:
penalty = max((sim(d, j) for j in s), default=0.0)
scores[d] = lam * rel[d] - (1 - lam) * penalty
top = max(scores.values())
pick = min(d for d in rest if scores[d] == top)
out.append((pick, top, scores))
s.append(pick)
rest.remove(pick)
return out
def assert_same(got, want):
assert [d for d, _ in got] == [d for d, _, _ in want]
for (d, score), (_, top, _) in zip(got, want):
assert math.isclose(score, top, rel_tol=TOL, abs_tol=TOL)
def test_example_of_the_page():
cands, rel, sim = toy("q2")
assert cands == [2, 3, 4, 5]
assert mmr(cands, rel, sim, 1.0, 3) == [4, 3, 5]
assert mmr(cands, rel, sim, 0.7, 3) == [4, 5, 3]
assert mmr(cands, rel, sim, 0.5, 3) == [4, 5, 2]
steps = mmr_steps(cands, rel, sim, 0.7, 3)
assert math.isclose(steps[0][1], 0.7 * rel[4], rel_tol=TOL)
assert math.isclose(steps[1][1], 0.7 * rel[5] - 0.3 * sim(5, 4), rel_tol=TOL)
@pytest.mark.parametrize("qid", ["q1", "q2", "q3"])
@pytest.mark.parametrize("lam", [0.0, 0.3, 0.5, 0.7, 1.0])
def test_toy_matches_the_formula(qid, lam):
cands, rel, sim = toy(qid)
for k in range(len(cands) + 2):
assert_same(mmr_steps(cands, rel, sim, lam, k), direct(cands, rel, sim, lam, k))
@pytest.mark.parametrize("seed", range(200))
def test_random_instances_match_the_formula(seed):
rng = random.Random(seed)
n = rng.randint(1, 12)
coarse = seed % 2 == 0 # values on a grid of 0.25 force many ties
val = (lambda: rng.randint(0, 4) / 4) if coarse else rng.random
ids = rng.sample(range(100), n)
rel = {d: val() for d in ids}
m = {}
for a in ids:
for b in ids:
if a < b:
m[a, b] = m[b, a] = val()
sim = lambda i, j: m[i, j]
lam = rng.choice([0.0, 0.25, 0.5, 0.75, 1.0, rng.random()])
k = rng.randint(0, n + 1)
assert_same(mmr_steps(ids, rel, sim, lam, k), direct(ids, rel, sim, lam, k))
def test_lambda_one_is_ranking_by_relevance():
rng = random.Random(7)
ids = list(range(10))
rel = {d: rng.random() for d in ids}
order = sorted(ids, key=lambda d: (-rel[d], d))
assert mmr(ids, rel, lambda i, j: rng.random(), 1.0, 10) == order
def test_rejects_bad_lambda():
with pytest.raises(ValueError):
mmr([1], {1: 1.0}, lambda i, j: 0.0, 1.5, 1)
History
Carbonell and Goldstein presented MMR in a two-page paper at SIGIR 1998. They built it at Carnegie Mellon for reranking search results and for single and multi-document summaries, and they described it as a balance of relevance and novelty. The method became the standard implicit approach to diversification, and later methods such as IA-Select in 2009 and xQuAD in 2010 kept its greedy form while modelling the intents of the query. The paper was reprinted in SIGIR Forum in 2017.
References
- Jaime Carbonell and Jade Goldstein, The use of MMR, diversity-based reranking for reordering documents and producing summaries, Proceedings of the 21st Annual International ACM SIGIR Conference (SIGIR 1998), 335-336, the definition of MMR as the argmax over the unselected documents of lambda Sim1(Di, Q) minus (1 - lambda) times the largest Sim2(Di, Dj) over the selected documents, and its use for reranking and for summaries
- Jaime Carbonell and Jade Goldstein, The use of MMR, diversity-based reranking for reordering documents and producing summaries, ACM SIGIR Forum 51(2), 2017, the reprint of the 1998 paper
- Rodrygo L. T. Santos, Craig Macdonald and Iadh Ounis, Exploiting query reformulations for web search result diversification, Proceedings of the 19th International Conference on World Wide Web (WWW 2010), 881-890, Section 2 (MMR as the canonical implicit diversification method, which assumes that similar documents cover similar aspects) and Section 6 (MMR with a trained lambda as a baseline on the TREC 2009 Web track)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2ZKYCZ Edit this page History Report an error Markdown