Cosine Similarity vs Dot Product: Normalize Embeddings Correctly
Understand when cosine similarity and dot product give different embedding rankings. Run a Python lab covering normalization, zero vectors and score thresholds.
Cosine similarity compares vector direction after removing magnitude. Dot product retains magnitude, so a longer document vector can outrank a more closely aligned one. For nonzero unit vectors, their scores agree. This guide uses invented vectors and a runnable Python lab to explain when rankings agree, when thresholds change, and what to verify before changing an embedding index.
Why a larger vector can win the wrong comparison
Imagine debugging a retriever whose results changed after switching its scoring metric. The first useful question is whether the stored coordinates and the query were normalized. A label such as similarity does not establish the mathematical operation, and the same embedding coordinates can produce different rankings under different operations.
Take query q=(1, 0). Document A=(1, 0) points exactly in its direction. Document B=(4, 3) points somewhat away but has length 5. The raw dot products are 1 and 4, so B wins. Their cosine similarities are 1 and 0.8, so A wins. These are invented coordinates: the labels describe geometry, not measured relevance of real documents.
The query is already unit length in this example. Normalizing only the query therefore cannot repair the difference. The varying document lengths are still present. This small counterexample is useful when a configuration review concludes that query normalization alone makes an inner-product index equivalent to cosine.
Read the formula before interpreting the score
For equal-dimensional vectors, dot(a,b)=sum(a[i]*b[i]). The Euclidean norm is ||a||=sqrt(sum(a[i]²)). For nonzero vectors, cosine(a,b)=dot(a,b)/(||a||*||b||). Dividing each vector by its own norm produces its unit vector; taking the dot product of those unit vectors gives cosine similarity.
Cosine lies between -1 and 1 mathematically. A negative result is valid when the directions are opposed; it is not automatically an implementation error. A score of 0.8 is not an 80% probability of a correct answer. Neither a geometric score nor a ranking alone measures whether a retrieved passage supports a user’s question.
Raw dot products have no universal fixed range across arbitrary vectors. Multiplying the query by a positive constant multiplies all its dot scores by that constant while preserving their order. Consequently, a threshold can change behavior even when the top results stay identical. Keep ranking tests and threshold tests separate.
Source: scikit-learn: cosine similarity definition and zero-vector example ↗
Which normalization changes rankings, and which changes scores?
Consider one fixed, nonzero query against nonzero documents. Normalizing all documents removes their individual length factors. Dot product then equals the query norm multiplied by cosine. That common positive factor preserves ordering, including ties, but the numeric scores are not necessarily cosine values.
Normalizing both sides makes the dot score equal to cosine. If your application uses a minimum score, joins results from multiple queries, or displays scores to users, this distinction matters. The same document-only normalization that fixes ordering may leave cross-query scores on different scales.
Do not normalize every model by habit. The appropriate metric depends on the embedding model’s intended use and training contract. Magnitude may be meaningful to a model rather than accidental noise. Confirm the model documentation, including whether its output already ends with normalization, before adding transformations.
The table describes exact arithmetic and exhaustive comparison over the same vectors. Approximate candidate selection, reduced precision and tie handling can introduce additional differences. Equivalent formulas do not promise byte-identical ranked output from two differently configured indexes.
| Vectors used for dot product | Relation to cosine | Practical consequence |
|---|---|---|
| Raw query, raw documents | Query and document norms remain | Document magnitude can change ranking |
| Unit query, raw documents | Each document norm remains | Still not generally cosine ranking |
| Raw query, unit documents | Query norm × cosine | Same ranking for this query; scaled scores |
| Unit query, unit documents | Cosine score | Same mathematical scores and ranking |
Source: Sentence Transformers: similarity functions and normalized embeddings ↗
Do not confuse similarity with squared distance
On unit vectors, squared Euclidean distance satisfies ||u-v||²=2-2*dot(u,v). Thus maximizing cosine is equivalent to minimizing squared Euclidean distance in that setting. For cosine 0.8, the squared distance is 0.4; the Euclidean distance is sqrt(0.4). Those are different values even though they imply the same ordering.
Faiss documents that its L2 metric reports squared Euclidean distance. Other interfaces may expose a distance, a negated similarity or a transformed score. Verify the actual return contract before applying a comparison such as score >= 0.8. Copying a threshold between these representations silently changes its meaning.
A useful diagnostic records the metric name, whether larger or smaller is better, the normalization state and a manually calculated pair. If a service transforms scores, calculate the expected returned value using that service’s documented transformation. Do this before interpreting a dashboard as evidence of poor embeddings.
Source: Faiss: metric types, normalized inner product and squared L2 distance ↗
Run the complete Python correctness lab
Save the following as vectors.py and run python vectors.py with Python 3.12 or later. It uses only the standard library. The published script passed 1,030 checks in the authoring environment, including 200 seeded integer-vector pairs compared against an independent 50-digit Decimal formula.
The lab checks the ranking reversal, positive query scaling, document-only score scaling, the unit-vector distance identity and invalid inputs. Coordinates are deliberately limited to 64 dimensions and absolute value at most 1e100. These are teaching limits that keep the arithmetic bounded, not limits on embedding systems.
The zero-vector policy is explicit: raw dot product with zero is defined, but this cosine function rejects zero because direction is undefined. Tiny nonzero coordinates are tested separately. The implementation uses math.hypot for norms, math.fsum for sums and clips small floating-point overshoot at cosine’s endpoints; it is not a production vector-index implementation.
"""Python 3.12+; invented vectors, no embedding model or vector database."""
from decimal import Decimal, localcontext
import math
import random
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def vector(value):
if type(value) not in (list, tuple) or not 1 <= len(value) <= 64:
raise ValueError('Use 1 to 64 numeric coordinates')
if any(type(x) not in (int, float) or abs(x) > 1e100
or not math.isfinite(x) for x in value):
raise ValueError('Use finite coordinates with absolute value <= 1e100')
return tuple(float(x) for x in value)
def dot(a, b):
a, b = vector(a), vector(b)
if len(a) != len(b):
raise ValueError('Dimensions differ')
return math.fsum(x * y for x, y in zip(a, b))
def unit(a):
a = vector(a)
length = math.hypot(*a)
if length == 0:
raise ValueError('Zero vector has no cosine direction')
return tuple(x / length for x in a)
def cosine(a, b):
# This lab rejects zero vectors instead of choosing a library convention.
return max(-1.0, min(1.0, dot(unit(a), unit(b))))
def squared_l2(a, b):
a, b = vector(a), vector(b)
if len(a) != len(b):
raise ValueError('Dimensions differ')
return math.fsum((x-y)**2 for x, y in zip(a, b))
def ranking(query, documents, score):
# Name is a deterministic tie-breaker for this invented fixture.
return sorted(documents, key=lambda name: (-score(query, documents[name]), name))
def main():
q = (1, 0)
docs = {'aligned': (1, 0), 'large': (4, 3),
'orthogonal': (0, 5), 'opposite': (-1, 0)}
check(ranking(q, docs, dot) == ['large','aligned','orthogonal','opposite'],
'raw dot favors the large vector in this fixture')
check(ranking(q, docs, cosine) == ['aligned','large','orthogonal','opposite'],
'cosine favors the aligned vector')
for name, expected in [('aligned', 1), ('large', .8),
('orthogonal', 0), ('opposite', -1)]:
check(math.isclose(cosine(q, docs[name]), expected, abs_tol=1e-12), name)
normalized = {name: unit(v) for name, v in docs.items()}
check(ranking(q, normalized, dot) == ranking(q, docs, cosine), 'normalized ranking')
scaled_q = (3, 0)
check(ranking(scaled_q, docs, dot) == ranking(q, docs, dot), 'positive query scaling')
for name, value in docs.items():
check(math.isclose(dot(unit(q), normalized[name]), cosine(q,value), abs_tol=1e-12),
'both unit vectors give cosine score')
check(math.isclose(dot(scaled_q, normalized[name]), 3*cosine(q,value), abs_tol=1e-12),
'unit corpus only: scores have query scale')
check(dot((0,0), (1,2)) == 0, 'raw zero-vector dot is defined')
for a, b in [([], [1]), ([1], [1,2]), ([0,0], [1,2]),
([math.nan], [1]), ([math.inf], [1]), ([True], [1]),
(['1'], [1]), ([1e101], [1]), ([10**400], [1]), ([1]*65, [1]*65)]:
try:
cosine(a, b)
except ValueError:
check(True, 'invalid cosine input rejected')
else:
raise AssertionError('Expected input rejection')
check(math.isclose(cosine((1e-300,0), (1e-300,0)), 1), 'tiny nonzero vectors')
check(math.isclose(cosine((1e100,0), (0,1e100)), 0, abs_tol=1e-12), 'large vectors')
check(math.isclose(cosine((-1,0), (4,3)), -.8), 'negative scaling changes sign')
rng = random.Random(81)
with localcontext() as ctx:
ctx.prec = 50
for _ in range(200):
size = rng.randrange(2, 9)
a = [rng.randrange(-20, 21) for _ in range(size)]
b = [rng.randrange(-20, 21) for _ in range(size)]
if not any(a): a[0] = 1
if not any(b): b[0] = 1
# Independent high-precision direct formula on integer coordinates.
da, db = list(map(Decimal, a)), list(map(Decimal, b))
dp = sum(x*y for x,y in zip(da,db))
norm_product = (sum(x*x for x in da)*sum(y*y for y in db)).sqrt()
expected = float(dp / norm_product)
ua, ub = unit(a), unit(b)
check(dot(a,b) == float(dp), 'Decimal dot oracle')
check(math.isclose(cosine(a,b), expected, abs_tol=1e-12), 'Decimal cosine oracle')
check(math.isclose(math.hypot(*ua), 1, abs_tol=1e-12), 'unit norm')
check(math.isclose(squared_l2(ua,ub), 2-2*expected, abs_tol=1e-12),
'unit squared L2 identity')
check(math.isclose(cosine([7*x for x in a],b), expected, abs_tol=1e-12),
'positive-scale cosine invariance')
print(f'PASS: {checks} checks; 200 Decimal-oracle pairs')
print('raw dot ranking:', ranking(q, docs, dot))
print('cosine ranking:', ranking(q, docs, cosine))
if __name__ == '__main__':
main()
Interpret the output without inventing a semantic benchmark
The first output line should report PASS: 1030 checks; 200 Decimal-oracle pairs. The raw-dot order begins large, aligned; the cosine order begins aligned, large. The remaining orthogonal and opposite vectors score 0 and -1 under cosine. Alphabetical names provide a deterministic tie-breaker only for this lab.
The Decimal comparison independently evaluates the direct formula for small integer inputs. It checks the implementation against a second arithmetic path rather than comparing cosine to itself. The randomized cases are reproducible because their generator is seeded; they are not an exhaustive proof for every floating-point input.
No embedding model, vector database or approximate search index runs here. These checks establish the stated mathematical examples and input policy. They do not measure retrieval quality, latency, memory use or any model’s semantic accuracy. Use a separate labeled retrieval evaluation for those questions.
Handle zero vectors and invalid data deliberately
A zero vector has norm zero, making the cosine formula’s denominator zero. Libraries can choose a convention for this case; scikit-learn’s documented example returns zero similarity for a zero-vector input. That convention should not be mistaken for a measured orthogonal direction. Decide whether your pipeline should reject, quarantine or explicitly handle such records.
If a document unexpectedly produces a zero or non-finite embedding, inspect the model response and preprocessing before inserting a substitute. An empty input, a failed conversion or a malformed stored payload are different problems. Preserve enough non-sensitive metadata to identify the stage that introduced the invalid vector.
Equal dimensions are necessary for these formulas, but dimensions alone do not establish compatible embedding spaces. Check model identity, revision, query and document formatting, pooling and normalization. Two unrelated models can output the same number of coordinates without making their vectors comparable.
Source: scikit-learn: cosine similarity definition and zero-vector example ↗
A safe sequence for changing an existing retrieval pipeline
Start with a small frozen corpus and queries whose expected relevant passages you have reviewed. Export the coordinates needed for an exact baseline without modifying the active index. Calculate a few pair scores manually and reproduce the service’s metric and score direction. This isolates a scoring mismatch from changes in chunking or corpus contents.
Next, compare raw and normalized variants only where the model contract permits them. Record both top-result membership and numeric score distributions. If changing document normalization, inspect how your backend stores vectors and whether it requires rebuilding or replacing the index. Changing a query-side option cannot rewrite already stored coordinates.
Use separate validation questions to choose any threshold. Check relevant passages missed below it and irrelevant passages admitted above it. Reassess after changing model, corpus or score representation. There is no threshold in this tutorial that is suitable for every retriever.
Once an exact baseline behaves as intended, compare the approximate index against it using the same coordinates and queries. Missing candidates at this stage require investigation of index configuration and search behavior. A metric explanation cannot establish which approximate-search setting is adequate for a particular dataset.
The related retrieval-metrics guide explains recall, MRR and nDCG for labeled ranked lists, while the RAG debugging guide helps inspect the broader retrieval path. Use those checks to connect score arithmetic to evidence quality rather than assuming a more attractive numeric score improves an answer.
- Record the model and scoring contract.
- Verify dimensions, finite values, zero-vector policy and normalization at both boundaries.
- Match exact scores on a frozen sample before changing the active index.
- Evaluate retrieval and thresholds on reviewed queries; retain a recoverable previous configuration.
Choose the metric with a verifiable contract
The practical distinction is visible in four coordinates: (1, 0) is more aligned with the query than (4, 3), yet raw dot product gives the latter a higher score. Document magnitude explains that result. Both-side unit normalization gives cosine scores; document-only normalization preserves cosine order for a fixed nonzero query while retaining query scale.
Before changing a retriever, write down the expected vector transformation and returned score representation, then verify them with a small exact example. After the arithmetic agrees, evaluate whether the resulting passages actually answer your questions. Correct scoring is a necessary debugging step, and relevant evidence is the outcome that matters.
Your next steps
- Raw dot product retains document magnitude; cosine removes it for nonzero vectors.
- Normalizing only the query does not generally produce cosine ranking.
- Unit documents give cosine order for a fixed nonzero query; normalizing both sides gives cosine scores.
- Verify zero-vector policy, score direction and model compatibility before changing an index.
- A mathematical fixture is not a benchmark of semantic retrieval quality.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →