Sub topic 12
Improving precision with cross-encoder reranking
This chapter assumes you can run the bi-encoder search from earlier chapters (embed documents, take a matrix product, sort for the top k). It also assumes you know what hybrid search returns: a ranked list of candidate documents. Here you add a second, slower scoring stage that reorders those candidates.
Why a first-stage ranking is not enough
A bi-encoder embeds the query and each document separately. The document vectors can be computed once and stored. At query time you embed only the query and compare vectors. This is what makes search over millions of documents fast.
The cost is that the model compresses a whole document into one vector without knowing what the query will be. Details that matter for a specific question can get lost. The first-stage ranking is therefore good at recall (the right document is probably somewhere in the top 50 or 100) and weaker at precision (the right document is not always at rank 1).
Reranking fixes the ordering of a short candidate list with a more accurate model. The first stage finds candidates cheaply, and the second stage spends more compute per candidate.
Bi-encoders versus cross-encoders
A cross-encoder is a transformer that reads the query and the document together as one input. A typical input looks like [CLS] query [SEP] document [SEP]. Self-attention can then compare every query token with every document token directly. The model outputs a single relevance score, not a vector.
| Property | Bi-encoder | Cross-encoder |
|---|---|---|
| Input | One text at a time | Query and document together |
| Output | A vector | A relevance score |
| Document vectors precomputed | Yes | No, nothing to precompute |
| Cost per query | One forward pass, plus a vector search | One forward pass per candidate |
| Typical use | Retrieve from the whole collection | Reorder 20 to 200 candidates |
| Accuracy on ranking | Good | Usually clearly better |
Because the score depends on the query, a cross-encoder cannot cache anything per document. Scoring a 10-million-document collection with one would need 10 million forward passes for every query, which is impractical. This is why the two-stage design exists.
Reranking in code
The sentence-transformers library provides a CrossEncoder class. The model below was trained on the MS MARCO passage ranking dataset. It is small enough to run on a CPU.
import numpy as np
from sentence_transformers import SentenceTransformer, CrossEncoder
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
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",
"Passwords must contain at least twelve characters",
"Contact support if you lost your two-factor device",
]
doc_emb = bi_encoder.encode(docs, normalize_embeddings=True)
def retrieve(query, n_candidates):
q = bi_encoder.encode(query, normalize_embeddings=True)
scores = doc_emb @ q
return np.argsort(-scores)[:n_candidates]
def rerank(query, candidate_ids, top_k, batch_size=32):
pairs = [(query, docs[i]) for i in candidate_ids]
scores = cross_encoder.predict(pairs, batch_size=batch_size)
order = np.argsort(-scores)[:top_k]
return [(docs[candidate_ids[i]], float(scores[i])) for i in order]
query = "How do I reset my password?"
candidates = retrieve(query, n_candidates=4)
print("First stage:")
for i in candidates:
print(" ", docs[i])
print("After reranking:")
for text, score in rerank(query, candidates, top_k=2):
print(f" {score:7.3f} {text}")Run it on your own machine and compare the two lists. On a tiny collection like this one, the order may or may not change. The benefit shows up on larger collections, where many near-duplicates compete for the top positions.
Points to notice in the code:
predicttakes a list of(query, document)pairs and returns one score per pair, in the same order.argsort(-scores)sorts from the highest score to the lowest, the same pattern as in the search chapter.- The cross-encoder only ever sees the candidates, so the work scales with
n_candidates, not with the collection size.
What the scores mean
A cross-encoder trained as in the example above returns raw scores (logits). They are not probabilities and are not bounded to 0 through 1. Some models are trained with a sigmoid output, and then scores fall between 0 and 1. Check the model card.
Two consequences follow:
- Scores are comparable only within one query and one model. A score of 4.2 for one query does not mean the same thing as 4.2 for another.
- A fixed threshold ("keep results above 0") needs calibration on labeled queries from your own data. Do not guess it.
Do not mix cross-encoder scores with bi-encoder cosine similarities by simple addition. They are on different scales. If you want to combine them, use reciprocal rank fusion on ranks, as in the hybrid search chapter, or train a combiner on labeled data.
Choosing the candidate count
The number of candidates, often written N, controls the trade-off between quality and cost.
- Too small: if the relevant document is not in the first-stage top N, the reranker cannot find it. Reranking can only reorder what it receives. Recall@N of the first stage is the upper limit.
- Too large: latency grows linearly with N, and the reranker may promote odd matches from the long tail.
A practical way to pick N is to measure recall@k of the first stage for k = 20, 50, 100, 200 on labeled queries, then choose the smallest N where recall stops improving much. The evaluation chapter shows how to compute these metrics.
Rough latency planning (illustrative figures; measure on your own hardware):
| Setup | Candidates | Relative cost |
|---|---|---|
| Small MiniLM cross-encoder on a GPU | 100 | Tens of milliseconds |
| Same model on a CPU | 100 | Often a few hundred milliseconds or more |
| Large cross-encoder (hundreds of millions of parameters) on a CPU | 100 | Can reach seconds |
Cost also grows with text length, because attention cost rises with the number of tokens. Reranking 100 long chunks costs much more than reranking 100 short ones.
Edge cases and failure modes
Input length limits
Cross-encoders have a maximum sequence length, often 512 tokens, and the query and document share that budget. Text beyond the limit is cut off. If your chunks are longer than the budget, the reranker never sees the end of them. Keep chunk sizes in line with the reranker's limit, not only the embedding model's, which is a reason to revisit your chunking settings when you add a reranker.
Domain mismatch
A reranker trained on web search passages can behave poorly on legal text, source code, or product catalogs. The same warning applied to embedding models earlier. Always test on a sample of your own queries. If the reranker does worse than the first stage on your data, remove it or fine-tune it.
Language and query style
An English-only reranker will rank non-English documents unreliably. Multilingual rerankers exist. Pick one that matches your languages, and check that it handles your query style (short keywords versus full questions).
Ties and near-ties
When two candidates score almost the same, small changes such as batch composition on some hardware or a different library version can swap them. Do not build tests that depend on exact scores. Test on metrics over many queries.
Added latency and failure paths
The reranker is another model to load, host, and monitor. Decide ahead of time what happens when it times out. A common fallback is to return the first-stage order.
Checking that reranking helps
Do not assume a reranker improves results. Run the same labeled queries through both pipelines and compare MRR, recall@k, and nDCG at the cutoff your application uses (often the top 3 to 10). The recall_at_k and reciprocal_rank functions from earlier chapters work unchanged. Pass them the reranked ID list instead of the first-stage list.
Expect gains mostly in precision at the top (MRR, nDCG@5). Recall@N for the final list cannot exceed the first stage's recall@N, because reranking only permutes the same candidates. If recall@100 is low, fix the first stage with better chunking, a better embedding model, or hybrid search, not the reranker.
Summary of the decision
Add a cross-encoder reranker when all of these hold:
- The first stage already finds the right documents within its top 50 to 200 (high recall@N), but they are not ranked first.
- Your latency budget allows one extra model pass over N short texts.
- A measurement on labeled queries from your own data shows a gain.
If any of these fails, spend effort elsewhere first.
Exercise
A first-stage retriever has recall@100 of 0.70 on your labeled queries. You add a cross-encoder that reranks the top 100 and see MRR improve. A colleague says the reranker will also raise recall@100 to about 0.90. Is that right? What would you change to raise recall@100?
Show answer
No. The reranker only reorders the same 100 candidates, so recall@100 after reranking stays 0.70. A document missing from the candidates cannot be recovered. To raise recall@100, improve the first stage: tune the chunk size and overlap, try a better embedding model, or add BM25 through hybrid search with reciprocal rank fusion. Increasing N (for example to 200) can also raise recall, at the cost of more reranking latency.
Exercise
Why can't you precompute cross-encoder document representations the way you precompute bi-encoder document vectors, and what does this imply about where in the pipeline the cross-encoder belongs?
Show answer
A cross-encoder reads the query and the document together, and its score depends on both. There is no query-independent document representation to store, so every query needs a new forward pass for each document it scores. This makes it too expensive for the whole collection. It belongs in a second stage that scores only a short candidate list from a fast first stage such as a vector index or hybrid search.