Of course. This is one of the most fundamental applications of cosine similarity in modern AI. Here’s a breakdown of how it works in the context of LLM embeddings, moving from a high-level concept to a practical example.
The Core Idea: Meaning as a Location
Imagine a massive, invisible library where every possible concept, idea, and piece of text has a specific location.
-
LLM Embeddings are the "Coordinates": An LLM embedding is a list of numbers (a vector) that represents the "coordinates" of a piece of text (a word, sentence, or document) in this giant conceptual library. Texts with similar meanings are placed close to each other.
"The cat sat on the mat" might get the vector [0.12, -0.45, 0.67, ...]
"A feline rested on the rug" will get a very similar vector like [0.15, -0.41, 0.62, ...]
"Quantum physics is complex" will get a very different vector like [-0.88, 0.05, -0.23, ...]
-
Cosine Similarity is the "Compass": Cosine similarity doesn't measure the physical distance between these points. Instead, it measures their direction. It answers the question: "Are these two pieces of text pointing in the same conceptual direction?"
This is a crucial distinction. In this high-dimensional space, direction is a proxy for meaning.
How It Works Step-by-Step
Let's walk through a practical example: a semantic search engine. A user searches for "What are the best dog-friendly parks?".
Step 1: Generate Embeddings
First, the system uses a pre-trained LLM (like one from OpenAI, Google, or a model like BERT) to convert both the user's query and the potential documents into embedding vectors.
-
Query Vector (Q): The LLM processes "What are the best dog-friendly parks?" and outputs a vector, let's say with 768 dimensions (a common size).
Q = [0.4, -0.2, 0.9, ...]
-
Document Vectors (D1, D2, D3): The system has already done this for its database of documents.
- D1:
"A guide to local parks where canines are welcome."
D1_vector = [0.5, -0.3, 0.8, ...] (Conceptually similar to Q)
- D2:
"City council announces new public park funding."
D2_vector = [0.1, 0.5, 0.7, ...] (Related, but less specific)
- D3:
"The history of the domestic cat."
D3_vector = [-0.7, -0.1, -0.4, ...] (Completely different direction)
Step 2: Compute Cosine Similarity
Now, the system calculates the cosine similarity between the query vector Q and each document vector.
The formula is the same: similarity = (A · B) / (||A|| * ||B||)
-
cosine_similarity(Q, D1):
- The dot product of Q and D1 will be high because their corresponding positive/negative values will multiply to create large positive numbers.
- The result will be close to 1 (e.g., 0.92).
-
cosine_similarity(Q, D2):
- The vectors are somewhat aligned but not perfectly. The dot product will be positive but lower than the first one.
- The result might be 0.65.
-
cosine_similarity(Q, D3):
- The vectors are pointing in very different directions. Positive values in Q will often be multiplied by negative values in D3, leading to a low or even negative dot product.
- The result will be close to 0 (e.g., 0.08).
Step 3: Rank and Return Results
The system ranks the documents based on their cosine similarity scores in descending order:
- Doc 1 (Score: 0.92) ← Best match
- Doc 2 (Score: 0.65) ← Relevant, but not the best
- Doc 3 (Score: 0.08) ← Irrelevant
The user is shown "A guide to local parks where canines are welcome" as the top result because its meaning (direction) was most closely aligned with their query.
Why Cosine Similarity and Not Euclidean Distance?
This is a key question. Euclidean distance (the straight-line distance between two points) seems intuitive, but cosine similarity is often preferred for text embeddings for a critical reason:
Cosine similarity is insensitive to the magnitude (or length) of the vectors and only cares about their orientation.
In the context of text, the magnitude of an embedding vector can sometimes correspond to factors we want to ignore, like word frequency or sentence length.
Example:
- Doc A: "dogs are great"
- Doc B: "dogs are great, dogs are great, dogs are great"
These two documents have the exact same meaning. However, a simple embedding model might give Doc B a vector with a much larger magnitude because the phrase is repeated.
- Euclidean distance would see these two points as being far apart, suggesting they are dissimilar.
- Cosine similarity would see that they point in the exact same direction and give them a score of 1, correctly identifying them as semantically identical.
By focusing on the angle, cosine similarity hones in on the core semantic content, making it the perfect tool for comparing LLM embeddings.
Primary Applications in LLMs
- Semantic Search & RAG (Retrieval-Augmented Generation): Find the most relevant documents to answer a user's query.
- Text Classification & Clustering: Group similar documents or assign labels based on semantic content.
- Recommendation Systems: Recommend articles, products, or movies by finding items with similar descriptive embeddings.
- Plagiarism Detection: Identify documents with high semantic similarity, even if the wording is different.