Rerank retrieved chunks in two stages with a score threshold
Why it matters Production RAG systems retrieve dozens of chunks with vectors or BM25 and rerank a few with a cross-encoder before prompting.
Retrieval pipelines first pull many candidates cheaply, then rescore only the best of them with an expensive cross-encoder.
Write two_stage_rerank(cands, first_scores, cross_scores, n, k, threshold). cands are ids with parallel first-stage scores; cross_scores maps an id to its cross-encoder score. Steps:
1. Keep the top n candidates by first-stage score (ties by earlier position).
2. Sort them by cross score descending, ties by their first-stage rank.
3. Drop those with cross score below threshold.
4. Return the first k ids.
def two_stage_rerank(cands, first_scores, cross_scores, n, k, threshold)Example
two_stage_rerank(["a", "b", "c", "d"], [0.9, 0.8, 0.7, 0.1], {"a": 0.2, "b": 0.9, "c": 0.5, "d": 0.99}, 3, 2, 0.3) gives ['b', 'c'].
Understand the idea
A cross-encoder reads the query and a chunk together and judges relevance much better than vector similarity, but it is slow. So RAG pipelines work like a hiring funnel: a cheap screen (vector search or BM25) shortlists candidates, and the expensive interview (the cross-encoder) is held only for the shortlist.
Example: four chunks with first-stage scores 0.9, 0.8, 0.7 and 0.1. With n = 3, chunk d is never sent to the reranker, even though it would have scored 0.99. Among a, b, c the cross scores are 0.2, 0.9, 0.5. The threshold 0.3 removes a, leaving [b, c].
Rule: shortlist = top n by first score; ranked = sort shortlist by cross score; keep score >= threshold; return first k.
Choosing n trades recall against cost; values from 20 to 100 are common, with k of 3 to 10 chunks reaching the prompt.