WRITE · TRACE · UNDERSTAND

Diversify retrieved evidence with maximal marginal relevance

Documents contain unique string id and finite vector matching a nonempty finite query vector.

Read lesson: Diversify retrieved evidence with maximal marginal relevance →

Your experiment

Documents contain unique string id and finite vector matching a nonempty finite query vector. Require integer k>=0 and relevance_weight in [0,1]. Greedily maximize weight*cos(query,document)-(1-weight)*maximum cosine to an already selected document, using zero redundancy for the first choice. A zero vector has cosine zero. Break score ties by smaller id. Return selected IDs, never repeating a document.

Python runs in your browser. Your draft stays on this device.

What to look for

Review the embedding metric, relevance weight, duplicate policy and tie behavior. Permission filtering must happen before these candidates reach the reranker.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Diversify retrieved evidence with maximal marginal relevance works

The idea

The top results of a similarity search are often near copies of each other, and five versions of one passage tell a model no more than one does. Maximal marginal relevance, MMR, picks results one at a time and scores each candidate as relevance_weight * similarity - (1 - relevance_weight) * redundancy. Similarity is its cosine to the query. Redundancy is its highest cosine to anything already selected.

What makes it work is that the score is recomputed after every pick. A document that looked best on its own loses value the moment a close neighbour is chosen, so the next pick tends to cover something new. With relevance_weight at 1 this is plain ranking by cosine, and lower values trade relevance for variety.

How it works

  1. Validate k, a relevance_weight between 0 and 1, a non-empty finite query, unique string ids and vectors of matching length.
  2. Define cosine(a, b) so that any zero vector gives 0.
  3. For each document in remaining, compute its cosine to the query and its largest cosine to a document in selected, or 0 if none is selected.
  4. Score it as relevance_weight * similarity - (1 - relevance_weight) * redundancy.
  5. Move the best-scoring document from remaining to selected, with equal scores going to the smaller id.
  6. Repeat until k documents are chosen or none remain, then return the selected ids in pick order.

What it costs

Time
O(k² · n · d) here
Space
O(n)

This answer recomputes every cosine in each of the k rounds; caching the query similarities and each candidate's running maximum reduces the work to about k times n times d.

Where it is used

  • LangChain vector stores offer max_marginal_relevance_search, which fetches fetch_k candidates and returns k chosen by MMR with a lambda_mult weight.
  • Carbonell and Goldstein introduced MMR in 1998 for reranking search results and for selecting sentences in summaries.
  • KeyBERT can apply MMR, through use_mmr=True and a diversity setting, so that extracted keyphrases are not near duplicates.

Watch out for

  • Computing all scores once and sorting: redundancy depends on what has been picked, so scores must be recomputed every round.
  • Using the average similarity to the selected set in place of the maximum, which lets a near copy of one selected document through.
  • Breaking ties by input order: the Lab requires the smaller id, so reversing the input must not change the answer.