Two-Stage Retrieval with a Reranker

easy
Unit 3 · RAG I0/3 to milestone

Production RAG retrieves cheaply first (BM25 or vectors), then reranks the top few candidates with an expensive cross-encoder that reads the query and document together.

Implement rerank(query, docs, first_scores, cross_score, top_n, alpha=1.0):

  • Take the top_n docs by first_scores (ties: lower index first).
  • Score each of them with cross_score(query, doc). Only call it for those top_n docs, because it's expensive.
  • Min-max normalise both the first-stage scores and the cross scores within the top_n (if all values are equal, they normalise to 0).
  • The final score is alpha * cross_norm + (1 - alpha) * first_norm. Sort the top_n by final score, highest first, breaking ties by first-stage rank.
  • Append the remaining docs in first-stage order. Return the list of docs.
#rag#reranking#retrieval2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Two-Stage Retrieval with a Reranker · TechGradify