Subscribe
AI
6 min read

What Is Cosine Similarity? The 1960s Angle That Runs Every Vector Search

Every embedding API ships with a comparison function, and almost nobody explains it. When a retrieval demo says it "found the most relevant chunk," the relevance score behind that sentence is, more often than not, cosine similarity. It is the default way machines compare vectors, and the idea predates large language models by about sixty years. Related posts on this site cover the pieces around it: what embeddings are, what RAG is, and why distance gets strange in high dimensions. The formula

What Is Cosine Similarity? The 1960s Angle That Runs Every Vector Search

Every embedding API ships with a comparison function, and almost nobody explains it. When a retrieval demo says it "found the most relevant chunk," the relevance score behind that sentence is, more often than not, cosine similarity. It is the default way machines compare vectors, and the idea predates large language models by about sixty years.

Related posts on this site cover the pieces around it: what embeddings are, what RAG is, and why distance gets strange in high dimensions.

The formula in one line

Take two vectors, A and B. Their cosine similarity is the dot product of the two vectors divided by the product of their lengths:

cos(A, B) = (A · B) / (|A| x |B|)

That quotient is exactly the cosine of the angle between the two arrows. The value lands between -1 and 1. Two vectors pointing the same direction score 1. Two vectors at a right angle to each other score 0. Two vectors pointing in opposite directions score -1.

The crucial detail is what the formula deliberately throws away: the lengths. Cosine similarity answers one question only. Do these two vectors point the same way? How far apart they stand, or how long each arrow is, does not matter. In classic text retrieval, where every term weight is zero or positive, the angle between two document vectors can never exceed 90 degrees, so scores there live in the tighter range from 0 to 1.

Why angles instead of distances

The reason cosine beat plain distance for text is boring and practical: documents come in different lengths.

Imagine two articles on the same subject. One is a 200-word summary, the other a 5,000-word deep dive. In a vector space where each dimension counts a term, the long article is roughly the short article's vector scaled up. Its arrow points in nearly the same direction but stretches much farther from the origin.

Measure distance, and the two articles look far apart, because the lengths differ. Measure angle, and they look nearly identical, because the topic is the same. Dividing by the vector lengths, which is exactly what the cosine formula does, removes the length penalty and scores what both documents share: the mix of terms, not the volume of text.

Two arrows of different lengths rising from a shared origin, with an arc marking the angle between them

The 1960s origin

Cosine similarity did not arrive with embeddings. It arrived with early computerized search research.

Gerard Salton, the computer scientist widely regarded as the father of information retrieval, led the team that built the SMART system (System for the Mechanical Analysis and Retrieval of Text) at Cornell University in the 1960s. SMART introduced the vector space model: represent each document as a vector of term weights, represent the query the same way, and rank documents by the angle between query vector and document vector. Salton and Chris Buckley's 1988 survey of term-weighting work shows the cosine formula falling straight out of normalizing term weights by vector length, and notes it had been "used extensively" in SMART experiments.

SMART also ran the discipline's first serious experiments on what made retrieval work, testing weighting variants on benchmark collections like the Cranfield aeronautics abstracts and the CACM computer science papers. Every modern search stack, keyword or semantic, still inherits its vocabulary from that program: term frequency, inverse document frequency, normalization, ranking by score.

The TF-IDF weighting that fills the vector dimensions is the same generation of ideas. Cosine is the other half of the pair.

How it got into your vector database

Cosine entered modern NLP through word vectors. Mikolov and colleagues at Google trained word2vec in 2013 and evaluated it with analogy questions such as Germany is to Berlin as France is to what. The system answers by scanning the vocabulary for the word whose vector sits closest to the arithmetic result, using cosine distance to define closest. Their follow-up NeurIPS paper describes the same procedure over an analogy set of 8,869 semantic and 10,675 syntactic questions.

Sentence-BERT moved cosine into production retrieval. Reimers and Gurevych (2019) trained BERT so that sentence pairs can be compared "using cosine-similarity" alone, and reported the drop from brute force to lookup: finding the most similar pair among 10,000 sentences went from about 65 hours with vanilla BERT pair comparisons to about 5 seconds with SBERT vectors. That gap is the reason bi-encoder search became cheap enough to deploy everywhere.

The APIs formalized it. OpenAI's embedding documentation recommends cosine similarity, states that its vectors "are normalized to length 1," and notes two consequences: cosine reduces to a plain dot product, and on unit vectors cosine and Euclidean distance produce identical rankings. FAISS, Meta's vector search library, documents the same trick: normalize vectors, build an index with METRIC_INNER_PRODUCT, and the largest inner products are the largest cosines. For unit vectors the squared Euclidean distance equals 2 minus 2 times the dot product, so angle ranking and distance ranking are the same computation wearing different clothes.

In practice, therefore, a billion-vector search service rarely divides anything. It normalizes once at write time and then spends its life doing fused dot products, which is cosine similarity in disguise.

What the number does not mean

Three caveats separate a working retrieval system from a demo that quietly returns junk.

The score is a rank, not a percentage. A cosine of 0.87 does not mean the texts are "87% similar." Cosine values are ordinal signals: useful for deciding which candidate scores higher, not calibrated probabilities of agreement. OpenAI's own documentation says the choice of distance function "typically doesn't matter much" because ranking quality dominates; the same logic applies to reading absolute values off the scale. Thresholds that work on one embedding model and one corpus routinely fail on another.

Raw model vectors are anisotropic, which hurts cosine. Kawin Ethayarajh (2019) measured contextual embeddings from BERT, ELMo and GPT-2 by the average cosine similarity of randomly sampled word pairs and found the vectors crowd into a narrow cone in the space. Unrelated sentences already look similar to cosine because everything points roughly the same way. Tianyu Gao and colleagues (2021) tied this degeneration directly to weak similarity performance and showed that a contrastive training objective spreads embeddings toward a uniform distribution over the sphere. That is why you embed with a model fine-tuned for retrieval, not with the raw hidden states of a language model: the geometry cosine depends on has to be trained into the vectors.

Left: orange arrows bundled tightly in a narrow cone. Right: teal arrows spread evenly across a wide fan

Cosine discards magnitude on purpose, and magnitude can carry information. Because the formula divides by both lengths, a system that encodes meaning in vector norm loses it in the comparison. Recommendation engines exploit the reverse: FAISS notes inner product search "is typically used for maximum inner product search in recommendation systems," where the database vector's norm is part of the score. If your embeddings are not normalized and the norm means something, dot product and cosine will disagree, and neither is wrong. They answer different questions.

Why it won anyway

Cosine similarity survives because it is rotation invariant, bounded, scale free, and one multiply-add per dimension once vectors are normalized. It plugs into every approximate nearest neighbor index, it matches how tf-idf style document vectors behave, and it has sixty years of retrieval experiments behind it. The next time a vector database hands you a relevance score of 0.83, you know what it measured: an angle, drawn with 1960s mathematics, that the entire modern retrieval stack still agrees to treat as meaning.

Sources

AILLMEducation