What they’re really asking
If you only remember one thing, say this in the first minute: “Cosine similarity is the dot product divided by the two vector lengths. I’ll write it for two vectors, then for a query against a whole matrix by normalizing every row once, so search becomes one matrix multiply, then top-k with
argpartition. The edge cases I’ll handle out loud: a zero vector scores 0 instead of NaN, I normalize along rows, I compute in float32, and I sort highest first. For scale: this brute-force search is exact and fine to about a million vectors; past that I’d use an approximate index and measure it against this exact version.”The rest of this page explains each part of that answer.
The test is fluency with vectorized NumPy and with edge cases (zero vectors, number types, axes), at Senior speed. Expect follow-ups on scale.
What makes this more than a textbook formula is where it sits. Cosine similarity is the scoring function behind every “search by meaning” feature: an embedding model turns each piece of text into a vector, and the documents whose vectors point most nearly the same way as the question’s vector are the best matches. In a real system you run it against hundreds of thousands of vectors per query. So the interviewer wants the vectorized form, not a Python loop, and the small mistakes that make it silently wrong are the ones they probe.
(The source is a DEV playbook that lists an “Amazon (GenAI, L6)” loop with “practical ML coding (cosine similarity in NumPy)” under candidate reports, without naming one dev.to. The exact prompt is unknown, so this card answers the natural version: two vectors, then a query against a matrix, then top-k.)
Words you need first
- Cosine similarity: the cosine of the angle between two vectors. It is 1 when they point the same way, 0 when they are at right angles (unrelated), and −1 when they point in opposite directions. It ignores length.
- Normalize: divide a vector by its length so the length becomes 1. For two normalized vectors, cosine similarity is just their dot product.
- Top-k: the indexes of the k highest scores, best first.
- float16 / float32: 16-bit and 32-bit floating-point numbers. float16 is half the memory, but its largest value is 65,504.
Clarify first
- Two vectors, or a query against many documents? “I’ll do both, starting with two.”
- Are the inputs already normalized? “I’ll assume not.”
- What should a zero vector return? “I’d propose 0. A zero vector has no direction, and
0 / 0gives NaN, which sorts unpredictably.” - Do you want top-k too? “I’ll assume yes.”
Answer
The code
import numpy as np
def cosine(a, b, eps=1e-12):
a = np.asarray(a, dtype=np.float32); b = np.asarray(b, dtype=np.float32)
denom = np.linalg.norm(a) * np.linalg.norm(b)
return float(a @ b / denom) if denom > eps else 0.0
def cosine_matrix(Q, D, eps=1e-12): # (n_q, d), (n_d, d) -> (n_q, n_d)
Q = np.asarray(Q, dtype=np.float32); D = np.asarray(D, dtype=np.float32)
Qn = Q / np.maximum(np.linalg.norm(Q, axis=1, keepdims=True), eps)
Dn = D / np.maximum(np.linalg.norm(D, axis=1, keepdims=True), eps)
return Qn @ Dn.T
def top_k(scores, k):
k = min(k, scores.shape[-1])
idx = np.argpartition(-scores, k - 1)[:k] # O(n)
return idx[np.argsort(-scores[idx])] # sort only k
Follow one query through it
Take three documents and one query (values illustrative): a = [3, 1, 0], b = [0, 2, 2], c = [1, 0, 1], and
the query q = [0, 1, 1].
| Step | What happens | What to say in the interview |
|---|---|---|
| Normalize rows | Each row is divided by its length: b becomes [0, 0.707, 0.707]. | ”axis=1, keepdims=True: rows are the vectors, and keepdims makes the division broadcast per row.” |
| Normalize the query | q becomes [0, 0.707, 0.707]. | ”Now cosine is just a dot product.” |
| One matrix multiply | Scores: a 0.22, b 1.0, c 0.5. | ”One matrix-vector product scores every document at once, with no Python loop.” |
| Top-2 | argpartition picks b and c without sorting a; then those two are sorted. | ”Selection is linear; I only sort the k winners.” |
b points exactly the same way as the query, so it scores 1.0 even though it is a longer vector. That is the
point of cosine: direction, not size.
Points to say while writing
- Normalize once, then it’s a dot product. For unit vectors cosine equals the dot product, so store normalized document vectors and search with one matrix-vector product.
axis=1, keepdims=Truenormalizes rows and broadcasts correctly.axis=0is a classic silent bug: it normalizes columns, and the code still runs.- Zero vectors need an epsilon or an explicit rule.
- float32, not float16. Squaring large values in float16 overflows, because its maximum is 65,504.
argpartitionmakes top-k linear rather than a full O(n log n) sort.- A related identity. For unit vectors, ‖a − b‖² = 2 − 2·cos(a, b), so ranking by Euclidean distance and by cosine gives the same order.
Testing it
Test with orthogonal vectors (0), identical vectors (1), opposite vectors (−1), a scaled copy (1), a zero vector (0), and the matrix form against the pairwise form. Those tests ran and passed on 2026-10-12 in the family walkthrough’s suite.
The scale follow-up
Comparing the query with every vector is called flat (or brute-force) search. Its cost is the number of vectors times their dimension, and it is exact: it always finds the true best matches. For 1M vectors of 384 dimensions it needs about 1.5 GB of memory, and one query took about 44 ms on an Apple M1 Ultra under load (run 2026-10-12).
So flat search is exact and fine to about a million vectors per query process. Beyond that, or for many queries per second, use an approximate nearest-neighbour index (HNSW, IVF or product quantization: structures that find almost the best matches without comparing against every vector). Measure its recall against this exact version. Say: “The brute-force version is my ground truth. Whatever faster index I add, I measure how many of the true top results it still finds.”
The arithmetic behind the numbers (for a Staff-level follow-up)
per query: N × d multiply-adds; memory: N × d × 4 bytes (float32) N- number of document vectors
d- dimension
1M vectors × 384 dims: 384M multiply-adds and 1.5 GB; one query took about 44 ms on an Apple M1 Ultra under load (run 2026-10-12)
- The worked example: ‖b‖ = √8, ‖q‖ = √2, b · q = 4, so cos = 4 ÷ (√8 × √2) = 4 ÷ 4 = 1.0. For
c: 1 ÷ (√2 × √2) = 0.5. Fora: 1 ÷ (√10 × √2) ≈ 0.22.
Senior vs Staff
Cosine in NumPy
Senior
- Correct vectorized code with edge cases and tests, written quickly, with top-k via argpartition.
Staff
- Also connects it to the system: normalize at ingestion, store the model version, and use exact search as the ground truth for an approximate index's recall.
Small-team version
At small-team scale (thousands to about a million chunks), this function plus a NumPy matrix in memory is the vector store, and it is exact.
- Build: this function, a matrix loaded at startup, and the tests above.
- Reach for pgvector (a Postgres extension that stores and searches vectors) or a managed store when you need filters, persistence shared across services, or more vectors than fit comfortably in memory.
- Don’t add one just because a tutorial used one.
Pitfalls
- A Python loop over documents. It is far slower than one matrix product and shows you don’t think in vectors.
- Normalizing along the wrong axis, or forgetting the query. Both run without errors and give wrong scores.
- Returning NaN for zero vectors. NaN poisons the sort, so define the rule and return 0.
- Using
np.argsort(scores)[:k]. argsort is ascending, so it returns the least similar items.
Go deeper
- Family walkthrough, stage 0: Build a small RAG in code.
- Approximate indexes for the scale follow-up: Build Your Own Vector Index (HNSW + IVF-PQ).
- Where cosine top-k sits in a pipeline: Build Your Own RAG System.