BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Embeddings and RAG14 of 19 in topic

387. Rank documents with BM25

HardEmbeddings and RAG Pro

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.

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

Example 1

Input: bm25_scores([['kv', 'cache', 'stores', 'keys', 'and', 'values'], ['the', 'kv', 'cache', 'grows', 'with', 'every', 'token', 'in', 'the', 'long', 'context', 'window', 'here'], ['paged', 'attention', 'splits', 'cache', 'into', 'blocks']], ['paged'])

Output: [0.0, 0.0, 1.1222]

Example 2

Input: docs = [['kv', 'cache', 'stores', 'keys', 'and', 'values'], ['the', 'kv', 'cache', 'grows', 'with', 'every', 'token', 'in', 'the', 'long', 'context', 'window', 'here'], ['paged', 'attention', 'splits', 'cache', 'into', 'blocks']], query = ['kv', 'cache']

Output: [0.690544, 0.482057, 0.152782]

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Precompute df per term and avgdl.

Hint 2

Then sum the formula over query tokens for each document.

Common mistakes
  • The buggy version drops length normalisation.
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.

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.

Topics
Embeddings and RAG
Similar questions
  • Re-rank retrieved chunks for diversity with maximal marginal relevanceHard
  • Search an inverted-file (IVF) vector indexHard
  • Score vectors with product-quantisation lookup tablesHard
  • Split a document into overlapping chunksMedium
All Embeddings and RAG problems
Report
387 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import math
​
def bm25_scores(docs, query, k1=1.5, b=0.75):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS