Skip to content

Reranking

Chapter 8 1 code blocks 1708 words

Reranking vs cosine similarity: which is better?

Say this

They aren't competitors; they're two stages of one funnel. Cosine similarity on embeddings is a bi-encoder: every document was turned into a vector in advance, so searching millions of chunks takes milliseconds, but each document was squeezed into one vector before it ever saw the question, so it's coarse. A reranker is a cross-encoder: it reads the question and one chunk together, so every question word can attend to every chunk word, and it scores relevance much more accurately. But it costs one model pass per pair, so it can't scan the whole collection. So you use cosine to get a wide candidate list fast, for recall, and the reranker to order the few best precisely, for precision. Per pair the reranker is more accurate; for searching the collection, cosine is the only thing fast enough. In my project today I fuse dense and keyword results with RRF and keep 6; adding a cross-encoder over about 30 candidates is my next step, and I'd keep it only if Recall@5 improves.

  1. Whole collection
    all chunks
  2. 1
    Cosine / vector search
    fast and coarse → recall: don't miss it
  3. Top 30–50 candidates
    plus keyword search, fused by RRF
  4. 2
    Cross-encoder reranker
    slow and precise → precision: put them in the right order
  5. Top 3–5
    threshold → prompt → LLM
Bi-encoder (cosine)Cross-encoder (reranker)
Inputquestion and chunk embedded separatelyquestion + chunk read together
Precompute?yes: chunk vectors stored at indexingno: every pair computed at question time
Cost per question1 embedding + a vector search (ms)1 model pass per candidate pair
Scales tomillions of chunkstens of candidates
Accuracygood for topic, weak on detailsmuch better on details, negation, who-did-what
Scorescosine, range differs per modela relevance score, more comparable across questions
Examplesqwen3-embedding, bge-m3, text-embedding-3bge-reranker-v2-m3, Qwen3-Reranker, Cohere Rerank

Why the cross-encoder is more accurate (the real reason)

Bi-encoder
vector qquestion → modelvector cchunk → modelcos(q, c)
the chunk was compressed BEFORE it saw the question
Cross-encoder
[question SEP chunk]modelattention across bothscore
every question word can look at every chunk word

Compressing a whole chunk into one vector is an information bottleneck: it keeps the topic and loses the details. The cross-encoder never compresses; it compares the actual words.

An example where cosine fails and a reranker doesn't

Question: "Zaxarova kimni tanqid qildi?" (Whom did Zakharova criticize?)

  • Chunk A: "Zakharova criticized the EU's new sanctions…"
  • Chunk B: "EU officials criticized Zakharova's statement…"

Same words, same topic, so the cosine scores are nearly equal and B may even rank first. A cross-encoder reads who did what to whom and puts A clearly on top. The same holds for negation ("not allowed" vs "allowed"), numbers and conditions ("loans over 100 million").

Why not rerank everything?

Rough math: 1,000,000 chunks × about 10 ms per pair ≈ 10,000 s, almost 3 hours for one question. 30 candidates × 10 ms ≈ 0.3 s. That's why the order is always cosine first, reranker second.

RRF is not a reranker

RRF (what I use) merges two ranked lists by position, 160+rank, so a chunk that both dense and keyword search rank high wins. It never reads the text, so it can't fix a wrong order inside a list. A cross-encoder reads the text. They work together: RRF fuses → reranker reorders.

160+rank
rdensethe chunk's position in the dense list (1 = top)
rkeywordits position in the keyword list
60the constant k: it keeps rank 1 from dominating everything

How many candidates and how many to keep

  • In: 20–50. Too few and the right chunk may not be among them; the reranker can't fix what retrieval never returned.
  • Out: 3–5 for the prompt. Fewer, better chunks beat many average ones.
  • Threshold: put it on the reranker score; it's more reliable than raw cosine.

Example project

Today: dense top 12 + keyword search on rare words → RRF → top 6 → threshold 0.50 / 0.35. No cross-encoder yet. How I'd add it, about 10 lines:

python6 lines
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")      # loaded once at startup

candidates = retrieve(question, k=30)                   # dense + keyword + RRF
scores = reranker.predict([(question, c.text) for c in candidates])
best = [c for s, c in sorted(zip(scores, candidates), key=lambda x: -x[0])][:5]

Then measure on the same labelled questions: Recall@5 and MRR with and without it, plus the added latency. Keep it only if the numbers improve.

