In the realm of generative AI and large language models (LLMs), understanding how similarity is computed mathematically is key to grasping search and retrieval mechanisms. Two foundational concepts are cosine similarity and approximate nearest neighbor (ANN) search.
Cosine similarity measures the cosine of the angle between two vectors in a multi-dimensional space. It is defined as:
[ \text{cosine similarity}(A, B) = \frac{A \cdot B}{|A| |B|} ]
where (A \cdot B) is the dot product of vectors (A) and (B), and (|A|) and (|B|) are their magnitudes. The result ranges from -1 to 1, where 1 indicates identical direction (high similarity), 0 indicates orthogonality, and -1 indicates opposite directions.
In practice, cosine similarity is used to compare embedding vectors—numerical representations of text or images produced by AI models. For example, when searching for similar documents, each document is converted into an embedding, and cosine similarity identifies the closest matches.
However, in large-scale datasets, computing full pairwise similarities is computationally expensive. ANN search algorithms (like HNSW, FAISS, or Annoy) approximate the nearest neighbors by building index structures that quickly retrieve similar vectors without exhaustive comparison. This trade-off between speed and accuracy is crucial for real-time applications such as semantic search, recommendation systems, and retrieval-augmented generation (RAG).
By combining cosine similarity with ANN search, engineers can efficiently find relevant content in massive vector databases—a core component of modern AI systems.