Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#reranking#cross-encoder#retrieval
Frame · ai-engineering / rag / 07-reranking-with-cross-encoders.mdGuide 019 / 103

Reranking with cross-encoders

First-stage retrieval is built for speed: it compares a query vector with millions of precomputed chunk vectors, so the query and the chunk never actually meet. A reranker is the second stage that does let them meet. It reads the query and each candidate together and outputs a relevance score. On most RAG systems I have worked on, adding a reranker was the single biggest quality jump per line of code. This doc explains why it works, where it sits, and how to keep it from blowing your latency budget.

Why it matters

The LLM only sees the few chunks you put in the prompt. If the right chunk is at position 12 of the retriever's output and you pass the top 5, the answer is wrong no matter how good the model is. Rerankers fix exactly this: they are much better than embeddings at judging fine-grained relevance (negation, which entity a sentence is about, whether a passage actually answers the question or just shares keywords), so they move the right chunk from position 12 into the top 5.

Anthropic's contextual retrieval experiments are a public data point: adding a reranking step on top of contextual embeddings and contextual BM25 reduced their top-20 retrieval failure rate further than either retrieval improvement alone.

How it works

There are two architectures for scoring relevance with transformers.

A bi-encoder (your embedding model) encodes query and document separately into vectors and compares them with cosine similarity. Documents can be encoded once, offline, which is what makes vector search scale.

A cross-encoder concatenates query and document into one input and runs them through the transformer together, so attention flows between query tokens and document tokens. It outputs a single relevance score. It is far more accurate, and far more expensive: you must run the model once per (query, candidate) pair at query time, and nothing can be precomputed.

The standard design uses both: a bi-encoder (plus BM25) to fetch tens of candidates cheaply, then a cross-encoder to reorder them.

Rendering diagram…

Reranker options in 2026 fall into three groups:

  • Hosted APIs. Cohere Rerank (v2 API; Cohere's docs list rerank-v3.5 and newer rerank-v4.0 variants), Voyage and Jina also offer rerank endpoints. Easy to adopt and multilingual, at a per-request cost.
  • Open-weight cross-encoders. For example BAAI/bge-reranker-v2-m3 (multilingual, built on the BGE-M3 backbone) or the MS MARCO cross-encoders that ship with sentence-transformers. Run on your own GPU or even CPU for modest volume.
  • LLM rerankers. Prompt a general LLM to score or order candidates (pointwise or listwise). Flexible and good at nuanced instructions ("prefer the most recent policy"), but slower and more costly per candidate than a dedicated cross-encoder.

Reference architecture

Rendering diagram…

The "apply threshold" step is underrated. Reranker scores are more comparable across queries than raw cosine similarities, so a minimum score lets you pass fewer chunks when only one is relevant, or none at all, which gives the model permission to say it does not know.

Code

Two ways to rerank in Python: an open-weight cross-encoder with sentence-transformers, and Cohere's hosted Rerank API.

from sentence_transformers import CrossEncoder
import cohere

query = "Can unused vacation days be paid out when I leave?"
candidates = [
    "Unused vacation days carry over up to a maximum of 10 days.",
    "On termination, accrued but unused vacation is paid out in the final paycheck.",
    "Sick leave does not carry over and is not paid out.",
    "Vacation requests must be approved by your manager two weeks in advance.",
]

# Option 1: self-hosted cross-encoder
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3", max_length=512)
ranked = reranker.rank(query, candidates, top_k=2, return_documents=True)
for r in ranked:
    print(f"{r['score']:.3f}  {r['text']}")

# Option 2: hosted Cohere Rerank (reads CO_API_KEY from the environment)
co = cohere.ClientV2()
resp = co.rerank(model="rerank-v3.5", query=query, documents=candidates, top_n=2)
for result in resp.results:
    print(f"{result.relevance_score:.3f}  {candidates[result.index]}")

Note that the obvious keyword match ("Unused vacation days carry over") is about carry-over, not payout. A good reranker should put the termination sentence first; a pure embedding search often does not.

Trade-offs and pitfalls

  • Latency scales with candidates times length. Reranking 100 long chunks is much slower than 30 short ones. Tune candidate count on your eval set; quality usually plateaus well before 100.
  • Truncation hides the answer. Cross-encoders have a max input length (often 512 tokens for older models, longer for newer ones). If the relevant sentence is at the end of a long chunk, it may be cut off. Keep chunks within the reranker's window or let the API split long documents.
  • Batch and run on GPU. Pass all pairs in one batch; per-pair calls waste most of the time on overhead.
  • Scores are not probabilities. Calibrate thresholds on your data rather than assuming 0.5 means anything.
  • Domain shift. Rerankers trained on web search data can misjudge specialized text. Some APIs and open models can be fine-tuned on your labeled pairs.
  • LLM rerankers drift with prompts. If you use an LLM to rerank, pin the model and prompt and evaluate it like any other component.
  • Do not skip first-stage recall. A reranker can only reorder what it receives. If the right chunk is not in the candidate set, fix retrieval first.

Checklist

  • Add a reranker between hybrid retrieval and prompt assembly.
  • Retrieve 20 to 100 candidates, rerank, keep 3 to 8, and tune each number on your eval set.
  • Keep chunk length within the reranker's input limit.
  • Batch rerank calls and measure p95 latency under load.
  • Add a calibrated score threshold so irrelevant chunks are dropped.
  • Compare at least one hosted and one open-weight reranker on your own queries.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.