Skip to content

Chapter 1 · Retrieval

1.1 How does BM25 score documents, and what are the pros and cons of sparse retrieval? ★★

One-sentence answer

For each word in the query, BM25 computes "IDF × a saturated, length-normalized term frequency" and sums the scores over words: IDF rewards rare words, \(k_1\) makes the gain from term frequency saturate, and \(b\) lowers the score of documents longer than average. Sparse retrieval is very fast thanks to the inverted index, needs no training, is strong at exact matching and robust across domains; its fundamental limit is that it matches words, not meanings, so it cannot handle synonyms and rephrasing (vocabulary mismatch).

I will address three aspects: the path from TF-IDF to BM25, what the two hyperparameters of BM25 do, and the strengths, limits and improvements of sparse retrieval.

(1) Sparse retrieval represents text as a sparse vector over the vocabulary and relies on an inverted index for fast search.

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):

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

Here \(\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. 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. However, TF-IDF has two obvious flaws: the contribution of term frequency is linear, so a word that appears 20 times scores 10 times as much as one that appears twice, which makes no sense and is easy to game by keyword stuffing; and it ignores document length, so long documents, which naturally contain more words and more repetitions, get an unfair advantage. BM25 was designed to fix exactly these two problems.

(2) BM25 adds term-frequency saturation and length normalization on top of TF-IDF.

\[ \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. Here \(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 total number of documents, \(n(t)\) is the number of documents containing \(t\), and \(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}\). As \(f\) grows the score rises, but more and more slowly, approaching the ceiling \(k_1 + 1\). This matches intuition: the first occurrence of a word tells us "this document is about this word" and carries the most information, whereas by the tenth repetition almost nothing new is added. 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, so keyword stuffing stops working. \(k_1\) controls how fast saturation happens, and 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, because a word appearing a few more times in a long document may just reflect its length rather than greater relevance. \(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 should not be penalized too hard.

(3) Sparse retrieval's strengths are precision, no training and robustness; its fundamental limit is vocabulary mismatch.

  • Strengths: For exact matching, rare strings such as product model numbers, names, error codes (such as E1023), function names and legal clause numbers have high idf, so BM25 weights them heavily, while dense models often blur them with other strings that "look similar"; it needs no training and works out of the box in a new domain; and 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, with many dense retrievers trained only on MS MARCO doing worse than BM25 in new domains. It is also interpretable (you can see which words matched), fast and memory-light.
  • Limits: Its fundamental problem 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 cannot match them; it also ignores word order and negation, so "dog bites man" and "man bites dog" get the same score.
  • 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: SPLADE (Formal et al. 2021) uses a model to learn a weight for every word in the vocabulary, so that related words that do not appear in the document can still receive weight, while the representation stays sparse and can still be searched with an inverted index (how it works is in "Going deeper" below).

In summary: BM25 is a baseline that needs no training yet is hard to beat; its errors are complementary to those of dense retrieval, which is the starting point for hybrid retrieval (see 1.4).

Going deeper: the numbers behind saturation, an example of length normalization, and how SPLADE works

(1) With \(k_1 = 1.2\), the gain from term frequency saturates quickly.

One occurrence gives 1.0, two give about 1.38, and even ten give only about 1.96, never exceeding \(k_1 + 1 = 2.2\). With \(k_1 = 0\) only presence matters (binary); with a very large \(k_1\) the score approaches raw linear term frequency.

(2) The intuition behind length normalization.

A 10,000-word document mentioning "transformer" 5 times may be less on-topic than a 200-word one mentioning it 3 times. What \(b\) does is discount a document's term frequency according to its length relative to the average. Lucene and Elasticsearch default to \(k_1 = 1.2\) and \(b = 0.75\).

(3) How SPLADE achieves both "semantic expansion" and "sparsity".

SPLADE feeds the text through BERT and uses the MLM head to compute, at every position, a logit for every word in the vocabulary; these are passed through \(\log(1 + \mathrm{ReLU}(\cdot))\) and aggregated over all positions (summed in the original version, max-pooled in SPLADE v2), giving a weight vector over the vocabulary. Because the MLM head also assigns probability to semantically related words, "car" can receive weight in the representation of a document about "automobiles" even though it never appears there, which amounts to automatic term expansion. Training adds a sparsity-encouraging regularizer (FLOPS regularization) that drives almost all word weights to 0, so the representation stays sparse and can 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 with BM25.

Follow-up questions

Follow-up 1: With dense retrieval available, is BM25 still useful?

Yes, and it is usually a standard component of production systems. BM25 is good at exact literal matching, needs no training and is robust across domains, which covers exactly the weak spots of dense retrieval on rare entities, numbers and code identifiers; the two fail in different places, so they are often combined into hybrid retrieval (see 1.4). BM25 is also the most common tool for mining hard negatives (see 1.2) and the standard baseline for evaluating new retrievers.

Follow-up 2: How does learned sparse retrieval (e.g. SPLADE) differ from BM25 and from dense retrieval?

Its representation has the same form as BM25's, but its word weights are learned, as in a dense model. Compared with BM25, its weights come from a neural network and can be assigned to related words absent from the document, which eases vocabulary mismatch; compared with dense retrieval, its vector is a sparse vector over the vocabulary in which each dimension corresponds to a specific word, so it is interpretable and can reuse inverted-index infrastructure. The cost is that it must be trained, and encoding is slower than with BM25.

Follow-up 3: What does BM25 reduce to when \(k_1\) and \(b\) take extreme values?

With \(k_1 = 0\) it reduces to "the sum of the IDFs of the matched query words", and with \(b = 0\) document length is no longer considered. With \(k_1 = 0\) the fraction equals 1 whenever the word appears, so term frequency no longer matters; with a very large \(k_1\) term frequency becomes nearly linear, bringing back TF-IDF's problem; with \(b = 1\) normalization is fully by relative length, and long documents are penalized the most.

Common mistakes

  • Do not say that term frequency contributes linearly in BM25: It saturates, with a ceiling of \(k_1 + 1\).
  • Do not say that dense retrieval has surpassed BM25 across the board: In cross-domain and exact-match settings, BM25 is still a strong baseline.
  • Do not say that BM25 handles synonyms: It matches literal words only, which is precisely the vocabulary-mismatch problem.
  • Do not say that \(b\) penalizes all long documents: It adjusts only according to length relative to the average, and the default value normalizes only partially.

1.2 How is a dense retriever (two-tower model) trained? ★★★

One-sentence answer

A two-tower model encodes queries and documents separately into vectors, scores them with a dot product or cosine, and is trained with contrastive learning: for each query, the positive should get as high a probability as possible in a softmax over "one positive plus several negatives", which is the InfoNCE loss. The negatives are usually nearly free in-batch negatives plus a few hard negatives: the former supply quantity through large batches, the latter supply truly discriminative gradients, but false negatives among them must be guarded against.

I will address five aspects: the two-tower structure, the InfoNCE loss and temperature, in-batch negatives, hard negatives, and false negatives.

(1) A two-tower model encodes queries and documents separately, so document vectors can be computed offline.

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) = E_Q(q)^\top E_P(p)\). This structure of separate encoding is called a bi-encoder (two-tower model). Precisely because document encoding does not depend on the query, DPR could split Wikipedia into about 21 million 100-word passages, encode them all offline, and at query time encode the question once and run one maximum inner product search (MIPS). DPR's main finding was that training only on question–answer-passage pairs was enough for dense retrieval to beat BM25 by a wide margin on open-domain QA, with top-20 retrieval accuracy 9 to 19 points higher. The advantage of dense retrieval is semantic matching: "Who wrote Hamlet?" can match "This tragedy by Shakespeare…" even without shared keywords; however, 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 also needs training data and may degrade noticeably in unseen domains, and whenever the encoder is updated, the whole index must be rebuilt.

(2) The training objective is the InfoNCE contrastive loss, and the temperature determines which negatives the model focuses on.

\[ \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)} \]

For a query \(q\), take one relevant document \(p^+\) (the positive) and \(n\) irrelevant documents \(p_1^-, \dots, p_n^-\) (the negatives); \(s(\cdot, \cdot)\) is the similarity (dot product or cosine) and \(\tau\) is the temperature. This is the InfoNCE loss (van den Oord et al. 2018), 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 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). Looking further 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; therefore 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, which is exactly why hard negatives are needed later on.

(3) In-batch negatives make negatives nearly free, and the larger the batch, the stronger the contrastive signal.

\[ 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) \]

A batch holds \(B\) (query, positive) pairs; \(Q\) and \(P\) are the \(B\) query vectors and the \(B\) positive vectors stacked as rows, and one matrix multiplication gives the \(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. These negatives are almost free, because 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). However, in-batch negatives 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.

(4) Hard negatives supply truly discriminative gradients.

A hard negative is a document that looks very similar to the query but is not actually relevant. By the gradient analysis above, 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 do not match. There are three common ways to mine them:

  • Mining with BM25: Take passages ranked high by BM25 that do not contain the answer. DPR found that adding just one such BM25 negative per question on top of in-batch negatives clearly improved results.
  • Mining with the current model: 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".
  • Mining with a stronger model: For example, selecting negatives by cross-encoder scores.

(5) False negatives are the biggest risk of hard negatives, so the negatives must be denoised.

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. As a result, quite a few mined "hard negatives" are actually unlabeled positives, and training on them punishes the model for doing the right thing; moreover, the "harder" a negative is, the more likely it is a false negative. 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 denoised hard negatives.

In summary: the core of training a dense retriever is using contrastive learning to separate the positive from the negatives, and quality depends mainly on the quality of the negatives: in-batch negatives supply quantity, hard negatives supply difficulty, and denoising keeps the labels correct.

Comparing three sources of negatives:

Source of negatives Cost Difficulty Main risk
In-batch negatives Almost zero; reuses other queries' positives in the batch Mostly too easy Batch size is limited by memory; duplicate documents create false negatives
BM25 mining One offline retrieval pass Medium; lexically similar May include unlabeled positives
Mining with the current model or a cross-encoder Periodic index rebuilds or extra scoring High; exactly what the model confuses most Highest share of false negatives; denoising is essential

Going deeper: the gradient derivation, the mutual-information bound, and common training settings

(1) The gradient of InfoNCE.

Write \(s_+ = s(q, p^+)\) and \(s_j = s(q, p_j^-)\), with softmax probabilities \(p_+ = \exp(s_+/\tau) / Z\) and \(p_j = \exp(s_j/\tau) / Z\), where \(Z\) is the denominator. The loss can be written as:

\[ \mathcal{L} = -\frac{s_+}{\tau} + \log Z, \qquad \frac{\partial \mathcal{L}}{\partial s_j} = \frac{p_j}{\tau}, \qquad \frac{\partial \mathcal{L}}{\partial s_+} = -\frac{1 - p_+}{\tau} \]

So the positive is pulled up in proportion to how much probability it still "lacks", and each negative is pushed down in proportion to how much probability it holds. Once the positive holds nearly all the probability, the whole example stops producing gradient.

(2) InfoNCE and mutual information.

van den Oord et al. (2018) showed that minimizing InfoNCE maximizes a lower bound on the mutual information between the query and the positive: \(I(q; p^+) \ge \log(n+1) - \mathcal{L}\), where \(n+1\) is the total number of candidates. The more candidates, the tighter this bound, which gives a theoretical explanation for why more negatives usually help.

(3) Typical temperature values.

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\); there the vector norms themselves provide the scaling.

(4) Scaling up the number of negatives under limited memory.

Besides gathering vectors across GPUs, one can keep document vectors from several previous batches in a MoCo-style queue (He et al. 2019) as extra negatives, or use gradient caching (GradCache, Gao et al. 2021), which splits a large batch into small chunks computed separately, so that a very large effective batch is still possible with limited memory.

Follow-up questions

Follow-up 1: Why does cosine similarity need a fairly small temperature?

Because the range of cosine is too narrow; without scaling, the softmax is nearly uniform. Cosine lies only in \([-1, 1]\), so the gap between positive and negative scores is at most 2, the differences after \(\exp\) are small, the positive's probability cannot approach 1, and the gradients are weak. Dividing by a temperature of 0.01 to 0.05 amplifies score gaps by 20 to 100 times, which makes the softmax sharp enough and lets the model focus on the hardest negatives.

Follow-up 2: How can you train a dense retriever without labeled data?

Construct positives from the same document. Contriever (Izacard et al. 2021) randomly crops two spans from one document (independent cropping) 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, and a MoCo-style queue provides many of them. On BEIR, this fully unsupervised model beat BM25 in Recall@100 on 11 of 15 datasets, and using it as a starting point and fine-tuning on a little labeled data improves results further. The idea was later absorbed into the weakly supervised pretraining stage of general-purpose embedding models (see 1.8).

Follow-up 3: Does single-vector dense retrieval have theoretical limits?

Yes, though the limit concerns which combinations of relevance can be expressed, not only data or model size. Weller et al. (2025) proved that the number of distinct top-k document subsets a \(d\)-dimensional embedding can return is bounded by the dimension \(d\), and that even optimizing the vectors directly as free parameters on the test set cannot break this; based on it they built the LIMIT dataset, whose queries are very simple (along the lines of "who likes X") but whose required document combinations are very diverse, and the strongest single-vector embedding models of the time all performed poorly on it, worse the lower their dimension, while BM25 got it almost entirely right and multi-vector models did clearly better. However, follow-up work (Archish S et al. 2026) pointed out that LIMIT's sparse structure in theory requires only a very low dimension, and that the failure of single-vector models comes more from domain shift and from a mismatch between cosine similarity and relevance, which fine-tuning partly fixes, at the cost of catastrophic forgetting that is much worse for single-vector models than for multi-vector ones. The safer conclusion is therefore that single-vector representations do have an expressive ceiling, which is easier to hit when a query must satisfy several conditions at once; this is why multi-vector ColBERT (see 1.3), cross-encoder reranking (see 1.5) and sparse retrieval remain valuable.

Follow-up 4: Where do false negatives among in-batch negatives come from, and how are they handled?

