Skip to content
LLM application engineering Core 27 min read

Embeddings and vector search

An embedding model maps a piece of text to a point in a few hundred to a few thousand dimensions, trained so that texts which answer each other land close together. Vector search finds the nearest points to a query among millions, approximately, in milliseconds. The one idea: retrieval quality is decided by the embedding model, and retrieval speed by the index, and you tune them separately.

10,000 ft

Search used to mean matching words. Embeddings let software match meaning: "how do I get my money back" finds the refund policy even though it shares no keyword with it. The idea comes from representation learning (embeddings and representation learning), where contrastive training turns "these two texts belong together" into geometry. Vector search is the systems half: nearest-neighbour search made fast by graphs, clustering and compression. Together they are the retrieval engine of RAG, of semantic caching and deduplication, of recommendation, and of agent memory (context engineering and memory). They are also a common source of quiet failure: a retriever that misses the right passage makes the best language model in the world answer from nothing. Advanced RAG adds hybrid keyword search and re-ranking on top of what this page builds.

2,000 ft

  1. Embed the corpus offline. Split documents into chunks, run each through an embedding model (a transformer encoder plus pooling) to get a unit vector \(\mathbf d\in\mathbb R^{d}\).
  2. Index the vectors. Exact search compares the query with every vector; an approximate nearest-neighbour (ANN) index (HNSW graph, IVF clusters, PQ compression) visits a small fraction and returns almost the same top-\(k\).
  3. Embed the query online with the same model, often with a query-specific prefix or instruction.
  4. Score by similarity, usually cosine, which on unit vectors is the dot product.
  5. Optionally re-rank the top 50–200 with a slower, more accurate cross-encoder.
  6. Measure two things separately: retrieval quality against labelled relevant documents (recall@k, nDCG), and ANN fidelity against exact search (recall of the true neighbours).

Vector search: embed once offline, embed the query online, find neighbours
Vector search: embed once offline, embed the query online, find neighbours. offline (indexing), documents chunked, embedding model d = 384–3,072, ANN index HNSW / IVF-PQ, online (query), query text, same embedding model, approximate nearest neighbours, optional re-rank cross-encoder, searchVector search: embed once offline, embed the query online, find neighbours. offline (indexing), documents chunked, embedding model d = 384–3,072, ANN index HNSW / IVF-PQ, online (query), query text, same embedding model, approximate nearest neighbours, optional re-rank cross-encoder, search

Ground level

From text to a vector

A text embedding model is usually a transformer encoder (bidirectional attention, like BERT) or a decoder LLM adapted for the purpose. It reads up to its maximum length (512 tokens for many classic models, 8,192 or more for recent ones), produces one vector per token, and pools them into one vector: the mean of the token vectors, the vector of a special first token, or the last token's vector for decoder-based models. The result is normalised to unit length.

Sentence-BERT (Reimers and Gurevych, 2019) established the recipe: fine-tune BERT in a siamese setup so that the pooled vectors of related sentences are close. Before it, using raw BERT outputs as sentence vectors performed poorly, because the pre-training objective never asked whole-sentence vectors to be comparable. The lesson is general: an embedding's geometry means exactly what its training objective made it mean.

Two practical properties follow from this:

  • Truncation is silent. Text beyond the maximum length is dropped without an error. A 3,000-token chunk embedded by a 512-token model is represented by its first page only.
  • Queries and documents are different kinds of text. A question is short and phrased as a need; a passage is long and phrased as a statement. Many models are trained asymmetrically: E5 (Wang et al., 2022) prepends query: and passage:, and instruction-tuned embedders take a task description. Forgetting the prefix is a common, measurable loss of quality.

Similarity: cosine, dot product and distance

Three scores are in common use, and on unit vectors they are the same ranking:

\[ \cos(\mathbf q,\mathbf d)=\frac{\mathbf q^\top\mathbf d}{\lVert\mathbf q\rVert\,\lVert\mathbf d\rVert},\qquad \lVert\mathbf q-\mathbf d\rVert^2 = \lVert\mathbf q\rVert^2+\lVert\mathbf d\rVert^2-2\,\mathbf q^\top\mathbf d = 2-2\cos(\mathbf q,\mathbf d)\ \text{ if both are unit.} \]

So for normalised embeddings, maximising the dot product, maximising cosine and minimising Euclidean distance return identical neighbours. OpenAI's embeddings, for example, are normalised to length 1 and its docs recommend cosine similarity, computable as a plain dot product. If a model does not normalise, the dot product also rewards vector length, which some models use to encode salience; use the score the model was trained with.

One property of high dimensions trips up intuition. Two random unit vectors in \(d\) dimensions have cosine similarity with mean 0 and standard deviation almost exactly \(1/\sqrt d\): 0.125 at \(d=64\), 0.051 at \(d=384\), 0.026 at \(d=1{,}536\) (measured: 0.1245, 0.0517, 0.0259). Almost everything is nearly orthogonal to almost everything else. Real embeddings are not random: they typically occupy a narrow region of the sphere, so even unrelated texts often score well above zero, by an amount that differs from model to model. So absolute similarity values are not comparable across models. Never hard-code "0.8 means relevant"; calibrate a threshold on labelled pairs for the model you use.

How embedding models are trained

Modern text embedders are trained contrastively. Take a batch of \(B\) pairs \((q_i, d_i)\) that belong together: a question and its answer passage, a title and its body, two paraphrases, a search query and the page clicked. Embed everything, compute all \(B\times B\) similarities, and train each query to pick its own passage out of the batch:

\[ \mathcal L_{\text{InfoNCE}} = -\frac{1}{B}\sum_{i=1}^{B}\log\frac{\exp\big(s(q_i,d_i)/\tau\big)}{\sum_{j=1}^{B}\exp\big(s(q_i,d_j)/\tau\big)} . \]

The other passages in the batch serve as free negatives (in-batch negatives). This loss, named InfoNCE by van den Oord et al. (2018), is cross-entropy over "which passage is mine", with temperature \(\tau\) (typically 0.01–0.1) sharpening the softmax. DPR (Karpukhin et al., 2020) trained exactly this with BERT on question–passage pairs and beat a strong BM25 keyword system by 9–19 points absolute in top-20 passage retrieval accuracy on open-domain QA. Three ingredients separate good embedders from mediocre ones:

  1. Data scale and diversity. E5 pre-trained on a large curated set of naturally occurring text pairs and was, its authors report, the first model to beat BM25 on the BEIR benchmark zero-shot without labelled data. Contriever (Izacard et al., 2021) showed unsupervised contrastive pre-training alone gets far.
  2. Hard negatives. Random negatives are too easy after the first epoch. Mining passages that look relevant but are not (high BM25 score, wrong answer) forces finer distinctions.
  3. Large batches. More in-batch negatives make the softmax a harder classification problem; the InfoNCE bound below explains why.

Choosing an embedding model

MTEB (Muennighoff et al., 2022) benchmarks embedders across 8 task types, 58 datasets and 112 languages; its central finding was that "no particular text embedding method dominates across all tasks". The MTEB leaderboard is the place to start, with three cautions: benchmark averages hide your task, some models have seen benchmark data in training, and retrieval is only one of the task types averaged. Choose on:

Factor What to check
Retrieval quality on your data Build 50–200 labelled queries and measure recall@10 for 2–3 candidates. Nothing replaces this.
Dimension Storage and search cost scale linearly with \(d\). 384–1,024 is often enough.
Max input length Must exceed your chunk size, or chunks are silently truncated.
Languages and domain Multilingual models for mixed-language users; code or legal models where relevant.
Hosting and privacy API (no ops, data leaves you) vs open weights (you run the GPU, data stays).
Shrinkability Matryoshka-trained models can be truncated to fewer dimensions; some support int8 or binary vectors.

Matryoshka embeddings (Kusupati et al., 2022) are trained so that the first 64, 128, 256… coordinates are each a usable embedding on their own, by summing the loss over several prefix lengths. The paper reports up to 14× smaller embeddings at the same accuracy on ImageNet classification, and up to 14× real-world speed-ups for large-scale retrieval. OpenAI's text-embedding-3 models (1,536 dimensions for the small model, 3,072 for the large) expose this through a dimensions parameter. A common pattern is to search with short vectors and re-score the shortlist with full ones.

Changing the embedding model means re-embedding everything

Vectors from two different models live in unrelated spaces, even at the same dimension. A query embedded with model B searched against documents embedded with model A returns noise, without any error. Store the model name and version beside every vector, and treat a model upgrade as a migration: re-embed, re-index, re-evaluate, then switch.

Bi-encoders, cross-encoders and late interaction

Three ways to score a query against a document
Three ways to score a query against a document. bi-encoder q and d embedded separately score = q·d precompute d: millions/sec, late interaction (ColBERT) a vector per token score = Σ max sim more storage, more accurate, cross-encoder q and d read together score = model([q; d]) one forward pass per pair, more accurate, costlierThree ways to score a query against a document. bi-encoder q and d embedded separately score = q·d precompute d: millions/sec, late interaction (ColBERT) a vector per token score = Σ max sim more storage, more accurate, cross-encoder q and d read together score = model([q; d]) one forward pass per pair, more accurate, costlier

A bi-encoder compresses each text into one vector independently, so documents are embedded once and search is a dot product. The price is that the query and document never "see" each other; everything relevant about a 500-token passage must fit in one vector before the question is known. A cross-encoder concatenates query and document and runs the transformer on both, so attention can compare them token by token; it is far more accurate and far too slow to run over a corpus, so it re-ranks a shortlist (advanced RAG). Late interaction, introduced by ColBERT (Khattab and Zaharia, 2020), keeps one vector per token and scores with \(\sum_{i}\max_j \mathbf q_i^\top\mathbf d_j\) (each query token finds its best-matching document token). It recovers much of the cross-encoder's accuracy while documents can still be precomputed; the paper reports two orders of magnitude faster execution than BERT re-rankers, at the cost of storing many vectors per passage.

Exact search and why it does not scale

Exact (\(k\)-nearest-neighbour) search is a matrix–vector product: score all \(N\) vectors, keep the top \(k\). For \(N=10^7\) vectors of \(d=1{,}024\) dimensions that is \(10^{10}\) multiply-adds, about 20 GFLOP per query, over \(4\times10^{10}\) bytes (41 GB in float32) of memory that must be streamed for every query. On a laptop CPU that is seconds per query. Below about a million vectors, exact search on a GPU, or even NumPy, is perfectly reasonable, and it has perfect recall: start there. Above that, approximate search trades a few percent of recall for 10–1,000× speed.

Approximate nearest neighbours: three families

Inverted file (IVF): cluster, then search a few clusters. Run k-means on the vectors to get nlist centroids; assign each vector to its nearest centroid's list. At query time, find the nprobe nearest centroids and search only their lists. Cost falls by roughly \(\text{nlist}/\text{nprobe}\); recall falls when a true neighbour sits in a list you did not probe (vectors near cluster boundaries). The nprobe knob trades one for the other at query time.

Product quantisation (PQ): compress the vectors. Jégou, Douze and Schmid (2011) split each \(d\)-dimensional vector into \(m\) sub-vectors, run k-means with 256 centroids in each subspace, and store each sub-vector as one byte: the id of its nearest centroid. A 1,024-dimensional float32 vector (4,096 bytes) becomes, with \(m=64\), 64 bytes: 64× smaller. Distances to a query are computed from lookup tables without decompressing (below). PQ is how billion-scale indexes fit in RAM, and IVF-PQ (IVF to choose lists, PQ to store their contents) is the classic FAISS configuration.

Graphs (HNSW): walk towards the query. Malkov and Yashunin's HNSW (2016) links every vector to a few dozen near neighbours, in a hierarchy of layers like a skip list: each vector appears in layer 0, and in each higher layer with exponentially decaying probability. Search starts at an entry point in the sparse top layer, greedily moves to whichever neighbour is closer to the query, drops a layer when it can improve no further, and at the bottom runs a beam search keeping the best ef candidates. Search cost grows roughly logarithmically with \(N\).

layer 2 (few nodes, long links)layer 1layer 0 (every vector, short links)entrydescendquery's true nearest neighbour
HNSW search. Long links in the upper layers cross the space in a few hops; short links in layer 0 refine. At the bottom, a beam of the best ef candidates explores the neighbourhood so the greedy walk does not stop at a near miss.
Index Memory Query speed Build Updates Typical use
Flat (exact) \(4Nd\) bytes slow at scale none trivial < 1M vectors, evaluation ground truth
IVF-Flat \(\approx 4Nd\) fast k-means easy appends medium scale, batch builds
IVF-PQ \(\approx Nm\) bytes fast k-means × 2 easy appends 100M–billions, memory-bound
HNSW \(4Nd\) + links fastest at high recall slow inserts fine, deletes awkward most production systems up to ~100M
DiskANN / Vamana SSD + small RAM fast slow supported billion scale on one machine

DiskANN (Subramanya et al., 2019) built a graph index (Vamana) that lives mostly on SSD, and served a billion-point dataset from a single workstation with 64 GB of RAM. ScaNN (Guo et al., 2019) showed that quantisation should weight errors by how much they change inner-product rankings (anisotropic quantisation). ANN-Benchmarks compares these families on common datasets; the curves (recall against queries per second) are the honest way to compare indexes.

Where the vectors live

You have three choices, and the boring one is often right:

  • A library in your process (FAISS, hnswlib): fastest, but you own persistence, updates and filtering.
  • Your existing database. pgvector adds vector types, distance operators (<-> L2, <#> negative inner product, <=> cosine distance) and HNSW and IVFFlat indexes to Postgres. HNSW indexes vector columns up to 2,000 dimensions and halfvec up to 4,000. Its defaults are m = 16, ef_construction = 64 and hnsw.ef_search = 40; for IVFFlat it suggests starting with rows / 1000 lists (up to 1M rows) and sqrt(lists) probes. You get transactions, joins, row-level security and backups for free.
  • A dedicated vector database: managed scaling, built-in hybrid search and filtering, at the cost of another system to keep in sync with your source of truth.

Filtering is the hard part. "Nearest neighbours where tenant = 42 and date > March" is the normal query in a product. Filtering after the ANN search can return fewer than \(k\) results (the nearest 40 were all other tenants); filtering before it can disconnect an HNSW graph or empty an IVF list. Mature systems interleave the filter with the search or partition by the filter key. Test with your real filter selectivity.

Why Jarvis has a vector table and does not use it

Finny's Jarvis planned semantic memory in pgvector: a table of message embeddings, protected by Postgres row-level security on the user id so each member can only ever recall their own conversations, and deletable on request. The table was built (1,536-dimensional vectors from a small hosted embedding model) and then never wired in. The team's later decision went the other way: follow-up questions are handled by having the routing call rewrite each question into a standalone query and by carrying structured session state (the last facts, the last plan slices, the focus FIRE type). For a user's own financial plan, recalling stale numbers by semantic similarity was a risk, not a feature. A vector index is a tool, not a default. See the Jarvis case study.

Evaluating retrieval

Keep two evaluations apart:

  1. Is the embedding model finding relevant documents? Needs labelled data: queries with the documents a human (or a careful LLM judge, spot-checked) marks relevant. Metrics: recall@k (did the relevant documents make the top \(k\)?), MRR (how high is the first relevant one?), nDCG (graded relevance with a position discount). BEIR (Thakur et al., 2021) is the standard zero-shot suite, and found that BM25 keyword search is "a robust baseline" that many dense models failed to beat out of domain; always include it.
  2. Is the ANN index faithful to exact search? Needs no labels: compare the index's top \(k\) with exact search's top \(k\) on sample queries. Tune ef_search or nprobe until this is above 0.95–0.99, then stop worrying about the index and spend effort on the model and the chunks.

First principles

Why should nearest neighbours in a learned space retrieve relevant text? Look at what InfoNCE optimises. For a query \(q\), the batch contains one passage drawn from \(p(d\mid q)\) and \(B-1\) drawn from the marginal \(p(d)\). The classifier that best identifies the true passage scores each candidate by how much more likely it is under \(p(d\mid q)\) than under \(p(d)\). So the optimal score satisfies

\[ \exp\big(s^\star(q,d)/\tau\big)\ \propto\ \frac{p(d\mid q)}{p(d)} , \]

that is, the learned similarity approximates the pointwise mutual information between query and passage, up to a constant. Relevance, as defined by the training pairs, becomes a dot product. Two consequences: the embedding knows only the notion of relevance present in its training pairs (a model trained on paraphrases will retrieve paraphrases, not answers); and because the score is a ratio against \(p(d)\), generic passages that match everything are pushed down.

Why can a single dot product work at all? Because a dot product in \(d\) dimensions can represent a rich similarity only if the structure of relevance is approximately low-rank. Text has this structure: topics, entities and intents are shared across millions of documents. It fails where relevance is combinatorial ("documents that mention X but not Y", "the passage with this exact number"), which is why keyword search and cross-encoders remain necessary partners.

Why does approximate search work despite the "curse of dimensionality"? In the worst case, nearest neighbour search in high dimensions cannot beat a linear scan, and distances between random points concentrate (we measured cosine spread shrinking as \(1/\sqrt d\)). But embeddings are not random: they lie near a much lower-dimensional, clustered structure. IVF exploits the clusters; HNSW exploits the fact that neighbourhoods are navigable; PQ exploits the fact that most of the variance lives in few directions per subspace. Approximate methods work because real data is far from the worst case.

The maths

InfoNCE. With batch similarity matrix \(S\in\mathbb R^{B\times B}\), \(S_{ij}=s(q_i,d_j)\), the loss is row-wise cross-entropy with the diagonal as targets:

\[ \mathcal L = -\frac1B\sum_{i=1}^B\Big[\frac{S_{ii}}{\tau}-\log\sum_{j=1}^B e^{S_{ij}/\tau}\Big]. \]

Its gradient with respect to a query embedding is

\[ \frac{\partial\mathcal L_i}{\partial\mathbf q_i} = \frac1\tau\Big(\sum_j \pi_{ij}\,\mathbf d_j - \mathbf d_i\Big),\qquad \pi_{ij}=\frac{e^{S_{ij}/\tau}}{\sum_k e^{S_{ik}/\tau}}, \]

for \(s=\mathbf q^\top\mathbf d\): gradient descent pulls \(\mathbf q_i\) towards its positive and pushes it away from the softmax-weighted average of all candidates. Small \(\tau\) concentrates \(\pi\) on the hardest negatives. Van den Oord et al. show \(I(q;d)\ \ge\ \log B - \mathcal L\), so a lower loss certifies more mutual information, and the bound can never exceed \(\log B\): one reason larger batches help.

Product quantisation. Split \(\mathbf x\in\mathbb R^d\) into \(m\) sub-vectors \(\mathbf x^{(1)},\dots,\mathbf x^{(m)}\) of dimension \(d/m\). For each subspace learn a codebook \(\{\mathbf c^{(j)}_1,\dots,\mathbf c^{(j)}_{256}\}\) by k-means and store \(\text{code}_j(\mathbf x)=\arg\min_c\lVert\mathbf x^{(j)}-\mathbf c^{(j)}_c\rVert\). For a query \(\mathbf q\), the asymmetric score keeps the query exact:

\[ \mathbf q^\top\mathbf x\ \approx\ \sum_{j=1}^m \mathbf q^{(j)\top}\mathbf c^{(j)}_{\text{code}_j(\mathbf x)} = \sum_{j=1}^m T_j\big[\text{code}_j(\mathbf x)\big], \]

where \(T_j\) is a 256-entry table computed once per query (\(256\cdot d\) multiply-adds in total). Each database vector then costs \(m\) table lookups and additions instead of \(d\) multiply-adds, and its storage is \(m\) bytes instead of \(4d\). The codebook is effectively \(256^m\) centroids (for \(m=8\), about \(1.8\times10^{19}\)) represented with \(256m\) stored vectors.

IVF cost. With \(N\) vectors in nlist lists of average size \(N/\text{nlist}\), a query costs about \(\text{nlist}\cdot d\) (rank the centroids) plus \(\text{nprobe}\cdot (N/\text{nlist})\cdot d\) (scan the lists). Minimising over nlist for fixed nprobe gives nlist \(\approx\sqrt{\text{nprobe}\cdot N}\), the origin of the "about \(\sqrt N\) lists" rule of thumb.

Ranking metrics. For one query with relevant set \(R\) and ranked results \(r_1,r_2,\dots\):

\[ \text{recall@}k=\frac{|R\cap\{r_1..r_k\}|}{|R|},\qquad \text{RR}=\frac{1}{\min\{i: r_i\in R\}},\qquad \text{nDCG@}k=\frac{\sum_{i=1}^{k} \frac{\text{rel}(r_i)}{\log_2(i+1)}}{\text{ideal value of the same sum}} . \]

MRR is RR averaged over queries; for RAG, recall@k usually matters most, because the generator can read all \(k\) passages but cannot read one that was not retrieved.

0.30.50.70.900.10.20.3share of the database scanned per querynprobe 1481632recall@10 vs exact search20,000 vectors, 100 lists
The IVF trade-off measured by the code below: scanning 7% of the vectors finds 77% of the true top-10, 15% finds 90%, 31% finds 97%. The last few points of recall are the most expensive, so decide what recall your application needs before tuning.

Build it

First, the geometry: the cosine–distance identity, and InfoNCE with in-batch negatives at three temperatures.

import numpy as np
rng = np.random.default_rng(0)
unit = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)

a, b = unit(rng.normal(size=(2, 384)))
print(f"cos = {a @ b:.4f}   |a-b|^2 = {np.sum((a - b)**2):.4f}   2 - 2cos = {2 - 2 * (a @ b):.4f}")

# A batch of 4 (query, passage) pairs. Matching passages are noisy copies of their query.
B, d = 4, 384
q = unit(rng.normal(size=(B, d)))
p = unit(q + 0.1 * rng.normal(size=(B, d)))
S = q @ p.T                                       # S[i, j] = cos(query i, passage j)
print("similarity matrix (rows = queries, diagonal = true pairs):")
print(np.round(S, 3))

def info_nce(S, tau):
    """Cross-entropy of picking the true passage (diagonal) among the batch: in-batch negatives."""
    logits = S / tau
    logits -= logits.max(1, keepdims=True)                     # log-sum-exp stability
    log_probs = logits - np.log(np.exp(logits).sum(1, keepdims=True))
    return -np.mean(np.diag(log_probs)), np.exp(np.diag(log_probs))

for tau in (1.0, 0.1, 0.02):
    loss, p_true = info_nce(S, tau)
    print(f"tau={tau:<5} loss={loss:.3f}  P(true passage) per query = {np.round(p_true, 3)}")

Output:

cos = -0.0081   |a-b|^2 = 2.0161   2 - 2cos = 2.0161
similarity matrix (rows = queries, diagonal = true pairs):
[[ 0.45   0.104 -0.122  0.029]
 [-0.011  0.463  0.013 -0.032]
 [ 0.045 -0.028  0.456 -0.096]
 [ 0.026  0.012  0.032  0.44 ]]
tau=1.0   loss=1.067  P(true passage) per query = [0.341 0.348 0.35  0.336]
tau=0.1   loss=0.037  P(true passage) per query = [0.953 0.974 0.972 0.955]
tau=0.02  loss=0.000  P(true passage) per query = [1. 1. 1. 1.]

The diagonal similarities (about 0.45) are only modestly above the off-diagonal ones, yet at \(\tau=0.1\) each query assigns over 95% probability to its own passage. Temperature turns small cosine gaps into confident decisions, which is why it is a key hyperparameter of contrastive training. At \(\tau=1\) the loss barely distinguishes right from wrong, so gradients would be weak.

Second, approximate search: an IVF index and product quantisation built from scratch on 20,000 clustered 64-dimensional unit vectors, measured against exact search.

import numpy as np
rng = np.random.default_rng(0)
N, d, n_q, k = 20_000, 64, 200, 10

def unit(x): return x / np.linalg.norm(x, axis=-1, keepdims=True)
centres = rng.normal(size=(200, d))                       # 200 "topics"
X = unit(centres[rng.integers(0, 200, N)] + 0.6 * rng.normal(size=(N, d)))
Q = unit(X[rng.integers(0, N, n_q)] + 0.3 * rng.normal(size=(n_q, d)))
truth = np.argsort(-Q @ X.T, axis=1)[:, :k]               # exact top-10 by cosine

def kmeans(data, c, iters=10):
    C = data[rng.choice(len(data), c, replace=False)]
    for _ in range(iters):
        a = np.argmin((C**2).sum(1) - 2 * data @ C.T, axis=1)
        C = np.stack([data[a == j].mean(0) if (a == j).any() else C[j] for j in range(c)])
    return C

def recall(found): return np.mean([len(set(f) & set(t)) / k for f, t in zip(found, truth)])

# IVF: cluster the database, search only the nprobe nearest lists.
nlist = 100
C = kmeans(X[:5000], nlist)
assign = np.argmin((C**2).sum(1) - 2 * X @ C.T, axis=1)
lists = [np.where(assign == j)[0] for j in range(nlist)]
print("IVF  nprobe  recall@10  share of vectors scanned")
for nprobe in (1, 2, 4, 8, 16, 32):
    found, scanned = [], 0
    for q in Q:
        ids = np.concatenate([lists[j] for j in np.argsort(-C @ q)[:nprobe]])
        found.append(ids[np.argsort(-X[ids] @ q)[:k]]); scanned += len(ids)
    print(f"     {nprobe:>6}  {recall(found):9.3f}  {scanned / (n_q * N):10.3f}")

# PQ: split each vector into m sub-vectors, quantise each to one of 256 centroids (1 byte).
def pq_search(m, ks=256):
    sub = d // m
    books = [kmeans(X[:5000, i*sub:(i+1)*sub], ks, iters=8) for i in range(m)]
    codes = np.stack([np.argmin((B**2).sum(1) - 2 * X[:, i*sub:(i+1)*sub] @ B.T, axis=1)
                      for i, B in enumerate(books)], axis=1)
    def scores(q):  # asymmetric distance: exact query, database via (m, 256) lookup tables
        tables = np.stack([B @ q[i*sub:(i+1)*sub] for i, B in enumerate(books)])
        return tables[np.arange(m), codes].sum(1)
    top = [np.argsort(-scores(q))[:100] for q in Q]
    rerank = [c[np.argsort(-X[c] @ q)[:k]] for c, q in zip(top, Q)]
    return recall([t[:k] for t in top]), recall(rerank)
print("PQ   bytes/vector  compression  recall@10  top-100 PQ + exact re-rank")
for m in (8, 16):
    r, rr = pq_search(m)
    print(f"     {m:>12}  {d*4//m:>10}x  {r:9.3f}  {rr:10.3f}")

Output (about two seconds on a laptop):

IVF  nprobe  recall@10  share of vectors scanned
          1      0.365       0.007
          2      0.505       0.015
          4      0.638       0.032
          8      0.770       0.069
         16      0.897       0.145
         32      0.972       0.309
PQ   bytes/vector  compression  recall@10  top-100 PQ + exact re-rank
                8          32x      0.208       0.736
               16          16x      0.486       0.967

Read the two tables together. IVF buys speed with recall, and nprobe is a dial you turn at query time. PQ alone is a poor ranker at these code sizes, but as a shortlist generator followed by exact re-scoring of 100 candidates it recovers 0.967 recall from 16-byte codes. That two-stage pattern (cheap and wide, then expensive and narrow) recurs throughout retrieval, and again in re-ranking for RAG.

Things to try

  • Lower the noise in X from 0.6 to 0.3 (tighter clusters). How does IVF recall at nprobe=1 change, and why?
  • Set nlist to 400 and re-run. Compare recall at equal share scanned, not equal nprobe.
  • Combine them: run PQ only inside the probed IVF lists (IVF-PQ). Measure memory, recall and vectors touched.
  • With a real embedding model (for example from Sentence Transformers), embed 1,000 FAQ answers and 50 questions you write, label the right answer for each, and compute recall@⅕/10. Then try the model's query prefix, and without it.

In practice

  • Start exact. Under a million vectors, a flat index (or pgvector without an index) gives perfect recall and is fast enough; add ANN when latency demands it.
  • Normalise and be consistent. Same model, same version, same prefixes, same normalisation for queries and documents. Store the model id with each vector.
  • Evaluate on your own queries. Leaderboards pick candidates; 100 labelled queries from your logs pick the winner.
  • Tune the index for ≥ 0.95 recall against exact search, then stop: the remaining quality is in the model, the chunking and the re-ranker.
  • Plan for filters and deletes from day one (tenancy, permissions, right to erasure).
  • Watch dimensions and precision. 1M × 1,536 float32 vectors are 6.1 GB before index overhead; halving precision or dimension halves that.
  • Pair with keyword search. Exact identifiers, numbers, rare names and code are where dense retrieval is weakest and BM25 is strongest (advanced RAG).

