🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Document Ranking: From BM25 to Dense Retrieval

Natural Language ProcessingDocument Ranking: From BM25 to Dense RetrievalđŸŸĸ Free Lesson

Document Ranking: From BM25 to Dense Retrieval

Module: Natural Language Processing | Difficulty: Advanced

What You'll Learn

  • 1Derive a BM25 score with length normalization and tune k1 and b
  • 2Compute MAP, MRR, and nDCG@k on a five-document run
  • 3Separate pointwise, pairwise, and listwise learning to rank
  • 4Choose between sparse, dense, and cross-encoder retrieval by latency budget

Document ranking orders a corpus by relevance to a query, and it is the component that decides whether a retrieval system surfaces the right evidence at all. Production search stacks keep a sparse lexical stage for recall, add a dense bi-encoder for semantic coverage, and finish with a cross-encoder reranker that reads query and document together. This lesson derives BM25 term weighting, defines the ranking metrics that everything is reported with, and implements both the scorer and the evaluator in Python.

Sparse Term Weighting

BM25 (Robertson and Zaragoza, 2009) scores a document by summing an IDF weight times a saturating term frequency. Saturation is the key idea: moving a term from 1 to 2 occurrences should matter much more than moving from 20 to 21, and the parameter controls how fast the gain flattens.

SystemYearRetrieval familyMS MARCO dev MRR@10
BM251994Sparse lexical0.184
DPR2020Dense bi-encoder0.314
ColBERTv22021Late interaction0.360
ANCE2021Approximate NN training0.336
monoT5 rerank2020Cross-encoder0.378

Learning to rank

Three training paradigms differ in the label they consume. Pointwise regressors predict a relevance score per document and train with squared error. Pairwise models consume pairs and only ask which of two documents should rank higher, which is exactly what a human annotator provides. Listwise models optimize the full metric, typically by differentiable surrogates over the whole top- window.

Dense Retrieval and the Retrieval Stack

A dense bi-encoder embeds query and document independently and scores them by inner product, so the whole document set can be pre-embedded once and searched with an approximate nearest-neighbour index. MS MARCO holds about 8,800,000 passages for 502,939 training queries, and a graph index over that corpus returns the top 100 in about 10 milliseconds where exact search needs far longer.

ColBERT instead keeps token-level vectors and aggregates with a MaxSim operator, which recovers token interactions without a full cross-encoder. Cross-encoders read the query and document in one sequence and produce the strongest scores in the table, but their cost is linear in candidate count, so they are only ever applied to the top 50 to 100 first-stage hits.

Worked Code

python
import math
from collections import Counter


class BM25:
    def __init__(self, docs, k1=1.2, b=0.75):
        self.k1, self.b = k1, b
        self.docs = [d.split() for d in docs]
        self.len = [len(d) for d in self.docs]
        self.avg = sum(self.len) / max(1, len(self.len))
        self.df = Counter()
        self.tf = [Counter(d) for d in self.docs]
        for d in self.docs:
            for t in set(d):
                self.df[t] += 1
        self.n = len(self.docs)

    def idf(self, t):
        return math.log(1 + (self.n - self.df.get(t, 0) + 0.5) / (self.df.get(t, 0) + 0.5))

    def score(self, q, i):
        total = 0.0
        for t in q.split():
            f = self.tf[i].get(t, 0)
            if not f:
                continue
            norm = 1 - self.b + self.b * self.len[i] / max(1.0, self.avg)
            total += self.idf(t) * (f * (self.k1 + 1)) / (f + self.k1 * norm)
        return total

    def rank(self, q, k=3):
        scored = [(self.score(q, i), i) for i in range(self.n)]
        return sorted(scored, reverse=True)[:k]


DOCS = [
    "bm25 ranks documents by term frequency and length normalization",
    "the index stores postings lists for every term in the vocabulary",
    "dense retrieval embeds the query and the document into vectors",
    "a cross encoder reads query and document in a single sequence",
    "the reranker rescores the top candidates produced by the first stage",
]
engine = BM25(DOCS)
for s, i in engine.rank("term frequency length normalization", k=3):
    print(round(s, 3), DOCS[i])
python
import math
from collections import defaultdict


def dcg(gains):
    return sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(gains))


def ndcg_at_k(ranked_gains, k):
    gains = ranked_gains[:k]
    ideal = sorted(ranked_gains, reverse=True)[:k]
    idcg = dcg(ideal)
    return 0.0 if idcg == 0 else dcg(gains) / idcg


