Velamuvi AIAcademy

Lesson 10 of 16 · Retrieval

Reranking

Improve RAG with reranking: why embeddings miss details, how cross-encoders read question and passage together, two-stage retrieval and the cost trade-offs.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain the difference between an embedding model (bi-encoder) and a reranker (cross-encoder)
  • Set up two-stage retrieval: retrieve many candidates, rerank to a few
  • Use a reranking model in Python
  • Weigh the extra quality against the extra time and cost

Why the first search isn't enough

Embedding search is fast because the question and every chunk are embedded separately: chunk vectors are computed once, ahead of time. The price is that the model never sees the question and the chunk together. It compares two summaries, and fine details get lost.

Two-stage retrieval

  1. Retrieve a generous shortlist quickly: 20 to 100 candidates from vector or hybrid search.
  2. Rerank the shortlist with a cross-encoder and keep the top 3 to 5 for the prompt.

The program below shows the idea. Stage 2 uses a simple stand-in scorer that, like a real reranker, looks at the question and each candidate together: shared words (ignoring endings like “carry” versus “carried”) and whether a “how many” question meets a sentence with a number:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

SENTENCES = [(title, s.rstrip(".") + ".") for title, text in HANDBOOK.items() for s in text.split(". ")]

# ---- Stage 1: fast embedding search returns a shortlist ----
def first_stage(question, k=4):
    q = embed(question)
    return sorted(SENTENCES, key=lambda ts: cosine(q, embed(ts[0] + ". " + ts[1])), reverse=True)[:k]

# ---- Stage 2: a reranker reads the question and each candidate TOGETHER ----
# (A stand-in for a real cross-encoder model, so you can see the idea.)
STOP = {"how", "many", "much", "can", "i", "do", "the", "a", "to", "my", "of", "is", "what", "when"}

def rerank_score(question, sentence):
    q_words = [w for w in words(question) if w not in STOP]
    s_stems = {w[:4] for w in words(sentence)}
    overlap = sum(w[:4] in s_stems for w in q_words)          # shared words, ignoring endings
    asks_number = question.lower().startswith(("how many", "how much", "how long"))
    has_number = any(ch.isdigit() for ch in sentence)
    return overlap + (0.5 if asks_number and has_number else 0.0)

question = "How many unused days can I carry over?"
shortlist = first_stage(question)
print("Stage 1 (embedding similarity):")
for title, sentence in shortlist:
    print("  ", sentence)

reranked = sorted(shortlist, key=lambda ts: rerank_score(question, ts[1]), reverse=True)
print("Stage 2 (reranked):")
for title, sentence in reranked:
    print(f"   {rerank_score(question, sentence):>3}  {sentence}")

The embedding search put the general “25 days” sentence first, because it's very similar in topic. The sentence that actually answers “how many days can I carry over” was third. After reranking it's first, and the irrelevant sentences sink to the bottom, where a cut-off removes them.

A real reranker

On your own computer, the sentence-transformers library runs open reranking models (pip install sentence-transformers; the model downloads the first time):

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

question = "How many unused days can I carry over?"
candidates = [
    "Full-time employees get 25 days of paid annual leave per year.",
    "Book holiday in the HR portal at least two weeks ahead.",
    "Up to 5 unused days can be carried over to next year.",
]
scores = reranker.predict([(question, c) for c in candidates])
ranked = sorted(zip(scores, candidates), reverse=True)
for score, text in ranked:
    print(f"{score:6.2f}  {text}")

Several AI providers also offer reranking through an API: send the query and a list of documents, get back relevance scores. And a general LLM can rerank too, by asking it to score or order passages, which is flexible but slower and more expensive per query.

Common mistakes

Practice exercise

Finish the second stage of retrieval: keep only the top candidates according to the reranker.

Your solutionPython
# Shortlist from the vector database, with the reranker's score for each
shortlist = [
    {"text": "Employees get 25 days of paid annual leave.", "rerank": 0.41},
    {"text": "Book holiday two weeks ahead.",               "rerank": 0.08},
    {"text": "Up to 5 unused days can be carried over.",    "rerank": 0.93},
    {"text": "Sick pay covers up to 10 days per year.",     "rerank": 0.02},
]
keep = 2

# Keep the best `keep` candidates by reranker score and print their text, best first.
Knowledge check

Why is a cross-encoder reranker only applied to a shortlist, not the whole collection?

Summary

  • Embedding models are bi-encoders: fast, but they never see the question and chunk together.
  • Rerankers (cross-encoders) read both together and judge relevance much more accurately.
  • Use two stages: retrieve 20–100 candidates fast, rerank, keep the top 3–5.
  • Reranking adds some time and cost, and can only reorder what retrieval found.

Next: rewriting questions so retrieval understands them better.

Finished reading? Tick it off to track your progress.