Sub topic 1
Where reranking fits: first-stage retrieval
Prerequisites
This chapter assumes you have:
- Basic Python: lists, functions, and installing packages with pip.
- Familiarity with text embeddings and vector similarity search (cosine similarity, nearest neighbours).
- A general idea of what a transformer model is.
- Basic information retrieval vocabulary: query, document, passage, relevance.
You do not need to know how cross-encoders work yet. This chapter explains the stage that comes before them and why that stage exists. Later chapters cover the reranker itself.
The problem: finding a few good passages in a large collection
A retrieval system takes a query and returns the passages most likely to answer it. In a retrieval-augmented generation (RAG) system, those passages go into a language model prompt. In a search box, they go to a user. In both cases, the order matters. People read the top results first, and a prompt has limited room, so only the first few passages are used.
Two requirements pull against each other:
- The system must look at a large collection, often millions of passages.
- The system must rank the best passages first, which needs a careful judgment of relevance.
No single model does both cheaply. Careful judgment costs one model run per query-passage pair. Across a million passages, that means a million model runs for every query, which is far too slow. The standard answer is to split the work into stages.
What first-stage retrieval does
First-stage retrieval is the fast, broad step. It reduces the whole collection to a small candidate pool, usually tens to a few hundred passages. It is built for speed and recall: it should make sure the relevant passages are somewhere in the pool, even if they are not at the top.
Two families of first-stage retrievers are common.
Lexical retrieval
Lexical retrieval matches the words in the query against the words in the passages. The most common method is BM25, which scores a passage higher when it contains query terms that are rare across the collection and appear often in that passage.
- Strengths: fast, needs no model training, handles exact terms such as error codes, product names, and identifiers.
- Weaknesses: it cannot match different words with the same meaning. A query for "change a password" can miss a passage titled "Reset your credentials".
Dense retrieval
Dense retrieval uses a bi-encoder, a neural model that turns text into a fixed-length vector called an embedding. The query and each passage are encoded separately. Relevance is the similarity (usually cosine or dot product) between the two vectors.
The key property is that passage vectors do not depend on the query. You encode every passage once, ahead of time, and store the vectors in an index. At query time you encode only the query and run a nearest-neighbour search. Approximate nearest-neighbour indexes such as HNSW make this fast even for very large collections.
- Strengths: matches by meaning, so paraphrases and synonyms work.
- Weaknesses: compresses a whole passage into one vector, which loses detail. It can also miss rare exact terms.
Why the first stage is fast: precomputation
The speed of a bi-encoder comes from where the work happens.
| Work | When it happens | Cost per query |
|---|---|---|
| Encode every passage | Once, at indexing time | None |
| Encode the query | At query time | One short model run |
| Compare query to passages | At query time | One index lookup |
Because the expensive part moves to indexing time, query cost stays low no matter how large the collection grows. This is also the limit of the approach, and later chapters explain it. The passage vector was computed without knowing the query, so it cannot reflect how a particular query relates to particular words in the passage.
The two-stage idea
Reranking adds a second stage that works only on the small candidate pool.
The division of labour is:
- Stage one is cheap per passage and scans everything. Its job is recall: do not lose the relevant passages.
- Stage two is expensive per passage and looks only at the pool. Its job is precision at the top: put the best passages first.
A reranker that reads a query and a passage together can judge relevance more accurately than comparing two precomputed vectors. Because it only sees, for example, 50 passages and not 5 million, the extra cost is affordable. The next chapters explain why and how.
A small first-stage example
The following code builds a dense first stage over a tiny corpus and returns a candidate pool. It uses the sentence-transformers library. Install it first with pip install sentence-transformers.
from sentence_transformers import SentenceTransformer, util
bi_encoder = SentenceTransformer("all-MiniLM-L6-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.",
]
# Done once, at indexing time.
corpus_emb = bi_encoder.encode(
corpus, convert_to_tensor=True, normalize_embeddings=True
)
def first_stage(query, k=3):
# Done per query.
q_emb = bi_encoder.encode(
query, convert_to_tensor=True, normalize_embeddings=True
)
hits = util.semantic_search(q_emb, corpus_emb, top_k=k)[0]
return [(corpus[h["corpus_id"]], h["score"]) for h in hits]
for passage, score in first_stage("how to change an api key"):
print(f"{score:.2f} {passage}")Notice what the code does and does not do:
corpus_embis computed once. Adding the query later costs one extra encoding.util.semantic_searchreturns thetop_knearest passages with their cosine similarity.- The
kargument is the candidate pool size. Here it is 3 because the corpus has four passages. In a real system you would use a larger value.
The order of the output is the first-stage ranking. The scores are similarities between two independently computed vectors. Treat the ranking as a good first guess, not as a final answer.
What makes a good candidate pool
The reranker can only reorder what it receives. If a relevant passage is not in the pool, no reranker can bring it back. This gives the first stage a clear goal: maximize recall at k, the fraction of relevant passages that appear in the top k results.
An example makes the ceiling concrete. Suppose a query has one relevant passage.
| Pool size k | Relevant passage in pool? | Best possible result after reranking |
|---|---|---|
| 5 | No (it was at rank 8) | Reranking cannot help |
| 10 | Yes | Reranker can move it to rank 1 |
Two consequences follow:
- First-stage recall at the pool size sets an upper bound on the final quality.
- Precision at the very top matters less in the first stage, because the second stage fixes the order.
This is why first-stage tuning and reranker tuning have different targets. You tune the first stage for recall at the depth you plan to rerank. You tune the reranker for ordering quality. Later chapters measure both with recall@k, MRR, and nDCG.
Common first-stage problems
Some failures begin before the reranker runs. Check these first when results look wrong.
- Vocabulary mismatch with lexical search. The query and the answer use different words, so BM25 never retrieves the answer.
- Missed exact terms with dense search. A query containing a part number or error code returns passages that are about the right topic but do not contain the code.
- Poor chunking. If passages are cut so that the answer is split across two chunks, neither chunk looks relevant. Chunk size affects both stages.
- Pool too small. A relevant passage sits at rank 60 but you only pass 50 candidates on.
- Embedding model mismatch. A general-purpose embedding model may perform poorly on specialized text such as legal or medical documents.
Using more than one first stage
Lexical and dense retrieval fail in different ways, so many systems run both and merge their lists. This is hybrid retrieval. A common merging method is reciprocal rank fusion, which uses only ranks and so avoids comparing BM25 scores to cosine similarities. A later chapter covers it in detail. For now, remember that "first stage" can mean one retriever or a combination, and the reranker treats the merged pool the same way.
Summary of the roles
| Row | First stage | Reranker |
|---|---|---|
| Input | Query and whole collection | Query and candidate pool |
| Work per passage | Very small, mostly precomputed | Full model run per query-passage pair |
| Main goal | High recall | Good ordering at the top |
| Typical output size | 50 to a few hundred | The few passages you will use |
| Failure it cannot fix | Poor ordering inside the pool | A relevant passage missing from the pool |
Exercise
A reranker is added to a search system, but the relevant passage for many queries still does not appear in the final results. First-stage retrieval returns 20 candidates, and logs show the relevant passage is often at rank 35 to 40. What is the most likely cause, and what is the first change you would try?
Show answer
The candidate pool is too small. The relevant passage never reaches the reranker, so the reranker cannot promote it. First increase the pool size (for example to 50 or 100) and measure recall@k at the new depth. If recall stays low, look at the first stage itself: chunking, the embedding model, or adding a lexical retriever.
Exercise
Why can a bi-encoder search a million passages quickly, while running a model on every query-passage pair at query time cannot?
Show answer
A bi-encoder encodes each passage once at indexing time, independent of any query. At query time it encodes only the query and does a nearest-neighbour lookup over stored vectors. Running a model on every query-passage pair needs one model run per passage for every query, which scales with collection size and is too slow.