Diverse Retrieval with Maximal Marginal Relevance

medium
Unit 4 · RAG II0/3 to milestone

Top-k retrieval often returns five near-identical chunks, wasting the LLM's context window. Maximal Marginal Relevance (MMR) picks results that are relevant to the query and different from what's already been chosen:

MMR(d)=λ⋅sim(d,q)−(1−λ)⋅max⁡s∈Ssim(d,s)\text{MMR}(d) = \lambda \cdot \text{sim}(d, q) - (1 - \lambda) \cdot \max_{s \in S} \text{sim}(d, s)

Start with an empty selection SS. Repeatedly add the remaining document with the highest MMR score until kk are chosen. While SS is empty, the diversity term is 0. Similarity is cosine similarity. Break ties by the lower index.

Implement mmr(query, docs, k, lam=0.5) returning the indices of the chosen documents, in selection order. docs has shape (n, d). If k > n, return all indices.

#rag#retrieval#ranking2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Diverse Retrieval with Maximal Marginal Relevance · TechGradify