Sub topic 3
Exact nearest neighbor search with brute force
Prerequisites
This chapter assumes you can read basic Python and NumPy, and that you know what a dot product is. You should also know that an embedding is a vector, and that the previous chapter covered how metrics such as cosine similarity and Euclidean distance compare two vectors.
What exact search does
Exact nearest neighbor search is also called brute force or a flat scan. It compares the query against every stored vector, scores each one, and returns the best k. Nothing is skipped, so the answer is always correct for the metric you chose.
This makes it the baseline for the rest of the tutorial. Later chapters build approximate indexes. You will judge them by how closely their results match this exact answer.
A worked example
The code below uses cosine similarity. If you scale every vector to length 1, cosine similarity equals the dot product. The whole database can then be scored with one matrix product.
import numpy as np
rng = np.random.default_rng(0)
vectors = rng.normal(size=(1000, 64)).astype("float32")
query = rng.normal(size=64).astype("float32")
def normalize(x):
return x / np.linalg.norm(x, axis=-1, keepdims=True)
# After normalization, the dot product equals cosine similarity.
scores = normalize(vectors) @ normalize(query)
top5 = np.argsort(-scores)[:5]
print(top5, scores[top5])Here is how it works:
vectorsholds 1,000 vectors of 64 dimensions. Rowiis the vector with idi.normalizedivides each vector by its length. Theaxis=-1argument computes the length of each row separately.normalize(vectors) @ normalize(query)multiplies a 1000 by 64 matrix by a vector of length 64. The result is 1,000 scores.np.argsort(-scores)sorts from highest to lowest score. The first five positions are the ids of the best matches.
Cost
Scoring one vector takes about d multiplications and additions, where d is the number of dimensions. Scoring N vectors takes about N × d operations. Memory is also N × d × 4 bytes for float32.
| Vectors (N) | Dimensions (d) | Memory in float32 |
|---|---|---|
| 1 million | 768 | about 3 GB |
| 100 million | 768 | about 307 GB |
| 1 billion | 1536 | about 6 TB |
The cost grows linearly with N. Doubling the data doubles the work per query. The next chapter looks at why this becomes a problem at scale.
Common errors
- Forgetting to normalize. Without normalization, a dot product favors long vectors. It no longer measures cosine similarity.
- Sorting everything.
argsortsorts all N scores, which costs O(N log N). For large N,np.argpartitionfinds the top k in O(N) time. You then sort only those k results. - Mixing up distance and similarity. For Euclidean distance, smaller is better. For cosine similarity and dot product, larger is better. Negating the scores, as in
-scoresabove, handles the second case. - Normalizing the query only. Normalize both sides, or normalize the stored vectors once when you insert them. Doing it once at insert time avoids repeating the work on every query.
Why it still matters
Brute force is also a tool for testing. To measure an approximate index, run the same queries through both and compare the ids. The overlap is the recall, which a later chapter covers in detail. Keep a flat index around as your ground truth.
Exercise
A collection has 2 million vectors with 384 dimensions stored as float32. Roughly how much memory do the vectors need, and how does the work per query change if the collection grows to 4 million vectors?
Show answer
Memory is 2,000,000 × 384 × 4 bytes, which is about 3.07 GB. Brute-force cost is linear in N, so at 4 million vectors the memory and the work per query both double, to about 6.1 GB and twice the scoring operations.
Exercise
You replace np.argsort(-scores)[:5] with np.argpartition(-scores, 5)[:5] to speed up the search. What extra step do you need, and why?
Show answer
argpartition places the five best items in the first five positions but does not order them among themselves. You must sort those five by score, for example with idx[np.argsort(-scores[idx])], to get them in ranked order.