Sub topic 11
Reranking Retrieved Passages
This chapter assumes you have read the earlier chapters on top-k retrieval and hybrid search. You should know how embeddings, cosine similarity, and reciprocal rank fusion work. You should also be comfortable with basic Python and with calling a model from a library.
Why a second ranking step
The first-stage retriever (vector search, keyword search, or both) is built for speed. It compares the query with millions of precomputed chunk vectors. That is cheap, but the comparison is coarse. The query and the chunk are each squashed into one vector independently, so the model never sees them together.
This causes two common problems:
- The right passage is in the top 30 but not in the top 5, so it never reaches the prompt.
- Passages that are topically close but do not answer the question outrank the passage that does.
A reranker is a second, slower model that re-scores a small candidate set. The pipeline becomes a funnel:
- Retrieve a wide set (for example, the top 50) cheaply.
- Rerank those 50 with an expensive model that reads the query and each passage together.
- Keep the best few (for example, the top 5) for the prompt.
Bi-encoders and cross-encoders
The difference between the two model types explains the cost and the quality gap.
A bi-encoder embeds the query and each passage separately. Passage vectors are computed once at ingestion time and stored. At query time you embed only the query, then compare vectors. Cost per query is small and nearly independent of corpus size when an index is used.
A cross-encoder takes the query and one passage as a single input and outputs one relevance score. The model's attention can connect words in the query to words in the passage directly. This is usually more accurate, but nothing can be precomputed. Every query needs one model run per candidate.
| Property | Bi-encoder (first stage) | Cross-encoder (reranker) |
|---|---|---|
| Input | Text alone | Query and passage together |
| Precompute passage side | Yes | No |
| Cost per query | One embedding plus an index lookup | One model run per candidate |
| Works over the full corpus | Yes | No, candidates only |
| Typical accuracy | Good | Better on relevance ordering |
This is why reranking only ever runs on a short candidate list. Running a cross-encoder over a million chunks per query is impractical.
A minimal reranking step
The reranking logic is independent of the model. A function that takes a scoring callable keeps the pipeline testable.
def rerank(query, candidates, score_fn, top_n=5):
# candidates is a list of (doc_id, text) pairs
scored = [(score_fn(query, text), doc_id, text) for doc_id, text in candidates]
scored.sort(key=lambda item: item[0], reverse=True)
return scored[:top_n]
def overlap_score(query, text):
# Toy scorer: fraction of query words that appear in the passage
q_words = set(query.lower().split())
t_words = set(text.lower().split())
return len(q_words & t_words) / len(q_words) if q_words else 0.0
candidates = [
("a", "Refunds are issued within 14 days of a return request."),
("b", "Our refund policy page was redesigned last spring."),
("c", "To request a refund, submit a return and wait 14 days."),
]
for score, doc_id, text in rerank("how long do refunds take", candidates, overlap_score, top_n=2):
print(f"{doc_id} {score:.2f} {text}")The toy scorer only counts shared words, so it is not a real reranker. It shows the shape of the step: score every pair, sort, truncate.
Using a real cross-encoder
The sentence-transformers library provides cross-encoders. Install it with pip install sentence-transformers. The model downloads on first use.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def cross_encoder_rerank(query, candidates, top_n=5, batch_size=32):
# candidates is a list of (doc_id, text) pairs
pairs = [(query, text) for _, text in candidates]
scores = model.predict(pairs, batch_size=batch_size)
ranked = sorted(
zip(scores, candidates), key=lambda item: item[0], reverse=True
)
return [(float(s), doc_id, text) for s, (doc_id, text) in ranked[:top_n]]Scores from this model are raw values, often called logits. They are comparable within one query, but you should not treat them as probabilities or compare them across different queries without calibration.
Choosing the candidate count
The candidate count, often called the first-stage depth, is the main tuning knob. It trades recall against latency and cost.
- Too small (for example, 5 candidates feeding a rerank to 5): the reranker can only reorder, so it cannot rescue a relevant passage ranked 12th.
- Too large (for example, 500): latency grows linearly, and more near-miss passages compete with the right one.
A practical process is to measure recall@k on a labeled set at several depths, using the recall_at_k function from the evaluation chapter. Pick the smallest depth where recall stops improving much. Values between 20 and 100 are common starting points.
Hosted rerankers and LLM rerankers
You have three broad options for the reranking model.
- Local cross-encoder. You control latency, data stays on your machine, and cost is compute. You must host it, and a GPU may be needed at high traffic.
- Hosted reranking API. Simple to adopt, with no model hosting. Each query sends the candidate text to a third party, which matters for private data and adds a network call.
- LLM as reranker. You prompt a language model to rate or order passages. It is flexible and can follow custom criteria, but it is the slowest and most expensive option. Its output can also vary between runs, so set the temperature to 0 and validate the output format.
Edge cases and pitfalls
Truncation. Cross-encoders have a maximum input length, often 512 tokens for the query and passage combined. A long chunk is silently cut off, so a relevant sentence near the end may never be scored. Keep chunks within the reranker's limit, or score sub-windows and take the maximum.
Domain mismatch. A reranker trained on web search data may rank poorly on legal text, code, or product codes. Test it on your own queries before trusting it.
Discarding good first-stage signals. A reranker replaces the first-stage order. If it is weaker than the retriever on exact identifiers such as error codes, you lose those matches. One mitigation is to fuse the reranker score with the first-stage rank using reciprocal rank fusion.
Score thresholds. Dropping passages below a fixed score can help the model refuse when nothing is relevant. Choose the threshold from labeled data, because raw scores shift between models.
Duplicates. Overlapping chunks can fill the top 5 with near-copies of one passage. Deduplicate before or after reranking.
Latency. Rerank time grows with candidate count and passage length. Batch the pairs, cap passage length, and measure the p95 latency, not only the average.
Measuring whether it helps
Reranking is an added cost, so verify the gain. Using a labeled set of queries with known relevant chunk ids:
- Compute recall@5 and MRR (mean reciprocal rank) for first-stage retrieval alone.
- Compute the same metrics after reranking the top 50.
- Compare, and also record added latency per query.
If recall@5 rises noticeably while recall@50 stays the same, the reranker is working as intended. If neither moves, the first stage was already ordering well and the extra step may not be worth its cost.
Exercise
A system retrieves the top 5 passages with a bi-encoder, then reranks those same 5 with a cross-encoder and keeps all 5. Users report that the correct passage is often missing from the prompt. Will the reranker fix this, and what would you change?
Show answer
No. With 5 candidates and 5 kept, the reranker only reorders the same passages, so a relevant passage that was not retrieved stays missing. Increase the first-stage depth (for example, retrieve 50), rerank, and then keep the top 5. Confirm the change by comparing recall@5 before and after on a labeled query set.
Exercise
Why can a cross-encoder not replace the first-stage retriever over a corpus of one million chunks?
Show answer
A cross-encoder needs a model run for every query and passage pair, and passage-side work cannot be precomputed. Scoring one million chunks per query would be far too slow and costly. A bi-encoder with a vector index avoids this by precomputing passage vectors and searching them quickly, so the cross-encoder is reserved for a short candidate list.