Choose the geometry before choosing the index
Distinguish cosine, inner product, and squared Euclidean ranking, including normalization and zero-vector policy.
On this page
The question for today
What you’ll understand
- Calculate three retrieval scores for the same vectors.
- Derive the normalized inner-product and L2 equivalence.
- Define an explicit policy for invalid and zero embeddings.
An index accelerates a ranking rule; it cannot decide what similarity should mean. Imagine a query about a short physics note and two document embeddings: one points almost in the query direction but has a large norm, while another sits nearby in Euclidean space. Different metrics can legitimately select different documents. Before measuring approximate recall, write down the exact score, its ordering direction, and the preprocessing used on each side. Otherwise a perfectly implemented index can answer a different question from the one the application intended, and the benchmark can reward that mistake.
Three scores, three contracts
Squared Euclidean distance adds the squared coordinate differences and ranks smaller values first. Faiss L2 indexes report this squared quantity, so a returned value of nine corresponds to Euclidean distance three. Taking a square root preserves ranking but changes thresholds and units. Maximum inner product instead ranks larger dot products first. A positive rescaling of one fixed query rescales every inner product equally; independently rescaling stored vectors can change which document wins.
Cosine similarity divides the dot product by both norms, so it compares direction rather than magnitude. That removes information when an embedding model deliberately uses norm to express confidence, popularity, or another learned signal. Treat normalization as part of the model contract rather than an automatic improvement. Record whether the query encoder and document encoder are symmetric or deliberately different, and check their documented scoring rule before selecting the index metric.
Normalization has a domain
For nonzero vectors, dividing by the Euclidean norm places them on the unit sphere. Expanding the squared difference of two unit vectors leaves two minus twice their dot product. Thus descending cosine, descending normalized inner product, and ascending normalized squared L2 produce the same order in exact arithmetic. This statement requires normalization on both sides. Normalizing only the query leaves database norms in the inner-product score and does not establish the equivalence.
A zero vector has no direction, so its cosine is undefined. Adding a tiny denominator does not discover a missing direction; it defines a new scoring convention. A production ingestion policy might reject zero embeddings, quarantine them for re-encoding, or assign a separately specified fallback route. Apply the same policy during evaluation. Also reject nonfinite coordinates and check normalization tolerances, because NaNs and overflow can poison both training and sorting before the search algorithm begins.
Define reproducible ranking
A test oracle should compute the chosen score against the same eligible document snapshot as the approximate index. Specify whether distance is squared, how ties are broken, and whether document IDs represent unique logical items. A deterministic secondary key such as ascending ID makes exact top-k sets reproducible when scores tie. Floating-point implementations may disagree near a boundary, so retain distances and inspect a tolerance-aware tie analysis alongside strict ID intersection.
Try separating geometric quality from semantic usefulness. Exact neighbors under a poorly trained encoder can still be irrelevant to a person. Conversely, a semantically useful result can count as a geometric miss. Use an exact search to isolate index approximation, then a separate task evaluation to judge the embedding model. When a new encoder changes its dimension or normalization, rebuild the reference scores before comparing indexes; a familiar array shape alone does not preserve the old geometry.
Work it through
One pair reverses the winner
Use q=(1,0), document A=(3,0), and document B=(1,1). Compute maximum inner product, cosine, and minimum squared L2 without normalizing the stored vectors first. Then explain which transformation restores cosine equivalence.
The inner products are q·A=3 and q·B=1, so maximum inner product chooses A. The norms are 1, 3, and √2 respectively; the larger stored norm contributes directly to the first ranking.
Cosines are 3/(1×3)=1 and 1/√2≈0.7071, so directional similarity also chooses A. Raw squared distances are (1−3)²=4 and (1−1)²+(0−1)²=1, so raw L2 chooses B.
Normalize both documents: A becomes (1,0) and B becomes (1/√2,1/√2). Their squared distances to q become 0 and 2−√2≈0.5858, agreeing with the cosine order.
The original raw-L2 winner is B; cosine and inner product choose A. Normalized-L2 agrees with cosine because both sides are nonzero unit vectors, not because all three unprocessed metrics are interchangeable.
The living notebook
Explore the model
Interactive lab · vectors
Direction and magnitude are separate controls
Reset, set Angle to 60° and Magnitude to 2, and predict x=1, y=√3, length=2 before Step. Relative to the fixed query (1,0), the dot product is x=1 and cosine is 0.5. Reset, set Angle to 60° and Magnitude to 1, then Step: x=0.5 while cosine stays 0.5. Both controls are set after each fresh Reset. This displays one 2D vector, not an ANN search or normalization algorithm.
- x component
- 1.393
- y component
- 0.975
- Magnitude
- 1.7
Playback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forScaling changes the projection and norm together while leaving the direction unchanged.
Pause & reason
Check your understanding
Your turn
Try it yourself
A nonzero query q=(2,0) is compared with x=(0,2). Find their cosine and normalized squared L2. What happens if x is replaced by (0,0)?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Compute both norms before dividing. Expand the distance between the resulting unit vectors.
Compare with the solution
Both original norms are 2 and the dot product is zero, so cosine is 0. Unit vectors (1,0) and (0,1) have squared distance 2. Replacing x by zero makes its norm zero and cosine undefined; the declared invalid-vector or fallback policy must handle it rather than pretending normalization produced a valid direction.
Keep the idea
Take it with you
- Choose the score and its ordering direction explicitly.
- Cosine equivalence requires nonzero unit vectors on both sides.
- Benchmark index approximation separately from encoder usefulness.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.