Skip to content
AI360Xpert
Gen AI

Maximal Marginal Relevance (MMR)

MMR balances relevance with diversity. It scores documents not just on how well they match the query, but on how different they are from the documents already selected.

MMR rejects highly relevant documents if they are identical to documents already in the results list, forcing the system to retrieve diverse perspectives.
MMR rejects highly relevant documents if they are identical to documents already in the results list, forcing the system to retrieve diverse perspectives.

Why Does This Exist?

Imagine you are using a RAG (Retrieval-Augmented Generation) pipeline to ask the question, "What were the causes of the 2008 financial crisis?"

If your dense vector search simply returns the top 5 most similar documents, those 5 documents might all be different news articles covering the exact same event on the exact same day. They are all highly relevant to the query, but they are completely redundant with each other. If you feed those 5 identical articles into an LLM, the LLM won't learn about the housing bubble, the credit rating agencies, and the deregulation; it will just get the same narrow perspective repeated 5 times.

Maximal Marginal Relevance (MMR) is a reranking algorithm designed to solve this exact problem. It forces the retrieval system to balance relevance (how well the document matches the query) with diversity (how different the document is from the ones you've already selected). By introducing a diversity penalty, MMR ensures that the final list of documents covers the broadest possible semantic space for the user's query.

Think of It Like This

Drafting a fantasy sports team

Imagine you are drafting a fantasy basketball team, and you want the "best" team possible.

If you use standard vector search, you just sort all the players in the league by their total points scored and draft the top 5. The result? You draft 5 point guards. Sure, they are the 5 highest-scoring players individually, but as a team, you have no centers, no forwards, and no defense. Your team will fail.

If you use MMR, you draft your first player based purely on points (relevance). When drafting your second player, you look at their points, but you subtract points if they play the same position as your first draft pick (diversity penalty). You end up drafting the best point guard, the best center, the best forward, etc. The individual players might not be the absolute top 5 scorers in the league, but the combined team is vastly superior because it covers all the necessary bases.

How It Actually Works

The Tradeoff Formula

MMR is applied as a second-stage reranker. First, you retrieve a candidate pool of documents (e.g., the top 20) using standard semantic search. Then, MMR iteratively selects the best documents from that pool to form the final result list (e.g., the top 5).

At each step, MMR chooses the document DiD_i from the unselected pool that maximizes the following formula:

MMR=λSim1(Di,Q)(1λ)maxDjSSim2(Di,Dj)\text{MMR} = \lambda \cdot \text{Sim}_1(D_i, Q) - (1 - \lambda) \cdot \max_{D_j \in S} \text{Sim}_2(D_i, D_j)

Let's break this down:

  • QQ: The user's query.
  • DiD_i: The candidate document we are evaluating.
  • SS: The set of documents we have already selected.
  • Sim1(Di,Q)\text{Sim}_1(D_i, Q): The relevance score. How similar is the document to the query?
  • maxSim2(Di,Dj)\max \text{Sim}_2(D_i, D_j): The redundancy penalty. We compare the candidate document to every document we've already selected (DjSD_j \in S) and find the maximum similarity. If it's highly similar to any already-selected document, the penalty is high.
  • λ\lambda (Lambda): The tradeoff parameter between 0 and 1.

Tuning the Lambda (λ\lambda) Parameter

The λ\lambda parameter is the dial you turn to control the behavior of the search:

  • λ=1.0\lambda = 1.0: Pure relevance. The redundancy penalty is multiplied by zero (11=0)(1 - 1 = 0). The algorithm behaves exactly like standard vector search.
  • λ=0.5\lambda = 0.5: A balanced approach. Equal weight is given to matching the query and avoiding redundancy.
  • λ=0.0\lambda = 0.0: Pure diversity. The algorithm completely ignores the query and just tries to pick documents that are as different from each other as possible. (Rarely used in practice).

In most RAG applications, λ\lambda is tuned empirically, usually landing between 0.5 and 0.8.

Show Me the Code

You can easily implement MMR in Python using numpy and cosine similarity. Notice how the list of selected documents is built up iteratively.

import numpy as np
def cosine_similarity(a, b):    # Dot product of normalized vectors    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def mmr(query_vector, doc_vectors, top_k=3, lambda_param=0.5):    """    Selects top_k documents using Maximal Marginal Relevance.    """    unselected = list(range(len(doc_vectors)))    selected = []        # Step 1: Compute relevance scores for all documents to the query    relevance_scores = [cosine_similarity(query_vector, doc) for doc in doc_vectors]        # Step 2: Iteratively select the best document    while len(selected) < top_k and unselected:        mmr_scores = []                for i in unselected:            relevance = relevance_scores[i]                        # If nothing is selected yet, there is no redundancy penalty            if not selected:                redundancy = 0.0            else:                # Find the maximum similarity between candidate i and all selected docs                redundancy = max([cosine_similarity(doc_vectors[i], doc_vectors[s]) for s in selected])                        # The core MMR formula            score = lambda_param * relevance - (1 - lambda_param) * redundancy            mmr_scores.append((score, i))                # Pick the document with the highest MMR score in this iteration        best_score, best_idx = max(mmr_scores, key=lambda x: x[0])                selected.append(best_idx)        unselected.remove(best_idx)            return selected
# --- Dummy Data ---# Let's say these are 1D vectors for simplicityquery = np.array([1.0, 0.0])
# Docs 0, 1, and 2 are highly relevant (high X value) but nearly identical to each other.# Doc 3 is less relevant but entirely different (high Y value).docs = [    np.array([0.99, 0.10]), # highly relevant to [1, 0]    np.array([0.98, 0.15]), # highly relevant, redundant with Doc 0    np.array([0.97, 0.20]), # highly relevant, redundant with Doc 0    np.array([0.60, 0.80])  # less relevant, but very diverse]
print("Standard Search (Lambda=1.0):", mmr(query, docs, top_k=2, lambda_param=1.0))# -> Standard Search (Lambda=1.0): [0, 1] (Returns two identical documents)
print("MMR Search (Lambda=0.5):", mmr(query, docs, top_k=2, lambda_param=0.5))# -> MMR Search (Lambda=0.5): [0, 3] (Returns Doc 0, penalizes Doc 1 & 2, grabs diverse Doc 3)

Watch Out For

Computational cost on large candidate pools

MMR is an O(N2)O(N^2) algorithm relative to the size of the candidate pool. At each iteration, you must compute the similarity between every unselected document and every selected document. If you try to run MMR on a candidate pool of 10,000 documents, the nested loops will cause a massive latency spike. This is why MMR is strictly a reranking step—you should only ever apply it to a small pool (e.g., the top 20 to 100 documents) returned by a fast vector database.

The Quick Version

  • Standard vector search returns the most relevant documents, which often results in highly redundant, overlapping content.
  • MMR (Maximal Marginal Relevance) is a reranking algorithm that balances relevance with diversity.
  • It iterates through a candidate pool, scoring documents positively for matching the query, but penalizing them if they are too similar to documents already selected.
  • The λ\lambda parameter allows you to tune the exact tradeoff: λ=1\lambda=1 is pure relevance, while lower values introduce more diversity.
  • Read Reranking for an overview of the two-stage retrieval pipeline where MMR is typically deployed.
  • Read Late Interaction Retrieval (ColBERT) to learn about another powerful, computationally heavy reranking strategy.
  • Read Similarity Metrics to understand the mathematical distance functions (like Cosine Similarity) that power the MMR formula.

Related concepts