Algorithm Search⌘K

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
Properties
deterministiciterative
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 λ\lambda sets the balance: λ=1\lambda = 1 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 RR of nn candidate documents, usually the top of a first ranking, a relevance score Sim1(d,q)\mathrm{Sim}_1(d, q) for each, a similarity Sim2(d,d′)\mathrm{Sim}_2(d, d') between documents, λ∈[0,1]\lambda \in [0, 1] and a length kk. The output is a list of min⁡(k,n)\min(k, n) 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 SS the list chosen so far, the next document is

d∗=arg⁡max⁡d∈R∖S[λ Sim1(d,q)−(1−λ)max⁡d′∈SSim2(d,d′)].d^\ast = \arg\max_{d \in R \setminus S} \Big[ \lambda\, \mathrm{Sim}_1(d, q) - (1 - \lambda) \max_{d' \in S} \mathrm{Sim}_2(d, d') \Big].

The maximum over the empty set is taken as 0, so for λ>0\lambda > 0 the first pick is the most relevant document. Ties go to the smaller document id. The largest similarity of each candidate to SS only changes by one new term per step, so the procedure keeps it in an array:

  1. MMR(R, rel, sim, λ, k)
  2. 1rest ← R sorted by id
  3. 2S ← empty list
  4. 3for each d in rest: closest[d] ← 0
  5. 4while rest is not empty and |S| < k:
  6. 5for each d in rest:
  7. 6score(d) ← λ · rel(d) − (1 − λ) · closest[d]
  8. 7b ← the d with the largest score, ties to the smaller id; move b from rest to S
  9. 8for each d in rest:
  10. 9closest[d] ← sim(d, b) if |S| = 1, else max(closest[d], sim(d, b))
  11. 10return 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 λ=1\lambda = 1 the order is the ranking by relevance, d4, d3, d5, with the tie of d3 and d5 broken by the id. With λ=0.7\lambda = 0.7:

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 0.3⋅0.4226=0.12680.3 \cdot 0.4226 = 0.1268 for its overlap with d4, while d5 loses only 0.3⋅0.1690=0.05070.3 \cdot 0.1690 = 0.0507, so d5, the document that the judgments of the collection rate highest for q2, moves up to second place. With λ=0.5\lambda = 0.5 the order becomes d4, d5, d2: d3 is now penalized below d2, which is not relevant at all. Too small a λ\lambda trades relevance for difference, which is why λ\lambda 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, closest[d]\mathrm{closest}[d] is the largest similarity of dd to the chosen documents, or 0 before the first pick. Line L9 keeps it, because the maximum over S∪{b}S \cup \{b\} is the larger of the maximum over SS and sim(d,b)\mathrm{sim}(d, b). Then line L6 computes the MMR score exactly. The proof also shows the two ends of the range: λ=1\lambda = 1 gives the ranking by relevance, and λ=0\lambda = 0 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 RR be a finite set of candidate ids with a total order, rel:R→R\mathrm{rel} : R \to \mathbb{R}, sim:R×R→R\mathrm{sim} : R \times R \to \mathbb{R} and λ∈[0,1]\lambda \in [0, 1]. For a chosen list SS (as a set) and d∈R∖Sd \in R \setminus S, define the penalty πS(d)=max⁡j∈Ssim(d,j)\pi_S(d) = \max_{j \in S} \mathrm{sim}(d, j) for S≠∅S \ne \emptyset and π∅(d)=0\pi_\emptyset(d) = 0, and the MMR score

MMRS(d)=λ rel(d)−(1−λ) πS(d).\mathrm{MMR}_S(d) = \lambda\, \mathrm{rel}(d) - (1 - \lambda)\, \pi_S(d).

The MMR selection of Carbonell and Goldstein, with the tie rule of this page, is the list s1,…,sms_1, \ldots, s_m with m=min⁡(k,∣R∣)m = \min(k, |R|), where sts_t is the smallest id among the maximizers of MMRSt−1\mathrm{MMR}_{S_{t-1}} over R∖St−1R \setminus S_{t-1} and St={s1,…,st}S_t = \{s_1, \ldots, s_t\}.

Lemma 1 (invariant). At the start of each pass of the loop of line L4, with SS the set of ids chosen so far, closest[d]=πS(d)\mathrm{closest}[d] = \pi_S(d) for every remaining dd.

Proof. By induction on ∣S∣|S|. For S=∅S = \emptyset, line L3 sets every value to 0=π∅(d)0 = \pi_\emptyset(d). Suppose the claim holds before a pass that adds bb, so S′=S∪{b}S' = S \cup \{b\}. If S=∅S = \emptyset, lines L8 and L9 set closest[d]=sim(d,b)=π{b}(d)\mathrm{closest}[d] = \mathrm{sim}(d, b) = \pi_{\{b\}}(d) for every remaining dd, whatever its sign. Otherwise they set closest[d]=max⁡(πS(d),sim(d,b))=πS′(d)\mathrm{closest}[d] = \max(\pi_S(d), \mathrm{sim}(d, b)) = \pi_{S'}(d), because the maximum over S′S' is the larger of the maximum over SS and the new term. □\square

Theorem 2 (output). The procedure returns s1,…,sms_1, \ldots, s_m, each with its score MMRSt−1(st)\mathrm{MMR}_{S_{t-1}}(s_t).

Proof. By Lemma 1, line L6 computes MMRS(d)\mathrm{MMR}_S(d) for each remaining dd. 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 sts_t. Line L7 records it with its score and removes it. The loop runs while ids remain and fewer than kk are chosen, so it makes mm passes. □\square

Corollary 3 (the ends of the range of lambda). For λ=1\lambda = 1 the output is the first mm ids in the order rel descending, then id ascending. For λ=0\lambda = 0 the first pick is the smallest id, because every score is 00, and each later pick minimizes the largest similarity to the chosen ids.

Proof. For λ=1\lambda = 1 the score is rel(d)\mathrm{rel}(d) and does not depend on SS, so the picks are the remaining maxima in turn. For λ=0\lambda = 0 the score is −πS(d)-\pi_S(d). □\square

Cost. Let n=∣R∣n = |R|. Each of the m≤km \le k passes scores at most nn ids in line L6 and calls sim\mathrm{sim} at most nn times in line L8, so the procedure makes at most nknk calls of sim\mathrm{sim} and O(nk)O(nk) other operations, after the sort of line L1 in O(nlog⁡n)O(n \log n). It keeps one value for each id, O(n)O(n) extra space. The direct form of the formula recomputes πS\pi_S from scratch and calls sim\mathrm{sim} O(nk2)O(nk^2) 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 0.250.25 so that ties are frequent.

Complexity

Each of the at most kk passes scores at most nn documents and computes at most nn similarities, so MMR makes at most nknk calls of Sim2\mathrm{Sim}_2 and O(nk)O(nk) other work, after an O(nlog⁡n)O(n \log n) sort of the ids. It keeps one value per candidate, O(n)O(n) extra space. If a similarity costs O(t)O(t) time, as a cosine of sparse vectors with tt terms does, the total is O(nkt)O(nkt). The direct form of the formula, which recomputes the maximum over SS at every step, needs O(nk2)O(nk^2) 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 λ\lambda to mean anything.
  • Reduces to relevance ranking. With λ=1\lambda = 1 the output is the first ranking, so MMR can only help when λ<1\lambda < 1.
  • 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 SS, 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 λ\lambda 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, λ\lambda weights relevance; in xQuAD, λ\lambda 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, nknk 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 λ\lambda 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.

irtoy.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example