AI Hints
Home›RAG Tutorial›Retrieval and Grounding Metrics
RAG · Lesson 73 of 120

MRR

How high was it.

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

Hit rate says whether we found the fact. Mean reciprocal rank, or MRR, also asks how high it was. First place scores one. Second place scores a half. Third, a third. And a miss scores zero.

MRR
From the video: MRR
  • First: 1
  • Second: 1/2
  • Miss: 0

Computing MRR

Rank finds the position of the first chunk with the fact, in the top five. The reciprocal rank is one divided by that position. MRR is the average over all questions. Run it. Each question's rank is printed, and the average sits between zero and one.

mrr.pypython
import json
from rag_kit import load_docs, make_chunks, Index

tests = json.load(open("eval_set.json"))
index = Index(make_chunks(load_docs()))

def rank(t, k=5):
    for i, (s, c) in enumerate(index.search(t["question"], k), 1):
        if t["fact"] in c["text"]: return i
    return None

ranks = [rank(t) for t in tests]
print("ranks:", ranks)
print("MRR:", round(sum(1 / r for r in ranks if r) / len(tests), 2))
Output
ranks: [5, None, None, None, 1, 1, 1, 1, 1, 1]
MRR: 0.62
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]
Also uses eval_set.json
[
 {"question": "What does E03 mean?", "source": "ebike_errors.md", "fact": "speed sensor"},
 {"question": "What is the APR?", "source": "finance.md", "fact": "9.9"},
 {"question": "Can I spread the payments?", "source": "finance.md", "fact": "spread the cost"},
 {"question": "How many hours until my e-bike is full again?", "source": "ebike_battery.md", "fact": "4 hours"},
 {"question": "How long until my money comes back?", "source": "returns.md", "fact": "7 working days"},
 {"question": "Can I get next-day delivery on a bike?", "source": "shipping.md", "fact": "Next-day"},
 {"question": "How much is a rental deposit?", "source": "rentals.md", "fact": "£150"},
 {"question": "When is the York shop open?", "source": "stores.md", "fact": "5:30pm"},
 {"question": "How much is a Basic service?", "source": "servicing.md", "fact": "£49"},
 {"question": "Do you deliver bikes to France?", "source": "shipping.md", "fact": "complete bikes"}
]

MRR in practice

MRR matters when the top chunk carries the most weight, for example when you send only one or two chunks. A rise in MRR means the right chunk is moving up.

keyvalue
1.0always first
0.5usually second
Matters whenfew chunks sent
Risingright chunk moving up

Summary

MRR rewards finding the fact near the top. Next, precision and recall.

Key takeaways
  • 1 / rank
  • Average it
  • Higher is better
Next up: Precision and Recall at k — finding all of it