They arise when two queries in a batch share the same or a near-identical positive document. In that case another query's positive is also my positive, yet it is penalized as a negative. The usual fixes are deduplicating when building batches, or masking the columns of the similarity matrix that are identical or highly similar to a query's own positive.

Common mistakes

  • Do not say that InfoNCE is a binary classification loss: It is an \((n+1)\)-way cross-entropy over a softmax of the positive and all negatives.
  • Do not say that the harder the negative, the better: The harder a negative, the more likely it is an unlabeled positive, so denoising is required.
  • Do not say that random negatives alone are enough: Easy negatives produce almost no gradient, so fine distinctions are never learned.
  • Do not say that the temperature is an unimportant scaling factor: It determines how sharp the softmax is and which negatives the model focuses on.
  • Do not say that in-batch negatives require encoding extra documents: They reuse vectors already computed in the batch, at almost no extra cost.

1.3 What is ColBERT's late interaction? ★

One-sentence answer

ColBERT keeps one vector per token; at scoring time each query token finds its most similar token among all of the document's tokens (MaxSim), and these maximum similarities are summed. Because document encoding still does not depend on the query and can be computed offline, the two interact only in this final, cheap computation, hence "late interaction". It is more accurate than a single vector and generalizes better across domains, at the cost of a much larger index.

I will address three aspects: how MaxSim is computed, why it is called late interaction and why it is more accurate, and its cost and engineering practice.

(1) Instead of squeezing the text into one vector, ColBERT uses MaxSim for token-level matching.

A bi-encoder squeezes a whole document into one vector and easily loses details; a cross-encoder (see 1.5) lets the query and document interact fully, which is accurate but cannot be precomputed. ColBERT (Khattab & Zaharia 2020) takes a middle path: 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\) finds the most similar of all the document's token vectors \(\mathbf{d}_j\), and the results are summed over all query tokens:

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

Here \(|q|\) and \(|d|\) are the numbers of tokens in the query and the document.

(2) It is called late interaction because the interaction happens only at the last step, and token-level matching makes it more accurate than a single vector.

Document encoding still does not 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 the final, cheap MaxSim step, not inside every Transformer layer as in a cross-encoder, hence late interaction. It is 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 is not washed out by the average meaning of the whole passage. As a result, its zero-shot generalization on cross-domain benchmarks like BEIR is clearly better than that of single-vector models, and it also does much better than single-vector models on datasets like LIMIT that require combinatorial matching (see 1.2).

(3) Its main cost is storage, which engineering keeps in check through compression and two-step retrieval.

A 100-token passage needs 100 vectors instead of 1, so the index is more than an order of magnitude larger than a single-vector one. ColBERTv2 (Santhanam et al. 2021) used residual compression to cut storage by 6 to 10 times, and the PLAID engine (Santhanam et al. 2022) 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.

In summary: with "one vector per token plus MaxSim at the last step", ColBERT keeps the ability to encode offline while gaining token-level matching precision, and sits between bi-encoders and cross-encoders in both quality and cost.

Going deeper: the storage budget, training, and multimodal extensions

(1) The storage budget.

A single-vector model stores one vector per passage, say a 768-dimensional one; ColBERT stores one 128-dimensional vector per token, so a 100-token passage has \(100 \times 128 = 12800\) dimensions in total, about 17 times as many, and 100 times as many vectors. The larger number of vectors also inflates the overhead of the ANN index itself, which is why ColBERTv2 focused on compression.

(2) Training and details.

ColBERT is also trained with contrastive learning; ColBERTv2 additionally distills from cross-encoder scores and uses denoised supervision with hard negatives. The original ColBERT also pads queries to a fixed length with [MASK] tokens (query augmentation), and the vectors at these [MASK] positions act as a soft query expansion.

(3) The same idea has been applied to images of document pages and to multimodal embeddings.

ColPali (Faysse et al. 2024) splits the image of a document page into patches, gives each patch a vector, and matches them against query tokens with MaxSim, removing the need for OCR and layout parsing; jina-embeddings-v4 (Günther et al. 2025) offers both single-vector and multi-vector outputs in the same model.

Follow-up questions

Follow-up 1: How does ColBERT compare with bi-encoders and cross-encoders in cost and quality?

It sits in the middle on both. Compared with a bi-encoder, it can likewise encode documents offline, but it is more accurate and generalizes better, at the cost of an index more than an order of magnitude larger; compared with a cross-encoder, it does not need a full model run per candidate and is much faster, but because interaction happens only at the last step, its precision is generally below that of a cross-encoder (the four scoring approaches are compared in 1.5).

Follow-up 2: How does ColBERT avoid computing MaxSim against every document?

Find candidates with ANN first, then score only the candidates exactly. For each query token vector, run an ANN search over all documents' token vectors; the documents that own the hit tokens form the candidate set, and full MaxSim is computed only for them. PLAID further uses centroids of the token vectors to prune irrelevant candidates quickly, which substantially reduces latency.

Follow-up 3: Why does MaxSim go from the query to the document rather than being symmetric?

Because retrieval cares about "whether each need in the query is satisfied by the document". Taking, for each query token, its maximum similarity in the document and summing measures how well the document covers the query, and the rest of the document's content that is unrelated to the query does not lower the score. Summing in the other direction, from the document to the query, would let the many unrelated tokens of a long document affect the score, which does not match what retrieval needs.

Common mistakes

  • Do not say that ColBERT is a cross-encoder: Its document encoding does not depend on the query and can be computed offline.
  • Do not say that MaxSim averages the similarities of all token pairs: It takes, for each query token, the maximum similarity in the document, and then sums.
  • Do not ignore its storage cost: With one vector per token, the index is more than an order of magnitude larger than a single-vector one.

1.4 How does hybrid retrieval fuse results, and what is RRF? ★★

One-sentence answer

Hybrid retrieval runs BM25 and dense retrieval in parallel and fuses the two ranked lists into one; because the two fail in different places, the merged recall is higher than either alone. Their scores are on different scales and cannot simply be added: either normalize and then weight them (a convex combination), or use RRF, which fuses by rank only, \(\mathrm{RRF}(d)=\sum_r 1/(k+\mathrm{rank}_r(d))\), with the constant \(k\) usually set to 60. Without labeled data RRF is a safe default; with a small labeled set, a tuned weighted fusion is usually better.

I will address four aspects: why combine, why scores cannot simply be added, how RRF works, and the trade-off between the two fusion methods.

(1) BM25 and dense retrieval fail in different places, so merging them raises recall.

BM25 is good at exact literal matching (error codes, model numbers, names, identifiers in code) but does not understand synonyms or rephrasing; dense retrieval is good at semantic matching but insensitive to rare strings and exact numbers. Precisely because the two fail in different places, 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.

(2) Simply adding the scores does not work, because the two retrievers' scores are on completely different scales.

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. If they are added directly, BM25 dominates. 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), where \(\alpha\) is the weight of dense retrieval. This keeps information about score magnitudes, but \(\alpha\) needs tuning, and min-max normalization is easily skewed by a few extreme scores.

(3) RRF uses only ranks and flattens the top of the list with the constant \(k\), so it rewards documents that appear in several lists.

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

Reciprocal Rank Fusion (RRF, Cormack et al. 2009) ignores scores altogether and uses only ranks. Here \(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), the term is 0 if \(d\) is missing from a list, and \(k\) is a smoothing constant, usually 60 (not the same as the \(k\) in top-k). There are two intuitions behind it: it uses only ranks, so there is no scale problem at all, and neither training nor tuning is needed; at the same time, \(k\) "flattens" the top of the list, so with \(k = 60\) the top few positions score almost the same, and appearing in several lists therefore matters more than ranking 1st in one. For example, if document A ranks 1st in BM25 only and document B ranks 5th in both lists, B's RRF score is about twice A's and it comes out ahead; with a very small \(k\), by contrast, the top-ranked document would dominate.

(4) RRF is safe but discards score information; with labeled data, a tuned weighted fusion is usually better.

RRF's drawback is that it throws away the information in the scores: a top result one retriever is very sure about and a top result 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 is therefore: 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 2).

In summary: the value of hybrid retrieval comes from the complementary errors of the two retrievers; to fuse them, either use ranks (RRF) to sidestep the scale problem, or normalize and tune the weights with a small amount of labeled data.

Comparing the two fusion methods:

Normalized weighting (convex combination) RRF
Information used Score magnitudes Ranks only
Tuning needed The weight \(\alpha\), which relies on a little labeled data Usually just \(k = 60\)
Pros Keeps confidence information; better once tuned No scale problem; works out of the box; robust
Cons Normalization is sensitive to extreme scores Discards score information; somewhat sensitive to \(k\)

Going deeper: a numerical example of RRF, and the role of \(k\)

(1) A numerical example.

With \(k = 60\), rank 1 earns \(1/61 \approx 0.0164\) and rank 10 earns \(1/70 \approx 0.0143\), a difference of only about 13%. 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.

(2) The smaller \(k\), the more weight the top positions carry.

With \(k = 0\), rank 1 earns 1, rank 2 earns 0.5 and rank 10 only 0.1, so the fused result is decided almost entirely by the top document in each list; the larger \(k\), the smaller the differences between positions, and the more the fusion favors "how many lists a document appears in". \(k = 60\) is the empirical value chosen in the experiments of Cormack et al. (2009) and widely adopted since.

(3) Fusion is usually followed by reranking.

Fusion improves recall, but the ordering remains fairly coarse. The Contextual Retrieval experiments (see Chapter 0, 0.4) also show that adding a reranker on top of hybrid retrieval lowers the retrieval failure rate substantially further.

Follow-up questions

Follow-up 1: What does the constant \(k\) in RRF do, and how does its value matter?

It controls how large the advantage of the top positions is. With a small \(k\), the top-ranked document scores far above the others, and the fused result approaches "whoever ranks at the top wins"; with a large \(k\), the positions score similarly, and fusion mainly rewards documents that appear in several lists. The common \(k = 60\) keeps the top positions close, thereby favoring "consensus across retrievers".

Follow-up 2: How does RRF handle a document that appears in only one list?

It contributes 0 for the list it is missing from, and only the term where it appears is added. This is exactly why RRF favors consensus: a document found by both retrievers receives two contributions. As a result, how many candidates each retriever returns (the top-N) also affects the outcome; if N is too small, many documents appear in only one list.

Follow-up 3: In what settings does hybrid retrieval help most?

Settings with lots of terminology, identifiers, or domain shift. Examples are error codes and function names in technical documentation, legal clause numbers, and medical terms and drug names, which are weak spots of dense retrieval and strengths of BM25; conversely, where users phrase things colloquially and their wording differs a lot from the documents, dense retrieval makes up for BM25. The less the two retrievers' errors overlap, the larger the benefit of combining them.

Common mistakes

  • Do not add BM25 scores and cosine scores directly: They are on different scales, and BM25 would dominate.
  • Do not confuse the \(k\) in RRF with the \(k\) in top-k: The former is a smoothing constant, usually 60.
  • Do not say that RRF is always the best fusion method: With a little labeled data, a tuned weighted fusion is usually better.
  • Do not say that reranking is unnecessary after hybrid retrieval: Fusion raises recall; precision still relies on a reranker.

1.5 Why do rerankers improve quality, and how do cross-encoders differ from bi-encoders? ★★

One-sentence answer

A bi-encoder encodes the query and the document separately and compares their vectors only once at the end; a cross-encoder concatenates the two and feeds them through a Transformer together, so they can attend to each other in every layer, which amounts to "reading the document with the question in mind" and is far more accurate. But its document representation depends on the query and cannot be pre-indexed, so it can only rescore the small set of candidates returned by first-stage retrieval; real systems therefore use a cascade in which "retrieval is for recall and reranking is for precision".

I will address four aspects: why a cross-encoder is more accurate, why it cannot be used for retrieval directly, how rerankers are trained, and reranking with LLMs.

(1) A cross-encoder lets the query and document interact in every layer, so it "reads the document with the question in mind".

\[ 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. When a bi-encoder encodes a document, it does not know what the query will be, so it can only squeeze the document into a "general-purpose" vector and hope it is useful for every possible question, which is essentially a guess; a cross-encoder instead 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.

(2) A cross-encoder cannot be pre-indexed, so it can only be applied to a small set of candidates, which leads to a cascade.

Because the document's representation depends on the query, a cross-encoder cannot 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, whereas a bi-encoder only encodes the query once and runs one vector search. Real systems therefore use a cascade: BM25 or a bi-encoder quickly recalls around the top 100, a cross-encoder rescores those candidates, 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.

(3) Rerankers can be trained with pointwise or listwise losses, and a trained reranker is often used as a teacher.

  • Pointwise training: Binary classification on each (query, document) pair with binary cross-entropy, judging "relevant / not relevant".
  • Listwise training: Softmax cross-entropy over one positive and several hard negatives taken from the first-stage retriever, the same form as InfoNCE in 2.2.
  • Distillation as a teacher: A trained cross-encoder is often used as a teacher, distilling its scores into a bi-encoder, or used to denoise mined hard negatives (see 1.2).

(4) LLMs can also serve as rerankers; they are more flexible, but more expensive.

  • 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 the 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) works this way; 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 cannot do. The drawbacks are just as clear: high latency and cost, since one reranking call may process tens of thousands of tokens; sensitivity of listwise ranking to input order (position bias); and output that may be malformed, or miss or repeat IDs. In practice, therefore, a large model's ranking ability is often distilled into smaller open models (e.g. RankZephyr, Pradeep et al. 2023), or LLM reranking is reserved for small candidate sets where precision matters most.

In summary: one rule underlies the four scoring approaches: 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. This is exactly where the industry's "multi-stage funnel" comes from: a cheap method recalls a few hundred candidates from a huge corpus, and progressively more expensive and more accurate models filter them stage by stage, each stage handling an order of magnitude fewer documents.

Comparing the four scoring approaches:

