Skip to content

Chapter 2 · Retrieval


2.1 Sparse Retrieval: TF-IDF and BM25 ★★

TF-IDF and the inverted index ★

\[\mathrm{tfidf}(t, d) = \mathrm{tf}(t, d) \cdot \log \frac{N}{\mathrm{df}(t)}\]

Sparse retrieval represents a text as a vector as long as the vocabulary, with one dimension per word; almost all dimensions are 0, hence "sparse". The idea behind TF-IDF is simple: a word matters for a document because it appears often in that document (term frequency) and because it is rare across the corpus (inverse document frequency). In the formula, \(\mathrm{tf}(t, d)\) is the number of times word \(t\) occurs in document \(d\), \(N\) is the total number of documents, and \(\mathrm{df}(t)\) is the number of documents containing \(t\). A word like "the" or "is" that appears in almost every document has \(\mathrm{df} \approx N\), so its idf is close to 0 and it barely counts; a word like "HNSW" that appears in only a few documents has a large idf, so a match on it is a strong signal. Once the query and documents are represented as TF-IDF vectors, they are ranked by cosine similarity.

Sparse retrieval is fast thanks to the inverted index: for each word, keep a list of the documents that contain it (a posting list). At query time you fetch only the lists for the few words in the query, merge them and score, without touching any other document. Search engines have been built on this structure for decades.

TF-IDF has two obvious flaws. First, tf grows linearly: a word that appears 20 times scores 10 times as much as one that appears twice, which clearly makes no sense and is easy to game by keyword stuffing. Second, it ignores document length: long documents naturally contain more words and more repetitions, which gives them an unfair advantage. BM25 was designed to fix exactly these two problems.

Interview questions

  • ★ Explain TF-IDF. Why is sparse retrieval fast?

BM25 ★★

\[\mathrm{BM25}(q, d) = \sum_{t \in q} \mathrm{IDF}(t) \cdot \frac{f(t, d)\,(k_1 + 1)}{f(t, d) + k_1 \left(1 - b + b \cdot \dfrac{|d|}{\mathrm{avgdl}}\right)}, \qquad \mathrm{IDF}(t) = \ln\!\left(\frac{N - n(t) + 0.5}{n(t) + 0.5} + 1\right)\]

BM25 (Robertson & Zaragoza 2009) scores each query word and sums the scores. \(f(t, d)\) is the number of times word \(t\) appears in document \(d\), \(|d|\) is the document length in tokens, \(\mathrm{avgdl}\) is the average document length in the corpus, \(N\) is the number of documents, and \(n(t)\) is the number of documents containing \(t\). \(k_1\) and \(b\) are two hyperparameters. The IDF part plays the same role as in TF-IDF, rewarding rare words (this is Lucene's version; the \(+1\) at the end keeps it from going negative). The real improvement is the fraction in the middle, which handles the term-frequency problem and the length problem separately.

Term-frequency saturation (\(k_1\)). Ignore length for now (set \(b = 0\)); the fraction becomes \(\frac{f(k_1+1)}{f + k_1}\). It is 0 at \(f = 0\); as \(f\) grows the score rises, but more and more slowly, approaching the ceiling \(k_1 + 1\). With \(k_1 = 1.2\), for example, one occurrence gives 1.0, two give about 1.38, and even ten give only about 1.96, never exceeding 2.2. This matches intuition: the first occurrence of a word tells us "this document is about this word" and carries the most information; the tenth carries almost none. Saturation has another important effect: in a multi-word query, a document that matches several different query words beats one that repeats a single word many times, and keyword stuffing stops working. \(k_1\) controls how fast saturation happens: with \(k_1 = 0\) only presence matters (binary); with a very large \(k_1\) the score approaches raw linear tf. The usual range is 1.2 to 2.0.

Length normalization (\(b\)). The term \(k_1(1 - b + b \cdot |d|/\mathrm{avgdl})\) in the denominator changes with document length. When a document is longer than average, \(|d|/\mathrm{avgdl} > 1\), the denominator grows, and the same term frequency earns a lower score. The reason is that a word appearing a few more times in a long document may just reflect its length, not greater relevance: a 10,000-word document mentioning "transformer" 5 times may be less on-topic than a 200-word one mentioning it 3 times. \(b\) lies between 0 and 1: \(b = 0\) means no length normalization, \(b = 1\) means full normalization by relative length. The default of 0.75 is a compromise, because long documents sometimes genuinely cover more and shouldn't be penalized too hard. Lucene and Elasticsearch default to \(k_1 = 1.2\) and \(b = 0.75\).

Interview questions

  • ★★ Write the BM25 formula and explain what \(k_1\) and \(b\) do.
  • ★ How does BM25 improve on TF-IDF?

Strengths and limits of sparse retrieval ★★

BM25 is still an important component of RAG systems today, because it has several strengths dense retrieval can't match. First, exact matching: product model numbers, names, error codes (such as E1023), function names and legal clause numbers are rare strings with high idf, so BM25 weights them heavily, while dense models often blur them with other strings that "look similar". Second, it needs no training and works out of the box in a new domain. Third, it generalizes robustly: the BEIR benchmark (Thakur et al. 2021) evaluated zero-shot retrieval on 18 datasets from different domains and found BM25 to be a strong baseline; many dense retrievers trained only on MS MARCO did worse than BM25 in new domains. It is also interpretable (you can see which words matched), fast and memory-light.

Its fundamental limit is vocabulary mismatch: it recognizes words, not meanings. If the query says "car" and the document says "automobile", or the query asks "how do I make my program run faster" while the document talks about "performance optimization", BM25 can't match them. It also ignores word order and negation: "dog bites man" and "man bites dog" get the same score. There are two directions for improvement. One is document expansion: doc2query (Nogueira et al. 2019) uses a model to generate the questions each document might answer and appends them to the document before indexing. The other is learned sparse retrieval, such as SPLADE (Formal et al. 2021). It uses BERT's MLM head to compute a weight for every word in the vocabulary (aggregating the outputs over all positions), so related words that don't appear in the document (say, "car" for a document about "automobiles") can still get weight, which amounts to automatic term expansion. Training adds a sparsity-encouraging regularizer that drives almost all word weights to 0, so the representation stays sparse and can still be searched with an inverted index. It combines BM25's exact matching and interpretability with a dense model's semantic ability; the cost is that the model must be trained, and encoding documents is slower than BM25.

Interview questions

  • ★★ With dense retrieval available, is BM25 still useful? What is each good at?
  • ★ What is learned sparse retrieval (e.g. SPLADE), and how does it differ from BM25 and dense retrieval?

2.2 Dense Retrieval ★★

Bi-encoders and DPR ★★

\[s(q, p) = E_Q(q)^\top E_P(p)\]

Dense retrieval encodes both queries and documents into low-dimensional dense vectors (hundreds to thousands of dimensions, every dimension non-zero) and uses vector similarity as relevance. The classic example is DPR (Dense Passage Retrieval, Karpukhin et al. 2020): two independent BERT-base encoders, \(E_Q\) for questions and \(E_P\) for passages, each taking the 768-dimensional vector at the [CLS] position; relevance is their dot product \(s(q, p)\). This structure, where queries and documents are encoded separately, is called a bi-encoder (or two-tower model).

The key to scaling to large corpora is that document encoding doesn't depend on the query. DPR split Wikipedia into about 21 million 100-word passages, encoded them all offline and indexed them with FAISS; at query time it encodes the question once and runs one maximum inner product search (MIPS). DPR's main finding was that training only on question–answer-passage pairs, with no extra pretraining task, was enough for dense retrieval to beat BM25 by a wide margin on open-domain QA: 9 to 19 points higher top-20 retrieval accuracy.

The advantage of dense retrieval is semantic matching: in vector space, expressions with similar meanings sit close together, so "Who wrote Hamlet?" can match "This tragedy by Shakespeare…" even without shared keywords. Its limits come from the same place: a whole passage is squeezed into one fixed-length vector, which is an information bottleneck, so details like specific numbers and rare entity names are easily lost. It needs training data and may degrade noticeably in domains it never saw during training, and whenever the encoder is updated, the whole index has to be rebuilt.

Interview questions

  • ★★ What is a bi-encoder, and how does DPR work?
  • ★ What are the pros and cons of dense retrieval compared with BM25?

Contrastive training with InfoNCE ★★

\[\mathcal{L} = -\log \frac{\exp\big(s(q, p^+)/\tau\big)}{\exp\big(s(q, p^+)/\tau\big) + \sum_{j=1}^{n} \exp\big(s(q, p_j^-)/\tau\big)}\]

Dense retrievers are trained with contrastive learning: for a query \(q\), take one relevant document \(p^+\) (the positive) and \(n\) irrelevant documents \(p_1^-, \dots, p_n^-\) (the negatives), and teach the model to score the positive high and the negatives low. The formula is the InfoNCE loss (van den Oord et al. 2018). \(s(\cdot, \cdot)\) is the similarity (dot product or cosine) and \(\tau\) is the temperature. It is essentially an \((n+1)\)-way classification: softmax over all candidates' scores, push the positive's probability toward 1, and use cross-entropy as the loss. The name comes from contrastive predictive coding; one can show that minimizing it maximizes a lower bound on the mutual information between the query and the positive, and the more negatives, the tighter the bound.

The temperature \(\tau\) controls how sharp the softmax is. With a small \(\tau\), gaps between scores are amplified and the loss is dominated by the few highest-scoring negatives, so the model concentrates on pushing away the hardest ones; with a large \(\tau\), all negatives are treated more evenly (Wang & Liu 2020 analyze this systematically). Cosine similarity only ranges over \([-1, 1]\), so without dividing by a fairly small \(\tau\) (commonly 0.01 to 0.05) the softmax would be very flat and the gradients weak. DPR used unnormalized dot products, which amounts to \(\tau = 1\).

Why does the choice of negatives matter so much? Look at the gradient. Differentiating with respect to negative \(j\)'s score gives \(\partial \mathcal{L} / \partial s_j = p_j / \tau\), where \(p_j\) is the softmax probability assigned to that negative. In other words, each negative is pushed down in proportion to how much probability it "steals". A negative the model already scores very low has \(p_j \approx 0\), produces almost no gradient and contributes nothing to training. This is the starting point for hard negatives below.

Interview questions

  • ★★ Write the InfoNCE loss and explain the role of the temperature \(\tau\).
  • ★ Why does cosine similarity need a fairly small temperature?

In-batch negatives ★★

\[S = Q P^\top \in \mathbb{R}^{B \times B}, \qquad \mathcal{L} = \frac{1}{B} \sum_{i=1}^{B} \mathrm{CE}\big(\mathrm{softmax}(S_{i,:}/\tau),\; i\big)\]

Where do negatives come from? The cheapest source is in-batch negatives: a batch holds \(B\) (query, positive) pairs; multiply the \(B\) query vectors by the \(B\) positive vectors once to get a \(B \times B\) similarity matrix \(S\). The diagonal holds each query's score with its own positive, and the other \(B-1\) entries in row \(i\) are the negatives for query \(i\), i.e. other queries' positives. Applying cross-entropy (CE) to each row with "the correct answer is column \(i\)" gives the formula above.

The benefit is that these negatives are almost free: the document vectors have to be computed for their own queries anyway, and the only extra work is one \(B \times B\) matrix multiplication. And the larger the batch, the more negatives each query sees and the stronger the contrastive signal. DPR found that larger batches worked better, and today's general-purpose embedding models often use batch sizes of thousands to tens of thousands in pretraining, also gathering vectors from all GPUs so that every query is contrasted with documents from every device (cross-device negatives).

In-batch negatives have limits too. First, they are random, and most are too easy: for a query about sorting in Python, the other documents in the batch might be about French cooking, stocks and football, so the model only needs to tell topics apart and never learns fine distinctions (the reason is the gradient analysis above). Second, batch size is limited by GPU memory (tricks such as a MoCo-style negative queue or gradient caching help). Third, there can be false negatives: if two queries in a batch share the same or a near-identical positive document, it gets wrongly treated as a negative, so duplicates have to be removed or masked.

Interview questions

  • ★★ What are in-batch negatives, and why is a larger batch usually better?

Hard negatives ★★

A hard negative is a document that looks very similar to the query but isn't actually relevant. Why they matter was explained above via the gradient: easy negatives already score low and produce almost no gradient; only negatives the model tends to confuse force it to learn fine distinctions. Moreover, at real retrieval time the competitors are exactly these documents: for "How do I sort a list in Python?", the passages to rule out are about "sorting a dictionary in Python" or "sorting a list in Java", not about French cooking. If training only shows easy negatives, the training and test distributions don't match.

There are three common ways to mine them. First, with BM25: take passages ranked high by BM25 that don't contain the answer. DPR found that adding just one such BM25 negative per question on top of in-batch negatives clearly improved results. Second, with the model itself: ANCE (Xiong et al. 2020) periodically rebuilds the ANN index with the current model during training and takes negatives from the model's own retrieval results, so the negatives are always "what the current model confuses most". Third, with a stronger model, for example selecting negatives by cross-encoder scores.

The biggest risk with hard negatives is false negatives. Many datasets label only one or two positives per query, leaving other relevant documents unmarked; most MS MARCO queries, for instance, have just one labeled relevant passage. Quite a few mined "hard negatives" are actually unlabeled positives, and training on them punishes the model for doing the right thing. RocketQA (Qu et al. 2020) uses a cross-encoder to filter out negatives that score very high and are probably relevant (denoised hard negatives); other common practices are skipping the top few results before sampling, or replacing 0/1 hard labels with cross-encoder soft scores for distillation. In practice, in-batch negatives are usually mixed with a small number of hard negatives.

Interview questions

  • ★★ Why are hard negatives needed, how are they mined, and what are the risks?
  • ★ What are false negatives, and how can they be mitigated?

Unsupervised dense retrieval ★

All the training above needs labeled (query, relevant document) pairs, and many domains have no such data at all. Contriever (Izacard et al. 2021) showed that a decent dense retriever can be trained with no labels at all. The key is to create positives from the same document: randomly crop two non-overlapping spans from one document (independent cropping) and treat them as a positive pair, since two spans of the same document very likely talk about the same thing; spans from different documents serve as negatives. To get many negatives, it uses a MoCo-style queue that keeps document vectors from several previous batches, not just the current one. On BEIR, this fully unsupervised model beat BM25 in Recall@100 on 11 of 15 datasets, and using it as a pretraining starting point, then fine-tuning on a little in-domain data or on MS MARCO, improves results further. The idea was later absorbed into the first-stage weakly supervised pretraining of general-purpose embedding models (see 2.8).

Interview questions

  • ★ How can you train a dense retriever without labeled data?

Limits of a single vector ★

A fundamental issue with dense retrieval is that a text gets just one \(d\)-dimensional vector, and retrieval is decided entirely by the inner product between query and document vectors. Does this limit which "patterns of relevance" can be expressed? Weller et al. (2025) proved theoretically that it does: the number of distinct top-k document subsets a \(d\)-dimensional embedding can return is bounded by the dimension \(d\). And the limit doesn't depend on the training method; even optimizing the vectors directly as free parameters on the test set can't break it. Based on this, they built a dataset called LIMIT whose queries are very simple (along the lines of "who likes X") but whose required document combinations are very diverse, and the strongest embedding models of the time all performed poorly on it, worse the lower their dimension. By contrast, BM25, whose dimension is enormous, gets LIMIT almost entirely right, and multi-vector models do much better than single-vector ones.

This result shows that the problem with single-vector retrieval isn't only "not enough data, model not big enough": the representation itself has a ceiling. As query relevance becomes more flexible (complex instructions, several conditions to satisfy at once), that ceiling is easier to hit. This is also why multi-vector ColBERT, cross-encoding rerankers and sparse retrieval remain valuable today: they aren't bound by a single vector.

Interview questions

  • ★ Does single-vector dense retrieval have theoretical limits?

2.3 Late Interaction: ColBERT ★

\[s(q, d) = \sum_{i=1}^{|q|} \max_{1 \le j \le |d|} \mathbf{q}_i^\top \mathbf{d}_j\]

A bi-encoder squeezes a whole document into one vector and easily loses details; a cross-encoder (see 2.5) lets the query and document interact fully, which is accurate but can't be precomputed. ColBERT (Khattab & Zaharia 2020) takes a middle path: instead of squeezing the text into one vector, it keeps one vector per token (projected to a smaller dimension such as 128 and normalized). At scoring time, each query token vector \(\mathbf{q}_i\) looks for the most similar of all the document's token vectors \(\mathbf{d}_j\) (MaxSim), and these maximum similarities are summed over all query tokens, as in the formula.

It's called late interaction because the document encoding still doesn't depend on the query, so it can be computed offline and stored just like a bi-encoder's; the query and document interact only in this final, cheap MaxSim step, not inside every Transformer layer as in a cross-encoder.

Why is it more accurate than a single-vector bi-encoder? Because matching happens at the token level: every query word has to find its own "support" in the document, and a rare entity name isn't washed out by the average meaning of the whole passage. Its zero-shot generalization on cross-domain benchmarks like BEIR is also clearly better than single-vector models. The main cost is storage: a 100-token passage needs 100 vectors instead of 1, so the index is dozens of times larger or more. ColBERTv2 (Santhanam et al. 2021) used residual compression to cut storage by 6 to 10 times, and engines such as PLAID sped up search further. Retrieval usually first runs ANN over token vectors to gather candidate documents and then computes exact MaxSim on them; ColBERT can also serve as a reranker that only rescores first-stage candidates. Overall it sits between bi-encoders and cross-encoders in both quality and cost. (The same idea has also been applied to images of document pages, as in ColPali.)

Interview questions

  • ★ How is ColBERT's MaxSim computed, and why is it called late interaction?
  • ★ How does ColBERT compare with bi-encoders and cross-encoders in cost and quality?

2.4 Hybrid Retrieval and Fusion ★★

Why combine ★★

BM25 and dense retrieval have strengths and weaknesses that are almost exactly complementary. BM25 is good at exact literal matching (error codes, model numbers, names, identifiers in code) but doesn't understand synonyms or rephrasing; dense retrieval is good at semantic matching but insensitive to rare strings and exact numbers. The two fail in different places, so merging their results gives higher recall than either alone. In practice, hybrid retrieval is almost standard in production RAG, and the gain is especially clear across domains and in terminology-heavy settings. The recipe is simple: run both retrievers in parallel, take the top-N from each, and fuse the two ranked lists into one. The hard part is how to fuse.

Interview questions

  • ★★ Why use hybrid retrieval? Where does each of BM25 and dense retrieval fail?

Score fusion and RRF ★★

\[\mathrm{RRF}(d) = \sum_{r \in R} \frac{1}{k + \mathrm{rank}_r(d)}\]

You can't just add the scores. BM25 scores have no upper bound and might be 5 or 30, with a different range for every query; cosine similarity lies in \([-1, 1]\) and is usually squeezed into a narrow band. One approach is to normalize, then weight: for each query, min-max normalize each retriever's scores to \([0, 1]\), then compute \(s = \alpha\, s_{\text{dense}} + (1 - \alpha)\, s_{\text{sparse}}\) (a convex combination). This keeps information about score magnitudes, but \(\alpha\) needs tuning, and min-max normalization is easily skewed by a few extreme scores.

Reciprocal Rank Fusion (RRF, Cormack et al. 2009) ignores scores altogether and uses only ranks. In the formula, \(R\) is the set of ranked lists being fused (say, one from BM25 and one from dense retrieval), \(\mathrm{rank}_r(d)\) is document \(d\)'s position in list \(r\) (starting at 1), and if \(d\) is missing from a list, that term is 0. \(k\) is a smoothing constant, usually 60 (not to be confused with the \(k\) in top-k).

There are two intuitions behind RRF. First, it uses only ranks, so there is no scale problem at all: no training and no tuning needed. Second, \(k\) "flattens" the top of the list: with \(k = 60\), rank 1 earns \(1/61 \approx 0.0164\) and rank 10 earns \(1/70 \approx 0.0143\), so the top few positions differ only slightly. As a result, appearing in several lists matters more than being first in one. For example, document A ranks 1st in BM25 only and scores about 0.016; document B ranks 5th in both lists and scores about \(2/65 \approx 0.031\), so B comes out ahead of A. With a very small \(k\), the top-ranked document would dominate.

RRF's drawback is that it throws away the information in the scores: a first place one retriever is very sure about and a first place that barely made it look the same to RRF. Bruch et al. (2022) compared them systematically and found that a tuned convex combination beats RRF both in-domain and out-of-domain, and that only a few labeled examples are needed to tune \(\alpha\); RRF is also more sensitive to the choice of \(k\) than commonly assumed. A practical conclusion: without labeled data, RRF is a safe default; with a small labeled set, try tuning a convex combination. RRF is also often used to fuse the multiple result lists produced by multi-query (see Chapter 3).

Interview questions

  • ★★ Write the RRF formula. What does the constant \(k\) do?
  • ★★ Why can't you just add the BM25 score and the dense score?
  • ★ What are the pros and cons of RRF versus normalized weighted fusion?

2.5 Rerankers ★★

Cross-encoders vs bi-encoders ★★

\[s(q, d) = \mathbf{w}^\top\, \mathrm{BERT}\big(\texttt{[CLS]}\; q\; \texttt{[SEP]}\; d\; \texttt{[SEP]}\big)_{\texttt{[CLS]}}\]

A cross-encoder concatenates the query and the document into one sequence, feeds it through a Transformer, takes the output at [CLS] and maps it to a relevance score with a linear layer \(\mathbf{w}\). The fundamental difference from a bi-encoder is that every query token and every document token can attend to each other in every layer.

Why is it more accurate? When a bi-encoder encodes a document, it doesn't know what the query will be, so it can only squeeze the document into a "general-purpose" vector and hope it's useful for every possible question, which is essentially a guess. A cross-encoder reads the document with the question in mind: it can line up "before 2020" in the query with a specific date in the document, notice negations, and check whether a number in the document is the one the query asks about. The early monoBERT (Nogueira & Cho 2019) applied a BERT cross-encoder to passage reranking on MS MARCO and improved substantially over earlier methods, establishing the approach.

Why can't it be used for retrieval directly? Because the document's representation depends on the query, it can't be precomputed or indexed. For every query, each candidate document has to be concatenated with it and run through a full forward pass. With ten million documents in the store, one query would need ten million BERT runs, which is completely infeasible; a bi-encoder only encodes the query once and runs one vector search. So real systems use a cascade: BM25 or a bi-encoder quickly recalls around the top 100, a cross-encoder rescores those 100, and the best 5 to 10 go into the prompt. Reranking latency is proportional to the number of candidates and their length, so the candidate count is kept in check, smaller models are common (MiniLM or BERT-base size), and scoring is batched on GPUs.

For training, a cross-encoder can do pointwise binary classification with binary cross-entropy ("relevant / not relevant"), or listwise softmax cross-entropy over one positive and several hard negatives taken from the first-stage retriever. A trained cross-encoder is also often used as a teacher, distilling its scores into a bi-encoder.

Interview questions

  • ★★ Why is a cross-encoder more accurate than a bi-encoder, and why can't it be used for retrieval directly?
  • ★ How is a reranker usually trained?

LLM rerankers ★

LLMs can also serve as rerankers, in three common ways. Pointwise: ask the LLM, for each candidate, "Is this passage relevant to the question?" and use its probability of answering "yes" as the score. Pairwise: give the LLM two candidates at a time and ask which is more relevant, then sort using these pairwise comparisons (e.g. PRP, Qin et al. 2023). Listwise: give the LLM a query and a dozen or two numbered candidates at once and have it output the sorted IDs directly. RankGPT (Sun et al. 2023) is listwise; when there are too many candidates to fit, it uses a sliding window that ranks one segment at a time from the end of the list toward the front, gradually "bubbling" the good documents to the top.

The strengths of LLM rerankers are strong zero-shot ability, world knowledge, and the ability to define relevance by instruction, such as "prefer recent documents" or "must mention pricing", which a fixed, trained cross-encoder can't do. The drawbacks are just as clear: high latency and cost, since one reranking call may process tens of thousands of tokens; listwise ranking is sensitive to input order (position bias), so the same candidates in a different order can come back ranked differently; and the output may be malformed, or miss or repeat IDs. So in practice, a large model's ranking ability is often distilled into smaller open models (e.g. RankZephyr), or LLM reranking is reserved for small candidate sets where precision matters most.

Interview questions

  • ★ How can an LLM be used for reranking, and how do pointwise, pairwise and listwise differ?
  • ★ What problems do LLM rerankers have?

Comparing the four scoring approaches ★★

Bi-encoder ColBERT Cross-encoder LLM reranker
Query–document interaction None until one final dot product Token-level MaxSim at the end Full attention in every layer Full attention, plus instructions and reasoning
Precompute documents offline Yes (one vector each) Yes (one vector per token) No No
Cost per query One query encoding + ANN search ANN + MaxSim over candidates; large index One forward pass per candidate Very high: long prompts, many tokens
Quality Good Better Best among BERT-sized models Strong, especially zero-shot and for complex criteria
Typical role First-stage retrieval First stage or reranking Reranking the top ~100 Reranking the top ~20–100

Looking at the four together, one rule underlies them all: the earlier and more fully the query and document interact, the more accurate the score, but the less can be precomputed and the higher the cost per query. A bi-encoder has no interaction at all, so documents can all be encoded offline, which allows first-stage retrieval over hundreds of millions of documents; ColBERT interacts only at the token level at the very end and can still encode offline, at the cost of a larger index; cross-encoders and LLMs let the two interact in every layer and can only be applied to a small set of candidates. This is exactly where the industry's "multi-stage funnel" comes from: use a cheap method to recall a few hundred candidates from a huge corpus, then filter them stage by stage with more expensive, more accurate models, each stage handling an order of magnitude fewer documents, until only a few remain for the prompt.

Interview questions

  • ★ Compare bi-encoders, ColBERT, cross-encoders and LLM rerankers in cost and quality.

2.6 ANN Indexes ★★

Why ANN ★

Exact nearest-neighbor search compares the query with every vector in the store, costing \(O(Nd)\). With a hundred million 768-dimensional vectors, each query needs about 77 billion multiply-adds, which no latency or cost budget can afford. ANN (approximate nearest neighbor) indexes trade a little accuracy for orders of magnitude of speed: they don't guarantee finding the true nearest neighbors, but they do most of the time. ANN quality is usually measured by ANN recall@k: how much ANN's top-k overlaps with the exact top-k. Designing an ANN index means balancing three things: recall, latency and memory, plus build time and whether incremental updates are supported. In RAG, the error ANN introduces is usually much smaller than the embedding model's own error, so tuning ANN recall above about 95% is generally enough.

Interview questions

  • ★ Why do we need ANN, and how do you judge an ANN index?

IVF (inverted file index) narrows the search. At build time, k-means clusters all vectors into nlist clusters, and each vector is assigned to its nearest centroid. At query time, the query is compared with all centroids, the nprobe nearest clusters are chosen, and exact search runs only inside them. With nlist = 1000 and nprobe = 10, only about 1% of the vectors are compared.

The key parameter is nprobe: a larger nprobe searches more clusters, raising recall but slowing things down; at nprobe = nlist it degenerates into brute-force search. IVF typically misses when a true nearest neighbor sits on a cluster boundary and was assigned to an adjacent cluster that wasn't probed. nlist is usually a few times \(\sqrt{N}\). IVF needs centroids trained on representative data first; if the distribution of later data shifts, clusters become very unbalanced, efficiency drops, and retraining is needed. Also, IVF by itself only cuts computation without compressing vectors, so memory use is the same as storing the raw vectors.

Interview questions

  • ★ How does IVF speed up search, how does nprobe affect recall and latency, and why does it miss neighbors?

PQ: compressing vectors ★

\[\mathbf{x} = \big[\mathbf{x}^{(1)}, \dots, \mathbf{x}^{(m)}\big], \qquad \mathbf{x}^{(j)} \approx \mathbf{c}^{(j)}_{i_j}, \qquad \mathrm{code}(\mathbf{x}) = (i_1, \dots, i_m)\]

PQ (product quantization, Jégou et al. 2011) tackles memory. It cuts a \(d\)-dimensional vector into \(m\) segments of \(d/m\) dimensions each and runs k-means separately on each segment, learning a codebook of 256 centroids. When storing a vector, each segment records only which centroid it is closest to, an ID \(i_j\) from 0 to 255, which fits in exactly one byte. So a vector takes only \(m\) bytes. For example, a 768-dimensional float32 vector normally takes 3,072 bytes; with \(m = 96\) it takes 96 bytes, a 32× compression.

PQ also computes distances quickly, using asymmetric distance computation: the query itself isn't compressed. First compute the distance from each segment of the query to the 256 centroids in that segment's codebook, giving an \(m \times 256\) table; after that, the distance between the query and any stored vector is just \(m\) table lookups added together, with no multiplications at all. The price is that it's lossy: every segment is approximated by its nearest centroid, so distances are only estimates and recall drops. A common fix is to use PQ to pick a generous candidate set quickly and then recompute exact distances with the original vectors (if they are stored). PQ is rarely used alone; the most common setup is IVF-PQ, where IVF narrows the search and PQ compresses storage, the classic combination for billion-scale vector search.

Interview questions

  • ★ How does PQ compress vectors and compute distances quickly?

HNSW: a hierarchical graph ★★

HNSW (Hierarchical Navigable Small World, Malkov & Yashunin 2016) is the default index in most vector databases today. It organizes vectors into a multi-layer proximity graph: each vector is a node connected to several of its nearest nodes. The bottom layer (layer 0) contains all nodes; each node is randomly assigned a top layer, with higher layers exponentially less likely, so higher layers have fewer nodes and "longer" edges, a bit like a skip list, or like a road network of highways plus city streets.

Search starts from the entry node at the top layer and moves greedily to whichever neighbor is closer to the query, until no neighbor is closer; it then drops to the next layer and continues from where it stopped. At layer 0 it runs a beam search with a candidate list of size efSearch and finally returns the nearest \(k\). The long edges on upper layers let the search leap across large regions quickly, and the short edges on lower layers handle fine positioning, so only a few nodes need to be visited to find near neighbors. Inserting a new vector uses the same search to find its neighbors on each layer and then connects them, so incremental writes are supported and no training is needed.

There are three main parameters. M is the number of edges per node: a larger M makes the graph denser and recall higher but uses more memory. efConstruction is the candidate list size during graph building: larger gives a better graph but slower builds. efSearch is the candidate list size at query time: larger raises recall and latency, and it can be adjusted per query. HNSW has an excellent recall–latency trade-off. The costs are high memory (it stores the full original vectors plus dozens of edges per node) and usually must sit entirely in RAM; slow builds; and awkward deletions, which usually can only be marked, with graph quality degrading as deletions pile up and periodic rebuilds needed. With strict metadata filters, fewer nodes are traversable and the graph's connectivity gets worse.

Interview questions

  • ★★ How does HNSW work, and what do M, efConstruction and efSearch affect?
  • ★ What are HNSW's drawbacks, and why are deletions and filtering hard for it?

Comparison and choice ★★

Index How it works Recall Latency Memory Build and updates
Flat (exact) Compare with every vector 100% Slow, \(O(N)\) Full vectors Nothing to build; updates are trivial
IVF-Flat k-means clusters; search the nprobe nearest High, tuned by nprobe Fast Full vectors + centroids Needs training; inserts are easy; drift unbalances clusters
IVF-PQ IVF + PQ-compressed vectors Medium; re-ranking with raw vectors helps Very fast Very small (tens of bytes per vector) Needs training
HNSW Multi-layer proximity graph, greedy search Very high, tuned by efSearch Very fast Largest: full vectors + graph edges No training; slow build; deletions are hard

The choice mainly depends on scale and memory budget. For tens to hundreds of thousands of vectors, brute-force search (Flat) is often fast enough and has no error at all. For millions to tens of millions with enough memory, HNSW is the most common choice. At billion scale, the full vectors don't fit in memory, so you need compressed indexes like IVF-PQ, or approaches that put a graph index on SSD (such as DiskANN). Vectors can also be scalar-quantized (e.g. float32 to int8) or binary-quantized to cut memory further. Common libraries include FAISS (Johnson et al. 2017) and ScaNN.

Interview questions

  • ★★ Compare HNSW, IVF and PQ in recall, latency and memory.
  • ★ Which index would you choose for billion-scale vector search?

2.7 Retrieval Metrics ★★

\[\mathrm{Recall@}k = \frac{|\mathrm{Rel} \cap \mathrm{Top}_k|}{|\mathrm{Rel}|}, \qquad \mathrm{MRR} = \frac{1}{|Q|} \sum_{i=1}^{|Q|} \frac{1}{\mathrm{rank}_i}\]
\[\mathrm{DCG@}k = \sum_{i=1}^{k} \frac{2^{\mathrm{rel}_i} - 1}{\log_2(i + 1)}, \qquad \mathrm{nDCG@}k = \frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k}\]

The three core metrics ★★

Recall@k measures "how much of what should be found was found". \(\mathrm{Rel}\) is the set of all documents relevant to the query, \(\mathrm{Top}_k\) is the system's top \(k\) results, and Recall@k is the fraction of relevant documents that appear in the top \(k\). It ignores the order within the top \(k\). Open-domain QA often uses a looser version called top-k accuracy or hit rate: it scores 1 if at least one relevant document is in the top \(k\), and 0 otherwise (this is what DPR reported). Its complement is Precision@k, the fraction of the top \(k\) that is relevant.

MRR (Mean Reciprocal Rank) looks only at where the first relevant document is ranked. \(\mathrm{rank}_i\) is the position of the first relevant result for query \(i\); take its reciprocal and average over all \(|Q|\) queries. A first relevant document at rank 1 scores 1, at rank 3 scores 1/3, and if none is found, 0. It suits cases with "only one correct answer" or where "users look only at the first result", but it ignores the positions of all other relevant documents.

nDCG (normalized Discounted Cumulative Gain) is the most fine-grained, accounting for both degree of relevance and position. \(\mathrm{rel}_i\) is the relevance grade of the document at position \(i\) (e.g. 0 = irrelevant, 1 = partly relevant, 2 = relevant, 3 = highly relevant). The numerator \(2^{\mathrm{rel}_i} - 1\) is the gain, which uses an exponent to amplify the value of highly relevant documents (some implementations use \(\mathrm{rel}_i\) directly as the gain); the denominator \(\log_2(i+1)\) is the position discount, so the lower a document ranks, the more its contribution is discounted. Summing "gain over discount" across the top \(k\) gives DCG@k. Since queries have different numbers of relevant documents, DCG values can't be compared directly, so we divide by IDCG@k, the maximum DCG achievable by sorting documents from most to least relevant; nDCG then lies between 0 and 1. A simple example: with a single relevant document (\(\mathrm{rel} = 1\)), DCG is 1 if it's ranked first, but only \(1/\log_2 4 = 0.5\) if it's ranked third.

