Implementing BM25

A tested implementation of BM25 over an inverted index. What to precompute at indexing time, scoring with accumulators traced step by step, document-at-a-time scoring with upper bounds, a hand-checked example on the four Arctic sentences, the effect of k1 and b on Cranfield, the variants that different systems compute under the same name, an experiment showing how much the variants matter, and the same design in this site's own search. Worked problems on scoring, bounds, saturation and updating an index.

With each term's IDF stored in the dictionary and the normalizer $K_d = k_1(1 - b + b\,L_d/L_{\mathrm{avg}})$ stored per document, BM25 costs three operations per posting at query time. A thirty-line Python class does this and reproduces a hand calculation on the course's four Arctic sentences exactly. On Cranfield (1,400 abstracts, 225 queries, top 10), document-at-a-time evaluation with exact per-term bounds returned the same top 10 as exhaustive scoring for every query while completing 9.2 percent as many scores, a share that fell each time the collection doubled. The defaults $k_1 = 1.2$, $b = 0.75$ give a mean average precision of 0.307, within 0.01 of the grid's best (0.316). Of the variants that share the name, only the original Robertson–Spärck Jones IDF changed it measurably (by −0.0046).

Query 185's average precision of 0.784, and every other BM25 number in this unit, came from scoring Cranfield's 1,400 abstracts thousands of times over. A typical Cranfield query has about twelve terms and touches about two thousand postings. This article shows how the scoring is organized so that it stays cheap, and how far two systems that both report "BM25" are computing the same thing.

BM25 is a short formula, and a working implementation is about thirty lines. The decisions that matter are what to compute in advance, so that query time involves only a few multiplications per posting, and which of several slightly different versions of the formula to compute. Systems that all claim to use "BM25" differ in their IDF, in whether they include a constant factor, in how they store document lengths, and in how they treat repeated query terms.

Here is the route. First we give a compact implementation and trace it by hand on the course's four Arctic sentences. Then we show how a document-at-a-time evaluation skips most of the work while returning the same top results. Finally we measure on Cranfield how $k_1$ and $b$ affect effectiveness, and how much the variants matter. The article assumes the formula above and the accumulator method of computing vector scores.

What to precompute

The BM25 score of document $d$ for query $q$ is

$$\sum_{t \in q} \mathrm{IDF}(t) \cdot \frac{\mathit{tf}_{t,d}\,(k_1 + 1)}{\mathit{tf}_{t,d} + K_d}, \qquad K_d = k_1 \left(1 - b + b\, \frac{L_d}{L_{\mathrm{avg}}}\right).$$

Here $\mathit{tf}_{t,d}$ is the number of times term $t$ occurs in $d$, $L_d$ is the document's length, and $L_{\mathrm{avg}}$ the average length over the collection. Two parts of this do not depend on the query:

  • $\mathrm{IDF}(t)$ depends only on the term and the collection, so it can be stored in the dictionary with each term.
  • $K_d$ depends only on the document's length, the average length, and the parameters, so it can be stored in an array indexed by document.

Precomputing both leaves a single expression to evaluate for each posting $(d, \mathit{tf})$ of each query term: one addition, one multiplication by the IDF, and one division. The postings must store term frequencies. An index built only for Boolean retrieval need not (see the inverted index).

Three quantities are easy to get subtly wrong:

  • Document length $L_d$ is the number of tokens after analysis (stop words removed, if the index removes them). It is not the number of distinct terms, and not the length of the raw text. Whatever the definition, $L_{\mathrm{avg}}$ must use the same one.
  • Document frequency $\mathit{df}$ is the length of the term's postings list: the number of documents containing the term, not its total number of occurrences.
  • Both are collection statistics. When documents are added or deleted, $N$, $\mathit{df}$, and $L_{\mathrm{avg}}$ change, and with them every IDF and every $K_d$. Real systems recompute them periodically, or compute them per index segment and accept small inconsistencies.

An implementation

import heapq
import math
from collections import Counter, defaultdict


