4.4.14Alignment, Prompting & RAG

Reranking and hybrid search

2,155 words10 min readdifficulty · medium

1. WHY do we need this at all?

A naive RAG pipeline does: embed query → nearest neighbours in vector DB → feed top-k to LLM. Two failure modes:

  1. Dense (vector) search misses exact terms. Embeddings capture meaning, so a query for the error code "ERR_4092" or the drug "Metformin" may retrieve semantically "nearby" but literally wrong chunks. It has no notion of an exact keyword match.
  2. Sparse (keyword) search misses meaning. A search for "car" will not match a doc that only says "automobile".

The 80/20 insight: retrieval quality — not prompt tweaking — is usually the single biggest lever on RAG accuracy. Hybrid + rerank often beats any prompt engineering.


2. The two retrievers — derived from first principles

2.1 Sparse: BM25 (WHAT and WHY)

We want to score how relevant a document DD is to a query with terms q1,,qnq_1,\dots,q_n. Intuition to build in:

  • A term that appears more often in DD should raise the score (term frequency, TF) — but with diminishing returns (the 50th "cat" tells us little beyond the 5th).
  • A term that is rare across the whole corpus is more discriminating (inverse document frequency, IDF). "The" is useless; "photosynthesis" is gold.
  • Long documents get a term-count advantage unfairly, so we normalise by length.

Putting these three ideas into a formula:

Why this shape?

  • The fraction f(k1+1)f+k1()\frac{f(k_1+1)}{f+k_1(\dots)} saturates: as ff\to\infty the score (k1+1)IDF\to (k_1+1)\cdot\text{IDF}, giving diminishing returns. That's the "50th cat" effect.
  • k1k_1 controls how fast it saturates; bb controls how strongly length normalisation kicks in (b=0b=0 ⇒ ignore length, b=1b=1 ⇒ full normalisation).
  • IDF(qi)=ln ⁣Nn(qi)+0.5n(qi)+0.5+1\text{IDF}(q_i)=\ln\!\frac{N-n(q_i)+0.5}{n(q_i)+0.5}+1, with NN = total docs, n(qi)n(q_i) = docs containing qiq_i — rare terms get a big multiplier.

2.2 Dense: cosine similarity of embeddings

Embed query and doc into vectors q,dRm\mathbf{q},\mathbf{d}\in\mathbb{R}^m with a bi-encoder (each encoded independently), score by: sim(q,d)=qdqd\text{sim}(\mathbf{q},\mathbf{d})=\frac{\mathbf{q}\cdot\mathbf{d}}{\|\mathbf{q}\|\,\|\mathbf{d}\|} Because documents are embedded offline once, this is fast (approximate nearest neighbour search) — but the query and doc never "see" each other, so subtle interactions are lost.


3. Merging the two lists — Reciprocal Rank Fusion (RRF)

The scores from BM25 and cosine are on incomparable scales. We can't just add them. RRF sidesteps this by using only the rank of each document in each list.

Why 1/(k+rank)1/(k+\text{rank})? A document ranked #1 contributes 1k+1\frac{1}{k+1}; ranked #100 contributes 1k+1000\frac{1}{k+100}\approx 0. So top positions dominate, and a doc that appears in both lists (even at middling rank) beats a doc that appears in only one. The constant kk softens the difference between rank 1 and rank 2 so it isn't winner-take-all.

Figure — Reranking and hybrid search

4. Reranking with a cross-encoder (the precision step)

The winning architecture: retrieve broadly and cheaply (bi-encoder + BM25 → top-100), then rerank precisely and expensively (cross-encoder → top-5). You pay the expensive cost only on 100 items, not the whole corpus.

final top-k=TopKk({CrossEncoder(q,d) : dHybrid-top-100})\text{final top-}k = \text{TopK}_k\Big(\big\{\,\text{CrossEncoder}(q,d)\ :\ d\in\text{Hybrid-top-}100\,\big\}\Big)


5. Common mistakes (steel-manned)


6. Feynman

Recall Explain to a 12-year-old

Imagine finding a fact in a huge library. One helper (keyword search) looks for the exact words you said. Another helper (meaning search) looks for books that are about the same idea even with different words. You ask both so nothing good is missed — that's hybrid search. They hand you a messy pile of 100 books. Then a super-careful reader (the reranker) actually reads your question and each book together and puts the best 5 on top. You only give those 5 to the answer-writer, so it doesn't get confused by a big messy pile.


7. Flashcards

What problem does hybrid search solve that pure vector search cannot?
Exact/rare keyword and code matches (e.g. "ERR_4092") that embeddings miss; it adds lexical (BM25) recall to semantic recall.
What are the two component retrievers in hybrid search?
Sparse/lexical (BM25 keyword) and dense/semantic (embedding cosine similarity).
Why does BM25's term-frequency term saturate?
Diminishing returns — extra occurrences of a term add little info; the fraction f(k1+1)f+k1()(k1+1)IDF\frac{f(k_1+1)}{f+k_1(\dots)}\to(k_1+1)\text{IDF} as ff\to\infty.
What do the BM25 parameters k1k_1 and bb control?
k1k_1 = how fast term-frequency saturates; bb = strength of document-length normalisation (00=none, 11=full).
Give the RRF formula.
RRF(d)=r1k+rankr(d)\text{RRF}(d)=\sum_r \frac{1}{k+\text{rank}_r(d)}, typically k=60k=60.
Why use rank-based RRF instead of adding raw scores?
BM25 and cosine are on incomparable scales; RRF uses only ranks so it's scale-free and rewards docs found by both retrievers.
Difference between a bi-encoder and a cross-encoder?
Bi-encoder embeds query and doc separately (fast, precomputable, coarse); cross-encoder processes them jointly with cross-attention (slow, accurate, per-pair).
Why can't a cross-encoder be used to search the whole corpus?
It needs one forward pass per document and can't precompute embeddings, so scoring millions of docs per query is infeasible — it's a reranker on a small candidate set.
Hybrid search improves which metric, and reranking improves which?
Hybrid → recall (widen net); reranking → precision@top-k (order the best first).
Why not just feed a large top-k to the LLM instead of reranking?
Lost-in-the-middle: buried relevant chunks get ignored, plus higher cost, latency, and hallucination from noise.
What is the typical two-stage retrieve-then-rerank sizing?
Retrieve ~100 candidates cheaply (hybrid), rerank with cross-encoder to ~5 for the LLM.
Can reranking recover a relevant doc missing from the candidate set?
No — reranking only reorders; recall must be handled at retrieval time.

8. Connections

  • Vector Databases and ANN Search — supplies the dense candidate list.
  • BM25 and TF-IDF — the sparse retriever's scoring foundation.
  • Embeddings and Bi-encoders — how dense vectors are produced.
  • Cross-encoders and Sentence Transformers — the reranking model.
  • Retrieval-Augmented Generation (RAG) — the pipeline this feeds.
  • Lost in the Middle - LLM context limits — why small top-k matters.
  • Evaluation - Recall@k and MRR — how to measure retrieval quality.

Concept Map

split into

embed into

misses meaning

misses exact terms

merged with

merged with

improves recall

re-scored by

improves precision at top

fed to

solved by

defines score for

Query

Sparse BM25 keyword

Dense vector search

Retrieval failure modes

Hybrid search

Candidate list top-100

Reranking cross-encoder

Top-k passages

LLM answer

BM25 formula TF-IDF length norm

Hinglish (regional understanding)

Intuition Hinglish mein samjho

RAG me sabse bada problem yeh hai: agar sahi document retrieve hi nahi hua, toh LLM kabhi sahi jawab nahi de sakta — woh hallucinate karega. Isliye retrieval quality par focus karna 80/20 move hai. Ab do tarike ke search hote hain. Dense (vector) search meaning samajhta hai — "car" aur "automobile" ko same maanta hai — par exact keyword ya error code jaise "ERR_4092" ko miss kar deta hai. Sparse search (BM25) exact words dhoondhta hai par meaning nahi samajhta. Hybrid search dono ko mila deta hai, taaki koi bhi accha document chhoote na — isse recall badhta hai.

BM25 ka logic simple hai: jo term document me zyada baar aaye woh important (TF), par bahut zyada baar aane se fayda kam hota jaata hai (saturation). Jo term poore corpus me rare ho woh zyada discriminating (IDF). Aur lambe documents ko length se normalise karte hain taaki unko unfair advantage na mile. Dono retrievers ki scores alag-alag scale par hoti hain, isliye directly add nahi kar sakte. Solution: RRF — sirf rank use karo, score nahi. Jo document dono lists me aata hai woh upar chadh jaata hai, kyunki do gawaah ek se behtar hote hain.

Fir aata hai reranking. Retrieval ke baad hamare paas top-100 candidates hote hain, thodi si messy list. Ab ek cross-encoder query aur har document ko ek saath padhta hai (dono ke tokens ek dusre ko attend karte hain), isliye woh bahut accurate score deta hai — par mehenga hota hai. Isliye ise sirf 100 candidates par lagate hain, poore corpus par nahi. Yeh top-5 ko upar le aata hai, aur wahi 5 LLM ko dete hain. Yaad rakho: hybrid recall badhata hai, rerank precision badhata hai — pehle wide net dalo, fir best fish rakho. Aur ek cheez: rerank sirf order badal sakta hai, agar sahi doc top-100 me hai hi nahi toh rerank kuch nahi kar payega — isliye recall pehle important hai.

Go deeper — visual, from zero

Test yourself — Alignment, Prompting & RAG

Connections