Interview questions

  • ★★ Write the nDCG formula and explain the gain, the discount and the normalization.
  • ★ What do MRR and Recall@k each measure?

Which metric for RAG ★★

Different settings call for different metrics. In RAG, the generator reads every chunk placed in the prompt, so what matters most is whether the needed chunks make it into the top-k, where \(k\) should equal the number actually placed in the prompt; that is Recall@k (or hit rate). But order isn't irrelevant: content in the middle is more easily ignored by the model (see Chapter 3), and anything beyond the length budget gets truncated, so MRR and nDCG are useful secondary metrics. When evaluating a reranker, nDCG@10 or MRR@10 is typical, since its whole job is to put the best documents first.

Public benchmarks have their own conventions: MS MARCO passage ranking reports MRR@10; BEIR and MTEB retrieval report nDCG@10; open-domain QA such as Natural Questions reports top-20 and top-100 accuracy. These evaluations need labeled relevance judgments (qrels). Note that labels are often incomplete: every unlabeled document counts as irrelevant, so a good system that finds relevant but unlabeled documents is actually underrated. LLMs are now also commonly used to judge relevance in bulk; this is covered together with end-to-end RAG evaluation in Chapter 7. Also remember that retrieval metrics and final answer quality don't line up perfectly: higher recall that drags in many distractors can make the final answer worse (see Chapter 1).

