Sub topic 7
Exact top-k search with matrix operations
This chapter assumes you can write basic Python and NumPy, and that you know the dot product and vector length. It also assumes you have met cosine similarity and can produce embeddings with a model such as all-MiniLM-L6-v2. The chapter turns "find the most similar documents" into a few NumPy operations. It also covers how the cost grows, and where this approach stops being practical.
What exact top-k search means
Given a query vector and a collection of document vectors, exact top-k search computes the similarity between the query and every document. It then returns the k documents with the highest scores. It is also called brute-force or flat search. "Exact" means the result is the true top k under your metric. Approximate indexes, covered in a later chapter, trade some of that guarantee for speed.
Brute force is the baseline for every other method. It has no index to build, no tuning parameters, and no recall loss. For collections up to roughly a few hundred thousand vectors, it is often fast enough, and it is the reference you measure approximate indexes against.
From a loop to one matrix product
A direct implementation scores each document in a Python loop. The same work is a single matrix-vector product. Stack the N document embeddings into a matrix D of shape (N, d). If both D and the query q have unit length, then D @ q has shape (N,), and entry i is the cosine similarity between document i and the query.
import numpy as np
rng = np.random.default_rng(0)
N, d = 5000, 384
D = rng.standard_normal((N, d)).astype("float32")
D /= np.linalg.norm(D, axis=1, keepdims=True) # unit-length rows
q = rng.standard_normal(d).astype("float32")
q /= np.linalg.norm(q)
# Loop version: one dot product per document.
loop_scores = np.array([np.dot(D[i], q) for i in range(N)])
# Matrix version: all dot products in one call.
matrix_scores = D @ q
print(D.shape, matrix_scores.shape) # (5000, 384) (5000,)
print(np.allclose(loop_scores, matrix_scores, atol=1e-5)) # TrueBoth versions give the same numbers. The matrix version is much faster because NumPy hands the work to an optimized linear algebra library (BLAS). BLAS uses vectorized CPU instructions and, for larger matrices, several threads. The loop pays Python interpreter overhead on every document.
The same idea extends to many queries. With a query matrix Q of shape (m, d), the product Q @ D.T has shape (m, N). Row j holds the scores of query j against all documents.
Why unit vectors make this work
The matrix product computes dot products. A dot product equals cosine similarity only when both vectors have length 1, because cosine similarity is the dot product divided by the product of the two lengths. If you normalize once at indexing time (for example with normalize_embeddings=True), cosine search reduces to a plain matrix product, with no division at query time.
Euclidean distance gives the same ranking on unit vectors. For unit vectors a and b, the squared distance is ‖a−b‖² = 2 − 2(a·b). Smaller distance therefore means larger dot product, and sorting by either gives the same order.
a = D[0]
b = D[1]
print(np.isclose(np.sum((a - b) ** 2), 2 - 2 * np.dot(a, b), atol=1e-5)) # TrueSelecting the top k
Once you have the N scores, you need the k largest. There are two common approaches.
np.argsort(-scores)[:k]sorts all N scores. The cost is O(N log N).np.argpartition(-scores, k-1)[:k]moves the k best indices to the front in O(N) time, but leaves them in no particular order. You then sort just those k.
For small N, the difference does not matter. For hundreds of thousands of documents and many queries, partitioning saves measurable time. The function below handles one or many queries and returns ids and scores, best first.
import numpy as np
def top_k(doc_emb, queries, k=5):
"""Exact top-k by dot product.
doc_emb: (N, d) array. queries: (d,) or (m, d) array.
Returns (ids, scores), each of shape (m, k), best first.
"""
queries = np.atleast_2d(queries)
k = min(k, doc_emb.shape[0]) # k cannot exceed N
scores = queries @ doc_emb.T # (m, N)
part = np.argpartition(-scores, k - 1, axis=1)[:, :k] # unordered top k
part_scores = np.take_along_axis(scores, part, axis=1)
order = np.argsort(-part_scores, axis=1) # sort only the k winners
ids = np.take_along_axis(part, order, axis=1)
return ids, np.take_along_axis(scores, ids, axis=1)
# Check against a full sort on random unit vectors.
rng = np.random.default_rng(1)
D = rng.standard_normal((2000, 64)).astype("float32")
D /= np.linalg.norm(D, axis=1, keepdims=True)
Q = rng.standard_normal((3, 64)).astype("float32")
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
ids, scores = top_k(D, Q, k=5)
reference = np.argsort(-(Q @ D.T), axis=1)[:, :5]
print(np.array_equal(ids, reference)) # True
print(ids.shape, scores.shape) # (3, 5) (3, 5)The np.take_along_axis calls are what let the code work row by row for a batch of queries. Plain fancy indexing would pick the same columns for every row.
The data flow looks like this:
Putting it together with real text
The sentence-transformers model produces the vectors. The top_k function above does the search. The document ids returned index into your original list of texts.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
docs = [
"Steps to recover access to your account",
"Our office is open from 9 to 5 on weekdays",
"Change your login credentials in the security settings",
"The cafeteria serves lunch at noon",
]
doc_emb = model.encode(docs, normalize_embeddings=True)
queries = ["How do I reset my password?", "When can I get lunch?"]
q_emb = model.encode(queries, normalize_embeddings=True)
ids, scores = top_k(doc_emb, q_emb, k=2)
for qi, query in enumerate(queries):
print(query)
for doc_id, score in zip(ids[qi], scores[qi]):
print(f" {score:.3f} {docs[doc_id]}")Cost: time and memory
Exact search does N·d multiply-adds per query. Doubling the collection doubles the query time. Memory is the other limit.
| Quantity | Formula | Example (N = 1,000,000, d = 384, float32) |
|---|---|---|
| Document matrix | N · d · 4 bytes | about 1.5 GB |
| Score matrix for m queries | m · N · 4 bytes | 100 queries: about 400 MB |
| Work per query | N · d multiply-adds | about 384 million |
Two practical consequences follow.
- Batch the queries, but cap the batch. A large
Qmakes the(m, N)score matrix large. If memory is tight, loop over slices ofQwith, say, 64 queries at a time. - The document matrix must fit in RAM. Storing
float16, or a memory-mapped file, reduces the footprint. Check retrieval quality after any precision change, because lower precision can reorder close scores.
Edge cases
- k larger than N. Without the
min(k, N)guard,argpartitionraises an error. Thetop_kfunction above clamps k. - Ties. Two documents with identical scores come back in an unspecified order. Duplicated documents produce exact ties, so deduplicate your corpus if order matters.
- Zero vectors. An empty string or an all-zero vector cannot be normalized, because its length is 0, and dividing by it yields
nan. Ananscore breaks sorting. Filter out empty texts before encoding. - Dtype mismatch. NumPy promotes mixed
float32andfloat64operands tofloat64. That silently doubles memory and slows the product. Keep both sides infloat32. - Filters. To search only a subset (for example one customer's documents), index into
Dfirst, or set the excluded scores to-infbefore selecting the top k. Remember to map the subset's positions back to the original ids.
When exact search stops being enough
Exact search is a good default. Consider an approximate index when query latency exceeds your budget at your collection size. The limit usually shows up somewhere between hundreds of thousands and a few million vectors, depending on hardware and how many queries arrive at once. Before switching, measure your own latency. Then compare the approximate index's results against this exact search to quantify the recall you give up. That comparison is the main reason to keep a brute-force implementation around.
Exercise
You have 200,000 document embeddings with 768 dimensions stored as float32. How much memory does the document matrix need? You will score a batch of 50 queries at once. How large is the score matrix? Which selection function would you use to get the top 10 for each query, and why?
Show answer
The document matrix needs 200,000 × 768 × 4 bytes = 614,400,000 bytes, about 614 MB. The score matrix has shape (50, 200,000), so it needs 50 × 200,000 × 4 bytes = 40,000,000 bytes, about 40 MB. Use np.argpartition with kth = 9 along axis 1 to pull out the 10 best indices per row in O(N) time, then np.argsort only those 10 scores per row to order them. This avoids sorting all 200,000 scores for each query.
Exercise
Your corpus embeddings were normalized, but a colleague passes unnormalized query vectors to top_k. Does the ranking of documents for a single query change? Do the returned scores change? What about when the document vectors are unnormalized instead?
Show answer
With unnormalized queries and normalized documents, the ranking for one query does not change, because scaling the query by a positive constant scales every score by the same constant. The score values do change, so they are no longer cosine similarities and cannot be compared across queries. With unnormalized documents, the ranking can change, because each score is scaled by a different document length, and longer vectors are favored.