class BM25Index:
    def __init__(self, docs, k1=1.2, b=0.75):
        """docs: {doc_id: list of analyzed terms}"""
        self.k1, self.b = k1, b
        self.N = len(docs)
        self.postings = defaultdict(list)            # term -> [(doc_id, tf), ...]
        lengths = {}
        for doc_id, terms in docs.items():
            lengths[doc_id] = len(terms)
            for term, tf in Counter(terms).items():
                self.postings[term].append((doc_id, tf))
        avgdl = sum(lengths.values()) / self.N
        # Everything that does not depend on the query is computed once, here.
        self.norm = {d: k1 * (1 - b + b * L / avgdl) for d, L in lengths.items()}
        self.idf = {t: math.log(1 + (self.N - len(p) + 0.5) / (len(p) + 0.5))
                    for t, p in self.postings.items()}

    def search(self, query_terms, k=10):
        scores = defaultdict(float)                  # accumulators, term at a time
        for term in query_terms:
            idf = self.idf.get(term)
            if idf is None:
                continue
            for doc_id, tf in self.postings[term]:
                scores[doc_id] += idf * tf * (self.k1 + 1) / (tf + self.norm[doc_id])
        return heapq.nlargest(k, scores.items(), key=lambda item: item[1])

The scoring loop is the term-at-a-time accumulator method of computing vector scores, with the BM25 term weight in place of the cosine contribution. The IDF uses Lucene's form, which is never negative (see Okapi BM25). Thirty lines are easy to get wrong, so the next step is to run them on something small enough to check by hand.

A hand-checked example: the Arctic sentences

The four Arctic sentences have followed the course from the architecture article through the inverted index to computing vector scores:

  1. Arctic sea ice is declining as the climate warms.
  2. A warming climate threatens Arctic seabirds and their food.
  3. Climate models predict warmer winters in Europe.
  4. Seabirds of the Arctic: a field guide.

They are analyzed exactly as in those articles: lowercased, split into runs of letters, the eight-word stop list removed, and stemmed with the original Porter algorithm. The query is arctic climate warming, which analyzes to arctic, climat and warm. The parameters are $k_1 = 1.2$ and $b = 0.75$. The documents become:

Document Terms Length $L_d$
1 arctic sea ic declin climat warm 6
2 warm climat threaten arctic seabird food 6
3 climat model predict warmer winter europ 6
4 seabird arctic field guid 4

Document 3 does not match warm: as the architecture article noted, the Porter rules leave warmer unchanged.

Step 1: what the index stores

Building the index produces, for the three query terms, these postings lists of (document, term frequency) pairs, with the IDF stored beside each term:

Term df IDF Postings
arctic 3 $\ln(1 + 1.5/3.5) = 0.3567$ (1, 1), (2, 1), (4, 1)
climat 3 $\ln(1 + 1.5/3.5) = 0.3567$ (1, 1), (2, 1), (3, 1)
warm 2 $\ln(1 + 2.5/2.5) = 0.6931$ (1, 1), (2, 1)

The average length is $(6 + 6 + 6 + 4)/4 = 5.5$, so the stored normalizers are

$$K_d = 1.2\left(0.25 + 0.75 \times \frac{L_d}{5.5}\right) = \begin{cases} 1.2818 & L_d = 6 \ (\text{documents 1, 2, 3}) \\ 0.9545 & L_d = 4 \ (\text{document 4}). \end{cases}$$

Every term occurs once where it occurs, so its frequency factor is $\frac{1 \times 2.2}{1 + K_d}$: 0.9641 for the three longer documents and 1.1256 for document 4. Values are rounded to four decimals, and each product below is computed before rounding.

Step 2: accumulators, term at a time

The search processes one query term at a time. It walks the term's postings list and adds each document's contribution to that document's accumulator. Accumulators are created on first touch, so a document that contains no query term never gets one.

After processing Doc 1 Doc 2 Doc 3 Doc 4
arctic $0.3567 \times 0.9641 = 0.3439$ 0.3439 $0.3567 \times 1.1256 = 0.4015$
climat 0.6878 0.6878 0.3439 0.4015
warm $0.6878 + 0.6931 \times 0.9641 = 1.3561$ 1.3561 0.3439 0.4015

Example (the same order as cosine, by a different mechanism). These scores agree with cosine scoring about documents 3 and 4. Each matches one query term, the two terms have the same IDF, and under cosine scoring document 4 ranked higher because it is shorter. BM25 also ranks document 4 higher, for a different reason. Cosine divides the whole score by the document's vector length. Here, instead, document 4's four tokens give it a smaller $K_d$, so one occurrence earns a larger share of the saturation curve: 1.1256 of the possible 2.2, against 0.9641. The final step selects the $k$ largest accumulators:

Rank Document Terms matched Score
1 1 arctic, climat, warm $(0.3567 + 0.3567 + 0.6931) \times 0.9641 = 1.3561$
1 2 arctic, climat, warm 1.3561
3 4 arctic $0.3567 \times 1.1256 = 0.4015$
4 3 climat $0.3567 \times 0.9641 = 0.3439$

The BM25Index class above returns exactly these scores (tools/experiments/cranfield/bm25_impl.py runs it on the same documents). Documents 1 and 2 stay tied, as they did under cosine scoring, because they match the same terms and have the same length.

Document at a time, with upper bounds

Term-at-a-time scoring needs an accumulator for every document that contains any query term. It also cannot know any document's final score until the last list is read. The alternative, described in computing vector scores, is document-at-a-time evaluation. It opens every query term's postings list, advances through them together in document order, and finishes each document's score when its turn comes. Only the current top $k$ needs to be kept.

Here is the idea in one sentence: a document that cannot beat the weakest of the current top $k$ need not be scored. Saturation makes that check possible, because it bounds each term's contribution. Since $\frac{\mathit{tf}\,(k_1 + 1)}{\mathit{tf} + K_d} < k_1 + 1$ for any frequency, no document can get more than $(k_1 + 1)\,\mathrm{IDF}(t)$ from term $t$. A tighter bound is the largest contribution that actually occurs in the term's postings list, which can be computed once at indexing time.

Once the top $k$ is full, its smallest score is a threshold $\theta$. A document's bound is the sum of the bounds of the terms it contains. If that bound does not exceed $\theta$, the document cannot enter the top $k$ and need not be scored. This is the principle behind the MaxScore and WAND algorithms (see search at scale). Dynamic pruning with MaxScore and WAND states both algorithms in full and proves them safe.

The example, with $k = 1$

With the bound $(k_1 + 1)\,\mathrm{IDF}$, arctic and climat can each contribute at most $2.2 \times 0.3567 = 0.7847$, and warm at most $2.2 \times 0.6931 = 1.5249$. Walking the documents in order, keeping only the best one:

Document Terms present Bound Threshold $\theta$ Action Score
1 arctic, climat, warm 3.0943 0 score it 1.3561, becomes the top 1
2 arctic, climat, warm 3.0943 1.3561 score it 1.3561, not better
3 climat 0.7847 1.3561 skip: bound $\le \theta$ not computed
4 arctic 0.7847 1.3561 skip: bound $\le \theta$ not computed

Documents 3 and 4 are never scored, and the answer is the same as before (document 2 only ties document 1, so the first one found stays). On four documents the saving is two scores; on a real collection it is most of the work.

How much it saves on Cranfield

The Cranfield collection has 1,400 documents, and its queries are long natural-language questions, averaging 11.9 analyzed terms. Term at a time, a query touches on average 2,176 postings and creates 969 accumulators (median 1,027, maximum 1,359). So most queries score most of the collection.

A document-at-a-time evaluation in the style of MaxScore, with exact per-term bounds and $k = 10$, works as follows:

  1. Sort the query terms by bound, smallest first.
  2. Call the longest run of smallest-bound terms whose bounds add up to no more than $\theta$ the non-essential terms. A document containing only those cannot reach $\theta$. So candidates are drawn only from the postings of the other, essential terms.
  3. For each candidate, add the essential terms' contributions. Then add the non-essential ones in decreasing order of bound, stopping as soon as the partial score plus the remaining bounds falls to $\theta$ or below.
  4. As the top 10 fills and $\theta$ rises, more terms become non-essential.