Interview questions

  • ★★ When is each of Recall@k, MRR and nDCG appropriate, and which matters most for RAG?
  • ★ How do incomplete labels affect retrieval evaluation?

2.8 Modern Embedding Models ★

The standard training recipe ★

DPR was trained on a single QA dataset and didn't transfer to other domains. Today's general-purpose embedding models (e.g. E5, Wang et al. 2022; GTE, Li et al. 2023; BGE, Xiao et al. 2023) mostly use two-stage training. Stage one is weakly supervised contrastive pretraining: collect huge numbers of naturally paired texts from the web, such as (title, body), (forum question, best answer), (post, comment) and (paper, a sentence citing it), up to hundreds of millions of pairs, and train contrastively with in-batch negatives and very large batches. This data is noisy but extremely broad, so the model learns general semantic similarity. Stage two is supervised fine-tuning: continue training on high-quality labeled data (such as MS MARCO, Natural Questions and NLI) with mined hard negatives, sometimes with distillation from a cross-encoder. The backbone is usually a BERT-sized encoder, with mean pooling or the [CLS] vector as the output.

These models are usually evaluated on MTEB (Muennighoff et al. 2022), which covers 8 task types, including retrieval, reranking, clustering, classification and semantic textual similarity (STS), across dozens of datasets, aiming to measure whether an embedding model is truly "general". Still, the leaderboard is only a reference; evaluating on your own data is what counts (see Chapter 1).

