Reranking Search Results with Cross Encoders
Rerank retrieval candidates by scoring each query and document pair directly, and weigh the latency and cost before adding this stage to the request path.
On this page
Introduction
First stage retrieval optimizes for speed, so it embeds the query and documents independently and compares vectors. That independence is what makes it fast and what limits its precision: the model never sees the query and document together. A cross encoder scores the pair jointly, producing a far more accurate relevance number, but at a cost that makes it impractical for the whole corpus. The standard architecture therefore retrieves a generous candidate set cheaply, then reranks that shortlist with the expensive model. Done well, this two stage design keeps interactive search fast while delivering the accuracy of joint scoring exactly where it matters.
Bi Encoders Versus Cross Encoders
A bi encoder embeds the query and each document separately, so document vectors can be precomputed once and compared against a single query vector; that independence is what makes retrieval fast. A cross encoder feeds the query and one document together through the transformer and outputs one relevance score, which cannot be precomputed and must run once per candidate. The cross encoder is more accurate because attention can compare every query term against every document term, capturing negation, order and exact phrasing that vector similarity blurs. That accuracy only pays off on a shortlist, where the extra cost is bounded.
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def rerank(query: str, candidates: list[dict], top_n: int = 5) -> list[dict]:
if not candidates:
return []
# Cap the passage length so cost stays bounded; keep the head, not the tail.
pairs = [(query, c["body"][:2000]) for c in candidates]
scores = reranker.predict(pairs, batch_size=32)
for c, s in zip(candidates, scores):
c["rerank_score"] = float(s)
ranked = sorted(candidates, key=lambda c: c["rerank_score"], reverse=True)
return ranked[:top_n]
Choosing the Candidate Set Size
The reranker can only reorder what retrieval returns, so the candidate set must contain the relevant documents before reranking begins. Retrieve more candidates than you finally show, commonly fifty to two hundred, and measure recall at that K to confirm the ceiling of the whole pipeline. If recall at K is low, no reranker helps and the fix belongs upstream in retrieval or chunking. Reranking improves precision at the top of the list, which is exactly where users look and where a correct answer either appears or does not.
import math
def answer_or_abstain(query: str, candidates: list[dict], threshold: float = 0.2) -> dict:
ranked = rerank(query, candidates, top_n=5)
if not ranked or ranked[0]["rerank_score"] < threshold:
# No candidate is confidently relevant: refuse instead of hallucinating.
return {"answer": None, "reason": "no_relevant_context", "best_score": ranked[0]["rerank_score"] if ranked else None}
context = "\n\n".join(c["body"] for c in ranked)
return {"answer": generate(query, context), "sources": [c["doc_id"] for c in ranked]}
Running the Reranker Efficiently
Score candidates in batches and cap the document length, because cost grows with the number of pairs and their length. A distilled reranker runs in tens of milliseconds per hundred candidates on a GPU and acceptably on a CPU for smaller sets, so match the model size to your latency budget. Cache scores for repeated queries when traffic is bursty, and degrade gracefully by falling back to the first stage order when the reranker times out rather than failing the whole request. Never rerank on the critical path without a timeout.
Calibrating and Thresholding Scores
Reranker scores are useful for more than ordering: a low top score is a reliable signal that no candidate is relevant, which lets you abstain instead of generating a fabricated answer. Calibrate the threshold on a labelled set so the false abstain rate stays acceptable, and store the score alongside each result for later analysis. Do not assume scores are comparable across different reranker models, because their scales differ, and re-calibrate whenever you swap the model.
Measuring Whether Reranking Helps
Evaluate reranking as an A/B change on a golden set: compare mean reciprocal rank and normalised discounted cumulative gain with and without the reranker at the same cutoff. Track end to end latency as well, since a reranker that adds two hundred milliseconds may not be worth a small gain in ranking quality. Run the evaluation as an automated test so that a model or index change which silently degrades ranking fails the build instead of reaching users.
Pitfalls That Waste the Reranker
The most common mistake is truncating the document so aggressively that the relevant sentence is cut off, which makes the cross encoder reject the very document that held the answer. The second is reranking a filtered candidate set that never contained the answer to begin with. The third is comparing raw scores across queries as though they were probabilities. Each of these turns an accurate model into a costly no-op, so validate the whole pipeline end to end rather than the model in isolation.
Fitting the Reranker into a Latency Budget
A reranker sits between retrieval and generation, so its latency adds directly to time to first token. Budget it explicitly: if retrieval takes forty milliseconds and the reranker adds a hundred and fifty, the user waits nearly two hundred milliseconds before generation even starts. Reduce the candidate set, use a smaller distilled model, or move reranking off the synchronous path and let the first stage results render while reranking refines them in the background. For interactive search, cap the whole retrieval and reranking stage at a fixed deadline and return the best available ordering when that deadline passes, so a slow reranker degrades quality rather than availability.
Sources
Sources: Sentence Transformers cross encoder, MS MARCO dataset, Hugging Face reranker models.
FAQ
- How many candidates should I rerank?
- Enough that recall at K is high, commonly fifty to two hundred. Reranking a shortlist that never contained the answer cannot recover it, so tune K against a golden set first.
- Can I skip reranking if my vector search is already good?
- If precision at the top of the list is already sufficient for your use case, adding a reranker only adds latency. Measure mean reciprocal rank with and without it before committing.
Report a problem with this articleOpens a pre-filled issue on GitHub.