Pruning cannot change the top 10 when the bounds are true bounds. A document is skipped, or its scoring abandoned, only when its score so far plus the bounds of the terms not yet added is at most $\theta$. Its full score is at most that sum, so it is at most $\theta$, the score of the tenth document already held. The threshold never falls, so the document could not enter the top 10 later either. A document that ties the tenth score exactly is the one case to watch. The evaluation visits documents in increasing document number, so every document already held was visited earlier and has a smaller document number than the one being considered. A skipped document whose score equals $\theta$ therefore loses the tie to every held document with that score, both here and in the exhaustive ranking, which also breaks ties by the smaller document number. A later document can displace a held one only by scoring strictly more than $\theta$. So no tie is resolved differently. The argument assumes exact arithmetic. In floating point the two passes add the contributions in different orders, so documents with equal true scores can in principle be ordered differently; on Cranfield no query was affected.

Across the 225 queries, the pruned evaluation returned the same top 10, in the same order, as exhaustive scoring for every query. It considered 510 candidate documents per query on average and completed the score of 89. That is 9.2 percent of the documents that term-at-a-time scoring scored in full.

On Cranfield the saving grows with the size of the collection. Running the same comparison on the first 175, 350 and 700 abstracts, with every collection statistic recomputed for the smaller collection, gives:

Abstracts Scored exhaustively, per query Scores completed with pruning Completed, as a share
175 127.2 44.6 35.1%
350 253.2 56.8 22.4%
700 492.7 69.5 14.1%
1,400 969.3 89.2 9.2%

Each doubling of the collection doubles the exhaustive work and adds only 12 to 20 completed scores. The top 10 was identical to the exhaustive one for all 225 queries at every size. The pattern has a plain reading: the threshold for the top 10 rises as more good documents are seen, while the number of documents that can beat it grows slowly. It is a measurement on nested parts of one small collection, not a law; the size of the saving on other collections depends on their queries and their score distributions.

Speed is half the story. The other half is what the parameters do to the ranking, which the next section measures.

The effect of $k_1$ and $b$

The defaults $k_1 = 1.2$ and $b = 0.75$ are a starting point. Running the implementation over a grid of values on all 225 Cranfield queries, with the setup of comparing ranking models, shows how much each parameter matters:

Mean average precision of BM25 on all 225 Cranfield queries for each combination of k1 (rows) and b (columns). The bottom row, k1 = 0, ignores term frequency and is the same for every b. Notice how effectiveness rises steeply away from k1 = 0 and b = 0, then flattens into a broad plateau: the default (solid box, 0.307) is within 0.01 of the best value in the grid (dashed box, 0.316 at k1 = 6, b = 0.75).
Mean average precision of BM25 on all 225 Cranfield queries for each combination of k1 (rows) and b (columns). The bottom row, k1 = 0, ignores term frequency and is the same for every b. Notice how effectiveness rises steeply away from k1 = 0 and b = 0, then flattens into a broad plateau: the default (solid box, 0.307) is within 0.01 of the best value in the grid (dashed box, 0.316 at k1 = 6, b = 0.75).

Reading the grid row by row and column by column:

  • $k_1 = 0$ discards term frequency. The frequency factor becomes $\mathit{tf}/\mathit{tf} = 1$ for any document containing the term. BM25 then reduces to a sum of IDFs over matching terms, a binary model much like the BIM without relevance information. Its MAP, 0.225, is close to the BIM's 0.220. Every larger $k_1$ does better: term frequency is worth about 0.08 in MAP here.
  • $b = 0$ discards length normalization. At $k_1 = 1.2$, MAP falls from 0.307 to 0.271. Cranfield's abstracts vary in length by a factor of more than ten, and without normalization the long ones win too often.
  • $b = 1$ normalizes fully and costs a little (0.303 at $k_1 = 1.2$). Full normalization treats all of a long document's length as verbosity. Yet some long abstracts are long because they cover more, as the BM25 article explains.
  • The plateau is broad. Every combination with $k_1$ between 1.2 and 6 and $b$ between 0.5 and 0.9 lies between 0.301 and 0.316. Larger $k_1$ lets the score keep growing with term frequency for longer before it saturates, and it helps slightly on this collection.

Measured by nDCG at 10, the picture is the same: 0.368 at the defaults and 0.380 at the best grid point ($k_1 = 6$, $b = 0.5$). Values are rounded to three decimals. This grid was evaluated on all the queries, so its best point is an optimistic estimate of what tuning would achieve on new queries. The comparison article tunes on half the queries and tests on the other half, and finds a gain of 0.003.

Within the plateau, then, the parameters matter little. The next section shows that the exact form of the formula matters even less for effectiveness, with one exception.

Variants that share a name

Kamphuis, de Vries, Boytsov, and Lin (2020) compared eight variants of BM25, drawn from the literature and from widely used systems, on three newswire test collections. The differences among implementations include:

  • The IDF. The original Robertson–Spärck Jones form, $\log \frac{N - \mathit{df} + 0.5}{\mathit{df} + 0.5}$, is negative for terms in more than half the collection. Lucene adds 1 inside the logarithm to keep it positive. Others use $\log(N/\mathit{df})$.
  • The $(k_1 + 1)$ factor. It scales every score by the same constant and so cannot change a ranking (Robertson and Zaragoza, 2009, sec. 3.5.1). Lucene has omitted it since version 8.
  • Document length. Some systems store lengths exactly. Lucene stores them in a single byte, with lossy encoding, so documents of somewhat different lengths are normalized identically.
  • Repeated query terms. A term appearing twice in the query may be counted twice, counted once, or weighted by a saturated query frequency with the parameter $k_3$. Robertson and Zaragoza (2009, sec. 3.5.1) report that the saturation was found unimportant, so counting each occurrence as a separate term is the usual choice.

They found that the differences in effectiveness among the variants were small and that none was statistically significant. The variant still matters for reproducibility, since two papers reporting "BM25" on the same collection can produce different numbers.

How much they matter on Cranfield

Running the variants on the Cranfield collection, with the setup of comparing ranking models, gives a similar picture:

Variant MAP Difference from Lucene form $p$
Lucene IDF, with $(k_1 + 1)$, repeated terms counted 0.3066
Original RSJ IDF (can be negative) 0.3020 −0.0046 0.048
$\log(N/\mathit{df})$ IDF 0.3065 −0.0001 0.75
Without the $(k_1 + 1)$ factor 0.3066 0 1.0
Query terms deduplicated 0.3063 −0.0003 0.87

Removing the constant factor changes nothing, as expected. Only the original IDF makes a measurable difference, and it is small. On Cranfield only one term, flow, occurs in more than half the documents. Its negative weight penalizes documents about the collection's most common subject. On collections where stop-word removal is light, more terms cross the halfway point and the effect can grow. Counting repeated query terms twice, which matters for 66 of the 225 queries, makes no meaningful difference.

Example (a negative IDF reverses a ranking). On the Arctic sentences, the original RSJ IDF reverses the ranking for the query arctic climate warming. Arctic and climat each occur in three of the four documents, and warm in two. The original IDF of arctic and climat is $\ln(1.5/3.5) = -0.8473$, and that of warm is $\ln(2.5/2.5) = 0$. Every matching document scores below zero: document 3 −0.8169, document 4 −0.9537, and documents 1 and 2 −1.6338 each. The two documents that match every query word come last, and a document matching none would beat all four. A tiny collection makes the effect extreme; Lucene's added 1 prevents it.

Scaling up

The implementation above keeps everything in memory and scores every document that contains any query term. Production systems change three things:

  1. Compressed postings on disk, decoded as they are read (see index compression).
  2. Document-at-a-time evaluation with dynamic pruning, as traced above. Methods such as WAND go further than the simple bound check. They use the bounds to jump over long stretches of postings lists without decoding them (see computing vector scores and search at scale). Block-max indexes store a bound for every block of a list as well, so that a skip can rest on the bound of the stretch being passed over.
  3. Precomputed impacts. Some systems, among them those of learned sparse retrieval, store, in place of the term frequency, the term's entire contribution to the document's score, quantized to a few bits. Scoring then becomes pure addition, at the cost of fixing $k_1$ and $b$ at indexing time. Stored this way, a document is a sparse vector of impacts and its score a dot product with the query, which is how Limits of Single-Vector Retrieval writes BM25 before asking how far such a vector can be compressed. This site's search box does the same for its instant results: the server precomputes each term's BM25F contribution to each article, and the browser only adds.

For research, toolkits such as Anserini (Yang, Fang, and Lin, 2017), built on Lucene, and its Python interface Pyserini provide BM25 with documented settings and published baselines on standard collections. That makes results reproducible.

