Re-rank retrieved chunks for diversity with maximal marginal relevance
Top-k by similarity often returns near-duplicate chunks, wasting the context window. Maximal marginal relevance (MMR) picks chunks one at a time, rewarding similarity to the query and penalizing similarity to chunks already picked.
Write mmr_select(query, docs, k, lam). query has shape (d,), docs has shape (n, d). Use cosine similarity everywhere.
- Start with an empty selected list.
- Repeat k times (or until all docs are picked): for every unpicked doc i, compute lam * cos(query, doc_i) - (1 - lam) * max over picked j of cos(doc_i, doc_j). When nothing is picked yet, the max term is 0.
- Pick the doc with the highest value. Ties: lowest index.
Return the list of picked indices in pick order.
def mmr_select(query, docs, k, lam)Example
with lam = 1 MMR is plain top-k by cosine similarity; with lam = 0 it only avoids redundancy.
Understand the idea
Plain top-k retrieval often returns several near copies of the same chunk, wasting the context window. Maximal marginal relevance picks chunks one at a time and asks two questions: how relevant is this to the query, and how similar is it to something I already picked? A near duplicate of a chosen chunk gets pushed down. Worked example: query q = [1, 1], docs d0 = [1, 0], d1 = [1, 0.05], d2 = [0, 1], lam = 0.5. Cosines with q: 0.7071, 0.7415, 0.7071. First pick: no redundancy yet, so d1 wins. Second pick: d0 scores 0.5 * 0.7071 - 0.5 * cos(d0, d1) = 0.3536 - 0.4994 = -0.1458; d2 scores 0.3536 - 0.5 * 0.0499 = 0.3286. So d2 is picked, giving [1, 2], while plain top-k would give [1, 0]. Rule: value(i) = lam * cos(q, d_i) - (1 - lam) * max over picked j of cos(d_i, d_j), with the max term 0 when nothing is picked; take the highest, lowest index on ties; repeat k times. Use the max, not an average. MMR is used to diversify context passed to an LLM in RAG.