Rank documents with BM25

BM25 is still the keyword half of most hybrid RAG search. It is TF-IDF with two fixes: repeated words saturate, and long documents are penalised.

For query terms q and a document D with length |D|, avgdl the mean document length and N documents:
idf(q) = ln(1 + (N - df + 0.5) / (df + 0.5))
score(D) = sum over query terms of idf(q) * f (k1 + 1) / (f + k1 (1 - b + b |D| / avgdl))
where f is the count of q in D.

Write bm25_scores(docs, query, k1=1.5, b=0.75) for token lists. Return a list of scores, one per doc. A repeated query term counts each time it appears in the query.

Signaturedef bm25_scores(docs, query, k1=1.5, b=0.75)

Understand the idea

BM25 is a keyword ranking score, an improved TF-IDF. It adds two ideas. Saturation: the tenth time a word appears adds much less than the first, controlled by k1. Length normalisation: long documents naturally contain more words, so their counts are scaled down relative to average length, controlled by b. Worked example: docs D1 = [cat, cat, dog] (length 3) and D2 = [dog, fish] (length 2), avgdl 2.5, N = 2, query [cat], k1 = 1.5, b = 0.75. cat appears in 1 doc, so idf = ln(1 + (2 - 1 + 0.5) / (1 + 0.5)) = ln 2 = 0.693. For D1, f = 2: denominator = 2 + 1.5 x (0.25 + 0.75 x 3 / 2.5) = 3.725; numerator = 2 x 2.5 = 5; score = 0.693 x 5 / 3.725 = 0.930. D2 scores 0. Rule: score = sum over query terms (repeats count) of idf x f (k1 + 1) / (f + k1 (1 - b + b |D| / avgdl)). Hybrid RAG search combines BM25 with embeddings.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: query kv cachebm25_scores(_D, ['kv', 'cache'])
  • Sample 2: rare termbm25_scores(_D, ['paged'])