Skip to main content

Does cosine similarity measure semantic similarity?

Geometry, anisotropy, nearest-neighbour rankings, and metric choice

Cosine similarity must be interpreted within the geometry of embedding space; it does not establish semantic proximity by itself. The embedding-linearity hypothesis addresses a different question: how are features represented and decoded?

Practice: Mathematical foundations exercises, including cosine calculation and interpretation.

The question behind the default metric

Cosine similarity is widely used to compare sentence, document, and query embeddings. It is simple, inexpensive, and invariant to vector magnitude. But it does not directly measure “semantic similarity”: it measures angular alignment between representations produced by a particular model.

This distinction matters. A metric cannot be interpreted independently of the task, encoder, data distribution, and training objective.

1. Definition and assumptions

For two non-zero vectors \(x,y\in\mathbb{R}^d\),

\[ \operatorname{cos}(x,y)=\frac{x^\top y}{\|x\|_2\,\|y\|_2}. \]

The score lies in \([-1,1]\). A high value means the vectors point in similar directions. It does not, by itself, mean that two texts are equivalent, imply the same answer, or are interchangeable in a search system.

Normalization removes information carried by vector magnitude. This is useful when magnitude is a nuisance; it may discard a useful signal if the model encodes one in the norm. Steck, Ekanadham, and Kallus analytically show that, for some families of regularized linear models, cosine similarities can be arbitrary, non-unique, or controlled by regularization. Their result cautions against automatic use of the metric; it does not prove that cosine fails for every modern encoder.

2. Why cosine can mislead

Anisotropy and concentrated scores

An embedding space is anisotropic when vectors are not distributed uniformly across directions. In such spaces, unrelated sentence pairs can still receive high cosine scores. Li et al. (EMNLP 2020) analyse anisotropy in pretrained BERT sentence embeddings and report that it harms semantic similarity in their experiments. Ethayarajh (2019) also finds non-isotropic contextual representations in BERT, ELMo, and GPT-2.

Practical consequence: inspecting a few scores is not enough. Examine score distributions for positive, negative, and random pairs, and measure whether the metric separates the classes relevant to the task.

The hubness phenomenon

In high-dimensional spaces, some points can become nearest neighbours of a large number of other points. These “hubs” may appear repeatedly in results without being good matches for every query. Local rankings can therefore be biased even when the distance formula is implemented correctly.

Closeness is not relevance

Two texts can be lexically or topically close while expressing opposite facts (“the treatment works” / “the treatment does not work”). Conversely, very different formulations can answer the same question. Representation similarity is therefore not automatically equivalent to logical equivalence, document relevance, or usefulness in RAG.

The metric depends on the model and its training objective

Sentence Transformers models do not all target the same scoring function: some are trained or recommended for dot product, others for cosine. Sentence Transformers documentation explains that dot product between normalized vectors is equivalent to cosine, while dot product on unnormalized vectors retains magnitude information. Respect the assumptions of the chosen model instead of replacing its default metric without evaluation.

Encoding a text pair: bi-encoder or cross-encoder?

Sentence-pair similarity also depends on how the model encodes the texts. Two common architectures serve different constraints:

Bi-encoder Cross-encoder
Encoding Each input is encoded independently by its own branch. The branches may share weights (Siamese) or use different weights. The two texts are combined and processed jointly, allowing token-level interaction during scoring.
Typical output Two reusable vectors, compared afterwards with an appropriate metric. A pair-specific score computed after the texts interact.
Strength Documents can be encoded and indexed in advance; large-corpus retrieval is efficient. The model can account for interactions between both texts while scoring the pair.
Limitation The texts cannot interact directly during encoding; quality depends strongly on the training objective and data. Every candidate pair must be processed again; scoring a query against an entire corpus is expensive.

Three retrieval architectures: a bi-encoder independently encodes query and document into one vector each, a cross-encoder jointly processes the query and each candidate document, and ColBERT-style late interaction independently encodes contextual token vectors then compares each query token with document tokens using MaxSim and sums the maxima.

Comparison of bi-encoder, cross-encoder and late-interaction retrieval architectures.

A bi-encoder is defined by independent encoding, not by mandatory weight sharing. A Siamese bi-encoder ties the weights of its two branches, as in the original Sentence-BERT architecture; other dual-encoder designs may use separate query and document encoders. See Reimers and Gurevych (2019), Sentence-BERT.

A cross-encoder’s output is a task-specific pair score. It is not automatically a calibrated probability, a universal measure of semantic similarity, or a score comparable across unrelated models. Its ranking value must be measured on the target task.

A useful middle ground: late interaction

ColBERT independently encodes a query and each document into sets of contextualized token vectors, then compares them at query time. In its MaxSim formulation, each query-token vector takes its maximum similarity with document-token vectors; those maxima are aggregated into a document score. Documents can be encoded offline, while token-level matching preserves finer interactions than a single-vector bi-encoder. This is neither a standard single-vector bi-encoder nor a cross-encoder that jointly runs the Transformer over each pair.

The trade-off is a larger multi-vector index, more involved retrieval infrastructure and additional storage/serving considerations. Khattab and Zaharia (2020), ColBERT and Santhanam et al. (2022), ColBERTv2 describe the architecture and compression improvements. ColBERTv2 reduces, but does not erase, the representation-footprint trade-off.