The search box of this site is a working instance of the design above, and each choice in it can be named in this article's terms (app/search.py; How This Search Works describes the whole engine).

  • IDF. It uses the same Lucene form as the class above, $\ln\left(1 + \frac{N - \mathit{df} + 0.5}{\mathit{df} + 0.5}\right)$, with $\mathit{df}$ counted over whole pages.
  • Term score. It forms the BM25F pseudo frequency $x = \sum_f w_f\, \mathit{tf}_f / B_f$, with $B_f = 1 - b_f + b_f\, l_f / \bar{l}_f$ for each field, and scores a term as $\mathrm{IDF} \times \frac{x}{k_1 + x}$, with $k_1 = 1.2$ and every $b_f = 0.5$. For a single field of weight 1 this is $\mathrm{IDF} \times \frac{\mathit{tf}}{\mathit{tf} + k_1 B}$, the formula of this article without the constant $(k_1 + 1)$.
  • Lengths. Field lengths count stop words, because the index keeps positions for phrase queries and a stop word occupies a position.
  • Impacts. At startup the server computes the contribution of every (term, page) pair, rounded to four decimals, and sends the table to the browser. The instant results add those numbers and the title bonus, and a parity test (tools/search/test_parity.py) checks that they rank as the server does.

Example (the single-field case, checked). Scoring the Arctic sentences with the site's term score, one field of weight 1 and $b = 0.5$, gives 0.6238 for documents 1 and 2, 0.1582 for document 3 and 0.1752 for document 4. The BM25Index class with $b = 0.5$ gives 1.3725, 1.3725, 0.3480 and 0.3853. Each is exactly 2.2 times the site's value, the factor $(k_1 + 1)$, so the two rank identically. The script transcribes the site's two lines of scoring code and asserts the ratio.

Worked problems

These problems are posed on the article's own example, the four Arctic sentences with $k_1 = 1.2$ and $b = 0.75$; the course text's chapter 11 has no exercise on implementing BM25. The script tools/experiments/cranfield/bm25_impl.py checks every number.

Problem 1 (another query). Score the query seabirds climate against the four sentences and rank them.

Solution. The query analyzes to seabird and climat. Seabird occurs once each in documents 2 and 4, so its IDF is $\ln(1 + 2.5/2.5) = 0.6931$. Climat has IDF 0.3567 and postings in documents 1, 2 and 3. Every frequency is 1, so the frequency factors are those of step 1: 0.9641 for the six-token documents and 1.1256 for document 4.

Document From seabird From climat Score
1 $0.3567 \times 0.9641 = 0.3439$ 0.3439
2 $0.6931 \times 0.9641 = 0.6683$ 0.3439 1.0122
3 0.3439 0.3439
4 $0.6931 \times 1.1256 = 0.7802$ 0.7802

The ranking is document 2, then 4, then 1 and 3 tied. Document 4 matches one term and beats two documents that also match one, because its term is the rarer one and its length the shorter.

Problem 2 (two kinds of bound). Find the best document for seabirds climate with a document-at-a-time pass and $k = 1$, first with the bound $(k_1 + 1)\,\mathrm{IDF}$ for each term, then with the exact bound, the largest contribution in the term's postings list. Say which documents each pass scores.

Solution. The loose bounds are $2.2 \times 0.6931 = 1.5249$ for seabird and $2.2 \times 0.3567 = 0.7847$ for climat. The exact bounds are the largest entries of the table in Problem 1: 0.7802 for seabird (document 4) and 0.3439 for climat.

Document Terms Loose bound Action Exact bound Action Threshold after
1 climat 0.7847 score: 0.3439 0.3439 score: 0.3439 0.3439
2 seabird, climat 2.3096 score: 1.0122 1.1241 score: 1.0122 1.0122
3 climat 0.7847 skip 0.3439 skip 1.0122
4 seabird 1.5249 score: 0.7802 0.7802 skip 1.0122

Both passes return document 2. The loose bound scores three documents and skips one. The exact bound scores two and skips two: for document 4 it is 0.7802, which is at most the threshold 1.0122, while the loose bound 1.5249 is not. The loose bound assumes a term could reach its full saturation in some document. The exact bound knows that no document in the list comes close, and that knowledge costs one stored number per term.

