Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 12 steps

Build and Measure a RAG System
  1. 1
    What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  2. 2
    Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  3. 3
    Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  4. 4
    Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  5. 5
    Vector Databases Hands-On: The Same Search in Chroma and pgvector
  6. 6
    Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  7. 7
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  8. 8
    RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  9. 9
    Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  10. 10
    Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  11. 11
    Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  12. 12
    RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Learning path: Build and Measure a RAG System · Step 10 of 12

Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't

A cross-encoder reads the question and each candidate together and re-orders them. On one question it lifts the right article from fourth to first. On 12 golden questions, first places go from 10 to 9. Here's why, what changes with a weaker first pass, and how many candidates are worth the milliseconds.

Chaand Sheikh

·27 November 2026Retrieval and RAG

What you will learn

  • Explain the two jobs: a fast first pass decides what is seen, a slow cross-encoder decides the order
  • Rerank hybrid-search candidates with cross-encoder/ms-marco-MiniLM-L-6-v2
  • Measure a reranker on golden questions instead of trusting that it always helps
  • Pick how many candidates to rerank from quality and milliseconds

Before you start

  • Hybrid Search: BM25 Plus Dense Embeddings
  • The RAG Pipeline Explained

Reranking is one small step at the very end of retrieval. A fast search finds a few likely articles; a slower model then reads each one beside the question and puts them in a better order. That slower model is a cross-encoder.

You'll often hear that reranking always helps. So we'll measure it on our own questions, and the answer turns out to be more interesting than that.

A recruiter and an interviewer

A recruiter skims a big pile of CVs fast, looking for the right words, and five land on the shortlist. An interviewer then sits with those five, one at a time, and really reads them, so the order changes. But a great CV left in the pile never gets an interview: the interviewer only sees what the recruiter passed along.

Two jobs. The recruiter (first pass) decides who gets seen. The interviewer (second pass) decides the order.

Found, but in fourth place

The 12 synthetic help articles from hybrid search. A customer types I typed the wrong expiry date, and hybrid search returns five articles:

First  1  A02  Error E-4027: session expired
First  2  A01  Checkout stops with a bank message
First  3  A07  Reset your password
First  4  A05  Why a payment is declined
First  5  A08  Cancel your subscription

The top hit is wrong. The right one, A05, even contains the words "expiry date" (a wrong card number or expiry date), but it sits in fourth place. It's been found, just in the wrong place, which is exactly what a second step can fix.

Apart, or read together

Dense search versus a cross-encoder Dense search: apart question article encoder encoder compare article vectors stored before any question: fast Cross-encoder: together question + article cross-encoder reads both score nothing to store: a new pair per candidate, every question: slow So: fast pass wide (finds), slow pass narrow (orders).
Why a cross-encoder runs on a few candidates, never on the whole collection.

In dense search, the question and the article each become a vector separately; they never meet, and we compare the two vectors at the end. That's why article vectors can be stored ahead of time. A cross-encoder takes the question and one article together as a single pair, and gives back one score. Nothing can be prepared, so it only gets the few candidates the first pass found.

The second pass in code

The first pass is the hybrid search from before, BM25 and embeddings fused with RRF, cut to the top n:

def first_pass(question, n=5):
    # fast: search all twelve, keep only the top n
    fused = rrf(bm25_ranking(question),
                dense_ranking(question))
    return [a for a, _ in fused[:n]]

And the whole second pass, rerank.py:

from sentence_transformers import CrossEncoder

from articles import TEXT

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


def second_pass(question, candidates):
    # slow: the model reads each candidate
    pairs = [(question, TEXT[a]) for a in candidates]
    scores = reader.predict(pairs)
    ranked = sorted(zip(candidates, scores),
                    key=lambda p: -p[1])
    return [(a, float(s)) for a, s in ranked]

The model is small, runs on a CPU and needs no API key. pairs joins the question with each candidate's text, so five candidates means five pairs. predict is the slow line: the model reads each pair and a score comes out. sorted puts the highest first. Notice it only re-orders: nothing new can join the list.

