Text embeddings convert text into numerical vectors that represent its semantic meaning. They allow applications to identify related sentences, search documents by meaning, and group similar content even when the wording is different. Understanding how embeddings work, how cosine similarity compares them, and how to choose a consistent model is essential when building semantic search and RAG applications.
1. What Are Text Embeddings?
Computers can store text as characters and strings, but understanding whether two sentences express similar ideas requires more than comparing their words.
Consider these three sentences:
- "How can I reset my password?"
- "I forgot my password and need to change it."
- "What is the weather like today?"
The first two sentences use different words but express a similar intention. The third sentence discusses something completely different.
A traditional keyword search might look for matching terms. A semantic search system attempts to identify relationships in meaning. This is where text embeddings become useful.
A text embedding is a numerical representation of text in the form of a vector. An embedding model converts a sentence, paragraph, or document into a list of floating-point numbers. Applications can then compare these vectors using mathematical similarity measures.
For example, an embedding might look like this:
embedding = [
0.021,
-0.143,
0.087,
0.256,
-0.091
]
This is only a simplified five-dimensional illustration. Real embedding models usually produce vectors containing hundreds or thousands of dimensions.
Each dimension contributes to the learned representation. Individual numbers generally do not have a simple human-readable meaning such as "this number represents happiness" or "this number represents passwords."
2. How Does Text Become a Vector?
An embedding model follows a process that converts text into a numerical representation.
A simplified pipeline looks like this:
Input Text
|
v
Tokenization
|
v
Token Embeddings
|
v
Transformer Encoder
|
v
Pooling / Representation
|
v
Final Text Vector
Let's understand these steps.
Step 1: Tokenization
The input sentence is divided into smaller units called tokens. A token can represent a complete word, a part of a word, or punctuation.
For example:
"I love machine learning"
A tokenizer might divide it into pieces such as:
["I", "love", "machine", "learning"]
The actual tokenization depends on the model's vocabulary and tokenizer.
Step 2: Convert Tokens into Numerical Representations
Each token is mapped to a numerical representation that the neural network can process.
These representations contain learned information about the tokens. The model then processes them to capture contextual relationships.
Step 3: Generate a Contextual Representation
Many modern embedding models use Transformer-based encoders.
A Transformer processes the token representations and uses mechanisms such as self-attention to capture relationships between words.
For example, the meaning of "bank" can depend on whether the sentence discusses money or a river.
The contextual representations help the model understand these differences.
Step 4: Pooling into One Vector
A sentence contains multiple token representations, but many embedding applications need one fixed-size vector for the complete sentence.
Pooling combines token-level representations into a single vector. Common approaches include mean pooling and special-token pooling, depending on the model architecture.
The final output is a fixed-dimensional vector that can be stored, compared, and retrieved later.
3. Why Do Similar Sentences Cluster Together?
The most useful way to understand embeddings is to imagine a shared vector space.
A vector space is a mathematical space where each vector represents a position. In an embedding model, the position reflects learned patterns of relationships between text inputs.
When a model is trained to represent related sentences similarly, their embeddings tend to appear closer together.
Consider these sentences:
Group A: Password-related sentences
- "How do I reset my password?"
- "I forgot my login password."
- "I cannot access my account because I lost my password."
Group B: Weather-related sentences
- "Will it rain tomorrow?"
- "What is the weather forecast?"
- "Is the temperature going to increase?"
A suitable embedding model should generally place the sentences in Group A closer to one another and the sentences in Group B closer to each other.
A simplified two-dimensional illustration:
Semantic Vector Space
Password-related cluster
A1 A2
A3
Weather-related cluster
B1
B2 B3
This is a conceptual illustration, not an actual embedding plot. Real embeddings usually contain hundreds or thousands of dimensions.
For visualization, developers can use dimensionality-reduction techniques such as PCA or t-SNE to project high-dimensional vectors into two dimensions. Such projections are useful for exploring patterns, but they can distort distances and relationships.
One important point: similar wording does not always mean similar meaning, and different wording does not necessarily mean different meaning. Embeddings attempt to capture semantic relationships, but their quality depends on the model, language, domain, and task.
4. What Is Cosine Similarity?
After converting sentences into vectors, we need a way to compare them.
One commonly used method is cosine similarity.
Cosine similarity measures the cosine of the angle between two vectors. It focuses on their direction rather than simply comparing their numerical magnitudes.
The formula is:
[ \text{Cosine Similarity}(A,B)
\frac{A \cdot B} {|A||B|} ]
Here:
- (A) is the first embedding vector.
- (B) is the second embedding vector.
- (A \cdot B) is their dot product.
- (|A|) and (|B|) are their vector magnitudes.
For non-zero vectors, the theoretical cosine similarity range is from -1 to 1.
- A value closer to 1 indicates similar vector directions.
- A value around 0 indicates little directional similarity.
- A value closer to -1 indicates opposite directions.
The actual score distribution depends on the embedding model and task. A score of 0.8 is not a universal guarantee that two sentences have the same meaning.
5. Calculate Cosine Similarity in Python
Let's calculate similarity between sentences using a pretrained model from Sentence Transformers.
For this example, we will use all-MiniLM-L6-v2, a compact English sentence-embedding model that produces 384-dimensional vectors.
Its model card is available on Hugging Face.
Step 1: Install the Library
pip install -U sentence-transformers
Step 2: Load the Embedding Model
from sentence_transformers import SentenceTransformer
model = SentenceTransformer(
"sentence-transformers/all-MiniLM-L6-v2"
)
The model downloads its required files when loaded for the first time.
Step 3: Convert Sentences into Embeddings
sentences = [
"How do I reset my password?",
"I forgot my password and need to change it.",
"What is the weather like today?"
]
embeddings = model.encode(
sentences,
normalize_embeddings=True
)
print(embeddings.shape)
The output shape is:
(3, 384)
This means we generated three embeddings, each containing 384 numerical values.
Step 4: Calculate Cosine Similarity
We can use the util.cos_sim() function provided by Sentence Transformers.
from sentence_transformers import util
similarity_1 = util.cos_sim(
embeddings[0],
embeddings[1]
)
similarity_2 = util.cos_sim(
embeddings[0],
embeddings[2]
)
print("Password sentence similarity:", similarity_1.item())
print("Password vs weather similarity:", similarity_2.item())
The first comparison should generally produce a higher similarity score because both sentences discuss changing or resetting a password.
The second comparison should generally produce a lower score because the sentences discuss unrelated topics.
Exact scores can vary with model revisions, library versions, and configurations. The important thing is the relative relationship between the examples, not a fixed numerical threshold.
Because we requested normalized embeddings, their vector magnitudes are 1. For normalized vectors, the dot product is equivalent to cosine similarity. Sentence Transformers also provides similarity utilities and supports other similarity functions.
See the Sentence Transformers semantic similarity documentation.
6. How to Choose the Right Embedding Model
Choosing an embedding model is not simply about selecting the model with the largest vector dimension.
The right model depends on what your application needs to do.
For example, a model that performs well on English sentence similarity may not be the best option for multilingual document retrieval.
Consider these factors before selecting one.
Language Support
If your application primarily processes English content, an English-focused model may be sufficient.
However, applications that handle Hindi, English, or mixed-language queries should use a model evaluated for multilingual tasks.
For example, Microsoft's multilingual-e5-small is designed for multilingual embedding tasks and produces 384-dimensional embeddings.
Its model documentation also specifies how query and passage prefixes should be used for retrieval tasks.
Explore the Multilingual E5 model collection.
Do not assume that a model performs equally well across every supported language. Test it using real examples from your users.
Task Requirements
Different applications require different embedding behaviour.
| Use case | What to prioritize |
|---|---|
| Semantic search | Relevant document retrieval |
| Sentence similarity | Meaning comparison |
| Document clustering | Meaningful grouping |
| Recommendation systems | Useful similarity relationships |
| Multilingual search | Cross-language retrieval quality |
| RAG applications | Query-to-document retrieval performance |
A model designed for sentence similarity may not automatically be the best choice for an asymmetric retrieval task, where a short query must retrieve a longer document.
Some embedding models also require task-specific instructions or prefixes. Follow the model's documentation rather than assuming every model accepts plain text in exactly the same way.
Speed, Cost, and Deployment
A larger model may improve retrieval quality on some datasets, but it can also require more memory, compute, and inference time.
Hosted embedding APIs introduce input-token costs and network latency. Local embedding models offer more control over deployment and data processing but require suitable infrastructure.
Benchmark candidate models using your own queries and document collection. Measure retrieval quality, response time, memory usage, and cost before making a production decision.
7. What Do Embedding Dimensions Mean?
Embedding dimensions describe how many numerical values are present in a vector.
For example:
| Model | Example vector dimensions |
|---|---|
| all-MiniLM-L6-v2 | 384 |
| multilingual-e5-small | 384 |
| text-embedding-3-small | 1,536 by default |
| text-embedding-3-large | 3,072 by default |
These are model-specific configurations, not a universal ranking of quality.
A vector with 1,536 dimensions contains more numerical values than a vector with 384 dimensions. However, more dimensions do not automatically guarantee better search results.
Storage Impact
Assume embeddings are stored using 32-bit floating-point numbers. Each dimension then requires approximately four bytes of raw vector storage.
For one million vectors:
| Dimensions | Approximate raw vector storage |
|---|---|
| 384 | 1.5 GB |
| 768 | 3.0 GB |
| 1,536 | 6.0 GB |
| 3,072 | 12.0 GB |
These estimates exclude database indexes, metadata, replicas, and storage overhead.
Higher dimensions can increase memory usage and similarity-computation requirements. Lower dimensions can reduce infrastructure costs, but may also affect retrieval quality.
Can You Reduce Embedding Dimensions?
Some embedding models support configurable output dimensions.
For example, OpenAI's text-embedding-3-small and text-embedding-3-large support the dimensions parameter.
A Python example:
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-small",
input="How do text embeddings work?",
dimensions=512
)
embedding = response.data[0].embedding
print(len(embedding))
The resulting vector has 512 dimensions instead of the model's default 1,536.
Dimension reduction should be evaluated on your own retrieval dataset. A smaller vector can reduce storage requirements, but you should verify that it still retrieves the documents your users need.
See the OpenAI embeddings guide for supported models and dimension configuration.
8. Common Mistakes When Working with Embeddings
Embeddings are relatively easy to generate, but production retrieval systems can fail when they are managed incorrectly.
These are some common mistakes to avoid.
Mixing Embeddings from Different Models
This is one of the most important mistakes.
Imagine you generate document embeddings using Model A, but later generate user query embeddings using Model B.
Even if both models return vectors with 384 dimensions, their coordinate spaces may be different.
The numbers at a particular position do not have a shared meaning across independently trained models. Their similarity scores cannot be assumed to represent meaningful relationships.
For example:
Document Embedding: Model A, 384 dimensions
Query Embedding: Model B, 384 dimensions
The dimensions match, but the vector spaces may not.
Always use a compatible embedding model and configuration for both indexed documents and incoming queries.
When switching models, regenerate the document embeddings and rebuild or migrate the vector index. Do not simply start storing new model vectors alongside old ones.
Treating Similarity Scores as Probabilities
A cosine similarity score of 0.85 does not mean there is an 85% probability that two sentences have the same meaning.
It is a geometric similarity measure, not a calibrated probability.
The appropriate relevance threshold varies with the model, dataset, language, and retrieval task.
Use a labelled evaluation dataset to determine useful thresholds rather than choosing one based on intuition.
Ignoring Query and Document Formatting
Some retrieval models expect different input instructions for queries and documents.
For example, multilingual E5 models use prefixes such as:
query: How do embeddings work?
passage: Embeddings represent text as numerical vectors.
Ignoring the required format can reduce retrieval quality even when the model itself is suitable.
Always follow the model card and use consistent preprocessing.
Choosing Dimensions Without Testing
Using the largest available vector is not always the most efficient choice.
It can increase storage, indexing, and compute requirements without providing enough improvement for your application.
Compare multiple supported dimensions using the same retrieval test set. Choose the smallest configuration that meets your quality requirements.
Using Poor Chunking Strategies
For document search and RAG, developers often split content into chunks before generating embeddings.
If chunks are too large, a vector may represent several unrelated topics. If they are too small, important context can be lost.
Choose chunk sizes based on the structure of your content and test how well queries retrieve the relevant sections.
9. How Embeddings Fit into a Semantic Search System
Generating embeddings is only one part of a complete semantic search pipeline.
A typical application follows two stages.
Indexing stage:
- Collect documents.
- Clean and split them into useful chunks.
- Generate embeddings using a selected model.
- Store the vectors alongside document IDs and metadata in a vector database.
Search stage:
- Receive a user's query.
- Generate a query embedding using the compatible model.
- Compare it with stored document vectors.
- Retrieve the most relevant results.
- Optionally rerank the retrieved results before returning them.
For large datasets, a vector database or vector index can speed up nearest-neighbour retrieval instead of comparing every vector manually.
This approach is commonly used in semantic search, recommendation systems, and Retrieval-Augmented Generation (RAG).
Sentence Transformers explains this workflow in its semantic search guide.
Conclusion
Text embeddings turn sentences and documents into numerical vectors that capture learned semantic relationships. These vectors allow applications to compare meaning, group related content, and retrieve relevant information even when users do not use the exact words stored in a document.
Cosine similarity provides a practical way to compare embeddings, while the choice of model and dimensions affects retrieval quality, storage, and performance.
For production applications, use a model that fits your language and task, evaluate it with real queries, and keep the embedding model consistent across document indexing and query generation.
Good semantic search starts with good embeddings, but reliable retrieval depends on using them consistently and evaluating them with real application data.