Common misconceptions

  • "Cosine 0.8 means similar." Similarity scales differ by model; calibrate on labelled pairs.
  • "Bigger dimension is better." Past a few hundred dimensions, quality gains are model-specific and small while cost grows linearly; Matryoshka truncation often loses little.
  • "A vector database is required for RAG." It is required for scale and operations, not for correctness. NumPy, FAISS or Postgres are fine for most first versions.
  • "Embeddings understand the question." A bi-encoder compresses the document before seeing the question. Negation, numbers and fine distinctions are often lost; that is what re-rankers are for.

Check yourself

Show that ranking by Euclidean distance and by cosine similarity give the same order for unit vectors.

For unit vectors \(\lVert\mathbf q-\mathbf d\rVert^2 = 1+1-2\mathbf q^\top\mathbf d = 2-2\cos(\mathbf q,\mathbf d)\), a strictly decreasing function of cosine. Smallest distance is largest cosine.

Why do contrastive embedders benefit from large batches?

Each query must pick its positive out of \(B\) candidates, so a larger \(B\) means more (and statistically harder) negatives per step, a more informative gradient, and a higher ceiling on the mutual information the loss can certify (\(I\ge\log B-\mathcal L\)).

A product search works well for descriptions but fails for queries like 'SKU 4471-B'. Why, and what is the fix?

The identifier is rare, has no semantic neighbours, and is fragmented by the tokeniser; a bi-encoder trained on natural-language relevance has no reason to preserve it in the vector. Add keyword (BM25) retrieval, or an exact-match path for identifiers, and fuse the results.

With PQ using m = 16 sub-quantisers of 256 centroids, how many bytes does each vector take, how many distinct codes exist, and how many centroids are stored?

16 bytes per vector. \(256^{16}=2^{128}\approx3.4\times10^{38}\) distinct reconstructions, from only \(16\times256=4{,}096\) stored sub-centroids. That combinatorial codebook is the point of PQ.

Your HNSW index returns 0.99 recall against exact search, but users say answers miss relevant documents. Where do you look?

Not at the index: it already returns what exact search would. Look at the embedding model (domain mismatch, missing query prefix), the chunking (relevant text split or truncated), and the query (needs rewriting), and measure with labelled relevance, not exact-search agreement.

Hard: derive the optimal number of IVF lists for fixed nprobe, and say why real systems deviate from it.

Cost \(\approx d\,(\text{nlist}+\text{nprobe}\cdot N/\text{nlist})\). Differentiate in nlist and set to zero: \(1 = \text{nprobe}\cdot N/\text{nlist}^2\), so \(\text{nlist}=\sqrt{\text{nprobe}\cdot N}\). Real systems deviate because recall at fixed nprobe falls as lists shrink (more boundary effects), because list sizes are unbalanced, because centroid search can itself be indexed, and because memory layout and batching change the constants.

Hard: why does InfoNCE's optimal critic approximate pointwise mutual information, and what does that imply about what the embedding retrieves?

The task is to pick the sample drawn from \(p(d\mid q)\) among samples from \(p(d)\); the Bayes-optimal classifier scores each candidate by the likelihood ratio \(p(d\mid q)/p(d)\), so \(\exp(s/\tau)\propto p(d\mid q)/p(d)\) and \(s\propto\text{PMI}(q,d)\) up to a constant. The model therefore retrieves whatever the training pairs define as belonging together, and penalises generic passages with high \(p(d)\). Train on paraphrase pairs and you retrieve paraphrases; train on question–answer pairs and you retrieve answers.

Go deeper

Papers

Articles

Code and tools

  • FAISS — Meta. The reference ANN library: flat, IVF, PQ, HNSW, on CPU and GPU.
  • pgvector — Vector search inside Postgres, with HNSW and IVFFlat.
  • MTEB leaderboard — Where to shortlist embedding models.

Where this leads