Interview questions

  • ★ How are modern general-purpose embedding models usually trained?

Instruction-tuned embeddings ★

What "similar" means depends on the task. For retrieval, a question should be close to its answer; for duplicate-question detection, it should be close to another question with the same meaning; for classification, grouping by topic and grouping by sentiment need entirely different notions of similarity. One fixed embedding can't serve all of these. INSTRUCTOR (Su et al. 2022) prepends a natural-language instruction describing the task and domain, such as "Represent the medical question for retrieving supporting documents:", and trains on many instruction-tagged tasks, so the same model produces vectors suited to different tasks depending on the instruction. Most later models put the instruction only on the query side and leave documents without one, so documents are encoded once and reused across tasks. When using such a model, always follow the instruction format it was trained with, or quality drops noticeably.

Interview questions

  • ★ Why do embedding models use instructions, and which side are they added to?

LLM-based embeddings ★

Starting in 2024, most of the top models on MTEB switched to decoder-only LLMs as the backbone. E5-Mistral (Wang et al. 2023) is a representative: it used proprietary LLMs to generate synthetic training data covering 93 languages and hundreds of thousands of tasks, and fine-tuned an open decoder-only LLM with a standard contrastive loss for fewer than 1,000 steps to reach strong results, without the huge weakly supervised pretraining stage. NV-Embed (Lee et al. 2024) removes the causal mask during contrastive training so every token sees the whole input, and uses a latent attention layer for pooling; training has two stages, first contrastive instruction tuning on retrieval data, then mixing in non-retrieval tasks. LLM2Vec (BehnamGhader et al. 2024) proposed a way to turn a decoder LLM into an encoder without labeled data: enable bidirectional attention, then adapt with masked prediction and unsupervised contrastive learning.

