Reranking (cross-encoders)

In one sentence

Retrieve many candidates cheaply, then let a slower, smarter model reorder them and keep only the best few for the prompt.

Analogy: A recruiter skims 200 CVs by keywords in minutes; the hiring manager then reads the top 20 carefully and picks 3.

Stage 1 optimizes recall in milliseconds; stage 2 buys precision on a small set.

How it works

  • Vector search uses a bi-encoder: query and documents are embedded separately, so it is fast but imprecise.
  • A cross-encoder reads query and candidate together, catching negation and exact constraints that cosine similarity misses.
  • It is far too slow for millions of documents, but cheap on ~50 candidates.
  • So production RAG runs two stages: retrieve the top ~50–100 for recall, then rerank and keep the top 3–8.
  • Fewer, better chunks mean better answers and a shorter, cheaper prompt.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your RAG bot gives wrong answers. Tracing shows the right chunk ranks #14 of the top-50 candidates, but only the top 5 reach the LLM. Highest-leverage fix?

Go deeper

Full explanation

Vector search uses a bi-encoder: query and document are embedded separately, so documents can be pre-computed and searched in milliseconds. The price is precision — the two texts never "see" each other.

A cross-encoder feeds the query and one candidate together into a transformer and outputs a relevance score. Every query token can attend to every document token, so it catches negation, exact constraints and subtle relevance that cosine similarity misses. It is far too slow to run over millions of documents, but cheap on 50.

So production RAG uses two stages:

  1. Recall — Hybrid search & RRF or vector search returns top ~50–100.
  2. Precision — the reranker scores each (query, chunk) pair and you keep the top 3–8.

Fewer, better chunks means better answers and a smaller, cheaper prompt.

Code Rerank 50 candidates with an open cross-encoder
pythonRerank 50 candidates with an open cross-encoder
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")

def rerank(query: str, chunks: list[str], keep: int = 5) -> list[str]:
    # One forward pass per (query, chunk) pair, batched
    scores = reranker.predict([(query, c) for c in chunks])
    ranked = sorted(zip(scores, chunks), reverse=True)
    return [c for _, c in ranked[:keep]]

candidates = hybrid_search(query, k=50)   # stage 1: cheap recall
context = rerank(query, candidates)        # stage 2: precision
Real example

A support bot is asked "How do I cancel without losing my data?". Vector search ranks a chunk titled "Cancel your plan — data is deleted after 30 days" first because it is semantically close. The cross-encoder reads both texts together, notices the "without losing data" constraint, and promotes the "Export your data before cancelling" chunk from #14 to #1.

Trade-offs +3 · −3

+ You gain

  • Usually the single biggest quality jump you can add to a RAG pipeline.
  • Fewer chunks in the prompt: lower cost, less distraction for the LLM.
  • Drop-in: no re-indexing needed, works over any first-stage retriever.

− You pay

  • Adds latency, roughly 50–300 ms for ~50 pairs depending on model and hardware.
  • Can't fix bad recall: if the right chunk isn't in the top 50, it's gone.
  • Another model to host or another API to pay and depend on.

Use it when

Almost any production RAG where answer quality matters and you can afford ~100–200 ms more.

Avoid it when

Ultra-low-latency autocomplete, or when recall@50 is already the bottleneck — fix retrieval first.

Numbers to know 2
  • Typical shape: retrieve 50–100 → rerank → keep 3–8.
  • Anthropic measured contextual retrieval + reranking cutting top-20 retrieval failures by 67%.
Common pitfalls 3
  • Reranking a top-5: there's nothing left to reorder. Give it a wide pool.
  • Using an English-only reranker on multilingual data.
  • Not measuring: track recall@k before and nDCG/answer quality after the reranker.
Interview questions 2

Answer out loud first, then reveal.

Why not just use the cross-encoder for the whole search?Show answer

Because it can't pre-compute anything: it must run the model once per (query, document) pair at query time. Over a million documents that's a million forward passes per query. Bi-encoders let you embed documents offline and do ANN search in milliseconds, so I use them for recall and spend the cross-encoder's cost only on the top 50.

Your RAG answers are wrong although the right document exists. Where do you look?Show answer

I split the problem. First, is the right chunk in the top-50 candidates (recall@50)? If not, it's chunking, embeddings or missing lexical search — add hybrid search. If it is there but not in the final top-5, ranking is the issue — add or tune a reranker. If it reaches the prompt and the answer is still wrong, it's generation: prompt, context order or model.