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. You will build a two-stage pipeline: a bi-encoder retrieves a candidate pool, and a cross-encoder reorders it.
Why two stages
A bi-encoder embeds each passage once, ahead of time. At query time it embeds only the query and compares vectors. That makes search over millions of passages fast, but the model never sees the query and the passage together.
A cross-encoder reads the query and one passage as a single input and outputs a relevance score. It is usually more accurate. It also needs one full model pass for every (query, passage) pair, and it cannot precompute anything per passage. Running it over a whole corpus is too slow.
The two-stage pipeline combines the strengths of both:
- Retrieve. The bi-encoder returns the top
k_retrievecandidates, for example 50 or 100. The goal is recall: the right passage must be somewhere in this pool. - Rerank. The cross-encoder scores only those candidates and keeps the top
k_final. The goal is precision: the best passage should be near the top.
Scoring pairs with a cross-encoder
Start with the reranker alone. Install the library with pip install sentence-transformers. The CrossEncoder class loads a model that 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}")Three details matter here:
predictreturns scores in the same order as the input pairs. Sorting is your job, and you must keep each score attached to its passage, which is why the code useszip.max_length=512caps the combined token length of query and passage. Longer inputs are truncated. A later chapter covers the consequences.- The score is useful for comparing passages for one query. It is not a probability. Chapter material on reading scores covers this in detail.
The full pipeline
Now connect both stages. The bi-encoder encodes the corpus once. At query time you embed the query, take the top k_retrieve hits, score those pairs, and keep the best k_final.
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}")How the code works
The corpus has four passages, so top_k=50 simply returns all four. In a real system the corpus is large and the pool is a small slice of it.
util.semantic_search returns, for each query, a list of dictionaries with corpus_id and score. The score there is the bi-encoder similarity. The code ignores it and uses the cross-encoder score instead. Mixing the two scales is possible, but they are not comparable, so the simplest rule is to rank by the reranker score alone.
The order list holds indices into hits, sorted by cross-encoder score. Slicing order[:k_final] keeps the top results. Converting with float(...) turns a NumPy value into a plain Python number, which is easier to serialize.
normalize_embeddings=True makes vectors unit length, so cosine similarity and dot product agree. Use the same setting for the corpus and the query.
Choosing the two sizes
k_retrieve and k_final do different jobs:
| Parameter | Controls | Too small | Too large |
|---|---|---|---|
| `k_retrieve` | How many candidates the reranker sees | The relevant passage may never enter the pool, and no reranker can recover it | Latency and cost grow linearly |
| `k_final` | How many passages you return or pass downstream | Useful context is dropped | Noise reaches the user or the language model |
A common starting point is 50 to 100 candidates and 3 to 10 final results. A later chapter covers how to tune candidate depth with measurements.
Edge cases and design points
The reranker cannot add documents. It only reorders the pool. If the first stage misses the relevant passage, the final result misses it too. When quality is poor, check recall of the candidate pool before blaming the reranker.
Fewer hits than requested. If the corpus has fewer passages than k_retrieve, you get fewer hits. The code above handles this, because it builds pairs from whatever hits contains. Guard against an empty result before calling predict if your corpus can be empty.
Embedding the corpus once. Compute corpus_emb at indexing time and store it, usually in a vector index. Only the query is embedded on each request. The cross-encoder has no such cache, which is why it runs on a small pool.
Model pairing. The two models do not need to come from the same family. They are trained separately and communicate only through the candidate list. You can replace the first stage with lexical search or a hybrid without touching the reranker.
Batching. batch_size=32 groups pairs into batches for the model. Larger batches use hardware better but need more memory. The default is fine to start with.
Ties and ordering. sorted is stable, so equal scores keep their retrieval order. This is a reasonable tiebreaker because the first stage already ranked those candidates.
Common mistakes
- Reranking the whole corpus. This works on four passages and fails at scale. Always put a cheap retriever first.
- Passing passages without the query. The cross-encoder needs
(query, passage)pairs. A list of passages alone is an error. - Using a different query string for each stage without meaning to. If you rewrite the query for retrieval, decide whether the reranker should see the original or the rewritten one. Be consistent and test both.
- Sorting ascending.
sorteddefaults to ascending order. Usereverse=Trueso the highest score comes first. - Treating scores as thresholds across queries. A score of 3.0 for one query does not mean the same relevance as 3.0 for another.
Exercises
Exercise
A teammate sets k_retrieve=5 and says the cross-encoder keeps returning the wrong passage. The correct passage is ranked 12th by the bi-encoder. What is the cause, and what is the fix?
Show answer
The correct passage never enters the candidate pool, so the cross-encoder cannot see it. A reranker only reorders the candidates it receives. Raise k_retrieve (for example to 50 or 100) so the passage is in the pool, and check first-stage recall@k to confirm.
Exercise
Why can the corpus embeddings be computed once but the cross-encoder scores cannot?
Show answer
The bi-encoder embeds each passage independently of any query, so the vectors can be stored and reused. The cross-encoder reads the query and passage together, so its score depends on the specific pair and must be computed again for every new query.