Skip to content

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 kk.

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: u⋅v=∑iuivi=∥u∥∥v∥cos⁡θu \cdot v = \sum_i u_i v_i = \lVert u \rVert \lVert v \rVert \cos\theta; 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 nprobe nearest 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 M and efSearch for 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 vv, and topk_cosine(query, matrix, k), the exact top-kk rows by cosine with ties to the lowest index.

Learning objectives

  • Derive a⋅b=∥a∥∥b∥cos⁡θa \cdot b = \lVert a \rVert \lVert b \rVert \cos\theta 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-kk search that is reproducible across runs and languages.
SymbolMeaningType / shape
a,b,x,va, b, x, vvectors of length ddfloat64[d]
a⋅b=∑iaibia \cdot b = \sum_i a_i b_iinner (dot) productscalar
∥a∥=a⋅a\lVert a \rVert = \sqrt{a \cdot a}Euclidean lengthscalar
θ\thetaangle between aa and bbradians
ε\varepsilonclamp for tiny norms: 10−810^{-8} in cosine_sim, 10−1210^{-12} in normalizescalar
x^\hat{x}the unit vector x/∥x∥x / \lVert x \rVertfloat64[d]
proj⁡vx\operatorname{proj}_v xorthogonal projection of xx onto the line through vvfloat64[d]
MMa matrix whose nn rows are the candidatesfloat64[n, d]
qqa query vector, or a batch of themfloat64[d] or [q, d]
kkhow many results to returnint

The inner product of two vectors is a⋅b=∑iaibia \cdot b = \sum_i a_i b_i, and a⋅a=∥a∥2a \cdot a = \lVert a \rVert^2. Expanding ∥a−b∥2=∥a∥2−2 a⋅b+∥b∥2\lVert a - b \rVert^2 = \lVert a \rVert^2 - 2\,a \cdot b + \lVert b \rVert^2 and comparing with the law of cosines for the triangle with sides aa, bb, a−ba - b gives

a⋅b=∥a∥ ∥b∥cos⁡θ.a \cdot b = \lVert a \rVert \, \lVert b \rVert \cos\theta .

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 ∣a⋅b∣≤∥a∥∥b∥\lvert a \cdot b \rvert \le \lVert a \rVert \lVert b \rVert (problem 3 of the linear algebra problem set, part b proves it) is what makes cos⁡θ\cos\theta a number in [−1,1][-1, 1].

If “similar meaning” is about direction, you want to remove length from the picture. Cosine similarity divides out both lengths:

cos⁡(a,b)=a⋅b∥a∥ ∥b∥.\cos(a, b) = \frac{a \cdot b}{\lVert a \rVert \, \lVert b \rVert} .

It depends only on directions: scaling aa or bb by a positive number leaves it unchanged, a negative one flips its sign, and cos⁡(a,a)=1\cos(a, a) = 1. Normalizing a vector, x^=x/∥x∥\hat{x} = x / \lVert x \rVert, makes its length 1, and for unit vectors cosine similarity is just the dot product, cos⁡(a,b)=a^⋅b^\cos(a, b) = \hat{a} \cdot \hat{b}. 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 AA of shape [7,5][7, 5] and bb of shape [5][5] returns 7 similarities. The reduced axis is dropped.

The formula breaks at one point. A zero vector has no direction, and 0/00 / 0 is NaN. The contract follows PyTorch’s cosine_similarity and clamps each norm separately:

cos⁡(a,b)=a⋅bmax⁡(∥a∥,ε) max⁡(∥b∥,ε),ε=10−8.\cos(a, b) = \frac{a \cdot b}{\max(\lVert a \rVert, \varepsilon)\,\max(\lVert b \rVert, \varepsilon)}, \qquad \varepsilon = 10^{-8} .

A zero vector then has similarity 0 with everything. Clamping the product instead, max⁡(∥a∥∥b∥,ε)\max(\lVert a \rVert \lVert b \rVert, \varepsilon), looks equivalent and is not. Two parallel vectors of length 10−510^{-5} have a product of norms 10−10<ε10^{-10} < \varepsilon, so the product clamp returns 10−10/10−8=0.0110^{-10}/10^{-8} = 0.01 for what is plainly the same direction, while separate clamps leave both norms alone and return 1. normalize uses the same rule with ε=10−12\varepsilon = 10^{-12}, so it maps the zero vector to itself.

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 v≠0v \ne 0 closest to xx is

proj⁡vx=x⋅vv⋅v v.\operatorname{proj}_v x = \frac{x \cdot v}{v \cdot v}\, v .

