BM25 vs Embeddings: Why Hybrid Retrieval Wins

BM25 vs embeddings on 300 labelled queries. Build both in NumPy, measure where each one fails, and merge them with reciprocal rank fusion.

Cover Image for BM25 vs Embeddings: Why Hybrid Retrieval Wins

You're looking for a scientific paper to help answer a question. One search names a gene, while another describes its effect in ordinary language. The right abstract can be missed if the retriever handles only one form well. A retrieval-augmented system then has to answer without that evidence, so the search deserves a comparison of its own.

Which query you ask changes the useful evidence. BEIR's 2021 zero-shot tests put BM25 ahead of all four dense retrievers on average. We build both methods and fuse their scores. Fusion helps across our full query set, but lowers scores on queries dominated by exact identifiers.

Dense vectors relate paraphrases, while BM25 rewards matching terms directly. Anthropic's 2024 contextual-retrieval report found a benefit from combining them. Adding BM25 alongside contextual embeddings reduced top-20 retrieval failures from 3.7% to 2.9%. We check the same trade-off query by query.

The evaluation measures nDCG@10 on 5,183 abstracts with 300 labelled queries. BM25 scores 0.661, dense 0.645 and fusion 0.694. On identifier queries, dense puts the right document first on 14 of 40; BM25 gets all of them. You will implement BM25 in NumPy and reciprocal rank fusion over an inference-only MiniLM index, then inspect the rescues and failures. The comparison runs on a laptop in under a minute.

Let's Build It

Open this in Google Colab and run it top to bottom.

Open In Colab

Here is rank fusion working on one query. The two ranked lists come from the two retrievers, and the third column is built by walking down both at once, adding 1/(60+rank)1/(60 + \text{rank}) to each document as it appears.

Animation of reciprocal rank fusion merging two ranked lists. The left column is the BM25 top eight and the middle column is the dense top eight for the query Statins decrease blood cholesterol. Rows light up one rank at a time from the top, and the right column rebuilds itself after each step, showing each document's accumulated fusion score. Document 3208, ranked second by BM25 and first by dense, finishes first. Document 1390, the relevant one, ranked third by both, finishes second. Document 3314, ranked first by BM25 but absent from the dense list, finishes fifth.

The corpus is SciFact from the BEIR benchmark: 5,183 scientific abstracts, 300 claims used as queries, and human relevance judgements for each. Small enough to index in half a second, real enough that the numbers line up with the published leaderboard.

corpus = load_scifact()               # 5,183 abstracts, 300 judged queries
queries, gold = corpus.query_list, corpus.gold

bm25 = BM25(corpus.texts)             # 0.4 seconds to index
doc_vecs = embed(corpus.texts)        # 29 seconds, inference only, no training
query_vecs = embed(queries)

lexical = [bm25.rank(q, k=100) for q in queries]
dense = [np.argsort(-row)[:100] for row in query_vecs @ doc_vecs.T]
hybrid = [rrf([a, b]) for a, b in zip(lexical, dense)]

for name, ranked in [("BM25", lexical), ("dense", dense), ("hybrid", hybrid)]:
    print(name, evaluate(ranked, gold))
          nDCG@10   MRR@10  recall@1  recall@10  recall@100
BM25       0.6611   0.6304    0.5275     0.7784      0.8852
dense      0.6451   0.6047    0.4823     0.7833      0.9250
hybrid     0.6940   0.6587    0.5479     0.8206      0.9543

Two panels. The left panel plots recall@k against k on a log axis from 1 to 100 for three retrievers: hybrid in blue is highest at every depth, rising from 0.55 at k equals 1 to 0.95 at k equals 100. BM25 in teal starts at 0.53 and ends at 0.89. Dense in amber starts lowest at 0.48, crosses above BM25 at around k equals 8, and ends at 0.93. The right panel is a bar chart of nDCG@10 showing BM25 0.661, dense 0.645 and hybrid 0.694.

Three things in that table are worth a second look. BM25, with no neural network anywhere in it, beats a sentence embedding model on the metric that matters most for RAG. Dense wins on deep recall, finding 92.5% of relevant documents in its top 100 against BM25's 88.5%. Fusion beats both on every column at once, and no setting of BM25's own parameters gets it there.

What Just Happened?

The judgements, and why you need them

The 300 queries come with relevance labels, 1.13 relevant documents each on average. Without labels you cannot tell whether a retrieval change helped, and "the answers look better" is not a measurement. Any serious retrieval work starts by writing down fifty queries and marking which documents should come back; the rest of this post is only possible because someone did that first.

BM25 as an inverted index

BM25 scores a document by summing one weight per query term. Each weight answers three questions about that word: how rare is it across the corpus, how often does it appear in this document, and how long is this document.

tf = count_terms(docs)                          # documents by vocabulary, sparse
df = (tf > 0).sum(axis=0)                       # documents containing each term
idf = np.log(1 + (n_docs - df + 0.5) / (df + 0.5))

norm = 1 - b + b * doc_len / doc_len.mean()     # long documents get discounted
weight = raw_tf * (k1 + 1) / (raw_tf + k1 * norm) * idf

Every entry is computed once and stored term-major, which is what an inverted index is: for each word, the list of documents containing it and the weight it contributes to each. Scoring is then a walk over one posting list per query term.

def score(self, query):
    scores = np.zeros(self.n_docs, dtype=np.float32)
    for token in tokenise(query):
        term = self.vocab.get(token)
        if term is None:
            continue                            # a word nobody wrote cannot match
        span = slice(self.starts[term], self.starts[term + 1])
        scores[self.docs_for_term[span]] += self.weight_for_posting[span]
    return scores

That loop touches only the documents that contain a query word, which is why lexical search stays fast on a laptop where a dense index wants a GPU to build. Our index holds 633,514 postings over a 35,734-word vocabulary and scores all 300 queries in 0.04 seconds.

The dense index

The dense side runs a MiniLM encoder over each document, mean-pools the token vectors, and normalises the result so cosine similarity becomes a dot product. Retrieval is then one matrix multiply.

hidden = model(**batch).last_hidden_state              # tokens to vectors
mask = batch["attention_mask"].unsqueeze(-1).float()
pooled = (hidden * mask).sum(1) / mask.sum(1)          # mean over real tokens
pooled = torch.nn.functional.normalize(pooled, dim=-1) # cosine becomes a dot product

Two details in those four lines cost accuracy later. The mask matters because padding tokens would otherwise drag every short document towards the same vector. And the encoder truncates at 256 tokens, which cuts the tail off 71% of this corpus, whose abstracts average 337 tokens. Nothing raises an error and nothing is logged; the documents are simply indexed on their opening paragraphs.

Reciprocal rank fusion

A BM25 score of 31.4 and a cosine similarity of 0.71 are not comparable, and normalising them means picking a scale and a weight. Reciprocal rank fusion sidesteps the problem by throwing the scores away and keeping only the positions.

RRF(d)=∑r∈R1k+r(d)\text{RRF}(d) = \sum_{r \in R} \frac{1}{k + r(d)}
def rrf(rankings, k=60, top=100):
    scores = {}
    for ranking in rankings:
        for position, doc in enumerate(ranking, start=1):
            scores[doc] = scores.get(doc, 0) + 1 / (k + position)
    return sorted(scores, key=lambda d: -scores[d])[:top]

The constant kk flattens the top of each list. With k=60k = 60, rank 1 contributes 0.0164 and rank 3 contributes 0.0159, so one retriever's confident first pick does not outvote a document that both retrievers put in their top five. That is the behaviour in the animation above: BM25's first choice falls to fifth because the dense index never mentions it, and the document both agree on at rank three finishes second.

Going Deeper

The three factors, ablated

Each part of the weight can be switched off to see what it was doing. Same corpus, same queries, one factor removed at a time.

VariantnDCG@10Change
Full BM250.6611
No saturation (raw counts)0.5402-0.121
No IDF (all words equal)0.5350-0.126
No length normalisation0.6490-0.012

IDF and saturation each carry about twelve points of nDCG. Length normalisation carries one, because every document here is an abstract and the lengths barely vary; on a corpus mixing tweets with legal filings that number would look different.

Three panels. The left panel plots term contribution against the number of times a term appears in a document, for k1 of 0.3, 0.9 and 2.0, each rising steeply then flattening towards a ceiling, against a dashed grey line for the raw count that keeps rising to 8. The middle panel plots measured nDCG@10 against k1, rising sharply from 0.614 at k1 equals 0 to a flat plateau of about 0.661 between 0.6 and 2.0, with the maximum circled at k1 equals 0.6, then falling to 0.653 at k1 equals 3. The right panel plots nDCG@10 against b over a very narrow range from 0.649 to 0.663, rising unevenly with the maximum circled at b equals 1.0.

The left panel is the saturation function on its own. A word appearing five times in a document is stronger evidence than one appearance, but not five times stronger, and k1k_1 sets how quickly the curve flattens. The middle panel is the same knob measured on real queries: at k1=0k_1 = 0 the count is discarded entirely and every present term contributes its IDF, which still scores 0.6138. Term counts add about five points on top of rarity.

The right panel is a warning about tuning. The whole bb sweep spans 0.014 of nDCG, the curve is not monotonic, and the best value on this corpus is 1.0 rather than the 0.4 the run used. Chasing that would be fitting to 300 queries.

Two failure modes, named

The aggregate scores hide what is happening underneath. On these 300 queries BM25 is strictly better on 73, dense is strictly better on 69, and they tie on 158. The disagreement is symmetric and it is not noise.

Two panels. The left panel is a scatter plot with one point per query, plotting the rank of the correct document under BM25 on the horizontal axis against its rank under dense retrieval on the vertical axis, both on log scales with a band marked missed for documents outside the top 100. Points cluster along the diagonal but a large fraction sit far off it, including a vertical stripe of points at the missed column and a horizontal stripe at the missed row. The right panel is a bar chart: dense finds it and BM25 misses on 24 queries, BM25 finds it and dense misses on 14, and neither finds it on 8.

The stripes along the two edges matter most. On 24 queries the dense index finds a document that BM25 loses entirely from its top 100, and on 14 queries BM25 rescues one that dense loses. Two named problems produce those two stripes.

Two panels, each pairing a real query with the document it should retrieve. The top panel, labelled the vocabulary gap, shows the query about co-IR blockade and adverse autoimmune events against the document Is autoimmunity the Achilles heel of cancer immunotherapy, sharing 2 of 8 words over four letters; BM25 does not place it in the top 100 while dense ranks it first. The bottom panel, labelled the lexical gap, shows the query Activation of PPM1D suppresses p53 function against the document Mosaic PPM1D mutations are associated with predisposition to breast and ovarian cancer, sharing 2 of 4 words; BM25 ranks it first while dense ranks it fifteenth.

The vocabulary gap is two ways of saying one thing. A query about "co-IR blockade" and "adverse autoimmune events" wants a paper titled "Is autoimmunity the Achilles' heel of cancer immunotherapy?". They share two content words. BM25 sums weights over shared terms, so with nothing to share it scores near zero and never sees the document. The embedding puts them next to each other because the training data connected those phrasings.

The lexical gap is a string with no meaning to learn. "Activation of PPM1D suppresses p53 function" is one rare gene symbol plus three ordinary words. BM25 gives PPM1D the highest IDF the corpus can produce and returns the document first. The encoder's wordpiece tokeniser shreds the symbol into fragments it has no useful representation for, and the right document lands at rank fifteen.

Each gap has its own fix, and neither fix helps the other. Stemming, synonym lists and query expansion attack the vocabulary gap. Exact matching attacks the lexical gap. Running both retrievers gets both fixes.

Rare identifiers, isolated

To measure the lexical gap instead of asserting it, build queries where the identifier is the only thing that distinguishes the target. Take each token that occurs in exactly one document and looks like a symbol (starts with a letter, mixes letters and digits, four to twelve characters), then pad it with three words common enough across the corpus to name a topic without pinning a document. Forty queries such as alk2 vascular endothelial stem and nct00153101 outcomes people high.

Dot plot of forty rare-identifier queries sorted by dense rank. Teal dots for BM25 sit at rank 1 for all forty queries, forming a flat line at the bottom. Amber dots for the dense index start at rank 1 for fourteen queries and rise steadily through ranks 2, 3, 5, 15, 22 and 45 to a band at the top marked missed, where eight queries have the correct document outside the top 100.

RetrievernDCG@10Correct document at rank 1Missed entirely
BM251.000040 of 400
dense0.468214 of 408
hybrid0.712025 of 400

BM25 is perfect, for mechanical reasons. Each identifier carries the highest IDF this corpus can produce, 8.1, and exactly one document contains it. The dense index loses a fifth of them past rank 100, which for a RAG pipeline pulling five chunks means the answer never reaches the model.

Delete the identifier from those same queries and dense falls to 0.1185, confirming that the identifier was carrying its signal. BM25 holds at 0.8944 on the leftover words, because three mid-frequency terms co-occurring in one abstract are themselves a strong lexical fingerprint.

The metrics, and why accuracy is not one

Retrieval has no accuracy. A retriever returns a ranked list, and how much a mistake costs depends on where in that list it lands.

  • recall@k asks whether the relevant documents are anywhere in the top kk. Set kk to the number of chunks your prompt will hold, since that number caps everything downstream.
  • MRR@10 is the reciprocal of the rank of the first hit, averaged. Use it when one good document is enough.
  • nDCG@10 discounts each hit by log⁡2(rank+1)\log_2(\text{rank} + 1) and divides by the best achievable arrangement. Use it when several documents are relevant and their order matters.

The three disagree in useful ways. Dense beats BM25 on recall@100 (0.9250 against 0.8852) while losing on recall@1 (0.4823 against 0.5275): it casts a wider net and ranks less sharply inside it. Report a single number and you will hide exactly that.

Rank fusion against score fusion

Rank fusion is not the only way to combine two lists. The alternative normalises both score distributions and blends them with a weight α\alpha. Both were measured.

Two panels. The left panel plots nDCG@10 against the RRF constant k on a log axis, from 0.7112 at k equals 1 down to 0.6919 at k equals 1000, with the usual default of 60 circled at 0.6940, all of it above a dashed line at 0.6611 marking BM25 alone. The right panel plots nDCG@10 against the score-fusion weight alpha, rising from 0.6451 at alpha 0, which is dense only, to a peak of 0.7156 at alpha 0.4, then falling to 0.6611 at alpha 1, which is BM25 only, crossing a dashed line at the rank-fusion result of 0.694 twice.

Tuned score fusion wins: 0.7156 at α=0.4\alpha = 0.4 against 0.6940 for rank fusion at the customary k=60k = 60. Reporting only that would be misleading in two directions.

First, rank fusion has its own constant, and 60 is a convention rather than an optimum. At k=5k = 5 it reaches 0.7131, level with tuned score fusion. Second, and more important, look at the shape of the two curves. Every setting of kk from 1 to 1000 beats both retrievers, so the worst thing an untuned rank fusion can do is win by less. Score fusion at α=0.8\alpha = 0.8 scores 0.6838, below rank fusion, and at the endpoints it degenerates into a single retriever.

The choice comes down to whether you have labels. With a judged query set, tune the weight and take the extra two points. Without one, rank fusion needs no score calibration, survives one retriever changing its score scale after a model upgrade, and cannot land you below where you started. Most teams shipping RAG are in the second situation, which is why the vector stores default to it.

The price of fusion

Fusion is insurance, and insurance has a premium. On the identifier queries BM25 scores a perfect 1.0000 and hybrid scores 0.7120, because half the votes come from a retriever that is wrong. Across the 300 SciFact queries, hybrid beats both retrievers on 28, matches the better of the two on 209, and lands below the better one on 63.

Fusion pays when you cannot predict which retriever will be right. When you can, route instead. When a query is one part number and nothing else, send it to the lexical index alone. Query classification of that kind is cheap, and on a corpus where one failure mode dominates it beats fusing on principle.

Chunk size, the variable nobody ablates

Chunking is usually copied from a tutorial and never revisited. The same corpus indexed at five granularities, evaluated at document level so the numbers stay comparable:

Two panels. The left panel plots nDCG@10 against chunk size for 32, 64, 128, 256 words and whole documents. BM25 in teal climbs steadily from 0.596 at 32 words to 0.661 at whole documents. Dense in amber does the opposite, starting highest at 0.673 for 32 and 64 words and falling to 0.645 at whole documents. Hybrid in blue is above both at every size except 32, peaking at 0.694 for whole documents. The right panel is a bar chart of index size, falling from 34,823 vectors at 32 words to 5,183 for whole documents.

The two curves run in opposite directions. Dense retrieval improves as chunks shrink, from 0.6451 on whole abstracts to 0.6734 at 32 words, because a single 384-dimensional vector cannot hold a 215-word abstract and because chunking removes the 256-token truncation. BM25 degrades the same way, from 0.6611 to 0.5964, because splitting a document destroys the term co-occurrence that made it findable and inflates every chunk's IDF contribution.

So the chunk size that is best for your embeddings is close to the worst for your lexical index. Hybrid peaks on whole documents here at 0.6940, though the best recall@100 comes from 64-word chunks at 0.9637. If you must pick one number for both indexes, measure it; if you can afford two indexes, chunk them differently.

The cost of each index

