Sub topic 12
Improving precision with cross-encoder reranking
This chapter assumes you can build the semantic search from the earlier chapters: embed documents, embed a query, and take the top-k by cosine similarity. It also assumes you know recall@k and MRR.
Why the first pass is imprecise
The embedding model in your search is a bi-encoder. It encodes the query and each document separately, and you compare the two vectors afterward. That is fast, because document vectors are computed once and stored. The cost is that each text is squeezed into one vector before the model sees the other text. Fine details, such as negation or which entity does what to which, can get lost.
A cross-encoder reads the query and a document together as one input. Every query token can attend to every document token. The model outputs a single relevance score. This is usually more accurate, but nothing can be precomputed. Scoring a million documents per query would be far too slow.
The two-stage pattern
Combine both. A cheap first stage retrieves a few dozen candidates. A cross-encoder then reorders only those candidates.
The first stage is judged on recall: the relevant document must be somewhere in the candidate set. The reranker is judged on precision: the relevant document must end up near the top.
Reranking in code
import numpy as np
from sentence_transformers import SentenceTransformer, CrossEncoder
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
docs = [
"Steps to recover access to your account",
"Our office is open from 9 to 5 on weekdays",
"Change your login credentials in the security settings",
"The cafeteria serves lunch at noon",
]
doc_emb = bi_encoder.encode(docs, normalize_embeddings=True)
def search_and_rerank(query, n_candidates=3, k=2):
q = bi_encoder.encode(query, normalize_embeddings=True)
candidates = np.argsort(-(doc_emb @ q))[:n_candidates]
pairs = [(query, docs[i]) for i in candidates]
scores = reranker.predict(pairs) # one score per pair
order = np.argsort(-scores)[:k]
return [(docs[candidates[j]], float(scores[j])) for j in order]
for text, score in search_and_rerank("How do I reset my password?"):
print(f"{score:.2f} {text}")The cross-encoder takes a list of (query, document) pairs and returns one score for each. These scores are raw model outputs. They are not cosine similarities, and they are only comparable within one query.
Choosing the candidate count
Candidate count is the main tuning knob.
| Candidates | Effect |
|---|---|
| Too few | The relevant document may never reach the reranker, so reranking cannot fix it. |
| Too many | Latency and cost grow linearly, because each candidate needs a full model pass. |
A common starting point is 50 to 100 candidates. To tune it, measure recall@n for the first stage, then pick the smallest n where recall stops improving. Also measure MRR or nDCG before and after reranking on labeled queries to confirm that reranking helps on your data.
Common errors
- Reranking the whole collection. This is the slowest possible design. Always retrieve first.
- Comparing reranker scores across queries or mixing them with cosine scores. Use them only to sort within one query.
- Ignoring the input limit. Cross-encoders truncate long inputs, so rerank chunks, not whole documents.
- Skipping evaluation. A reranker trained on web search data can underperform on specialized domains.
Exercise
Your first stage returns the top 20 documents, and the only relevant document is ranked 35th. Will a cross-encoder reranking those 20 results fix this? What would you change?
Show answer
No. The relevant document is not in the candidate set, so the reranker never sees it. Increase the candidate count to at least 40, or improve first-stage recall with hybrid search or better chunking. Then rerank the larger set.