Choose cosine, inner product or L2 from the embedding contract and test exact rankings before building an ANN index.
Vector similarity metrics: normalization changes the ranking
The metric is part of the embedding contract
A vector index needs a comparison rule. Cosine similarity compares direction after accounting for vector length; inner product combines direction and magnitude; Euclidean distance measures geometric separation. None is universally best for retrieval. An embedding model may assume normalized outputs or use vector length as a signal. If that contract changes, the same passage vectors can rank differently even when their dimensions match. Record the metric, normalization rule, model revision and dimension together. Embedding migrations should reject an index whose metric or normalization rule differs from the serving query encoder.
Normalize both sides when cosine is the goal
For nonzero unit vectors, the inner product equals cosine similarity. Squared L2 distance then equals two minus twice the inner product, so all three produce equivalent orderings when applied consistently to those unit vectors. That equivalence does not hold when only queries are normalized or when passage magnitudes vary. Normalize vectors before indexing and before querying if the backend implements cosine through inner product. A zero vector cannot be normalized; reject it and inspect the encoder pipeline rather than silently inserting it.
Compare exact scores before ANN tuning
An approximate index can miss a neighbor because of graph traversal, quantization or filters. First run exact search under the intended metric; then compare ANN results to that baseline at a fixed K and permission scope. Otherwise a rank change caused by accidental normalization may be blamed on a candidate budget. HNSW budgets affect exploration, while quantization affects stored precision. Keep these experiments separate.
Do not mix metric scores across branches
An L2 distance is smaller when better; cosine and inner product are larger when better. Their numeric scales differ and may vary by model or collection. A hybrid ranker cannot add raw values from these branches and expect a meaningful order. Convert each branch to a common calibrated signal using judged data, or combine ranks while keeping branch score interpretation intact. Fusion calibration handles this final step. A threshold learned for cosine cannot be copied to an inner-product index without reevaluation.
Test distributions and exceptions
Measure exact top-K recall on paraphrases, rare identifiers and out-of-domain text; compare score distributions before setting any answer threshold. Include zero vectors, NaNs, dimension mismatches and vectors whose magnitudes differ sharply. Check whether the embedding provider normalizes outputs at each version, but verify actual stored vectors rather than relying on a name. If magnitude is useful, cosine may discard a valuable signal. If magnitude is accidental, inner product may let unusually large vectors dominate. The decision belongs to measured retrieval quality, not a formula alone.
Worked contract
from math import isfinite, sqrt
def scores(query: tuple[float, ...], passage: tuple[float, ...]
) -> tuple[float, float, float]:
if not query or len(query) != len(passage):
raise ValueError("dimension mismatch")
if not all(isfinite(value) for value in query + passage):
raise ValueError("non-finite coordinate")
query_norm = sqrt(sum(value * value for value in query))
passage_norm = sqrt(sum(value * value for value in passage))
if query_norm == 0 or passage_norm == 0:
raise ValueError("zero vector")
dot = sum(left * right for left, right in zip(query, passage))
squared_l2 = sum((left - right) ** 2
for left, right in zip(query, passage))
return dot, dot / (query_norm * passage_norm), squared_l2
query = (1.0, 0.0)
aligned = (4.0, 0.0)
nearby = (1.0, .3)
assert scores(query, aligned)[0] > scores(query, nearby)[0]
assert scores(query, aligned)[1] > scores(query, nearby)[1]
assert scores(query, aligned)[2] > scores(query, nearby)[2]Performance and operating cost
Computing any one score for D-dimensional vectors takes O(D) time and O(1) extra space. Exact ranking across N passages takes O(ND) score work plus top-K selection or sorting; normalization can be precomputed at ingestion but still costs O(D) per new vector. ANN reduces comparisons at the cost of approximate recall and index memory. The example deliberately shows that inner product and cosine favor the long aligned vector while L2 favors the shorter nearby one; those are different ranking contracts, not a contradiction.
Common Mistakes
- Normalizing queries but leaving indexed passages unnormalized when expecting cosine order.
- Comparing a smaller-is-better L2 distance directly with larger-is-better cosine scores.
- Changing metric settings without rebuilding or validating the indexed vectors.
- Passing zero, non-finite or wrong-dimensional vectors into a search index.
Validation drill
On 67 judged queries, compare exact cosine, inner-product and L2 top-12 results under one embedding version. Report per-slice recall and vector norm distributions before selecting the production metric.
