Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Embedding dimension
- How many numbers a model uses to describe one text; the tracker’s model uses 384.
- Distance concentration
- In many dimensions the nearest and farthest points from a query end up at similar distances.
- Nearest/farthest distance ratio
- The nearest distance divided by the farthest, for one query: a value near 0 means the closest distance is small relative to the farthest. A value near 1 means little relative separation. When all distances are zero, this ratio is undefined.
- Approximate nearest neighbour (ANN) index Also HNSW, IVF
- A search structure that visits a small part of the data and usually, not always, returns the true nearest items.
- Recall@k
- The share of the exact k nearest items that the index returned, in any order.
Why this matters
Semantic search, duplicate detection and retrieval for AI assistants all rank items by the distance between embeddings, lists of hundreds of numbers a model produces for each text. In that many dimensions distances behave differently from the two-dimensional pictures we reason with, and the index that makes the search fast is allowed to miss.
This lesson assumes vectors, square roots and percentages.
Distance in many dimensions
An embedding represents an item as a vector. Recall that Euclidean distance takes the square root of the summed squared coordinate differences; adding dimensions adds terms to that sum. High-dimensional intuition concerns the spread of those distances as well as their size.
Concentration means that nearest and farthest distances can become similar relative to their size. An approximate index adds a separate question: how many exact nearest neighbours did the search retrieve? The random-point example isolates the geometry; real embeddings still need measurement and labelled matches.
01Distance between embeddings
Distance between embeddings
Your issue tracker suggests possible duplicates while someone files a bug. After the team switched to a 384-dimension embedding model and an approximate index, clear duplicates were sometimes missed, and reports like “app is slow sometimes” got a confident suggestion that had nothing to do with them.
The tracker embeds each issue’s title and description into 384 numbers. The distance between two issues is the square root of the summed squared differences, the same formula as on a map with more terms. The lab uses separate four-component worked embeddings so every contribution is visible; they are not four selected coordinates from the 384-component vectors. In that reduced model, a new report about the CSV export dropping its last row is 0.0854 from issue 4127, which describes the same bug, and 1.3195 from the farthest open issue. The worked lab accepts at most 10,000 total embedding components and nonempty same-dimension vectors. Inputs, each component difference, each squared difference, accumulated squared-distance sum and resulting distance are finite in binary64; when farthest>0, the computed nearest/farthest ratio is finite. This is a supplied valid-input precondition, not a generic overflow-handling exercise. All-zero distances still produce ratio none and ties retain input order.
Search code often compares squared distances, since dropping the square root keeps the order. That works for ranking, but not when you compare one distance with another: the squares give 0.0073 and 1.7410, and their ratio 0.0042 instead of 0.0648.
02Everything is about equally far
Everything is about equally far
Predict how the ratio changes as the dimension grows.
// 500 random points and a query in d dimensions: how much nearer is the nearest than the farthest?
let state = 42;
const rand = () => (state = (state * 48271) % 2147483647) / 2147483647;
for (const d of [2, 16, 128, 384]) {
const point = () => Array.from({ length: d }, rand);
const points = Array.from({ length: 500 }, point);
const query = point();
const distances = points.map((p) =>
Math.sqrt(p.reduce((sum, x, i) => sum + (x - query[i]!) * (x - query[i]!), 0))
);
const near = Math.min(...distances);
const far = Math.max(...distances);
console.log(
`d=${d} nearest ${near.toFixed(2)} farthest ${far.toFixed(2)} ratio ${(near / far).toFixed(2)}`
);
}
In 2 dimensions some point is almost on top of the query and the ratio is 0.01. In 384 dimensions the nearest of 500 random points is 7.09 away and the farthest 8.66: a ratio of 0.82. Each extra coordinate adds a little independent difference, and those sums all grow toward the same size. Real embeddings have more structure than random points, but this does not prove that every vague report behaves like random points. Measure the actual embedding distribution and calibrate the decision on labelled pairs.
03Judge the nearest against the farthest
Judge the nearest against the farthest
The old panel suggested the nearest issue whenever it was closer than 0.9, a number tuned by eye on the previous model. Distances from a different model have a different scale, and a vague report is 0.77 from its nearest issue only because it is about that far from everything.
| Report | Nearest | Farthest | Ratio | Panel |
|---|---|---|---|---|
| CSV export drops the last row | #4127 0.0854 | 1.3195 | 0.0648 | suggest #4127 |
| App is slow sometimes | #4415 0.7721 | 0.8703 | 0.8871 | nothing |
04Why the index is approximate
Why the index is approximate
The tracker holds 400,000 issues. An exact search computes 400,000 × 384 = 153,600,000 coordinate contributions for every keystroke pause, over 614 MB of 32-bit floats. An HNSW index instead walks a graph of neighbours and looks at a few thousand vectors. It is fast and usually right, and because distances bunch together in many dimensions, a near miss can lead it down the wrong part of the graph.
Computing the exact farthest issue also requires a full scan; the relative-distance rule here is an offline/small-set diagnostic, not a free HNSW operation. An online implementation needs to measure that cost or validate a cheaper reference-set approximation separately. Recall@k measures the index independently: take a sample of reports, find their exact k nearest issues with a full scan, and count how many the index returned, in any order, out of k. For the CSV report the exact three are 4127, 4415 and 4501; the index returned 4127, 4501 and 3856, so recall@3 is 2 / 3 = 0.67. Count distinct retrieved IDs: repeated copies of #4127 are still one found neighbor. If all distances are zero, near/far is mathematically undefined; the diagnostic prints none for the ratio and makes no claim of separation. The suggestion rule separately treats an exact zero-distance candidate as a possible match, keeping input order on a tie.
From Node.js the vectors usually live in Postgres: pgvector’s HNSW index answers ORDER BY embedding <-> $1 approximately, and the same query with the index disabled gives the exact neighbours to measure recall against.
05What recall does not say
What recall does not say
06Fix the duplicate suggestions
Fix the duplicate suggestions
Calculate the full distances on a small audit set before changing the suggestion rule. Then separate the label-quality question from the search-quality question: a low relative distance can justify a possible-match notice, while recall compares distinct returned IDs with an exact scan.
An issue tracker’s possible duplicates
Compute distances, suggest clear duplicates, then measure the index.
In the frontend The possible-duplicate notice in Next.js and Svelte Optional
The new-issue form gets the nearest matches and the farthest distance from the search endpoint, and shows a notice only when the nearest clearly stands out.
// The new-issue form: show a possible duplicate only when the nearest issue clearly stands out.
type Match = { id: number; title: string; distance: number };
export function PossibleDuplicate({
matches,
farthest,
ratio
}: {
matches: Match[];
farthest: number;
ratio: number;
}) {
const nearest = matches[0];
if (!nearest || !(nearest.distance === 0 || nearest.distance < ratio * farthest))
return null;
return (
<aside>
Possible duplicate:{' '}
<a href={`/issues/${nearest.id}`}>
#{nearest.id} {nearest.title}
</a>
</aside>
);
}
Check this idea later
Sources
- pgvector: HNSW indexes and ef_search
- FAISS: index types (IndexFlatL2, IndexHNSWFlat)
- Malkov and Yashunin: Efficient and robust approximate nearest neighbor search using HNSW graphs
- Beyer et al.: When is “nearest neighbor” meaningful?
Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The tracker, issue numbers and four-number vectors are a worked model; the 500-point example uses a fixed-seed generator.
Sign in to keep your read marks on every device. Sign in
Was this helpful?