Reranking deep dive: the follow-up questions

  1. What is the reranker's job, in one line? Take the candidates retrieval found and put them in the right order by real relevance to this question, so the best 3–5 go to the LLM and weak ones are dropped.
  2. What exactly goes in and comes out? In: one pair, [question] [SEP] [chunk text]. Out: one number, a logit. Sigmoid turns it into 0–1 ("how relevant"). Run it for every candidate, sort by the number.
  3. How is a cross-encoder trained? On (question, passage, label) data such as MS MARCO. Pointwise: binary cross-entropy, relevant = 1, not = 0. Listwise: one positive plus several hard negatives in a group, softmax cross-entropy so the positive gets the highest score. Hard negatives (passages that look relevant but aren't, usually taken from retrieval's own top results) matter most.
  4. How is an LLM-based reranker like Qwen3-Reranker different? It's a small LLM asked "Does this document answer the query? yes/no". The score is the probability of "yes". Same job, built on an LLM, usually stronger on multilingual and instruction-style queries.
  5. What other kinds exist? Listwise LLM reranking (RankGPT style): the LLM sees many passages and writes the order. Strong, but slow and expensive. Late interaction (ColBERT): one vector per token, matched token to token. Between bi- and cross-encoder in cost and accuracy. Rules / features: boost newer documents, trusted sources, exact keyword matches.
  6. Why not just increase top-k instead of reranking? A bigger k raises recall but floods the prompt with weak chunks. The LLM then gets more noise, more tokens and more cost, and relevant text lands in the middle where models attend least. Reranking lets you search wide and still send few.
  7. How do you measure if reranking helped? On a labelled set with the correct chunk per question: MRR = mean of 1/rank of the first correct chunk (rewards putting it first); nDCG@k = graded relevance with a log discount for lower positions, ∑k=1relklog2(k+1), divided by the ideal; Recall@k at the final k sent to the LLM. Compare with and without the reranker, plus p95 latency.
    ∑k=1relklog2(k+1)
    relkhow relevant the result at position k is (0, 1, 2 …)
    log2(k+1)the discount: lower positions count less
    ÷ IDCGdivide by the same sum for the perfect order, so the result is between 0 and 1
  8. Where does the threshold go? On the reranker score, after reranking. Reranker scores are more comparable between questions than cosine, so one cut works better. Still measure it on labelled data.
  9. How do you keep latency down? Cap candidates (20–50), batch all pairs in one GPU call, truncate each chunk to the reranker's trained length, use a small model (MiniLM-sized on CPU, about 0.6B on GPU), cache scores for repeated questions.
  10. Does chunk length matter for a reranker? Yes. Many rerankers are trained on short passages (around 512 tokens), and attention cost grows quickly with length. With my 1800-token chunks I'd rerank smaller child chunks of about 300 tokens and send their parent to the LLM, the parent–child pattern.
  11. What is MMR and why mention it? Maximal Marginal Relevance picks results that are relevant but not duplicates: score=λ·sim(q,d)−(1−λ)·maxdj∈Ssim(d,dj). Useful because overlapping chunks are near-copies; without it two of the top 5 can say the same thing.
    score=λ·sim(q,d)−(1−λ)·maxdj∈Ssim(d,dj)
    qthe question
    da candidate chunk
    Schunks already chosen
    λbalance: 1 = only relevance, 0 = only variety
  12. In what order do the final chunks go into the prompt? Best first (some systems also put a strong one last), because models attend most to the start and end of the context ("lost in the middle").
  13. Can the reranker work in Uzbek and Russian? Choose a multilingual one (bge-reranker-v2-m3, Qwen3-Reranker) and test on your own Uzbek questions. Never assume; Uzbek is a low-resource language.
  14. Can you fine-tune a reranker on your own data? Yes. Positives: (question, chunk the answer cited or the user accepted). Hard negatives: chunks retrieval ranked high that weren't used. A few epochs. Only worth it once you have a few hundred real examples.
  15. When would you not use a reranker? Tiny collections where top-k is already right, very strict latency budgets, or exact lookups (an ID or an article number) where keyword search alone is enough. Decide by measuring.
  16. Does reranking reduce hallucination? Indirectly. Better evidence and a more reliable threshold mean the LLM gets fewer misleading chunks and refuses more correctly. It doesn't check the answer; the grounding check does that.

Trap questions

  • "So is reranking better than semantic search?" Per pair, yes, it's more accurate. As a search method, no, it can't search. The right answer is both, in that order.
  • "Can the reranker find a chunk the search missed?" No. It only reorders candidates. That's why the first stage is tuned for recall (wide k, hybrid search).
  • "What does it cost?" Tens to hundreds of milliseconds for 30 pairs on a GPU, more on CPU. Cap the candidate count.
  • "Is there something in between?" Late-interaction models like ColBERT keep one vector per token and match token to token: more precise than one vector, cheaper than a cross-encoder.

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents