Dive into Deep Learning · §19.4
Sparse, Dense and Approximate Retrieval
the book corpus · BM25 · the flat scan · fusion · reranking · inverted files · product quantization · HNSW
The problem
220 dev questions about this book. Is a passage that answers among the first ten?
| retriever | Recall@10 |
|---|---|
| BM25: weighted word counts | 0.96 |
| Qwen3-Embedding-0.6B: one vector per text | 0.99 |
| either of the two | 1.00 |
Exactly one of the two succeeds on 11 of the 220 questions, 5%: BM25 alone on 2, the embedder alone on 9.
softmax_weights; the embedder ranks ten other passages on the same topic above it.And a flat scan of 10^8 passages reads 200 GB of float16 vectors per question.
Goals
Running example: the book as 5,324 chunks; 220 dev questions written and checked by language models, not people; among them, “How does load_array decide whether to shuffle?”
Where this fits
| movement | section |
|---|---|
| vectors | Word Embeddings |
| Pretrained Encoders | |
| Text Embeddings from Contrastive Training | |
| finding | Sparse, Dense and Approximate Retrieval |
| using | Retrieval-Augmented Generation |
| Failures and Fixes in RAG |
The book corpus
| kept | left out |
|---|---|
| the other chapters, 232 documents | Language Models part: its notebooks hold the questions |
| PyTorch tabs | Attic, retiring NLP chapters, front matter |
| references as titles, math in text | slide decks, exercises, citations, import-only cells |
display for a generator, dense (long code cut) for the embedder, sparse (math removed) for BM25.Chunking
The GAN chapter introduction, 789 tokens:
| chunking | chunks (tokens) | where chunks start |
|---|---|---|
| sections, at most 512 tokens | 2 (459, 316) | at the text, at the resources list |
| windows of 256, 64 shared | 4 (256, 256, 256, 213) | three of four mid-sentence |
Whole book: 5,324 section chunks, median 364 tokens; 9,447 windows.
Ids such as sec512:chapter_transformers/kv-cache#001 stay fixed within a corpus version.
Measures
r: rank of the first relevant chunk; \mathrm{rel}_i \in \{0, 1\}. Recall@k asks whether, MRR and nDCG how early.
| measure | one question |
|---|---|
| Recall@k | 1 if r \le k |
| MRR@10 | 1/r if r \le 10 |
| nDCG@10 | \sum_{i \le 10} \mathrm{rel}_i / \log_2(i+1) over its best value |
| relevant at ranks | Recall@1 | Recall@5 | MRR@10 | nDCG@10 |
|---|---|---|---|---|
| 3 | 0 | 1 | 0.333 | 0.500 |
| 1 and 4 | 1 | 1 | 1 | ? |
Answer. \dfrac{1 + 1/\log_2 5}{1 + 1/\log_2 3} = \dfrac{1.431}{1.631} = 0.877. The second chunk sits at rank 4 instead of 2. pytrec_eval agrees.
The word index
BookRetriever is also split into book, retriever.A question of ten words reads ten lists, however large the corpus.
BM25
W_{td} = \mathrm{idf}(t)\,\frac{\mathrm{tf}_{td}}{\mathrm{tf}_{td} + k_1\big(1 - b + b\,|d|/\overline{|d|}\big)}, \quad \mathrm{idf}(t) = \log\Big(1 + \frac{N - \mathrm{df}_t + 0.5}{\mathrm{df}_t + 0.5}\Big)
\mathrm{tf}_{td}: count of t in chunk d; |d|: its length; \mathrm{df}_t: chunks containing t; N: all chunks.
| occurrences, k_1 = 1.2, b = 0.75 | 1 | 2 | 5 | \infty |
|---|---|---|---|---|
| share of the idf, average length | 0.45 | 0.63 | 0.81 | 1 |
| share of the idf, twice the average | 0.32 | 0.49 | 0.70 | 1 |
Rare words count most: over 5,324 chunks, idf is 8.2 for a term in one chunk and 0.69 for a term in half of them.
Check and tune
bm25s library for 200 of 200 training questions; scores agree to 4 \times 10^{-7}.Tune on training questions, never on the questions you report. A flat grid leaves no room for tuning to show.
The flat scan
\mathbf{S} = \mathbf{Q}\mathbf{X}^\top, N chunks, B questions, m = 1{,}024: 2NmB operations, 2Nm bytes read in float16. One question: one operation per byte. RTX 4090 ridge, where compute and memory take equal time: about 160 operations per byte.
| matrix | batch | measured | roofline |
|---|---|---|---|
| book, N = 5{,}324, 11 MB | 1 | 0.05 ms | 0.011 ms |
| synthetic, N = 131{,}072, 256 MiB | 1 | 0.33 ms | 0.27 ms |
| synthetic, N = 131{,}072, 256 MiB | 220 | 0.7 ms | 0.36 ms |
Batch 220: about 220 operations per byte, past the ridge, so arithmetic sets the bound; 0.003 ms per question.
For the book, encoding the questions (about 1 ms each in a batch of 220) costs more than the scan.
Fusion
s(d) = \sum_r \frac{1}{k + \mathrm{rank}_r(d)}, \qquad k = 60
Source: Cormack, Clarke and Büttcher (2009), who found k = 60 near-optimal but not critical.
Reranking
| bi-encoder | cross-encoder | |
|---|---|---|
| reads | question and chunk apart | the pair together |
| chunk work | once, before any question | once per question |
| cost per question | one encoding, one scan | one forward pass per candidate |
| ms per question, book | about 1 (batched) | about 230 for 20, 1,200 for 100 |
Qwen3-Reranker-0.6B: P(\text{yes}) = e^{z_\text{yes}} / (e^{z_\text{yes}} + e^{z_\text{no}}) for “Does this chunk meet the query?”
About a quarter of a second per question for 20 chunks: affordable for a short list, not for the collection.
Check
The reranker scores the first 20 fused chunks and sorts them by P(\text{yes}).
Answer. Nothing, and Recall@20 does not move either. Reranking only permutes the chunks it is given; it changes Recall@k only for k below its depth.
The retrievers compared
| dev, 220 questions | Recall@1 | Recall@10 | nDCG@10 | ms |
|---|---|---|---|---|
| BM25 | 0.76 | 0.96 | 0.82 | about 0.2 |
| embedder | 0.70 | 0.99 | 0.81 | about 1 |
| RRF | 0.80 | 0.99 | 0.86 | about 1 |
| RRF + rerank@20 | 0.84 | 0.99 | 0.89 | about 230 |
| RRF + rerank@100 | 0.84 | 0.99 | 0.89 | about 1,200 |
Paired on the same questions: fusion ranks better than the embedder (nDCG@10 +0.05) and than BM25 (+0.04), both intervals excluding 0; reranking 20 adds 0.03 more; reranking 100 adds nothing.
No room beyond 20: for all but one question the first 20 fused chunks already hold a relevant one.
BM25 against the embedder
Identifier question: the question or its reference answer contains code, such as a dotted name or a call.
| embedder − BM25 | Recall@10 | nDCG@10 |
|---|---|---|
| all, 220 | +0.03, interval excludes 0 | within noise |
| identifier, 80 | within noise (BM25 two more) | BM25 ahead by 0.09 (p 0.007) |
| other, 140 | +0.06, interval excludes 0 | within noise |
Identifier questions come from 28 documents. Sign-flip test: flip each document’s mean difference at random; p is how often the total is as large.
“Dense beats BM25” is a claim about a corpus, a question set and a model.
Inverted files
k-means cuts the space into n_\text{list} cells; a question scans its n_\text{probe} nearest cells:
\text{vectors compared} = n_\text{list} + n_\text{probe}\,N / n_\text{list}
N = 67{,}853: 1{,}024 + 16 \times 66 \approx 2{,}100 instead of 67,853. Measured on one CPU thread: about 0.4 ms against 16 ms.
A neighbor across the border of an unprobed cell is never seen: recall against exact search 0.85.
Derivation
I. Split \mathbf{x} \in \mathbb{R}^m into M blocks; replace block j by the index i_j of its nearest of K centroids \mathbf{c}_{j,i}.
\|\mathbf{y} - \hat{\mathbf{x}}\|^2 = \sum_{j=1}^M T_j[i_j], \qquad T_j[i] = \|\mathbf{y}^{(j)} - \mathbf{c}_{j,i}\|^2
m = 1{,}024, M = 64, K = 256: 64 bytes instead of 4,096 in float32; codebooks 1 MiB. IVF-PQ codes offsets from the cell centroid inside an inverted file: a smaller error, but neighbors across a border no longer share codes.
The smallest case
m = 4, M = 2, K = 2; codebooks \{(1,0), (0,1)\} and \{(1,1), (-1,0)\}; \mathbf{x} = (0.9, 0.2, -0.8, 0.1), \mathbf{y} = (1, 1, 0, 0).
| centroid 0 | centroid 1 | |
|---|---|---|
| T_1 for (1, 1) | 1 | 1 |
| T_2 for (0, 0) | 2 | 1 |
Answer. Code (0, 1), \hat{\mathbf{x}} = (1, 0, -1, 0): T_1[0] + T_2[1] = 2, where the true squared distance is 1.30. Error of the distance |\sqrt{1.30} - \sqrt{2}| = 0.27 \le \|\mathbf{x} - \hat{\mathbf{x}}\| = 0.32.
IVF-PQ, every cell probed
PQ64 codes; residual codes in every cell, all cells probed
cells vectors per cell recall mean |e|^2 top 10 in the cell of the 1st
1 67853 0.703 0.414 1.000
16 4240 0.696 0.383 0.676
64 1060 0.680 0.359 0.588
256 265 0.654 0.331 0.521
1024 66 0.627 0.298 0.489
Close vectors with the same code share their error; across a border the errors are independent. The loss is in the coding, not the probing.
Graphs
M), 64 at the bottom; \mathit{efConstruction} = 200 candidates while building.Source: Malkov and Yashunin (2020); built here with Faiss.
The trade-off, 67,853 vectors
Marker area: bytes per vector. Left: recall against exact search. Right: dev Recall@10 of the book’s questions.
Which recall
| index, one CPU thread | against exact search | dev Recall@10 |
|---|---|---|
| flat scan | 1.00 | 0.99 |
| IVF-Flat, 16 probes | 0.85 | 0.97 |
| IVF-PQ, 64 bytes, 16 probes | 0.59–0.60 | 0.90–0.94 |
IVF-PQ: ranges over three k-means seeds.
Against exact search counts all ten neighbors; a reader needs one relevant chunk among ten.
Recall against exact search measures the index; task recall measures what a user notices.
The book retriever
rerank_k adds Qwen3-Reranker-0.6B; index='hnsw' or 'ivfpq' builds a Faiss index for larger collections.Hit carries every stage’s score:“How does load_array decide whether to shuffle?” |
rank of the passage |
|---|---|
| BM25: the name matches, score 25 against at most 15 | 1 |
| embedder: 0.001 ahead of “A Loader for Every Epoch” | 1 |
| fusion, 1/61 + 1/61 = 0.033 | 1 |
Check
Bytes per vector: float32 4,096; HNSW about 4,370; IVF-PQ64 code 64.
Answer. Float32 needs 4 TB and the graph more, so IVF-PQ: 64 GB of codes plus ids. Rescore the best candidates with exact vectors from disk, since 64-byte codes found only about 0.6 of the exact neighbors here.
Recap
load_array question: BM25 first by a wide margin, the embedder first by 0.001.Next: which chunks a language model should read, and which stage failed when its answer is wrong.