Sub topic 11
Combining lexical and dense retrieval before reranking
This chapter assumes you can write basic Python and know what a text embedding is. It also assumes you have met the retrieve-then-rerank pipeline from the earlier chapters. Here the focus is the candidate pool that feeds the cross-encoder. A reranker can only reorder what it receives, so the pool needs to contain the relevant passages.
Why one retriever is often not enough
Two kinds of first-stage retrievers are common.
- Lexical retrieval, such as BM25, scores passages by the words they share with the query. It is exact. It handles rare terms, product codes, error messages, and names well. It fails when the passage uses different words from the query.
- Dense retrieval uses a bi-encoder to turn the query and each passage into vectors. It matches meaning, so "change an API key" can find "rotate credentials". It can miss exact strings, such as
ERR_4021, because the embedding blurs rare tokens.
The two fail on different queries. Combining them raises the chance that the relevant passage enters the candidate pool. That is recall, and recall at the first stage sets the ceiling for the whole pipeline.
The score problem
You might try to merge the two result lists by adding scores. This usually goes wrong, because the scores are not comparable.
- BM25 scores are unbounded and depend on the corpus and the query length. A good match can score 3 or 30.
- Cosine similarity from a bi-encoder usually falls in a narrow band, often 0.2 to 0.8.
Adding a BM25 score of 14.2 to a cosine of 0.61 means BM25 dominates. You could normalize each list (min-max or z-score) and then weight them. That works, but the result is sensitive to outliers and to the weight you choose. It also needs tuning whenever the corpus changes.
Reciprocal rank fusion
Reciprocal rank fusion (RRF) avoids the score problem by ignoring scores. It uses only each document's rank in each list. For a document d, the fused score is:
RRF(d) = sum over lists of 1 / (k + rank(d))
The constant k is commonly 60. It limits how much the top ranks dominate. A document ranked 1 in one list scores 1/61. A document ranked 10 scores 1/70. The difference is small, so a document that appears near the top of both lists beats a document that is first in only one list.
def reciprocal_rank_fusion(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
lexical = ["d2", "d5", "d1"]
dense = ["d1", "d2", "d8"]
print(reciprocal_rank_fusion([lexical, dense]))Work through the output by hand. d2 is rank 1 in the lexical list and rank 2 in the dense list, so its score is 1/61 + 1/62. d1 is rank 3 and rank 1, so its score is 1/63 + 1/61. These are close, and d2 comes out slightly ahead. d5 and d8 each appear in only one list, so they land after the two documents found by both. The printed order is ['d2', 'd1', 'd5', 'd8'].
Notice what the function does not need. It does not need score scales, it does not need to know which retriever produced a list, and it accepts any number of lists. A document missing from a list simply gets no contribution from it.
Where fusion sits in the pipeline
Fusion is a step between first-stage retrieval and the cross-encoder. Both retrievers run on the same query, the fused list is cut to the candidate depth, and the cross-encoder scores that cut.
A complete hybrid example
The next example runs both retrievers over a small corpus, fuses them, and reranks. It uses the rank_bm25 package for the lexical side. Install it with pip install rank_bm25 sentence-transformers.
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer, CrossEncoder, util
corpus = [
"Rotate API keys from the Security page.",
"Reset your password in Account Settings.",
"Our API returns JSON by default.",
"Error ERR_4021 means the request token has expired.",
"Billing invoices are emailed on the first of each month.",
]
def tokenize(text):
return text.lower().replace(".", " ").split()
bm25 = BM25Okapi([tokenize(p) for p in corpus])
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
corpus_emb = bi_encoder.encode(corpus, convert_to_tensor=True,
normalize_embeddings=True)
def reciprocal_rank_fusion(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
def hybrid_search(query, depth=20, k_final=3):
# Lexical ranking: document indexes, best first
lex_scores = bm25.get_scores(tokenize(query))
lexical = sorted(range(len(corpus)), key=lambda i: lex_scores[i],
reverse=True)[:depth]
# Dense ranking
q_emb = bi_encoder.encode(query, convert_to_tensor=True,
normalize_embeddings=True)
hits = util.semantic_search(q_emb, corpus_emb, top_k=depth)[0]
dense = [h["corpus_id"] for h in hits]
# Fuse, then rerank the fused pool
pool = reciprocal_rank_fusion([lexical, dense])[:depth]
pairs = [(query, corpus[i]) for i in pool]
scores = cross_encoder.predict(pairs, batch_size=32)
order = sorted(range(len(pool)), key=lambda j: scores[j], reverse=True)
return [(corpus[pool[j]], float(scores[j])) for j in order[:k_final]]
for passage, score in hybrid_search("what does ERR_4021 mean"):
print(f"{score:.2f} {passage}")The query contains ERR_4021. BM25 matches that token exactly, while a dense model may not. Fusion carries the exact match into the pool, and the cross-encoder then judges whether the passage answers the question. Note that BM25 here is a toy: with five documents, the tokenizer and the ranking are only illustrative.
Practical details
Choose the same depth for each list
Pull the same number of candidates from each retriever, for example 50 each. The fused list can have up to 100 unique documents. Cut it to your reranking depth before the cross-encoder. Candidate depth is discussed in its own chapter, and fusion changes the tradeoff: documents found by both retrievers rise to the top of the cut, so a smaller cut loses less.
Deduplicate by document, not by text
Both retrievers must use the same ID for the same passage. If the lexical index and the vector store assign IDs separately, RRF treats one passage as two. Use one ID scheme, and key RRF on that ID.
Weight the lists when you have evidence
Plain RRF treats the lists equally. You can multiply each list's contribution by a weight, for example 1.0 for dense and 0.5 for lexical. Do this only after you measure on labeled queries. Without measurement, equal weights are a safer default.
Tune `k` last
The constant k = 60 comes from the original RRF paper and works across many datasets. Smaller values give more influence to the top ranks. Changing it rarely matters as much as fixing tokenization, chunking, or the embedding model.
Measuring whether fusion helps
Evaluate each stage separately, using the metrics from the evaluation chapter.
- Compute recall@N for lexical alone, dense alone, and fused, where N is your reranking depth. This tells you if the pool improved.
- Compute MRR and nDCG on the final reranked list for each pool. This tells you if the end result improved.
A typical finding is that fusion raises recall@N a few points over the better single retriever, and the reranked metrics improve less. If your cross-encoder is strong and the dense pool already has high recall, fusion may add little. If your corpus has many identifiers, acronyms, or exact phrases, the gain is usually larger.
| Situation | Likely effect of adding lexical retrieval |
|---|---|
| Natural-language questions, paraphrased content | Small gain |
| Codes, SKUs, error strings, names | Large gain |
| Short queries of one or two words | Moderate gain |
| Domain jargon the embedding model has not seen | Moderate to large gain |
Common errors
- Fusing raw scores from different retrievers. Use ranks, or normalize carefully.
- Running the reranker on the full fused list of 100 or more documents without checking latency. Cut first.
- Using different tokenization at index time and query time for BM25. Terms then never match.
- Treating fusion as a replacement for reranking. Fusion merges lists by rank agreement. It does not read the query and passage together, so it cannot judge relevance as a cross-encoder does.
- Evaluating only the final list. If the final result is poor, you cannot tell whether the pool or the reranker is at fault.
Exercise
Lexical ranking is ["a", "b", "c"] and dense ranking is ["c", "a", "d"]. Using RRF with k = 60, which document comes first, and why does "b" rank below "c"?
Show answer
Document "a" comes first. It scores 1/61 + 1/62 (about 0.03252). Document "c" scores 1/63 + 1/61 (about 0.03226), so it is second. Document "b" appears only in the lexical list at rank 2, so it scores 1/62 (about 0.01613), which is lower than any document found by both retrievers. The final order is a, c, b, d, because "d" scores 1/63 (about 0.01587) and "b" scores 1/62.
Exercise
Your fused pool has recall@50 of 0.92, but the final reranked MRR is low. Which stage should you investigate first, and why?
Show answer
Investigate the reranker. A recall@50 of 0.92 means the relevant passage is in the pool for most queries, so the pool is not the main limit. Check truncation of long passages, domain mismatch between the cross-encoder's training data and your content, and whether the labels used for evaluation are correct.