AI Hints
Home›RAG Tutorial›Context and Variety
RAG · Lesson 65 of 120

MMR

Varied results.

⏱ 2 min read▶ Video at 1:04:39🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Sometimes the top results all say the same thing, from the same page. That wastes space in the prompt. Maximal marginal relevance, or MMR, picks results that are relevant, but also different from each other.

MMR
From the video: MMR
  • Top results repeat
  • Wasted space
  • Relevant and different

Picking varied results

MMR fetches ten candidates. It picks one at a time. Each pick scores high on the question, minus how close it is to chunks already picked. Lambda balances the two. Run it. Plain search takes two chunks from the error page. MMR swaps one for a different page.

mmr.pypython
from rag_kit import load_docs, make_chunks, Index, embed

index = Index(make_chunks(load_docs()))

def mmr(q, k=3, lam=0.5):
    hits = index.search(q, 10)
    vecs, qv, picked = embed([c["text"] for s, c in hits]), embed([q])[0], []
    while len(picked) < k:
        def score(i):
            closest = max([vecs[i] @ vecs[j] for j in picked], default=0)
            return lam * (vecs[i] @ qv) - (1 - lam) * closest
        picked.append(max((i for i in range(10) if i not in picked), key=score))
    return [hits[i][1]["source"] for i in picked]

q = "What can go wrong with my e-bike?"
print("plain:", [c["source"] for s, c in index.search(q, 3)])
print("mmr:  ", mmr(q))
Output
plain: ['ebike_errors.md', 'ebike_errors.md', 'ebike_battery.md']
mmr:   ['ebike_errors.md', 'servicing.md', 'ebike_battery.md']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Using MMR

A lambda of one means pure relevance, like normal search. Zero means pure variety. Around point five is a good start. LangChain vector stores offer MMR as a search type.

keyvalue
lambda = 1pure relevance
lambda = 0pure variety
Start at0.5
LangChainsearch_type mmr

Summary

MMR balances relevance with variety, so the prompt isn't filled with repeats. Next, filters from the question.

Key takeaways
  • Relevant
  • Different
  • lambda balances
Next up: Filters from the Question — self-querying