To see it, write x=c v+rx = c\,v + r and ask that the residual rr be orthogonal to vv: 0=r⋅v=x⋅v−c (v⋅v)0 = r \cdot v = x \cdot v - c\,(v \cdot v), so c=(x⋅v)/(v⋅v)c = (x \cdot v)/(v \cdot v). By Pythagoras, any other point c′vc' v on the line is farther: ∥x−c′v∥2=∥r∥2+(c−c′)2∥v∥2\lVert x - c'v \rVert^2 = \lVert r \rVert^2 + (c - c')^2 \lVert v \rVert^2.

Three consequences follow, and a correct implementation must show all of them: projecting twice changes nothing; the residual x−proj⁡vxx - \operatorname{proj}_v x is orthogonal to vv; and the result does not depend on the length of vv, because vv appears once on top and twice below. That last point is where the common bug lives: dividing by ∥v∥\lVert v \rVert instead of v⋅vv \cdot v is correct only for unit vv. 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.

Given a query qq and candidate rows M1,…,MnM_1, \dots, M_n, topk_cosine returns the indices of the kk rows with the largest cos⁡(q,Mi)\cos(q, M_i), 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 −score-\text{score} 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, O(nd)O(nd) 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.

Take a=(3,4)a = (3, 4) and b=(4,3)b = (4, 3). Every quantity from the section follows in a line:

QuantityValue
a⋅ba \cdot b12+12=2412 + 12 = 24
∥a∥\lVert a \rVert, ∥b∥\lVert b \rVert55, 55
cos⁡(a,b)\cos(a, b)24/25=0.9624/25 = 0.96
a^\hat{a}(0.6,0.8)(0.6, 0.8)
proj⁡ba=2425(4,3)\operatorname{proj}_b a = \frac{24}{25} (4, 3)(3.84,2.88)(3.84, 2.88)
residual a−proj⁡baa - \operatorname{proj}_b a(−0.84,1.12)(-0.84, 1.12); check: −0.84⋅4+1.12⋅3=−3.36+3.36=0-0.84 \cdot 4 + 1.12 \cdot 3 = -3.36 + 3.36 = 0

Now find the top 3 for the query q=(3,4)q = (3, 4) among five rows:

RowVectorq⋅Miq \cdot M_i∥Mi∥\lVert M_i \rVertcosine
0(4,3)(4, 3)24524/25=0.9624/25 = 0.96
1(6,8)(6, 8)501050/50=150/50 = 1
2(−3,−4)(-3, -4)−25-255−1-1
3(10,0)(10, 0)301030/50=0.630/50 = 0.6
4(0,2)(0, 2)828/10=0.88/10 = 0.8

By cosine the top 3 are rows 1,0,41, 0, 4 with scores 1,0.96,0.81, 0.96, 0.8. By raw dot product they would be rows 1,3,01, 3, 0: the long vector (10,0)(10, 0), which points 53°53° away from qq, would beat (0,2)(0, 2), only 37°37° away. Ranking by raw dot product lets long vectors win; ranking by cosine does not.

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 1≤k≤n1 \le k \le n.

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 a⋅ba \cdot b divided by both norms, each clamped separately to avoid 0/00/0 while still scoring tiny parallel vectors as 1. normalize is the same division with one vector, clamped at 10−1210^{-12}, so the zero vector maps to itself. Projection needs c=(x⋅v)/(v⋅v)c = (x \cdot v)/(v \cdot v); dividing by v⋅vv \cdot v, not ∥v∥\lVert v \rVert, is forced by the derivation, and a zero vv raises.

Exact top-kk is “score every row, sort descending, keep kk”. 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 −score-\text{score} 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 v⋅vv \cdot v and refuses the zero direction. On the worked example, x⋅v=24x \cdot v = 24, v⋅v=25v \cdot v = 25, and the result is 0.96 (4,3)=(3.84,2.88)0.96\,(4, 3) = (3.84, 2.88):

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 * vv

Top-kk comes after validating shapes and 1≤k≤n1 \le k \le n:

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 (0.96,1,−1,0.6,0.8)(0.96, 1, -1, 0.6, 0.8); sorting −score-\text{score} gives rows 1,0,4,3,21, 0, 4, 3, 2, and the first three are returned. The full solution is inner.py.

cosine_sim, normalize, and project are O(d)O(d) per vector. topk_cosine is O(nd)O(nd) to score and O(nlog⁡n)O(n \log n) to sort, per query, with an [n,d][n, d] temporary per query rather than a [q,n,d][q, n, d] 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 O(n)O(n) instead of O(nlog⁡n)O(n \log n), 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 −score-\text{score}. The tradeoff accepted is that brute force scales linearly in nn; approximate indexes, listed under further reading, are the answer when that becomes too slow.

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 1,0,41, 0, 4 with scores 1,0.96,0.81, 0.96, 0.8, since cosine, not dot product, ranks word-vector neighbours. A [7,5][7, 5] 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 [−1,1][-1, 1], and satisfy cos⁡(a,a)=1\cos(a, a) = 1: the angle and nothing else. A zero vector must give 0 (and normalize must keep it 0), while parallel vectors of norm 10−510^{-5} give 1. Normalized rows must have unit length, rescaling must recover xx, and axis must be respected, since vector indexes store unit rows.

Projection must satisfy P2=PP^2 = P, give a residual orthogonal to vv, and not depend on vv‘s length; projecting onto 0 and mismatched lengths must raise rather than produce NaN or broadcast silently. Top-kk 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 k=0k = 0, k>nk > n, and a wrong query length must raise, while k=nk = n returns every row.

The mistakes that cause these failures:

PitfallSymptomHow the solution avoids it
ranking by the raw dot productfrequent words (long vectors) are everyone’s nearest neighbourscores 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 disagreesstable sort on -scores
clamping the product of the normstiny but parallel vectors score 0.01 instead of 1clamps nx and ny separately
projecting with ∥v∥\lVert v \rVert in the denominatorcorrect only for unit vv; the residual is not orthogonaldivides by vdotv
no clamp at allNaN for any zero vector, and NaN sorts unpredictablynp.maximum(norm, eps) on every norm
projecting onto the zero vectorNaN instead of an errorraises when vdotv == 0
returning the top-kk in ascending orderthe worst match firstsorts −score-\text{score}, so the best match is first
summing over the last axis whatever axis sayswrong results for column-stored vectorspasses axis to every sum, norm, and squeeze

In AI Engineering, analogy in word2vec skip-gram with negative sampling, and the PPMI-SVD baseline ranks b−a+cb - a + c 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-kk 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.

  • torch.nn.functional.cosine_similarity (torch/nn/functional.py, aten/src/ATen/native/Distance.cpp): the same per-norm clamp, batched on GPU.
  • FAISS IndexFlatIP over 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).
  • Inner product: a⋅b=∑iaibi=∥a∥∥b∥cos⁡θa \cdot b = \sum_i a_i b_i = \lVert a \rVert \lVert b \rVert \cos\theta.
  • 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: proj⁡vx=x⋅vv⋅vv\operatorname{proj}_v x = \frac{x \cdot v}{v \cdot v} v, the closest point to xx on the line through vv.
  • Exact top-kk: scoring every candidate and returning the kk best, ties to the lowest index.
  • The inner product a⋅b=∥a∥∥b∥cos⁡θa \cdot b = \lVert a \rVert \lVert b \rVert \cos\theta 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 ε\varepsilon: a zero vector gives 0, not NaN, and two tiny parallel vectors still give 1.
  • The projection onto vv divides by v⋅vv \cdot v, not by ∥v∥\lVert v \rVert, and leaves a residual orthogonal to vv.
  • Exact top-kk breaks ties toward the lowest index, so every run and every language returns the same list.
  1. Why does cosine_sim clamp ∥a∥\lVert a\rVert and ∥b∥\lVert b\rVert separately instead of clamping their product?

    Answer

    With norms of 10−510^{-5} each, the product 10−1010^{-10} is below ε=10−8\varepsilon = 10^{-8}, so a product clamp divides 10−1010^{-10} by 10−810^{-8} and returns 0.01 for two parallel vectors. Separate clamps leave each norm untouched (both exceed 10−810^{-8}) and return 1, while a zero vector still gives 0.

  2. Why is the projection coefficient divided by v⋅vv \cdot v and not ∥v∥\lVert v\rVert?

    Answer

    The coefficient multiplies vv itself, which carries one factor of ∥v∥\lVert v\rVert. The orthogonality condition gives c=(x⋅v)/(v⋅v)c = (x\cdot v)/(v\cdot v), so the result (x⋅v^)v^(x \cdot \hat v)\hat v does not depend on the length of vv. Dividing by ∥v∥\lVert v\rVert is right only when ∥v∥=1\lVert v\rVert = 1.

  3. On the worked example, why would raw dot product rank row 3 above row 4?

    Answer

    q⋅(10,0)=30>q⋅(0,2)=8q \cdot (10, 0) = 30 > q \cdot (0, 2) = 8 because (10,0)(10, 0) is five times longer, even though it points 53°53° away from qq against 37°37°. Cosine divides the lengths out and gives 0.6<0.80.6 < 0.8.

  4. Why does topk_cosine score queries one at a time through cosine_sim instead 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.