def evaluate(run, qrels, k=10):
    rr, ap, n = [], [], 0
    for q, ranking in run.items():
        rel = qrels[q]
        hits, hits_so_far = 0, 0
        for i, d in enumerate(ranking[:k]):
            if rel.get(d, 0) > 0:
                hits += 1
                hits_so_far += hits / (i + 1)
        if hits:
            rr.append(1.0 / (ranking.index(next(d for d in ranking if rel.get(d, 0) > 0)) + 1))
            ap.append(hits_so_far / max(1, sum(1 for v in rel.values() if v > 0)))
        else:
            rr.append(0.0)
            ap.append(0.0)
        n += 1
    return {
        "MRR": sum(rr) / n,
        "MAP": sum(ap) / n,
        "nDCG@5": sum(ndcg_at_k([qrels[q].get(d, 0) for d in ranking], 5) for q, ranking in run.items()) / n,
    }


run = {"q1": ["d3", "d1", "d4", "d2"], "q2": ["d5", "d2", "d1"]}
qrels = {"q1": {"d1": 3, "d2": 2, "d4": 1}, "q2": {"d2": 3, "d5": 1}}
for name, value in evaluate(run, qrels, k=4).items():
    print(name, round(value, 4))

Real-World Applications

  • BM25 with and is still the baseline in every retrieval paper, scoring 0.184 MRR@10 on MS MARCO dev.
  • DPR (Karpukhin et al., 2020) raised that to 0.314 by training a dual encoder on 502,939 question-passage pairs.
  • ColBERTv2 reaches 0.360 with late interaction, keeping token vectors so a query term can attend to its best matching term in the passage.
  • A cross-encoder reranker such as monoT5 adds another 0.018 to reach 0.378, which is why stacks are layered rather than replaced.

âš ī¸Retrieval quality caps everything downstream

A retrieval-augmented system cannot cite evidence it never retrieved: with BM25 at 0.184 MRR@10, roughly eight of ten answers that need the correct passage in the top 10 will miss it before generation even starts.

Common Mistakes

Reporting recall without stating k

Fix: Recall is meaningless without the cutoff: recall@10 and recall@1000 differ by an order of magnitude on an 8.8M-passage corpus

Tuning BM25 on the test split

Fix: k1 and b must be tuned on a held-out dev qrel set; otherwise the reported gain is indistinguishable from overfitting

Comparing a cross-encoder to a first-stage system

Fix: Match the candidate budget: a reranker that only sees the top 100 has a hard ceiling set by first-stage recall at 100

Best Practices

  • Run sparse and dense first stages in parallel and fuse with reciprocal rank fusion, which needs no score normalization
  • Measure first-stage recall at the exact k your reranker consumes, not at 1000
  • Report MRR@10, Recall@1000, and latency together, since MS MARCO submissions are ranked by a single official metric

Key Takeaways

  • BM25 saturates term frequency with k1 = 1.2 and normalizes length with b = 0.75
  • MS MARCO dev moves from 0.184 BM25 to 0.314 DPR to 0.378 with cross-encoder reranking
  • Dense retrieval makes scoring O(1) per pair but requires an ANN index over all 8.8M passages
  • nDCG uses 2^rel - 1 over log2(i+1), so depth errors are penalized gently and top-rank swaps heavily

Frequently Asked Questions

Why does BM25 still appear in modern stacks?

Because it is exact, fast, and matches on rare identifiers that dense embeddings blur. Fusion of BM25 and dense hits with reciprocal rank fusion typically beats either alone by 2 to 5 points of recall@100.

What does the k1 parameter actually control?

Saturation of term frequency. With a term going from 1 to 2 occurrences is worth much more than 10 to 11; raising toward 3 or 4 moves the ranking toward raw term frequency.

When is a cross-encoder worth the cost?

When first-stage recall at your budget is already above 95 percent, because reranking cannot recover documents the first stage dropped. On MS MARCO the extra 0.018 MRR@10 is worth it only after the index covers the top 100 well.

Interview Questions

Q1: Derive BM25 from TF-IDF in one step.

Replace the raw or log term frequency with f(k1+1)/(f + k1(1-b+b*dl/avgdl)), which saturates the numerator at k1+1 times IDF and applies a document-length penalty scaled by b

Q2: Why is nDCG preferred over precision@k for graded relevance?

It discounts by position with log2(i+1) and normalizes against the ideal ranking, so scores run from 0 to 1 and grades above binary are honoured

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement