Sub topic 4
Building a Retrieve-Then-Rerank Pipeline
This chapter assumes you can write basic Python, know what text embeddings and vector similarity search are, and have a general idea of what a transformer model is. It also assumes you know the retrieval terms query, document, and relevance.
The two-stage idea
A bi-encoder turns each passage into a vector once, ahead of time. A query then needs one encoding and a fast nearest-neighbor lookup. This is cheap, so it works over millions of passages. It is also approximate, because the query and passage never see each other during encoding.
A cross-encoder reads the query and one passage together in a single model pass. It sees how the words relate and usually ranks more accurately. It cannot be precomputed, because every query-passage pair needs its own forward pass. Running it over a whole corpus is too slow.
The standard answer is two stages. The first stage retrieves a pool of candidates cheaply. The second stage rescoring only that pool, then keeps the top few.
Scoring pairs with a cross-encoder
Start with the second stage alone. CrossEncoder.predict takes a list of (query, passage) pairs and returns one score per pair.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
query = "How do I rotate an API key?"
passages = [
"API keys can be rotated from the Security page by creating a new key and deleting the old one.",
"Our API supports JSON and XML response formats.",
"To change your password, open Account Settings and choose Reset password.",
]
scores = model.predict([(query, p) for p in passages])
ranked = sorted(zip(passages, scores), key=lambda x: x[1], reverse=True)
for passage, score in ranked:
print(f"{score:.2f} {passage}")The passage about rotating keys should come first. The scores only order passages for one query. Chapter-level detail on reading them comes later.
Connecting both stages
The next example joins the stages in one search function. Both models load once, and the corpus is embedded once.
from sentence_transformers import SentenceTransformer, CrossEncoder, util
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
corpus = [
"Rotate API keys from the Security page.",
"Reset your password in Account Settings.",
"Our API returns JSON by default.",
"Billing invoices are emailed on the first of each month.",
]
corpus_emb = bi_encoder.encode(corpus, convert_to_tensor=True, normalize_embeddings=True)
def search(query, k_retrieve=50, k_final=3):
q_emb = bi_encoder.encode(query, convert_to_tensor=True, normalize_embeddings=True)
hits = util.semantic_search(q_emb, corpus_emb, top_k=k_retrieve)[0]
pairs = [(query, corpus[h["corpus_id"]]) for h in hits]
scores = cross_encoder.predict(pairs, batch_size=32)
order = sorted(range(len(hits)), key=lambda i: scores[i], reverse=True)
return [(corpus[hits[i]["corpus_id"]], float(scores[i])) for i in order[:k_final]]
for passage, score in search("how to change an api key"):
print(f"{score:.2f} {passage}")Here is what each step does:
semantic_searchreturns up tok_retrievehits, each a dictionary withcorpus_idand a similarityscore.- The code builds one
(query, passage)pair per hit. predictscores all pairs in batches of 32.- The code sorts hit positions by cross-encoder score and keeps the first
k_final.
The corpus here has four passages, so k_retrieve=50 returns all of them. With a real corpus, the pool would be a small slice of it.
Two parameters, two jobs
k_retrieve controls recall. A relevant passage that the first stage misses can never be recovered by the reranker. k_final controls what the downstream consumer sees, such as a user or a language model prompt. A larger k_retrieve gives the reranker more chances to find the right passage, and it costs more time per query.
Common mistakes
- Reranking the full corpus. Cost grows with every pair, so limit it to the candidate pool.
- Passing passages in the wrong shape.
predictexpects pairs, not a query and a separate list. - Sorting scores without keeping the link to passages. Always sort indexes or zipped pairs.
- Mixing similarity scores from the bi-encoder with cross-encoder scores. They are on different scales, so use the cross-encoder score for the final order.
Exercise
In the search function, a relevant passage is ranked 70th by the bi-encoder, and k_retrieve is 50. Can the cross-encoder place it first? What two changes could help?
Show answer
No. The passage never enters the candidate pool, so the cross-encoder never scores it. You can raise k_retrieve above 70, which costs more cross-encoder passes per query, or improve the first stage, for example with a better embedding model or by adding lexical retrieval.