Courses / RAG Systems / Module 1
Module 1: Retrieval foundations: BM25, dense retrieval, recall@k, MRR, nDCG
10 h · theory 3 · hands-on 4 · project 2 · revision 1
You will be able to
- Explain how BM25 scores a document and why it still wins on exact terms
- Explain dense retrieval and where embeddings fail
- Compute recall@k, MRR and nDCG by hand and in code
- Build a small golden set and measure a retriever on it
Capstone increment: Retrieval eval harness: a golden set of 30 questions and a script that reports recall@5, MRR and nDCG for the baseline.
Job-description skills: Search relevance evaluation, BM25, Dense retrieval · Lab tools: bm25s, sentence-transformers, ranx, numpy
1. Retrieval is the whole game
A RAG system can only be as good as the documents it puts in front of the model. If the right passage is not in the top results, no prompt and no model can recover it. That is why this course starts with retrieval and measures it before anything else.
Picture the pipeline in two halves. Offline, documents are parsed, chunked and indexed. Online, each question is rewritten, matched against the index, re-ranked and passed to the model with instructions to answer only from that context, or say "not found". Every module in this course improves one box and proves it with numbers.
2. BM25: why keyword search still wins on exact terms
BM25 scores a document by the query words it contains. Three ideas make it work: rare words matter more (inverse document frequency, IDF), repeating a word helps but with diminishing returns (term-frequency saturation, controlled by k1), and long documents are penalised a little so they don't win by sheer size (length normalisation, controlled by b).
BM25 is unbeatable for exact strings: form numbers like HR-17, error codes, product SKUs, names and acronyms. It is also fast, needs no GPU and explains itself: you can point at the words that matched. Its blind spot is meaning. "Vacation" does not match a document that only says "annual leave".
In code, bm25s is the modern, fast Python implementation (rank-bm25 still appears in tutorials, but its last release was in 2022). OpenSearch and Elasticsearch use BM25 as their default scorer.
Deep dive
Deep dive: BM25, term by term
BM25 scores a document D for a query by adding one term per query word: IDF(word) × tf·(k1 + 1) / (tf + k1·(1 − b + b·|D| / avgdl)), where tf is how often the word appears in D. Three ideas are packed in: rare words count more (IDF); repeating a word helps, with diminishing returns (saturation, set by k1 ≈ 1.2); and long documents are discounted because they mention everything (length normalisation, set by b ≈ 0.75).
IDF(word) = ln(1 + (N − n + 0.5) / (n + 0.5)), where N is the number of documents and n the number containing the word. A word that appears in every document gets an IDF near zero, which is why BM25 ignores “the” without a stop-word list.
Worked example: query “refund laptop”, N = 1,000 documents, average length 100 words, k1 = 1.2, b = 0.75
IDF(refund): n = 50 → ln(1 + 950.5 / 50.5) = ln(19.82) = 2.99 IDF(laptop): n = 200 → ln(1 + 800.5 / 200.5) = ln(4.99) = 1.61 doc A: 100 words, “refund” ×2, “laptop” ×1 (length factor 1.0) refund: 2.99 × (2 × 2.2) / (2 + 1.2 × 1.0) = 2.99 × 1.375 = 4.11 laptop: 1.61 × (1 × 2.2) / (1 + 1.2 × 1.0) = 1.61 × 1.000 = 1.61 total 5.72 doc B: 400 words, “refund” ×4, “laptop” ×1 (length factor 0.25 + 0.75 × 4 = 3.25) refund: 2.99 × (4 × 2.2) / (4 + 1.2 × 3.25) = 2.99 × 1.114 = 3.33 laptop: 1.61 × (1 × 2.2) / (1 + 1.2 × 3.25) = 1.61 × 0.449 = 0.72 total 4.05 B says “refund” twice as often, but A wins: saturation plus the length penalty
3. Dense retrieval: matching meaning
Dense retrieval embeds the question and every chunk as vectors, then returns the chunks whose vectors point in the most similar direction (cosine similarity). Because the embedding model has learned that "vacation" and "annual leave" mean similar things, it finds documents with no words in common with the question.
The trade-offs: it can miss exact identifiers, it inherits the embedding model's blind spots (domain jargon, Indian languages, very short queries), and its scores are not comparable across models. Choosing and fine-tuning embedding models is Module 4.
Try both below. The playground uses a tiny hand-made meaning space instead of a real embedding model, but the behaviour is the real one: each method finds what the other misses, and a blend of the two (hybrid search, Module 6) usually beats either.
| Rank (faded = not retrieved) | Relevant? | Document | BM25 → dense → blended score |
|---|---|---|---|
| 1 | Travel reimbursement Claim travel expenses with form HR-17 within 30 days. Attach receipts for flights, trains and hotels. | BM25 1.00 · dense 0.00 · 0.50 | |
| 2 | Salary and payslips Salary is credited on the last working day. Download payslips and Form 16 from the payroll portal. | BM25 0.44 · dense 0.00 · 0.22 | |
| 3 | Annual leave policy Employees get 24 days of annual leave. Apply for leave in the HR portal at least two weeks ahead. | BM25 0.00 · dense 0.00 · 0.00 | |
| 4 | Holiday calendar Public holidays for 2027 by office location. Optional holidays need manager approval. | BM25 0.00 · dense 0.00 · 0.00 | |
| 5 | Laptop and equipment Each employee receives a laptop. Report a lost or stolen device to IT security within 24 hours. | BM25 0.00 · dense 0.00 · 0.00 | |
| 6 | Password and MFA rules Use a password manager and turn on MFA. Never share one-time codes, even with IT. | BM25 0.00 · dense 0.00 · 0.00 | |
| 7 | Work from home Hybrid staff may work remotely up to three days a week. Home internet is reimbursed up to Rs 1,000 a month. | BM25 0.00 · dense 0.00 · 0.00 | |
| 8 | Parental leave Birth parents get 26 weeks of paid leave; other parents get 4 weeks. Tell HR 8 weeks before the leave starts. | BM25 0.00 · dense 0.00 · 0.00 |
Guided experiments
- “where is form HR-17”: slide to dense only. The travel document drops out and recall falls to 0. Why does BM25 find it instantly?
- “vacation days per year”: slide to BM25 only. It can only match the word “days”, so the holiday calendar is missed. Which word in the question does no document contain?
- “time off when we have a baby”: BM25 only retrieves nothing at all. Slide to dense only: both leave policies come back. What did the dense side “know” that BM25 didn’t?
- “my computer was stolen” at the middle setting: try k = 1, then k = 2. Recall@k and nDCG change while MRR stays at 1. What does each metric reward?
- Find one blend where every question gets recall@3 = 1. That’s why production systems use hybrid search.
- Type your own question and tick the relevant documents yourself. That is how a golden set is built.
4. Measuring retrieval: recall@k, MRR and nDCG
recall@k asks: of the documents that answer the question, what share made it into the top k? It is the first number to watch in RAG, because anything outside the top k never reaches the model.
MRR (mean reciprocal rank) asks: how high was the first relevant document? 1 at rank 1, 0.5 at rank 2, 0.33 at rank 3. It suits questions with one right answer.
nDCG@k (normalised discounted cumulative gain) rewards putting relevant documents near the top, with a logarithmic discount for each lower position, and divides by the best possible ordering so a perfect ranking scores 1. It handles several relevant documents and graded relevance.
Report them together, per question type, and always next to the baseline. A change that raises MRR but lowers recall@5 can make answers worse, because the second relevant passage stops reaching the model.
Deep dive
Deep dive: computing recall, MRR and nDCG by hand
Recall@k asks “did the right documents make it into the top k at all?”. It matters most for RAG, because the model can’t use what it never sees. MRR asks “how high is the first right document?”. nDCG asks “is the whole ranking in the best order?” and is the only one of the three that uses graded relevance (a perfect answer counts more than a related one).
nDCG divides the ranking’s discounted cumulative gain (DCG) by the DCG of the ideal ranking (IDCG), so it is 1.0 for a perfect order and comparable across queries with different numbers of relevant documents. Each result contributes (2^grade − 1) / log₂(rank + 1): the gain is large for highly relevant documents, and the discount shrinks it the lower they appear.
Worked example: the list in the tool, k = 5 (grades by rank 0, 3, 1, 0, 2; one grade-2 document never retrieved)
recall@5 = relevant in top 5 / all relevant = 3 / 5 = 0.60
RR = 1 / rank of first relevant = 1 / 2 = 0.50
DCG@5 = 0/1 + 7/1.585 + 1/2 + 0/2.322 + 3/2.585
= 0 + 4.42 + 0.50 + 0 + 1.16 = 6.08
ideal grades in order: 3, 2, 2, 1, 1
IDCG@5 = 7/1 + 3/1.585 + 3/2 + 1/2.322 + 1/2.585
= 7 + 1.89 + 1.50 + 0.43 + 0.39 = 11.21
nDCG@5 = 6.08 / 11.21 = 0.54| Rank | Result | Grade | Gain 2^g − 1 | ÷ log₂(rank + 1) | = DCG part | |
|---|---|---|---|---|---|---|
| 1 | Shipping times for remote PIN codes | 0 | 1.00 | 0.00 | ||
| 2 | Refund window for electronics | 7 | 1.58 | 4.42 | ||
| 3 | How refunds reach your bank | 1 | 2.00 | 0.50 | ||
| 4 | Gift card terms | 0 | 2.32 | 0.00 | ||
| 5 | Return a damaged laptop | 3 | 2.58 | 1.16 | ||
| 6 | Store opening hours | – | – | – | ||
| 7 | Track a courier | – | – | – | ||
| 8 | Refund status FAQ | – | – | – |
- Precision@5 = relevant in top 5 ÷ 5 = 0.60
- Recall@5 = relevant in top 5 ÷ all relevant that exist = 0.60 (the missing document counts against you)
- Reciprocal rank = 1 ÷ rank of the first relevant result = 0.50; MRR is its average over all your test queries
- nDCG@5 = DCG 6.08 ÷ ideal DCG 11.21 (grades sorted best first: 3, 2, 2, 1, 1) = 0.542
Guided experiments
- Move “Refund window for electronics” (grade 3) to rank 1. Which metrics change, and which don’t? Why can reordering inside the top k never change recall@k?
- Swap a grade-1 result above the grade-3 one. MRR doesn’t care (any relevant result counts), but nDCG does. Which metric matches what a user feels?
- Set k = 8. Recall still isn’t 1. What does that tell you to fix: the ranking or the retrieval?
- Change the “Store opening hours” grade to 2. In a RAG system, who should set these grades, and how many labelled queries do you need before nDCG differences mean something?
5. Your golden set: the asset that outlives every model
A golden set is a list of real questions, each with the documents that answer it. Start with 30 questions from real users, support tickets or subject experts, not ones you invent while looking at the documents (those are too easy). Include questions the documents cannot answer, so you can test the "not found" path later.
Store it as JSONL in the repo, version it like code, and grow it every time a user reports a bad answer. In this module's capstone step you build the first version and a script that scores the baseline. Every later module reruns it.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 1.1: Tune BM25 by hand
In the BM25 starter, D1 and D8 tie for the query "leave": both say it twice in 14 words. Add five words to D8's text, then score "leave" with b = 0, 0.75 and 1, and with k1 = 0.5 and 2.0.
Expected: A table of scores: the tie stays at b = 0 and D1 pulls ahead as b grows. Two sentences explaining length normalisation and term-frequency saturation.
Lab 1.2: Build the golden set
Write 30 questions about the sample corpus in data/golden.jsonl ({"id", "question", "relevant": [doc ids]}), including at least 5 the corpus cannot answer.
Expected: golden.jsonl with 30 lines; 5+ entries have an empty relevant list.
Lab 1.3: Score the baseline
Run BM25 (bm25s) and a dense retriever (sentence-transformers, all-MiniLM-L6-v2) over the corpus and score both with src/retrieval/metrics.py. Commit the scores to docs/baseline.md.
Expected: A table of recall@5, MRR and nDCG@5 for BM25 and dense retrieval, with one paragraph on where each one fails.
Go deeper
Videos
- Crash Course IR - Fundamentals · Sebastian Hofstätter · ~47 min. A university lecture on inverted indexes and ranked retrieval with TF-IDF and BM25; the clearest foundation for this module.
- Crash Course IR - Evaluation · Sebastian Hofstätter · ~37 min. Walks through MRR, MAP and nDCG with worked examples, and how judgements are collected.
- Dense Retrieval ❤ Knowledge Distillation · Sebastian Hofstätter · ~59 min. How dense retrievers are trained and where they beat or lose to BM25. Watch the first half now; the rest supports Module 4.
- A no nonsense intro to BM25 · Abhishek Thakur · ~16 min. A short, code-first walk through the BM25 formula if you want a quick refresher.
- BM25 : The Most Important Text Metric in Data Science · ritvikmath · ~18 min. BM25 derived from TF-IDF, with saturation and length normalisation drawn out.
- Every Ranking Metric : MRR, MAP, NDCG · ritvikmath · ~21 min. MRR, MAP and nDCG computed on examples, so you can check your own numbers.
Further reading
- Article Practical BM25 - Part 2: The BM25 Algorithm and its Variables · Elastic. The formula term by term, with what k1 and b do and when to change them.
- Article Okapi BM25 · Wikipedia. The formula and the IDF variants in one place, for quick reference.
- Article Discounted cumulative gain · Wikipedia. DCG, IDCG and nDCG with a worked example to check your own numbers against.
- Paper BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models · Thakur et al., 2021. Why BM25 is still a hard baseline: dense models often lose to it outside their training domain.
- Paper Dense Passage Retrieval for Open-Domain Question Answering · Karpukhin et al., 2020. The paper that made dense retrieval beat BM25 on QA, and introduced in-batch negatives for it.
GitHub repositories
- xhluca/bm25s: The README benchmarks and bm25s/__init__.py: how BM25 is computed with sparse matrices for speed.
- AmenRa/ranx: The metrics list and the Qrels/Run objects: the format used for the golden set and runs in this course.
- beir-cellar/beir: The README results table: BM25 is still a strong baseline across 18 datasets, and dense models don't always beat it.
- embeddings-benchmark/mteb: The retrieval tasks: how embedding models are compared, which you will use critically in Module 4.
- NirDiamant/RAG_Techniques: Skim the table of contents as a map of the techniques this course measures one by one.
Checkpoint quiz
Interview questions
- Explain BM25 to a product manager, then write its formula and say what k1 and b do.
- When would you choose BM25 over dense retrieval, and when the reverse? Give a concrete example of each.
- Your RAG answers got worse after switching embedding models, but answer accuracy on a demo looks fine. How do you find out what happened?
- Define recall@k, MRR and nDCG. Which would you optimise for a RAG system that passes the top 5 chunks to the model, and why?
- How would you build a golden set for an internal knowledge assistant in two days?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).