Second 1  A05  Why a payment is declined             -5.38
Second 2  A02  Error E-4027: session expired        -10.14
Second 3  A01  Checkout stops with a bank message   -11.29
Second 4  A08  Cancel your subscription             -11.38
Second 5  A07  Reset your password                  -11.40

The declined-payment article rides from fourth to first. The scores are negative, and that's fine: they're raw scores, only good for sorting against each other.

Twelve golden questions

One question proves nothing. The fair test is a golden set: 12 questions where the right article is already marked (golden.py). For each one, the project records where the right article landed before and after reranking:

python run.py compare
question                                              first  then
error E-4072                                              1     1  same
my card was refused                                       1     1  same
reset my password                                         1     1  same
why did the bank reject my payment                        1     1  same
what does E-4027 mean                                     1     1  same
are your servers down                                     1     1  same
how long until my refund arrives                          1     1  same
my role does not let me do this                           1     1  same
I typed the wrong expiry date                             4     1  better
get a copy of what I paid                                 3     2  better
add a colleague to our account                            1     3  WORSE
can I pay with something else after the bank says no      1     2  WORSE
First place before: 10  after: 9

Eight questions don't change. Two get better and two get worse. Count first places: 10 before, 9 after. On these questions the second step did not win.

When it helps, and when it doesn't

Look at the scores behind one of the losses, add a colleague to our account. Three articles score about -10.7, -10.7 and -11.2, and the right one is the lowest. All low, all close: the model isn't seeing a good match anywhere. Compare reset my password: the right article scores about 7.9 and the next about -9.8. There, the model is sure.

Now give it a weaker first pass, BM25 alone. First places go from 7 to 9 after reranking. So a reranker helps more when the first pass is weak. But get a copy of what I paid never made BM25's top 5, and the reranker can't rescue what it never saw.

Setup (12 questions)First places
BM25 top 57
BM25 top 5, reranked9
Hybrid top 510
Hybrid top 5, reranked9

A reranker is one more model with its own opinion. This one was trained on web search, not help-centre articles, and that may be part of the story, though it wasn't tested here. Check its opinion on your own questions.

How many candidates?

python run.py counts
n   found  first-place  first-pass  second-pass
1     10       10          41 ms       55 ms
3     11        8          37 ms      135 ms
5     12        9          42 ms      136 ms
8     12        9          33 ms      166 ms
12    12        9          50 ms      251 ms
  • n = 1: nothing to re-order. Found for 10 questions, 10 in first place.
  • n = 3: found goes up to 11, but first places fall to 8. The expiry question misses the list, so the second pass never sees it.
  • n = 5: all 12 are found, 9 in first place, at about 136 ms per question for the second pass.
  • n = 8 and 12: quality doesn't move. Only the time grows, to 166 and 251 ms.

The milliseconds were measured on one CPU and move around between runs, so trust the trend, not the digits. On this data, five is where everything is found; past it you pay and gain nothing.

Common mistakes

  • Adding a reranker because "it always helps". Measure first places (or MRR and nDCG) with and without it.
  • Expecting it to fix recall. It only re-orders; a missed article stays missed.
  • Reranking the whole collection. Every candidate is a model call per question.
  • Comparing cross-encoder scores with cosine scores, or treating negative scores as "bad". They are raw sort keys.
  • Reading a gap of one on 12 questions as a result. That's a single question.

Quick recap

  • A fast first pass decides what gets seen; a slower cross-encoder decides the order.
  • It can only re-order, so if the first pass misses an article, it's gone.
  • Measure on golden questions, for quality and for milliseconds. A reranker earns its place on your data, or it stays out.

Try it yourself

Add two questions of your own to golden.py, worded unlike any article, and run python run.py compare again. Does reranking help those?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Build and Measure a RAG System · step 10 of 12

Previous
Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
Next post
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

On this page

  • A recruiter and an interviewer
  • Found, but in fourth place
  • Apart, or read together
  • The second pass in code
  • Twelve golden questions
  • When it helps, and when it doesn't
  • How many candidates?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.