Other useful alternatives are not all dense bi-encoders: - Lexical retrieval (BM25) is a strong, inexpensive baseline when exact terms, names, identifiers or rare technical vocabulary matter. - Learned sparse retrieval (SPLADE) learns sparse term-weight representations and uses inverted-index-style retrieval; it can expand beyond literal matching while retaining lexical interpretability and efficient sparse infrastructure. See Formal et al. (2021). - Hybrid retrieval combines complementary lexical and dense (or sparse neural) candidate lists. It can improve recall, but fusion is not guaranteed to help every query or corpus; evaluate it rather than treating it as a default law. - Reranking can follow any candidate generator—BM25, dense, sparse, hybrid or structured search. It cannot recover a relevant document that the candidate stage never retrieved.

The BEIR benchmark is a useful counterweight to single-dataset claims: it compares lexical, sparse, dense, late-interaction and reranking systems across heterogeneous domains, and reports meaningful effectiveness/efficiency trade-offs. There is no universally best architecture.

A common pipeline combines them: a bi-encoder quickly retrieves candidate passages, then a cross-encoder re-ranks that shortlist by scoring each query–passage pair. A cross-encoder is therefore not necessarily a replacement for vector retrieval; it can be a more discriminating second stage applied to a small candidate set.

This distinction also explains why a contextualized state from a pretrained BERT model is not automatically a good sentence embedding: pooling, training objective, pair examples, and target task all matter. Choose a sentence or retrieval encoder evaluated for the intended use, then measure ranking quality on representative queries. A high similarity score is neither proof of logical equivalence nor a guarantee of relevance.

AugSBERT illustrates another trade-off: use a cross-encoder to produce pair scores or labels, then train a faster bi-encoder to reproduce those judgments. The article’s detailed account and implementation are only partially accessible; see Part 2 as optional further reading, not as independent performance validation.

For how these architectures fit into text and visual document retrieval, see RAG, memory, and document retrieval, including the ColPali example. A concise visual overview is available in Daily Dose’s Visual Guide to Bi-encoders, Cross-encoders and ColBERT.

3. When cosine is a reasonable choice

Cosine is a reasonable baseline when:

  • the encoder is designed and evaluated for semantic similarity;
  • normalization matches the model’s training and recommended use;
  • the goal is to compare directions rather than representation magnitudes;
  • the system is validated on queries and documents representative of real use;
  • nearest-neighbour rankings, not just absolute scores, are evaluated.

It is less reliable as a stand-alone signal when the encoder was not adapted to the task, scores are concentrated in a narrow range, data are out of distribution, or the task requires fine-grained logical distinctions.

4. Reproducible experiment to add to the repository

The experiment should isolate the metric from the rest of the system.

  1. Choose a documented evaluation set (for example, STS Benchmark for sentence similarity, plus a retrieval dataset relevant to the intended use case).
  2. Compare several encoders: a sentence model trained for similarity, a retrieval embedding model, and, if possible, raw BERT embeddings as a control.
  3. Compare cosine, dot product, Euclidean distance, and rank-based retrieval. Document whether vectors are normalized.
  4. Report task-appropriate metrics: Spearman/Pearson for annotated similarity scores, Recall@k / MRR / nDCG for retrieval.
  5. Inspect false positives, hubs, and score distributions; report uncertainty intervals when the protocol supports them.

Do not compare metrics across models trained with different objectives and attribute every difference to the formula alone. When comparing cosine and dot product, explicitly include the normalized-vector case, where they induce the same ranking.

import numpy as np

def cosine_similarity(x: np.ndarray, y: np.ndarray) -> float:
    """Cosine similarity for two non-zero vectors."""
    x_norm = np.linalg.norm(x)
    y_norm = np.linalg.norm(y)
    if x_norm == 0 or y_norm == 0:
        raise ValueError("Cosine similarity is undefined for zero vectors.")
    return float(np.dot(x, y) / (x_norm * y_norm))

This snippet assumes equal-shaped, one-dimensional, finite arrays and makes the definition and zero-vector edge case explicit; it does not validate those input contracts. It is not, by itself, a benchmark or a production-hardened numerical implementation. Direct norms and dot products can overflow for extremely large finite values or underflow for extremely small ones; production code should use a tested implementation with documented numerical behaviour.

Checks that distinguish competing interpretations

  • Misconception: “A high cosine proves that two texts mean the same thing.” Counterexample: “the treatment works” and “the treatment does not work” may remain close in an embedding space dominated by shared vocabulary.
  • Misconception: “Dot product is always a different alternative.” For normalized vectors, dot product and cosine give the same score; without normalization, vector norms can change the ranking.
  • Qualification: anisotropy and hubness are possible diagnostics, not automatic explanations for every retrieval error. Measure them on the representations and task in question.

When auditing a conclusion, ask: what assumptions about the encoder and normalization are required? What counterexample would falsify the semantic interpretation? Which target-task metric would distinguish the options?

Takeaway

For how these vectors are represented and constructed, see also Embedding space.

Cosine is a geometric metric, not a universal definition of semantics. Treat it as a hypothesis to test against a baseline and concrete errors on the target task; no isolated geometric property guarantees system relevance.

Supplementary resources Research papers and visual explanations for deeper study of cosine similarity.

Research papers

Additional research and visual explanations

Technical documentation and explanations

Library documentation describes implementation behaviour; it does not replace scientific evaluation. The cited papers study different models, objectives, and protocols, so their results should not be collapsed into one conclusion without considering those differences.