Sub topic 14
Choosing and adapting a reranker model
This chapter assumes you can run the two-stage pipeline from earlier chapters. It also assumes you know recall@k, MRR, and nDCG, and that you know the difference between pointwise, pairwise, and listwise training. Here you will choose a reranker for your own data and decide whether to fine-tune it.
Start with the constraints, not the leaderboard
Public benchmark rankings measure average quality on general web-style search. Your corpus, queries, and latency budget are different. Before you compare models, write down the constraints that rule candidates out.
| Constraint | Question to ask | Why it matters |
|---|---|---|
| Latency | How many milliseconds can reranking take per query? | Cost grows with candidate depth times model size. |
| Language | Are queries or passages multilingual? | Many popular cross-encoders were trained on English data only. |
| Input length | How long are your passages after chunking? | A model with a 512-token limit silently drops the rest. |
| Hosting | Can you run a model yourself, or must you call an API? | Self-hosting needs GPU or CPU capacity. An API adds network latency and per-call cost. |
| License | Does the license allow commercial use? | Some strong checkpoints carry non-commercial terms. |
| Domain | Is the text legal, medical, code, or support tickets? | A model trained on general web queries may not match your vocabulary. |
Check the license and the training data on each model card yourself. Do not assume them from the model's name.
Model families you will meet
Most options fall into three groups.
- Small distilled cross-encoders, such as the MiniLM models in the
cross-encoder/ms-marco-*series. They have a few tens of millions of parameters and run acceptably on CPU. They are a good baseline because the earlier chapters already use them. - Larger encoder rerankers, such as BERT-large-class or XLM-RoBERTa-based checkpoints, including multilingual ones. They are usually more accurate and slower. They generally need a GPU for interactive latency at depth 50 or more.
- Hosted reranking APIs and LLM-based rerankers. Hosted APIs remove operations work but add network latency, cost per request, and data-sharing questions. LLM rerankers were compared in the previous chapter. They cost the most per pair, so you usually use them on a short candidate list or for offline labeling.
Within a family, a larger model is not always better for your task. A 12-layer model costs roughly twice a 6-layer model per pair. Whether the extra quality is worth that cost is something to measure.
Build a small labeled evaluation set first
You cannot choose a model without data that reflects your queries. Collect 50 to 200 real queries. For each query, keep the candidate list your first stage returns and mark which passages are relevant. Candidates from your actual first stage are what matter, because a reranker only reorders what it is given.
Labels can come from search logs (clicks are noisy but cheap), from domain experts, or from an LLM judge that a human spot-checks. Treat even a small set of 50 queries as a rough signal. Differences of one or two points of MRR between models on 50 queries are probably noise.
Compare candidate models on your data
The harness below scores every candidate list with each model. It reports MRR@10, recall@3, and seconds per query. The two-query evaluation set is a placeholder. Replace it with your own labeled data.
import time
from sentence_transformers import CrossEncoder
eval_set = [
{
"query": "How do I rotate an API key?",
"relevant": {"a"},
"candidates": [
{"id": "b", "text": "Our API supports JSON and XML response formats."},
{"id": "a", "text": "Rotate API keys from the Security page by creating a new key."},
{"id": "c", "text": "Reset your password in Account Settings."},
],
},
{
"query": "When are invoices sent?",
"relevant": {"d"},
"candidates": [
{"id": "e", "text": "Reset your password in Account Settings."},
{"id": "d", "text": "Billing invoices are emailed on the first of each month."},
{"id": "f", "text": "Our API returns JSON by default."},
],
},
]
def reciprocal_rank(ranked_ids, relevant, k=10):
for i, doc_id in enumerate(ranked_ids[:k], start=1):
if doc_id in relevant:
return 1.0 / i
return 0.0
def recall_at_k(ranked_ids, relevant, k):
return len(set(ranked_ids[:k]) & relevant) / len(relevant)
def evaluate(model_name, data, batch_size=32):
model = CrossEncoder(model_name, max_length=512)
rr, rec = [], []
start = time.perf_counter()
for item in data:
pairs = [(item["query"], c["text"]) for c in item["candidates"]]
scores = model.predict(pairs, batch_size=batch_size)
order = sorted(range(len(pairs)), key=lambda i: scores[i], reverse=True)
ranked = [item["candidates"][i]["id"] for i in order]
rr.append(reciprocal_rank(ranked, item["relevant"]))
rec.append(recall_at_k(ranked, item["relevant"], 3))
elapsed = time.perf_counter() - start
return {
"model": model_name,
"mrr@10": sum(rr) / len(rr),
"recall@3": sum(rec) / len(rec),
"sec_per_query": elapsed / len(data),
}
for name in [
"cross-encoder/ms-marco-MiniLM-L-6-v2",
"cross-encoder/ms-marco-MiniLM-L-12-v2",
]:
print(evaluate(name, eval_set))Also record the first-stage ranking and compute the same metrics for it. If a reranker does not beat that baseline by a margin you can see across the whole set, it is not worth its latency.
Latency measured on your laptop does not predict production. Time each model on the hardware you will deploy to, at the candidate depth you plan to use, with realistic passage lengths.
Decide whether to adapt
Adapting a model means fine-tuning it on your own query-passage pairs. It costs labeling effort, training time, and ongoing maintenance, so treat it as a later step. The decision follows the measurements.
The first question in the diagram matters most. If the relevant passage is not among the candidates, no reranker can recover it. Recall@k of the first stage caps what any reranker can achieve, so fix retrieval before touching the reranker.
Fine-tune with hard negatives
Fine-tuning pays off when the domain vocabulary differs from the model's training data, for example internal product names or specialized jargon. You need pairs of a query and a passage with a label. Positives are passages judged relevant. Negatives should be hard negatives: passages your first stage ranks highly that are not relevant. Random negatives are too easy, and the model learns little from them.
The script below fine-tunes a small cross-encoder with a pointwise objective. Each pair has a label of 1.0 or 0.0. It uses the fit interface of sentence-transformers. Newer releases mark fit as legacy in favor of a trainer-based API, but it still works. Check the documentation for the version you have installed.
from torch.utils.data import DataLoader
from sentence_transformers import CrossEncoder, InputExample
model = CrossEncoder(
"cross-encoder/ms-marco-MiniLM-L-6-v2",
num_labels=1,
max_length=256,
)
train_samples = [
InputExample(texts=["rotate api key", "Rotate API keys from the Security page."], label=1.0),
InputExample(texts=["rotate api key", "Our API returns JSON by default."], label=0.0),
InputExample(texts=["rotate api key", "Reset your password in Account Settings."], label=0.0),
InputExample(texts=["invoice date", "Billing invoices are emailed on the first of each month."], label=1.0),
InputExample(texts=["invoice date", "Rotate API keys from the Security page."], label=0.0),
]
train_loader = DataLoader(train_samples, shuffle=True, batch_size=4)
model.fit(
train_dataloader=train_loader,
epochs=1,
warmup_steps=1,
output_path="reranker-tuned",
)
scores = model.predict([("rotate api key", "Rotate API keys from the Security page.")])
print(scores)Five pairs only demonstrate the mechanics. A useful fine-tune needs thousands of queries. For each query, include one or more positives and several hard negatives mined from your first stage.
Practical points when fine-tuning:
- Start from a pretrained reranker, not a raw language model. It already knows the task, so it needs far fewer examples.
- Use a low learning rate and one to three epochs. More training on a small set overfits and can hurt general queries.
- Mine negatives carefully. An unlabeled passage ranked high by the first stage may actually be relevant. Treating it as a negative teaches the model the wrong thing. Spot-check a sample of negatives.
- Keep the training max length equal to your serving max length. Otherwise the model sees different truncation at inference.
- Compare against the untouched model on the held-out set. Look at nDCG and MRR overall, and also at a sample of general queries to catch regressions.
Scores change when the model changes
Raw cross-encoder scores are not calibrated probabilities, and they are not comparable between models. If your application uses a score threshold, such as "drop passages below 0.3", changing or fine-tuning the model invalidates it. Re-derive the threshold from labeled data for each model version, and store the model name with any logged scores.
Operational checklist
- Pin the model name and revision in your configuration so an upstream change cannot alter rankings unnoticed.
- Re-run the evaluation set whenever you change the model, the chunking, the candidate depth, or the first-stage retriever.
- Log the query, the candidate IDs, and the rerank scores for a sample of traffic so you can build the next labeled set from real queries.
- Keep the previous model available for rollback.
Exercise
Your reranker beats the first-stage baseline by 0.04 MRR on 40 labeled queries, but recall@50 of the first stage is only 0.72. Where would you invest first, and why?
Show answer
Improve the first stage before fine-tuning or switching rerankers. With recall@50 at 0.72, the relevant passage is missing from the candidate pool for 28% of queries, and no reranker can return a passage it never receives. Options are a deeper candidate list, hybrid lexical and dense fusion, or better chunking. A 0.04 MRR gain on 40 queries is also within likely noise, so build a larger labeled set before drawing conclusions about the reranker.