Sub topic 14
Choosing and Adapting a Reranker Model
This chapter assumes you can run the two-stage pipeline from earlier chapters, know recall@k, MRR and nDCG, and have a rough idea of latency per candidate. Here you decide which cross-encoder to use and whether to adapt it.
What to compare
Pick a model on four things: quality on your data, latency, input length, and language coverage.
| Factor | What to check | Why it matters |
|---|---|---|
| Quality | nDCG@10 on your own labeled queries | Public benchmark scores often do not transfer |
| Latency | Milliseconds per 50 pairs on your hardware | Cost scales with candidate depth times model size |
| Max length | Tokens the model accepts (often 512) | Longer passages get truncated |
| Language | English-only or multilingual | An English model ranks other languages poorly |
Model size drives latency. A 6-layer MiniLM model is several times faster than a 12-layer one, and much faster than a large model. A larger model usually scores better, but the gain shrinks while the cost keeps growing.
Build a small evaluation set first
Do not choose from a leaderboard alone. Collect 50 to 200 real queries and mark the relevant passages for each. Then run every candidate model over the same first-stage pool and compare nDCG@10 and MRR. Always include the no-rerank baseline.
import math
import time
from sentence_transformers import CrossEncoder
def ndcg_at_k(ranked_ids, relevant, k=10):
dcg = sum(1 / math.log2(i + 1)
for i, d in enumerate(ranked_ids[:k], start=1) if d in relevant)
ideal = sum(1 / math.log2(i + 1)
for i in range(1, min(len(relevant), k) + 1))
return dcg / ideal if ideal else 0.0
def evaluate(model_name, eval_set):
# eval_set: list of (query, {doc_id: text}, set_of_relevant_ids)
model = CrossEncoder(model_name, max_length=512)
start = time.perf_counter()
scores_total = 0.0
for query, candidates, relevant in eval_set:
ids = list(candidates)
scores = model.predict([(query, candidates[i]) for i in ids], batch_size=32)
ranked = [i for _, i in sorted(zip(scores, ids), reverse=True)]
scores_total += ndcg_at_k(ranked, relevant)
elapsed = time.perf_counter() - start
return scores_total / len(eval_set), elapsed / len(eval_set)
eval_set = [
("How do I rotate an API key?",
{"a": "Rotate API keys from the Security page.",
"b": "Our API returns JSON by default.",
"c": "Reset your password in Account Settings."},
{"a"}),
]
for name in ["cross-encoder/ms-marco-MiniLM-L-6-v2",
"cross-encoder/ms-marco-MiniLM-L-12-v2"]:
ndcg, seconds = evaluate(name, eval_set)
print(f"{name}: nDCG@10={ndcg:.3f}, {seconds * 1000:.0f} ms/query")The loop reports quality and latency together, so you can see what each extra layer costs.
Decide whether to adapt
Fine-tuning helps when your vocabulary differs from the training data, for example legal text, code, or internal product names. It needs labeled pairs and hard negatives, as covered in the training chapters. Start with a few thousand pairs. Use a held-out query set for evaluation, and never evaluate on queries used for training.
Practical rules
- Start with the smallest model that clears your latency budget, then move up only if nDCG improves on your set.
- Check the license. Some popular rerankers restrict commercial use.
- Pin the model version, so a silent upstream change does not shift your rankings.
- Re-run the evaluation when your documents or query mix change.
Exercise
Your off-the-shelf reranker gives no nDCG gain over the first stage, and you find the relevant passage is missing from the top 50 candidates for 40% of queries. Should you switch to a larger reranker or fine-tune?
Show answer
Neither yet. A reranker can only reorder what it receives, so the problem is the candidate pool. Improve first-stage retrieval (hybrid fusion, better chunking, or a deeper pool), then re-evaluate the reranker.