Advanced about 5 h
The picture
01
BM25
exact terms
02
Dense
meaning
03
RRF fusion
merge rankings
04
Cross-encoder
rescore top 50
05
Top 5
to the LLM
Why one retriever is not enough
Dense retrieval captures meaning but misses exact strings (error codes, SKUs, names). Keyword retrieval (BM25) nails exact terms but misses paraphrase. Combining them is cheap and reliably better than either alone.
Reciprocal rank fusion
Scores from different retrievers are not comparable, but ranks are. RRF adds for each list a document appears in (a common default is ).
from collections import defaultdict
from rank_bm25 import BM25Okapi
tokenised = [d.lower().split() for d in docs]
bm25 = BM25Okapi(tokenised)
def bm25_rank(query, k=50):
s = bm25.get_scores(query.lower().split())
return list(np.argsort(-s)[:k])
def dense_rank(query, k=50):
q = model.encode(query, normalize_embeddings=True)
return list(np.argsort(-(D @ q))[:k])
def rrf(rankings, k=60):
score = defaultdict(float)
for ranking in rankings:
for r, doc_id in enumerate(ranking, start=1):
score[doc_id] += 1.0 / (k + r)
return sorted(score, key=score.get, reverse=True)
def hybrid(query, top=50):
return rrf([bm25_rank(query), dense_rank(query)])[:top]
Reranking with a cross-encoder
A bi-encoder embeds query and document separately, so document vectors are precomputed: fast, but the model never sees them together. A cross-encoder reads the pair jointly and scores relevance directly: much more accurate, but you must run it per candidate, so apply it only to the top 20 to 100.
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def retrieve(query, k=5, pool=50):
cand = hybrid(query, pool)
scores = reranker.predict([(query, docs[i]) for i in cand])
order = np.argsort(-scores)[:k]
return [cand[i] for i in order]
This two-stage pattern (cheap recall, then expensive precision) is the standard shape of production retrieval. Late-interaction models such as ColBERT sit between the two.
Measure the gain
Run your evaluation set through four configurations (dense only, BM25 only, hybrid, hybrid plus rerank) and tabulate recall@5 and p95 latency. Rerankers often add the largest single improvement, at a latency cost you should budget for.
Common mistakes
- Reranking only 5 candidates, which gives the reranker nothing to fix.
- Fusing raw scores instead of ranks.
- Skipping a BM25 baseline, then crediting a fancy model for gains a keyword index would have given.
Exercises
- Reproduce the four-way comparison on a corpus with many identifiers.
- Vary the rerank pool from 10 to 100 and plot quality against latency.
You are done when you can…
- Implement reciprocal rank fusion of a keyword and a dense ranking
- Add a cross-encoder reranker and measure the change in recall@5 and latency
- Explain why bi-encoders are fast and cross-encoders are accurate