Bi-encoder ColBERT Cross-encoder LLM reranker
Query–document interaction Only one final dot product Token-level MaxSim at the end Full attention in every layer Full attention, plus instructions and reasoning
Documents encoded 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 relevance criteria
Typical role First-stage retrieval First stage or reranking Reranking the top ~100 Reranking the top ~20–100

Going deeper: rerankers in 2025, and rerankers that reason before scoring

(1) LLM-based pointwise rerankers have become the dominant form among open models.

For example, Qwen3-Reranker (Zhang et al. 2025) puts the instruction, query and document into a chat-formatted prompt, frames the relevance judgment as binary classification, and takes the score as the softmax over the next-token probabilities of "yes" versus "no". This approach exploits both the LLM's language understanding and the ease of parallelizing pointwise scoring.

(2) The benefit of reasoning rerankers is still debated.

Rank1 (Weller et al. 2025) distilled about 600,000 reasoning traces generated by DeepSeek-R1 on MS MARCO to train a reranker that first writes out its reasoning and then gives a relevance judgment; it performed strongly on reasoning-intensive retrieval benchmarks such as BRIGHT and on negation and instruction-following tasks. However, Jedidi et al. (2025) compared pointwise rerankers with and without reasoning under the same training setup and found that the reasoning process brought no general advantage. Reasoning rerankers are therefore better suited to settings where judging relevance genuinely requires multi-step reasoning, and in ordinary retrieval they may not be worth their extra generation cost (test-time compute in general is discussed in the Inference, Evaluation & Deployment direction, Chapter 4).

Follow-up questions

Follow-up 1: How do you set the number of candidates for reranking?

Trade off the reranker's recall ceiling against latency. A reranker can only reorder the candidates it is given and cannot recover documents missed by first-stage retrieval, so the candidate count sets the recall ceiling of reranking; but reranking latency grows linearly with the candidate count. In practice 50 to 100 is common; check on an evaluation set whether first-stage Recall@N is already high enough, and then adjust to the latency budget.

Follow-up 2: How can the position bias of LLM rerankers be mitigated?

Shuffle and rank several times, or switch to an order-insensitive approach. In listwise ranking, the same candidates in a different order can come back ranked differently; a common mitigation is to shuffle the candidates randomly several times and aggregate the results, or to use pointwise or pairwise scoring (pairwise can ask each pair twice with the positions swapped). Both cost more LLM calls.

Follow-up 3: How can a cross-encoder's scores be used to improve a bi-encoder?

There are two main uses: distillation and denoising. Distillation uses the cross-encoder's soft scores on candidates as training targets for the bi-encoder, so that the bi-encoder learns a finer relevance ordering; denoising uses the cross-encoder to identify mined hard negatives that are probably relevant and removes them from the negatives (as in RocketQA, see 1.2).

Common mistakes

  • Do not say that a cross-encoder can precompute document representations: Its document representation depends on the query, so it cannot be indexed.
  • Do not say that a reranker can recover documents missed by first-stage retrieval: It can only reorder the candidates it is given.
  • Do not say that LLM rerankers are always better than cross-encoders: They are more expensive, slower and position-biased, so the choice depends on the setting.
  • Do not say that reasoning rerankers are always better: Under the same training setup, the reasoning process brought no general advantage.

1.6 What approximate nearest neighbor (ANN) indexes are there, and how do HNSW and IVF-PQ work? ★★

One-sentence answer

Exact nearest-neighbor search compares the query with every vector and becomes unaffordable at scale; ANN trades a little recall for orders of magnitude of speed. IVF clusters with k-means first and searches only the nprobe nearest clusters at query time; PQ cuts each vector into segments and encodes each segment as one byte using a codebook of 256 centroids, which both compresses storage and allows distances to be computed by table lookup; HNSW builds a multi-layer proximity graph, descends greedily from the top layer and runs a beam search at the bottom, giving the best recall–latency trade-off but using the most memory. HNSW is common at moderate scale, and IVF-PQ or SSD-based graph indexes at billion scale.

I will address four aspects: why ANN is needed, how IVF narrows the search, how PQ compresses vectors, and how HNSW searches with a layered graph; I will then give guidance on choosing.

(1) The cost of exact search grows linearly with the size of the store, so ANN is needed to trade a little accuracy for speed.

Exact nearest-neighbor search compares the query with every vector in the store, costing \(O(Nd)\), where \(N\) is the number of vectors and \(d\) the dimension; 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 do not 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 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.

(2) IVF clusters first and then searches, using nprobe to trade recall against speed.

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. For example, with nlist = 1000 and nprobe = 10, only about 1% of the vectors are compared. 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 lies near a cluster boundary and was assigned to an adjacent cluster that was not probed. In addition, 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; and by itself it only cuts computation, without compressing vectors.

(3) PQ quantizes vectors segment by segment, which both compresses storage and allows fast distance computation by table lookup.

\[ \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 \(\mathbf{x}\) into \(m\) segments \(\mathbf{x}^{(1)}, \dots, \mathbf{x}^{(m)}\) of \(d/m\) dimensions each and runs k-means separately on each segment, learning a codebook of 256 centroids, where \(\mathbf{c}^{(j)}_{i}\) is the \(i\)-th centroid in the codebook of segment \(j\). When storing a vector, each segment records only which centroid it is closest to, an ID \(i_j\) from 0 to 255 that 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. For distances, PQ uses asymmetric distance computation: the query itself is not compressed; first compute the distance from each of its segments 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. The price is that it is 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 and then recompute exact distances with the original vectors (if they are stored). In practice 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.

(4) HNSW searches a multi-layer proximity graph greedily; it has the best recall–latency trade-off but uses the most memory.

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, and 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, 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. Its three main parameters are:

  • M: The number of edges per node. A larger M makes the graph denser and recall higher, but uses more memory.
  • efConstruction: The candidate list size during graph building. Larger gives a better graph but slower builds.
  • efSearch: The candidate list size at query time. Larger raises both recall and latency, and it can be adjusted per query.

HNSW's costs are high memory (it stores the full original vectors plus dozens of edges per node) and usually having to 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 also gets worse.

In summary: the choice of ANN index depends mainly on scale and memory budget: up to a few hundred thousand vectors brute force is enough; for millions to tens of millions with enough memory, use HNSW; at billion scale, use compressed indexes like IVF-PQ or SSD-based graph indexes.

Comparing the indexes:

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

Going deeper: parameter rules of thumb, the PQ distance formula, and billion-scale options

(1) Parameter rules of thumb.

IVF's nlist is usually a few times \(\sqrt{N}\); in HNSW each node's layer count follows an exponentially decaying distribution, so the number of nodes shrinks by roughly a constant factor with each layer up, and the total number of search steps grows roughly with \(\log N\).

(2) PQ's asymmetric distance.

\[ \|\mathbf{q} - \mathbf{x}\|^2 \approx \sum_{j=1}^{m} \big\|\mathbf{q}^{(j)} - \mathbf{c}^{(j)}_{i_j}\big\|^2 \]

Here \(\mathbf{q}^{(j)}\) is the \(j\)-th segment of the query and \(\mathbf{c}^{(j)}_{i_j}\) is the codebook centroid for the \(j\)-th segment of the stored vector. Each term on the right can be read directly from the precomputed \(m \times 256\) table, so one distance computation needs only \(m\) lookups and additions, with no multiplications.

(3) Options at billion scale and with less memory.

When the full vectors do not fit in memory, besides IVF-PQ, the graph index can be placed on SSD (as in DiskANN, Subramanya et al. 2019), keeping only compressed vectors in memory for navigation; vectors can also be scalar-quantized (e.g. float32 to int8, cutting memory to a quarter) or binary-quantized. Common libraries include FAISS (Johnson et al. 2017) and ScaNN (Guo et al. 2019).

Follow-up questions

Follow-up 1: Why are deletions and filtering hard for HNSW?

Because its search relies on the connectivity of the graph. Deleting a node outright would cut the paths that pass through it, so deletions are usually only marked: the search still passes through the node but does not return it; as deletions accumulate, the graph fills with "dead nodes" and search efficiency and quality both decline, so periodic rebuilds are needed. Strict metadata filtering has a similar problem: when few nodes are eligible, greedy search easily gets "disconnected" between the nodes that satisfy the filter, so dedicated filter-aware search or a fallback to brute force over the small subset is needed.

Follow-up 2: Which index would you choose for billion-scale vector search?

A compressed index or a disk-based index. A billion 768-dimensional float32 vectors take about 3 TB, so the full vectors cannot fit in memory, and indexes like HNSW that need everything in memory no longer apply. Common choices are IVF-PQ (each vector compressed to tens of bytes, with a small set of candidates re-ranked using the original vectors) or approaches like DiskANN that keep the graph on SSD, combined with sharding across multiple machines.

Follow-up 3: How do you judge an ANN index?

Look at latency, throughput and memory at a given recall. Recall is measured by ANN recall@k, the overlap with exact search; indexes and parameters are usually compared by plotting recall against queries per second (QPS), and the choice also weighs memory footprint, build time and support for incremental updates.

Common mistakes

  • Do not say that ANN returns the exact nearest neighbors: It is approximate search that trades a little recall for speed.
  • Do not say that IVF reduces memory: IVF only cuts computation; compressing storage requires PQ or quantization.
  • Do not say that HNSW needs training or that deletion is easy: It needs no training, but deletions can only be marked and periodic rebuilds are required.
  • Do not confuse ANN recall with retrieval recall: The former measures overlap with exact search results, the latter whether truly relevant documents were found.

1.7 Which metrics are used to evaluate retrieval? ★

One-sentence answer

The three most common are: Recall@k, the share of relevant documents that make it into the top \(k\); MRR, the reciprocal rank of the highest-ranked relevant document; and nDCG@k, which accounts for both relevance grade and a position discount and is normalized by the ideal ordering. In RAG, what matters most is whether the needed content is among the \(k\) chunks placed in the prompt, i.e. Recall@k or hit rate, with MRR and nDCG as secondary metrics; rerankers are usually evaluated with nDCG@10 or MRR@10.

I will address three aspects: the definitions of the three metrics, which one to look at in RAG, and common pitfalls in evaluation.

(1) The three core metrics measure "whether it was found", "where the top correct result ranks" and "how good the overall ordering is".

\[ \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} \]
  • 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).
  • MRR (Mean Reciprocal Rank): Looks only at where the highest-ranked relevant document is. \(\mathrm{rank}_i\) is the position of the highest-ranked relevant result for query \(i\); take its reciprocal and average over all \(|Q|\) queries: rank 1 scores 1, 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 top results", but it ignores the positions of all other relevant documents.
  • nDCG (normalized Discounted Cumulative Gain): Accounts for both degree of relevance and position. \(\mathrm{rel}_i\) is the relevance grade of the document at position \(i\) (e.g. 0 for irrelevant, 3 for highly relevant); the numerator \(2^{\mathrm{rel}_i} - 1\) is the gain, which uses an exponent to amplify the value of highly relevant documents; the denominator \(\log_2(i+1)\) is the position discount, so the lower a document ranks, the more its contribution is discounted. Since queries have different numbers of relevant documents, DCG values cannot be compared directly, so we divide by IDCG@k, the maximum DCG achievable by sorting documents from most to least relevant, which puts nDCG between 0 and 1.

(2) In RAG, what matters most is whether the needed chunks make it into the prompt, i.e. Recall@k.

The RAG 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 of chunks actually placed in the prompt; that is Recall@k (or hit rate). However, order is not entirely irrelevant: content in the middle is more easily ignored by the model (see Chapter 2), 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.

(3) Evaluation has two common pitfalls: incomplete labels, and retrieval metrics that do not track final answer quality.

  • Labels are often incomplete: Evaluation needs labeled relevance judgments (qrels), and 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 to supplement labels; this is covered together with end-to-end RAG evaluation in Chapter 6.
  • Retrieval metrics are not answer quality: Higher recall that drags in many distractors can make the final answer worse (see Chapter 0, 0.6). Retrieval metrics should therefore be read together with end-to-end answer quality.

In summary: Recall@k tells you whether it was found, MRR where the top correct result ranks, and nDCG how good the overall ordering is; in RAG, rely mainly on Recall@k, with \(k\) equal to the number of chunks actually placed in the prompt.

Going deeper: numerical examples and the conventions of public benchmarks

(1) A simple nDCG example.

With a single relevant document (\(\mathrm{rel} = 1\)), DCG is 1 if it is ranked first and only \(1/\log_2 4 = 0.5\) if it is ranked third. Since the ideal ordering puts it first, IDCG is 1, so nDCG is 1 and 0.5 respectively. Some implementations use \(\mathrm{rel}_i\) directly as the gain, which is identical for binary relevance.

(2) Precision@k is the complement of Recall@k.

Precision@k is the fraction of the top \(k\) results that are relevant. In RAG it roughly measures how much noise is in the prompt, the other side of Recall@k.

(3) Reporting conventions of public benchmarks.

Benchmark Usual metric Reason
MS MARCO passage ranking MRR@10 Most queries have only one labeled relevant passage
BEIR and MTEB retrieval tasks nDCG@10 Comparison across datasets, some with graded relevance
Open-domain QA such as Natural Questions Top-20 and top-100 accuracy It suffices that the retrieved results contain the answer

Follow-up questions

Follow-up 1: When are MRR and Recall@k each appropriate?

MRR suits settings that need only one correct result, Recall@k settings that need everything found. For example, in a search box users usually click only the top results, and in QA a single passage containing the answer may be enough, so MRR fits better; in RAG, all top-\(k\) results are handed to the generator, or the question needs information aggregated from several documents, so what matters is whether all relevant documents make it into the top \(k\), which is Recall@k.

Follow-up 2: How do incomplete labels affect retrieval evaluation?

They systematically underrate systems that find new relevant documents. In many datasets, relevance labels come from pools of results returned by earlier systems; if a new system finds relevant documents outside that pool, they count as irrelevant and the metric actually drops. This is especially unfair to dense retrievers, whose behavior differs a lot from earlier systems. Mitigations include labeling the new system's results additionally, or using LLMs for relevance judgments (see Chapter 6).

Follow-up 3: Why does nDCG divide by IDCG?

So that scores are comparable across queries. One query may have ten highly relevant documents and another only one, so the maximum DCG they can reach differs greatly; after dividing by each query's ideal DCG, nDCG falls between 0 and 1, where 1 means the ordering has reached the best possible result for that query, which is what makes averaging over all queries meaningful.

Common mistakes

  • Do not say that Recall@k cares about the order within the top \(k\): It only checks whether relevant documents make it into the top \(k\).
  • Do not say that MRR considers all relevant documents: It looks only at the highest-ranked relevant document.
  • Do not say that nDCG works only with binary relevance: It was designed for graded relevance.
  • Do not pick the evaluation \(k\) arbitrarily in RAG: \(k\) should equal the number of chunks actually placed in the prompt.

1.8 What progress have modern embedding models made? ★

One-sentence answer

Modern general-purpose embedding models commonly follow a two-stage recipe of "large-scale weakly supervised contrastive pretraining + high-quality supervised fine-tuning"; the backbone has shifted from BERT-sized encoders to decoder-only LLMs (such as E5-Mistral and NV-Embed, and in 2025 Qwen3-Embedding and Gemini Embedding), and models commonly support task instructions on the query side and Matryoshka representations whose dimensions can be truncated. New trends in 2025–2026 also include more synthetic training data, unified multimodal embeddings, and embeddings for reasoning-intensive retrieval.

I will address four aspects: the general training recipe, instruction-tuned embeddings, LLM-based embeddings, and new trends in 2025–2026.

(1) General-purpose embedding models mostly use two-stage training: weakly supervised pretraining, then supervised fine-tuning.

DPR was trained on a single QA dataset and did not 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. The earlier stage 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. The later stage 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 of these models is usually a BERT-sized encoder, with mean pooling or the [CLS] vector as the output, and they 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.

(2) Instruction-tuned embeddings let one model produce different notions of "similar" depending on the task.

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 therefore cannot 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.

(3) Since 2024, most top models on the leaderboards have switched to decoder-only LLM backbones.

E5-Mistral (Wang et al. 2023) is 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 that every token sees the whole input, and uses a latent attention layer for pooling; 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. 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; however, the cost is that they are 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. To address this, Matryoshka representation learning (Kusupati et al. 2022) trains vectors so that their first 64, 128, 256 and so on dimensions are each a usable embedding on their own, so they can simply be truncated at use time, ranking coarsely with short vectors and then refining with full ones.

(4) Progress in 2025–2026 shows up mainly in four directions.

  • LLM backbones and synthetic data have become the mainstream recipe: Qwen3-Embedding (Zhang et al. 2025) comes in 0.6B, 4B and 8B sizes, pretrains on about 150 million weakly supervised pairs synthesized by Qwen3-32B, then performs supervised fine-tuning and model merging; it supports Matryoshka dimensions and query-side instructions, and the 8B version topped the multilingual MTEB leaderboard at release. Gemini Embedding (Lee et al. 2025) is initialized from Gemini, outputs 3,072 dimensions by default with Matryoshka truncation, and ranked first on MMTEB at release. By 2026, the top of the leaderboard included embedding models at the 27B scale (e.g. Harrier-OSS, Microsoft 2026).
  • Small models remain highly competitive: MMTEB (Enevoldsen et al. 2025) extended evaluation to more than 500 tasks and over 250 languages and found that, among publicly available models at the time, the best overall was multilingual-e5-large-instruct with only 560 million parameters, not a larger LLM-based model; EmbeddingGemma (Schechter Vera et al. 2025), with 300 million parameters, ranked first among models under 500M and stayed ahead even when truncated to 128 dimensions or quantized to 4 bits, which suits on-device deployment.
  • Unified multimodal embeddings: jina-embeddings-v4 (Günther et al. 2025) maps text and images into the same space and offers both single-vector and multi-vector outputs, and is strong at retrieving visually rich documents such as tables and charts; Gemini Embedding 2 (Shanbhogue et al. 2026) goes further, mapping text, images, video and audio into one space and supporting arbitrarily interleaved multimodal inputs.
  • Embeddings for reasoning-intensive retrieval: BRIGHT (Su et al. 2024) constructed retrieval tasks in which judging relevance requires reasoning, on which conventional embedding models perform poorly; ReasonIR (Shao et al. 2025) synthesized reasoning-intensive queries and hard negatives specifically to train a retriever, and clearly outperformed earlier embedding models and BM25 on BRIGHT.

In summary: the progress of embedding models can be summed up as stronger backbones, more (synthetic) data, and more flexible use (instructions, truncatable dimensions, multimodality); but with ever more models available, evaluation on your own data remains the final basis for choosing one.

Representative models:

Model Backbone Key ideas
E5 / GTE / BGE BERT-sized encoder Weakly supervised contrastive pretraining + supervised fine-tuning with hard negatives
INSTRUCTOR Encoder (T5-based) Prepends task instructions; trains on many instruction-tagged tasks
E5-Mistral Decoder-only LLM LLM-synthesized multilingual, multi-task data; last-token pooling; short fine-tuning
NV-Embed Decoder-only LLM Removes the causal mask; latent attention pooling; two-stage instruction tuning
LLM2Vec Decoder-only LLM Unsupervised conversion to a bidirectional encoder: masked prediction + unsupervised contrastive learning
Qwen3-Embedding Qwen3 (0.6B–8B) Synthetic weakly supervised pretraining + supervised fine-tuning + model merging; Matryoshka; query-side instructions
Gemini Embedding Gemini Initialized from Gemini; 3,072 dimensions by default with Matryoshka truncation
jina-embeddings-v4 Vision-language model Unified space for text and images; both single-vector and multi-vector outputs

Going deeper: pooling a decoder, the Matryoshka objective, and the Qwen3-Embedding recipe

(1) How to 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, therefore mixes in many representations that "have not finished reading the sentence". There are two common approaches: append an [EOS] and take the last token's hidden state (what E5-Mistral and Qwen3-Embedding do), or switch to bidirectional attention and then pool, as NV-Embed and LLM2Vec do.

(2) The training objective of Matryoshka representation learning.

\[ \mathcal{L}_{\text{MRL}} = \sum_{m \in \mathcal{M}} c_m\, \mathcal{L}\big(\mathbf{z}_{1:m}\big) \]

Here \(\mathcal{M}\) is a set of nested dimensions (such as 64, 128, 256, …, the full dimension), \(\mathbf{z}_{1:m}\) is the first \(m\) dimensions of the vector, \(\mathcal{L}\) is the original training loss (such as a contrastive loss), and \(c_m\) is the weight for each dimension. Because every prefix is trained separately to be a usable representation, information is concentrated in the leading dimensions, and truncation loses little. This differs from applying PCA after training.

(3) The Qwen3-Embedding training recipe.

It first uses Qwen3-32B to synthesize about 150 million weakly supervised pairs covering retrieval, bitext mining, semantic similarity, classification and other tasks for contrastive pretraining; it then performs supervised fine-tuning on about 7 million pairs of public labeled data plus about 12 million filtered, high-quality synthetic pairs; finally it merges several fine-tuning checkpoints with spherical linear interpolation (slerp). In the contrastive loss, besides hard negatives, the other queries and documents in the batch also serve as negatives, and candidates whose similarity is clearly higher than the positive's are masked to reduce false negatives. Its companion reranker uses a pointwise binary-classification formulation (see 1.5).

Follow-up questions

Follow-up 1: When using a decoder-only LLM for embeddings, why not just use mean pooling?

Because under causal attention, earlier tokens have not seen the full input. Each position's hidden state encodes only the prefix before it, and the earlier the token, the less complete its information, so averaging over them dilutes the meaning of the whole sentence. Hence one either takes the hidden state of the last token (usually an appended [EOS]), the only one that has seen the whole sentence, or removes the causal mask in favor of bidirectional attention, so that every token sees the full input before pooling.

Follow-up 2: What are the pros and cons of LLM-based embeddings versus BERT-sized models?

Better quality and flexibility, but much higher cost. The pros are richer knowledge and language understanding, strong multilingual ability, long inputs and the ability to follow complex instructions; the cons are that encoding a text costs dozens of times the compute of BERT-base and the vectors are large, so when indexing hundreds of millions of documents, the differences in compute, storage and search cost are dramatic. A common division of labor is therefore to use a small model for very large corpora and latency-sensitive settings, and LLM embeddings when quality matters most, controlling cost with Matryoshka truncation or quantization.

Follow-up 3: What are Matryoshka representations useful for in practice?

One model can pick its dimension on demand, trading cost against quality flexibly. For example, the main index can be built with short 256-dimensional vectors to cut storage and search costs, with full-dimensional vectors used to refine a small set of candidates; different deployment environments can also choose different dimensions without training several models.

Common mistakes

  • Do not choose a model from its overall MTEB score alone: Evaluation on your own data, languages and query style is the final basis.
  • Do not say that mean pooling a decoder LLM is fine as is: Under causal attention, take the last token, or switch to bidirectional attention.
  • Do not say that Matryoshka is truncation or dimensionality reduction applied after training: It trains every prefix of the dimensions to be a usable representation from the start.
  • Do not say that larger embedding models are always better: One of the best public models on MMTEB had only 560 million parameters, and larger models cost much more.

1.9 How do you handle the asymmetry between queries and documents? ★

One-sentence answer

Queries are usually short questions or keywords, while documents are long and declarative; more importantly, a question and its answer are not similar in the sense of "meaning the same thing", so retrieval must learn relevance rather than similarity. The remedies are: train on asymmetric data such as (query, relevant passage) pairs; distinguish the two sides with role prefixes or query-side instructions; expand the query side or the document side to bring the two closer (e.g. HyDE, doc2query); and control document length or use token-level matching.

I will address three aspects: where the asymmetry lies, why it makes similarity-trained models go wrong, and the common remedies.

(1) Queries and documents are asymmetric in form, length and semantic role.

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.

(2) Because of this asymmetry, a model trained only on symmetric tasks ranks "another question" above the answer.

A model trained on symmetric tasks such as paraphrase or semantic textual similarity (STS) would judge another question, "How are the seasons formed?", to be more "similar" than the answer passage, and would rank someone else's question above the answer. So retrieval needs to learn relevance, i.e. "can this text answer this question", rather than similarity, i.e. "do these two texts mean the same thing". This also explains why a model with a high STS score does not necessarily retrieve well.

(3) There are four common kinds of remedies.

  • Train on asymmetric data: Train on (query, relevant passage) pairs rather than only paraphrase pairs, so that the model learns that "a question should sit close to its answer".
  • Distinguish the roles of the inputs: DPR simply uses two separate encoders for queries and passages; more common today is a shared encoder with role markers on the input, for example 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, and 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.
  • Bring the two sides closer 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 2); 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" (the idea behind doc2query, see 1.1).
  • Handle the 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 reason chunks should not be too large (see Chapter 0, 0.4), and why token-level matching like ColBERT has an edge on long documents (see 1.3).

In summary: query–document asymmetry means that retrieval must learn "can it answer" rather than "does it mean the same", so train on asymmetric data, mark the roles with prefixes or instructions, and expand the query side or the document side when needed.

Going deeper: rules for using prefixes, and why shared encoders are more common

(1) How prefixes should be used for different tasks.

Task type Examples Query side Document side
Asymmetric retrieval Open-domain QA, document search query: or a task instruction passage:, or nothing
Symmetric tasks Semantic similarity, duplicate-question detection, clustering The same prefix on both sides The same prefix on both sides

E5 recommends distinguishing the two sides with query: and passage: for asymmetric tasks such as retrieval, and using query: on both sides for symmetric tasks such as semantic similarity, bitext mining and clustering, and when using embeddings as features. Instruction-style models (such as Qwen3-Embedding) concatenate the instruction in front of the query and leave the document unchanged, so document vectors can be reused across tasks.

(2) Why a shared encoder with role markers is more common than two separate encoders.

Two separate encoders let each side adapt to its own input distribution, but they double the parameters, and the query encoder learns only from short texts, which uses data inefficiently; a shared encoder lets both sides share the same understanding of language and generalizes better, while the prefix preserves the ability to distinguish roles at very low cost.

Follow-up questions

Follow-up 1: Why might a model that does well on STS not do well at retrieval?

Because STS measures "do they mean the same", whereas retrieval needs "can it answer". An STS model has learned to pull sentences with the same meaning together, so at retrieval time it ranks another question similar to the query above the real answer passage; a retrieval model needs to learn, from asymmetric data such as (query, relevant passage) pairs, to pull a question toward its answer. This is also why MTEB reports retrieval and STS as separate task categories.

Follow-up 2: What happens if the query or passage prefix is left out?

Quality drops noticeably, because the input no longer matches the training conditions. During training the model relies on the prefix to tell the role of the input; without it, a query may be encoded as if it were a document, or both sides may be treated as a symmetric task, and the vectors land in a different region from where they did in training. A subtler error is inconsistent prefix usage between indexing time and query time; the system raises no error, and retrieval quality simply gets worse.

Follow-up 3: How do HyDE and doc2query differ?

Both use generation to bridge the asymmetry; they differ in which side is expanded and when the cost is paid. HyDE has an LLM generate a hypothetical answer at query time, adding one LLM call and extra online latency to every query; the hypothetical answer may contain false facts, but it is used only for retrieval, not as evidence. doc2query generates likely questions for each document at indexing time, so the cost is paid once offline and online queries carry no extra overhead, but the index grows. Details of HyDE are in Chapter 2.

Common mistakes

  • Do not say that retrieval means finding the most semantically similar text: Retrieval looks for text that can answer the question, i.e. relevance rather than similarity.
  • Do not add the query-side retrieval instruction to documents as well: For models that put instructions only on the query side, documents should be left as they are.
  • Do not say that a two-tower model must use two separate encoders: Today a shared encoder with role prefixes is more common.
  • Do not treat the hypothetical answer generated by HyDE as evidence: It is used only for retrieval and may contain false facts.