9.6 Inner products, projections, cosine similarity, and top-k
word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering turns every word into a vector, and from then on every question about words becomes a question about angles. Which words are closest to “king”? Which word completes “man is to king as woman is to ?” How well do the model’s similarities agree with human ratings? All of these are cosine similarities and a sorted list of the best .
Concepts from other sections (5)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- Stable sort: a sort that keeps equal elements in their input order; heapsort is not one. Read more: 18.4 Binary heap in Programming and Algorithms
- IVF (inverted file index): a vector index that clusters rows around centroids and scans only the
nprobenearest clusters. Read more: 27.2 Retrieval: BM25, Flat and IVF Vectors, RRF, and MMR in AI Engineering - HNSW (hierarchical navigable small world): the dominant ANN index, a multi-layer proximity graph searched by greedy descent, tuned with
MandefSearchfor recall against latency. Read more: Chapter 27: Retrieval and RAG in AI Engineering - tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot in AI Engineering
Each of them is easy to get subtly wrong. A version that ranks by raw dot product quietly prefers frequent words, because their vectors are longer. One that divides by a zero norm fills the table with NaN. One that breaks ties by whatever order the sort happens to leave makes two runs disagree. The same search later runs over document embeddings in Retrieval: BM25, Flat and IVF Vectors, RRF, and MMR in AI Engineering, re-implemented in Go. This section pins the definitions down once.
Nothing needs to be built first. It helps to remember from Vectors, matrices, row-major layout, and matmul that the dot product is the inner loop of matmul, and the linear algebra problem set, part a is useful practice. The solution is inner.py, with contract inner.pyi: normalize(x), cosine_sim(a, b) with each norm clamped on its own, project(x, v) onto the line through , and topk_cosine(query, matrix, k), the exact top- rows by cosine with ties to the lowest index.
Learning objectives
- Derive and explain why cosine, not the raw dot product, measures similarity of direction.
- Clamp norms so that zero vectors give 0 and tiny parallel vectors still give 1.
- Project a vector onto a line, and show the residual is orthogonal and the result independent of the line vector’s length.
- Implement exact top- search that is reproducible across runs and languages.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| vectors of length | float64[d] | |
| inner (dot) product | scalar | |
| Euclidean length | scalar | |
| angle between and | radians | |
clamp for tiny norms: in cosine_sim, in normalize | scalar | |
| the unit vector | float64[d] | |
| orthogonal projection of onto the line through | float64[d] | |
| a matrix whose rows are the candidates | float64[n, d] | |
| a query vector, or a batch of them | float64[d] or [q, d] | |
| how many results to return | int |
Inner products and angles
Section titled “Inner products and angles”The inner product of two vectors is , and . Expanding and comparing with the law of cosines for the triangle with sides , , gives
So the inner product is positive when the vectors point the same way, zero when they are perpendicular (orthogonal), and negative when they point apart. It mixes length and angle. The Cauchy-Schwarz inequality (problem 3 of the linear algebra problem set, part b proves it) is what makes a number in .
Cosine similarity and normalization
Section titled “Cosine similarity and normalization”If “similar meaning” is about direction, you want to remove length from the picture. Cosine similarity divides out both lengths:
It depends only on directions: scaling or by a positive number leaves it unchanged, a negative one flips its sign, and . Normalizing a vector, , makes its length 1, and for unit vectors cosine similarity is just the dot product, . That is how a vector index stores embeddings: normalize once, then every search is one matrix product.
In code, vectors lie along an axis (the last by default) and the other axes broadcast: cosine_sim(A, b) with of shape and of shape returns 7 similarities. The reduced axis is dropped.
Zero and tiny vectors
Section titled “Zero and tiny vectors”The formula breaks at one point. A zero vector has no direction, and is NaN. The contract follows PyTorch’s cosine_similarity and clamps each norm separately:
A zero vector then has similarity 0 with everything. Clamping the product instead, , looks equivalent and is not. Two parallel vectors of length have a product of norms , so the product clamp returns for what is plainly the same direction, while separate clamps leave both norms alone and return 1. normalize uses the same rule with , so it maps the zero vector to itself.
Projection onto a line
Section titled “Projection onto a line”Cosine tells you how aligned two vectors are; projection tells you how much of one lies along the other. The point on the line through closest to is
To see it, write and ask that the residual be orthogonal to : , so . By Pythagoras, any other point on the line is farther: .
Three consequences follow, and a correct implementation must show all of them: projecting twice changes nothing; the residual is orthogonal to ; and the result does not depend on the length of , because appears once on top and twice below. That last point is where the common bug lives: dividing by instead of is correct only for unit . The zero vector spans no line, so projecting onto it raises. The least squares of SVD, Eckart-Young low rank, and least squares is the same idea with a whole column space in place of a line.
Exact top-k
Section titled “Exact top-k”Given a query and candidate rows , topk_cosine returns the indices of the rows with the largest , in descending order of score, together with the scores. Two rules make it reproducible.
First, ties go to the lowest index, the same rule greedy sampling uses. Duplicate rows, and rows that are positive multiples of each other, score exactly the same. A stable sort on keeps tied rows in index order; sorting ascending and reversing puts the highest index first instead.
Second, identical rows get bitwise identical scores. The solution computes each query’s scores through cosine_sim itself, an elementwise product summed along each row. A BLAS matrix product can round equal rows differently in different blocks, which would break ties at random.
This is “exact” (brute force) search: it scores every row, per query, which is what word-vector work and the evaluation zoo need for vocabularies of tens of thousands of words. Approximate indexes (IVF, HNSW) trade exactness for speed and arrive with the retrieval chapter of AI Engineering.
Working it by hand
Section titled “Working it by hand”Take and . Every quantity from the section follows in a line:
| Quantity | Value |
|---|---|
| , | , |
| residual | ; check: |
Now find the top 3 for the query among five rows:
| Row | Vector | cosine | ||
|---|---|---|---|---|
| 0 | 24 | 5 | ||
| 1 | 50 | 10 | ||
| 2 | 5 | |||
| 3 | 30 | 10 | ||
| 4 | 8 | 2 |
By cosine the top 3 are rows with scores . By raw dot product they would be rows : the long vector , which points away from , would beat , only away. Ranking by raw dot product lets long vectors win; ranking by cosine does not.
Designing the API
Section titled “Designing the API”def normalize(x: ArrayLike, axis: int = -1, eps: float = 1e-12) -> NDArray: ...def cosine_sim(a: ArrayLike, b: ArrayLike, axis: int = -1, eps: float = 1e-8) -> NDArray: ...def project(x: ArrayLike, v: ArrayLike, axis: int = -1) -> NDArray: ...def topk_cosine(query: ArrayLike, matrix: ArrayLike, k: int) -> tuple[NDArray, NDArray]: """(indices int64, scores float64), [k] or [q, k], descending, ties to the lowest index."""Every function reduces along one axis and broadcasts over the rest, and every function that takes two vectors checks that their lengths agree along that axis, because anything else would broadcast silently into a wrong answer. topk_cosine accepts a single query of shape [d], returning shape [k], or a batch [q, d], returning [q, k]; it requires .
Building it step by step
Section titled “Building it step by step”Because every function reduces along one axis of vectors and broadcasts over the rest, the solution needs one helper: a norm along axis with keepdims=True, so the result divides back into the input without reshaping. Cosine is divided by both norms, each clamped separately to avoid while still scoring tiny parallel vectors as 1. normalize is the same division with one vector, clamped at , so the zero vector maps to itself. Projection needs ; dividing by , not , is forced by the derivation, and a zero raises.
Exact top- is “score every row, sort descending, keep ”. Reproducibility forces two more choices: the scores of equal rows must be bitwise equal, so they are computed elementwise, one query at a time, through cosine_sim; and the sort must be stable on so ties keep index order. Treating a single query as a batch of one and stripping the axis at the end keeps one code path.
The two helpers:
def _norm(x, axis): """Euclidean norm along axis, kept as a size-1 axis for broadcasting.""" return np.sqrt(np.sum(x * x, axis=axis, keepdims=True))
def _check_lengths(a, b, axis, who): # vectors must have the same length along the reduced axis; anything else # would broadcast silently into a wrong answer if a.ndim == 0 or b.ndim == 0 or a.shape[axis] != b.shape[axis]: raise ValueError( f"{who}: vector lengths differ along axis {axis}: {a.shape} vs {b.shape}" )Normalization and cosine, with the per-norm clamp:
def normalize(x, axis=-1, eps=1e-12): v = np.asarray(x, dtype=np.float64) return v / np.maximum(_norm(v, axis), eps) # zero vector: 0 / eps = 0
def cosine_sim(a, b, axis=-1, eps=1e-8): x = np.asarray(a, dtype=np.float64) y = np.asarray(b, dtype=np.float64) _check_lengths(x, y, axis, "cosine_sim") # Clamp each norm on its own: two parallel vectors of norm 1e-5 keep their # norms and score 1; clamping the product would give 0.01. nx = np.maximum(_norm(x, axis), eps) ny = np.maximum(_norm(y, axis), eps) # the reduced axis is dropped from the result return np.squeeze(np.sum(x * y, axis=axis, keepdims=True) / (nx * ny), axis=axis)Projection divides by and refuses the zero direction. On the worked example, , , and the result is :
def project(x, v, axis=-1): xv = np.asarray(x, dtype=np.float64) vv = np.asarray(v, dtype=np.float64) _check_lengths(xv, vv, axis, "project") vdotv = np.sum(vv * vv, axis=axis, keepdims=True) if (vdotv == 0.0).any(): raise ValueError("project: cannot project onto the zero vector") # Divide by v . v, not by ||v||: the coefficient multiplies v itself. return np.sum(xv * vv, axis=axis, keepdims=True) / vdotv * vvTop- comes after validating shapes and :
Q = q[None, :] if q.ndim == 1 else q # one code path for [d] and [q, d] # One query at a time through cosine_sim itself: identical rows get bitwise # identical scores (a BLAS product may round equal rows differently). scores = np.stack([cosine_sim(Q[i], M) for i in range(Q.shape[0])]) # [q, n] # Stable sort on -score: descending, and equal scores stay in row order, # so ties go to the lowest index. idx = np.argsort(-scores, axis=1, kind="stable")[:, :k].astype(np.int64) top = np.take_along_axis(scores, idx, axis=1) return (idx[0], top[0]) if q.ndim == 1 else (idx, top)For the worked query the scores are ; sorting gives rows , and the first three are returned. The full solution is inner.py.
Why this design
Section titled “Why this design”cosine_sim, normalize, and project are per vector. topk_cosine is to score and to sort, per query, with an temporary per query rather than a one for the whole batch.
Three faster-looking alternatives were rejected. Q @ M.T for the scores is faster, but BLAS may round identical rows differently depending on how it blocks the product, which turns exact ties into random order; tie stability across runs and across the Go port matters more here than speed. argpartition is instead of , but it does not preserve the order of equal elements, so the lowest-index tie rule would need a second pass; a full stable sort is simpler and fast enough for vocabularies of tens of thousands. And sorting ascending then reversing puts tied rows in descending index order, which is why the solution sorts . The tradeoff accepted is that brute force scales linearly in ; approximate indexes, listed under further reading, are the answer when that becomes too slow.
What can go wrong
Section titled “What can go wrong”A correct solution passes checks at each layer. The hand example must reproduce the cosine, projection, residual, and unit vector, and the top 3 must be rows with scores , since cosine, not dot product, ranks word-vector neighbours. A batch against one vector must work along the last axis and along axis 0, because the evaluation zoo scores whole vocabularies at once. Cosine must be symmetric, scale invariant, flip sign under negation, stay in , and satisfy : the angle and nothing else. A zero vector must give 0 (and normalize must keep it 0), while parallel vectors of norm give 1. Normalized rows must have unit length, rescaling must recover , and axis must be respected, since vector indexes store unit rows.
Projection must satisfy , give a residual orthogonal to , and not depend on ‘s length; projecting onto 0 and mismatched lengths must raise rather than produce NaN or broadcast silently. Top- must match a full sort on 6 queries against 200 rows of mixed lengths, indices and scores both. Duplicate and rescaled rows must come back in index order, so results are reproducible across runs and languages. And , , and a wrong query length must raise, while returns every row.
The mistakes that cause these failures:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| ranking by the raw dot product | frequent words (long vectors) are everyone’s nearest neighbour | scores with cosine_sim, which divides by both norms |
| ties broken toward the highest index (sort ascending, then reverse) | two equal candidates come back in the other order; the Go port disagrees | stable sort on -scores |
| clamping the product of the norms | tiny but parallel vectors score 0.01 instead of 1 | clamps nx and ny separately |
| projecting with in the denominator | correct only for unit ; the residual is not orthogonal | divides by vdotv |
| no clamp at all | NaN for any zero vector, and NaN sorts unpredictably | np.maximum(norm, eps) on every norm |
| projecting onto the zero vector | NaN instead of an error | raises when vdotv == 0 |
| returning the top- in ascending order | the worst match first | sorts , so the best match is first |
summing over the last axis whatever axis says | wrong results for column-stored vectors | passes axis to every sum, norm, and squeeze |
Where this leads
Section titled “Where this leads”In AI Engineering, analogy in word2vec skip-gram with negative sampling, and the PPMI-SVD baseline ranks against the vocabulary with topk_cosine and uses it for nearest-neighbour checks of the embeddings, and the word-similarity task in The evaluation harness and the model zoo correlates cosine_sim with human ratings (Spearman). In AI Engineering, the Go retriever of Retrieval: BM25, Flat and IVF Vectors, RRF, and MMR re-implements cosine and exact top- with the same tie rule; it is a port, not a call site. With this section the chapter’s tools are complete, and the problem sets give you practice with all of them.
Further reading
Section titled “Further reading”torch.nn.functional.cosine_similarity(torch/nn/functional.py,aten/src/ATen/native/Distance.cpp): the same per-norm clamp, batched on GPU.- FAISS
IndexFlatIPover normalized rows (faiss/IndexFlat.cpp): exact search with SIMD and BLAS inner products and a heap per query. - FAISS IVF and HNSW indexes (
faiss/IndexIVF.cpp,faiss/IndexHNSW.cpp): sublinear search with a recall knob (nprobe,efSearch). - pgvector’s
<=>cosine distance (pgvector/src/vector.c): the same search inside Postgres, with IVFFlat and HNSW indexes. - Strang, Introduction to Linear Algebra, sections 1.2 and 4.2; Mikolov, Yih, and Zweig, “Linguistic regularities in continuous space word representations” (2013).
Key terms
Section titled “Key terms”- Inner product: .
- Orthogonal: having inner product zero.
- Cosine similarity: the inner product divided by both lengths; depends only on direction.
- Normalization: dividing a vector by its length to get a unit vector.
- Orthogonal projection: , the closest point to on the line through .
- Exact top-: scoring every candidate and returning the best, ties to the lowest index.
Summary
Section titled “Summary”- The inner product mixes length and angle; dividing out both lengths leaves the angle alone, which is what “similar meaning” should measure.
- Ranking by raw dot product lets long vectors win; ranking by cosine does not.
- Clamp each norm separately with : a zero vector gives 0, not NaN, and two tiny parallel vectors still give 1.
- The projection onto divides by , not by , and leaves a residual orthogonal to .
- Exact top- breaks ties toward the lowest index, so every run and every language returns the same list.
Review questions
Section titled “Review questions”-
Why does
cosine_simclamp and separately instead of clamping their product?Answer
With norms of each, the product is below , so a product clamp divides by and returns 0.01 for two parallel vectors. Separate clamps leave each norm untouched (both exceed ) and return 1, while a zero vector still gives 0.
-
Why is the projection coefficient divided by and not ?
Answer
The coefficient multiplies itself, which carries one factor of . The orthogonality condition gives , so the result does not depend on the length of . Dividing by is right only when .
-
On the worked example, why would raw dot product rank row 3 above row 4?
Answer
because is five times longer, even though it points away from against . Cosine divides the lengths out and gives .
-
Why does
topk_cosinescore queries one at a time throughcosine_siminstead of a matrix product?Answer
So that identical rows get bitwise identical scores. Elementwise products summed along each row round the same way for equal rows; a blocked BLAS product may not, and then the stable sort would order “tied” rows by rounding noise.