The BM25 index took 0.39 seconds to build and holds 633,514 postings in 7.6 MB. The dense index took 29 seconds on an M-series laptop, using its GPU, and holds 5,183 vectors in 8.0 MB. The sizes match almost exactly, which is not what most people expect, so the honest comparison is about hardware and change cost: rebuilding the lexical index after a corpus update is free, rebuilding the vectors is a GPU job, and every encoder upgrade is a full re-index. Retrieval time favours BM25 on a corpus this size (0.04 seconds for 300 queries against a 300 by 5,183 matrix multiply), but that ordering flips once the corpus is large enough to need an approximate-nearest-neighbour index.

Where This Comes From

BM25 is the surviving member of a research programme that ran for thirty years, and reading it as "a term-frequency heuristic" misses that every part of it was derived.

A two-track timeline. The upper teal track, labelled lexical, runs through 1976 relevance weighting by Robertson and Sparck Jones, 1994 saturation from the 2-Poisson model, 1995 BM25 named at Okapi at TREC-3, and 2009 BM25 and Beyond by Robertson and Zaragoza. The lower amber track, labelled neural, runs through 2013 dense word vectors with word2vec, 2019 sentence embeddings with Sentence-BERT, 2020 dense passage retrieval by Karpukhin et al., and 2021 BEIR finding BM25 still wins out of domain. A blue diamond in the middle marks 2009 reciprocal rank fusion by Cormack et al., and dashed arrows from the ends of both tracks converge on a second diamond marking 2024, hybrid as the default in every vector store.

Robertson and Sparck Jones (1976) started it by asking what weight a term deserves given how many relevant and non-relevant documents contain it. With no relevance information their weight collapses to the IDF in our code. The saturation curve arrived through the 2-Poisson model, which assumes a term is either "elite" for a document or not, and that term counts follow different distributions in each case. Robertson and Zaragoza's survey states the consequence:

We refer to this behaviour as saturation. That is, any one term's contribution to the document score cannot exceed a saturation point (the asymptotic limit), however frequently it occurs in the document. This turns out to be a very valuable property of the BM25 weighting function defined below.

Robertson & Zaragoza (2009), p. 356

Because the 2-Poisson model gives no closed form, the authors fitted the simplest curve with the right shape, tf/(k+tf)tf/(k + tf). Length normalisation came from a second argument, between two explanations for why one document is longer than another: verbosity (the author used more words for the same content) and scope (the author had more to say). While verbosity argues for dividing by length, scope argues against it. Their compromise is the bb in our code, and the survey states its effect plainly: "setting b=1b = 1 will perform full document-length normalisation, while b=0b = 0 will switch normalisation off."

Assembled, that is equation 3.15 of the survey, which is the weight line in the Quick Win:

wiBM25(tf)=tfk1((1−b)+bdlavdl)+tf  wiRSJw_i^{\text{BM25}}(tf) = \frac{tf}{k_1\left((1-b) + b\frac{dl}{avdl}\right) + tf}\; w_i^{\text{RSJ}}

Our implementation carries an extra (k1+1)(k_1 + 1) in the numerator, which the survey notes is "the same for all terms, and therefore does not affect the ranking produced". It exists so a single occurrence gets the same weight under BM25 as under the presence-only scheme. On parameter values the paper is candid that the theory runs out: "the model provides no guidance on how these should be set", with 1.2 < k1k_1 < 2 and 0.5 < bb < 0.8 offered as empirically reasonable. The k1=0.9k_1 = 0.9, b=0.4b = 0.4 used here comes from the Anserini defaults that the BEIR baselines use, and the sweeps above show why nobody agrees: the plateau is flat.

The dense track begins properly with Karpukhin et al. (2020), who showed a BERT bi-encoder trained on question-passage pairs beating BM25 by 9 to 19 points on open-domain QA. Thakur et al. (2021) then built BEIR to ask whether that transferred, and found it often did not: models tuned on one distribution lost to BM25 on corpora they had not seen. SciFact, used in this post, is one of those datasets, and our 0.6611 for BM25 against 0.6451 for MiniLM reproduces the pattern.

Cormack, Clarke and Buettcher (2009) supplied the join. Their two-page SIGIR paper showed that summing reciprocal ranks beat Condorcet fusion, CombMNZ and the individual learning-to-rank methods on the LETOR benchmark, using no training and no weights. They picked k=60k = 60 as the best average across their runs, and the constant has been copied ever since, including into the vector stores that now ship it as a default.

Further reading

Interactive Tools

  • Eigenvalue & SVD Visualizer: The geometry behind cosine similarity, projections and the low-rank structure a dense index relies on
  • LLM Cost Calculator: Price the context window that your chosen k and chunk size will fill on every request

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions