06.3 Similarity Metrics and Nearest-Neighbour Search

RetrievalLesson 3 of 1011,322 words9 parts
Module 06 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

02.3 defined what similarity means for vectors: the dot product, cosine similarity and Euclidean distance, and the rule that on normalized vectors all three produce the same ranking. 06.1 and 06.2 produce the vectors themselves — this lesson is about what you do with them at query time: turning "how similar are these two vectors?" into "which of my million chunks are closest to this query?", exactly, before any approximation enters the picture. You will learn to implement exact k-nearest-neighbour search in NumPy and understand its true cost, to read the wildly different distance conventions used by every vector library and database, to interpret similarity scores honestly (they are not probabilities) and choose thresholds with evidence, to recognise the geometric pathologies that break naive search (anisotropy, hubness), to diversify results with maximal marginal relevance, to use embeddings for clustering, deduplication and outlier detection, to define and measure recall@k — the one number that decides whether an approximate index is good enough — and to know when a non-vector metric or a multi-vector (late-interaction) scorer beats plain cosine search.

What you'll learn

  • Exact k-nearest-neighbour search in NumPy: vectorised scoring of every document, argpartition vs a full sort, batch queries as one matrix multiplication, dtype choices, and the arithmetic that tells you when brute force is the right answer
  • The convention zoo: cosine similarity vs cosine distance, inner-product negation, squared L2, and "distance" values that are really 1 − similarity — per library and per database, in one verified table
  • A model-to-metric cheat sheet: which similarity measure each embedding family was trained for, and the normalisation each one expects
  • Thresholds and score interpretation: score distributions, choosing a cut-off on a labelled set, top-k vs threshold vs both, per-query adaptive thresholds, and what "no good results" should do downstream
  • Anisotropy, mean-centring, whitening and hubness — the geometry quirks that make some documents appear in everyone's top-k — with a runnable demonstration
  • Maximal Marginal Relevance (MMR): full code that trades relevance for diversity, and when near-duplicate chunks make it necessary
  • Embeddings as a general similarity tool: k-means clustering, near-duplicate detection, outlier detection and semi-supervised label propagation (scikit-learn)
  • Approximate vs exact search: the curse of dimensionality in plain English, the precise definition of recall@k, a toy approximate search you can measure, and the recall/latency/memory trade-off
  • Non-vector metrics worth keeping: Jaccard, Hamming and edit distance — and when exact-match similarity beats semantic similarity
  • Late interaction / multi-vector scoring (ColBERT-style MaxSim): the concept, a hand-computed example, and why it exists

What you don't need

  • API keys or any embedding model. Every runnable sample uses tiny hand-made vectors or seeded synthetic data — the same trick 02.3 and 06.4 use — so you can see the algorithms work without a single API call.
  • Knowledge of vector indexes. Approximate indexes (HNSW, IVF, quantization) are 06.4; databases are 06.5. This lesson defines the exact operation those systems approximate, and the recall metric used to judge them.
  • The embedding APIs themselves. 06.1 covers calling them; 02.3, Part 4 covers the metric definitions — this lesson links back rather than repeating them.

Setup

The runnable samples need Python 3.11+, NumPy and scikit-learn:

bash
uv init similarity-search --bare --python 3.13 && cd similarity-search   # first time only
uv add numpy scikit-learn
# or: pip install numpy scikit-learn

These commands install the newest release of each package. The samples and outputs were produced with numpy 2.5.4 and scikit-learn 1.9.1 as of November 2026; a newer major version may change defaults (clustering results in particular can shift), so check the library's changelog if a number does not match. Every output shown below was produced by actually running the code on synthetic data — nothing here calls a model or an API. Where a sample would need a real embedding model or a running database, the code is illustrative and labelled as such.


What you must be able to do after this lesson#

  • Explain what a nearest-neighbour search computes
  • Choose a metric and read scores correctly for it
  • Set a similarity threshold using your own data
  • Use MMR to diversify results
  • Explain the trade-off between exact and approximate search

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just do a brute-force scan, it's only 50k vectors." 1.6 Cost arithmetic
"The index returns distance, not similarity — which direction is better?" 2.1 Similarity, distance and score
"Our cosine scores look different after switching vector DBs." 2.2 The convention table
"Is 0.72 a good match?" 3.1 Scores are not probabilities and 3.3 Choosing a threshold
"Some chunks show up for every query." 4.2 Hubness
"The top-5 results are all the same paragraph reworded." 5 MMR and diversity
"Our recall@10 is 0.94 — is that good?" 7.2 What recall@k means
"Why approximate at all? Why not always exact?" 7.1 Why approximation exists
"The model can't tell 'E-4012' from 'E-4021'." 8 Non-vector metrics
"Can we get ColBERT-quality ranking without re-embedding everything?" 9 Late interaction

Part 1: The search operation, exactly#

1.1 Quick recall: three ways to compare two vectors#

02.3, Part 4 owns the definitions; here is the working table you will use for the rest of the lesson:

Measure What it rewards Range "Better" means On unit-length vectors
Dot product aligned direction and large magnitude any real higher equals cosine similarity
Cosine similarity aligned direction only −1 … 1 higher identical to dot product
Euclidean (L2) distance geometric closeness 0 … ∞ lower d² = 2 − 2·cosine — same ranking as cosine

Two consequences do all the work in this lesson. First, embedding models are trained for one of these measures — almost always cosine — and the model's output vectors are usually already unit-length (normalised), which collapses all three rankings into one. Second, every search system in the wild reports one of these quantities under different names and sometimes inverted signs, which is what Part 2 untangles.

1.2 Exact k-NN: the definition#

k-nearest neighbours (k-NN) search answers one question: given a query vector q and a corpus of N stored vectors, which k stored vectors are closest to q under the chosen measure? "Closest" is defined by the metric — for cosine-trained embeddings, highest cosine similarity (equivalently, smallest cosine distance, or smallest L2 distance on unit vectors).

Formally, exact k-NN computes a score s(q, xᵢ) for every stored vector xᵢ, sorts (or partially sorts) all N scores, and returns the top k. That is the whole algorithm — and its whole cost is N similarity computations per query.

python
# s1_2_exact_knn.py — the whole idea in 15 lines
import numpy as np


def normalize_rows(A: np.ndarray) -> np.ndarray:
    """Project every row onto the unit sphere (length 1)."""
    return A / np.linalg.norm(A, axis=1, keepdims=True)


def exact_topk(X: np.ndarray, q: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray]:
    """Return (indices, scores) of the k docs most similar to q.

    X: (N, d) unit-length document vectors.  q: (d,) unit-length query.
    Scores are cosine similarities: higher is better.
    """
    scores = X @ q                      # (N,) — one dot product per doc
    idx = np.argpartition(-scores, k)[:k]      # k best, unordered
    idx = idx[np.argsort(-scores[idx])]        # order them properly
    return idx, scores[idx]

Two details in that snippet matter more than they look:

  • X @ q computes N dot products in one vectorised operation — a single matrix-vector product, which is what BLAS libraries (and GPUs) are built for. There is no Python loop over documents.
  • np.argpartition(-scores, k)[:k] finds the k largest scores without sorting all N — expected O(N) work instead of O(N log N). The second argsort then sorts only those k values. For k ≪ N this is meaningfully faster than np.argsort(-scores)[:k]; 1.3 shows when each wins.

1.3 Top-k without a full sort: argpartition#

np.argsort sorts everything: O(N log N) comparisons. np.argpartition(a, k) rearranges a so the element at position k is the one that would sit there in sorted order — everything before it is smaller or equal, everything after is larger — without sorting the rest. Run it on the negated scores and the first k slots hold the k largest scores, unordered; selecting those k and sorting them costs O(N + k log k).

python
# s1_3_argpartition.py — same top-3, two ways
import numpy as np

rng = np.random.default_rng(0)
scores = rng.random(1_000_000)          # pretend these are cosine scores

# Full sort: correct, but sorts a million values
top3_sort = np.argsort(-scores)[:3]

# argpartition on -scores: the first 3 slots hold the 3 largest scores
top3_part = np.argpartition(-scores, 3)[:3]
top3_part = top3_part[np.argsort(-scores[top3_part])]   # order them properly

print("same set?", set(top3_sort.tolist()) == set(top3_part.tolist()))
print("top3 by sort:", top3_sort.tolist())
print("top3 by argpartition:", top3_part.tolist())
Output3 lines
same set? True
top3 by sort: [789314, 6138, 938712]
top3 by argpartition: [789314, 6138, 938712]

When does the difference matter? Sorting a million floats takes ~50–100 ms; argpartition does it in ~5–10 ms on typical hardware. At small N (under ~10k) neither is noticeable — the matrix multiply dominates anyway.

1.4 Batch queries: one matrix multiplication#

Search never serves one query at a time. A batch of B queries against N documents is one matrix multiplication: S = Q @ X.T produces a (B, N) score matrix where S[i, j] is the similarity of query i to document j. Top-k is then applied row-wise.

python
# s1_4_batch_knn.py — score 200 queries against 3000 docs in one shot
import numpy as np

rng = np.random.default_rng(7)
N, D, K_TOPICS = 3000, 64, 8

# Synthetic corpus: 8 "topics", each a tight cluster on the unit sphere
centers = rng.normal(size=(K_TOPICS, D))
centers /= np.linalg.norm(centers, axis=1, keepdims=True)
labels = rng.integers(0, K_TOPICS, N)
X = centers[labels] + 0.35 * rng.normal(size=(N, D))
X = X / np.linalg.norm(X, axis=1, keepdims=True)   # unit vectors

Q = centers[rng.integers(0, K_TOPICS, 200)] + 0.35 * rng.normal(size=(200, D))
Q = Q / np.linalg.norm(Q, axis=1, keepdims=True)

S = Q @ X.T                                # (200, 3000) similarity matrix
k = 10
idx = np.argpartition(-S, k, axis=1)[:, :k]         # k candidates per row
gathered = np.take_along_axis(S, idx, axis=1)       # their scores
order = np.argsort(-gathered, axis=1)               # sort within each row
topk_idx = np.take_along_axis(idx, order, axis=1)   # final ids per row
topk_scores = np.take_along_axis(gathered, order, axis=1)

print("score matrix:", S.shape, "-> top-k:", topk_idx.shape)
print("query 0 top-3 doc ids:", topk_idx[0, :3].tolist())
print("query 0 top-3 scores:", topk_scores[0, :3].round(4).tolist())
Output3 lines
score matrix: (200, 3000) -> top-k: (200, 10)
query 0 top-3 doc ids: [196, 1089, 155]
query 0 top-3 scores: [0.4454 0.4044 0.4036]