There's a specific technical question here: how do you get one sentence vector out of a decoder? Under causal attention, only the last token has seen the whole input; earlier tokens have seen only a prefix. Mean pooling over all tokens, as with BERT, mixes in many representations that "haven't finished reading the sentence". So there are two common approaches: append an [EOS] and take the last token's hidden state (what E5-Mistral does), or switch to bidirectional attention and then pool, as NV-Embed and LLM2Vec do.

The benefits of LLM embeddings are the richer knowledge and language understanding from pretraining, strong multilingual ability, inputs of thousands of tokens, and better instruction following. The cost is that they're expensive: a 7B encoder needs dozens of times the compute of BERT-base per text, vectors are often 4,096-dimensional, and storage and search cost more too; when indexing hundreds of millions of documents, the difference is dramatic. So a common division of labor in practice: use a small model for very large corpora and latency-sensitive settings, and LLM embeddings when quality matters most, truncating vectors to save cost when needed. (Matryoshka representation learning (Kusupati et al. 2022) trains vectors so that their first 64, 128, 256… dimensions are each a usable embedding on their own, so you can simply truncate them, rank coarsely with short vectors and then refine with full ones.)

Interview questions

  • ★ How do you pool a decoder-only LLM into an embedding, and why not just use mean pooling?
  • ★ What are the pros and cons of LLM-based embeddings versus BERT-sized models?

