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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletwo_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, ...
  • Sample 2: cross tiestwo_stage_rerank([10, 11, 12, 13, 14], [5, 4, 3, 2, 1], {10: 0.5, 11: 0.7, 12: 0.7, 13: 0.1, 14: 0.9}, 4, 3...
  • Test 3: all filteredtwo_stage_rerank(['x', 'y'], [1, 2], {'x': 0.1, 'y': 0.2}, 2, 2, 0.5)
  • Test 4: first tiestwo_stage_rerank(['p', 'q', 'r'], [1.0, 1.0, 1.0], {'p': 0.3, 'q': 0.4, 'r': 0.9}, 2, 3, 0.0)