Problem 3 (how fast the frequency factor saturates). For a six-token document of this collection, compute the frequency factor $\frac{\mathit{tf}\,(k_1 + 1)}{\mathit{tf} + K_d}$ for term frequencies 1, 2, 3 and 10, and express each as a share of its limit.

Solution. $K_d = 1.2818$ for a six-token document, and the limit as $\mathit{tf}$ grows is $k_1 + 1 = 2.2$.

$\mathit{tf}$ Factor Share of 2.2
1 $2.2/2.2818 = 0.9641$ 43.8%
2 $4.4/3.2818 = 1.3407$ 60.9%
3 $6.6/4.2818 = 1.5414$ 70.1%
10 $22/11.2818 = 1.9500$ 88.6%

The first occurrence earns 44 percent of everything the term can ever contribute, and the second adds 17 points more. This is why the loose bound of Problem 2 is loose for short documents with low counts: it sits at 100 percent.

Problem 4 (one new document changes every stored number). A fifth document, Arctic climate report, is added. Recompute the IDFs, the normalizers and the scores for the query arctic climate warming.

Solution. The new document analyzes to arctic, climat, report, three tokens. Now $N = 5$ and the average length is $(6 + 6 + 6 + 4 + 3)/5 = 5.0$.

  • IDFs. Arctic and climat now occur in 4 of 5 documents: $\ln(1 + 1.5/4.5) = 0.2877$, down from 0.3567. Warm still occurs in 2, but $N$ has grown: $\ln(1 + 3.5/2.5) = 0.8755$, up from 0.6931.
  • Normalizers. $K_d = 1.2\,(0.25 + 0.75\,L_d/5)$, which is 1.38 for six tokens (it was 1.2818), 1.02 for four (0.9545) and 0.84 for three. The frequency factors for one occurrence are $2.2/2.38 = 0.9244$, $2.2/2.02 = 1.0891$ and $2.2/1.84 = 1.1957$.
  • Scores. Documents 1 and 2: $(0.2877 + 0.2877 + 0.8755) \times 0.9244 = 1.3411$. Document 3: $0.2877 \times 0.9244 = 0.2659$. Document 4: $0.2877 \times 1.0891 = 0.3133$. Document 5: $2 \times 0.2877 \times 1.1957 = 0.6879$.

The ranking is 1 and 2 tied, then 5, 4 and 3. No word of documents 1 to 4 changed, yet every one of their scores did, because $N$, two document frequencies and the average length all moved. An index that stored the old IDFs and normalizers would now be computing a slightly different formula from a freshly built one, which is the inconsistency that systems updating in segments accept.

What we have learned

The formula is cheap because almost everything in it can be computed before the query arrives: the IDF in the dictionary, $K_d$ in an array, and three operations per posting. On the Arctic sentences the implementation reproduced the hand calculation exactly. Bounding each term's contribution let a document-at-a-time pass skip two of the four documents; on Cranfield it completed 9.2 percent as many scores as exhaustive scoring, with the same top 10, and the share fell each time the collection doubled. The parameters sit on a broad plateau, and the variants differ little in effectiveness, though enough to break reproducibility.

All of this measured one model against itself. Comparing ranking models runs BM25 against Boolean retrieval, TF-IDF and the BIM on the same collection and tests whether the differences are real. Rank fusion then combines such rankings instead of choosing among them. Beyond the course, Dense Passage Retrieval runs a dense retriever against this BM25 setup on Cranfield, and Hybrid Retrieval combines the two.

References

  • Kamphuis, C., de Vries, A. P., Boytsov, L., and Lin, J. (2020). Which BM25 do you mean? A large-scale reproducibility study of scoring variants. In Proceedings of ECIR 2020, 28–34. record · 2 pages
  • Robertson, S., and Zaragoza, H. (2009). The probabilistic relevance framework: BM25 and beyond. Foundations and Trends in Information Retrieval, 3(4), 333–389. record · 8 pages
  • Yang, P., Fang, H., and Lin, J. (2017). Anserini: Enabling the use of Lucene for information retrieval research. In Proceedings of SIGIR 2017, 1253–1256. record · 2 pages

Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 12 revisions