Sub topic 7
Exact top-k search with matrix operations
This chapter assumes you know basic Python and NumPy, and that you can compute a dot product and a vector length. It also assumes you have met cosine similarity and know how to produce embeddings with a pretrained model. Here you turn those pieces into a working search.
The idea: one matrix product scores everything
Exact search, also called brute-force search, compares the query to every document vector and keeps the best k. It sounds slow, but the comparison is a single matrix operation, and NumPy runs it in optimized native code.
Suppose you have N documents embedded as an N x d matrix. If every vector has unit length, cosine similarity equals the dot product. Multiplying the matrix by the query vector of length d gives a vector of N scores, one per document.
import numpy as np
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)
def search(query, k=2):
q = model.encode(query, normalize_embeddings=True)
scores = doc_emb @ q # cosine similarity, since vectors are unit length
top = np.argsort(-scores)[:k] # indices of the k highest scores
return [(docs[i], float(scores[i])) for i in top]
for text, score in search("How do I reset my password?"):
print(f"{score:.3f} {text}")The two account-related documents should come first, even though neither contains the word "password". The scores are cosine values, so higher means closer.
Step by step
doc_embhas shape(4, 384). Each row is one document.qhas shape(384,). It is the query embedded the same way as the documents.doc_emb @ qhas shape(4,). Entryiis the dot product of documentiwith the query.np.argsort(-scores)sorts ascending on the negated scores, so the best document comes first. Slicing[:k]keeps the top k.
Batching queries
To run many queries at once, stack them into a Q x d matrix and compute Q_emb @ doc_emb.T. The result has shape (Q, N), and each row holds the scores for one query. This is faster than looping, because one large matrix product uses the CPU or GPU more efficiently than many small ones.
Common errors
- Forgetting to normalize. The dot product equals cosine similarity only for unit-length vectors. If you skip
normalize_embeddings=True, long vectors score higher regardless of direction. - Embedding the query differently from the documents. Use the same model and the same settings for both sides.
- Sorting the wrong way.
np.argsort(scores)sorts ascending. Negate the scores or reverse the result. - Using
klarger than N. Slicing is safe, but you get fewer than k results.
Cost and when to stop using it
Each query costs about N * d multiply-adds, so time grows linearly with the collection size. The matrix itself takes N * d * 4 bytes in float32. One million 384-dimensional vectors take about 1.5 GB. Exact search is a good default up to roughly hundreds of thousands of vectors, and it always returns the true nearest neighbors, which makes it the baseline for judging approximate methods later.
For large N, np.argsort sorts all scores, which wastes work. np.argpartition(-scores, k)[:k] finds the top k in linear time, and you then sort only those k.
import numpy as np
def top_k(scores, k):
k = min(k, len(scores))
idx = np.argpartition(-scores, k - 1)[:k]
return idx[np.argsort(-scores[idx])]
scores = np.array([0.1, 0.9, 0.4, 0.8, 0.2])
print(top_k(scores, 3)) # [1 3 2]Exercise
You have 200,000 documents embedded as unit-length float32 vectors with 768 dimensions. Roughly how much memory does the matrix need, and why is argpartition preferable to argsort for getting the top 10?
Show answer
The matrix needs 200,000 768 4 bytes, about 614 MB. argsort sorts all 200,000 scores, while argpartition finds the 10 best in linear time, and you then sort only those 10.
Exercise
You normalized the document vectors but forgot to normalize the query vector. Do the document rankings for that one query change?
Show answer
No. Scaling the query by a positive constant multiplies every score by the same constant, so the order is unchanged. The scores are no longer true cosine values, though, so thresholds and comparisons across queries become wrong.