Sparse, Dense and Approximate Retrieval

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

BM25 and the Embedder Each Find Questions the Other Misses

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.

  • BM25 alone: the question names a function, softmax_weights; the embedder ranks ten other passages on the same topic above it.
  • Embedder alone: the question says “computed”, the passage “calculated”.

And a flat scan of 10^8 passages reads 200 GB of float16 vectors per question.

By the End of This Deck You Can

Goals

  • score a question against an inverted index with BM25;
  • estimate when a flat dense scan is limited by memory;
  • fuse two rankings by rank and rerank the top with a cross-encoder;
  • derive asymmetric distances for product quantization;
  • read a recall, latency and memory trade-off and choose an index.

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?”

Two Indexes Find the Passages; an Approximate Index Makes Search Fast

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
  • What to retrieve: a word index and a vector index, merged, then reranked.
  • How fast: exact scan, or an approximate index.
  • Skips: training retrievers, learned sparse retrieval, late interaction.

The Corpus Is the Book at One Commit, Without the Part That Asks About It

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
  • Split by document, within each chapter: 168 train, 32 dev, 32 test.
  • Views: display for a generator, dense (long code cut) for the embedder, sparse (math removed) for BM25.

Section Chunks Follow the Text; Windows Cut Through Sentences

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.

Check: Relevant Chunks at Ranks 1 and 4. What Is nDCG@10?

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.

An Inverted Index Is a Sparse Term-by-Chunk Matrix

The word index

  • \mathbf{W}: one row per term, one column per chunk; W_{td} > 0 only if term t occurs in chunk d.
  • Row t is the list of chunks containing t.
  • Question term counts \mathbf{n}: all scores = \mathbf{n}^\top\mathbf{W}, touching only the question’s rows.
  • Terms: lower-cased words and numbers; an identifier such as BookRetriever is also split into book, retriever.

A question of ten words reads ten lists, however large the corpus.

BM25 Saturates Repeated Words and Discounts Long Chunks

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.

Tuning BM25 on Training Questions Gains Nothing on Dev

Check and tune

  • Same first chunk as the bm25s library for 200 of 200 training questions; scores agree to 4 \times 10^{-7}.
  • Grid of 24 settings on 5,614 training questions: Recall@10 from 0.915 to 0.934.
  • Chosen: k_1 = 1.2, b = 0.9, identifiers split.
  • Dev Recall@10: 0.96 under both settings, the same on every question.

Tune on training questions, never on the questions you report. A flat grid leaves no room for tuning to show.

A Flat Scan Is One Matrix Product, Limited by Memory at Batch 1

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.

Reciprocal-Rank Fusion Needs Ranks, Not Scores

Fusion

s(d) = \sum_r \frac{1}{k + \mathrm{rank}_r(d)}, \qquad k = 60

  • First in one list, third in the other: 1/61 + 1/63 = 0.0323.
  • First in one list only: 1/61 = 0.0164.
  • Rank 10 scores 13% less than rank 1: close to a vote.
  • Score fusion must first z-score each list (subtract its mean, divide by its standard deviation); the dense weight \lambda = 0.7 was chosen on training questions.

Source: Cormack, Clarke and Büttcher (2009), who found k = 60 near-optimal but not critical.

A Cross-Encoder Reads the Pair, So It Can Only Reorder a Short List

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: We Rerank the First 20. What Happens to Recall@100?

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.

Fusion Improves the Ranking, Reranking 20 Improves It Again, 100 Adds Nothing

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.

On Identifier Questions BM25 Ranks Relevant Chunks Higher

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.

An Inverted File Scans 16 of 1,024 Cells: 33 Times Fewer Vectors, About 35 Times Faster

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.

Product Quantization Stores 64 Bytes per Vector and Reads Distances from a Table

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}.

  1. A squared distance is a sum over coordinates, so for an exact question \mathbf{y}

\|\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

  1. Table: Km multiply-adds once per question; then M look-ups per code.

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.

Check: Two Look-Ups by Hand. How Far Is the Question From the Code?

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.

Coding Offsets Within Cells Lowers the Error and Still Loses Neighbors

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
  • More cells: shorter offsets, mean squared error 0.41 → 0.30.
  • Yet recall against exact search falls 0.70 → 0.63: at 1,024 cells only half of the ten nearest share the cell of the first.

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.

HNSW Walks a Layered Graph; Its Memory Is Mostly the Vectors

Graphs

  • Each vector links to near neighbors; a search walks toward the question and stops when no neighbor is closer, possibly at a dead end.
  • Upper layers hold a shrinking random subset with long links; the walk crosses there and refines at the bottom.
  • Up to 32 links per layer (Faiss’s M), 64 at the bottom; \mathit{efConstruction} = 200 candidates while building.
  • \mathit{efSearch} candidates while searching let the walk back out of dead ends: the knob that trades recall for time.
  • Memory: 4,096 bytes of vector plus 272 for the graph per vector.

Source: Malkov and Yashunin (2020); built here with Faiss.

HNSW Reaches 0.97 of the Exact Neighbors About 50 Times Faster Than the Scan

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.

BookRetriever Fuses BM25 and the Embedder by Rank; the Reranker Is Optional

The book retriever

  • BM25 (k_1 = 1.2, b = 0.9) and an exact scan of the stored Qwen3-Embedding-0.6B vectors, fused by RRF with k = 60.
  • rerank_k adds Qwen3-Reranker-0.6B; index='hnsw' or 'ivfpq' builds a Faiss index for larger collections.
  • Each 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: A Billion Vectors and 128 GB of Memory. Which Index?

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

Recap

  • BM25 0.96, embedder 0.99 Recall@10; 5% found by only one; both together find all 220.
  • BM25 ranks identifier questions higher: nDCG@10 by 0.09. The load_array question: BM25 first by a wide margin, the embedder first by 0.001.
  • RRF: nDCG@10 +0.05 over the embedder, +0.04 over BM25; rerank@20: +0.03 more, about a quarter of a second per question.
  • 67,853 vectors: HNSW 0.97 of the exact neighbors, about 50 times faster than one thread’s scan; IVF-PQ 64 bytes per vector at recall about 0.6 against exact search, task recall 0.90 to 0.94 across k-means seeds.
  • Offsets coded in more cells: smaller errors (0.41 → 0.30), fewer neighbors found (0.70 → 0.63).

Next: which chunks a language model should read, and which stage failed when its answer is wrong.