2.9 Query–Document Asymmetry ★

Queries and documents look very different in retrieval. A query is usually short, a few words, often a question or a list of keywords, and possibly incomplete; a document is much longer, declarative, and contains the answer along with lots of other content. More importantly, a question and its answer are not similar in the sense of "meaning the same thing". "Why do we have seasons?" and "The Earth's axis is tilted by about 23.4 degrees, so different hemispheres receive different amounts of sunlight during its orbit…" share almost no words and have completely different sentence structures. A model trained on symmetric tasks like paraphrase or semantic textual similarity (STS) would judge another question, "How are the seasons formed?", to be more "similar" than the answer passage, and rank someone else's question above the answer. So retrieval needs to learn relevance, not similarity.

There are several common ways to handle this asymmetry:

  1. Train on asymmetric data. Train on (query, relevant passage) pairs rather than only paraphrase pairs, so the model learns that "a question should sit close to its answer".
  2. Mark the roles. DPR simply uses two separate encoders for queries and passages. More common today is a shared encoder with role markers on the input: E5 expects query: in front of queries and passage: in front of documents, while instruction-style models put a task instruction only in front of the query. Shared parameters generalize better and halve the parameter count; the role marker tells the model "is this input a question or a document". Leaving out the prefix at use time mismatches the training conditions and noticeably hurts quality. Conversely, for symmetric tasks such as deduplication or clustering, both sides should use the same prefix (E5 recommends query: on both).
  3. Bridge the gap on the query side or the document side. On the query side, an LLM can first write a hypothetical answer and use it for retrieval, turning "question finds answer" into "answer finds answer" (HyDE, see Chapter 3). On the document side, generate a few questions each chunk can answer and index them along with it, turning "question finds answer" into "question finds question" (this is the idea behind doc2query).
  4. Length asymmetry. The longer a document, the harder it is for one vector to represent everything in it, while a query usually cares about only a small part. This is one more reason chunks shouldn't be too large (see Chapter 1), and why token-level matching like ColBERT has an edge on long documents.

Interview questions

  • ★★ What is query–document asymmetry, and why do embedding models distinguish queries from passages?
  • ★ Why might a model that does well on semantic similarity (STS) not do well at retrieval?