Three things to notice:

  • S is 200 × 3000 = 600,000 floats — about 2.4 MB in float32. That is the memory cost of exact search: you either materialise the whole score matrix (fast, memory-hungry) or loop over queries and reuse one (N,) score vector (slower per query, tiny memory). For B=1 interactive search, the single-vector version in 1.2 is what you want; for offline batch scoring (evaluation, re-ranking candidates), the matrix version wins.
  • np.take_along_axis is how you sort "each row's top-k" without a Python loop — it gathers and reorders along an axis using an index array.
  • The scores (~0.40–0.45) are cosine similarities of 64-dimensional unit vectors — realistic magnitudes for a small model on clustered data. Real 768- or 1536-dimensional embeddings from current models score differently; the scale is model-specific, which is why Part 3 exists.

1.5 dtypes: float32, float16, and what precision buys you#

Vectors come in three common precisions (quantization in depth is 06.4, Part 4 and 06.2, Part 9):

dtype Bytes per number When it appears
float32 4 The default everywhere; what APIs return unless asked otherwise
float16 2 Half-precision storage/compute; some GPU paths and halfvec in pgvector
int8 / binary 1 / 1 bit Compressed indexes; always paired with rescoring

For exact search, float16 halves memory bandwidth — which is usually the bottleneck for X @ q — at a small accuracy cost. On the same synthetic corpus:

python
# s1_5_dtype.py — float16 vs full-precision top-k agreement
import numpy as np

rng = np.random.default_rng(7)
N, D = 3000, 64
centers = rng.normal(size=(8, D)); centers /= np.linalg.norm(centers, axis=1, keepdims=True)
labels = rng.integers(0, 8, N)
X = centers[labels] + 0.35 * rng.normal(size=(N, D))
X /= np.linalg.norm(X, axis=1, keepdims=True)
Q = centers[rng.integers(0, 8, 200)] + 0.35 * rng.normal(size=(200, D))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
k = 10

def topk_idx(Qm, Xm, k):
    S = Qm @ Xm.T
    idx = np.argpartition(-S, k, axis=1)[:, :k]
    g = np.take_along_axis(S, idx, axis=1)
    o = np.argsort(-g, axis=1)
    return np.take_along_axis(idx, o, axis=1)

a = topk_idx(Q, X, k)
b = topk_idx(Q.astype(np.float16), X.astype(np.float16), k)
overlap = np.mean([len(set(x) & set(y)) / k for x, y in zip(a, b)])
print(f"float16 top-{k} overlap with full precision: {overlap:.1%}")
print(f"memory: float64 {X.nbytes/1e6:.1f} MB vs float16 {X.astype(np.float16).nbytes/1e6:.1f} MB "
      f"(float32 would be {X.astype(np.float32).nbytes/1e6:.1f} MB)")
Output2 lines
float16 top-10 overlap with full precision: 99.8%
memory: float64 1.5 MB vs float16 0.4 MB (float32 would be 0.8 MB)

(The arrays here are NumPy's default float64, which is why the first memory figure is 1.5 MB rather than float32's 0.8 MB; real embeddings arrive as float32.) On well-separated clusters, float16 loses almost nothing. On corpora with many near-tied scores (real embeddings are full of them), expect lower overlap — measure on your data. The rule: float16 for storage and candidate generation, float32 for the final ranking of survivors is the standard production pattern, and it's exactly what "rescore" means in 06.4.

1.6 Cost arithmetic and the break-even point#

Exact search costs, per query:

  • Compute: 2 × N × d floating-point operations (multiply-add counts as two) for the score matrix, plus O(N) for the top-k selection.
  • Memory traffic: N × d × bytes read from wherever the vectors live — RAM if the index is resident, disk if it isn't. For X @ q, memory bandwidth usually beats FLOPs as the limit: a 1M × 768 float32 index is 3 GB that must stream through the memory bus for every query.

Worked example — 1M chunks, d = 768, float32:

Quantity Value
Index size 1,000,000 × 768 × 4 B ≈ 3.1 GB
FLOPs per query 2 × 10⁶ × 768 ≈ 1.5 GFLOP
At ~50 GFLOP/s effective (single-threaded BLAS, typical laptop) ~30 ms compute
At ~20 GB/s memory bandwidth ~150 ms just to read the vectors

So one exact query over a million 768-d vectors is roughly 0.1–0.3 s — fine for a nightly batch job, far too slow for an interactive search box at any real QPS. The crossover where exact search stops being comfortable is typically hundreds of thousands of vectors for interactive latency, and lower if you need many queries per second — but it depends entirely on d, dtype, hardware and whether the index fits in RAM. Treat every number here as an order of magnitude and measure your own hardware:

python
# s1_6_bench_knn.py — time exact search on YOUR machine
import time
import numpy as np

rng = np.random.default_rng(0)
D = 768
Q = 32  # queries per batch

for N in [10_000, 100_000, 1_000_000]:
    X = rng.normal(size=(N, D)).astype(np.float32)
    X /= np.linalg.norm(X, axis=1, keepdims=True)
    Qb = rng.normal(size=(Q, D)).astype(np.float32)
    Qb /= np.linalg.norm(Qb, axis=1, keepdims=True)
    _ = Qb @ X.T                       # warm-up
    t0 = time.perf_counter()
    S = Qb @ X.T
    idx = np.argpartition(-S, 10, axis=1)[:, :10]
    dt = time.perf_counter() - t0
    print(f"N={N:>9,}  batch top-10: {dt*1000:8.1f} ms  ({dt/Q*1000:6.2f} ms/query)")
    del X, S, idx
Example output · illustrative3 lines
N=   10,000  batch top-10:      3.4 ms  (  0.11 ms/query)
N=  100,000  batch top-10:     43.2 ms  (  1.35 ms/query)
N=1,000,000  batch top-10:    463.1 ms  ( 14.47 ms/query)

Linear scaling, as the arithmetic predicts: 10× the vectors ≈ 10× the time. That linearity is exactly what approximation breaks — Part 7 shows what you give up to get it.

1.7 When brute force is the right answer#

Exact k-NN is not a fallback — for many real systems it is the correct production choice:

Situation Why exact wins
Under ~10⁵–10⁶ vectors (depends on d, dtype, latency target) Fast enough; zero recall loss; simplest possible ops
Heavy metadata filtering After filtering you may have only hundreds of candidates — scoring all of them exactly beats any ANN index (06.6)
Need determinism ANN results vary run-to-run and version-to-version; tests and audits sometimes need the true top-k
Small corpora that will stay small A help-centre FAQ of 20k chunks will never need HNSW
Prototype / evaluation harness The ground truth every ANN recall number is measured against is exact search

06.4, Part 1 expands this into the scale-regime decision table; the point here is that "exact" and "approximate" are points on a cost/quality dial, not good-vs-bad.


Part 2: Metric and score conventions#

2.1 Similarity, distance and score: three different things#

The single most confusing thing about vector search is that every system reports its results differently, and the differences are not cosmetic — they decide whether your "highest score wins" code returns the best or the worst documents. Three properties vary independently:

  1. Is the number a similarity or a distance? Similarity: bigger = closer. Distance: smaller = closer. Getting this backwards inverts your ranking — a classic silent bug.
  2. Is it the raw metric or a transformed one? Cosine distance is 1 − cosine similarity. Squared L2 is ‖a−b‖², not ‖a−b‖ — still monotonic (same ranking) but the values differ, which matters for thresholds.
  3. Is there a sign flip for sorting convenience? Databases that only support ascending index scans sometimes return the negative of what you want, so "best" is the most negative number.

Add one more wrinkle: some systems return a score that isn't any of these metrics at all — Elasticsearch rescales similarities into a positive _score where bigger is better but the mapping is piecewise and non-linear (2.2).

2.2 The convention table: every library and database#

Verified against official documentation as of November 2026. "Better" is from the user's perspective.

System Setting / operator Returns Better is Notes
NumPy (this lesson) X @ q on unit vectors cosine similarity higher You choose; dot on unnormalised vectors mixes length in
sentence-transformers model.similarity(a, b) model's similarity_fn_name: cosine (default), dot, euclidean, manhattan higher for cosine/dot; euclidean/manhattan return negative distance so higher is still better Check model.similarity_fn_name; encode(..., normalize_embeddings=True) makes cosine ≡ dot
FAISS IndexFlatL2 / METRIC_L2 squared Euclidean distance lower METRIC_INNER_PRODUCT returns raw inner product (higher better; use faiss.normalize_L2 first for cosine). Cosine = normalise + IP index. The generic IndexFlat accepts other metrics (METRIC_L1, METRIC_Linf, METRIC_Lp, …)
pgvector <-> L2 distance lower <=> cosine distance (1 − cos); <#> negative inner product (Postgres only scans ASC, so "most similar" = most negative); <+> L1; <~>/<%> Hamming/Jaccard for bit vectors. Cosine similarity = 1 − (a <=> b)
Qdrant distance: Cosine / Euclid / Dot / Manhattan similarity for Cosine/Dot, distance for Euclid/Manhattan mixed! Cosine collections auto-normalise vectors at upload, so Cosine ≡ Dot there; Manhattan added in v1.7
Chroma hnsw:space = l2 (default) / cosine / ip distance in all cases lower (0 = identical) cosine returns 1 − cos; ip returns 1 − dot. Chroma's docs warn: normalise embeddings for l2/ip
Elasticsearch / OpenSearch similarity = cosine / dot_product / l2_norm / max_inner_product _score higher Scores are rescaled to be positive; bit vectors only support l2_norm
sqlite-vec vec_distance_cosine / vec_distance_L2 / vec_distance_hamming distance lower vec0 tables take distance_metric=cosine; functions error on mismatched types/lengths
Annoy angular / euclidean / manhattan / hamming / dot distance (angular ≈ cosine distance) lower Static index; angular is the usual choice for embeddings

The pattern to internalise: there is no universal "score". Before writing ORDER BY score DESC anywhere, check three things — similarity or distance, raw or transformed, and whether the value is comparable across queries at all (Part 3).

2.3 The model-to-metric cheat sheet#

The index metric must match what the embedding model was trained for. Verified defaults as of November 2026 (model details live in 06.1 and 02.3):

Model family Trained metric Vectors normalised? Index setting to use
OpenAI text-embedding-3-* cosine yes (documented) cosine distance / IP on unit vectors
Gemini gemini-embedding-001 cosine yes at 3,072 dims; re-normalise after truncation cosine
Gemini gemini-embedding-2 cosine yes, including truncated dims cosine
Voyage voyage-4* cosine yes cosine
Cohere embed-v* cosine yes cosine
Mistral mistral-embed cosine yes (norm 1) cosine
sentence-transformers models varies — read similarity_fn_name only with normalize_embeddings=True whatever the model reports
E5 / BGE / Qwen3-Embedding (open weights) cosine (with required prefixes) normalise yourself cosine
CLIP / SigLIP-style multimodal cosine (scaled by a learned temperature at inference) yes cosine
ColBERT-style multi-vector MaxSim over token vectors per-token normalised late-interaction scorer, not a plain index metric

When in doubt: cosine similarity on L2-normalised vectors is the safe default for text embeddings, and it is what every major embedding API documents. The failures come from mismatches — an IP index over unnormalised vectors, a cosine index over vectors from a model trained for IP, or code that treats a distance as a similarity.

2.4 The mismatch failure, demonstrated#

The nastiest convention bugs don't error — they silently return plausible-looking wrong rankings. Watch what happens when unnormalised vectors meet an inner-product index:

python
# s2_4_metric_mismatch.py — same vectors, wrong index metric
import numpy as np

rng = np.random.default_rng(1)
# "Documents": two topics, but doc vectors have WILDLY different lengths
X = np.array([
    [10.0, 0.0],    # topic A, huge norm (e.g. unnormalised model output)
    [9.5, 0.5],
    [0.1, 10.0],    # topic B, huge norm, different direction
    [0.0, 1.0],     # topic B-ish, TINY norm
])
q = np.array([9.8, 0.4])   # query near topic A

def cosine(x, y):
    return float(x @ y / (np.linalg.norm(x) * np.linalg.norm(y)))

# What cosine says: doc 0 and 1 win
cs = [cosine(q, x) for x in X]
print("cosine ranking:", np.argsort(-np.array(cs)).tolist())

# What inner product says on UNNORMALISED vectors: length dominates
ips = [float(q @ x) for x in X]
print("inner-product ranking:", np.argsort(-np.array(ips)).tolist())
print("IP scores:", [round(v,1) for v in ips])

# The same IP on NORMALISED vectors = cosine ranking
Xn = X / np.linalg.norm(X, axis=1, keepdims=True)
qn = q / np.linalg.norm(q)
ipn = [float(qn @ x) for x in Xn]
print("IP on unit vectors == cosine ranking:",
      np.argsort(-np.array(ipn)).tolist() == np.argsort(-np.array(cs)).tolist())
Output4 lines
cosine ranking: [1, 0, 2, 3]
inner-product ranking: [0, 1, 2, 3]
IP scores: [98.0, 93.3, 5.0, 0.4]
IP on unit vectors == cosine ranking: True

Even here the metrics already disagree on the top spot — cosine prefers doc 1 (marginally better aligned with the query), inner product prefers doc 0 (marginally longer). The failure mode is much clearer with a case where a long, off-topic vector beats a short, on-topic one:

python
# add a long vector pointing 45 degrees off the query's direction
X2 = np.vstack([X, [[80.0, 80.0]]])       # huge norm, mostly off-topic
q2 = np.array([9.8, 0.4])
ip_scores = [float(q2 @ x) for x in X2]
cs_scores = [cosine(q2, x) for x in X2]
print("IP ranking now:", np.argsort(-np.array(ip_scores)).tolist())
print("cosine ranking now:", np.argsort(-np.array(cs_scores)).tolist())
Output2 lines
IP ranking now: [4, 0, 1, 2, 3]
cosine ranking now: [1, 0, 4, 2, 3]

Document 4 — the long vector — wins under inner product purely because ‖q‖·‖x‖ inflates its score (an IP of 816 against ~98 for the best on-topic document), while cosine pushes it behind the two on-topic documents. It still outranks the two genuinely off-topic docs under cosine — 45° off-axis is far more aligned than near-perpendicular — but the point stands: under inner product, length decided the winner, not direction. This is why every "use IP for speed" guide begins with "normalise your vectors first" — and why a vector database configured for Dot/ip over unnormalised embeddings silently prefers whichever documents happen to have the largest vectors.


Part 3: Thresholds and score interpretation#

3.1 Scores are not probabilities#

The question "is 0.72 a good match?" has no answer without three pieces of context:

  • The model. Each embedding model has its own score scale. all-MiniLM-L6-v2 puts unrelated sentences near 0 and paraphrases at 0.6–0.9; anisotropic models (like E5-family models, per 02.3, 4.6) compress almost everything into 0.7–1.0. A "0.72" means something completely different under each.
  • The measure and transformation. A cosine distance of 0.28 is a similarity of 0.72; a Chroma ip score of −49 is a dot product of 50. You can't compare numbers across conventions even on the same vectors.
  • The corpus. Scores are relative to your documents. A query about a niche topic scores low against everything; the same query against a corpus full of near-duplicates scores high.

What a similarity score is good for: ranking. "Doc A is more similar to the query than doc B" is reliable. "Doc A is 80% relevant" is not — there is no calibration behind the number unless you build one.

3.2 Looking at score distributions#

Before choosing any threshold, look at the data. Here is what relevant-vs-irrelevant scores look like on synthetic clustered data (the same 8-topic corpus as 1.4, one query near topic 0):

python
# s3_2_score_distributions.py — relevant vs irrelevant score spread
import numpy as np

rng = np.random.default_rng(11)
D = 32
centers = rng.normal(size=(6, D)); centers /= np.linalg.norm(centers, axis=1, keepdims=True)
q = centers[0] + 0.2 * rng.normal(size=D); q /= np.linalg.norm(q)

# "relevant": docs planted near the query's topic
rel = centers[0] + 0.25 * rng.normal(size=(40, D))
rel /= np.linalg.norm(rel, axis=1, keepdims=True)
# "irrelevant": docs from the other topics
irr = centers[1:6][rng.integers(0, 5, 160)] + 0.4 * rng.normal(size=(160, D))
irr /= np.linalg.norm(irr, axis=1, keepdims=True)

rel_scores = rel @ q
irr_scores = irr @ q
print(f"relevant:    min={rel_scores.min():.3f}  median={np.median(rel_scores):.3f}")
print(f"irrelevant: max={irr_scores.max():.3f}  median={np.median(irr_scores):.3f}")
print(f"overlap region: [{max(rel_scores.min(), irr_scores.min()):.3f}, "
      f"{min(rel_scores.max(), irr_scores.max()):.3f}]")
Output3 lines
relevant:    min=0.062  median=0.378
irrelevant: max=0.467  median=0.007
overlap region: [0.062, 0.467]

Read that carefully: the distributions overlap. The best irrelevant doc (0.467) outscores the worst relevant doc (0.062). No threshold separates them perfectly — which is the normal situation, not a bug. This is why retrieval systems return ranked lists with a cutoff and why downstream stages (reranking, the LLM) exist.

3.3 Choosing a threshold with a labelled set#

When you do need a hard cut-off — deduplication, "show related articles", abstention — choose it on labelled data, not vibes. The procedure:

  1. Collect pairs you know are matches and pairs you know aren't (50–200 is enough to start).
  2. Embed both sides with your production model and preprocessing.
  3. Sweep the threshold and measure the trade-off you actually care about.
python
# s3_3_choose_threshold.py — sweep a similarity threshold on labelled pairs
import numpy as np

rng = np.random.default_rng(11)
D = 32
centers = rng.normal(size=(6, D)); centers /= np.linalg.norm(centers, axis=1, keepdims=True)
q = centers[0] + 0.2 * rng.normal(size=D); q /= np.linalg.norm(q)
rel = centers[0] + 0.25 * rng.normal(size=(40, D)); rel /= np.linalg.norm(rel, axis=1, keepdims=True)
irr = centers[1:6][rng.integers(0, 5, 160)] + 0.4 * rng.normal(size=(160, D))
irr /= np.linalg.norm(irr, axis=1, keepdims=True)
rel_scores = rel @ q          # labelled relevant
irr_scores = irr @ q          # labelled irrelevant

def precision_recall_at(rel_s, irr_s, t):
    tp = int((rel_s >= t).sum()); fp = int((irr_s >= t).sum())
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / len(rel_s)
    return precision, recall

print("threshold sweep (score >= t counts as 'match'):")
print(f"{'t':>5} {'precision':>10} {'recall':>7}")
for t in [0.3, 0.4, 0.5, 0.6, 0.7]:
    p, r = precision_recall_at(rel_scores, irr_scores, t)
    print(f"{t:>5.1f} {p:>10.2f} {r:>7.2f}")
Output7 lines
threshold sweep (score >= t counts as 'match'):
    t  precision  recall
  0.3       0.83    0.72
  0.4       0.94    0.38
  0.5       1.00    0.17
  0.6       1.00    0.05
  0.7       0.00    0.00

The shape of that table is the lesson: raising the threshold trades recall for precision. t=0.4 keeps 38% of relevant docs with 94% precision; t=0.5 is perfectly precise but misses 83% of relevant docs; t=0.7 matches nothing at all. Which point you pick depends on the cost of each error — a dedup job wants high precision (don't merge different things), a "did we find the answer" check wants high recall.

3.4 top-k vs threshold vs both#

Production retrievers almost always combine the two signals:

Strategy Returns Good for Watch out for
top-k only the k best, always RAG pipelines feeding an LLM — you want a fixed context budget Always returns something, even when nothing is relevant
threshold only everything above t "related articles", dedup, alerts Variable result counts; empty results are common and meaningful
top-k AND threshold up to k, only scores ≥ t Search UIs, abstention-aware retrieval Needs both tuned; the empty case must be handled

A useful diagnostic is the score gap — the drop between consecutive ranked scores. Real relevant hits cluster at the top, then there's often a visible "elbow" where scores fall off a cliff:

python
# s3_4_score_gap.py — look for the elbow in a ranked score list
import numpy as np

# plausible cosine scores for one query's top-12 (illustrative shape)
scores = np.array([0.71, 0.68, 0.66, 0.61, 0.44, 0.41, 0.39, 0.37, 0.35, 0.33, 0.31, 0.30])
gaps = scores[:-1] - scores[1:]
for i, (s, g) in enumerate(zip(scores, np.append(gaps, 0))):
    bar = "#" * int(s * 40)
    print(f"{i+1:>2}. {s:.2f}  gap={g:.2f}  {bar}")
elbow = int(np.argmax(gaps)) + 1
print(f"\nlargest gap after rank {elbow} — a candidate cut point")
Output14 lines
 1. 0.71  gap=0.03  ############################
 2. 0.68  gap=0.02  ###########################
 3. 0.66  gap=0.05  ##########################
 4. 0.61  gap=0.17  ########################
 5. 0.44  gap=0.03  #################
 6. 0.41  gap=0.02  ################
 7. 0.39  gap=0.02  ###############
 8. 0.37  gap=0.02  ##############
 9. 0.35  gap=0.02  ##############
10. 0.33  gap=0.02  #############
11. 0.31  gap=0.01  ############
12. 0.30  gap=0.00  ############

largest gap after rank 4 — a candidate cut point

That elbow is a hint, not a rule — the 0.17 drop after rank 4 suggests ranks 5+ are a different population. Use it to sanity-check thresholds, not to set them automatically.

3.5 Per-query adaptive thresholds#

A single global threshold fails because queries have different score scales: a query tightly inside a dense topic scores high across the board; an unusual query scores low everywhere. Two adaptive patterns:

  • Relative to the top score: accept results within α of the best score (score ≥ α · top1). Simple, self-normalising, but fragile when the top hit is an outlier.
  • Relative to the distribution: accept scores above median + β·MAD or top1 − δ, computed per query over the candidate scores. More robust; needs enough candidates to estimate a distribution.

And the downstream consequence: when nothing clears the bar, say so. Returning the top-3 anyway and letting the LLM answer from weakly-related chunks produces confident hallucinations. The abstention behaviour — return "no relevant documents found" and let the caller decide — is a Module 07 concern (07 index); your job here is to surface the signal honestly: return the scores and a best_score/gap alongside the hits so the caller can decide.


Part 4: Geometry quirks — anisotropy and hubness#

Deep-dive

4.1 Anisotropy: everything points roughly the same way#

02.3, 4.6 introduced anisotropy: a model whose vectors crowd into a narrow cone of directions, so every pair scores high. It's why E5-family models put unrelated sentences at 0.7+ while MiniLM puts them near 0.

The standard diagnosis is the mean vector: average all your document vectors. For an isotropic (well-spread) space the mean is near zero; for an anisotropic one it's a large vector pointing in the "common direction" everything shares. The standard remedy is mean-centring: subtract the corpus mean from every vector (query included), re-normalise, then search. A stronger cousin, all-but-the-top removal — which subtracts the mean and projects out the top few dominating principal directions — exists in the literature; see the going-deeper note.

python
# s4_1_anisotropy.py — measure the common direction in your corpus
import numpy as np

rng = np.random.default_rng(11)
N, D = 500, 64
# anisotropic synthetic data: every vector is the shared direction plus a little noise
common = rng.normal(size=D); common /= np.linalg.norm(common)
X = common + 0.3 * rng.normal(size=(N, D)) / np.sqrt(D)
X /= np.linalg.norm(X, axis=1, keepdims=True)

mu = X.mean(axis=0)
print(f"mean-vector norm: {np.linalg.norm(mu):.3f}  (near 0 = isotropic, large = anisotropic)")
print(f"mean pairwise cosine (sample): ", end="")
sample = X[rng.integers(0, N, 200)] @ X[rng.integers(0, N, 200)].T
off = ~np.eye(200, dtype=bool)
print(f"{sample[off].mean():.3f}")
Output2 lines
mean-vector norm: 0.958  (near 0 = isotropic, large = anisotropic)
mean pairwise cosine (sample): 0.918

A mean-vector norm of 0.96 on unit vectors is strongly anisotropic — nearly every vector points along the common direction, and the average pairwise cosine of 0.92 confirms it. Mean-centring then re-normalising is the cheap fix:

python
# centre BOTH corpus and queries by the corpus mean, then re-normalise
mu = X.mean(axis=0)
Xc = X - mu; Xc /= np.linalg.norm(Xc, axis=1, keepdims=True)
q = X[0].copy()
qc = (q - mu); qc /= np.linalg.norm(qc)
print(f"cosine before centring: {float(q @ X[5] / (np.linalg.norm(q)*np.linalg.norm(X[5]))):.3f}")
print(f"cosine after centring:  {float(qc @ Xc[5]):.3f}")
Output2 lines
cosine before centring: 0.917
cosine after centring:  -0.055

The shared direction accounted for almost all of that 0.92 similarity — after centring, the same pair scores ≈ 0. That is the intended effect when the common direction is noise; it is also why centring changes what "similar" means.

4.2 Hubness: some vectors are everyone's nearest neighbour#

Hubness is the weirdo cousin of anisotropy: in high-dimensional spaces, a small number of points end up in many different queries' top-k lists — they are "hubs" — while most points are never anyone's neighbour ("anti-hubs"). It's a documented property of high-dimensional data (Radovanović et al., 2010, Hubs in Space) and it gets worse as dimensionality grows.

The symptom in production: certain chunks — often generic boilerplate, short text, or vectors near the corpus centre — appear in the top results for unrelated queries, crowding out genuinely relevant documents.

python
# s4_2_hubness.py — count how often each doc appears in top-k
import numpy as np

rng = np.random.default_rng(3)
Nh, Dh, K, NQ = 2000, 128, 10, 300
H = rng.normal(size=(Nh, Dh)); H /= np.linalg.norm(H, axis=1, keepdims=True)

# plant 5 "hub" vectors near the mean direction
mu = H.mean(axis=0); mu /= np.linalg.norm(mu)
hub_idx = rng.choice(Nh, 5, replace=False)
H[hub_idx] = 0.7 * mu + 0.3 * H[hub_idx]
H[hub_idx] /= np.linalg.norm(H[hub_idx], axis=1, keepdims=True)

Qh = H[rng.integers(0, Nh, NQ)]
k_occ = np.zeros(Nh, dtype=int)
S = Qh @ H.T
for row in S:
    for j in np.argpartition(-row, K)[:K]:
        k_occ[j] += 1

print(f"top-k occurrences: mean={k_occ.mean():.1f} max={k_occ.max()} "
      f"min={k_occ.min()} skew={((k_occ-k_occ.mean())**3).mean()/k_occ.std()**3:.2f}")
print(f"expected if uniform: {NQ*K/Nh:.1f}")
top = np.argsort(-k_occ)[:5]
print("most frequent:", top.tolist(), "counts:", k_occ[top].tolist())

# remedy: centre BOTH sides, re-normalise
mu_h = H.mean(axis=0)
Hc = H - mu_h; Hc /= np.linalg.norm(Hc, axis=1, keepdims=True)
Qc = Qh - mu_h; Qc /= np.linalg.norm(Qc, axis=1, keepdims=True)
k_occ2 = np.zeros(Nh, dtype=int)
S2 = Qc @ Hc.T
for row in S2:
    for j in np.argpartition(-row, K)[:K]:
        k_occ2[j] += 1
print(f"after centring: max={k_occ2.max()} skew={((k_occ2-k_occ2.mean())**3).mean()/k_occ2.std()**3:.2f}")
Output4 lines
top-k occurrences: mean=1.5 max=10 min=0 skew=1.12
expected if uniform: 1.5
most frequent: [1837, 632, 110, 1702, 994] counts: [10, 9, 9, 8, 7]
after centring: max=10 skew=1.09

Two honest readings of that output:

  • The planted hubs appear up to 10 times where uniformity predicts 1.5 — a ~7× over-representation. Even without planted hubs, real embedding spaces show positive skew.
  • Centring did not fix it here — because we planted the hubs at the mean direction, and centring subtracts exactly that direction from everything. This is the caveat in action: remedies depend on why the hubs exist. If hubs are near-centre vectors, centring can make them worse or unchanged; if they're anisotropy artifacts, it helps. Measure on your corpus before applying any remedy — compute the k-occurrence histogram on a few hundred real queries and see whether a few documents dominate.

Part 5: MMR and diversity#

5.1 The problem: top-k is a relevance ranking, not a result set#

Exact k-NN returns the k most similar documents — but similarity is not relevance, and similar documents are often similar to each other. Three chunks that all say "refunds take 14 days" in slightly different words will fill your top-3, crowding out the warranty and return-policy chunks the user actually needs. This is the near-duplicate problem, and it shows up everywhere: overlapping chunks from 05.6's chunking strategies, boilerplate-heavy pages, template-generated content.

Maximal Marginal Relevance (MMR) (Carbonell & Goldstein, 1998) is the standard greedy fix. Instead of picking the k most relevant documents, pick them one at a time, each time choosing the document that maximises:

text
score(d) = λ · sim(query, d) − (1 − λ) · max sim(d, already_selected)
  • λ = 1 → pure relevance (plain top-k).
  • λ = 0 → pure diversity (each pick maximally different from what's already chosen).
  • 0 < λ < 1 → the trade-off dial. Typical values 0.5–0.8 for retrieval.

5.2 MMR in code#

python
# s5_2_mmr.py — greedy MMR over unit vectors
import numpy as np


def normalize_rows(A):
    return A / np.linalg.norm(A, axis=1, keepdims=True)


def mmr_topk(q, D, k, lam):
    """Greedy MMR. q: (d,) query; D: (N, d) docs; returns selected indices."""
    Dn = normalize_rows(D)
    qn = q / np.linalg.norm(q)
    rel = Dn @ qn                              # relevance of every doc
    selected, remaining = [], list(range(len(D)))
    while remaining and len(selected) < k:
        if not selected:
            best = max(remaining, key=lambda i: rel[i])
        else:
            sel = Dn[selected]                 # (s, d) already chosen
            # each candidate's max similarity to ANY selected doc
            div = (Dn[remaining] @ sel.T).max(axis=1)
            scores = lam * rel[remaining] - (1 - lam) * div
            best = remaining[int(np.argmax(scores))]
        selected.append(best)
        remaining.remove(best)
    return selected

Now watch it work on a corpus where the two most relevant docs are near-duplicates:

python
# s5_2b_mmr_demo.py — relevance vs diversity on 6 docs
import numpy as np
from s5_2_mmr import mmr_topk, normalize_rows

q = np.array([1.0, 0.0, 0.0, 0.0])
docs = np.array([
    [0.95, 0.05, 0.0, 0.0],   # 0: refund policy
    [0.96, 0.04, 0.0, 0.01],  # 1: same policy reworded — near-dup of 0
    [0.90, 0.10, 0.0, 0.05],  # 2: return window — relevant, different angle
    [0.10, 0.90, 0.0, 0.0],   # 3: shipping times — irrelevant
    [0.05, 0.05, 0.90, 0.10], # 4: pricing tiers — irrelevant
    [0.0, 0.0, 0.10, 0.95],   # 5: store locations — irrelevant
], dtype=float)
labels = ["refund policy", "refund policy (reworded)", "return window",
          "shipping times", "pricing tiers", "store locations"]

for lam in [1.0, 0.5]:
    sel = mmr_topk(q, docs, 3, lam)
    print(f"lambda={lam}: {[labels[i] for i in sel]}")
Output2 lines
lambda=1.0: ['refund policy (reworded)', 'refund policy', 'return window']
lambda=0.5: ['refund policy (reworded)', 'refund policy', 'pricing tiers']

Read that second line carefully — it's the honest lesson. With λ=0.5, the third slot went to "pricing tiers", a completely irrelevant doc, because it was maximally different from the two refund docs already chosen. λ=0.5 over-weighted diversity: "return window" lost because it's somewhat similar to the refund docs (all point along the x-axis), while an irrelevant doc won on pure difference.

MMR doesn't create relevance — it redistributes it. The practical guidance:

  • Use MMR when your corpus has known near-duplicate problems (overlapping chunks, templated content) and your downstream consumer is a human scanning results or an LLM with a fixed context budget.
  • Tune λ on labelled data like any threshold — start at 0.7, measure whether diversity helped or hurt.
  • Deduplicate before retrieval when you can — it's cheaper and more reliable than diversifying after the fact. MMR is for the cases where you can't (chunks that are similar but not identical).
  • Cost: each pick costs |remaining| × |selected| extra similarity computations — negligible for k ≤ 20 over hundreds of candidates, which is why MMR is applied to the candidate set, not the whole corpus.

Part 6: Neighbours beyond retrieval#

Deep-dive

Embeddings aren't only for search. Once you have vectors, a whole toolkit of classical ML applies — and scikit-learn implements most of it. All samples below run on synthetic clustered data; swap in your real embeddings (from 06.1/06.2) unchanged.

6.1 Clustering: finding the topics in your corpus#

k-means groups vectors into k clusters by iteratively assigning each vector to its nearest centroid and moving centroids to the cluster means. On embeddings it answers "what topics does my corpus contain?" — useful for corpus exploration, taxonomy discovery, and sampling diverse examples.

python
# s6_1_clustering.py — k-means on synthetic topic clusters
import numpy as np
from sklearn.cluster import KMeans

rng = np.random.default_rng(5)
N, D, KT = 900, 32, 5
cen = rng.normal(size=(KT, D)); cen /= np.linalg.norm(cen, axis=1, keepdims=True)
true_labels = rng.integers(0, KT, N)
E = cen[true_labels] + 0.3 * rng.normal(size=(N, D))
E /= np.linalg.norm(E, axis=1, keepdims=True)

km = KMeans(n_clusters=KT, n_init=10, random_state=0).fit(E)

# purity: fraction of points whose cluster's majority label matches theirs
purity = sum(np.bincount(true_labels[km.labels_ == c], minlength=KT).max()
             for c in range(KT) if (km.labels_ == c).any()) / N
print(f"k-means purity vs planted topics: {purity:.1%}")
print("cluster sizes:", np.bincount(km.labels_, minlength=KT).tolist())
Output2 lines
k-means purity vs planted topics: 95.3%
cluster sizes: [180, 205, 176, 184, 155]

k-means recovered the five planted topics at 95% purity — expected, since the synthetic clusters are well-separated. On real embeddings the clusters are fuzzier; that's fine, because the use is exploration: read a few documents per cluster, name the cluster, and you've got a corpus map. For non-spherical clusters (which embeddings often produce), HDBSCAN (the hdbscan package, PyPI hdbscan==0.8.44 as of November 2026) finds density-based clusters without fixing k — worth trying when k-means gives you one giant cluster plus noise.

6.2 Near-duplicate detection via nearest neighbours#

Finding pairs of near-identical chunks is a nearest-neighbour query with a twist: you want all pairs above a similarity threshold, not top-k per query. scikit-learn's NearestNeighbors does it in one call:

python
# s6_2_dedup.py — find near-duplicate chunks
import numpy as np
from sklearn.neighbors import NearestNeighbors

# five support-macro-like texts; three are the same refund policy reworded
docs = [
    "Refunds are issued within 14 days of receiving the returned item.",
    "You will get your refund within 14 days after we receive the return.",
    "The mobile app is available for iOS and Android.",
    "Team plans let you invite colleagues and share projects.",
    "Refunds take 14 days once the returned item arrives.",
]
# hand-set embeddings: the three refund sentences cluster together
emb = np.array([
    [0.9, 0.1, 0.0], [0.88, 0.12, 0.02], [0.05, 0.9, 0.1],
    [0.1, 0.05, 0.9], [0.87, 0.11, 0.03],
])
emb /= np.linalg.norm(emb, axis=1, keepdims=True)

nn = NearestNeighbors(n_neighbors=2, metric="cosine").fit(emb)
dist, idx = nn.kneighbors(emb)   # dist[i,0] is self (0); idx[i,1] is nearest other
pairs = sorted((dist[i, 1], i, idx[i, 1]) for i in range(len(emb)) if idx[i, 1] > i)
for d, i, j in pairs:
    flag = "  <-- near-duplicate" if d < 0.15 else ""
    print(f"cosine distance={d:.3f}  #{i} ~ #{j}{flag}")
Output2 lines
cosine distance=0.000  #1 ~ #4  <-- near-duplicate
cosine distance=0.001  #0 ~ #1  <-- near-duplicate

The two flagged pairs (#1 ~ #4 and #0 ~ #1) chain all three refund sentences into one duplicate group (#0 and #4 are close too, but each one's single nearest neighbour is #1, so that pair is not listed); the unrelated docs are never flagged. In production this is how you deduplicate a corpus before embedding (06.2 covers dedup at ingestion), detect repeated content across tenants, or find boilerplate that survived cleaning. For N in the millions, NearestNeighbors brute-force is too slow — that's an ANN job for 06.4 or a self-join in your vector DB (06.5).

6.3 Outlier detection#

Vectors far from everything else flag unusual content — spam in a ticket corpus, off-topic chatbot inputs, corrupted parses, injection attempts. LocalOutlierFactor scores each point by how much more isolated it is than its neighbours:

python
# s6_3_outliers.py — LOF on message embeddings
import numpy as np
from sklearn.neighbors import LocalOutlierFactor

msgs = [
    "Your order has shipped.", "Your order is out for delivery.",
    "Your order was delivered.", "Your order has been packed.",
    "Your parcel is on its way to you.", "Your delivery is scheduled.",
    "Congratulations, you won a free cruise! Click here.",
]
# 2-D stand-ins: six shipping messages cluster, the spam is far away
emb = np.array([
    [0.95,0.05],[0.9,0.1],[0.92,0.08],[0.88,0.12],[0.93,0.07],[0.89,0.11],
    [0.1,0.95],
])
emb /= np.linalg.norm(emb, axis=1, keepdims=True)

lof = LocalOutlierFactor(n_neighbors=3, novelty=True).fit(emb)
scores = -lof.score_samples(emb)   # higher = more unusual
for s, m in sorted(zip(scores, msgs)):
    print(f"{s:7.3f}  {m}")
Output7 lines
  0.777  Your order was delivered.
  0.823  Your order is out for delivery.
  0.974  Your delivery is scheduled.
  0.974  Your order has been packed.
  1.026  Your order has shipped.
  1.026  Your parcel is on its way to you.
 22.979  Congratulations, you won a free cruise! Click here.

The spam message scores ~23× the normal ones — an unambiguous outlier. Simpler alternatives that work on embeddings: distance to the corpus centroid, distance to the k-th nearest neighbour, or an isolation-forest on the vectors. All are cheap enough to run as data-quality checks (05.10).

6.4 Label propagation: semi-supervised classification#

When you have a few labelled examples and many unlabelled ones, LabelSpreading diffuses labels across the neighbour graph — "if this unlabelled chunk is nearest to labelled billing chunks, it's probably billing too". It's a cheap baseline for classification and routing before you train anything:

python
# s6_4_label_spreading.py — propagate 6 labels to 6 unknowns
import numpy as np
from sklearn.semi_supervised import LabelSpreading

# 2-D stand-ins for ticket embeddings; -1 = unlabelled
X = np.array([
    [0.95,0.05],[0.9,0.1],[0.92,0.08],    # billing (label 0)
    [0.1,0.9],[0.15,0.85],[0.08,0.92],    # technical (label 1)
    [0.9,0.15],[0.85,0.2],                # unknown, near billing
    [0.2,0.8],[0.12,0.88],                # unknown, near technical
    [0.5,0.5],[0.55,0.45],                # unknown, ambiguous middle
])
y = np.array([0,0,0, 1,1,1, -1,-1, -1,-1, -1,-1])

lsp = LabelSpreading(kernel="knn", n_neighbors=3, alpha=0.2).fit(X, y)
print("predicted:", lsp.transduction_.tolist())
print("counts [billing, technical]:", np.bincount(lsp.transduction_).tolist())
Output2 lines
predicted: [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0]
counts [billing, technical]: [6, 6]

The two near-billing unknowns got label 0, the near-technical ones label 1, and the ambiguous middle point went to technical (label 1) — reasonable given its neighbours. This is the same geometry as zero-shot classification (02.3, 8.2) but uses your labelled data to sharpen the boundaries. For production classification at scale, a small logistic-regression head on frozen embeddings usually beats label spreading — but this is the right first experiment.

6.5 Visualising embeddings#

To see clusters, project to 2-D. 02.3, Part 9 showed PCA in NumPy; scikit-learn wraps it plus t-SNE:

python
# s6_5_viz.py — PCA and t-SNE coordinates for plotting
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

rng = np.random.default_rng(5)
E = rng.normal(size=(300, 64))   # pretend these are embeddings
pca = PCA(n_components=2).fit_transform(E)
tnse = TSNE(n_components=2, random_state=0).fit_transform(E)
print("PCA coords shape:", pca.shape, " t-SNE coords shape:", tnse.shape)
# feed either to matplotlib scatter, coloured by cluster or label
Output1 line
PCA coords shape: (300, 2)  t-SNE coords shape: (300, 2)

PCA preserves global structure (which clusters are far apart); t-SNE preserves local neighbourhoods (which points are similar) but distorts distances — 02.3, 9.2 covers why 2-D plots lie. UMAP (umap-learn, PyPI 0.5.12 as of November 2026) is the modern alternative with better global structure preservation. For exploration only — never evaluate retrieval quality from a plot.


7.1 Why approximation exists: the curse of dimensionality#

Exact k-NN costs N similarity computations per query — linear in corpus size. At a million vectors that's already ~0.1–0.3 s per query (1.6); at a hundred million it's minutes. You cannot brute-force your way out.

Approximate nearest-neighbour (ANN) indexes break the linear scan by touching only a small fraction of the vectors — clustering the space and probing a few clusters (IVF), walking a neighbour graph (HNSW), or compressing vectors so comparisons are cheap (quantization). 06.4 teaches those families in depth. This part is about the contract they all share: they return approximately the right answer, and you need a way to measure how approximately.

The reason approximation is possible at all is subtle: in high dimensions, "nearest" is less special than it looks. Random vectors in 768 dimensions are all roughly equidistant (cosine ≈ 0), so the ranking near the top is decided by small differences — which is exactly what ANN exploits: it doesn't need to find the nearest neighbour, just a set that contains the true top-k often enough.

7.2 recall@k: the number that decides if ANN is good enough#

recall@k for an approximate search is the fraction of the true top-k that the approximate search returned:

text
recall@k = |approx_topk ∩ exact_topk| / k

averaged over queries. Exact search has recall@k = 1.0 by definition. An IVF index probing nprobe=10 of nlist=100 cells might return recall@10 = 0.92 — meaning it found 9.2 of the true top-10 on average.

Why recall and not "accuracy" or "precision": for retrieval, the question is "did we find the right documents?" — missing a relevant chunk is the failure that matters, because nothing downstream can recover it (06.9 reranks what you retrieved; it can't resurrect what recall missed). Precision (are the returned docs relevant?) is a reranking/evaluation concern for 06.10.

python
# s7_2_recall_at_k.py — the metric, precisely
import numpy as np


def recall_at_k(approx_ids, exact_ids, k):
    """Mean fraction of the true top-k found by the approximate search.

    approx_ids, exact_ids: (n_queries, >=k) arrays of document indices.
    """
    hits = [len(set(a[:k]) & set(e[:k])) / k
            for a, e in zip(approx_ids, exact_ids)]
    return float(np.mean(hits))


# toy example: 3 queries, k=3
exact = np.array([[5, 2, 9], [1, 7, 3], [4, 8, 0]])
approx = np.array([[5, 2, 4], [1, 7, 3], [8, 4, 2]])  # misses one each
print(f"recall@3 = {recall_at_k(approx, exact, 3):.3f}")  # 7/9
Output1 line
recall@3 = 0.778

That's the whole metric. Everything in 06.4's tuning procedure is "measure recall@k against exact-search ground truth, then trade it against latency and memory".

7.3 A toy ANN you can measure: LSH-lite#

To make recall concrete, here's the simplest possible approximate search: random hyperplane LSH. Hash each vector by the signs of its dot products with b random directions; vectors that are close tend to land in the same bucket. At query time, scan only the buckets matching the query's signature, rescore exactly.

python
# s7_3_lsh_recall.py — toy LSH + recall measurement on synthetic data
import numpy as np

rng = np.random.default_rng(5)
N, D, KT, K, NQ = 4000, 64, 8, 10, 100
cen = rng.normal(size=(KT, D)); cen /= np.linalg.norm(cen, axis=1, keepdims=True)
lab = rng.integers(0, KT, N)
X = cen[lab] + 0.4 * rng.normal(size=(N, D)); X /= np.linalg.norm(X, axis=1, keepdims=True)
Q = cen[rng.integers(0, KT, NQ)] + 0.4 * rng.normal(size=(NQ, D))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)

def exact_topk(Qm, Xm, k):
    S = Qm @ Xm.T
    idx = np.argpartition(-S, k, axis=1)[:, :k]
    g = np.take_along_axis(S, idx, axis=1)
    o = np.argsort(-g, axis=1)
    return np.take_along_axis(idx, o, axis=1)

def lsh_search(Qm, Xm, k, nbits, n_tables):
    """Return approximate top-k ids per query via random-hyperplane LSH."""
    results = []
    # Precompute signatures per table
    tables = []
    for _ in range(n_tables):
        R = rng.normal(size=(D, nbits))
        R /= np.linalg.norm(R, axis=0, keepdims=True)
        sig = (Xm @ R > 0).astype(np.int64)
        keys = sig.dot(1 << np.arange(nbits, dtype=np.int64))
        lut = {}
        for i, key in enumerate(keys):
            lut.setdefault(int(key), []).append(i)
        tables.append((R, lut))
    for qi in range(len(Qm)):
        cand = set()
        for R, lut in tables:
            sigq = (Qm[qi] @ R > 0).astype(np.int64)
            keyq = int(sigq.dot(1 << np.arange(nbits, dtype=np.int64)))
            cand.update(lut.get(keyq, []))
        if not cand:
            results.append(np.array([], dtype=int)); continue
        cand = np.array(sorted(cand))
        s = Xm[cand] @ Qm[qi]
        results.append(cand[np.argsort(-s)[:k]])
    return results

def recall(approx_lists, exact_idx, k):
    return float(np.mean([len(set(a) & set(e[:k])) / k
                          for a, e in zip(approx_lists, exact_idx)]))

exact_idx = exact_topk(Q, X, K)
for nb in [4, 6, 8, 10]:
    approx = lsh_search(Q, X, K, nbits=nb, n_tables=6)
    approx_arr = np.array([np.pad(a, (0, K-len(a)), constant_values=-1)[:K] for a in approx])
    rec = np.mean([len(set(a[a>=0]) & set(e)) / K for a, e in zip(approx_arr, exact_idx)])
    print(f"nbits={nb}: recall@{K} = {rec:.3f}")
Output4 lines
nbits=4: recall@10 = 0.590
nbits=6: recall@10 = 0.312
nbits=8: recall@10 = 0.120
nbits=10: recall@10 = 0.061

That sweep is the whole ANN story in miniature. Fewer bits → bigger buckets → more candidates scanned → higher recall but slower queries. nbits=4 finds 59% of the true top-10; nbits=10 finds 6% but scans almost nothing. LSH is a deliberately weak ANN — real indexes (HNSW, IVF) are far better — but the shape is identical: a knob trading recall for speed, and recall@k as the way to measure it.

7.4 The recall/latency/memory triangle#

Every ANN index sits on the same three-way trade-off:

flowchart LR
    subgraph ann ["The ANN trade-off"]
        REC["recall@k<br/>(quality ceiling)"]
        LAT["query latency / QPS<br/>(speed)"]
        MEM["index memory<br/>(cost)"]
    end
    REC <-->|"trade"| LAT
    LAT <-->|"trade"| MEM
    MEM <-->|"trade"| REC
  • Recall is set mostly at build time (index structure, quantization) and query time (how much of the index you probe).
  • Latency improves as you probe less — fewer cells, smaller ef, fewer candidates.
  • Memory shrinks with compression (quantization, dimensionality reduction, fewer links) but compression itself costs recall.

You can't maximise all three; you pick an operating point. The procedure — build ground truth once, sweep the query knob, pick the smallest value meeting your recall target — is 06.4, Part 5. What's decided here is the metric that procedure optimises.

7.5 When approximation is acceptable#

ANN is acceptable when:

  • Your corpus is large enough that exact is too slow (1.7 gives the rough boundary).
  • You can measure recall@k on a labelled query set and it meets your bar (typically ≥0.9 for RAG first-stage retrieval; the exact target depends on downstream reranking — 06.10 covers evaluation).
  • You have a fallback: reranking candidates, hybrid keyword search (06.8) catching what dense ANN misses, or the LLM tolerating imperfect context.

ANN is not acceptable when you need the provably-correct top-k (audits, exact dedup, small corpora) or when recall is so low that downstream stages can't recover. The honest summary: ANN trades a measurable, bounded quality loss for orders-of-magnitude speed — and "measurable" is the whole point of recall@k.


Part 8: Non-vector metrics#

Reference

Embeddings capture meaning, not identity. When what matters is exact matching — IDs, SKUs, error codes, names, versions — a non-semantic metric beats cosine every time, because cosine happily reports "E-4012" and "E-4021" as 0.79-similar (02.3, 10.6). Three metrics worth knowing:

8.1 Jaccard similarity: set overlap#

Jaccard similarity = |A ∩ B| / |A ∪ B| — the fraction of combined elements shared by two sets. Tokenise texts into word sets and it becomes a cheap lexical similarity that ignores word order and duplicates.

8.2 Hamming distance: bit differences#

Hamming distance counts the positions where two equal-length bit strings differ. It's what binary-quantized embeddings use (02.3, 10.2), and it's the right metric for binary feature vectors (hashtag sets, permission bits, Bloom-filter-style signatures).

8.3 Edit distance: fuzzy string matching#

Levenshtein (edit) distance counts the minimum insertions, deletions and substitutions to turn one string into another. "warranty" → "warrenty" is 1; "E-4012" → "E-4021" is 2. It's the workhorse of typo-tolerant search and record linkage — and the basis of the fuzzy/typo-tolerant matching covered alongside BM25 in 06.7.

python
# s8_nonvector.py — three non-vector metrics, pure Python
def jaccard(a, b):
    sa, sb = set(a), set(b)
    return len(sa & sb) / len(sa | sb) if sa | sb else 1.0


def hamming_bits(a, b):
    return sum(x != y for x, y in zip(a, b))


def levenshtein(a, b):
    """Minimum single-character edits to turn a into b."""
    if len(a) < len(b):
        a, b = b, a
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j-1] + 1,
                           prev[j-1] + (ca != cb)))
        prev = cur
    return prev[-1]


print("Jaccard {warranty,refund,return} vs {warranty,returns,shipping}:",
      round(jaccard({"warranty","refund","return"},
                    {"warranty","returns","shipping"}), 3))
print("Hamming 10110011 vs 10100011:",
      hamming_bits([1,0,1,1,0,0,1,1],[1,0,1,0,0,0,1,1]), "bit differs")
print("edit distance 'warranty' vs 'warrenty':",
      levenshtein("warranty", "warrenty"))
print("edit distance 'E-4012' vs 'E-4021':",
      levenshtein("E-4012", "E-4021"))
print("edit distance 'kestrel pump' vs 'kestrel pumps':",
      levenshtein("kestrel pump", "kestrel pumps"))
Output5 lines
Jaccard {warranty,refund,return} vs {warranty,returns,shipping}: 0.2
Hamming 10110011 vs 10100011: 1 bit differs
edit distance 'warranty' vs 'warrenty': 1
edit distance 'E-4012' vs 'E-4021': 2
edit distance 'kestrel pump' vs 'kestrel pumps': 1

8.4 When non-semantic similarity wins#

You need to match... Use Because
Exact IDs, SKUs, error codes, clause numbers Edit distance / exact match "E-4012" ≠ "E-4021" semantically near-identical but factually different
Names with typos Edit distance + phonetic (Soundex/metaphone) "Smith" vs "Smyth"
Tag/keyword overlap Jaccard on token sets Order-free set comparison
Binary feature vectors Hamming Fast popcount; the metric binary embeddings are built for
"Same meaning, different words" Cosine on embeddings The whole point of embeddings

The production pattern is hybrid: use the cheap exact metric for the fields where exactness matters (filter on error_code = 'E-4012' in metadata — 06.6), and embeddings for the semantic remainder. 06.7 and 06.8 build the full lexical+semantic system.


Part 9: Late interaction and multi-vector scoring#

Deep-dive

9.1 The idea: don't compress the document to one vector#

Everything so far assumes one vector per text — the bi-encoder approach: embed the query once, embed each document once, compare the two vectors. It works, but it forces the document's entire meaning into a single point. Late interaction keeps many vectors per document — typically one per token — and compares query tokens against document tokens at query time.

The canonical model is ColBERT (Khattab & Zaharia, 2020): a BERT encoder produces a vector for every token in the query and every token in the document. Relevance is scored by MaxSim:

text
score(q, d) = Σ over query tokens i of  max over document tokens j of  sim(qᵢ, dⱼ)

Each query token finds its best-matching document token, those maxima are summed. "capital city" matches "Paris is the capital and largest city" because capital→capital and city→city both score high — fine-grained alignment a single vector can't express.

9.2 MaxSim, hand-computed#

python
# s9_maxsim.py — MaxSim on tiny hand-made token vectors (2-D)
import numpy as np


def normalize_rows(A):
    return A / np.linalg.norm(A, axis=1, keepdims=True)


def maxsim(q_tokens, d_tokens):
    """Sum over query tokens of max similarity to any doc token."""
    Q = normalize_rows(q_tokens)   # (nq, d)
    D = normalize_rows(d_tokens)   # (nd, d)
    return float((Q @ D.T).max(axis=1).sum())


# pretend tokens: query "capital city", docs A and B (2-D stand-ins)
q_tok = np.array([[1.0, 0.0], [0.0, 1.0], [0.7, 0.7]])   # 3 query token vecs
doc_a = np.array([[1.0, 0.0], [0.9, 0.1], [0.2, 0.8]])    # doc A: 3 token vecs
doc_b = np.array([[0.1, 0.9], [0.2, 0.8], [0.0, 1.0]])    # doc B: 3 token vecs

print("similarity matrix Q x docA:")
print(np.round(normalize_rows(q_tok) @ normalize_rows(doc_a).T, 3))
print(f"MaxSim(query, docA) = {maxsim(q_tok, doc_a):.3f}")
print(f"MaxSim(query, docB) = {maxsim(q_tok, doc_b):.3f}")
Output5 lines
similarity matrix Q x docA:
[[1.    0.994 0.243]
 [0.    0.11  0.97 ]
 [0.707 0.781 0.857]]
MaxSim(query, docA) = 2.828  MaxSim(query, docB) = 2.100

Each row of the matrix is one query token's similarity to every doc token; MaxSim takes the row max (1.0, 0.97, 0.857) and sums → 2.828. Doc A wins because its tokens align with the query's — the "late" in late interaction is that this token-level matching happens after encoding, at query time, not inside the model.

9.3 Cost and when it's worth it#

Bi-encoder (what you've used so far) Late interaction (ColBERT-style)
Vectors per doc 1 ~1 per token (hundreds)
Storage N × d N × tokens × d — 50–200× larger
Query cost 1 vector comparison per doc token×token comparisons — needs specialised indexes (PLAID, ColBERTv2's centroid compression, or multi-vector support in Qdrant — verify current support in 06.5)
Quality good recall, loses fine detail better precision on exact-term and phrase matching

The engineering trade: late interaction buys ranking quality at a steep storage and query-cost price. It's why it appears as a reranking option more than a first-stage retriever — 06.9 covers ColBERT/PyLate/RAGatouille in depth, including the MaxSim optimisation tricks that make it practical. The concept to carry forward: the "one vector per text" assumption is a choice, and when it bottlenecks quality, multi-vector scoring is the escape hatch.


Symptom Likely cause Fix
Results look "fine" but wrong docs rank top Distance treated as similarity (or vice versa); index metric ≠ model metric Check the convention table (2.2); verify normalisation
A long, off-topic doc always wins Inner-product index over unnormalised vectors — magnitude dominates Normalise at write time; use cosine metric; re-embed + rebuild index on model change
"0.72 is a great score" on model A, mediocre on model B Scores aren't comparable across models Never port thresholds; re-tune per model (3.3)
Same 3 near-duplicate chunks fill every top-k Corpus has duplicates / overlapping chunks Dedup at ingestion (06.2); MMR (Part 5)
One generic chunk appears for every query Hubness / anisotropy Measure k-occurrence skew (4.2); try mean-centring; improve chunking
NaN scores poisoning results Zero vector from empty input or failed embed validate_embeddings at index time (06.2)
float16 top-k differs from float32 Near-tied scores flip under lower precision Rescore survivors in float32; check overlap on your data
Exact search too slow at scale N × d linear cost exceeded latency budget ANN index (06.4); measure recall@k first
ANN "works" but misses the right doc recall@k below target; reranker can't recover misses Raise probe/ef; hybrid search (06.8); evaluate recall (06.10)
Threshold returns nothing / everything Threshold from another model or stale corpus Re-tune on labelled set; use top-k+threshold combo (3.4)
Confident wrong answers from weak matches Returning top-k regardless of score Surface best_score/gap; abstain downstream (3.5)

Decision table — which similarity operation for which job:

Job Operation Metric k / threshold
RAG first-stage retrieval exact k-NN → ANN at scale cosine on unit vectors top-k (e.g. 20–50 candidates for rerank)
"Related articles" / dedup thresholded similarity cosine threshold tuned on labelled pairs
Near-duplicate detection all-pairs NN above threshold cosine distance strict threshold (e.g. >0.9 sim)
Outlier / anomaly detection distance-to-neighbours / LOF cosine or Euclidean score ranking, not threshold
Topic discovery k-means / HDBSCAN Euclidean on unit vectors choose k by exploration
Exact-ID / SKU / error-code match edit distance / metadata filter Levenshtein / exact —
Fine-grained ranking MaxSim late interaction per-token cosine rerank top-N only

Common misconceptions#

Misconception Reality
"Cosine similarity 0.8 means 80% relevant." Scores are model-specific, uncalibrated ranking signals — not probabilities (3.1).
"All vector DBs return the same kind of score." They return similarity, distance, or rescaled scores under different names and sign conventions (2.2).
"If the index says 'cosine', my vectors are handled correctly." The index metric must match the model's training metric and your vectors must be normalised as that metric expects (2.3).
"ANN returns the same results as exact search, just faster." It returns approximately the same results — recall@k is a measured fraction, never guaranteed (7.2).
"A higher similarity threshold always means better precision." Only if the score distributions actually separate — they often overlap (3.2); and recall collapses as threshold rises (3.3).
"Mean-centring / whitening always improves embeddings." It changes the similarity measure; helps when the common direction is noise, hurts when it's signal. Measure on your data (4.1).
"MMR makes results better." It trades relevance for diversity — too low a λ fills results with irrelevant-but-different docs (5.2).
"Embeddings understand exact identifiers." "E-4012" and "E-4021" are near-identical vectors; use exact metrics/filters for IDs (8, 02.3, 10.6).
"One vector per document is the only way." Late interaction keeps per-token vectors and scores finer-grained matches at higher cost (Part 9).
"k-NN means k-nearest documents." It means k-nearest vectors — which are usually document chunks, but could be images, users, or anything embedded.

Key takeaways#

  • Exact k-NN is the baseline everything approximates. Score every vector, take top-k. Vectorised it's X @ q + argpartition; batch it's one Q @ X.T matmul. Cost is N × d per query — linear, memory-bandwidth-bound, fine to ~10⁵–10⁶ vectors.
  • There's no universal "score". Similarity vs distance, raw vs transformed (1−cos, squared L2, negative IP), rescaled _score — check the convention table before writing ORDER BY anywhere.
  • Match metric to model. Cosine on unit-normalised vectors is the safe default for text embeddings; verify each model's training metric and normalisation, and never mix conventions silently.
  • Scores rank, they don't measure. Choose thresholds on labelled data, expect overlapping distributions, prefer top-k+threshold combos, and surface abstention signals honestly.
  • Geometry has pathologies. Anisotropy (everything scores high) and hubness (some docs appear for everyone) are real; mean-centring/whitening are remedies to measure, not defaults.
  • MMR diversifies greedily via λ·relevance − (1−λ)·max-sim-to-selected; tune λ or deduplicate upstream.
  • Embeddings are a general similarity tool — clustering, dedup, outliers, label propagation all work on the same vectors.
  • recall@k is the ANN contract. Approximate search trades a measurable recall loss for speed; measure it against exact-search ground truth and tune the operating point (06.4).
  • Non-vector metrics win for identity — edit distance for IDs/typos, Jaccard for sets, Hamming for bits; hybrid them with embeddings for the semantic remainder.
  • One vector per text is a choice — late interaction/MaxSim scores token-level matches at much higher storage and query cost (06.9).

Terms introduced in this lesson#

Term One-line definition
Exact k-NN Scoring a query against every stored vector and returning the true top-k
argpartition NumPy's partial-sort: the k largest elements without sorting all N
Score matrix The (n_queries, N) matrix of all pairwise similarities from one matmul
Cosine distance 1 − cosine similarity; what pgvector <=>, Chroma cosine, sqlite-vec return
Negative inner product What pgvector <#> returns so Postgres' ascending index scan yields "most similar first"
Squared L2 What FAISS METRIC_L2 reports — monotonic with L2, different values
Similarity vs distance vs score Three reporting conventions: bigger-better, smaller-better, rescaled-positive
Score threshold A cut-off on similarity score deciding match/no-match
Score distribution The spread of scores for relevant vs irrelevant items — usually overlapping
Precision / recall (at a threshold) Of items above threshold, fraction truly relevant / of truly relevant, fraction caught
Score gap / elbow The drop between consecutive ranked scores; a hint for cut points
Per-query adaptive threshold Threshold relative to each query's own score distribution
Abstention Returning "no relevant results" rather than weak matches
Anisotropy Embedding vectors crowding into a narrow cone → all scores high
Mean-centring Subtracting the corpus mean vector from every embedding to remove the common direction
All-but-the-top Post-processing that removes the corpus mean and projects out the top dominating principal directions — a stronger cousin of mean-centring
Whitening Decorrelating dimensions via inverse-covariance transform (stronger, riskier than centring)
Hubness Some vectors appearing in disproportionately many top-k lists
k-occurrence How often a document appears across queries' top-k — the hubness diagnostic
MMR (maximal marginal relevance) Greedy reranking trading relevance for diversity via λ
recall@k (ANN) Fraction of the true top-k an approximate search returns
LSH (locality-sensitive hashing) Hashing similar vectors to the same bucket via random projections
Jaccard similarity Set overlap: |A∩B| / |A∪B|
Hamming distance Count of differing bit positions between equal-length bit strings
Levenshtein / edit distance Minimum single-character edits between two strings
Late interaction Scoring query↔document token vectors at query time (ColBERT)
MaxSim Late-interaction score: sum over query tokens of max sim to doc tokens
Multi-vector embedding Keeping per-token (or per-chunk) vectors instead of one vector per text

All terms are also collected in the glossary.


Exercises#

  1. Top-k correctness: write exact_topk for Euclidean distance (lower=better) and confirm it returns the same ranking as cosine on normalised vectors for 100 random queries. Then break it by feeding unnormalised vectors — what changes?
  2. argpartition edge cases: test np.argpartition(-scores, k)[:k] when k=1, k=N, and when scores contain ties. Which case raises, and which returns a valid but arbitrarily tie-broken answer? (Hint: k=N raises ValueError; ties never change which scores are in the top-k, only which tied document ids you get, so assert on scores in tests, not on ids.)
  3. Conventions audit: take the convention table (2.2) and write a 10-line score_to_rank adapter that normalises any system's output to "higher = more similar". Test it on FAISS L2 (squared), pgvector <=> (cosine distance), and Chroma ip (1−dot) outputs.
  4. Threshold on your data: if you have embeddings from 06.1, collect 30 query→doc pairs labelled relevant/not and reproduce the 3.3 sweep. Where's your precision/recall elbow?
  5. Hubness hunt: run the 4.2 k-occurrence count on a real corpus of your chunks (a few hundred queries). Do a few documents dominate? What are they?
  6. MMR tuning: extend mmr_topk to also return the relevance rank, and sweep λ ∈ {0.3, 0.5, 0.7, 0.9, 1.0} on a corpus with known duplicates. At what λ does diversity start hurting relevance?
  7. Recall measurement: modify s7_3_lsh_recall.py to also report candidate count per query (how many docs LSH scanned before rescoring) vs recall. Plot the recall-vs-work trade-off — is it the same shape as 06.4's tuning curves?
  8. Non-vector hybrid: build a tiny scorer that combines cosine similarity (semantic) with 1 − normalised_edit_distance (exact) for error-code queries like "E-4012". On which queries does each component win?
  9. MaxSim by hand: with 2-D token vectors, compute MaxSim for a query against three docs where one has all tokens in one place and another spreads them — which wins and why?
  10. Benchmark your hardware: run s1_6_bench_knn.py and record your ms/query at each N. At what N does exact search exceed your latency budget? That number is your ANN threshold.
Hints and what you should see

(Numbers below come from plain-Python versions of the same maths, from outputs this lesson already prints, or are marked "expected"; your own NumPy run should reproduce the plain-Python ones.)

  1. For unit vectors ‖a − b‖² = 2 − 2·cos(a, b), so ranking by ascending Euclidean distance and by descending cosine is the same ranking (up to float ties): expect 100 of 100 queries to agree. With unnormalised vectors they disagree. A plain-Python check with q = (1, 0) and documents A = (0.8, 0.6), B = (3, 0.3) (long, almost the same direction as q), C = (0.5, 0.9): cosine ranks B (0.995) > A (0.800) > C (0.486), but raw Euclidean distance ranks A (0.632) < C (1.030) < B (2.022), so B drops from first to last, because L2 punishes length and cosine ignores it. After normalising, L2 gives B (0.100) < A (0.632) < C (1.014), the same order as cosine. The fix is to normalise once, at ingest, or to choose the metric deliberately.

  2. Each case in your test: k=1 works (one slot); k=N raises ValueError (the kth index must be smaller than N), so guard it as 1.3 shows; with ties, assert on the sorted scores of the result, never on ids.

  3. A small adapter that is correct for unit vectors (checked in plain Python by simulating each system's output for three documents; all three adapters recovered the same cosine values and the same order a > c > b):

    python
    def score_to_rank(value, system):
        """Normalise a raw output to 'higher = more similar'."""
        if system == "faiss_l2_squared":          return 1 - value / 2   # unit vectors: d2 = 2 - 2cos
        if system in ("pgvector_cosine_distance", "chroma_ip", "chroma_cosine"): return 1 - value
        if system == "pgvector_neg_inner_product": return -value          # <#> returns -dot
        if system in ("similarity", "faiss_ip", "qdrant_cosine"):         return value
        raise ValueError(system)

    For FAISS the 1 - d/2 form only equals cosine on unit vectors; on unnormalised vectors use -d (rank only) and do not compare values across queries. Test it by feeding each system's raw output for the same three vectors and asserting identical order.

  4. Reuse precision_recall_at from 3.3 with a finer grid of thresholds. Expected shape, as in the lesson's table: precision rises and recall falls as t rises; pick t where precision meets your target (say 0.95) with the most recall left, or the F1 maximum, and report how many labelled pairs back the choice. With 30 pairs, one flipped label moves precision by several points, so give a range, not a decimal. The elbow depends on your model and data, so there is no number to match.

  5. Expected shape from the lesson's own run (mean 1.5 occurrences, max 10, skew 1.12): a skewed count where a few documents appear far above the mean and many appear zero times. On real chunk corpora the dominant ones are typically generic, short or boilerplate chunks (tables of contents, headers, legal footers, "contact us"). That is typical, not guaranteed: look at the top five and decide whether to deduplicate, re-chunk or rerank them (see the mitigations at the end of 4.2).

  6. Ran in plain Python on the 6-document demo (4-D vectors), returning each pick's relevance rank (1 = most similar to the query):

    λ Selected (relevance rank)
    0.3 reworded refund policy (1), store locations (6), shipping times (4)
    0.5 reworded refund policy (1), refund policy (2), pricing tiers (5)
    0.7, 0.9, 1.0 reworded refund policy (1), refund policy (2), return window (3)

    The row for 0.5 reproduces the lesson's output. Stepping λ in 0.05 shows the third pick flips from the irrelevant "pricing tiers" to the relevant "return window" at λ = 0.55, so on this corpus diversity starts hurting relevance below about 0.55. At 0.3 even the second pick is the least relevant document. All three relevant documents point the same way (they are the corpus's only relevant ones), so any λ that prefers diversity must reach into irrelevant documents; on your corpus with known duplicates the threshold will move. Extend mmr_topk to return [(i, rel[i], rank_of_i)] and plot mean relevance rank of the selected set against λ.

  7. Expected shape, not run here: the number of distinct candidates falls steeply as nbits grows. Each table splits the corpus into 2^nbits buckets, so a bucket holds roughly N / 2^nbits vectors on uniform data (about 250 at nbits=4, about 4 at nbits=10 for N=4000), and n_tables=6 multiplies that by up to 6 minus overlap. The data is clustered, so real buckets are bigger than that. Plot recall (0.590, 0.312, 0.120, 0.061 from the lesson) against your candidate counts: recall rises with work, as in 06.4's curves, but LSH needs far more candidates for the same recall than IVF or HNSW, which is why it is a teaching tool here.

  8. A scorer: score = alpha * cosine + (1 - alpha) * (1 - levenshtein(q, d) / max(len(q), len(d))), lower-casing both strings first (e-4012 against E-4012 scores 0.833 without it, 1.0 with it). Ran on the string part alone, for the query E-4012: itself 1.000, E-4013 and E-5012 0.833, E-4021 and E-4102 0.667, and payment gateway timeout 0.043. So the string metric separates near-identical codes that an embedding model tends to place almost on top of each other (the point of 8.4), and wins for exact identifiers and typos. The embedding wins for paraphrases and descriptions ("payment gateway timed out" should find the error's explanation although the two share no characters in common), where the string score is about 0. The lexical score also hurts when a query is a sentence: the edit distance to a long document is dominated by length, so apply it only to short fields such as codes and titles. You need your own embeddings from 06.1 for the cosine half; no numbers are given for it here because they depend on the model.

  9. Ran in plain Python with query tokens (1, 0) and (0, 1): a document with all its tokens in one place, (1, 0) and (0.9, 0.1), scores MaxSim 1.100 (the second query token finds nothing close); a document with tokens spread across both directions, (1, 0) and (0, 1), scores 2.000; a single blended token (0.7, 0.7) scores 1.414 (each query token matches it at 0.707). The spread document wins because MaxSim lets every query token pick its own best partner, so coverage of all query tokens counts. A single mean-pooled vector cannot make that distinction: the pooled cosine to the pooled query is 1.000 for both the spread and the blended document (it separates only the clustered one, at 0.743), which is the information late interaction keeps.

  10. Expected shape: time per query grows about linearly with N, as in the lesson's illustrative table (about 0.1, 1.4 and 14.5 ms/query at 10k, 100k and 1M on the author's machine, yours will differ). Your ANN threshold is N_max = budget_ms / (ms_per_query / N), with ms_per_query / N taken from your largest run. Example with the illustrative figures: 14.47 ms at 1M gives about 1.4M vectors for a 20 ms budget. Re-run with Q = 1 to get interactive single-query latency, since the batch of 32 amortises memory traffic, and re-check at your real d and dtype.


Check yourself#

  1. What does exact k-NN compute per query, and why is it O(N) not O(N log N) with argpartition?
  2. Name the three things that vary between libraries' "score" conventions.
  3. Why does inner product on unnormalised vectors prefer long vectors regardless of meaning?
  4. What does pgvector's <#> operator return, and why?
  5. What is cosine distance, and which systems return it under a name that sounds like similarity?
  6. Why can't you compare a similarity score of 0.7 across two different embedding models?
  7. What three signals decide whether a threshold-based matcher works?
  8. What's the difference between top-k, threshold, and top-k+threshold retrieval?
  9. What is anisotropy, and what's the cheap remedy (and its caveat)?
  10. What is hubness, and how do you detect it on your own corpus?
  11. Write the MMR score formula and explain what λ controls.
  12. What does recall@k measure for an ANN index, and why is it the ceiling on downstream quality?
  13. In the LSH demo, what happens to recall as nbits decreases, and why?
  14. When is a non-vector metric (edit distance, Jaccard) better than cosine?
  15. How does MaxSim differ from comparing one query vector to one document vector?

Further resources#

  • 02.3 Embeddings: Part 4 (metric definitions), 4.6 (score interpretation), 10A.6 (limits), 10A.8 (beyond one vector).
  • 06.1 Embedding Models and APIs and 06.2 Embedding Pipelines: producing the vectors this lesson searches.
  • 06.4 Vector Indexes: HNSW, IVF, quantization, and the recall/latency/memory tuning procedure.
  • 06.5 Vector Databases and 06.6 Filtering: where these operations run in production.
  • 06.7 Keyword Search and 06.8 Hybrid Search: the lexical half of retrieval.
  • 06.9 Reranking: cross-encoders and late interaction in depth.
  • 06.10 Evaluating Retrieval: measuring retrieval quality properly.
  • pgvector: github.com/pgvector/pgvector README — distance operators and index ops classes.
  • FAISS: github.com/facebookresearch/faiss wiki "MetricType and distances" and "Faiss indexes".
  • Qdrant: qdrant.tech/documentation — "Distances" and "Collections" (metric names, auto-normalisation).
  • Chroma: docs.trychroma.com/docs/collections/configure — hnsw:space values and distance semantics.
  • Elasticsearch: elastic.co/docs — dense_vector similarity values (cosine, dot_product, l2_norm, max_inner_product).
  • sqlite-vec: alexgarcia.xyz/sqlite-vec/api-reference.html — distance functions.
  • sentence-transformers: huggingface.co/docs/sentence-transformers — similarity_fn_name, normalize_embeddings.
  • MMR: Carbonell & Goldstein, "The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries" (SIGIR 1998).
  • Hubness: Radovanović, Nanopoulos & Ivanović, "Hubs in Space: Popular Nearest Neighbors in High-Dimensional Data" (JMLR 2010).
  • ColBERT: Khattab & Zaharia, "ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT" (SIGIR 2020); ColBERTv2 (NAACL 2022).
  • scikit-learn: scikit-learn.org — KMeans, NearestNeighbors, LocalOutlierFactor, LabelSpreading, PCA, TSNE.

← 06.2 — Embedding Pipelines: Batching, Caching, Scale and Cost | Module 06 overview | 06.4 — Vector Indexes: HNSW, IVF, Quantization and Trade-offs →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close